Skip to content

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

summ fixes

sora431eb5868ef0
diff --git a/src/App.tsx b/src/App.tsx
index 4418863..d27af7f 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -150,6 +150,8 @@ import {
ZoomIn,
ZoomOut,
RotateCcw,
+ FlipHorizontal,
+ FlipVertical,
Plus,
Loader2,
Info as InfoIcon,
@@ -923,9 +925,12 @@ export function App() {
const {
viewportRef,
+ navigation,
zoom,
pan,
rotation,
+ flipX,
+ flipY,
isSpaceDown,
isShiftDown,
isRotateModifier,
@@ -937,6 +942,9 @@ export function App() {
zoomOut,
resetZoomAndCenter,
resetRotation,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ resetViewFlip,
} = useCanvasNavigation({
dimensions,
isWebtoonMode,
@@ -1538,6 +1546,9 @@ export function App() {
pan,
zoom,
rotation,
+ flipX,
+ flipY,
+ navigation,
activeLayerId,
activeSessionId: activeDocumentId,
activeLayerLocked: activeLayer?.locked ?? false,
@@ -1701,9 +1712,19 @@ export function App() {
(e: React.PointerEvent<HTMLElement> | PointerEvent) => {
if (!viewportRef.current) return { x: 0, y: 0 };
const vRect = viewportRef.current.getBoundingClientRect();
- return screenToCanvas(e.clientX, e.clientY, vRect, pan, zoom, rotation, dimensions);
+ return screenToCanvas(
+ e.clientX,
+ e.clientY,
+ vRect,
+ navigation.panRef.current,
+ navigation.zoomRef.current,
+ navigation.rotationRef.current,
+ dimensions,
+ navigation.flipXRef.current,
+ navigation.flipYRef.current
+ );
},
- [viewportRef, pan, zoom, rotation, dimensions]
+ [viewportRef, navigation, dimensions]
);
const handleSampleColor = useCallback(
@@ -5183,6 +5204,22 @@ export function App() {
return;
}
+ // Non-destructive View Flip shortcuts: Shift+H (Horizontal), Shift+V (Vertical)
+ if (e.shiftKey && !isSpaceDown) {
+ if (code === 'KeyH' || key === 'h') {
+ if (!hasOpenDocument || e.repeat) return;
+ e.preventDefault();
+ toggleFlipHorizontal();
+ return;
+ }
+ if (code === 'KeyV' || key === 'v') {
+ if (!hasOpenDocument || e.repeat) return;
+ e.preventDefault();
+ toggleFlipVertical();
+ return;
+ }
+ }
+
// Single-key tool & color shortcuts (no modifiers)
if (!e.shiftKey) {
const mappedTool = CODE_TO_TOOL[code];
@@ -6274,6 +6311,35 @@ export function App() {
disabled: !hasOpenDocument,
onClick: resetRotation,
},
+ {
+ id: 'view-div-flip',
+ label: '',
+ divider: true,
+ },
+ {
+ id: 'view-flip-horizontal',
+ label: 'Flip View Horizontal',
+ shortcut: 'Shift+H',
+ icon: <FlipHorizontal className="w-3.5 h-3.5" />,
+ checked: flipX,
+ disabled: !hasOpenDocument,
+ onClick: toggleFlipHorizontal,
+ },
+ {
+ id: 'view-flip-vertical',
+ label: 'Flip View Vertical',
+ shortcut: 'Shift+V',
+ icon: <FlipVertical className="w-3.5 h-3.5" />,
+ checked: flipY,
+ disabled: !hasOpenDocument,
+ onClick: toggleFlipVertical,
+ },
+ {
+ id: 'view-reset-flip',
+ label: 'Reset View Flip',
+ disabled: !hasOpenDocument || (!flipX && !flipY),
+ onClick: resetViewFlip,
+ },
{
id: 'view-div-ruler',
label: '',
@@ -6652,6 +6718,11 @@ export function App() {
onResetZoom={resetZoomAndCenter}
rotation={rotation}
onResetRotation={resetRotation}
+ flipX={flipX}
+ flipY={flipY}
+ onToggleFlipHorizontal={toggleFlipHorizontal}
+ onToggleFlipVertical={toggleFlipVertical}
+ onResetViewFlip={resetViewFlip}
dimensions={dimensions}
colorMode={colorMode}
menuSections={menuSections}
@@ -6744,6 +6815,9 @@ export function App() {
zoom={zoom}
pan={pan}
rotation={rotation}
+ flipX={flipX}
+ flipY={flipY}
+ navigation={navigation}
isSpaceDown={isSpaceDown}
isShiftDown={isShiftDown}
isRotateModifier={isRotateModifier}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 75a1655..90ba38c 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -12,7 +12,7 @@ import {
SoftProofSettings,
CanvasColorMode,
} from '../types/editor';
-import { ROTATE_CURSOR_CSS } from '../hooks/useCanvasNavigation';
+import { ROTATE_CURSOR_CSS, CanvasNavigationHandle } from '../hooks/useCanvasNavigation';
import { SelectionOverlay } from './SelectionOverlay';
import { TransformOverlay } from './TransformOverlay';
import { TextEditorOverlay } from './TextEditorOverlay';
@@ -41,6 +41,9 @@ interface CanvasAreaProps {
zoom: number;
pan: { x: number; y: number };
rotation: number;
+ flipX?: boolean;
+ flipY?: boolean;
+ navigation?: CanvasNavigationHandle;
isSpaceDown: boolean;
isShiftDown: boolean;
isRotateModifier: boolean;
@@ -122,13 +125,29 @@ interface CanvasAreaProps {
colorMode?: CanvasColorMode;
}
-function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
+export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
const native = e.nativeEvent;
- if (native && typeof native.getCoalescedEvents === 'function') {
+ if (!native) return [];
+ // Per W3C Pointer Events spec, pointerdown represents a single contact event;
+ // some Windows/WebView2 stylus drivers emit stale or DPI-offset coalesced packets on pointerdown.
+ if (native.type === 'pointerdown') {
+ return [native];
+ }
+ if (typeof native.getCoalescedEvents === 'function') {
try {
const coalesced = native.getCoalescedEvents();
if (coalesced && coalesced.length > 0) {
- return coalesced as unknown as PointerEvent[];
+ const last = coalesced[coalesced.length - 1];
+ // Guard against Chromium/WebView2 Windows Ink DPI coordinate-space mismatch where
+ // getCoalescedEvents() diverges from the dispatching PointerEvent's clientX/clientY.
+ if (
+ last &&
+ Number.isFinite(last.clientX) &&
+ Number.isFinite(last.clientY) &&
+ Math.hypot(last.clientX - native.clientX, last.clientY - native.clientY) <= 1.5
+ ) {
+ return coalesced as unknown as PointerEvent[];
+ }
}
} catch {}
}
@@ -148,6 +167,32 @@ function extractPredictedEvents(e: React.PointerEvent<HTMLElement>): PointerEven
return [];
}
+function formatArtboardTransform(
+ pan: { x: number; y: number },
+ zoom: number,
+ rotation: number,
+ flipX: boolean,
+ flipY: boolean,
+ dimensions: CanvasDimensions
+): string {
+ const sx = (flipX ? -1 : 1) * zoom;
+ const sy = (flipY ? -1 : 1) * zoom;
+ return `translate3d(${pan.x}px, ${pan.y}px, 0) rotate(${rotation}deg) scale(${sx}, ${sy}) translate3d(${-dimensions.width / 2}px, ${-dimensions.height / 2}px, 0)`;
+}
+
+function formatCursorRingTransform(
+ x: number,
+ y: number,
+ rotation: number,
+ flipX: boolean,
+ flipY: boolean,
+ tipAngleDeg: number
+): string {
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
+ return `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%) rotate(${rotation}deg) scale(${fx}, ${fy}) rotate(${tipAngleDeg}deg)`;
+}
+
export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
viewportRef,
onViewportReady,
@@ -157,6 +202,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
zoom,
pan,
rotation,
+ flipX = false,
+ flipY = false,
+ navigation,
isSpaceDown,
isRotateModifier,
isPanning,
@@ -289,25 +337,54 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
// Dynamic cursor dimensions according to brush tip shape, aspect ratio, and thickness
+ const liveCamera = navigation
+ ? navigation.getCameraState()
+ : { pan, zoom, rotation, flipX, flipY };
+ const liveZoom = liveCamera.zoom;
+ const livePan = liveCamera.pan;
+ const liveRotation = liveCamera.rotation;
+ const liveFlipX = liveCamera.flipX;
+ const liveFlipY = liveCamera.flipY;
+
const isCustomTip = Boolean(tipOutline && (tool === 'brush' || tool === 'eraser'));
const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;
const tipAspect = isCustomTip && tipOutline ? tipOutline.height / tipOutline.width : 1.0;
const activeToolSize = tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size;
- const cursorBaseWidth = Math.max(4, activeToolSize * zoom);
+ const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);
const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;
+ const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');
+ const tipAngleDeg = tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0;
- const cursorWidth = brushSettings.thicknessVertical && tool === 'brush'
+ const cursorWidth = thicknessVertical
? Math.max(2, cursorBaseWidth * thicknessRatio)
: cursorBaseWidth;
- const cursorHeight = brushSettings.thicknessVertical && tool === 'brush'
+ const cursorHeight = thicknessVertical
? Math.max(2, cursorBaseWidth * tipAspect)
: Math.max(2, cursorBaseWidth * tipAspect * thicknessRatio);
// Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
- const totalAngleDeg = (tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0) + rotation;
- const totalAngleRef = useRef(totalAngleDeg);
- totalAngleRef.current = totalAngleDeg;
+ const totalAngleDeg = tipAngleDeg + liveRotation;
+ const cursorConfigRef = useRef({
+ activeToolSize,
+ tipAspect,
+ thicknessRatio,
+ thicknessVertical,
+ tipAngleDeg,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ });
+ cursorConfigRef.current = {
+ activeToolSize,
+ tipAspect,
+ thicknessRatio,
+ thicknessVertical,
+ tipAngleDeg,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
+ };
const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);
// Dynamic on-canvas brush resizing via Ctrl + Alt + Drag
@@ -319,7 +396,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
hardness: brushSettings.hardness ?? 1.0,
});
- // Zero-latency direct DOM cursor preview element
+ // Zero-latency direct DOM cursor preview element & artboard container
+ const artboardRef = useRef<HTMLDivElement | null>(null);
const cursorRingRef = useRef<HTMLDivElement | null>(null);
const pointerStatRef = useRef<HTMLDivElement | null>(null);
@@ -349,14 +427,22 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
}, [showCursorCoordinates, showPressureInStatusBar]);
- // Update cursor rotation in-place when viewport rotates or brush tip angle changes while hovering
+ // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle changes while hovering
useEffect(() => {
const ring = cursorRingRef.current;
const pos = lastPointerPosRef.current;
if (ring && pos && ring.style.display !== 'none') {
- ring.style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0) translate(-50%, -50%) rotate(${totalAngleDeg}deg)`;
+ const cfg = cursorConfigRef.current;
+ ring.style.transform = formatCursorRingTransform(
+ pos.x,
+ pos.y,
+ cfg.rotation,
+ cfg.flipX,
+ cfg.flipY,
+ cfg.tipAngleDeg
+ );
}
- }, [totalAngleDeg]);
+ }, [tipAngleDeg, liveRotation, liveFlipX, liveFlipY]);
useEffect(() => {
const viewport = viewportRef.current;
@@ -368,10 +454,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
window.addEventListener('resize', updateRect);
+ window.addEventListener('scroll', updateRect, true);
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;
ro?.observe(viewport);
- const handleWindowPointerMove = (e: PointerEvent) => {
+ const updateCursorRingPos = (e: PointerEvent, forceRefreshRect: boolean = false) => {
const ring = cursorRingRef.current;
if (!ring) return;
@@ -387,7 +474,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return;
}
- if (!cachedRect) updateRect();
+ if (forceRefreshRect || !cachedRect) updateRect();
if (!cachedRect) return;
const x = e.clientX - cachedRect.left;
@@ -399,13 +486,28 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}
lastPointerPosRef.current = { x, y };
- const currentAngle = totalAngleRef.current;
- ring.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%) rotate(${currentAngle}deg)`;
+ const cfg = cursorConfigRef.current;
+ ring.style.transform = formatCursorRingTransform(
+ x,
+ y,
+ cfg.rotation,
+ cfg.flipX,
+ cfg.flipY,
+ cfg.tipAngleDeg
+ );
if (ring.style.display !== 'block') {
ring.style.display = 'block';
}
};
+ const handleWindowPointerMove = (e: PointerEvent) => {
+ updateCursorRingPos(e, false);
+ };
+
+ const handleViewportPointerEnterOrDown = (e: PointerEvent) => {
+ updateCursorRingPos(e, true);
+ };
+
const handlePointerLeave = () => {
lastPointerPosRef.current = null;
if (cursorRingRef.current) {
@@ -414,15 +516,20 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
viewport.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
+ viewport.addEventListener('pointerdown', handleViewportPointerEnterOrDown, { passive: true });
+ viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });
viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });
return () => {
window.removeEventListener('resize', updateRect);
+ window.removeEventListener('scroll', updateRect, true);
ro?.disconnect();
viewport.removeEventListener('pointermove', handleWindowPointerMove);
+ viewport.removeEventListener('pointerdown', handleViewportPointerEnterOrDown);
+ viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);
viewport.removeEventListener('pointerleave', handlePointerLeave);
};
- }, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef, tool]);
+ }, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef, tool, hasOpenDocument]);
// Compute colored onion skin frames and active cel isolation for animation
const onionSkinFrames = useMemo(() => {
@@ -448,65 +555,175 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
// Unified GPU Viewport Compositor
const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
const compositorRef = useRef<ViewportCompositor | null>(null);
+ const viewportCssSizeRef = useRef<{ width: number; height: number } | null>(null);
const renderParamsRef = useRef({
effectiveLayers,
- pan,
- zoom,
- rotation,
+ pan: livePan,
+ zoom: liveZoom,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
dimensions,
showCheckerboard,
onionSkinFrames,
softProofSettings,
+ activeLayerId,
+ brushOpacity: brushSettings.opacity ?? 1.0,
+ effectiveDraftCanvasRef,
});
renderParamsRef.current = {
effectiveLayers,
- pan,
- zoom,
- rotation,
+ pan: livePan,
+ zoom: liveZoom,
+ rotation: liveRotation,
+ flipX: liveFlipX,
+ flipY: liveFlipY,
dimensions,
showCheckerboard,
onionSkinFrames,
softProofSettings,
+ activeLayerId,
+ brushOpacity: brushSettings.opacity ?? 1.0,
+ effectiveDraftCanvasRef,
};
- // Synchronize viewport and draft overlay canvas resolution with the screen viewport
+ const buildCompositorOptions = (rp: typeof renderParamsRef.current, dpr: number) => {
+ const vCanvas = viewportCanvasRef.current;
+ const cssSize = viewportCssSizeRef.current;
+ if (vCanvas && compositorRef.current && cssSize && cssSize.width > 0 && cssSize.height > 0) {
+ const expectedW = Math.max(1, Math.round(cssSize.width * dpr));
+ const expectedH = Math.max(1, Math.round(cssSize.height * dpr));
+ if (vCanvas.width !== expectedW || vCanvas.height !== expectedH) {
+ compositorRef.current.resize(expectedW, expectedH);
+ const predCanvas = rp.effectiveDraftCanvasRef ? effectivePredictedCanvasRef?.current : null;
+ if (predCanvas && (predCanvas.width !== expectedW || predCanvas.height !== expectedH)) {
+ predCanvas.width = expectedW;
+ predCanvas.height = expectedH;
+ }
+ }
+ }
+ const draftCanvas = rp.effectiveDraftCanvasRef?.current ?? null;
+ const draftVersion = draftCanvas ? ((draftCanvas as any).__draftVersion ?? 0) : 0;
+ const draftSpace = ((draftCanvas as any)?.__draftSpace as 'document' | 'viewport' | undefined) ?? 'viewport';
+ const draftDocRect = (draftCanvas as any)?.__draftDocRect ?? null;
+ const draftMonochrome = Boolean((draftCanvas as any)?.__draftMonochrome);
+ return {
+ dimensions: rp.dimensions,
+ showCheckerboard: rp.showCheckerboard,
+ devicePixelRatio: dpr,
+ onionSkinFrames: rp.onionSkinFrames,
+ softProof: rp.softProofSettings,
+ activeLayerId: rp.activeLayerId ?? null,
+ activeDraftLayerId: rp.activeLayerId ?? null,
+ activeDraftCanvas: draftCanvas,
+ activeDraftDirtyRect: draftSpace === 'document' ? draftDocRect : null,
+ activeDraftVersion: draftVersion,
+ activeDraftSpace: draftSpace,
+ activeDraftOpacity: rp.brushOpacity,
+ activeDraftMonochrome: draftMonochrome,
+ };
+ };
+
+ // Direct zero-React-rerender camera subscription for smooth 60-240Hz pan, zoom, rotation, and view flip
useEffect(() => {
- const updateCanvasSizes = () => {
- const viewport = viewportRef.current;
- if (!viewport) return;
- const rect = viewport.getBoundingClientRect();
- const dpr = window.devicePixelRatio || 1;
- const w = Math.max(1, Math.ceil(rect.width * dpr));
- const h = Math.max(1, Math.ceil(rect.height * dpr));
+ if (!navigation) return;
+ return navigation.subscribeCamera((cam) => {
+ const rp = renderParamsRef.current;
+ rp.pan = cam.pan;
+ rp.zoom = cam.zoom;
+ rp.rotation = cam.rotation;
+ rp.flipX = cam.flipX;
+ rp.flipY = cam.flipY;
+
+ const cfg = cursorConfigRef.current;
+ cfg.rotation = cam.rotation;
+ cfg.flipX = cam.flipX;
+ cfg.flipY = cam.flipY;
+
+ const artboard = artboardRef.current;
+ if (artboard) {
+ artboard.style.transform = formatArtboardTransform(
+ cam.pan,
+ cam.zoom,
+ cam.rotation,
+ cam.flipX,
+ cam.flipY,
+ rp.dimensions
+ );
+ artboard.style.imageRendering = cam.zoom > 1 ? 'pixelated' : 'auto';
+ }
- const vCanvas = viewportCanvasRef.current;
- if (vCanvas && (vCanvas.width !== w || vCanvas.height !== h)) {
- vCanvas.width = w;
- vCanvas.height = h;
- if (!compositorRef.current) {
- compositorRef.current = new ViewportCompositor(vCanvas);
+ const ring = cursorRingRef.current;
+ if (ring) {
+ const baseW = Math.max(4, cfg.activeToolSize * cam.zoom);
+ const cW = cfg.thicknessVertical
+ ? Math.max(2, baseW * cfg.thicknessRatio)
+ : baseW;
+ const cH = cfg.thicknessVertical
+ ? Math.max(2, baseW * cfg.tipAspect)
+ : Math.max(2, baseW * cfg.tipAspect * cfg.thicknessRatio);
+ ring.style.width = `${cW}px`;
+ ring.style.height = `${cH}px`;
+ const pos = lastPointerPosRef.current;
+ if (pos && ring.style.display !== 'none') {
+ ring.style.transform = formatCursorRingTransform(
+ pos.x,
+ pos.y,
+ cam.rotation,
+ cam.flipX,
+ cam.flipY,
+ cfg.tipAngleDeg
+ );
}
- compositorRef.current.resize(w, h);
- const rp = renderParamsRef.current;
+ }
+
+ if (viewportCanvasRef.current && !compositorRef.current) {
+ compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
+ }
+ if (compositorRef.current) {
+ const dpr = window.devicePixelRatio || 1;
compositorRef.current.render(
rp.effectiveLayers,
- { pan: rp.pan, zoom: rp.zoom, rotation: rp.rotation },
+ {
+ pan: cam.pan,
+ zoom: cam.zoom,
+ rotation: cam.rotation,
+ flipX: cam.flipX,
+ flipY: cam.flipY,
+ },
rp.dimensions,
globalTileGrid,
- {
- dimensions: rp.dimensions,
- showCheckerboard: rp.showCheckerboard,
- devicePixelRatio: dpr,
- onionSkinFrames: rp.onionSkinFrames,
- softProof: rp.softProofSettings,
- }
+ buildCompositorOptions(rp, dpr)
);
}
+ });
+ }, [navigation]);
+
+ // Synchronize viewport and draft overlay canvas resolution with the screen viewport
+ useEffect(() => {
+ let dprMql: MediaQueryList | null = null;
+
+ const updateCanvasSizes = () => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ const rect = viewport.getBoundingClientRect();
+ if (rect.width > 0 && rect.height > 0) {
+ viewportCssSizeRef.current = { width: rect.width, height: rect.height };
+ }
+ const dpr = window.devicePixelRatio || 1;
+ const w = Math.max(1, Math.round(rect.width * dpr));
+ const h = Math.max(1, Math.round(rect.height * dpr));
const draftCanvas = effectiveDraftCanvasRef?.current;
- if (draftCanvas && (draftCanvas.width !== w || draftCanvas.height !== h)) {
+ if (
+ draftCanvas &&
+ (draftCanvas as any).__draftSpace !== 'document' &&
+ (draftCanvas.width !== w || draftCanvas.height !== h)
+ ) {
draftCanvas.width = w;
draftCanvas.height = h;
+ (draftCanvas as any).__draftHasContent = false;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
}
const predCanvas = effectivePredictedCanvasRef?.current;
@@ -514,9 +731,59 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
predCanvas.width = w;
predCanvas.height = h;
}
+
+ const vCanvas = viewportCanvasRef.current;
+ if (vCanvas) {
+ if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
+ const sizeChanged = vCanvas.width !== w || vCanvas.height !== h;
+ if (sizeChanged || !compositorRef.current) {
+ if (!compositorRef.current) {
+ vCanvas.width = w;
+ vCanvas.height = h;
+ compositorRef.current = new ViewportCompositor(vCanvas);
+ } else {
+ compositorRef.current.resize(w, h);
+ }
+ const rp = renderParamsRef.current;
+ compositorRef.current.render(
+ rp.effectiveLayers,
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
+ rp.dimensions,
+ globalTileGrid,
+ buildCompositorOptions(rp, dpr)
+ );
+ }
+ }
+ };
+
+ const handleDprChange = () => {
+ updateCanvasSizes();
+ attachDprListener();
+ };
+
+ const attachDprListener = () => {
+ if (dprMql) {
+ dprMql.removeEventListener?.('change', handleDprChange);
+ dprMql = null;
+ }
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
+ const curDpr = window.devicePixelRatio || 1;
+ dprMql = window.matchMedia(`(resolution: ${curDpr}dppx)`);
+ dprMql.addEventListener?.('change', handleDprChange);
+ }
};
updateCanvasSizes();
+ attachDprListener();
window.addEventListener('resize', updateCanvasSizes);
const ro = typeof ResizeObserver !== 'undefined' && viewportRef.current
? new ResizeObserver(updateCanvasSizes)
@@ -526,9 +793,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}
return () => {
window.removeEventListener('resize', updateCanvasSizes);
+ dprMql?.removeEventListener?.('change', handleDprChange);
ro?.disconnect();
};
- }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef]);
+ }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, hasOpenDocument]);
useEffect(() => {
if (viewportRef.current) {
@@ -544,9 +812,14 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
// Render scene using Unified GPU Viewport Compositor
useEffect(() => {
- if (!viewportCanvasRef.current) return;
+ const vCanvas = viewportCanvasRef.current;
+ if (!vCanvas) return;
+ if (compositorRef.current && compositorRef.current.getCanvas() !== vCanvas) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
if (!compositorRef.current) {
- compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
+ compositorRef.current = new ViewportCompositor(vCanvas);
}
// Ingest unindexed layer canvases into globalTileGrid
@@ -570,14 +843,21 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}
const dpr = window.devicePixelRatio || 1;
+ const rp = renderParamsRef.current;
compositorRef.current.render(
effectiveLayers,
- { pan, zoom, rotation },
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
dimensions,
globalTileGrid,
- { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames, softProof: softProofSettings }
+ buildCompositorOptions(rp, dpr)
);
- }, [effectiveLayers, layers, pan, zoom, rotation, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas, onionSkinFrames, softProofSettings]);
+ }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas, onionSkinFrames, softProofSettings, activeLayerId, brushSettings.opacity, colorMode]);
// Event-Driven Compositor Invalidation via SparseTileGrid subscription
useEffect(() => {
@@ -588,16 +868,16 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
const rp = renderParamsRef.current;
compositorRef.current.render(
rp.effectiveLayers,
- { pan: rp.pan, zoom: rp.zoom, rotation: rp.rotation },
+ {
+ pan: rp.pan,
+ zoom: rp.zoom,
+ rotation: rp.rotation,
+ flipX: rp.flipX,
+ flipY: rp.flipY,
+ },
rp.dimensions,
globalTileGrid,
- {
- dimensions: rp.dimensions,
- showCheckerboard: rp.showCheckerboard,
- devicePixelRatio: dpr,
- onionSkinFrames: rp.onionSkinFrames,
- softProof: rp.softProofSettings,
- }
+ buildCompositorOptions(rp, dpr)
);
}
};
@@ -911,17 +1191,25 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}}
/>
- {/* Artboard Container with 2D Affine Transformation (Pan, Zoom, and Rotation) */}
+ {/* Artboard Container with 2D Affine Transformation (Pan, Zoom, Rotation, and Non-Destructive View Flip) */}
<div
+ ref={artboardRef}
className="absolute origin-top-left select-none z-20"
style={{
width: dimensions.width,
height: dimensions.height,
- transform: `translate3d(${pan.x}px, ${pan.y}px, 0) rotate(${rotation}deg) scale(${zoom}) translate3d(${-dimensions.width / 2}px, ${-dimensions.height / 2}px, 0)`,
+ transform: formatArtboardTransform(
+ livePan,
+ liveZoom,
+ liveRotation,
+ liveFlipX,
+ liveFlipY,
+ dimensions
+ ),
transformOrigin: '0 0',
boxShadow: '0 0 0 1px #161616, 0 10px 40px rgba(0, 0, 0, 0.55)',
willChange: 'transform',
- imageRendering: zoom > 1 ? 'pixelated' : 'auto',
+ imageRendering: liveZoom > 1 ? 'pixelated' : 'auto',
backgroundColor: 'transparent',
backgroundImage: 'none',
}}
@@ -963,7 +1251,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
{/* Floating Nametag Pill */}
<div
className="absolute top-4 left-2 px-1.5 py-0.5 rounded text-[10px] font-semibold text-white shadow-lg whitespace-nowrap flex items-center space-x-1 pointer-events-none"
- style={{ backgroundColor: peer.color }}
+ style={{
+ backgroundColor: peer.color,
+ transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
+ }}
>
<span>{peer.name}</span>
{peer.isDrawing && <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
@@ -989,7 +1280,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
/>
<div
className="absolute top-5 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded text-[10px] font-bold text-white whitespace-nowrap shadow-md"
- style={{ backgroundColor: ping.color }}
+ style={{
+ backgroundColor: ping.color,
+ transform: `scale(${liveFlipX ? -1 : 1}, ${liveFlipY ? -1 : 1})`,
+ }}
>
{ping.name}
</div>
@@ -1001,7 +1295,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
<SelectionOverlay
selection={selection}
dimensions={dimensions}
- zoom={zoom}
+ zoom={liveZoom}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
onDeselect={onDeselect || (() => {})}
onTransformSelection={onTransformSelection || (() => {})}
onFillScreentone={onFillScreentone || (() => {})}
@@ -1018,8 +1314,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
{transformSession?.active && (
<TransformOverlay
session={transformSession}
- zoom={zoom}
- rotation={rotation}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
onUpdateSession={onUpdateTransformSession || (() => {})}
onApply={onApplyTransform || (() => {})}
onCancel={onCancelTransform || (() => {})}
@@ -1032,7 +1330,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
x={textSession.x}
y={textSession.y}
settings={textSession.settings}
- zoom={zoom}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
onUpdateSettings={onUpdateTextSettings || (() => {})}
onMove={onMoveTextSession || (() => {})}
onConfirm={onConfirmText || (() => {})}
@@ -1044,7 +1345,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
{activeBalloon && (
<SpeechBalloonOverlay
balloon={activeBalloon}
- zoom={zoom}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
onUpdateBalloon={onUpdateBalloon || (() => {})}
onConfirmBalloon={onConfirmBalloon || (() => {})}
onDeleteBalloon={onDeleteBalloon || (() => {})}
@@ -1083,16 +1387,16 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
/>
</div>
- {/* Active Draft/Stroke Overlay Canvas matching the Screen Viewport (Clip Studio Paint style) */}
+ {/* Offscreen Active Draft/Stroke Backing Canvas (composited in-stack inside ViewportCompositor at activeLayerId) */}
<canvas
ref={effectiveDraftCanvasRef}
className="absolute inset-0 pointer-events-none z-25"
style={{
width: '100%',
height: '100%',
- opacity: brushSettings.opacity ?? 1.0,
+ opacity: 0,
+ visibility: 'hidden',
display: 'block',
- filter: isMonochromeActive ? 'url(#ink-monochrome-threshold)' : undefined,
}}
/>
@@ -1105,7 +1409,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,
+ filter: isMonochromeActive && liveZoom >= 0.99 ? 'url(#ink-monochrome-threshold)' : undefined,
}}
/>
@@ -1127,9 +1431,12 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onUpdateRuler={onUpdatePerspectiveRuler}
onRemoveRuler={() => onUpdatePerspectiveRuler(null)}
dimensions={dimensions}
- pan={pan}
- zoom={zoom}
- rotation={rotation}
+ pan={livePan}
+ zoom={liveZoom}
+ rotation={liveRotation}
+ flipX={liveFlipX}
+ flipY={liveFlipY}
+ navigation={navigation}
viewportRef={viewportRef}
activeLockedAxis={activeLockedAxis}
isDrawing={isDrawing}
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 2800965..33b699f 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -8,6 +8,8 @@ import {
Users,
Settings,
RotateCcw,
+ FlipHorizontal,
+ FlipVertical,
} from 'lucide-react';
import {
CanvasDimensions,
@@ -33,6 +35,11 @@ interface HeaderProps {
onResetZoom: () => void;
rotation: number;
onResetRotation: () => void;
+ flipX?: boolean;
+ flipY?: boolean;
+ onToggleFlipHorizontal?: () => void;
+ onToggleFlipVertical?: () => void;
+ onResetViewFlip?: () => void;
dimensions?: CanvasDimensions;
colorMode?: CanvasColorMode;
menuSections?: MenuSection[];
@@ -64,6 +71,11 @@ export const Header: React.FC<HeaderProps> = React.memo(({
onResetZoom,
rotation,
onResetRotation,
+ flipX = false,
+ flipY = false,
+ onToggleFlipHorizontal,
+ onToggleFlipVertical,
+ onResetViewFlip,
colorMode = 'color',
menuSections,
hasOpenDocument = true,
@@ -224,6 +236,20 @@ export const Header: React.FC<HeaderProps> = React.memo(({
</span>
)}
+ {hasOpenDocument && (flipX || flipY) && (
+ <button
+ type="button"
+ onClick={onResetViewFlip}
+ data-testid="view-flip-badge"
+ title="Non-destructive View Mirror active (display only — layer pixels unchanged). Click to reset view flip."
+ className="h-6 px-1.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] font-mono uppercase text-[var(--accent)] border border-[var(--accent)]/40 flex items-center gap-1 transition-colors cursor-pointer"
+ >
+ <span>
+ {flipX && flipY ? 'View Flip H+V' : flipX ? 'View Flip H' : 'View Flip V'}
+ </span>
+ </button>
+ )}
+
{hasOpenDocument && isRotated && (
<button
type="button"
@@ -298,6 +324,48 @@ export const Header: React.FC<HeaderProps> = React.memo(({
</button>
</div>
+ {/* Non-Destructive View Flip Controls (CSP-style Mirror View) */}
+ {(onToggleFlipHorizontal || onToggleFlipVertical) && (
+ <div
+ className={`h-6 flex items-center bg-[#161616] rounded px-0.5 gap-0.5 ${
+ !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
+ }`}
+ >
+ {onToggleFlipHorizontal && (
+ <button
+ type="button"
+ onClick={onToggleFlipHorizontal}
+ aria-label="Flip View Horizontal"
+ aria-pressed={flipX}
+ title="Flip View Horizontal (Shift+H) — non-destructive view mirror"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ flipX
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <FlipHorizontal className="w-3.5 h-3.5" />
+ </button>
+ )}
+ {onToggleFlipVertical && (
+ <button
+ type="button"
+ onClick={onToggleFlipVertical}
+ aria-label="Flip View Vertical"
+ aria-pressed={flipY}
+ title="Flip View Vertical (Shift+V) — non-destructive view mirror"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ flipY
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <FlipVertical className="w-3.5 h-3.5" />
+ </button>
+ )}
+ </div>
+ )}
+
{/* Collab Session Button */}
{onOpenCollabModal && (
<button
diff --git a/src/components/PerspectiveRulerOverlay.tsx b/src/components/PerspectiveRulerOverlay.tsx
index 43545dc..dc22aa7 100644
--- a/src/components/PerspectiveRulerOverlay.tsx
+++ b/src/components/PerspectiveRulerOverlay.tsx
@@ -14,6 +14,7 @@ import {
} from '../utils/perspectiveMath';
import { canvasToScreen, screenToCanvas } from '../utils/canvasUtils';
import { CanvasDimensions } from '../types/editor';
+import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';
import {
Lock,
Unlock,
@@ -32,6 +33,9 @@ interface PerspectiveRulerOverlayProps {
pan: { x: number; y: number };
zoom: number;
rotation: number;
+ flipX?: boolean;
+ flipY?: boolean;
+ navigation?: CanvasNavigationHandle;
viewportRef: React.RefObject<HTMLDivElement | null>;
activeLockedAxis?: ConstraintAxis | null;
isDrawing?: boolean;
@@ -72,6 +76,9 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
pan,
zoom,
rotation,
+ flipX = false,
+ flipY = false,
+ navigation,
viewportRef,
activeLockedAxis = null,
}) => {
@@ -97,6 +104,9 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
pan,
zoom,
rotation,
+ flipX,
+ flipY,
+ navigation,
activeLockedAxis,
});
@@ -106,6 +116,9 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
pan,
zoom,
rotation,
+ flipX,
+ flipY,
+ navigation,
activeLockedAxis,
};
@@ -138,12 +151,24 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
const {
ruler: curRuler,
dimensions: dims,
- pan: curPan,
- zoom: curZoom,
- rotation: curRot,
+ pan: propPan,
+ zoom: propZoom,
+ rotation: propRot,
+ flipX: propFlipX,
+ flipY: propFlipY,
+ navigation: curNav,
activeLockedAxis: curAxis,
} = propsRef.current;
+ const liveCam = curNav
+ ? curNav.getCameraState()
+ : { pan: propPan, zoom: propZoom, rotation: propRot, flipX: propFlipX, flipY: propFlipY };
+ const curPan = liveCam.pan;
+ const curZoom = liveCam.zoom;
+ const curRot = liveCam.rotation;
+ const curFlipX = liveCam.flipX;
+ const curFlipY = liveCam.flipY;
+
if (!curRuler.enabled) {
ctx.restore();
return;
@@ -152,10 +177,10 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
const screenRect = { x: 0, y: 0, width: vRect.width, height: vRect.height };
// Canvas Corners in Screen Space
- const c0 = canvasToScreen(0, 0, curPan, curZoom, curRot, dims);
- const c1 = canvasToScreen(dims.width, 0, curPan, curZoom, curRot, dims);
- const c2 = canvasToScreen(dims.width, dims.height, curPan, curZoom, curRot, dims);
- const c3 = canvasToScreen(0, dims.height, curPan, curZoom, curRot, dims);
+ const c0 = canvasToScreen(0, 0, curPan, curZoom, curRot, dims, curFlipX, curFlipY);
+ const c1 = canvasToScreen(dims.width, 0, curPan, curZoom, curRot, dims, curFlipX, curFlipY);
+ const c2 = canvasToScreen(dims.width, dims.height, curPan, curZoom, curRot, dims, curFlipX, curFlipY);
+ const c3 = canvasToScreen(0, dims.height, curPan, curZoom, curRot, dims, curFlipX, curFlipY);
// 1. Draw Subtle Canvas Paper Boundary Guide
ctx.save();
@@ -171,21 +196,21 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
ctx.restore();
// 2. Horizon Line across the scene
- renderHorizonLine(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect);
+ renderHorizonLine(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, curFlipX, curFlipY);
// 3. Clean Sparse Guide Rays (Strictly 2 per VP for 2P/3P, 4 for 1P)
- renderCleanGuideRays(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, [c0, c1, c2, c3]);
+ renderCleanGuideRays(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, [c0, c1, c2, c3], curFlipX, curFlipY);
// 4. Single Upright Vertical Center Guide (for 1P and 2P)
- renderVerticalGuide(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, [c0, c1, c2, c3]);
+ renderVerticalGuide(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, [c0, c1, c2, c3], curFlipX, curFlipY);
// 5. Active Snapped Constraint Axis (High-contrast laser when inking)
if (curAxis) {
- renderActiveLockedAxis(ctx, curAxis, dims, curPan, curZoom, curRot, screenRect);
+ renderActiveLockedAxis(ctx, curAxis, dims, curPan, curZoom, curRot, screenRect, curFlipX, curFlipY);
}
// 6. Vanishing Point pivot rings
- renderVanishingPointVisuals(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect);
+ renderVanishingPointVisuals(ctx, curRuler, dims, curPan, curZoom, curRot, screenRect, curFlipX, curFlipY);
ctx.restore();
}, [viewportRef]);
@@ -242,24 +267,32 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
if (!viewport) return;
const vRect = viewport.getBoundingClientRect();
+ const liveCam = navigation
+ ? navigation.getCameraState()
+ : { pan, zoom, rotation, flipX, flipY };
+
if (activeDragTarget === 'horizon') {
const pStart = screenToCanvas(
dragStartRef.current.clientX,
dragStartRef.current.clientY,
vRect,
- pan,
- zoom,
- rotation,
- dimensions
+ liveCam.pan,
+ liveCam.zoom,
+ liveCam.rotation,
+ dimensions,
+ liveCam.flipX,
+ liveCam.flipY
);
const pCurr = screenToCanvas(
e.clientX,
e.clientY,
vRect,
- pan,
- zoom,
- rotation,
- dimensions
+ liveCam.pan,
+ liveCam.zoom,
+ liveCam.rotation,
+ dimensions,
+ liveCam.flipX,
+ liveCam.flipY
);
const deltaY = pCurr.y - pStart.y;
@@ -286,10 +319,12 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
e.clientX,
e.clientY,
vRect,
- pan,
- zoom,
- rotation,
- dimensions
+ liveCam.pan,
+ liveCam.zoom,
+ liveCam.rotation,
+ dimensions,
+ liveCam.flipX,
+ liveCam.flipY
);
const updatedVps = ruler.vps.map((vp) => {
@@ -341,14 +376,17 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
};
// Center coordinate of horizon line on canvas
+ const renderCam = navigation ? navigation.getCameraState() : { pan, zoom, rotation, flipX, flipY };
const horizon = getHorizonLine(ruler);
const horizonCenterScreen = canvasToScreen(
dimensions.width / 2,
(horizon.p1.y + horizon.p2.y) / 2,
- pan,
- zoom,
- rotation,
- dimensions
+ renderCam.pan,
+ renderCam.zoom,
+ renderCam.rotation,
+ dimensions,
+ renderCam.flipX,
+ renderCam.flipY
);
return (
@@ -388,7 +426,16 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
{/* Draggable VP Handles (on-screen & off-screen edge tags) */}
{ruler.vps.map((vp) => {
- const sPos = canvasToScreen(vp.x, vp.y, pan, zoom, rotation, dimensions);
+ const sPos = canvasToScreen(
+ vp.x,
+ vp.y,
+ renderCam.pan,
+ renderCam.zoom,
+ renderCam.rotation,
+ dimensions,
+ renderCam.flipX,
+ renderCam.flipY
+ );
const viewport = viewportRef.current;
const vRect = viewport ? viewport.getBoundingClientRect() : { width: 1920, height: 1080 };
const isInside =
@@ -629,11 +676,13 @@ function renderHorizonLine(
pan: { x: number; y: number },
zoom: number,
rotation: number,
- screenRect: { x: number; y: number; width: number; height: number }
+ screenRect: { x: number; y: number; width: number; height: number },
+ flipX: boolean = false,
+ flipY: boolean = false
) {
const horizon = getHorizonLine(ruler);
- const hp1 = canvasToScreen(horizon.p1.x, horizon.p1.y, pan, zoom, rotation, dims);
- const hp2 = canvasToScreen(horizon.p2.x, horizon.p2.y, pan, zoom, rotation, dims);
+ const hp1 = canvasToScreen(horizon.p1.x, horizon.p1.y, pan, zoom, rotation, dims, flipX, flipY);
+ const hp2 = canvasToScreen(horizon.p2.x, horizon.p2.y, pan, zoom, rotation, dims, flipX, flipY);
const screenDir = { x: hp2.x - hp1.x, y: hp2.y - hp1.y };
const sLen = Math.hypot(screenDir.x, screenDir.y);
@@ -739,7 +788,9 @@ function renderCleanGuideRays(
zoom: number,
rotation: number,
screenRect: { x: number; y: number; width: number; height: number },
- canvasCorners: Vector2D[]
+ canvasCorners: Vector2D[],
+ flipX: boolean = false,
+ flipY: boolean = false
) {
ctx.save();
@@ -756,11 +807,11 @@ function renderCleanGuideRays(
for (const vp of ruler.vps) {
const rayDirs = computeVpRayDirections(vp, dims, rayCount, ruler.horizonAngle);
- const sVp = canvasToScreen(vp.x, vp.y, pan, zoom, rotation, dims);
+ const sVp = canvasToScreen(vp.x, vp.y, pan, zoom, rotation, dims, flipX, flipY);
for (const dir of rayDirs) {
const pFar = { x: vp.x + dir.x * 10000, y: vp.y + dir.y * 10000 };
- const sFar = canvasToScreen(pFar.x, pFar.y, pan, zoom, rotation, dims);
+ const sFar = canvasToScreen(pFar.x, pFar.y, pan, zoom, rotation, dims, flipX, flipY);
const sDir = { x: sFar.x - sVp.x, y: sFar.y - sVp.y };
const sLen = Math.hypot(sDir.x, sDir.y);
if (sLen < 1e-4) continue;
@@ -786,19 +837,21 @@ function renderVerticalGuide(
zoom: number,
rotation: number,
screenRect: { x: number; y: number; width: number; height: number },
- canvasCorners: Vector2D[]
+ canvasCorners: Vector2D[],
+ flipX: boolean = false,
+ flipY: boolean = false
) {
if (ruler.type !== '1-point' && ruler.type !== '2-point') return;
const horizon = getHorizonLine(ruler);
const originDoc = { x: dims.width * 0.5, y: dims.height * 0.5 };
- const sOrigin = canvasToScreen(originDoc.x, originDoc.y, pan, zoom, rotation, dims);
+ const sOrigin = canvasToScreen(originDoc.x, originDoc.y, pan, zoom, rotation, dims, flipX, flipY);
const pNextDoc = {
x: originDoc.x + horizon.normal.x * 1000,
y: originDoc.y + horizon.normal.y * 1000,
};
- const sNext = canvasToScreen(pNextDoc.x, pNextDoc.y, pan, zoom, rotation, dims);
+ const sNext = canvasToScreen(pNextDoc.x, pNextDoc.y, pan, zoom, rotation, dims, flipX, flipY);
const sDir = { x: sNext.x - sOrigin.x, y: sNext.y - sOrigin.y };
const sLen = Math.hypot(sDir.x, sDir.y);
@@ -861,11 +914,13 @@ function renderActiveLockedAxis(
pan: { x: number; y: number },
zoom: number,
rotation: number,
- screenRect: { x: number; y: number; width: number; height: number }
+ screenRect: { x: number; y: number; width: number; height: number },
+ flipX: boolean = false,
+ flipY: boolean = false
) {
- const sOrigin = canvasToScreen(axis.origin.x, axis.origin.y, pan, zoom, rotation, dims);
+ const sOrigin = canvasToScreen(axis.origin.x, axis.origin.y, pan, zoom, rotation, dims, flipX, flipY);
const pNext = { x: axis.origin.x + axis.dir.x * 1000, y: axis.origin.y + axis.dir.y * 1000 };
- const sNext = canvasToScreen(pNext.x, pNext.y, pan, zoom, rotation, dims);
+ const sNext = canvasToScreen(pNext.x, pNext.y, pan, zoom, rotation, dims, flipX, flipY);
const sDir = { x: sNext.x - sOrigin.x, y: sNext.y - sOrigin.y };
const sLen = Math.hypot(sDir.x, sDir.y);
@@ -907,10 +962,12 @@ function renderVanishingPointVisuals(
pan: { x: number; y: number },
zoom: number,
rotation: number,
- screenRect: { x: number; y: number; width: number; height: number }
+ screenRect: { x: number; y: number; width: number; height: number },
+ flipX: boolean = false,
+ flipY: boolean = false
) {
for (const vp of ruler.vps) {
- const sPos = canvasToScreen(vp.x, vp.y, pan, zoom, rotation, dims);
+ const sPos = canvasToScreen(vp.x, vp.y, pan, zoom, rotation, dims, flipX, flipY);
const isInside =
sPos.x >= 0 &&
sPos.x <= screenRect.width &&
diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsx
index 296f86e..00db393 100644
--- a/src/components/SelectionOverlay.tsx
+++ b/src/components/SelectionOverlay.tsx
@@ -21,6 +21,8 @@ interface SelectionOverlayProps {
selection: CanvasSelection | null;
dimensions: CanvasDimensions;
zoom: number;
+ flipX?: boolean;
+ flipY?: boolean;
onDeselect: () => void;
onTransformSelection: () => void;
onFillScreentone: () => void;
@@ -36,6 +38,8 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
selection,
dimensions,
zoom,
+ flipX = false,
+ flipY = false,
onDeselect,
onTransformSelection,
onFillScreentone,
@@ -81,6 +85,8 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
if (!selection || !bounds) return null;
const invZoom = zoom > 0 ? 1 / zoom : 1;
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
return (
<>
@@ -141,7 +147,7 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
style={{
left: `${bounds.x + bounds.width / 2}px`,
top: `${bounds.y}px`,
- transform: `translate(-50%, calc(-100% - ${8 * invZoom}px)) scale(${invZoom})`,
+ transform: `translate(-50%, calc(-100% - ${8 * invZoom}px)) scale(${fx * invZoom}, ${fy * invZoom})`,
transformOrigin: 'bottom center',
}}
onPointerDown={(e) => e.stopPropagation()}
diff --git a/src/components/SpeechBalloonOverlay.tsx b/src/components/SpeechBalloonOverlay.tsx
index fd32d44..2e14214 100644
--- a/src/components/SpeechBalloonOverlay.tsx
+++ b/src/components/SpeechBalloonOverlay.tsx
@@ -13,6 +13,9 @@ import { getBalloonHandles, BalloonHandle } from '../utils/balloonEngine';
interface SpeechBalloonOverlayProps {
balloon: SpeechBalloon | null;
zoom: number;
+ rotation?: number;
+ flipX?: boolean;
+ flipY?: boolean;
onUpdateBalloon: (updater: (prev: SpeechBalloon) => SpeechBalloon) => void;
onConfirmBalloon: () => void;
onDeleteBalloon: () => void;
@@ -21,6 +24,9 @@ interface SpeechBalloonOverlayProps {
export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({
balloon,
zoom,
+ rotation = 0,
+ flipX = false,
+ flipY = false,
onUpdateBalloon,
onConfirmBalloon,
onDeleteBalloon,
@@ -67,8 +73,13 @@ export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({
const { activeHandle, startX, startY, initialBounds, initialTail } = dragRef.current;
if (!activeHandle) return;
- const dx = (e.clientX - startX) / zoom;
- const dy = (e.clientY - startY) / zoom;
+ const dxScreen = e.clientX - startX;
+ const dyScreen = e.clientY - startY;
+ const rad = (-rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const dx = ((dxScreen * cos - dyScreen * sin) * (flipX ? -1 : 1)) / zoom;
+ const dy = ((dxScreen * sin + dyScreen * cos) * (flipY ? -1 : 1)) / zoom;
onUpdateBalloon((prev) => {
if (activeHandle === 'tail-tip') {
@@ -242,7 +253,7 @@ export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({
style={{
left: `${bounds.x + bounds.width + 15}px`,
top: `${bounds.y}px`,
- transform: `scale(${zoom > 0 ? 1 / zoom : 1})`,
+ transform: `scale(${(flipX ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)}, ${(flipY ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)})`,
transformOrigin: 'top left',
}}
onPointerDown={(e) => e.stopPropagation()}
diff --git a/src/components/TextEditorOverlay.tsx b/src/components/TextEditorOverlay.tsx
index 4c9c76c..be45404 100644
--- a/src/components/TextEditorOverlay.tsx
+++ b/src/components/TextEditorOverlay.tsx
@@ -15,6 +15,9 @@ interface TextEditorOverlayProps {
y: number;
settings: TextSettings;
zoom: number;
+ rotation?: number;
+ flipX?: boolean;
+ flipY?: boolean;
onUpdateSettings: (updater: (prev: TextSettings) => TextSettings) => void;
onMove: (newX: number, newY: number) => void;
onConfirm: () => void;
@@ -36,6 +39,9 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({
y,
settings,
zoom,
+ rotation = 0,
+ flipX = false,
+ flipY = false,
onUpdateSettings,
onMove,
onConfirm,
@@ -65,8 +71,13 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({
const handleDragMove = (e: React.PointerEvent) => {
if (!isDraggingRef.current) return;
- const dx = (e.clientX - dragStartRef.current.clientX) / zoom;
- const dy = (e.clientY - dragStartRef.current.clientY) / zoom;
+ const dxScreen = e.clientX - dragStartRef.current.clientX;
+ const dyScreen = e.clientY - dragStartRef.current.clientY;
+ const rad = (-rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const dx = ((dxScreen * cos - dyScreen * sin) * (flipX ? -1 : 1)) / zoom;
+ const dy = ((dxScreen * sin + dyScreen * cos) * (flipY ? -1 : 1)) / zoom;
onMove(Math.round(dragStartRef.current.initX + dx), Math.round(dragStartRef.current.initY + dy));
};
@@ -121,7 +132,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({
<div
className="w-80 bg-[#1e1f22] border border-[#383a40] rounded-md shadow-2xl overflow-hidden flex flex-col"
style={{
- transform: `scale(${zoom > 0 ? 1 / zoom : 1})`,
+ transform: `scale(${(flipX ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)}, ${(flipY ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)})`,
transformOrigin: 'top left',
}}
>
diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsx
index f79f50e..30fe49c 100644
--- a/src/components/TransformOverlay.tsx
+++ b/src/components/TransformOverlay.tsx
@@ -23,6 +23,8 @@ interface TransformOverlayProps {
session: TransformSession;
zoom: number;
rotation: number; // canvas viewport rotation
+ flipX?: boolean;
+ flipY?: boolean;
onUpdateSession: (updater: (prev: TransformSession) => TransformSession) => void;
onApply: () => void;
onCancel: () => void;
@@ -32,6 +34,8 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
session,
zoom,
rotation: canvasRotation,
+ flipX = false,
+ flipY = false,
onUpdateSession,
onApply,
onCancel,
@@ -217,14 +221,16 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
});
};
- // Convert screen delta to un-rotated canvas coordinates
+ // Convert screen delta to un-rotated, un-flipped canvas coordinates
const screenDeltaToCanvas = (dxScreen: number, dyScreen: number): { dx: number; dy: number } => {
const canvasRotRad = (-canvasRotation * Math.PI) / 180;
const cCos = Math.cos(canvasRotRad);
const cSin = Math.sin(canvasRotRad);
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
return {
- dx: (dxScreen * cCos - dyScreen * cSin) / zoom,
- dy: (dxScreen * cSin + dyScreen * cCos) / zoom,
+ dx: ((dxScreen * cCos - dyScreen * cSin) * fx) / zoom,
+ dy: ((dxScreen * cSin + dyScreen * cCos) * fy) / zoom,
};
};
@@ -649,7 +655,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
style={{
left: `${nonAffineBounds.minX + nonAffineBounds.width / 2}px`,
top: `${nonAffineBounds.maxY}px`,
- transform: `translateX(-50%) translateY(${16 * invZoom}px) scale(${invZoom})`,
+ transform: `translateX(-50%) translateY(${16 * invZoom}px) scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,
transformOrigin: 'top center',
}}
onPointerDown={(e) => e.stopPropagation()}
diff --git a/src/engine/SplineGenerator.ts b/src/engine/SplineGenerator.ts
index 495915c..58e1f0e 100644
--- a/src/engine/SplineGenerator.ts
+++ b/src/engine/SplineGenerator.ts
@@ -12,6 +12,11 @@ export interface SplinePoint {
y: number;
pressure: number;
width: number;
+ tiltX?: number;
+ tiltY?: number;
+ twist?: number;
+ timestamp?: number;
+ isCorner?: boolean;
}
export interface CubicBezierSegment {
@@ -24,10 +29,10 @@ export interface CubicBezierSegment {
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 },
+ p0: { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0, timestamp: 0, isCorner: false },
+ c1: { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0, timestamp: 0, isCorner: false },
+ c2: { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0, timestamp: 0, isCorner: false },
+ p3: { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0, timestamp: 0, isCorner: false },
};
// Reusable exit tangent for Hermite continuity
@@ -63,6 +68,9 @@ export class SplineGenerator {
this.segment.p0.y = pPrev.y;
this.segment.p0.pressure = pPrev.pressure;
this.segment.p0.width = pPrev.width;
+ this.segment.p0.tiltX = pPrev.tiltX ?? 0;
+ this.segment.p0.tiltY = pPrev.tiltY ?? 0;
+ this.segment.p0.twist = pPrev.twist ?? 0;
this.segment.c1.x = pPrev.x + dx * 0.333;
this.segment.c1.y = pPrev.y + dy * 0.333;
@@ -78,6 +86,9 @@ export class SplineGenerator {
this.segment.p3.y = pCorner.y;
this.segment.p3.pressure = pCorner.pressure;
this.segment.p3.width = pCorner.width;
+ this.segment.p3.tiltX = pCorner.tiltX ?? 0;
+ this.segment.p3.tiltY = pCorner.tiltY ?? 0;
+ this.segment.p3.twist = pCorner.twist ?? 0;
this.hasLastTangent = false;
this.lastTangentX = 0;
@@ -104,11 +115,17 @@ export class SplineGenerator {
this.segment.p0.y = pPrev.y;
this.segment.p0.pressure = pPrev.pressure;
this.segment.p0.width = pPrev.width;
+ this.segment.p0.tiltX = pPrev.tiltX ?? 0;
+ this.segment.p0.tiltY = pPrev.tiltY ?? 0;
+ this.segment.p0.twist = pPrev.twist ?? 0;
this.segment.p3.x = pCurr.x;
this.segment.p3.y = pCurr.y;
this.segment.p3.pressure = pCurr.pressure;
this.segment.p3.width = pCurr.width;
+ this.segment.p3.tiltX = pCurr.tiltX ?? 0;
+ this.segment.p3.tiltY = pCurr.tiltY ?? 0;
+ this.segment.p3.twist = pCurr.twist ?? 0;
if (chordLen < 1e-4) {
this.segment.c1.x = pPrev.x;
@@ -213,6 +230,9 @@ export class SplineGenerator {
this.segment.p0.y = p1.y;
this.segment.p0.pressure = p1.pressure;
this.segment.p0.width = p1.width;
+ this.segment.p0.tiltX = p1.tiltX ?? 0;
+ this.segment.p0.tiltY = p1.tiltY ?? 0;
+ this.segment.p0.twist = p1.twist ?? 0;
this.segment.c1.x = p1.x + dx1;
this.segment.c1.y = p1.y + dy1;
@@ -228,6 +248,9 @@ export class SplineGenerator {
this.segment.p3.y = p2.y;
this.segment.p3.pressure = p2.pressure;
this.segment.p3.width = p2.width;
+ this.segment.p3.tiltX = p2.tiltX ?? 0;
+ this.segment.p3.tiltY = p2.tiltY ?? 0;
+ this.segment.p3.twist = p2.twist ?? 0;
// Cache tangent at P2 for subsequent Hermite provisional segment stitching
if (Math.hypot(dx2, dy2) > 1e-4) {
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index 14617b7..8c41d29 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -1,14 +1,16 @@
/**
* 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.
+ * Decouples pointer event handling from React, ingests coalesced events into a flat
+ * Float64Array ring buffer, manages 1-Euro + Corner-Snapping stabilization,
+ * provisional Hermite + Catmull-Rom stitching, speculative predictive tip overlay,
+ * and dirty-rect calculation for pointerup baking.
*/
-import { InputStabilizer } from './InputStabilizer';
+import { InputStabilizer, StabilizedSample } from './InputStabilizer';
import { SplineGenerator, SplinePoint, CubicBezierSegment } from './SplineGenerator';
import { TaperEngine } from './TaperEngine';
+import type { DirtyRect } from '../types/editor';
export interface ViewportTransform {
panX: number;
@@ -17,6 +19,8 @@ export interface ViewportTransform {
rotation: number;
canvasWidth: number;
canvasHeight: number;
+ flipX?: boolean;
+ flipY?: boolean;
}
export interface DirtyRectBounds {
@@ -34,26 +38,156 @@ export type SegmentRenderCallback = (
isProvisional: boolean
) => void;
+export interface StrokeSamplePoint {
+ x: number;
+ y: number;
+ pressure: number;
+ width: number;
+ tiltX: number;
+ tiltY: number;
+ twist: number;
+ timestamp: number;
+ isCorner: boolean;
+ vx: number;
+ vy: number;
+ pointerType: string;
+}
+
+export interface DrainOptions {
+ /** Maps stabilized raw sample into final pressure & width without heap allocation. */
+ resolvePoint?: (
+ rawX: number,
+ rawY: number,
+ rawPressure: number,
+ stabilizedPressure: number,
+ pointerType: string,
+ vx: number,
+ vy: number,
+ dtMs: number,
+ out: StrokeSamplePoint
+ ) => void;
+ /** Extra canvas-space padding factor for dirty rect expansion (blur/scatter). */
+ dirtyPadExtra?: number;
+ /** Invoked once per stabilized point (before segment emission). */
+ onPoint?: (pt: Readonly<StrokeSamplePoint>) => void;
+ /** Invoked for each sealed cubic Bézier segment (Catmull-Rom or sharp corner). */
+ onSegment?: (seg: CubicBezierSegment, isCorner: boolean) => void;
+}
+
+export interface FinalizeStrokeOptions {
+ enableFlickTaper?: boolean;
+ dirtyPadExtra?: number;
+ onPoint?: (pt: Readonly<StrokeSamplePoint>) => void;
+ onSegment?: (seg: CubicBezierSegment, isCorner: boolean) => void;
+}
+
+export const POINTER_TYPE_PEN = 0;
+export const POINTER_TYPE_MOUSE = 1;
+export const POINTER_TYPE_TOUCH = 2;
+
+export function encodePointerType(pointerType: string | undefined): number {
+ if (pointerType === 'mouse') return POINTER_TYPE_MOUSE;
+ if (pointerType === 'touch') return POINTER_TYPE_TOUCH;
+ return POINTER_TYPE_PEN;
+}
+
+export function decodePointerType(code: number): string {
+ if (code === POINTER_TYPE_MOUSE) return 'mouse';
+ if (code === POINTER_TYPE_TOUCH) return 'touch';
+ return 'pen';
+}
+
+/**
+ * Computes the clamped integer pixel DirtyRect for pointerup baking onto the base layer
+ * and SparseTileGrid. Returns null if bounds are empty or invalid.
+ */
+export function computeClampedBakeDirtyRect(
+ dirty: DirtyRectBounds | null | undefined,
+ canvasWidth: number,
+ canvasHeight: number,
+ brushSize: number,
+ wetEdge: number = 0,
+ wetEdgeRadius: number = 3.0
+): DirtyRect | null {
+ if (
+ !dirty ||
+ !Number.isFinite(dirty.minX) ||
+ !Number.isFinite(dirty.minY) ||
+ !Number.isFinite(dirty.maxX) ||
+ !Number.isFinite(dirty.maxY) ||
+ dirty.maxX < dirty.minX ||
+ dirty.maxY < dirty.minY ||
+ canvasWidth <= 0 ||
+ canvasHeight <= 0
+ ) {
+ return null;
+ }
+
+ const wetMargin = wetEdge > 0.01 ? Math.ceil(wetEdgeRadius * 2 + 8) : 0;
+ const pad = Math.ceil(Math.max(32, (brushSize || 10) * 1.5)) + wetMargin;
+
+ const sx = Math.max(0, Math.floor(dirty.minX - pad));
+ const sy = Math.max(0, Math.floor(dirty.minY - pad));
+ const maxX = Math.min(canvasWidth, Math.ceil(dirty.maxX + pad));
+ const maxY = Math.min(canvasHeight, Math.ceil(dirty.maxY + pad));
+ const dw = maxX - sx;
+ const dh = maxY - sy;
+
+ if (dw <= 0 || dh <= 0) {
+ return null;
+ }
+
+ return { x: sx, y: sy, width: dw, height: dh };
+}
+
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;
+ // Stride 8: [rawX, rawY, pressure, tiltX, tiltY, twist, timestamp, pointerTypeCode]
+ public static readonly BUFFER_CAPACITY = 2048;
+ private static readonly STRIDE = 8;
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 };
+ // Pre-allocated knot cache for zero-allocation spline stitching
+ private knotP0: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
+ private knotP1: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
+ private knotP2: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
+ private knotP3: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
private knotCount: number = 0;
+ // Pre-allocated scratch objects for zero-GC hot paths
+ private scratchCoord: { x: number; y: number } = { x: 0, y: 0 };
+ private scratchSample: StrokeSamplePoint = {
+ x: 0,
+ y: 0,
+ pressure: 0,
+ width: 1,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ timestamp: 0,
+ isCorner: false,
+ vx: 0,
+ vy: 0,
+ pointerType: 'pen',
+ };
+ private scratchPredPt: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
+ private scratchPrevPredPt: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
+
+ // Raw velocity tracker when stabilizerLevel === 0 (bypassed XY lag)
+ private lastRawX: number = 0;
+ private lastRawY: number = 0;
+ private lastRawTime: number = 0;
+ private lastVx: number = 0;
+ private lastVy: number = 0;
+ private hasLastRaw: boolean = false;
+ private stabilizerLevel: number = 0;
+
// Dirty rect tracking (integer bounds in canvas space)
public dirtyRect: DirtyRectBounds = {
minX: Infinity,
@@ -67,7 +201,7 @@ export class StrokePipeline {
private baseBrushSize: number = 10;
private strokeColor: string = '#000000';
- // Canvases
+ // Canvases (optional standalone mode)
private scratchCtx: CanvasRenderingContext2D | null = null;
private predictedCtx: CanvasRenderingContext2D | null = null;
private customRenderer: SegmentRenderCallback | null = null;
@@ -79,7 +213,20 @@ export class StrokePipeline {
}
public setStabilizerLevel(level: number): void {
- this.stabilizer.setStabilizerLevel(level);
+ this.stabilizerLevel = Math.min(50, Math.max(0, level));
+ this.stabilizer.setStabilizerLevel(this.stabilizerLevel);
+ }
+
+ public getStabilizerLevel(): number {
+ return this.stabilizerLevel;
+ }
+
+ public setZoomScale(zoom: number): void {
+ this.stabilizer.setZoomScale(zoom);
+ }
+
+ public setSharpCorners(enabled: boolean): void {
+ this.stabilizer.setSharpCorners(enabled);
}
public setBrushParameters(size: number, color: string): void {
@@ -87,9 +234,41 @@ export class StrokePipeline {
this.strokeColor = color;
}
+ public getTaperEngine(): TaperEngine {
+ return this.taperEngine;
+ }
+
+ public getStabilizer(): InputStabilizer {
+ return this.stabilizer;
+ }
+
+ public getSplineGenerator(): SplineGenerator {
+ return this.splineGen;
+ }
+
+ public getPendingCount(): number {
+ return this.headIndex - this.tailIndex;
+ }
+
+ public getKnotCount(): number {
+ return this.knotCount;
+ }
+
+ public getLastVelocity(): { vx: number; vy: number; speed: number } {
+ if (this.stabilizerLevel > 0) {
+ const s: Readonly<StabilizedSample> = this.stabilizer.getLastSample();
+ return { vx: s.vx, vy: s.vy, speed: s.speed };
+ }
+ return {
+ vx: this.lastVx,
+ vy: this.lastVy,
+ speed: Math.hypot(this.lastVx, this.lastVy),
+ };
+ }
+
public bindContexts(
- scratch: CanvasRenderingContext2D,
- predicted: CanvasRenderingContext2D
+ scratch: CanvasRenderingContext2D | null,
+ predicted: CanvasRenderingContext2D | null
): void {
this.scratchCtx = scratch;
this.predictedCtx = predicted;
@@ -102,16 +281,402 @@ export class StrokePipeline {
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);
+ public expandDirtyRect(x: number, y: number, radius: number): void {
+ const pad = Math.ceil(Math.max(0, radius) + 4);
+ const x0 = Math.max(0, Math.floor(x - pad));
+ const y0 = Math.max(0, Math.floor(y - pad));
+ const x1 = Math.ceil(x + pad);
+ const y1 = Math.ceil(y + pad);
+ if (x0 < this.dirtyRect.minX) this.dirtyRect.minX = x0;
+ if (y0 < this.dirtyRect.minY) this.dirtyRect.minY = y0;
+ if (x1 > this.dirtyRect.maxX) this.dirtyRect.maxX = x1;
+ if (y1 > this.dirtyRect.maxY) this.dirtyRect.maxY = y1;
+ }
+
+ public expandDirtyRectBounds(minX: number, minY: number, maxX: number, maxY: number): void {
+ const x0 = Math.max(0, Math.floor(minX));
+ const y0 = Math.max(0, Math.floor(minY));
+ const x1 = Math.ceil(maxX);
+ const y1 = Math.ceil(maxY);
+ if (x0 < this.dirtyRect.minX) this.dirtyRect.minX = x0;
+ if (y0 < this.dirtyRect.minY) this.dirtyRect.minY = y0;
+ if (x1 > this.dirtyRect.maxX) this.dirtyRect.maxX = x1;
+ if (y1 > this.dirtyRect.maxY) this.dirtyRect.maxY = y1;
+ }
+
+ /**
+ * Resets all pipeline state for a new stroke (used by both standalone and hook-driven modes).
+ */
+ public beginStroke(config?: {
+ stabilizerLevel?: number;
+ zoom?: number;
+ sharpCorners?: boolean;
+ brushSize?: number;
+ color?: string;
+ pointerId?: number;
+ }): void {
+ this.stabilizer.reset();
+ this.splineGen.reset();
+ this.taperEngine.reset();
+ this.resetDirtyRect();
+
+ if (config?.stabilizerLevel !== undefined) {
+ this.setStabilizerLevel(config.stabilizerLevel);
+ }
+ if (config?.zoom !== undefined) {
+ this.stabilizer.setZoomScale(config.zoom);
+ }
+ if (config?.sharpCorners !== undefined) {
+ this.stabilizer.setSharpCorners(config.sharpCorners);
+ }
+ if (config?.brushSize !== undefined || config?.color !== undefined) {
+ this.setBrushParameters(config.brushSize ?? this.baseBrushSize, config.color ?? this.strokeColor);
+ }
+
+ this.headIndex = 0;
+ this.tailIndex = 0;
+ this.knotCount = 0;
+ this.hasLastRaw = false;
+ this.lastVx = 0;
+ this.lastVy = 0;
+ this.isDrawing = true;
+ this.activePointerId = config?.pointerId ?? -1;
+ }
+
+ /**
+ * Aborts active stroke and clears transient buffers.
+ */
+ public abortStroke(): void {
+ this.headIndex = 0;
+ this.tailIndex = 0;
+ this.knotCount = 0;
+ this.hasLastRaw = false;
+ this.lastVx = 0;
+ this.lastVy = 0;
+ this.isDrawing = false;
+ this.activePointerId = -1;
+ this.resetDirtyRect();
+ }
+
+ /**
+ * Seeds an initial or pre-computed knot directly into the spline window (e.g. pointerdown or Shift+Click line).
+ */
+ public seedKnot(
+ x: number,
+ y: number,
+ pressure: number,
+ width: number,
+ tiltX: number = 0,
+ tiltY: number = 0,
+ twist: number = 0,
+ timestamp: number = 0,
+ padExtra: number = 0
+ ): void {
+ if (this.knotCount === 0) {
+ this.copyIntoKnot(this.knotP0, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ this.copyIntoKnot(this.knotP1, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ this.knotCount = 1;
+ } else if (this.knotCount === 1) {
+ this.copyIntoKnot(this.knotP2, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ this.knotCount = 2;
+ } else {
+ this.copyKnot(this.knotP0, this.knotP1);
+ this.copyKnot(this.knotP1, this.knotP2);
+ this.copyIntoKnot(this.knotP2, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ this.knotCount++;
+ }
+
+ if (this.stabilizerLevel > 0) {
+ this.stabilizer.process(x, y, pressure, timestamp);
+ }
+ this.lastRawX = x;
+ this.lastRawY = y;
+ this.lastRawTime = timestamp;
+ this.hasLastRaw = true;
+ this.expandDirtyRect(x, y, width + padExtra);
+ }
+
+ /**
+ * Zero-allocation write of a single raw pointer sample into the Float64Array ring buffer.
+ * If the buffer is full (2048 unread samples), advances tailIndex to drop the oldest unread sample safely.
+ */
+ public enqueueSample(
+ x: number,
+ y: number,
+ pressure: number,
+ tiltX: number = 0,
+ tiltY: number = 0,
+ twist: number = 0,
+ timestamp: number = 0,
+ pointerTypeCode: number = POINTER_TYPE_PEN
+ ): void {
+ if (this.headIndex - this.tailIndex >= StrokePipeline.BUFFER_CAPACITY) {
+ this.tailIndex = this.headIndex - StrokePipeline.BUFFER_CAPACITY + 1;
+ }
+ const offset = (this.headIndex % StrokePipeline.BUFFER_CAPACITY) * StrokePipeline.STRIDE;
+ this.inputRingBuffer[offset] = x;
+ this.inputRingBuffer[offset + 1] = y;
+ this.inputRingBuffer[offset + 2] = pressure;
+ this.inputRingBuffer[offset + 3] = tiltX;
+ this.inputRingBuffer[offset + 4] = tiltY;
+ this.inputRingBuffer[offset + 5] = twist;
+ this.inputRingBuffer[offset + 6] = timestamp;
+ this.inputRingBuffer[offset + 7] = pointerTypeCode;
+ this.headIndex++;
+ }
+
+ /**
+ * Drains all buffered samples from the Float64Array ring buffer, running InputStabilizer,
+ * TaperEngine, and SplineGenerator with zero per-sample object allocation.
+ * Returns the number of drained samples.
+ */
+ public drain(options?: DrainOptions): number {
+ let drained = 0;
+ const padExtra = options?.dirtyPadExtra ?? 0;
+
+ 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 tiltX = this.inputRingBuffer[offset + 3];
+ const tiltY = this.inputRingBuffer[offset + 4];
+ const twist = this.inputRingBuffer[offset + 5];
+ const timeMs = this.inputRingBuffer[offset + 6];
+ const pTypeCode = this.inputRingBuffer[offset + 7];
+ this.tailIndex++;
+ drained++;
+
+ const dtMs = this.hasLastRaw ? Math.max(1, timeMs - this.lastRawTime) : 1;
+ const pointerType = decodePointerType(pTypeCode);
+
+ let outX: number;
+ let outY: number;
+ let stabPressure: number;
+ let vx: number;
+ let vy: number;
+ let isCorner: boolean;
+
+ if (this.stabilizerLevel > 0) {
+ const stabilized = this.stabilizer.process(rawX, rawY, rawP, timeMs);
+ outX = stabilized.x;
+ outY = stabilized.y;
+ stabPressure = stabilized.pressure;
+ vx = stabilized.vx;
+ vy = stabilized.vy;
+ isCorner = stabilized.isCorner;
+ } else {
+ outX = rawX;
+ outY = rawY;
+ stabPressure = rawP;
+ if (this.hasLastRaw) {
+ vx = (rawX - this.lastRawX) / dtMs;
+ vy = (rawY - this.lastRawY) / dtMs;
+ } else {
+ vx = 0;
+ vy = 0;
+ }
+ isCorner = false;
+ }
+
+ this.lastRawX = outX;
+ this.lastRawY = outY;
+ this.lastRawTime = timeMs;
+ this.lastVx = vx;
+ this.lastVy = vy;
+ this.hasLastRaw = true;
+
+ const sample = this.scratchSample;
+ sample.x = outX;
+ sample.y = outY;
+ sample.tiltX = tiltX;
+ sample.tiltY = tiltY;
+ sample.twist = twist;
+ sample.timestamp = timeMs;
+ sample.isCorner = isCorner;
+ sample.vx = vx;
+ sample.vy = vy;
+ sample.pointerType = pointerType;
+
+ if (options?.resolvePoint) {
+ options.resolvePoint(rawX, rawY, rawP, stabPressure, pointerType, vx, vy, dtMs, sample);
+ } else {
+ const mappedPressure = this.taperEngine.mapPressure(stabPressure);
+ const smoothPressure = this.taperEngine.smoothPressure(mappedPressure);
+ sample.pressure = smoothPressure;
+ sample.width = Math.max(0.5, this.baseBrushSize * smoothPressure);
+ }
+
+ this.expandDirtyRect(sample.x, sample.y, sample.width + padExtra);
+ options?.onPoint?.(sample);
+
+ this.advanceSplineKnot(
+ sample.x,
+ sample.y,
+ sample.pressure,
+ sample.width,
+ sample.tiltX,
+ sample.tiltY,
+ sample.twist,
+ sample.timestamp,
+ sample.vx,
+ sample.vy,
+ sample.isCorner,
+ padExtra,
+ options?.onSegment
+ );
+ }
+
+ return drained;
+ }
+
+ /**
+ * Builds strictly ephemeral provisional + forward-predicted Bézier segments without mutating
+ * committed knots, stabilizer filter state, or dirtyRect.
+ */
+ public buildPredictedSegments(
+ predictedDocCoords: ReadonlyArray<{ x: number; y: number; pressure?: number }> | null,
+ maxPredDist: number,
+ onSegment: (seg: CubicBezierSegment) => void
+ ): boolean {
+ if (this.knotCount < 2) return false;
+
+ const vel = this.getLastVelocity();
+
+ // 1. Provisional unsealed bridge: knotP1 -> knotP2 matching Catmull-Rom geometry
+ const bridgeSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP2
+ );
+ onSegment(bridgeSeg);
+
+ // 2. Speculative lookahead strictly from hardware getPredictedEvents()
+ if (predictedDocCoords && predictedDocCoords.length > 0) {
+ this.copyKnot(this.scratchPrevPredPt, this.knotP2);
+ for (let i = 0; i < predictedDocCoords.length; i++) {
+ const raw = predictedDocCoords[i];
+ const dx = raw.x - this.scratchPrevPredPt.x;
+ const dy = raw.y - this.scratchPrevPredPt.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist < 0.5 || dist > maxPredDist * 2.5) break;
+ const clampedScale = dist > maxPredDist ? maxPredDist / dist : 1.0;
+
+ this.scratchPredPt.x = this.scratchPrevPredPt.x + dx * clampedScale;
+ this.scratchPredPt.y = this.scratchPrevPredPt.y + dy * clampedScale;
+ this.scratchPredPt.pressure = this.scratchPrevPredPt.pressure * 0.9;
+ this.scratchPredPt.width = Math.max(0.5, this.scratchPrevPredPt.width * 0.9);
+ this.scratchPredPt.tiltX = this.knotP2.tiltX;
+ this.scratchPredPt.tiltY = this.knotP2.tiltY;
+ this.scratchPredPt.twist = this.knotP2.twist;
+
+ const predSeg = this.splineGen.generateProvisionalSegment(
+ this.scratchPrevPredPt,
+ this.scratchPredPt,
+ vel.vx,
+ vel.vy
+ );
+ onSegment(predSeg);
+ this.copyKnot(this.scratchPrevPredPt, this.scratchPredPt);
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Finalizes the stroke on pointerup: seals the unsealed tail segment (knotP1 -> knotP2)
+ * and optionally computes ballistic exit flick taper via TaperEngine.
+ */
+ public finalizeStroke(endTimestampMs: number, options?: FinalizeStrokeOptions): DirtyRectBounds {
+ const padExtra = options?.dirtyPadExtra ?? 0;
+
+ if (this.knotCount >= 2) {
+ // Seal the final unsealed interior segment knotP1 -> knotP2
+ const finalSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP2
+ );
+ this.expandSegmentDirtyRect(finalSeg, padExtra);
+ if (options?.onSegment) {
+ options.onSegment(finalSeg, false);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, finalSeg, false);
+ }
+
+ if (options?.enableFlickTaper) {
+ const vel = this.getLastVelocity();
+ const flick = this.taperEngine.computeFlickTaper(
+ this.knotP2.x,
+ this.knotP2.y,
+ this.knotP2.width,
+ this.knotP2.pressure,
+ vel.vx,
+ vel.vy,
+ endTimestampMs
+ );
+ if (flick.count > 0) {
+ for (let i = 0; i < flick.count; i++) {
+ const fp = flick.points[i];
+ const sample = this.scratchSample;
+ sample.x = fp.x;
+ sample.y = fp.y;
+ sample.pressure = fp.pressure;
+ sample.width = fp.width;
+ sample.tiltX = this.knotP2.tiltX ?? 0;
+ sample.tiltY = this.knotP2.tiltY ?? 0;
+ sample.twist = this.knotP2.twist ?? 0;
+ sample.timestamp = fp.timestamp;
+ sample.isCorner = false;
+ sample.vx = vel.vx;
+ sample.vy = vel.vy;
+ sample.pointerType = 'pen';
+
+ this.expandDirtyRect(fp.x, fp.y, fp.width + padExtra);
+ options.onPoint?.(sample);
+ this.advanceSplineKnot(
+ fp.x,
+ fp.y,
+ fp.pressure,
+ fp.width,
+ sample.tiltX,
+ sample.tiltY,
+ sample.twist,
+ fp.timestamp,
+ vel.vx,
+ vel.vy,
+ false,
+ padExtra,
+ options.onSegment
+ );
+ }
+ // Seal final flick segment
+ const flickTailSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP2
+ );
+ this.expandSegmentDirtyRect(flickTailSeg, padExtra);
+ if (options.onSegment) {
+ options.onSegment(flickTailSeg, false);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, flickTailSeg, false);
+ }
+ }
+ }
+ }
+
+ this.isDrawing = false;
+ this.activePointerId = -1;
+ return this.dirtyRect;
}
/**
- * Pointer Down: resets filters and anchors stroke start without DOM overhead.
+ * Pointer Down (standalone canvas mode): resets filters and anchors stroke start without DOM overhead.
*/
public onPointerDown(
e: PointerEvent,
@@ -123,16 +688,7 @@ export class StrokePipeline {
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;
+ this.beginStroke({ pointerId: e.pointerId });
// Ingest coalesced start points
this.ingestPointerEvent(e, view);
@@ -140,8 +696,7 @@ export class StrokePipeline {
}
/**
- * Pointer Move: Extracts full hardware coalesced event stack (133 - 240+ Hz).
- * Zero React state updates or DOM allocations.
+ * Pointer Move (standalone canvas mode): extracts coalesced event stack into ring buffer.
*/
public onPointerMove(e: PointerEvent, view: ViewportTransform): void {
if (!this.isDrawing || e.pointerId !== this.activePointerId) return;
@@ -154,7 +709,7 @@ export class StrokePipeline {
}
/**
- * Pointer Up: Attenuates flick taper and prepares dirty rect for layer bake.
+ * Pointer Up (standalone canvas mode): attenuates flick taper and returns dirty rect for layer bake.
*/
public onPointerUp(
e: PointerEvent,
@@ -177,35 +732,8 @@ export class StrokePipeline {
this.ingestPointerEvent(e, view);
this.flush();
- // Evaluate exit flick taper using cached velocity from last processed sample (do not re-process knotP2)
- if (this.knotCount >= 2 && this.scratchCtx) {
- const exitSample = this.stabilizer.getLastSample();
- 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);
- }
- } else {
- // Seal the final segment knotP1 -> knotP2 onto scratchCtx
- const finalSeg = this.splineGen.generateCatmullRomSegment(
- this.knotP0,
- this.knotP1,
- this.knotP2,
- this.knotP2
- );
- this.renderSegment(this.scratchCtx, finalSeg, false);
- }
- }
+ // Seal final segment and evaluate exit flick taper
+ this.finalizeStroke(e.timeStamp, { enableFlickTaper: true });
// Clear prediction overlay canvas
if (this.predictedCtx) {
@@ -213,52 +741,51 @@ export class StrokePipeline {
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.
+ * Ingests native coalesced events into flat typed array ring buffer (zero per-event allocation).
*/
private ingestPointerEvent(e: PointerEvent, view: ViewportTransform): void {
- let events: PointerEvent[] | readonly PointerEvent[];
+ let coalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
if (typeof e.getCoalescedEvents === 'function') {
- const coalesced = e.getCoalescedEvents();
- events = coalesced && coalesced.length > 0 ? coalesced : [e];
- } else {
- events = [e];
+ const list = e.getCoalescedEvents();
+ if (list && list.length > 0) coalesced = list;
}
- for (let i = 0; i < events.length; i++) {
- const ev = events[i];
- const coords = this.screenToCanvas(ev.clientX, ev.clientY, view);
+ const len = coalesced ? coalesced.length : 1;
+ for (let i = 0; i < len; i++) {
+ const ev = coalesced ? coalesced[i] : e;
+ this.screenToCanvasInto(ev.clientX, ev.clientY, view, this.scratchCoord);
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++;
+ this.enqueueSample(
+ this.scratchCoord.x,
+ this.scratchCoord.y,
+ pressure,
+ ev.tiltX || 0,
+ ev.tiltY || 0,
+ ev.twist || 0,
+ ev.timeStamp,
+ encodePointerType(ev.pointerType)
+ );
}
}
/**
- * Screen space to canvas space coordinate transformation matrix.
+ * Screen space to canvas space coordinate transformation matrix (zero allocation).
*/
- private screenToCanvas(
+ private screenToCanvasInto(
screenX: number,
screenY: number,
- view: ViewportTransform
- ): { x: number; y: number } {
+ view: ViewportTransform,
+ out: { x: number; y: number }
+ ): void {
const cx = view.canvasWidth / 2;
const cy = view.canvasHeight / 2;
@@ -269,117 +796,152 @@ export class StrokePipeline {
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,
- };
+ const fx = view.flipX ? -1 : 1;
+ const fy = view.flipY ? -1 : 1;
+
+ out.x = (relX * cos - relY * sin) * fx + cx;
+ out.y = (relX * sin + relY * cos) * fy + cy;
}
/**
- * Flushes ring buffer, runs corner-snapping stabilizer, and draws splines.
+ * Standalone flush: drains ring buffer, runs stabilizer & splines onto bound scratchCtx.
*/
private flush(): void {
if (!this.scratchCtx) return;
+ const scratch = this.scratchCtx;
+ this.drain({
+ onSegment: (seg) => {
+ this.renderSegment(scratch, seg, false);
+ },
+ });
+ }
- 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++;
+ private copyIntoKnot(
+ dst: SplinePoint,
+ x: number,
+ y: number,
+ pressure: number,
+ width: number,
+ tiltX: number,
+ tiltY: number,
+ twist: number,
+ timestamp: number
+ ): void {
+ dst.x = x;
+ dst.y = y;
+ dst.pressure = pressure;
+ dst.width = width;
+ dst.tiltX = tiltX;
+ dst.tiltY = tiltY;
+ dst.twist = twist;
+ dst.timestamp = timestamp;
+ }
- // 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
- );
- }
+ private copyKnot(dst: SplinePoint, src: SplinePoint): void {
+ dst.x = src.x;
+ dst.y = src.y;
+ dst.pressure = src.pressure;
+ dst.width = src.width;
+ dst.tiltX = src.tiltX;
+ dst.tiltY = src.tiltY;
+ dst.twist = src.twist;
+ dst.timestamp = src.timestamp;
+ }
+
+ private expandSegmentDirtyRect(seg: CubicBezierSegment, padExtra: number = 0): void {
+ this.expandDirtyRect(seg.p0.x, seg.p0.y, seg.p0.width + padExtra);
+ this.expandDirtyRect(seg.c1.x, seg.c1.y, seg.c1.width + padExtra);
+ this.expandDirtyRect(seg.c2.x, seg.c2.y, seg.c2.width + padExtra);
+ this.expandDirtyRect(seg.p3.x, seg.p3.y, seg.p3.width + padExtra);
}
/**
* Zero-Delay Spline Pipeline with Adaptive Corner Snapping:
* When corner is detected (DeltaTheta > 45 deg), immediately commits sharp knot.
*/
- private processStabilizedPoint(
+ private advanceSplineKnot(
x: number,
y: number,
pressure: number,
width: number,
+ tiltX: number,
+ tiltY: number,
+ twist: number,
+ timestamp: number,
vx: number,
vy: number,
- isCorner: boolean
+ isCorner: boolean,
+ padExtra: number,
+ onSegment?: (seg: CubicBezierSegment, isCorner: boolean) => void
): void {
- if (!this.scratchCtx) return;
-
if (isCorner && this.knotCount >= 1) {
- const cornerPt: SplinePoint = { x, y, pressure, width };
- const prevKnot = this.knotCount >= 2 ? this.knotP2 : this.knotP1;
- const cornerSeg = this.splineGen.generateCornerSegment(prevKnot, 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.copyIntoKnot(this.knotP3, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+
+ if (this.knotCount >= 2) {
+ // First seal the pending interior segment P1 -> P2 before snapping into the sharp corner P2 -> P3
+ // (Matches renderCompleteStroke's centripetalCatmullRomToBezier so zero corner gaps occur!)
+ const preCornerSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP3
+ );
+ this.expandSegmentDirtyRect(preCornerSeg, padExtra);
+ if (onSegment) {
+ onSegment(preCornerSeg, false);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, preCornerSeg, false);
+ }
+
+ // Now seal P2 -> corner apex P3 with sharp corner endpoint
+ const toApexSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP1,
+ this.knotP2,
+ this.knotP3,
+ this.knotP3
+ );
+ this.expandSegmentDirtyRect(toApexSeg, padExtra);
+ if (onSegment) {
+ onSegment(toApexSeg, true);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, toApexSeg, false);
+ }
+ } else {
+ const cornerSeg = this.splineGen.generateCornerSegment(this.knotP1, this.knotP3);
+ this.expandSegmentDirtyRect(cornerSeg, padExtra);
+ if (onSegment) {
+ onSegment(cornerSeg, true);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, cornerSeg, false);
+ }
+ }
+ this.splineGen.commitCornerKnot(this.knotP3);
+ this.copyKnot(this.knotP0, this.knotP3);
+ this.copyKnot(this.knotP1, this.knotP3);
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.copyIntoKnot(this.knotP0, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ this.copyIntoKnot(this.knotP1, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
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);
- const provTarget = this.predictedCtx || this.scratchCtx;
- this.renderSegment(provTarget, seg, true);
+ this.copyIntoKnot(this.knotP2, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
+ if (!onSegment && this.predictedCtx) {
+ const seg = this.splineGen.generateProvisionalSegment(this.knotP1, this.knotP2, vx, vy);
+ this.renderSegment(this.predictedCtx, 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;
+ // Third+ knot: [P0, P1, P2, P3] -> seal P1 -> P2
+ this.copyIntoKnot(this.knotP3, x, y, pressure, width, tiltX, tiltY, twist, timestamp);
const sealedSeg = this.splineGen.generateCatmullRomSegment(
this.knotP0,
@@ -387,36 +949,28 @@ export class StrokePipeline {
this.knotP2,
this.knotP3
);
- this.renderSegment(this.scratchCtx, sealedSeg, false);
+ this.expandSegmentDirtyRect(sealedSeg, padExtra);
+ if (onSegment) {
+ onSegment(sealedSeg, false);
+ } else if (this.scratchCtx) {
+ this.renderSegment(this.scratchCtx, sealedSeg, false);
+ }
- if (this.predictedCtx) {
+ if (!onSegment && this.predictedCtx) {
const nextProvSeg = this.splineGen.generateProvisionalSegment(this.knotP2, this.knotP3, vx, vy);
this.renderSegment(this.predictedCtx, 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;
-
+ // Shift window (zero allocation)
+ this.copyKnot(this.knotP0, this.knotP1);
+ this.copyKnot(this.knotP1, this.knotP2);
+ this.copyKnot(this.knotP2, this.knotP3);
this.knotCount++;
}
/**
- * Speculative Forward Stroke Prediction:
+ * Speculative Forward Stroke Prediction (standalone mode):
* 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;
@@ -424,37 +978,37 @@ export class StrokePipeline {
this.predictedCtx.resetTransform();
this.predictedCtx.clearRect(0, 0, view.canvasWidth, view.canvasHeight);
- let predEvents: PointerEvent[] | readonly PointerEvent[] = [];
+ let predEvents: PointerEvent[] | readonly PointerEvent[] | null = null;
if (typeof e.getPredictedEvents === 'function') {
const pred = e.getPredictedEvents();
if (pred && pred.length > 0) predEvents = pred;
}
- if (predEvents.length > 0) {
- let prevPt = this.knotP2;
+ if (predEvents && predEvents.length > 0) {
+ this.copyKnot(this.scratchPrevPredPt, this.knotP2);
for (let i = 0; i < predEvents.length; i++) {
const ev = predEvents[i];
- const pt = this.screenToCanvas(ev.clientX, ev.clientY, view);
+ this.screenToCanvasInto(ev.clientX, ev.clientY, view, this.scratchCoord);
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 };
+ this.scratchPredPt.x = this.scratchCoord.x;
+ this.scratchPredPt.y = this.scratchCoord.y;
+ this.scratchPredPt.pressure = pVal;
+ this.scratchPredPt.width = w;
- const seg = this.splineGen.generateProvisionalSegment(prevPt, curPt, 0, 0);
+ const seg = this.splineGen.generateProvisionalSegment(this.scratchPrevPredPt, this.scratchPredPt, 0, 0);
this.renderSegment(this.predictedCtx, seg, true);
- prevPt = curPt;
+ this.copyKnot(this.scratchPrevPredPt, this.scratchPredPt);
}
} else {
- // Hermite extrapolation forward along velocity vector without mutating stabilizer filter state
- const sample = this.stabilizer.getLastSample();
- if (sample.speed > 0.05) {
+ const vel = this.getLastVelocity();
+ if (vel.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.scratchPredPt.x = this.knotP2.x + vel.vx * dt;
+ this.scratchPredPt.y = this.knotP2.y + vel.vy * dt;
+ this.scratchPredPt.pressure = this.knotP2.pressure;
+ this.scratchPredPt.width = this.knotP2.width;
+ const seg = this.splineGen.generateProvisionalSegment(this.knotP2, this.scratchPredPt, vel.vx, vel.vy);
this.renderSegment(this.predictedCtx, seg, true);
}
}
@@ -483,10 +1037,7 @@ export class StrokePipeline {
}
if (ctx === this.scratchCtx) {
- 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);
+ this.expandSegmentDirtyRect(seg);
}
}
}
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index d974e36..de453e2 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -28,10 +28,11 @@ import {
import {
calculateStrokeWidth,
drawSmoothCubicBezierSegment,
- catmullRomToBezier,
drawDot,
screenToCanvas,
+ screenToCanvasInto,
getCanvasToViewportMatrix,
+ getVisibleCanvasBounds,
createCanvasThumbnail,
formatTime,
get2DContext,
@@ -39,8 +40,13 @@ import {
renderCompleteStroke,
applyParametricTaper,
} from '../utils/canvasUtils';
-import { InputStabilizer } from '../engine/InputStabilizer';
-import { TaperEngine } from '../engine/TaperEngine';
+import {
+ StrokePipeline,
+ computeClampedBakeDirtyRect,
+ encodePointerType,
+} from '../engine/StrokePipeline';
+import { CubicBezierSegment } from '../engine/SplineGenerator';
+import { CanvasNavigationHandle } from './useCanvasNavigation';
import { applyCspWatercolorEdge } from '../engine/CspBrushEngine';
import { enforceColorMode, binarizeImageDataBuffer } from '../utils/colorUtils';
import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
@@ -49,7 +55,12 @@ import {
drawTexturedDot,
TexturedBrushOptions,
RadialMixingOptions,
+ canUseWebGlForTexturedBrush,
+ canUseWebGlForRadialBrush,
+ flushTexturedGpuDabs,
+ flushRadialGpuDabs,
} from '../utils/stampEngine';
+import { GpuDab } from '../utils/webglBrushEngine';
import { PaintReservoir, LayerPixelSampler } from '../utils/colorMixingEngine';
import { applyLayerEffects } from '../utils/layerEffectsEngine';
import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
@@ -152,6 +163,9 @@ interface UseCanvasDrawingProps {
pan: { x: number; y: number };
zoom: number;
rotation: number;
+ flipX?: boolean;
+ flipY?: boolean;
+ navigation?: CanvasNavigationHandle;
activeLayerId: string;
activeLayerLocked?: boolean;
activeLayerVisible?: boolean;
@@ -184,6 +198,9 @@ export function useCanvasDrawing({
pan,
zoom,
rotation,
+ flipX = false,
+ flipY = false,
+ navigation,
activeLayerId,
activeSessionId,
activeLayerLocked = false,
@@ -248,9 +265,17 @@ export function useCanvasDrawing({
const activePointerIdRef = useRef<number | null>(null);
// Keep navigation transforms and editor settings updated in synchronous refs
- const panRef = useRef(pan);
- const zoomRef = useRef(zoom);
- const rotationRef = useRef(rotation);
+ // When `navigation` handle is provided, read directly from its live refs so strokes hit exact document pixels even before debounced React state commits
+ const fallbackPanRef = useRef(pan);
+ const fallbackZoomRef = useRef(zoom);
+ const fallbackRotationRef = useRef(rotation);
+ const fallbackFlipXRef = useRef(flipX);
+ const fallbackFlipYRef = useRef(flipY);
+ const panRef = navigation?.panRef ?? fallbackPanRef;
+ const zoomRef = navigation?.zoomRef ?? fallbackZoomRef;
+ const rotationRef = navigation?.rotationRef ?? fallbackRotationRef;
+ const flipXRef = navigation?.flipXRef ?? fallbackFlipXRef;
+ const flipYRef = navigation?.flipYRef ?? fallbackFlipYRef;
const brushSettingsRef = useRef(brushSettings);
const toolRef = useRef(tool);
const colorModeRef = useRef(colorMode);
@@ -262,10 +287,12 @@ export function useCanvasDrawing({
const isMaskModeRef = useRef(isMaskMode);
const onUpdateMaskThumbnailRef = useRef(onUpdateMaskThumbnail);
- // Synchronously keep refs fresh during render execution
- panRef.current = pan;
- zoomRef.current = zoom;
- rotationRef.current = rotation;
+ // Synchronously keep fallback & editor refs fresh during render execution
+ fallbackPanRef.current = pan;
+ fallbackZoomRef.current = zoom;
+ fallbackRotationRef.current = rotation;
+ fallbackFlipXRef.current = flipX;
+ fallbackFlipYRef.current = flipY;
brushSettingsRef.current = brushSettings;
toolRef.current = tool;
colorModeRef.current = colorMode;
@@ -309,9 +336,11 @@ export function useCanvasDrawing({
}, []);
useEffect(() => {
- panRef.current = pan;
- zoomRef.current = zoom;
- rotationRef.current = rotation;
+ fallbackPanRef.current = pan;
+ fallbackZoomRef.current = zoom;
+ fallbackRotationRef.current = rotation;
+ fallbackFlipXRef.current = flipX;
+ fallbackFlipYRef.current = flipY;
brushSettingsRef.current = brushSettings;
toolRef.current = tool;
colorModeRef.current = colorMode;
@@ -331,38 +360,39 @@ export function useCanvasDrawing({
onCollabCursorMoveRef.current = onCollabCursorMove;
});
- // Full sequence of points for baking onto the high-resolution canvas on pointerup
+ // Full sequence of points for high-resolution baking on pointerup
const allStrokePointsRef = useRef<Point[]>([]);
- // Sliding window of points for real-time Bézier smoothing on the draft overlay canvas
- const strokePointsRef = useRef<Point[]>([]);
+ // Zero-allocation input ring buffer, 1-Euro corner-snapping stabilizer, spline generator, and taper engine
+ const strokePipelineRef = useRef(new StrokePipeline());
+
+ // Reusable per-frame GPU dab batch (eliminates per-frame array allocation on hot path)
+ const frameGpuDabsRef = useRef<GpuDab[]>([]);
- // Raw points window buffer for symmetric Gaussian FIR stabilization
- const rawPointsBufferRef = useRef<{ x: number; y: number; pressure: number; pointerType: string; tiltX?: number; tiltY?: number; twist?: number; timestamp?: number }[]>([]);
+ // Pre-allocated scratch coordinates for zero-GC pointermove ingestion & prediction
+ const scratchDocCoordRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const predCoordPoolRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ ]);
+ const predDocCoordsRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([]);
+ const predDabCounterRef = useRef<{ count: number }>({ count: 0 });
+ const lastQueuedPressureRef = useRef<number>(0.5);
- // Stabilizer tracking ref
+ // Stabilizer tracking ref (previous stabilized point for velocity dynamics)
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);
const liveDabCounterRef = useRef<{ count: number }>({ count: 0 });
- // Active color mixing reservoir and pre-stroke backup canvas for real-time wet blending/smudging
+ // Active color mixing reservoir & lazy tile sampler (reads clean pre-stroke SparseTileGrid)
const activeReservoirRef = useRef<PaintReservoir | null>(null);
const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
- const strokeBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);
const isWetColorStrokeRef = useRef<boolean>(false);
- const drewDirectlyOnLayerCanvasRef = useRef<boolean>(false);
- const liveStrokeIsolationRef = useRef<boolean>(false);
- const liveAccumCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const liveOrigCanvasTilesRef = useRef<Map<number, ImageData>>(new Map());
- const liveBeforeTileSnapshotRef = useRef<Map<string, { format: TileFormat; data: Uint8Array | null }>>(new Map());
const liveNeedsNotifyRef = useRef<boolean>(false);
- const isBatchFlushingRef = useRef<boolean>(false);
- const pendingBatchSyncRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);
const lastStrokeEndRef = useRef<{ x: number; y: number; pressure: number; width: number; layerId: string } | null>(null);
const isShiftLineStrokeRef = useRef<boolean>(false);
const historyQueueRef = useRef<Promise<void>>(Promise.resolve());
@@ -370,10 +400,11 @@ export function useCanvasDrawing({
const recentPointsTrailRef = useRef<{ x: number; y: number; t: number; pressure: number; width: number }[]>([]);
const strokeTotalDistanceRef = useRef<number>(0);
- // Dirty bounding box for the active stroke
+ // Dirty bounding box for the active stroke (mirrored from StrokePipeline.dirtyRect)
const dirtyRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);
const touchedTilesRef = useRef<Set<number>>(new Set());
- const lastProcessedPointRef = useRef<{ x: number; y: number } | null>(null);
+ const lastProcessedPointRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const hasLastProcessedPointRef = useRef<boolean>(false);
const markTouchedTiles = useCallback((minX: number, minY: number, maxX: number, maxY: number) => {
const dims = dimensionsRef.current;
@@ -393,8 +424,6 @@ export function useCanvasDrawing({
}
}, []);
- // Queue of incoming pointer coordinates to be batched and processed via requestAnimationFrame (rAF)
- const pendingPointsQueueRef = useRef<{ x: number; y: number; pressure: number; pointerType: string; tiltX?: number; tiltY?: number; twist?: number; timestamp?: number }[]>([]);
const drawRafIdRef = useRef<number | null>(null);
const clearDraftRafRef = useRef<number | null>(null);
@@ -426,6 +455,7 @@ export function useCanvasDrawing({
cachedViewportRectRef.current = null;
};
window.addEventListener('resize', handleResize);
+ window.addEventListener('scroll', handleResize, true);
let ro: ResizeObserver | null = null;
if (typeof ResizeObserver !== 'undefined' && viewportRef.current) {
ro = new ResizeObserver(handleResize);
@@ -433,6 +463,7 @@ export function useCanvasDrawing({
}
return () => {
window.removeEventListener('resize', handleResize);
+ window.removeEventListener('scroll', handleResize, true);
ro?.disconnect();
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
@@ -441,7 +472,7 @@ export function useCanvasDrawing({
cancelAnimationFrame(drawRafIdRef.current);
}
};
- }, [viewportRef]);
+ }, [viewportRef, disabled, activeSessionId]);
const dispatchPointerStat = useCallback((x: number | null, y: number | null, pressure: number) => {
pendingStatRef.current = {
@@ -695,206 +726,7 @@ export function useCanvasDrawing({
}
}, []);
- // Helper to restore all live-backed-up tiles back onto a layer canvas
- const restoreLiveOrigTilesToCanvas = useCallback((canvas: HTMLCanvasElement) => {
- if (liveOrigCanvasTilesRef.current.size === 0) return;
- const cCtx = get2DContext(canvas);
- if (!cCtx) return;
- for (const [numKey, tileImg] of liveOrigCanvasTilesRef.current) {
- const ty = Math.floor(numKey / 65536);
- const tx = numKey % 65536;
- cCtx.putImageData(tileImg, tx * TILE_SIZE, ty * TILE_SIZE);
- }
- }, []);
-
- // Helper to restore a specific sub-rectangle on `canvasCtx` from `liveOrigCanvasTilesRef`
- const restoreLiveRectFromOrigTiles = useCallback(
- (canvasCtx: CanvasRenderingContext2D, rx: number, ry: number, rw: number, rh: number) => {
- if (rw <= 0 || rh <= 0 || liveOrigCanvasTilesRef.current.size === 0) return;
- const minTx = rx >> 8;
- const minTy = ry >> 8;
- const maxTx = (rx + rw - 1) >> 8;
- const maxTy = (ry + rh - 1) >> 8;
- for (let ty = minTy; ty <= maxTy; ty++) {
- for (let tx = minTx; tx <= maxTx; tx++) {
- const tileImg = liveOrigCanvasTilesRef.current.get(ty * 65536 + tx);
- if (!tileImg) continue;
- const tileOriginX = tx * TILE_SIZE;
- const tileOriginY = ty * TILE_SIZE;
- const ix0 = Math.max(rx, tileOriginX);
- const iy0 = Math.max(ry, tileOriginY);
- const ix1 = Math.min(rx + rw, tileOriginX + tileImg.width);
- const iy1 = Math.min(ry + rh, tileOriginY + tileImg.height);
- if (ix1 > ix0 && iy1 > iy0) {
- canvasCtx.putImageData(
- tileImg,
- tileOriginX,
- tileOriginY,
- ix0 - tileOriginX,
- iy0 - tileOriginY,
- ix1 - ix0,
- iy1 - iy0
- );
- }
- }
- }
- },
- []
- );
-
- // Lazily snapshot pre-stroke tiles in both SparseTileGrid and canvas ImageData before live mutation
- const ensureLiveTileSnapshots = useCallback(
- (
- canvas: HTMLCanvasElement,
- canvasCtx: CanvasRenderingContext2D,
- layerId: string,
- minX: number,
- minY: number,
- maxX: number,
- maxY: number
- ) => {
- const cMinX = Math.max(0, Math.floor(minX));
- const cMinY = Math.max(0, Math.floor(minY));
- const cMaxX = Math.min(canvas.width, Math.ceil(maxX));
- const cMaxY = Math.min(canvas.height, Math.ceil(maxY));
- if (cMaxX <= cMinX || cMaxY <= cMinY) return;
-
- const minTx = cMinX >> 8;
- const minTy = cMinY >> 8;
- const maxTx = (cMaxX - 1) >> 8;
- const maxTy = (cMaxY - 1) >> 8;
-
- for (let ty = minTy; ty <= maxTy; ty++) {
- for (let tx = minTx; tx <= maxTx; tx++) {
- const numKey = ty * 65536 + tx;
- touchedTilesRef.current.add(numKey);
- if (!liveOrigCanvasTilesRef.current.has(numKey)) {
- const ox = tx * TILE_SIZE;
- const oy = ty * TILE_SIZE;
- const tw = Math.min(TILE_SIZE, canvas.width - ox);
- const th = Math.min(TILE_SIZE, canvas.height - oy);
- if (tw <= 0 || th <= 0) continue;
- if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
- const accCtx = get2DContext(liveAccumCanvasRef.current);
- accCtx?.clearRect(ox, oy, tw, th);
- }
- let origImg: ImageData;
- if (globalTileGrid.isLayerIngested(layerId) && typeof ImageData !== 'undefined') {
- const rawTile = globalTileGrid.readImageData(layerId, ox, oy, tw, th);
- origImg = new ImageData(new Uint8ClampedArray(rawTile.data), tw, th);
- canvasCtx.putImageData(origImg, ox, oy);
- } else {
- origImg = canvasCtx.getImageData(ox, oy, tw, th);
- }
- liveOrigCanvasTilesRef.current.set(numKey, origImg);
- if (!globalTileGrid.isLayerIngested(layerId) && !globalTileGrid.getTile(layerId, tx, ty, 0)) {
- const activeLayer = layersRef.current?.find((l) => l.id === layerId);
- const isMono =
- !isBackgroundLayerId(layerId) &&
- (colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
- globalTileGrid.writeImageData(
- layerId,
- origImg,
- ox,
- oy,
- isMono ? 'monochrome-1bit' : 'color-32bit',
- true
- );
- }
- const subSnap = globalTileGrid.snapshotTilesInRect(layerId, {
- x: ox,
- y: oy,
- width: tw,
- height: th,
- });
- for (const [k, v] of subSnap) {
- if (!liveBeforeTileSnapshotRef.current.has(k)) {
- liveBeforeTileSnapshotRef.current.set(k, v);
- }
- }
- }
- }
- }
- },
- []
- );
-
- // Sync a small mutated region of `canvas` into `globalTileGrid` during Live WYSIWYG preview
- const syncLiveRegionToTiles = useCallback(
- (
- canvas: HTMLCanvasElement,
- canvasCtx: CanvasRenderingContext2D,
- layerId: string,
- minX: number,
- minY: number,
- maxX: number,
- maxY: number,
- isMonochrome: boolean,
- activeLayer: LayerItem | undefined,
- bs: BrushSettings,
- isEraser: boolean,
- isBgEraser: boolean
- ) => {
- const rx = Math.max(0, Math.floor(minX));
- const ry = Math.max(0, Math.floor(minY));
- const rw = Math.min(canvas.width, Math.ceil(maxX)) - rx;
- const rh = Math.min(canvas.height, Math.ceil(maxY)) - ry;
- if (rw <= 0 || rh <= 0) return;
-
- ensureLiveTileSnapshots(canvas, canvasCtx, layerId, rx, ry, rx + rw, ry + rh);
-
- if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
- restoreLiveRectFromOrigTiles(canvasCtx, rx, ry, rw, rh);
- canvasCtx.save();
- canvasCtx.beginPath();
- canvasCtx.rect(rx, ry, rw, rh);
- canvasCtx.clip();
- applySelectionCanvasClip(canvasCtx, selectionRef.current);
- canvasCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- canvasCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- canvasCtx.globalCompositeOperation = 'source-atop';
- } else {
- canvasCtx.globalCompositeOperation = 'source-over';
- }
- canvasCtx.drawImage(liveAccumCanvasRef.current, rx, ry, rw, rh, rx, ry, rw, rh);
- canvasCtx.restore();
- }
-
- const segData = canvasCtx.getImageData(rx, ry, rw, rh);
- if (selectionRef.current?.mask) {
- // Reconstruct before pixels for exact 8-bit selection mask blending
- restoreLiveRectFromOrigTiles(canvasCtx, rx, ry, rw, rh);
- const beforeSub = canvasCtx.getImageData(rx, ry, rw, rh);
- applySelectionMaskToImageData(beforeSub, segData, rx, ry, selectionRef.current);
- canvasCtx.putImageData(segData, rx, ry);
- }
-
- if (isMonochrome) {
- binarizeImageDataBuffer(
- segData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- canvasCtx.putImageData(segData, rx, ry);
- }
-
- globalTileGrid.writeImageData(
- layerId,
- segData,
- rx,
- ry,
- isMonochrome ? 'monochrome-1bit' : 'color-32bit',
- true
- );
- liveNeedsNotifyRef.current = true;
- },
- [ensureLiveTileSnapshots, restoreLiveRectFromOrigTiles]
- );
-
- // Abort any in-progress stroke session immediately
+ // Abort any in-progress stroke session immediately (zero base-layer mutation to undo!)
const abortActiveStroke = useCallback(() => {
if (!isDrawingRef.current) return;
if (drawRafIdRef.current !== null) {
@@ -902,6 +734,7 @@ export function useCanvasDrawing({
drawRafIdRef.current = null;
}
const draftCanvas = effectiveDraftCanvasRef?.current;
+ let clearedActiveDraft = false;
if (draftCanvas) {
const dCtx = get2DContext(draftCanvas);
if (dCtx) {
@@ -911,57 +744,35 @@ export function useCanvasDrawing({
dCtx.resetTransform();
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
+ if ((draftCanvas as any).__draftHasContent) {
+ clearedActiveDraft = true;
+ }
+ (draftCanvas as any).__draftHasContent = false;
+ (draftCanvas as any).__draftCompositeOp = 'source-over';
+ (draftCanvas as any).__draftMonochrome = false;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
}
clearPredictedCanvas();
- if (drewDirectlyOnLayerCanvasRef.current) {
- const currentLayerId = activeLayerIdRef.current;
- const canvas = layerCanvasesRef.current.get(currentLayerId) || getActiveCanvas();
- if (canvas) {
- restoreLiveOrigTilesToCanvas(canvas);
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMono =
- !isBackgroundLayerId(currentLayerId) &&
- (colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
- for (const [numKey, tileImg] of liveOrigCanvasTilesRef.current) {
- const ty = Math.floor(numKey / 65536);
- const tx = numKey % 65536;
- globalTileGrid.writeImageData(
- currentLayerId,
- tileImg,
- tx * TILE_SIZE,
- ty * TILE_SIZE,
- isMono ? 'monochrome-1bit' : 'color-32bit',
- true
- );
- }
- globalTileGrid.notifyChange(true);
- }
- }
+ if (clearedActiveDraft) {
+ globalTileGrid.notifyChange(true);
}
+ strokePipelineRef.current.abortStroke();
+ frameGpuDabsRef.current.length = 0;
isDrawingRef.current = false;
activePointerIdRef.current = null;
allStrokePointsRef.current = [];
- strokePointsRef.current = [];
stabilizedPointRef.current = null;
- lastProcessedPointRef.current = null;
+ hasLastProcessedPointRef.current = false;
dirtyRectRef.current = null;
touchedTilesRef.current.clear();
- pendingPointsQueueRef.current = [];
- drewDirectlyOnLayerCanvasRef.current = false;
- liveStrokeIsolationRef.current = false;
- liveOrigCanvasTilesRef.current.clear();
- liveBeforeTileSnapshotRef.current.clear();
liveNeedsNotifyRef.current = false;
isShiftLineStrokeRef.current = false;
isToneStrokeRef.current = false;
- strokeBackupCanvasRef.current = null;
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
snapSessionRef.current.endStroke();
emitConstraintAxisChange(null);
- }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange, getActiveCanvas, layerCanvasesRef, restoreLiveOrigTilesToCanvas]);
+ }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange]);
// Jump directly to any past or future history step (serialized via historyQueueRef to prevent async race on rapid Ctrl+Z)
const jumpToHistoryIndex = useCallback(
@@ -1420,7 +1231,9 @@ export function useCanvasDrawing({
panRef.current,
zoomRef.current,
rotationRef.current,
- dims
+ dims,
+ flipXRef.current,
+ flipYRef.current
);
let pressure = 0;
@@ -1511,7 +1324,7 @@ export function useCanvasDrawing({
dualBrush: bs.dualBrush,
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu,
+ useGpu: bs.useGpu !== false,
underlyingCanvas: canvas || undefined,
sampler: layerPixelSamplerRef.current || undefined,
reservoir: activeReservoirRef.current || undefined,
@@ -1547,7 +1360,7 @@ export function useCanvasDrawing({
isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
- useGpu: bs.useGpu,
+ useGpu: bs.useGpu !== false,
dualBrush: bs.dualBrush,
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
@@ -1576,26 +1389,11 @@ export function useCanvasDrawing({
[]
);
- // Render a single smooth segment onto either Live Direct Layer/Tile preview or the viewport draft overlay
- const renderDraftSegment = useCallback((draftCtx: CanvasRenderingContext2D, point: Point) => {
- const pts = strokePointsRef.current;
-
- const isEraser = toolRef.current === 'eraser';
- const isBgEraser = isEraser && isBackgroundLayerId(activeLayerIdRef.current);
- const bs = brushSettingsRef.current;
- const mode = colorModeRef.current;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const canvas = getActiveCanvas();
- const currentLayerId = activeLayerIdRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
-
- let strokeColor: string;
- if (isMaskModeRef.current) {
- if (isEraser) {
- strokeColor = '#000000';
- } else {
+ // Helper: compute effective live stroke color for current mode/mask/bg-eraser
+ const resolveStrokeColor = useCallback(
+ (bs: BrushSettings, isEraser: boolean, isBgEraser: boolean, isMonochrome: boolean, mode: CanvasColorMode): string => {
+ if (isMaskModeRef.current) {
+ if (isEraser) return '#000000';
let clean = bs.color.replace('#', '');
if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
const r = parseInt(clean.slice(0, 2), 16) || 0;
@@ -1603,397 +1401,198 @@ export function useCanvasDrawing({
const b = parseInt(clean.slice(4, 6), 16) || 0;
const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
const hexVal = gray.toString(16).padStart(2, '0');
- strokeColor = `#${hexVal}${hexVal}${hexVal}`;
+ return `#${hexVal}${hexVal}${hexVal}`;
}
- } else {
- strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- }
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
- const strokeSpacing = bs.spacing ?? 0.08;
+ return isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ },
+ []
+ );
+
+ // Renders a sealed CubicBezierSegment onto draftCtx (either pushing into GPU batch or Canvas 2D fallback)
+ const emitLiveSegment = useCallback(
+ (
+ draftCtx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ bs: BrushSettings,
+ strokeColor: string,
+ strokeHardness: number,
+ strokeFlow: number,
+ strokeSpacing: number,
+ isMonochrome: boolean,
+ isPencil: boolean,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ useWireframeEraser: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ gpuBatch: GpuDab[] | undefined
+ ) => {
+ const sStart = seg.p0;
+ const c1Pt = seg.c1;
+ const c2Pt = seg.c2;
+ const sEnd = seg.p3;
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const segPad = Math.ceil(Math.max(sStart.width, sEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32);
+ const segMinX = Math.min(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) - segPad;
+ const segMinY = Math.min(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) - segPad;
+ const segMaxX = Math.max(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) + segPad;
+ const segMaxY = Math.max(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) + segPad;
+ strokePipelineRef.current.expandDirtyRectBounds(segMinX, segMinY, segMaxX, segMaxY);
+ markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
+
+ if (useWireframeEraser) {
+ 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, (sStart.width + sEnd.width) / 2);
+ draftCtx.beginPath();
+ draftCtx.moveTo(sStart.x, sStart.y);
+ draftCtx.bezierCurveTo(c1Pt.x, c1Pt.y, c2Pt.x, c2Pt.y, sEnd.x, sEnd.y);
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const draftCanvas = effectiveDraftCanvasRef?.current;
+ const draftScale = (draftCanvas as any)?.__draftScale ?? 1.0;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
- const renderSegmentToContext = (
- ctx: CanvasRenderingContext2D,
- sStart: Point,
- c1Pt: Point,
- c2Pt: Point,
- sEnd: Point,
- isolatedPass: boolean = false
- ): number => {
if (bs.customTipImage) {
const tipOptions = buildLiveTexturedOptions(
bs,
- bs.flow ?? 0.85,
+ isMonochrome ? 1.0 : (bs.flow ?? 1.0),
bs.spacing ?? 0.08,
strokeHardness,
- isMonochrome,
+ downscaledBinary ? false : isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- isolatedPass
+ true
);
- return drawTexturedCubicBezierSegment(
- ctx,
+ if (downscaledBinary && tipOptions.antiAlias === 0) {
+ tipOptions.antiAlias = 2;
+ }
+ stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
+ draftCtx,
sStart,
c1Pt,
c2Pt,
sEnd,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
+ liveColor,
bs.customTipImage,
tipOptions,
stampRemainderDistRef.current,
- liveDabCounterRef.current
+ liveDabCounterRef.current,
+ gpuBatch
);
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- return drawPencilCubicBezierSegment(
- ctx,
+ stampRemainderDistRef.current = drawPencilCubicBezierSegment(
+ draftCtx,
sStart,
c1Pt,
c2Pt,
sEnd,
- strokeColor,
+ liveColor,
grade,
isMonochrome ? 1.0 : (bs.flow ?? 0.74),
bs.grain ?? 1.0,
strokeHardness,
stampRemainderDistRef.current,
- isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isolatedPass ? false : Boolean(bs.isTransparentInk),
+ false,
+ false,
bs.useTilt ?? true
);
} else {
const radialMixingOptions = buildLiveRadialOptions(
bs,
- isMonochrome,
+ downscaledBinary ? false : isMonochrome,
canvas,
activeLayer,
- isolatedPass
+ true
);
- return drawSmoothCubicBezierSegment(
- ctx,
+ if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
+ radialMixingOptions.antiAlias = 2;
+ }
+ stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
+ draftCtx,
sStart,
c1Pt,
c2Pt,
sEnd,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
- isolatedPass ? false : isEraser && !isBgEraser,
+ liveColor,
+ false,
strokeHardness,
strokeFlow,
strokeSpacing,
stampRemainderDistRef.current,
bs.thickness ?? 1.0,
((bs.customTipAngle ?? 0) * Math.PI) / 180,
- 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;
-
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const segPad = Math.ceil(Math.max(segStart.width, segEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32);
- const segMinX = Math.min(segStart.x, c1.x, c2.x, segEnd.x) - segPad;
- const segMinY = Math.min(segStart.y, c1.y, c2.y, segEnd.y) - segPad;
- const segMaxX = Math.max(segStart.x, c1.x, c2.x, segEnd.x) + segPad;
- const segMaxY = Math.max(segStart.y, c1.y, c2.y, segEnd.y) + segPad;
- if (dirtyRectRef.current) {
- const docW = canvas ? canvas.width : dimensionsRef.current.width;
- const docH = canvas ? canvas.height : dimensionsRef.current.height;
- dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, Math.max(0, Math.floor(segMinX)));
- dirtyRectRef.current.minY = Math.min(dirtyRectRef.current.minY, Math.max(0, Math.floor(segMinY)));
- dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, Math.min(docW, Math.ceil(segMaxX)));
- dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, Math.min(docH, Math.ceil(segMaxY)));
- }
- markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
-
- // Live WYSIWYG Direct Layer/Tile Preview (Eraser, Transparent Ink, Alpha Lock, Color Mixing, Translucent, Clipped, Blend, Under-Layer)
- if (drewDirectlyOnLayerCanvasRef.current && canvas) {
- const canvasCtx = get2DContext(canvas);
- if (canvasCtx) {
- ensureLiveTileSnapshots(canvas, canvasCtx, currentLayerId, segMinX, segMinY, segMaxX, segMaxY);
- const clipRx = Math.max(0, Math.floor(segMinX));
- const clipRy = Math.max(0, Math.floor(segMinY));
- const clipRw = Math.min(canvas.width, Math.ceil(segMaxX)) - clipRx;
- const clipRh = Math.min(canvas.height, Math.ceil(segMaxY)) - clipRy;
- if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
- const accumCtx = get2DContext(liveAccumCanvasRef.current);
- if (accumCtx) {
- accumCtx.save();
- if (clipRw > 0 && clipRh > 0) {
- accumCtx.beginPath();
- accumCtx.rect(clipRx, clipRy, clipRw, clipRh);
- accumCtx.clip();
- }
- applySelectionCanvasClip(accumCtx, selectionRef.current);
- stampRemainderDistRef.current = renderSegmentToContext(accumCtx, segStart, c1, c2, segEnd, true);
- accumCtx.restore();
- }
- } else {
- canvasCtx.save();
- if (clipRw > 0 && clipRh > 0) {
- canvasCtx.beginPath();
- canvasCtx.rect(clipRx, clipRy, clipRw, clipRh);
- canvasCtx.clip();
- }
- applySelectionCanvasClip(canvasCtx, selectionRef.current);
- stampRemainderDistRef.current = renderSegmentToContext(canvasCtx, segStart, c1, c2, segEnd, false);
- canvasCtx.restore();
- }
- if (isBatchFlushingRef.current) {
- if (!pendingBatchSyncRectRef.current) {
- pendingBatchSyncRectRef.current = {
- minX: segMinX,
- minY: segMinY,
- maxX: segMaxX,
- maxY: segMaxY,
- };
- } else {
- pendingBatchSyncRectRef.current.minX = Math.min(pendingBatchSyncRectRef.current.minX, segMinX);
- pendingBatchSyncRectRef.current.minY = Math.min(pendingBatchSyncRectRef.current.minY, segMinY);
- pendingBatchSyncRectRef.current.maxX = Math.max(pendingBatchSyncRectRef.current.maxX, segMaxX);
- pendingBatchSyncRectRef.current.maxY = Math.max(pendingBatchSyncRectRef.current.maxY, segMaxY);
- }
- } else {
- syncLiveRegionToTiles(
- canvas,
- canvasCtx,
- currentLayerId,
- segMinX,
- segMinY,
- segMaxX,
- segMaxY,
- isMonochrome,
- activeLayer,
- bs,
- isEraser,
- isBgEraser
- );
- }
- return;
- }
- }
-
- // Fallback wireframe only for Vector / Screentone / Mask Eraser when direct preview is disabled
- if (isEraser && !isBgEraser) {
- 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;
- }
-
- // Ultra-fast viewport draft overlay for top-layer opaque strokes
- stampRemainderDistRef.current = renderSegmentToContext(draftCtx, segStart, c1, c2, segEnd, false);
- }, [buildLiveRadialOptions, buildLiveTexturedOptions, ensureLiveTileSnapshots, getActiveCanvas, markTouchedTiles, syncLiveRegionToTiles]);
-
- // 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
- ) => {
- const bs = brushSettingsRef.current;
- const dims = dimensionsRef.current;
- const stab = Math.min(50, Math.max(0, bs.stabilization ?? 0));
-
- const now = timestamp ?? performance.now();
- const dt = Math.max(1, now - (lastPointTimeRef.current || now));
- lastPointTimeRef.current = now;
-
- let velocityScale = 1.0;
- if (bs.velocityDynamics && stabilizedPointRef.current) {
- const dist = Math.hypot(rawX - stabilizedPointRef.current.x, rawY - stabilizedPointRef.current.y);
- const speed = dist / dt; // px / ms
- velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
- }
-
- const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
- let pt: Point;
- if (stab <= 0) {
- const baseP = bs.usePressure
- ? (hasCustomCurve ? rawPressure : taperEngineRef.current.mapPressure(rawPressure))
- : (rawPressure > 0 ? 1.0 : 0);
- const mappedP = bs.usePressure ? taperEngineRef.current.smoothPressure(baseP) : baseP;
- const width = calculateStrokeWidth(
- bs.size,
- mappedP,
- bs.minSizeFactor,
- bs.usePressure,
- pointerType,
- bs.pressureCurveGamma ?? 1.0,
- velocityScale,
- bs.pressureCurve
- );
- pt = { x: rawX, y: rawY, pressure: mappedP, width, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist, timestamp: now, isCorner: false };
- stabilizedPointRef.current = pt;
- } else {
- const sample = inputStabilizerRef.current.process(rawX, rawY, rawPressure, now);
- const baseP = bs.usePressure
- ? (hasCustomCurve ? sample.pressure : taperEngineRef.current.mapPressure(sample.pressure))
- : (rawPressure > 0 ? 1.0 : 0);
- const mappedP = bs.usePressure ? taperEngineRef.current.smoothPressure(baseP) : baseP;
- const smoothWidth = calculateStrokeWidth(
- bs.size,
- mappedP,
- bs.minSizeFactor,
- bs.usePressure,
- pointerType,
- bs.pressureCurveGamma ?? 1.0,
- velocityScale,
- bs.pressureCurve
+ radialMixingOptions,
+ gpuBatch
);
- 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;
- }
-
- // Track recent trail for exit velocity & tangent calculation
- if (allStrokePointsRef.current.length > 0) {
- const lastPt = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
- strokeTotalDistanceRef.current += Math.hypot(pt.x - lastPt.x, pt.y - lastPt.y);
- }
- recentPointsTrailRef.current.push({ x: pt.x, y: pt.y, t: now, pressure: pt.pressure, width: pt.width });
- if (recentPointsTrailRef.current.length > 16) {
- recentPointsTrailRef.current.shift();
- }
-
- // Expand dirty rectangle in canvas coordinates
- const blurMargin = (1 - (bs.hardness ?? 1.0)) * (pt.width * 1.5);
- const r = Math.max(24, Math.ceil(pt.width + blurMargin + 24));
- if (dirtyRectRef.current) {
- dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, Math.floor(pt.x - r)));
- dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, Math.floor(pt.y - r)));
- dirtyRectRef.current.maxX = Math.min(dims.width, Math.max(dirtyRectRef.current.maxX, Math.ceil(pt.x + r)));
- dirtyRectRef.current.maxY = Math.min(dims.height, Math.max(dirtyRectRef.current.maxY, Math.ceil(pt.y + r)));
}
-
- allStrokePointsRef.current.push(pt);
- renderDraftSegment(draftCtx, pt);
},
- [renderDraftSegment]
+ [buildLiveRadialOptions, buildLiveTexturedOptions, effectiveDraftCanvasRef, markTouchedTiles]
);
- // Zero-gap provisional + predicted tip overlay matching exact brush geometry
+ // Ephemeral predicted tail overlay rendered strictly onto effectivePredictedCanvasRef (never leaks into layer data)
const renderPredictedStroke = useCallback(
(predEvents: PointerEvent[], vRect: DOMRect) => {
clearPredictedCanvas();
- if (toolRef.current === 'eraser' || drewDirectlyOnLayerCanvasRef.current) return;
- const pts = strokePointsRef.current;
- if (pts.length < 2) return;
+ const bs = brushSettingsRef.current;
+ if (toolRef.current === 'eraser' || bs.isTransparentInk) return;
+ const pipeline = strokePipelineRef.current;
+ if (pipeline.getKnotCount() < 2) return;
const pCanvas = getPredictedCanvas();
if (!pCanvas) return;
const pCtx = get2DContext(pCanvas);
if (!pCtx) return;
- const bs = brushSettingsRef.current;
const dims = dimensionsRef.current;
const mode = colorModeRef.current;
const currentLayerId = activeLayerIdRef.current;
const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isPencil = bs.preset?.startsWith('pencil') ?? false;
-
- let strokeColor: string;
- if (isMaskModeRef.current) {
- let clean = bs.color.replace('#', '');
- if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
- const r = parseInt(clean.slice(0, 2), 16) || 0;
- const g = parseInt(clean.slice(2, 4), 16) || 0;
- const b = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
- const hexVal = gray.toString(16).padStart(2, '0');
- strokeColor = `#${hexVal}${hexVal}${hexVal}`;
- } else {
- strokeColor = enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- }
-
+ const isPencil = !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const strokeColor = resolveStrokeColor(bs, false, false, isMonochrome, mode);
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
const strokeSpacing = bs.spacing ?? 0.08;
- const pLast = pts[pts.length - 1];
- const pPrev = pts[pts.length - 2];
- const pPrev2 = pts.length >= 3 ? pts[pts.length - 3] : pPrev;
+ const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+ const predCoords = predDocCoordsRef.current;
+ predCoords.length = 0;
- let predPt: Point | null = null;
if (predEvents && predEvents.length > 0) {
- 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 - pLast.x;
- const dy = rawPred.y - pLast.y;
- const dist = Math.hypot(dx, dy);
- if (dist >= 0.5 && dist <= maxPredDist * 2.5) {
- const clampedScale = dist > maxPredDist ? maxPredDist / dist : 1.0;
- predPt = {
- x: pLast.x + dx * clampedScale,
- y: pLast.y + dy * clampedScale,
- pressure: pLast.pressure * 0.9,
- width: Math.max(0.5, pLast.width * 0.9),
- tiltX: pLast.tiltX,
- tiltY: pLast.tiltY,
- twist: pLast.twist,
- };
+ const scratch = scratchDocCoordRef.current;
+ const pool = predCoordPoolRef.current;
+ const limit = Math.min(predEvents.length, pool.length);
+ for (let i = 0; i < limit; i++) {
+ const ev = predEvents[i];
+ screenToCanvasInto(
+ ev.clientX,
+ ev.clientY,
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims,
+ scratch,
+ flipXRef.current,
+ flipYRef.current
+ );
+ const slot = pool[i];
+ slot.x = scratch.x;
+ slot.y = scratch.y;
+ slot.pressure = ev.pressure;
+ predCoords.push(slot);
}
}
@@ -2005,7 +1604,9 @@ export function useCanvasDrawing({
rotationRef.current,
dims,
scaleX,
- scaleY
+ scaleY,
+ flipXRef.current,
+ flipYRef.current
);
pCtx.save();
@@ -2015,121 +1616,149 @@ export function useCanvasDrawing({
pCtx.clip();
applySelectionCanvasClip(pCtx, selectionRef.current);
- const drawProvisionalSeg = (s0: Point, c1Pt: Point, c2Pt: Point, s3: Point, rem: number): number => {
- if (bs.customTipImage) {
- return drawTexturedCubicBezierSegment(
- pCtx,
- s0,
- c1Pt,
- c2Pt,
- s3,
- strokeColor,
- bs.customTipImage,
- {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: bs.opacity,
- flow: strokeFlow,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- usePressure: bs.usePressure,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- wetEdge: bs.wetEdge,
- grain: bs.grain ?? bs.textureDensity,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- },
- rem
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- return drawPencilCubicBezierSegment(
- pCtx,
- s0,
- c1Pt,
- c2Pt,
- s3,
- strokeColor,
- grade,
- isMonochrome ? 1.0 : (bs.flow ?? 0.74),
- bs.grain ?? 1.0,
- strokeHardness,
- rem,
- Boolean(activeLayer?.alphaLocked),
- Boolean(bs.isTransparentInk)
- );
- } else {
- return drawSmoothCubicBezierSegment(
- pCtx,
- s0,
- c1Pt,
- c2Pt,
- s3,
- strokeColor,
- false,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- rem,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- {
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- }
- );
- }
+ let predRem = stampRemainderDistRef.current;
+ // On viewport-sized predictedCanvas when zoomed out in monochrome, use smooth AA=2 (thresholded by SVG filter) so pixels never drop
+ const predAA = isMonochrome && zoomRef.current < 1.0 ? 2 : (isMonochrome ? 0 : bs.antiAlias);
+ const predTipOpts: TexturedBrushOptions | null = bs.customTipImage
+ ? {
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: 1.0,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: strokeHardness,
+ antiAlias: predAA,
+ pressureCurve: bs.pressureCurve,
+ usePressure: bs.usePressure,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ wetEdge: 0,
+ grain: bs.grain ?? bs.textureDensity,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useGpu: bs.useGpu !== false,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ }
+ : null;
+ const predRadialOpts: RadialMixingOptions = {
+ useGpu: bs.useGpu !== false,
+ antiAlias: predAA,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ grain: bs.grain ?? bs.textureDensity,
};
- // 1. Provisional unsealed segment (pPrev -> pLast) bridging draftCanvas to current stylus head
- const provNextKnot = predPt || pLast;
- const provCtrl = catmullRomToBezier(pPrev2, pPrev, pLast, provNextKnot);
- const remAfterProv = drawProvisionalSeg(pPrev, provCtrl.c1, provCtrl.c2, pLast, stampRemainderDistRef.current);
+ const predGpuDabs = frameGpuDabsRef.current;
+ predGpuDabs.length = 0;
+ const useGpuPred = bs.customTipImage
+ ? Boolean(predTipOpts && canUseWebGlForTexturedBrush(predTipOpts))
+ : (!isPencil && canUseWebGlForRadialBrush(predRadialOpts));
+
+ predDabCounterRef.current.count = liveDabCounterRef.current.count;
+ // In zoomed-out monochrome mode, committed LOD tiles (OR-downsampled) and mipmapped draftCanvas
+ // preserve sub-pixel ink at ~1.35 CSS px; lift transient predicted-bridge widths to match.
+ const minPredMonoWidth = isMonochrome && zoomRef.current < 0.99 ? 1.35 / Math.max(0.01, zoomRef.current) : 0;
+ // Render ONLY the real unsealed Catmull-Rom bridge (knotP1 -> knotP2), avoiding speculative
+ // ahead-of-cursor overshoot that snaps back / disappears upon pointerup.
+ const drew = pipeline.buildPredictedSegments(
+ null,
+ maxPredDist,
+ (seg) => {
+ const p0 = minPredMonoWidth > 0 && seg.p0.width < minPredMonoWidth ? { ...seg.p0, width: minPredMonoWidth } : seg.p0;
+ const p3 = minPredMonoWidth > 0 && seg.p3.width < minPredMonoWidth ? { ...seg.p3, width: minPredMonoWidth } : seg.p3;
+ if (bs.customTipImage && predTipOpts) {
+ predRem = drawTexturedCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ bs.customTipImage,
+ predTipOpts,
+ predRem,
+ predDabCounterRef.current,
+ useGpuPred ? predGpuDabs : undefined
+ );
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
+ predRem = drawPencilCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ grade,
+ isMonochrome ? 1.0 : (bs.flow ?? 0.74),
+ bs.grain ?? 1.0,
+ strokeHardness,
+ predRem,
+ false,
+ false
+ );
+ } else {
+ predRem = drawSmoothCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ predRem,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ predRadialOpts,
+ useGpuPred ? predGpuDabs : undefined
+ );
+ }
+ }
+ );
- // 2. Speculative lookahead segment (pLast -> predPt) if predicted events exist
- if (predPt) {
- const predCtrl = catmullRomToBezier(pPrev, pLast, predPt, predPt);
- drawProvisionalSeg(pLast, predCtrl.c1, predCtrl.c2, predPt, remAfterProv);
+ if (useGpuPred && predGpuDabs.length > 0) {
+ if (bs.customTipImage && predTipOpts) {
+ flushTexturedGpuDabs(pCtx, predGpuDabs, bs.customTipImage, strokeColor, predTipOpts);
+ } else {
+ flushRadialGpuDabs(pCtx, predGpuDabs, strokeColor, strokeHardness, false, false, predRadialOpts);
+ }
+ predGpuDabs.length = 0;
}
pCtx.restore();
- isPredictedCanvasDirtyRef.current = true;
+ if (drew) {
+ isPredictedCanvasDirtyRef.current = true;
+ }
},
- [clearPredictedCanvas, getPredictedCanvas]
+ [clearPredictedCanvas, getPredictedCanvas, resolveStrokeColor]
);
- // Flush batched points on requestAnimationFrame
+ // Flush batched points from StrokePipeline ring buffer on requestAnimationFrame (ZERO getImageData!)
const flushPendingPoints = useCallback(() => {
drawRafIdRef.current = null;
if (!isDrawingRef.current) return;
- const queue = pendingPointsQueueRef.current;
- if (queue.length === 0) {
- // Update predicted stroke overlay throttled to rAF
+ const pipeline = strokePipelineRef.current;
+ if (pipeline.getPendingCount() === 0) {
const predData = latestPredictedRef.current;
latestPredictedRef.current = null;
const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0 && !drewDirectlyOnLayerCanvasRef.current) {
+ if (vRect && allStrokePointsRef.current.length > 0) {
renderPredictedStroke(predData ? predData.predEvents : [], vRect);
} else if (isPredictedCanvasDirtyRef.current) {
clearPredictedCanvas();
@@ -2142,88 +1771,205 @@ export function useCanvasDrawing({
const draftCtx = get2DContext(draftCanvas);
if (!draftCtx) return;
- const queueLen = queue.length;
- const chunkPts: Point[] = [];
- let batchMinX = Infinity;
- let batchMinY = Infinity;
- let batchMaxX = -Infinity;
- let batchMaxY = -Infinity;
- let maxStrokeWidth = 0;
-
- isBatchFlushingRef.current = true;
- pendingBatchSyncRectRef.current = null;
-
- 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);
- batchMinX = Math.min(batchMinX, lastPt.x);
- batchMinY = Math.min(batchMinY, lastPt.y);
- batchMaxX = Math.max(batchMaxX, lastPt.x);
- batchMaxY = Math.max(batchMaxY, lastPt.y);
- maxStrokeWidth = Math.max(maxStrokeWidth, lastPt.width);
- }
- }
- queue.length = 0;
- isBatchFlushingRef.current = false;
+ const bs = brushSettingsRef.current;
+ const mode = colorModeRef.current;
+ const isEraser = toolRef.current === 'eraser';
+ const currentLayerId = activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const isVectorOrToneOrMask = activeLayer?.type === 'vector' || isToneStrokeRef.current || isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
+ const canvas = getActiveCanvas();
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
+ const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
+ const strokeSpacing = bs.spacing ?? 0.08;
+ const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
+ const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
+
+ // Check GPU instanced dab batch eligibility for this frame
+ const draftScale = (draftCanvas as any).__draftScale ?? 1.0;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveTipOpts = bs.customTipImage
+ ? buildLiveTexturedOptions(bs, isMonochrome ? 1.0 : (bs.flow ?? 1.0), strokeSpacing, strokeHardness, downscaledBinary ? false : isMonochrome, canvas, activeLayer, isEraser, isBgEraser, true)
+ : null;
+ if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
+ liveTipOpts.antiAlias = 2;
+ }
+ const liveRadialOpts = !bs.customTipImage && !isPencil
+ ? buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true)
+ : null;
+ if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
+ liveRadialOpts.antiAlias = 2;
+ }
+ const useGpuBatch =
+ !useWireframeEraser &&
+ (bs.customTipImage
+ ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
+ : (!isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts))));
+
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+
+ const collabActive = Boolean(currentStrokeIdRef.current && onCollabStrokeChunkRef.current);
+ const chunkPts: Point[] | null = collabActive ? [] : null;
+ let drewAnySegment = false;
+
+ pipeline.drain({
+ dirtyPadExtra,
+ resolvePoint: (rawX, rawY, rawPressure, stabPressure, pointerType, _vx, _vy, dtMs, out) => {
+ let velocityScale = 1.0;
+ if (bs.velocityDynamics && stabilizedPointRef.current) {
+ const dist = Math.hypot(rawX - stabilizedPointRef.current.x, rawY - stabilizedPointRef.current.y);
+ const speed = dist / Math.max(1, dtMs);
+ velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
+ }
- const pendingSync = pendingBatchSyncRectRef.current as { minX: number; minY: number; maxX: number; maxY: number } | null;
- pendingBatchSyncRectRef.current = null;
- if (pendingSync && drewDirectlyOnLayerCanvasRef.current) {
- const canvas = getActiveCanvas();
- const canvasCtx = canvas ? get2DContext(canvas) : null;
- if (canvas && canvasCtx) {
- const currentLayerId = activeLayerIdRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonochrome = colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- const isEraser = toolRef.current === 'eraser';
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- syncLiveRegionToTiles(
- canvas,
- canvasCtx,
- currentLayerId,
- pendingSync.minX,
- pendingSync.minY,
- pendingSync.maxX,
- pendingSync.maxY,
+ const baseP = bs.usePressure
+ ? (hasCustomCurve ? stabPressure : taperEngine.mapPressure(stabPressure))
+ : (rawPressure > 0 ? 1.0 : 0);
+ const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
+ let width = calculateStrokeWidth(
+ bs.size,
+ mappedP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ velocityScale,
+ bs.pressureCurve
+ );
+ if (isMonochrome && width < 1.25) {
+ width = 1.25;
+ }
+ out.pressure = mappedP;
+ out.width = width;
+ },
+ onPoint: (sample) => {
+ const pt: Point = {
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ };
+ if (allStrokePointsRef.current.length > 0) {
+ const prev = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
+ strokeTotalDistanceRef.current += Math.hypot(pt.x - prev.x, pt.y - prev.y);
+ }
+ stabilizedPointRef.current = pt;
+ lastPointTimeRef.current = sample.timestamp;
+ allStrokePointsRef.current.push(pt);
+ recentPointsTrailRef.current.push({
+ x: pt.x,
+ y: pt.y,
+ t: sample.timestamp || performance.now(),
+ pressure: pt.pressure,
+ width: pt.width,
+ });
+ if (recentPointsTrailRef.current.length > 16) {
+ recentPointsTrailRef.current.shift();
+ }
+ if (chunkPts) {
+ chunkPts.push(pt);
+ }
+ },
+ onSegment: (seg) => {
+ drewAnySegment = true;
+ emitLiveSegment(
+ draftCtx,
+ seg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
isMonochrome,
- activeLayer,
- brushSettingsRef.current,
+ isPencil,
isEraser,
- isBgEraser
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuBatch ? gpuBatch : undefined
);
+ },
+ });
+
+ // Flush the entire frame's GPU dab batch in a single WebGlBrushEngine FBO instanced draw call
+ if (useGpuBatch && gpuBatch.length > 0) {
+ const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ let flushed = false;
+ if (bs.customTipImage && liveTipOpts) {
+ flushed = flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
+ } else if (liveRadialOpts) {
+ flushed = flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, liveRadialOpts);
+ }
+ if (!flushed) {
+ // Rare context-lost fallback: draw recent points onto draftCtx via Canvas 2D
+ const pts = allStrokePointsRef.current;
+ if (pts.length >= 2) {
+ const pA = pts[pts.length - 2];
+ const pB = pts[pts.length - 1];
+ const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
+ emitLiveSegment(
+ draftCtx,
+ fallbackSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ undefined
+ );
+ }
}
+ gpuBatch.length = 0;
}
- if (batchMinX <= batchMaxX) {
+ // Mirror StrokePipeline dirtyRect bounds
+ const pDirty = pipeline.dirtyRect;
+ if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
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));
-
- if (dirtyRectRef.current) {
- dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, segMinX);
- dirtyRectRef.current.minY = Math.min(dirtyRectRef.current.minY, segMinY);
- dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, segMaxX);
- dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, segMaxY);
+ if (!dirtyRectRef.current) {
+ dirtyRectRef.current = {
+ minX: Math.max(0, pDirty.minX),
+ minY: Math.max(0, pDirty.minY),
+ maxX: Math.min(dims.width, pDirty.maxX),
+ maxY: Math.min(dims.height, pDirty.maxY),
+ };
+ } else {
+ dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, pDirty.minX));
+ dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, pDirty.minY));
+ dirtyRectRef.current.maxX = Math.min(dims.width, Math.max(dirtyRectRef.current.maxX, pDirty.maxX));
+ dirtyRectRef.current.maxY = Math.min(dims.height, Math.max(dirtyRectRef.current.maxY, pDirty.maxY));
}
}
- if (currentStrokeIdRef.current && chunkPts.length > 0) {
+ if (drewAnySegment) {
+ (draftCanvas as any).__draftHasContent = true;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
+ liveNeedsNotifyRef.current = true;
+ }
+
+ if (currentStrokeIdRef.current && chunkPts && chunkPts.length > 0) {
onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
}
@@ -2232,29 +1978,30 @@ export function useCanvasDrawing({
globalTileGrid.notifyChange();
}
- // Update predicted stroke overlay throttled to rAF
+ // Update ephemeral predicted stroke overlay throttled to rAF
const predData = latestPredictedRef.current;
latestPredictedRef.current = null;
const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0 && !drewDirectlyOnLayerCanvasRef.current) {
+ if (vRect && allStrokePointsRef.current.length > 0) {
renderPredictedStroke(predData ? predData.predEvents : [], vRect);
} else if (isPredictedCanvasDirtyRef.current) {
clearPredictedCanvas();
}
}, [
- applyStabilizedPointAndRender,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
clearPredictedCanvas,
effectiveDraftCanvasRef,
+ emitLiveSegment,
getActiveCanvas,
getViewportRect,
renderPredictedStroke,
- syncLiveRegionToTiles,
+ resolveStrokeColor,
]);
-
- // Pointer Down handler: initialize lightweight live stroke overlay without touching base canvas
+ // Pointer Down handler: initialize lightweight draft surface & StrokePipeline without touching base canvas or getImageData
const handlePointerDown = useCallback(
- (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
+ (e: React.PointerEvent<HTMLElement>, _coalescedEvents?: PointerEvent[]) => {
const isBrushOrEraser = toolRef.current === 'brush' || toolRef.current === 'eraser';
if (!isBrushOrEraser || disabled || e.button !== 0 || activeLayerLockedRef.current || !activeLayerVisibleRef.current) return;
e.preventDefault();
@@ -2266,6 +2013,9 @@ export function useCanvasDrawing({
const canvas = getActiveCanvas();
if (!canvas) return;
+ if (viewportRef.current) {
+ cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
+ }
const vRect = getViewportRect();
if (!vRect) return;
@@ -2273,12 +2023,6 @@ export function useCanvasDrawing({
const draftCanvas = effectiveDraftCanvasRef?.current;
if (!draftCanvas) return;
- // Update cached viewport rect on stroke start
- if (viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
-
- // Cancel any pending clear rAF from previous stroke and reset draft canvas immediately
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
clearDraftRafRef.current = null;
@@ -2287,48 +2031,83 @@ export function useCanvasDrawing({
const draftCtx = get2DContext(draftCanvas);
if (!draftCtx) return;
- // Reset and clear draft canvas with viewport transform
- draftCtx.resetTransform();
- draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ const isEraser = toolRef.current === 'eraser';
+ const currentLayerId = activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const allLayers = layersRef.current || [];
+ const activeLayer = allLayers.find((l) => l.id === currentLayerId);
+ const bs = brushSettingsRef.current;
+ const mode = colorModeRef.current;
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isTone = Boolean(activeLayer?.toneEnabled);
+ const isVectorLayer = activeLayer?.type === 'vector';
+ const isVectorOrToneOrMask = isVectorLayer || isTone || isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
+ isToneStrokeRef.current = isTone;
- const scaleX = draftCanvas.width / vRect.width;
- const scaleY = draftCanvas.height / vRect.height;
- const matrix = getCanvasToViewportMatrix(
+ // Configure GPU in-stack draft composite mode for ViewportCompositor (zero getImageData!)
+ const draftCompositeOp: GlobalCompositeOperation =
+ isVectorOrToneOrMask || isBgEraser
+ ? 'source-over'
+ : isEraser || bs.isTransparentInk
+ ? 'destination-out'
+ : activeLayer?.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ // Size draftCanvas in document space covering the visible document region (1:1 document pixels up to 2048px)
+ // Guarantees 100% live-vs-baked parity at any zoom level with zero getImageData!
+ const rawVis = getVisibleCanvasBounds(
+ vRect,
panRef.current,
zoomRef.current,
rotationRef.current,
- dimensionsRef.current,
- scaleX,
- scaleY
+ dims,
+ 128,
+ flipXRef.current,
+ flipYRef.current
);
- draftCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
+ const visMinX = rawVis.maxX > rawVis.minX ? rawVis.minX : 0;
+ const visMinY = rawVis.maxY > rawVis.minY ? rawVis.minY : 0;
+ const visW = Math.max(1, rawVis.maxX > rawVis.minX ? rawVis.maxX - rawVis.minX : dims.width);
+ const visH = Math.max(1, rawVis.maxY > rawVis.minY ? rawVis.maxY - rawVis.minY : dims.height);
+ const MAX_DRAFT_DIM = 2048;
+ const draftScale = Math.min(1.0, MAX_DRAFT_DIM / Math.max(visW, visH));
+ const surfaceW = Math.max(1, Math.ceil(visW * draftScale));
+ const surfaceH = Math.max(1, Math.ceil(visH * draftScale));
+ if (draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH) {
+ draftCanvas.width = surfaceW;
+ draftCanvas.height = surfaceH;
+ }
+
+ draftCtx.resetTransform();
+ draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ (draftCanvas as any).__draftHasContent = false;
+ (draftCanvas as any).__draftCompositeOp = draftCompositeOp;
+ (draftCanvas as any).__draftSpace = 'document';
+ (draftCanvas as any).__draftDocRect = {
+ x: visMinX,
+ y: visMinY,
+ width: surfaceW / draftScale,
+ height: surfaceH / draftScale,
+ };
+ (draftCanvas as any).__draftScale = draftScale;
+ (draftCanvas as any).__draftMonochrome = isMonochrome;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
+
+ draftCtx.setTransform(draftScale, 0, 0, draftScale, -visMinX * draftScale, -visMinY * draftScale);
draftCtx.save();
draftCtx.beginPath();
- draftCtx.rect(0, 0, dimensionsRef.current.width, dimensionsRef.current.height);
+ draftCtx.rect(0, 0, dims.width, dims.height);
draftCtx.clip();
applySelectionCanvasClip(draftCtx, selectionRef.current);
clearPredictedCanvas();
- const isEraser = toolRef.current === 'eraser';
- const isBgEraser = isEraser && isBackgroundLayerId(activeLayerIdRef.current);
-
- const currentLayerId = activeLayerIdRef.current;
- const allLayers = layersRef.current || [];
- const activeIdx = allLayers.findIndex((l) => l.id === currentLayerId);
- const activeLayer = activeIdx >= 0 ? allLayers[activeIdx] : undefined;
- const bs = brushSettingsRef.current;
- const mode = colorModeRef.current;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
-
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isTone = Boolean(activeLayer?.toneEnabled);
- isToneStrokeRef.current = isTone;
-
- let sourceCanvas: HTMLCanvasElement | null = null;
if (isTone) {
- sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
+ let sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
if (!sourceCanvas && canvas) {
sourceCanvas = document.createElement('canvas');
sourceCanvas.width = canvas.width;
@@ -2347,29 +2126,37 @@ export function useCanvasDrawing({
activePointerIdRef.current = e.pointerId;
isDrawingRef.current = true;
- const rawCoalesced = coalescedEvents ?? (e as any).coalescedEvents ?? (typeof e.nativeEvent?.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : null);
- const events: PointerEvent[] = (rawCoalesced && rawCoalesced.length > 0) ? Array.from(rawCoalesced) : [e.nativeEvent];
- const firstEvent = events[0] || e.nativeEvent;
+ // Always anchor pointerdown strictly to e.nativeEvent so the stroke begins at the
+ // exact center of the brush cursor ring even if Windows/WebView2 stylus drivers emit
+ // stale or DPI-offset coalesced packets on pointerdown.
+ const firstEvent = e.nativeEvent;
const rawStartPoint = getCanvasPoint(firstEvent);
const isAltOverride = e.altKey;
const startPoint = snapSessionRef.current.snapPoint(rawStartPoint, rulerRef.current, isAltOverride);
emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
- inputStabilizerRef.current.reset();
- inputStabilizerRef.current.setStabilizerLevel(bs.stabilization ?? 0);
- inputStabilizerRef.current.setZoomScale(zoomRef.current || 1.0);
- inputStabilizerRef.current.setSharpCorners(bs.sharpCorners !== false);
- taperEngineRef.current.reset();
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
+ const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const pipeline = strokePipelineRef.current;
+ pipeline.beginStroke({
+ stabilizerLevel: bs.stabilization ?? 0,
+ zoom: zoomRef.current || 1.0,
+ sharpCorners: bs.sharpCorners !== false,
+ brushSize: bs.size,
+ color: strokeColor,
+ pointerId: e.pointerId,
+ });
const startNow = startPoint.timestamp ?? performance.now();
lastPointTimeRef.current = startNow;
- if ((bs.stabilization ?? 0) > 0) {
- inputStabilizerRef.current.process(startPoint.x, startPoint.y, startPoint.pressure, startNow);
- }
const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
if (bs.usePressure) {
- const baseStartP = hasCustomCurve ? startPoint.pressure : taperEngineRef.current.mapPressure(startPoint.pressure);
- const smoothStartP = taperEngineRef.current.smoothPressure(baseStartP);
+ const baseStartP = hasCustomCurve ? startPoint.pressure : taperEngine.mapPressure(startPoint.pressure);
+ const smoothStartP = taperEngine.smoothPressure(baseStartP);
startPoint.pressure = smoothStartP;
startPoint.width = calculateStrokeWidth(
bs.size,
@@ -2382,6 +2169,16 @@ export function useCanvasDrawing({
bs.pressureCurve
);
}
+ if (isMonochrome && startPoint.width < 1.25) {
+ startPoint.width = 1.25;
+ }
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * (startPoint.width * 1.5);
+ const r = Math.max(
+ 32,
+ Math.ceil(Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32)
+ );
// CSP Shift + Click Straight Line from previous stroke end on the same layer
const prevStrokeEnd = lastStrokeEndRef.current;
@@ -2414,29 +2211,22 @@ export function useCanvasDrawing({
timestamp: startNow - 8,
};
allStrokePointsRef.current = [pLineStart, pLineMid, startPoint];
- strokePointsRef.current = [pLineStart, pLineMid];
+ pipeline.seedKnot(pLineStart.x, pLineStart.y, pLineStart.pressure, pLineStart.width, pLineStart.tiltX ?? 0, pLineStart.tiltY ?? 0, pLineStart.twist ?? 0, pLineStart.timestamp ?? 0, r);
+ pipeline.seedKnot(pLineMid.x, pLineMid.y, pLineMid.pressure, pLineMid.width, pLineMid.tiltX ?? 0, pLineMid.tiltY ?? 0, pLineMid.twist ?? 0, pLineMid.timestamp ?? 0, r);
} else {
allStrokePointsRef.current = [startPoint];
- strokePointsRef.current = [startPoint];
+ pipeline.seedKnot(startPoint.x, startPoint.y, startPoint.pressure, startPoint.width, startPoint.tiltX ?? 0, startPoint.tiltY ?? 0, startPoint.twist ?? 0, startNow, r);
}
- rawPointsBufferRef.current = [{
- x: startPoint.x,
- y: startPoint.y,
- pressure: startPoint.pressure,
- pointerType: firstEvent.pointerType,
- tiltX: startPoint.tiltX ?? 0,
- tiltY: startPoint.tiltY ?? 0,
- twist: startPoint.twist ?? 0,
- timestamp: startPoint.timestamp,
- }];
stabilizedPointRef.current = { ...startPoint };
- lastProcessedPointRef.current = { x: startPoint.x, y: startPoint.y };
- pendingPointsQueueRef.current = [];
+ lastProcessedPointRef.current.x = startPoint.x;
+ lastProcessedPointRef.current.y = startPoint.y;
+ hasLastProcessedPointRef.current = true;
+ lastQueuedPressureRef.current = startPoint.pressure;
recentPointsTrailRef.current = [{
x: startPoint.x,
y: startPoint.y,
- t: performance.now(),
+ t: startNow,
pressure: startPoint.pressure,
width: startPoint.width,
}];
@@ -2444,38 +2234,8 @@ export function useCanvasDrawing({
? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
: 0;
- if (!isShiftLine && events.length > 1) {
- for (let i = 1; i < events.length; i++) {
- const cEv = events[i];
- const rawPt = getCanvasPoint(cEv);
- const snapped = snapSessionRef.current.processPoint({ x: rawPt.x, y: rawPt.y }, rulerRef.current, isAltOverride);
- let cPressure = 0;
- if (cEv.pointerType === 'mouse') {
- cPressure = (cEv.buttons & 1) ? 0.5 : 0;
- } else {
- cPressure = cEv.pressure !== undefined ? Math.max(0, Math.min(1.0, cEv.pressure)) : 0;
- }
- pendingPointsQueueRef.current.push({
- x: snapped.x,
- y: snapped.y,
- pressure: cPressure,
- pointerType: cEv.pointerType,
- tiltX: cEv.tiltX ?? 0,
- tiltY: cEv.tiltY ?? 0,
- twist: cEv.twist ?? 0,
- timestamp: cEv.timeStamp,
- });
- }
- }
-
dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const blurMargin = (1 - (bs.hardness ?? 1.0)) * (startPoint.width * 1.5);
- const r = Math.max(
- 32,
- Math.ceil(Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32)
- );
const minInitX = isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
const minInitY = isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
const maxInitX = isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
@@ -2486,6 +2246,12 @@ export function useCanvasDrawing({
maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
};
+ pipeline.expandDirtyRectBounds(
+ dirtyRectRef.current.minX,
+ dirtyRectRef.current.minY,
+ dirtyRectRef.current.maxX,
+ dirtyRectRef.current.maxY
+ );
touchedTilesRef.current.clear();
markTouchedTiles(
dirtyRectRef.current.minX,
@@ -2494,59 +2260,15 @@ export function useCanvasDrawing({
dirtyRectRef.current.maxY
);
- let strokeColor: string;
- if (isMaskModeRef.current) {
- if (isEraser) {
- strokeColor = '#000000';
- } else {
- let clean = bs.color.replace('#', '');
- if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
- const cr = parseInt(clean.slice(0, 2), 16) || 0;
- const cg = parseInt(clean.slice(2, 4), 16) || 0;
- const cb = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * cr + 0.587 * cg + 0.114 * cb);
- const hexVal = gray.toString(16).padStart(2, '0');
- strokeColor = `#${hexVal}${hexVal}${hexVal}`;
- }
- } else {
- strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- }
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = bs.flow ?? 1.0;
-
const isWetColor = !isEraser && Boolean(bs.colorMixing);
isWetColorStrokeRef.current = isWetColor;
- liveOrigCanvasTilesRef.current.clear();
- liveBeforeTileSnapshotRef.current.clear();
liveNeedsNotifyRef.current = false;
- strokeBackupCanvasRef.current = null;
-
- const useDirectLayerPreview =
- !isTone &&
- activeLayer?.type !== 'vector' &&
- !isMaskModeRef.current;
-
- drewDirectlyOnLayerCanvasRef.current = useDirectLayerPreview;
- const needsIsolation = useDirectLayerPreview && (bs.opacity ?? 1.0) < 0.999;
- liveStrokeIsolationRef.current = needsIsolation;
- if (needsIsolation) {
- if (
- !liveAccumCanvasRef.current ||
- liveAccumCanvasRef.current.width !== canvas.width ||
- liveAccumCanvasRef.current.height !== canvas.height
- ) {
- liveAccumCanvasRef.current = document.createElement('canvas');
- liveAccumCanvasRef.current.width = canvas.width;
- liveAccumCanvasRef.current.height = canvas.height;
- }
- }
if (isWetColor && canvas) {
layerPixelSamplerRef.current = new LayerPixelSampler(
canvas,
- activeLayerIdRef.current,
- globalTileGrid,
- liveOrigCanvasTilesRef.current
+ currentLayerId,
+ globalTileGrid
);
activeReservoirRef.current = new PaintReservoir(strokeColor);
} else {
@@ -2556,148 +2278,195 @@ export function useCanvasDrawing({
const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
currentStrokeIdRef.current = strokeId;
- onCollabStrokeStartRef.current?.(strokeId, activeLayerIdRef.current, bs, toolRef.current, startPoint);
+ onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, toolRef.current, startPoint);
liveDabCounterRef.current.count = 0;
stampRemainderDistRef.current = bs.customTipImage
? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
+ : isPencil
+ ? Math.max(0.25, startPoint.width * (bs.spacing ?? 0.07))
: Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
const firstDotPoint = allStrokePointsRef.current[0];
- const drawInitialDotToCtx = (targetCtx: CanvasRenderingContext2D, isolatedPass: boolean) => {
+ // Draw initial dot strictly onto draftCanvas (GPU instanced batch or Canvas 2D fallback) — ZERO getImageData!
+ if (useWireframeEraser) {
+ draftCtx.save();
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.setLineDash([3, 3]);
+ draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
+ draftCtx.beginPath();
+ draftCtx.arc(firstDotPoint.x, firstDotPoint.y, Math.max(1, firstDotPoint.width / 2), 0, Math.PI * 2);
+ draftCtx.stroke();
+ draftCtx.restore();
+ } else {
+ const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+
if (bs.customTipImage) {
const tipOptions = buildLiveTexturedOptions(
bs,
- bs.flow ?? 0.85,
- bs.spacing ?? 0.08,
+ isMonochrome ? 1.0 : (bs.flow ?? 1.0),
+ strokeSpacing,
strokeHardness,
- isMonochrome,
+ downscaledBinary ? false : isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- isolatedPass
- );
- drawTexturedDot(
- targetCtx,
- firstDotPoint,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
- bs.customTipImage,
- tipOptions
+ true
);
+ if (downscaledBinary && tipOptions.antiAlias === 0) {
+ tipOptions.antiAlias = 2;
+ }
+ const useGpu = canUseWebGlForTexturedBrush(tipOptions);
+ drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions, useGpu ? gpuBatch : undefined);
+ if (useGpu && gpuBatch.length > 0) {
+ if (!flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, tipOptions)) {
+ drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions);
+ }
+ gpuBatch.length = 0;
+ }
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilDot(
- targetCtx,
+ draftCtx,
firstDotPoint,
- strokeColor,
+ liveColor,
grade,
isMonochrome ? 1.0 : (bs.flow ?? 0.74),
bs.grain ?? 1.0,
strokeHardness,
- isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isolatedPass ? false : Boolean(bs.isTransparentInk)
+ false,
+ false
);
} else {
- const radialMixingOptions = buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- isolatedPass
- );
+ const radialMixingOptions = buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true);
+ if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
+ radialMixingOptions.antiAlias = 2;
+ }
+ const useGpu = canUseWebGlForRadialBrush(radialMixingOptions);
drawDot(
- targetCtx,
+ draftCtx,
firstDotPoint,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
- isolatedPass ? false : isEraser && !isBgEraser,
+ liveColor,
+ false,
strokeHardness,
- isMonochrome ? 1.0 : strokeFlow,
+ strokeFlow,
radialMixingOptions,
bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ useGpu ? gpuBatch : undefined
);
- }
- };
-
- if (useDirectLayerPreview) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- const d = dirtyRectRef.current;
- ensureLiveTileSnapshots(canvas, cCtx, currentLayerId, d.minX, d.minY, d.maxX, d.maxY);
- if (needsIsolation && liveAccumCanvasRef.current) {
- const accCtx = get2DContext(liveAccumCanvasRef.current);
- if (accCtx) {
- accCtx.save();
- accCtx.beginPath();
- accCtx.rect(d.minX, d.minY, Math.max(1, d.maxX - d.minX), Math.max(1, d.maxY - d.minY));
- accCtx.clip();
- applySelectionCanvasClip(accCtx, selectionRef.current);
- drawInitialDotToCtx(accCtx, true);
- accCtx.restore();
+ if (useGpu && gpuBatch.length > 0) {
+ if (!flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, radialMixingOptions)) {
+ drawDot(
+ draftCtx,
+ firstDotPoint,
+ liveColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ radialMixingOptions,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180
+ );
}
- } else {
- cCtx.save();
- cCtx.beginPath();
- cCtx.rect(d.minX, d.minY, Math.max(1, d.maxX - d.minX), Math.max(1, d.maxY - d.minY));
- cCtx.clip();
- applySelectionCanvasClip(cCtx, selectionRef.current);
- drawInitialDotToCtx(cCtx, false);
- cCtx.restore();
+ gpuBatch.length = 0;
}
- syncLiveRegionToTiles(
- canvas,
- cCtx,
- currentLayerId,
- firstDotPoint.x - r,
- firstDotPoint.y - r,
- firstDotPoint.x + r,
- firstDotPoint.y + r,
- isMonochrome,
- activeLayer,
- bs,
- isEraser,
- isBgEraser
- );
- if (isShiftLine) {
- renderDraftSegment(draftCtx, startPoint);
- }
- globalTileGrid.notifyChange();
- liveNeedsNotifyRef.current = false;
}
- } else if (isEraser && !isBgEraser) {
- draftCtx.save();
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.setLineDash([3, 3]);
- draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
- draftCtx.beginPath();
- draftCtx.arc(firstDotPoint.x, firstDotPoint.y, Math.max(1, firstDotPoint.width / 2), 0, Math.PI * 2);
- draftCtx.stroke();
- draftCtx.restore();
- if (isShiftLine) {
- renderDraftSegment(draftCtx, startPoint);
+ }
+
+ if (isShiftLine && prevStrokeEnd) {
+ const lineSeg = pipeline.getSplineGenerator().generateCornerSegment(allStrokePointsRef.current[0], startPoint);
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveTipOpts = bs.customTipImage
+ ? buildLiveTexturedOptions(bs, isMonochrome ? 1.0 : (bs.flow ?? 1.0), strokeSpacing, strokeHardness, downscaledBinary ? false : isMonochrome, canvas, activeLayer, isEraser, isBgEraser, true)
+ : null;
+ if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
+ liveTipOpts.antiAlias = 2;
}
- } else {
- drawInitialDotToCtx(draftCtx, false);
- if (isShiftLine) {
- renderDraftSegment(draftCtx, startPoint);
+ const liveRadialOpts = !bs.customTipImage && !isPencil
+ ? buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true)
+ : null;
+ if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
+ liveRadialOpts.antiAlias = 2;
+ }
+ const useGpuLine =
+ !useWireframeEraser &&
+ (bs.customTipImage
+ ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
+ : (!isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts))));
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+ emitLiveSegment(
+ draftCtx,
+ lineSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuLine ? gpuBatch : undefined
+ );
+ if (useGpuLine && gpuBatch.length > 0) {
+ const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ if (bs.customTipImage && liveTipOpts) {
+ flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
+ } else if (liveRadialOpts) {
+ flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, liveRadialOpts);
+ }
+ gpuBatch.length = 0;
}
+ pipeline.seedKnot(startPoint.x, startPoint.y, startPoint.pressure, startPoint.width, startPoint.tiltX ?? 0, startPoint.tiltY ?? 0, startPoint.twist ?? 0, startNow, r);
}
- if (pendingPointsQueueRef.current.length > 0 && drawRafIdRef.current === null) {
+ (draftCanvas as any).__draftHasContent = true;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
+ globalTileGrid.notifyChange();
+ liveNeedsNotifyRef.current = false;
+
+ if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
}
},
- [buildLiveRadialOptions, buildLiveTexturedOptions, clearPredictedCanvas, disabled, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, ensureLiveTileSnapshots, flushPendingHistoryTasks, flushPendingPoints, getActiveCanvas, getCanvasPoint, getViewportRect, markTouchedTiles, renderDraftSegment, syncLiveRegionToTiles, viewportRef]
+ [
+ abortActiveStroke,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
+ clearPredictedCanvas,
+ disabled,
+ dispatchPointerStat,
+ effectiveDraftCanvasRef,
+ emitConstraintAxisChange,
+ emitLiveSegment,
+ flushPendingHistoryTasks,
+ flushPendingPoints,
+ getActiveCanvas,
+ getCanvasPoint,
+ getViewportRect,
+ layerSourceCanvasesRef,
+ markTouchedTiles,
+ resolveStrokeColor,
+ viewportRef,
+ ]
);
- // Pointer Move handler: throttled & batched coordinate ingestion via rAF with coalesced and predicted events
+ // Pointer Move handler: zero-allocation ingestion of getCoalescedEvents() & getPredictedEvents() into StrokePipeline ring buffer
const handlePointerMove = useCallback(
(
e: React.PointerEvent<HTMLElement>,
coalescedEvents?: PointerEvent[],
- _predictedEvents?: PointerEvent[]
+ predictedEvents?: PointerEvent[]
) => {
if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
const point = getCanvasPoint(e);
@@ -2712,41 +2481,68 @@ export function useCanvasDrawing({
if (!vRect) return;
const dims = dimensionsRef.current;
- const rawCoalesced =
+ const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =
coalescedEvents ??
(e as any).coalescedEvents ??
(typeof e.nativeEvent?.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : null);
- const events: PointerEvent[] =
- rawCoalesced && rawCoalesced.length > 0 ? Array.from(rawCoalesced) : [e.nativeEvent];
+ let rawCoalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
+ if (candidateCoalesced && candidateCoalesced.length > 0) {
+ const lastC = candidateCoalesced[candidateCoalesced.length - 1];
+ const nativeEvt = e.nativeEvent;
+ if (
+ lastC &&
+ nativeEvt &&
+ Number.isFinite(lastC.clientX) &&
+ Number.isFinite(lastC.clientY) &&
+ Math.hypot(lastC.clientX - nativeEvt.clientX, lastC.clientY - nativeEvt.clientY) <= 1.5
+ ) {
+ rawCoalesced = candidateCoalesced;
+ }
+ }
+ const count = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced.length : 1;
+ const pipeline = strokePipelineRef.current;
+ const scratch = scratchDocCoordRef.current;
+ const lastProc = lastProcessedPointRef.current;
const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, zoomRef.current));
+ const isAltOverride = e.altKey;
+ const isShiftKey = e.shiftKey;
+ const ruler = rulerRef.current;
+ const curPan = panRef.current;
+ const curZoom = zoomRef.current;
+ const curRot = rotationRef.current;
+ const curFlipX = flipXRef.current;
+ const curFlipY = flipYRef.current;
+
let lastQueuedX = 0;
let lastQueuedY = 0;
- let lastQueuedPressure = 0.5;
+ let lastQueuedPressure = lastQueuedPressureRef.current;
let hasQueued = false;
- for (let i = 0; i < events.length; i++) {
- const cEvent = events[i];
- const rawCoords = screenToCanvas(
+ for (let i = 0; i < count; i++) {
+ const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
+ screenToCanvasInto(
cEvent.clientX,
cEvent.clientY,
vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims
+ curPan,
+ curZoom,
+ curRot,
+ dims,
+ scratch,
+ curFlipX,
+ curFlipY
);
- const isAltOverride = e.altKey;
- const snapRes = snapSessionRef.current.processPoint(rawCoords, rulerRef.current, isAltOverride);
+ const snapRes = snapSessionRef.current.processPoint(scratch, ruler, isAltOverride);
let cx = snapRes.x;
let cy = snapRes.y;
if (snapRes.axis) {
emitConstraintAxisChange(snapRes.axis);
} else if (
!isShiftLineStrokeRef.current &&
- e.shiftKey &&
- !rulerRef.current?.enabled &&
+ isShiftKey &&
+ !ruler?.enabled &&
allStrokePointsRef.current.length > 0
) {
const originPt = allStrokePointsRef.current[0];
@@ -2767,35 +2563,43 @@ export function useCanvasDrawing({
cPressure = cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
}
- const last = lastProcessedPointRef.current;
if (
- last &&
- Math.hypot(cx - last.x, cy - last.y) < minStepDoc &&
+ hasLastProcessedPointRef.current &&
+ Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&
Math.abs(cPressure - lastQueuedPressure) <= 0.04
) {
continue;
}
- lastProcessedPointRef.current = { x: cx, y: cy };
-
- 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,
- });
+ lastProc.x = cx;
+ lastProc.y = cy;
+ hasLastProcessedPointRef.current = true;
+
+ pipeline.enqueueSample(
+ cx,
+ cy,
+ cPressure,
+ cEvent.tiltX ?? 0,
+ cEvent.tiltY ?? 0,
+ cEvent.twist ?? 0,
+ cEvent.timeStamp,
+ encodePointerType(cEvent.pointerType)
+ );
lastQueuedX = cx;
lastQueuedY = cy;
lastQueuedPressure = cPressure;
hasQueued = true;
}
- if (_predictedEvents && _predictedEvents.length > 0) {
- latestPredictedRef.current = { predEvents: _predictedEvents, vRect };
+ lastQueuedPressureRef.current = lastQueuedPressure;
+
+ const rawPredicted =
+ predictedEvents ??
+ (e as any).predictedEvents ??
+ (typeof e.nativeEvent?.getPredictedEvents === 'function' ? e.nativeEvent.getPredictedEvents() : null);
+
+ if (rawPredicted && rawPredicted.length > 0) {
+ latestPredictedRef.current = { predEvents: rawPredicted, vRect };
} else {
latestPredictedRef.current = null;
}
@@ -2805,14 +2609,14 @@ export function useCanvasDrawing({
onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, toolRef.current);
}
- if (pendingPointsQueueRef.current.length > 0 && drawRafIdRef.current === null) {
+ if ((pipeline.getPendingCount() > 0 || latestPredictedRef.current !== null) && drawRafIdRef.current === null) {
drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
}
},
[dispatchPointerStat, emitConstraintAxisChange, flushPendingPoints, getCanvasPoint, getViewportRect]
);
- // Pointer Up / Cancel handler: composite and bake stroke into high-res canvas at dirty rect
+ // Pointer Up / Cancel handler: finalize StrokePipeline, bake dirty rect ONCE into base layer + SparseTileGrid + Undo delta
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLElement>) => {
if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
@@ -2828,7 +2632,7 @@ export function useCanvasDrawing({
} catch {}
}
- // Cancel any pending rAF and flush remaining points synchronously
+ // Cancel any pending rAF and flush remaining buffered points synchronously
if (drawRafIdRef.current !== null) {
cancelAnimationFrame(drawRafIdRef.current);
drawRafIdRef.current = null;
@@ -2838,15 +2642,12 @@ export function useCanvasDrawing({
const bs = brushSettingsRef.current;
const endPoint = getCanvasPoint(e);
const draftCanvas = effectiveDraftCanvasRef?.current;
- const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
const canvas = getActiveCanvas();
if (canvas) {
(canvas as any).__isBlank = false;
(canvas as any).__isSolidWhite = false;
}
- // Finalize tail segment on draft canvas using Catmull-Rom cubic Bézier
- const pts = strokePointsRef.current;
const currentTool = toolRef.current;
const currentLayerId = activeLayerIdRef.current;
const isEraser = currentTool === 'eraser';
@@ -2860,192 +2661,58 @@ export function useCanvasDrawing({
const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
const isMonochrome = mode === 'monochrome' || isMonoLayer;
const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const targetTailCtx = draftCtx;
-
- let strokeColor: string;
- if (isMaskModeRef.current) {
- if (isEraser) {
- strokeColor = '#000000';
- } else {
- let clean = bs.color.replace('#', '');
- if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
- const r = parseInt(clean.slice(0, 2), 16) || 0;
- const g = parseInt(clean.slice(2, 4), 16) || 0;
- const b = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
- const hexVal = gray.toString(16).padStart(2, '0');
- strokeColor = `#${hexVal}${hexVal}${hexVal}`;
- }
- } else {
- strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- }
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
-
- const renderTailSegmentToCtx = (
- ctx: CanvasRenderingContext2D,
- pPrev: Point,
- c1: Point,
- c2: Point,
- pLast: Point,
- isolatedPass: boolean
- ) => {
- if (bs.customTipImage) {
- const tipOptions = buildLiveTexturedOptions(
- bs,
- bs.flow ?? 0.85,
- bs.spacing ?? 0.08,
- strokeHardness,
- isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- isolatedPass
- );
- stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
- ctx,
- pPrev,
- c1,
- c2,
- pLast,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
- bs.customTipImage,
- tipOptions,
- stampRemainderDistRef.current,
- liveDabCounterRef.current
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- stampRemainderDistRef.current = drawPencilCubicBezierSegment(
- ctx,
- pPrev,
- c1,
- c2,
- pLast,
- strokeColor,
- grade,
- isMonochrome ? 1.0 : (bs.flow ?? 0.74),
- bs.grain ?? 1.0,
- strokeHardness,
- stampRemainderDistRef.current,
- isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isolatedPass ? false : Boolean(bs.isTransparentInk),
- bs.useTilt ?? true
- );
- } else {
- const radialMixingOptions = buildLiveRadialOptions(
- bs,
- isMonochrome,
- canvas,
- activeLayer,
- isolatedPass
- );
- stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
- ctx,
- pPrev,
- c1,
- c2,
- pLast,
- isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
- isolatedPass ? false : isEraser && !isBgEraser,
- strokeHardness,
- isMonochrome ? 1.0 : (bs.flow ?? 1.0),
- bs.spacing ?? 0.08,
- stampRemainderDistRef.current,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- radialMixingOptions
- );
- }
- };
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
- if (pts.length >= 2) {
- const pLast = pts[pts.length - 1];
- const pPrev = pts[pts.length - 2];
- const pPrev2 = pts.length >= 3 ? pts[pts.length - 3] : pPrev;
- const { c1, c2 } = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ const pipeline = strokePipelineRef.current;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const tailPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
+ const enableFlickTaper =
+ !isEraser &&
+ !isShiftLineStrokeRef.current &&
+ activeLayer?.type !== 'vector' &&
+ Boolean(bs.taper?.useOut);
+
+ // Seal final Catmull-Rom segment & optional ballistic exit flick taper in StrokePipeline
+ let addedFlickPoints = false;
+ pipeline.finalizeStroke(e.timeStamp || performance.now(), {
+ enableFlickTaper,
+ dirtyPadExtra: tailPadExtra,
+ onPoint: (sample) => {
+ addedFlickPoints = true;
+ allStrokePointsRef.current.push({
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ });
+ },
+ onSegment: (seg) => {
+ const segPad = Math.ceil(Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32);
+ const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
+ const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
+ const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
+ const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
+ pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);
+ markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
+ },
+ });
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const tailMargin = Math.ceil(
- Math.max(pLast.width, pPrev.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
- );
- const docW = canvas ? canvas.width : dimensionsRef.current.width;
- const docH = canvas ? canvas.height : dimensionsRef.current.height;
- const tMinX = Math.max(0, Math.floor(Math.min(pPrev.x, c1.x, c2.x, pLast.x) - tailMargin));
- const tMinY = Math.max(0, Math.floor(Math.min(pPrev.y, c1.y, c2.y, pLast.y) - tailMargin));
- const tMaxX = Math.min(docW, Math.ceil(Math.max(pPrev.x, c1.x, c2.x, pLast.x) + tailMargin));
- const tMaxY = Math.min(docH, Math.ceil(Math.max(pPrev.y, c1.y, c2.y, pLast.y) + tailMargin));
-
- if (dirtyRectRef.current) {
- dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, tMinX);
- dirtyRectRef.current.minY = Math.min(dirtyRectRef.current.minY, tMinY);
- dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, tMaxX);
- dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, tMaxY);
- }
- markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
-
- if (drewDirectlyOnLayerCanvasRef.current && canvas) {
- const canvasCtx = get2DContext(canvas);
- if (canvasCtx && tMaxX > tMinX && tMaxY > tMinY) {
- ensureLiveTileSnapshots(canvas, canvasCtx, currentLayerId, tMinX, tMinY, tMaxX, tMaxY);
- const clipRw = tMaxX - tMinX;
- const clipRh = tMaxY - tMinY;
- if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
- const accumCtx = get2DContext(liveAccumCanvasRef.current);
- if (accumCtx) {
- accumCtx.save();
- accumCtx.beginPath();
- accumCtx.rect(tMinX, tMinY, clipRw, clipRh);
- accumCtx.clip();
- applySelectionCanvasClip(accumCtx, selectionRef.current);
- renderTailSegmentToCtx(accumCtx, pPrev, c1, c2, pLast, true);
- accumCtx.restore();
- }
- } else {
- canvasCtx.save();
- canvasCtx.beginPath();
- canvasCtx.rect(tMinX, tMinY, clipRw, clipRh);
- canvasCtx.clip();
- applySelectionCanvasClip(canvasCtx, selectionRef.current);
- renderTailSegmentToCtx(canvasCtx, pPrev, c1, c2, pLast, false);
- canvasCtx.restore();
- }
- syncLiveRegionToTiles(
- canvas,
- canvasCtx,
- currentLayerId,
- tMinX,
- tMinY,
- tMaxX,
- tMaxY,
- isMonochrome,
- activeLayer,
- bs,
- isEraser,
- isBgEraser
- );
+ // Merge pipeline dirtyRect with dirtyRectRef
+ const pDirty = pipeline.dirtyRect;
+ const mergedDirty = dirtyRectRef.current
+ ? {
+ minX: Math.min(dirtyRectRef.current.minX, Number.isFinite(pDirty.minX) ? pDirty.minX : dirtyRectRef.current.minX),
+ minY: Math.min(dirtyRectRef.current.minY, Number.isFinite(pDirty.minY) ? pDirty.minY : dirtyRectRef.current.minY),
+ maxX: Math.max(dirtyRectRef.current.maxX, Number.isFinite(pDirty.maxX) ? pDirty.maxX : dirtyRectRef.current.maxX),
+ maxY: Math.max(dirtyRectRef.current.maxY, Number.isFinite(pDirty.maxY) ? pDirty.maxY : dirtyRectRef.current.maxY),
}
- } else if (targetTailCtx) {
- if (isEraser && !isBgEraser) {
- targetTailCtx.save();
- targetTailCtx.lineCap = 'round';
- targetTailCtx.lineJoin = 'round';
- targetTailCtx.setLineDash([4, 4]);
- targetTailCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- targetTailCtx.lineWidth = Math.max(1, (pPrev.width + pLast.width) / 2);
- targetTailCtx.beginPath();
- targetTailCtx.moveTo(pPrev.x, pPrev.y);
- targetTailCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, pLast.x, pLast.y);
- targetTailCtx.stroke();
- targetTailCtx.restore();
- } else {
- renderTailSegmentToCtx(targetTailCtx, pPrev, c1, c2, pLast, false);
- }
- }
- }
+ : (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX) ? { ...pDirty } : null);
- // BAKE STROKE INTO HIGH-RESOLUTION BASE CANVAS (Dirty Rect only)
- const dirty = dirtyRectRef.current;
let exitSpeed = 0;
if (recentPointsTrailRef.current.length >= 2) {
const trail = recentPointsTrailRef.current;
@@ -3054,17 +2721,14 @@ export function useCanvasDrawing({
const pB = trail[trail.length - 1];
const dwellMs = Math.max(0, performance.now() - pB.t);
const dt = Math.max(1, (pB.t - pA.t) + dwellMs);
- const dx = pB.x - pA.x;
- const dy = pB.y - pA.y;
- const dist = Math.hypot(dx, dy);
- exitSpeed = dist / dt;
+ exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
}
- const shouldTaper = Boolean(bs.taper?.useIn) || Boolean(bs.taper?.useOut);
+ const shouldTaper = Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
if (shouldTaper && allStrokePointsRef.current.length >= 3) {
applyParametricTaper(allStrokePointsRef.current, {
useIn: Boolean(bs.taper?.useIn),
- useOut: Boolean(bs.taper?.useOut),
+ useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
minSizeFactor: bs.minSizeFactor,
exitSpeed,
});
@@ -3102,10 +2766,10 @@ 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;
+ let minX = mergedDirty ? mergedDirty.minX : 0;
+ let minY = mergedDirty ? mergedDirty.minY : 0;
+ let maxX = mergedDirty ? mergedDirty.maxX : canvas.width;
+ let maxY = mergedDirty ? mergedDirty.maxY : canvas.height;
for (const st of prevStrokes) {
if (st.bounds) {
minX = Math.min(minX, st.bounds.minX);
@@ -3201,17 +2865,23 @@ export function useCanvasDrawing({
currentStrokeIdRef.current || undefined
);
}
- } else if (canvas && dirty && allPoints.length > 0) {
- const wetMargin = (bs.wetEdge ?? 0) > 0.01 ? Math.ceil((bs.wetEdgeRadius ?? 3.0) * 2 + 8) : 0;
- const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5)) + wetMargin;
- const sx = Math.max(0, Math.floor(dirty.minX - pad));
- const sy = Math.max(0, Math.floor(dirty.minY - pad));
- const maxX = Math.min(canvas.width, Math.ceil(dirty.maxX + pad));
- const maxY = Math.min(canvas.height, Math.ceil(dirty.maxY + pad));
- const dw = maxX - sx;
- const dh = maxY - sy;
-
- if (dw > 0 && dh > 0) {
+ } else if (canvas && mergedDirty && allPoints.length > 0) {
+ const hasWetEdge =
+ !isMonochrome &&
+ !isEraser &&
+ !bs.isTransparentInk &&
+ (bs.wetEdge ?? 0) > 0.01;
+ const clampedBakeRect = computeClampedBakeDirtyRect(
+ mergedDirty,
+ canvas.width,
+ canvas.height,
+ bs.size || 10,
+ hasWetEdge ? (bs.wetEdge ?? 0) : 0,
+ bs.wetEdgeRadius ?? 3.0
+ );
+
+ if (clampedBakeRect) {
+ const { x: sx, y: sy, width: dw, height: dh } = clampedBakeRect;
const ctx = get2DContext(canvas);
if (ctx) {
let label = 'Brush Stroke';
@@ -3233,392 +2903,341 @@ export function useCanvasDrawing({
label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
}
- const dirtyRect = { x: sx, y: sy, width: dw, height: dh };
+ const dirtyRect = clampedBakeRect;
const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
const activeSelection = selectionRef.current;
- const hasWetEdge =
- !isMonochrome &&
- !isEraser &&
- !bs.isTransparentInk &&
- (bs.wetEdge ?? 0) > 0.01;
- const needsPostBake =
- !drewDirectlyOnLayerCanvasRef.current ||
- isMaskModeRef.current ||
- (isToneLayer && Boolean(sourceCanvas)) ||
- hasWetEdge ||
- (((bs.postCorrection ?? 0) > 0 || shouldTaper) && allPoints.length >= 3);
-
- if (!needsPostBake && drewDirectlyOnLayerCanvasRef.current) {
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- sCtx.clearRect(sx, sy, dw, dh);
- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
- }
+
+ if (isMaskModeRef.current) {
+ const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
+ const maskBs: BrushSettings = {
+ ...bs,
+ color: strokeColor,
+ isTransparentInk: false,
+ colorMixing: false,
+ };
+ const maskTool: ToolType = isEraser ? 'brush' : currentTool;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, dw, dh);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
+
+ if ((bs.opacity ?? 1.0) >= 0.999) {
+ renderCompleteStroke(ctx, allPoints, maskBs, maskTool, 'grayscale', false, canvas, false);
+ } else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ ctx.globalCompositeOperation = 'source-over';
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(bCtx, allPoints, { ...maskBs, opacity: 1.0 }, maskTool, 'grayscale', false, canvas, false);
+ bCtx.restore();
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
}
+ ctx.restore();
- const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(
- liveBeforeTileSnapshotRef.current
- );
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
+ if (activeSelection?.mask) {
+ applySelectionMaskToImageData(beforeMaskData, afterMaskData, sx, sy, activeSelection);
+ ctx.putImageData(afterMaskData, sx, sy);
+ }
+ if (activeLayer) {
+ activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
+ }
enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ pushHistoryStep(
+ toolForHistory,
+ 'Layer Mask Stroke',
+ beforeMaskData,
+ afterMaskData,
+ currentLayerId,
+ dirtyRect,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ true
+ );
});
- } else {
- if (drewDirectlyOnLayerCanvasRef.current) {
- restoreLiveOrigTilesToCanvas(canvas);
- for (const [numKey, tileImg] of liveOrigCanvasTilesRef.current) {
- touchedTilesRef.current.add(numKey);
- const ty = Math.floor(numKey / 65536);
- const tx = numKey % 65536;
- globalTileGrid.writeImageData(
- currentLayerId,
- tileImg,
- tx * TILE_SIZE,
- ty * TILE_SIZE,
- targetFormat,
- true
- );
- }
+ } else if (isToneLayer && sourceCanvas) {
+ if (!globalTileGrid.isLayerIngested(currentLayerId)) {
+ globalTileGrid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
}
+ const sCtx = get2DContext(sourceCanvas);
+ const beforeSelectionData =
+ activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (sCtx) {
+ sCtx.save();
+ sCtx.beginPath();
+ sCtx.rect(sx, sy, dw, dh);
+ sCtx.clip();
+ applySelectionCanvasClip(sCtx, activeSelection);
- if (isMaskModeRef.current) {
- const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
- const maskBs: BrushSettings = {
- ...bs,
- color: strokeColor,
- isTransparentInk: false,
- colorMixing: false,
- };
- const maskTool: ToolType = isEraser ? 'brush' : currentTool;
-
- ctx.save();
- ctx.beginPath();
- ctx.rect(sx, sy, dw, dh);
- ctx.clip();
- applySelectionCanvasClip(ctx, activeSelection);
-
- if ((bs.opacity ?? 1.0) >= 0.999) {
- renderCompleteStroke(ctx, allPoints, maskBs, maskTool, 'grayscale', false, canvas, false);
- } else {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- ctx.globalCompositeOperation = 'source-over';
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtx) {
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(bCtx, allPoints, { ...maskBs, opacity: 1.0 }, maskTool, 'grayscale', false, canvas, false);
- bCtx.restore();
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- ctx.restore();
-
- const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
- if (activeSelection?.mask) {
- applySelectionMaskToImageData(beforeMaskData, afterMaskData, sx, sy, activeSelection);
- ctx.putImageData(afterMaskData, sx, sy);
- }
- if (activeLayer) {
- activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
- }
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- 'Layer Mask Stroke',
- beforeMaskData,
- afterMaskData,
- currentLayerId,
- dirtyRect,
- undefined,
- undefined,
- undefined,
- undefined,
- true
- );
- });
- } else if (isToneLayer && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- const beforeSelectionData =
- activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (sCtx) {
- sCtx.save();
- sCtx.beginPath();
- sCtx.rect(sx, sy, dw, dh);
- sCtx.clip();
- applySelectionCanvasClip(sCtx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
- if (!needsIsolatedBake) {
- renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
- } else {
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
- }
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtxBake) {
- bCtxBake.clearRect(0, 0, dw, dh);
- bCtxBake.save();
- bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(
- bCtxBake,
- allPoints,
- { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- sourceCanvas,
- false
- );
- bCtxBake.restore();
- sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- sCtx.restore();
- }
-
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
- applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
- sCtx.putImageData(afterData, sx, sy);
- }
-
- if (activeLayer) {
- const freq = activeLayer?.toneFrequency ?? 60;
- const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
- const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
- const fxX = Math.max(0, sx - cellMargin);
- const fxY = Math.max(0, sy - cellMargin);
- const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
- const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensionsRef.current.dpi ?? 600,
- { x: fxX, y: fxY, width: fxW, height: fxH }
- );
- }
-
- if (afterData) {
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- }
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
-
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- } else {
- const beforeSelectionData =
- activeSelection?.mask ? ctx.getImageData(sx, sy, dw, dh) : null;
-
- ctx.save();
- ctx.beginPath();
- ctx.rect(sx, sy, dw, dh);
- ctx.clip();
- applySelectionCanvasClip(ctx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
-
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
if (!needsIsolatedBake) {
- renderCompleteStroke(ctx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
+ renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
} else {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
+ sCtx.globalCompositeOperation = 'destination-out';
} else if (activeLayer?.alphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
+ sCtx.globalCompositeOperation = 'source-atop';
} else {
- ctx.globalCompositeOperation = 'source-over';
+ sCtx.globalCompositeOperation = 'source-over';
}
const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true, willReadFrequently: hasWetEdge });
- if (bCtx) {
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
+ const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtxBake) {
+ bCtxBake.clearRect(0, 0, dw, dh);
+ bCtxBake.save();
+ bCtxBake.translate(-sx, -sy);
renderCompleteStroke(
- bCtx,
+ bCtxBake,
allPoints,
- {
- ...bs,
- opacity: 1.0,
- isTransparentInk: false,
- wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bs.color,
- },
+ { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
isEraser && !isBgEraser ? 'brush' : currentTool,
effectiveMode,
isBgEraser,
- canvas,
+ sourceCanvas,
false
);
- bCtx.restore();
-
- if (hasWetEdge) {
- const bakeImg = bCtx.getImageData(0, 0, dw, dh);
- applyCspWatercolorEdge(
- bakeImg,
- bs.wetEdge ?? 0,
- bs.wetEdgeRadius ?? 3.0,
- bs.wetEdgeAlphaPower ?? 25,
- bs.wetEdgeValuePower ?? 15
- );
- bCtx.putImageData(bakeImg, 0, 0);
- }
-
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ bCtxBake.restore();
+ sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
}
+ sCtx.restore();
+ }
- ctx.restore();
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
+ applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
+ sCtx.putImageData(afterData, sx, sy);
+ }
- if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = ctx.getImageData(sx, sy, dw, dh);
- applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
- ctx.putImageData(fullAfter, sx, sy);
- }
+ if (activeLayer) {
+ const freq = activeLayer?.toneFrequency ?? 60;
+ const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
+ const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
+ const fxX = Math.max(0, sx - cellMargin);
+ const fxY = Math.max(0, sy - cellMargin);
+ const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
+ const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensionsRef.current.dpi ?? 600,
+ { x: fxX, y: fxY, width: fxW, height: fxH }
+ );
+ }
- const useSparseTileSpans = dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
- if (useSparseTileSpans) {
- const rows = new Map<number, number[]>();
- for (const key of touchedTilesRef.current) {
- const ty = Math.floor(key / 65536);
- const tx = key % 65536;
- let list = rows.get(ty);
- if (!list) {
- list = [];
- rows.set(ty, list);
- }
- list.push(tx);
- }
+ if (afterData) {
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ }
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
- const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
- for (const [ty, txList] of rows) {
- txList.sort((a, b) => a - b);
- let spanStart = txList[0];
- let spanEnd = txList[0];
- for (let i = 1; i < txList.length; i++) {
- if (txList[i] <= spanEnd + 1) {
- spanEnd = txList[i];
- } else {
- const rx = Math.max(0, spanStart * TILE_SIZE);
- const ry = Math.max(0, ty * TILE_SIZE);
- const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
- const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
- spanStart = txList[i];
- spanEnd = txList[i];
- }
- }
- const rx = Math.max(0, spanStart * TILE_SIZE);
- const ry = Math.max(0, ty * TILE_SIZE);
- const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
- const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
- }
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ } else {
+ // Standard raster bake (single pointerup bake + SparseTileGrid write + Undo TileDelta)
+ if (!globalTileGrid.isLayerIngested(currentLayerId)) {
+ globalTileGrid.ingestCanvas(currentLayerId, canvas, targetFormat);
+ }
+
+ const beforeSelectionData =
+ activeSelection?.mask ? ctx.getImageData(sx, sy, dw, dh) : null;
- const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(
- liveBeforeTileSnapshotRef.current
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, dw, dh);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
+
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(ctx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
+ } else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true, willReadFrequently: hasWetEdge });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ canvas,
+ false
);
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, sp);
- for (const [k, v] of subSnap) {
- if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
- }
- const spanData = ctx.getImageData(sp.x, sp.y, sp.width, sp.height);
- if (isMonochrome) {
- binarizeImageDataBuffer(
- spanData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- ctx.putImageData(spanData, sp.x, sp.y);
- }
- globalTileGrid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ bCtx.restore();
+
+ if (hasWetEdge) {
+ const bakeImg = bCtx.getImageData(0, 0, dw, dh);
+ applyCspWatercolorEdge(
+ bakeImg,
+ bs.wetEdge ?? 0,
+ bs.wetEdgeRadius ?? 3.0,
+ bs.wetEdgeAlphaPower ?? 25,
+ bs.wetEdgeValuePower ?? 15
+ );
+ bCtx.putImageData(bakeImg, 0, 0);
}
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- sCtx.clearRect(sp.x, sp.y, sp.width, sp.height);
- sCtx.drawImage(canvas, sp.x, sp.y, sp.width, sp.height, sp.x, sp.y, sp.width, sp.height);
- }
- }
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+
+ ctx.restore();
+
+ if (beforeSelectionData && activeSelection?.mask) {
+ const fullAfter = ctx.getImageData(sx, sy, dw, dh);
+ applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
+ ctx.putImageData(fullAfter, sx, sy);
+ }
+
+ const useSparseTileSpans = dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
+ if (useSparseTileSpans) {
+ const rows = new Map<number, number[]>();
+ for (const key of touchedTilesRef.current) {
+ const ty = Math.floor(key / 65536);
+ const tx = key % 65536;
+ let list = rows.get(ty);
+ if (!list) {
+ list = [];
+ rows.set(ty, list);
+ }
+ list.push(tx);
+ }
+
+ const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
+ for (const [ty, txList] of rows) {
+ txList.sort((a, b) => a - b);
+ let spanStart = txList[0];
+ let spanEnd = txList[0];
+ for (let i = 1; i < txList.length; i++) {
+ if (txList[i] <= spanEnd + 1) {
+ spanEnd = txList[i];
+ } else {
+ const rx = Math.max(0, spanStart * TILE_SIZE);
+ const ry = Math.max(0, ty * TILE_SIZE);
+ const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
+ const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ spanStart = txList[i];
+ spanEnd = txList[i];
}
}
+ const rx = Math.max(0, spanStart * TILE_SIZE);
+ const ry = Math.max(0, ty * TILE_SIZE);
+ const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
+ const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ }
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- } else {
- const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(
- liveBeforeTileSnapshotRef.current
- );
- const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, sp);
for (const [k, v] of subSnap) {
if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
}
-
- const afterData = ctx.getImageData(sx, sy, dw, dh);
+ const spanData = ctx.getImageData(sp.x, sp.y, sp.width, sp.height);
if (isMonochrome) {
binarizeImageDataBuffer(
- afterData,
+ spanData,
activeLayer?.monoThreshold ?? 128,
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
);
- ctx.putImageData(afterData, sx, sy);
+ ctx.putImageData(spanData, sp.x, sp.y);
}
+ globalTileGrid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- sCtx.clearRect(sx, sy, dw, dh);
- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ const sCtx = get2DContext(existingSource);
+ if (sCtx) {
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ sCtx.clearRect(sp.x, sp.y, sp.width, sp.height);
+ sCtx.drawImage(canvas, sp.x, sp.y, sp.width, sp.height, sp.x, sp.y, sp.width, sp.height);
}
}
}
+ }
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ } else {
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = ctx.getImageData(sx, sy, dw, dh);
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ afterData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ ctx.putImageData(afterData, sx, sy);
+ }
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ const sCtx = get2DContext(existingSource);
+ if (sCtx) {
+ sCtx.clearRect(sx, sy, dw, dh);
+ sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ }
+ }
}
+
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
}
}
}
}
}
- // Synchronously notify tile grid compositor AND synchronously clear draft overlay in the same frame (zero double-alpha flash!)
- globalTileGrid.notifyChange(true);
-
+ // Clear draft overlay BEFORE synchronous tile grid notification so in-stack compositor
+ // swaps from live draft to committed tiles in a single atomic frame (zero double-alpha flash!)
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
clearDraftRafRef.current = null;
@@ -3632,42 +3251,43 @@ export function useCanvasDrawing({
dCtx.resetTransform();
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
+ (draftCanvas as any).__draftHasContent = false;
+ (draftCanvas as any).__draftCompositeOp = 'source-over';
+ (draftCanvas as any).__draftMonochrome = false;
+ (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
}
clearPredictedCanvas();
+ globalTileGrid.notifyChange(true);
+
if (currentStrokeIdRef.current) {
onCollabStrokeFinishRef.current?.(
currentStrokeIdRef.current,
currentLayerId,
endPoint,
- dirty ? {
- x: Math.max(0, Math.floor(dirty.minX)),
- y: Math.max(0, Math.floor(dirty.minY)),
- width: Math.max(1, Math.ceil(dirty.maxX) - Math.max(0, Math.floor(dirty.minX))),
- height: Math.max(1, Math.ceil(dirty.maxY) - Math.max(0, Math.floor(dirty.minY))),
+ mergedDirty ? {
+ x: Math.max(0, Math.floor(mergedDirty.minX)),
+ y: Math.max(0, Math.floor(mergedDirty.minY)),
+ width: Math.max(1, Math.ceil(mergedDirty.maxX) - Math.max(0, Math.floor(mergedDirty.minX))),
+ height: Math.max(1, Math.ceil(mergedDirty.maxY) - Math.max(0, Math.floor(mergedDirty.minY))),
} : undefined,
createdVectorStroke
);
currentStrokeIdRef.current = null;
}
+ strokePipelineRef.current.abortStroke();
+ frameGpuDabsRef.current.length = 0;
isDrawingRef.current = false;
activePointerIdRef.current = null;
allStrokePointsRef.current = [];
- strokePointsRef.current = [];
stabilizedPointRef.current = null;
- lastProcessedPointRef.current = null;
+ hasLastProcessedPointRef.current = false;
dirtyRectRef.current = null;
touchedTilesRef.current.clear();
- pendingPointsQueueRef.current = [];
- drewDirectlyOnLayerCanvasRef.current = false;
- liveStrokeIsolationRef.current = false;
- liveOrigCanvasTilesRef.current.clear();
- liveBeforeTileSnapshotRef.current.clear();
liveNeedsNotifyRef.current = false;
isShiftLineStrokeRef.current = false;
isToneStrokeRef.current = false;
- strokeBackupCanvasRef.current = null;
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
snapSessionRef.current.endStroke();
@@ -3683,8 +3303,6 @@ export function useCanvasDrawing({
}
},
[
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
clearPredictedCanvas,
effectiveDraftCanvasRef,
emitConstraintAxisChange,
@@ -3696,7 +3314,7 @@ export function useCanvasDrawing({
markTouchedTiles,
onUpdateLayerThumbnail,
pushHistoryStep,
- restoreLiveOrigTilesToCanvas,
+ resolveStrokeColor,
]
);
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 5ebb897..4c238a4 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -1,9 +1,35 @@
-import { useState, useRef, useEffect, useCallback } from 'react';
+import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { CanvasDimensions } from '../types/editor';
export const MIN_ZOOM = 0.01; // 1%
export const MAX_ZOOM = 32.0; // 3200%
+/** Debounce window (ms) before committing high-frequency camera updates to React UI state. */
+export const NAV_STATE_COMMIT_DEBOUNCE_MS = 140;
+
+/** Custom DOM event name dispatched on window whenever live camera transform changes. */
+export const CAMERA_CHANGE_EVENT = 'ink-camera-change';
+
+export interface CameraTransformState {
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number;
+ flipX: boolean;
+ flipY: boolean;
+}
+
+export type CameraSubscriber = (camera: CameraTransformState) => void;
+
+export interface CanvasNavigationHandle {
+ zoomRef: React.MutableRefObject<number>;
+ panRef: React.MutableRefObject<{ x: number; y: number }>;
+ rotationRef: React.MutableRefObject<number>;
+ flipXRef: React.MutableRefObject<boolean>;
+ flipYRef: React.MutableRefObject<boolean>;
+ getCameraState: () => CameraTransformState;
+ subscribeCamera: (listener: CameraSubscriber) => () => void;
+}
+
export const ZOOM_PRESETS = [
0.01,
0.02,
@@ -106,6 +132,8 @@ export function useCanvasNavigation({
const [zoom, setZoomState] = useState<number>(1.0);
const [pan, setPanState] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
const [rotation, setRotationState] = useState<number>(0.0);
+ const [flipX, setFlipXState] = useState<boolean>(false);
+ const [flipY, setFlipYState] = useState<boolean>(false);
const dimensionsRef = useRef<CanvasDimensions | undefined>(dimensions);
dimensionsRef.current = dimensions;
@@ -118,33 +146,99 @@ export function useCanvasNavigation({
const [isPanning, setIsPanning] = useState<boolean>(false);
const [isRotating, setIsRotating] = useState<boolean>(false);
- // Synchronous refs for sub-frame precision
+ // Synchronous refs for sub-frame precision (authoritative source of truth during active interaction)
const zoomRef = useRef<number>(1.0);
const panRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
const rotationRef = useRef<number>(0.0);
+ const flipXRef = useRef<boolean>(false);
+ const flipYRef = useRef<boolean>(false);
const isSpaceDownRef = useRef<boolean>(false);
const isShiftDownRef = useRef<boolean>(false);
const isPanningRef = useRef<boolean>(false);
const isRotatingRef = useRef<boolean>(false);
- // Coalesce high-frequency (240Hz) wheel/pan/rotate updates into 1 React render per animation frame
- const navCommitRafRef = useRef<number | null>(null);
- const scheduleNavStateCommit = useCallback(() => {
- if (navCommitRafRef.current !== null) return;
- navCommitRafRef.current = requestAnimationFrame(() => {
- navCommitRafRef.current = null;
- setZoomState(zoomRef.current);
- setPanState({ x: panRef.current.x, y: panRef.current.y });
- setRotationState(rotationRef.current);
+ const cameraSubscribersRef = useRef<Set<CameraSubscriber>>(new Set());
+ const cameraBroadcastRafRef = useRef<number | null>(null);
+ const navCommitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const getCameraState = useCallback((): CameraTransformState => {
+ return {
+ pan: { x: panRef.current.x, y: panRef.current.y },
+ zoom: zoomRef.current,
+ rotation: rotationRef.current,
+ flipX: flipXRef.current,
+ flipY: flipYRef.current,
+ };
+ }, []);
+
+ const subscribeCamera = useCallback((listener: CameraSubscriber) => {
+ cameraSubscribersRef.current.add(listener);
+ return () => {
+ cameraSubscribersRef.current.delete(listener);
+ };
+ }, []);
+
+ const emitCameraToSubscribers = useCallback(() => {
+ const camera = getCameraState();
+ cameraSubscribersRef.current.forEach((listener) => {
+ listener(camera);
+ });
+ if (typeof window !== 'undefined' && typeof CustomEvent === 'function') {
+ window.dispatchEvent(new CustomEvent<CameraTransformState>(CAMERA_CHANGE_EVENT, { detail: camera }));
+ }
+ }, [getCameraState]);
+
+ // Direct rAF-coalesced camera broadcast to CanvasArea DOM & ViewportCompositor (ZERO React setState calls)
+ const scheduleCameraBroadcast = useCallback(() => {
+ if (cameraBroadcastRafRef.current !== null) return;
+ cameraBroadcastRafRef.current = requestAnimationFrame(() => {
+ cameraBroadcastRafRef.current = null;
+ emitCameraToSubscribers();
});
+ }, [emitCameraToSubscribers]);
+
+ const broadcastCameraImmediate = useCallback(() => {
+ if (cameraBroadcastRafRef.current !== null) {
+ cancelAnimationFrame(cameraBroadcastRafRef.current);
+ cameraBroadcastRafRef.current = null;
+ }
+ emitCameraToSubscribers();
+ }, [emitCameraToSubscribers]);
+
+ const commitNavStateImmediate = useCallback(() => {
+ if (navCommitTimerRef.current !== null) {
+ clearTimeout(navCommitTimerRef.current);
+ navCommitTimerRef.current = null;
+ }
+ setZoomState(zoomRef.current);
+ setPanState({ x: panRef.current.x, y: panRef.current.y });
+ setRotationState(rotationRef.current);
+ setFlipXState(flipXRef.current);
+ setFlipYState(flipYRef.current);
}, []);
+ // Debounced commit to React state (~140ms after wheel/inertia ends; never per-rAF during motion)
+ const scheduleNavStateCommit = useCallback(() => {
+ if (navCommitTimerRef.current !== null) {
+ clearTimeout(navCommitTimerRef.current);
+ }
+ navCommitTimerRef.current = setTimeout(() => {
+ navCommitTimerRef.current = null;
+ if (isPanningRef.current || isRotatingRef.current) return;
+ commitNavStateImmediate();
+ }, NAV_STATE_COMMIT_DEBOUNCE_MS);
+ }, [commitNavStateImmediate]);
+
useEffect(() => {
return () => {
- if (navCommitRafRef.current !== null) {
- cancelAnimationFrame(navCommitRafRef.current);
- navCommitRafRef.current = null;
+ if (cameraBroadcastRafRef.current !== null) {
+ cancelAnimationFrame(cameraBroadcastRafRef.current);
+ cameraBroadcastRafRef.current = null;
+ }
+ if (navCommitTimerRef.current !== null) {
+ clearTimeout(navCommitTimerRef.current);
+ navCommitTimerRef.current = null;
}
};
}, []);
@@ -174,61 +268,68 @@ export function useCanvasNavigation({
const hasInitializedCenterRef = useRef<boolean>(false);
- const setZoom = useCallback((newZoomOrFn: number | ((prev: number) => number)) => {
- setZoomState((prev) => {
- const next = typeof newZoomOrFn === 'function' ? newZoomOrFn(prev) : newZoomOrFn;
+ const setZoom = useCallback(
+ (newZoomOrFn: number | ((prev: number) => number)) => {
+ const next = typeof newZoomOrFn === 'function' ? newZoomOrFn(zoomRef.current) : newZoomOrFn;
const safe = Number.isFinite(next) ? next : 1.0;
const clamped = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, safe));
zoomRef.current = clamped;
- return clamped;
- });
- }, []);
+ setZoomState(clamped);
+ broadcastCameraImmediate();
+ },
+ [broadcastCameraImmediate]
+ );
const setPan = useCallback(
(newPanOrFn: { x: number; y: number } | ((prev: { x: number; y: number }) => { x: number; y: number })) => {
- setPanState((prev) => {
- const next = typeof newPanOrFn === 'function' ? newPanOrFn(prev) : newPanOrFn;
- panRef.current = next;
- return next;
- });
+ const next = typeof newPanOrFn === 'function' ? newPanOrFn(panRef.current) : newPanOrFn;
+ panRef.current = { x: next.x, y: next.y };
+ setPanState(panRef.current);
+ broadcastCameraImmediate();
},
- []
+ [broadcastCameraImmediate]
);
- const setRotation = useCallback((newRotationOrFn: number | ((prev: number) => number)) => {
- setRotationState((prev) => {
- const next = typeof newRotationOrFn === 'function' ? newRotationOrFn(prev) : newRotationOrFn;
+ const setRotation = useCallback(
+ (newRotationOrFn: number | ((prev: number) => number)) => {
+ const next = typeof newRotationOrFn === 'function' ? newRotationOrFn(rotationRef.current) : newRotationOrFn;
rotationRef.current = next;
- return next;
- });
- }, []);
+ setRotationState(next);
+ broadcastCameraImmediate();
+ },
+ [broadcastCameraImmediate]
+ );
- const centerCanvas = useCallback((targetZoom: number = zoomRef.current) => {
- const viewport = viewportRef.current;
- let vw = viewport?.clientWidth ?? 0;
- let vh = viewport?.clientHeight ?? 0;
+ const centerCanvas = useCallback(
+ (targetZoom: number = zoomRef.current) => {
+ const viewport = viewportRef.current;
+ let vw = viewport?.clientWidth ?? 0;
+ let vh = viewport?.clientHeight ?? 0;
- 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;
+ 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),
- y: Math.round(vh / 2),
- };
+ const newCenter = {
+ x: Math.round(vw / 2),
+ y: Math.round(vh / 2),
+ };
- const safeZoom = Number.isFinite(targetZoom) ? targetZoom : 1.0;
- const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, safeZoom));
- panRef.current = newCenter;
- setPanState(newCenter);
- zoomRef.current = clampedZoom;
- setZoomState(clampedZoom);
- }, []);
+ const safeZoom = Number.isFinite(targetZoom) ? targetZoom : 1.0;
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, safeZoom));
+ panRef.current = newCenter;
+ zoomRef.current = clampedZoom;
+ setPanState(newCenter);
+ setZoomState(clampedZoom);
+ broadcastCameraImmediate();
+ },
+ [broadcastCameraImmediate]
+ );
/**
* Reset zoom based on layer/canvas dimensions.
@@ -257,6 +358,7 @@ export function useCanvasNavigation({
if (!viewport) {
rotationRef.current = 0.0;
setRotationState(0.0);
+ broadcastCameraImmediate();
return;
}
@@ -275,34 +377,118 @@ export function useCanvasNavigation({
const newPanY = vc.y + rx * Math.sin(dRad) + ry * Math.cos(dRad);
rotationRef.current = 0.0;
- setRotationState(0.0);
panRef.current = { x: newPanX, y: newPanY };
+ setRotationState(0.0);
setPanState({ x: newPanX, y: newPanY });
- }, []);
+ broadcastCameraImmediate();
+ }, [broadcastCameraImmediate]);
- const zoomToViewportCenter = useCallback((targetZoom: number) => {
+ /**
+ * Non-destructive horizontal view reflection across the viewport vertical midline (CSP-style).
+ * Does not modify any layer pixel buffers.
+ */
+ const toggleFlipHorizontal = useCallback(() => {
const viewport = viewportRef.current;
- if (!viewport) return;
+ const vw = viewport?.clientWidth ?? 0;
+ if (vw > 0) {
+ panRef.current = {
+ x: vw - panRef.current.x,
+ y: panRef.current.y,
+ };
+ }
+ if (Math.abs(rotationRef.current) > 0.0001) {
+ rotationRef.current = -rotationRef.current;
+ } else {
+ rotationRef.current = 0;
+ }
+ flipXRef.current = !flipXRef.current;
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ }, [broadcastCameraImmediate, commitNavStateImmediate]);
+
+ /**
+ * Non-destructive vertical view reflection across the viewport horizontal midline (CSP-style).
+ * Does not modify any layer pixel buffers.
+ */
+ const toggleFlipVertical = useCallback(() => {
+ const viewport = viewportRef.current;
+ const vh = viewport?.clientHeight ?? 0;
+ if (vh > 0) {
+ panRef.current = {
+ x: panRef.current.x,
+ y: vh - panRef.current.y,
+ };
+ }
+ if (Math.abs(rotationRef.current) > 0.0001) {
+ rotationRef.current = -rotationRef.current;
+ } else {
+ rotationRef.current = 0;
+ }
+ flipYRef.current = !flipYRef.current;
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ }, [broadcastCameraImmediate, commitNavStateImmediate]);
- const currentZoom = zoomRef.current;
- const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
- if (Math.abs(clampedZoom - currentZoom) < 0.0001) return;
+ /**
+ * Clears both horizontal and vertical non-destructive view reflections.
+ */
+ const resetViewFlip = useCallback(() => {
+ const wasFlipX = flipXRef.current;
+ const wasFlipY = flipYRef.current;
+ if (!wasFlipX && !wasFlipY) return;
- const vw = viewport.clientWidth;
- const vh = viewport.clientHeight;
- const centerX = vw / 2;
- const centerY = vh / 2;
+ const viewport = viewportRef.current;
+ const vw = viewport?.clientWidth ?? 0;
+ const vh = viewport?.clientHeight ?? 0;
- const ratio = clampedZoom / currentZoom;
- const newPanX = centerX - (centerX - panRef.current.x) * ratio;
- const newPanY = centerY - (centerY - panRef.current.y) * ratio;
+ let nextPanX = panRef.current.x;
+ let nextPanY = panRef.current.y;
+ let nextRot = rotationRef.current;
- zoomRef.current = clampedZoom;
- panRef.current = { x: newPanX, y: newPanY };
+ if (wasFlipX) {
+ if (vw > 0) nextPanX = vw - nextPanX;
+ nextRot = -nextRot;
+ }
+ if (wasFlipY) {
+ if (vh > 0) nextPanY = vh - nextPanY;
+ nextRot = -nextRot;
+ }
- setZoomState(clampedZoom);
- setPanState({ x: newPanX, y: newPanY });
- }, []);
+ panRef.current = { x: nextPanX, y: nextPanY };
+ rotationRef.current = Math.abs(nextRot) > 0.0001 ? nextRot : 0;
+ flipXRef.current = false;
+ flipYRef.current = false;
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ }, [broadcastCameraImmediate, commitNavStateImmediate]);
+
+ const zoomToViewportCenter = useCallback(
+ (targetZoom: number) => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+
+ const currentZoom = zoomRef.current;
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
+ if (Math.abs(clampedZoom - currentZoom) < 0.0001) return;
+
+ const vw = viewport.clientWidth;
+ const vh = viewport.clientHeight;
+ const centerX = vw / 2;
+ const centerY = vh / 2;
+
+ const ratio = clampedZoom / currentZoom;
+ const newPanX = centerX - (centerX - panRef.current.x) * ratio;
+ const newPanY = centerY - (centerY - panRef.current.y) * ratio;
+
+ zoomRef.current = clampedZoom;
+ panRef.current = { x: newPanX, y: newPanY };
+
+ setZoomState(clampedZoom);
+ setPanState({ x: newPanX, y: newPanY });
+ broadcastCameraImmediate();
+ },
+ [broadcastCameraImmediate]
+ );
const zoomIn = useCallback(() => {
const current = zoomRef.current;
@@ -395,7 +581,9 @@ export function useCanvasNavigation({
const dx = (width - prevWidth) / 2;
const dy = (height - prevHeight) / 2;
if (dx !== 0 || dy !== 0) {
- setPan((prev) => ({ x: prev.x + dx, y: prev.y + dy }));
+ panRef.current = { x: panRef.current.x + dx, y: panRef.current.y + dy };
+ scheduleCameraBroadcast();
+ scheduleNavStateCommit();
}
}
@@ -406,9 +594,9 @@ export function useCanvasNavigation({
ro.observe(viewport);
return () => ro.disconnect();
- }, [centerCanvas, setPan, activeDocumentId]);
+ }, [centerCanvas, scheduleCameraBroadcast, scheduleNavStateCommit, activeDocumentId]);
- // Mouse wheel zoom centered on cursor position (coalesced to 1 React render per rAF)
+ // Mouse wheel zoom centered on cursor position (live camera via rAF broadcast; React state debounced after wheel/inertia)
useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
@@ -429,6 +617,7 @@ export function useCanvasNavigation({
if (isWebtoonModeRef.current && !e.ctrlKey && !e.metaKey) {
panRef.current = { x: panRef.current.x, y: panRef.current.y - delta };
+ scheduleCameraBroadcast();
scheduleNavStateCommit();
return;
}
@@ -444,6 +633,7 @@ export function useCanvasNavigation({
zoomRef.current = nextZoom;
panRef.current = { x: nextPanX, y: nextPanY };
+ scheduleCameraBroadcast();
scheduleNavStateCommit();
}
};
@@ -452,7 +642,7 @@ export function useCanvasNavigation({
return () => {
viewport.removeEventListener('wheel', handleWheel);
};
- }, [activeDocumentId, scheduleNavStateCommit]);
+ }, [activeDocumentId, scheduleCameraBroadcast, scheduleNavStateCommit]);
// Global Keyboard Shortcuts (Space, Shift, Ctrl+0, Ctrl+Alt+0, Ctrl++, Ctrl+-)
useEffect(() => {
@@ -524,6 +714,7 @@ export function useCanvasNavigation({
};
const handleBlur = () => {
+ const wasInteracting = isPanningRef.current || isRotatingRef.current;
isSpaceDownRef.current = false;
setIsSpaceDown(false);
isShiftDownRef.current = false;
@@ -532,6 +723,10 @@ export function useCanvasNavigation({
setIsPanning(false);
isRotatingRef.current = false;
setIsRotating(false);
+ if (wasInteracting) {
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ }
};
window.addEventListener('keydown', handleKeyDown);
@@ -543,9 +738,9 @@ export function useCanvasNavigation({
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
- }, [resetRotation, resetZoomAndCenter, zoomIn, zoomOut]);
+ }, [resetRotation, resetZoomAndCenter, zoomIn, zoomOut, broadcastCameraImmediate, commitNavStateImmediate]);
- // Panning pointermove coalesced to rAF
+ // Panning pointermove: broadcasts directly to DOM/WebGL via rAF; commits React state only on pointerup
useEffect(() => {
if (!isPanning) return;
@@ -558,13 +753,14 @@ export function useCanvasNavigation({
x: isWebtoonModeRef.current ? panStartRef.current.panX : panStartRef.current.panX + dx,
y: panStartRef.current.panY + dy,
};
- scheduleNavStateCommit();
+ scheduleCameraBroadcast();
};
const handleWindowPointerUp = () => {
isPanningRef.current = false;
+ broadcastCameraImmediate();
setIsPanning(false);
- setPanState({ x: panRef.current.x, y: panRef.current.y });
+ commitNavStateImmediate();
};
window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
@@ -583,9 +779,9 @@ export function useCanvasNavigation({
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevUserSelect;
};
- }, [isPanning, scheduleNavStateCommit]);
+ }, [isPanning, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);
- // Rotating pointermove coalesced to rAF
+ // Rotating pointermove: broadcasts directly to DOM/WebGL via rAF; commits React state only on pointerup
useEffect(() => {
if (!isRotating) return;
@@ -632,14 +828,14 @@ export function useCanvasNavigation({
x: vc.x + rx * Math.cos(dRad) - ry * Math.sin(dRad),
y: vc.y + rx * Math.sin(dRad) + ry * Math.cos(dRad),
};
- scheduleNavStateCommit();
+ scheduleCameraBroadcast();
};
const handleWindowPointerUp = () => {
isRotatingRef.current = false;
+ broadcastCameraImmediate();
setIsRotating(false);
- setRotationState(rotationRef.current);
- setPanState({ x: panRef.current.x, y: panRef.current.y });
+ commitNavStateImmediate();
};
window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
@@ -658,7 +854,7 @@ export function useCanvasNavigation({
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevUserSelect;
};
- }, [isRotating, scheduleNavStateCommit]);
+ }, [isRotating, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);
useEffect(() => {
const handleAuxClick = (e: MouseEvent) => {
@@ -670,13 +866,36 @@ export function useCanvasNavigation({
return () => window.removeEventListener('auxclick', handleAuxClick);
}, []);
+ const navigation = useMemo<CanvasNavigationHandle>(
+ () => ({
+ zoomRef,
+ panRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ getCameraState,
+ subscribeCamera,
+ }),
+ [getCameraState, subscribeCamera]
+ );
+
const isRotateModifier = isSpaceDown && isShiftDown;
return {
viewportRef,
+ navigation,
zoom,
pan,
rotation,
+ flipX,
+ flipY,
+ zoomRef,
+ panRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ getCameraState,
+ subscribeCamera,
isSpaceDown,
isShiftDown,
isRotateModifier,
@@ -688,6 +907,9 @@ export function useCanvasNavigation({
zoomOut,
resetZoomAndCenter,
resetRotation,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ resetViewFlip,
setZoom,
setPan,
setRotation,
diff --git a/src/utils/__tests__/compositor.test.ts b/src/utils/__tests__/compositor.test.ts
index 4d772e6..592d9c1 100644
--- a/src/utils/__tests__/compositor.test.ts
+++ b/src/utils/__tests__/compositor.test.ts
@@ -4,8 +4,17 @@ import {
ViewportTransform,
COMPOSITOR_VERTEX_SHADER,
COMPOSITOR_FRAGMENT_SHADER,
+ COMPOSITOR_INSTANCED_VERTEX_SHADER,
+ COMPOSITOR_INSTANCED_FRAGMENT_SHADER,
+ VIEWPORT_DRAFT_VERTEX_SHADER,
+ BLEND_MODE_MAP,
groupLayersForCompositing,
+ partitionLayerStack,
+ isUnitNormalAssociative,
+ LayerStackCacheTracker,
+ ViewportCompositor,
} from '../compositor';
+import { SparseTileGrid } from '../tileEngine';
import { LayerItem } from '../../types/editor';
describe('Unified GPU Viewport Compositor', () => {
@@ -272,6 +281,1116 @@ describe('Unified GPU Viewport Compositor', () => {
expect(SOFT_PROOF_FRAGMENT_SHADER).toContain('outRgb = u_gamutWarningColor;');
});
});
+
+ describe('Non-Destructive View Flip (Flip Horizontal / Vertical)', () => {
+ it('applies u_flip uniform in vertex shader without mutating texture UVs', () => {
+ expect(COMPOSITOR_VERTEX_SHADER).toContain('uniform vec2 u_flip;');
+ expect(COMPOSITOR_VERTEX_SHADER).toContain('vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;');
+ expect(COMPOSITOR_VERTEX_SHADER).toContain('v_texCoord = a_quadPos;');
+ });
+
+ it('accurately mirrors frustum culling bounds when flipX and flipY are active', () => {
+ const docW = 2000;
+ const docH = 1600;
+ const viewportW = 800;
+ const viewportH = 600;
+
+ // Panned so viewport looks at top-left quadrant of unflipped document:
+ // Document center (1000, 800) is placed at screen (700, 500), zoom = 1.0
+ const unflippedBounds = calculateVisibleDocumentBounds(
+ viewportW,
+ viewportH,
+ { pan: { x: 700, y: 500 }, zoom: 1.0, rotation: 0, flipX: false, flipY: false },
+ docW,
+ docH
+ );
+ expect(unflippedBounds).toEqual({
+ minX: 300,
+ minY: 300,
+ maxX: 1100,
+ maxY: 900,
+ });
+
+ // With flipX = true at the same pan (700, 500), horizontal document region reflects around docW/2 = 1000:
+ // [300, 1100] -> [2000 - 1100, 2000 - 300] = [900, 1700]
+ const flippedHBounds = calculateVisibleDocumentBounds(
+ viewportW,
+ viewportH,
+ { pan: { x: 700, y: 500 }, zoom: 1.0, rotation: 0, flipX: true, flipY: false },
+ docW,
+ docH
+ );
+ expect(flippedHBounds).toEqual({
+ minX: 900,
+ minY: 300,
+ maxX: 1700,
+ maxY: 900,
+ });
+
+ // With flipY = true as well, vertical document region reflects around docH/2 = 800:
+ // [300, 900] -> [1600 - 900, 1600 - 300] = [700, 1300]
+ const flippedHVBounds = calculateVisibleDocumentBounds(
+ viewportW,
+ viewportH,
+ { pan: { x: 700, y: 500 }, zoom: 1.0, rotation: 0, flipX: true, flipY: true },
+ docW,
+ docH
+ );
+ expect(flippedHVBounds).toEqual({
+ minX: 900,
+ minY: 700,
+ maxX: 1700,
+ maxY: 1300,
+ });
+ });
+
+ it('renders non-destructively in 2D fallback with signed zoom scale while keeping tile grid untouched', async () => {
+ const { ViewportCompositor } = await import('../compositor');
+ const { SparseTileGrid } = await import('../tileEngine');
+
+ const grid = new SparseTileGrid();
+ const pixelBuf = new Uint8ClampedArray(16 * 16 * 4);
+ pixelBuf[0] = 240; // R at (0, 0)
+ pixelBuf[1] = 32; // G
+ pixelBuf[2] = 64; // B
+ pixelBuf[3] = 255; // A
+ grid.writeImageData('layer-1', { data: pixelBuf, width: 16, height: 16 }, 10, 20, 'color-32bit');
+
+ const scaleCalls: Array<[number, number]> = [];
+ const mock2DCtx = {
+ save: () => {},
+ restore: () => {},
+ clearRect: () => {},
+ scale: (sx: number, sy: number) => {
+ scaleCalls.push([sx, sy]);
+ },
+ translate: () => {},
+ rotate: () => {},
+ fillRect: () => {},
+ drawImage: () => {},
+ fillStyle: '#ffffff',
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ };
+
+ const mockCanvas = {
+ width: 800,
+ height: 600,
+ getContext: (type: string) => (type === '2d' ? mock2DCtx : null),
+ } as unknown as HTMLCanvasElement;
+
+ const compositor = new ViewportCompositor(mockCanvas);
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ compositor.render(
+ layers,
+ { pan: { x: 400, y: 300 }, zoom: 2.5, rotation: 15, flipX: true, flipY: false },
+ { width: 1000, height: 800 },
+ grid,
+ { dimensions: { width: 1000, height: 800 }, devicePixelRatio: 1 }
+ );
+
+ // Verify signed flip scale (-2.5, 2.5) was applied to viewport transform
+ expect(scaleCalls).toContainEqual([-2.5, 2.5]);
+
+ // Verify underlying layer tile pixels were NOT destructively flipped or mutated
+ const checkAfter = grid.readImageData('layer-1', 10, 20, 16, 16);
+ expect(checkAfter.data[0]).toBe(240);
+ expect(checkAfter.data[1]).toBe(32);
+ expect(checkAfter.data[2]).toBe(64);
+ expect(checkAfter.data[3]).toBe(255);
+ // Opposite corner of 16x16 patch remains transparent
+ expect(checkAfter.data[(15 * 16 + 15) * 4 + 3]).toBe(0);
+ });
+ });
+
+ describe('Baked Layer Stack Cache Partitioning & Invalidation (below / above)', () => {
+ const makeLayer = (id: string, overrides: Partial<LayerItem> = {}): LayerItem => ({
+ id,
+ name: id,
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ ...overrides,
+ });
+
+ const baseTransform: ViewportTransform = {
+ pan: { x: 400, y: 300 },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ const baseDimensions = { width: 1024, height: 1024, dpi: 300 };
+
+ it('keeps both below and above caches valid while editing the active layer', () => {
+ // UI top-to-bottom order: layer-9 (top) ... layer-0 (bottom)
+ const layers: LayerItem[] = [];
+ for (let i = 9; i >= 0; i--) {
+ layers.push(makeLayer(`layer-${i}`));
+ }
+
+ const versions = new Map<string, number>();
+ const getVer = (id: string) => versions.get(id) ?? 0;
+ const tracker = new LayerStackCacheTracker();
+
+ const first = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-4',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: true,
+ getLayerContentVersion: getVer,
+ });
+
+ expect(first.belowDirty).toBe(true);
+ expect(first.aboveDirty).toBe(true);
+ expect(first.partition.belowUnits.map((u) => u.group.baseNode.layer.id)).toEqual([
+ 'layer-0',
+ 'layer-1',
+ 'layer-2',
+ 'layer-3',
+ ]);
+ expect(first.partition.activeUnit?.group.baseNode.layer.id).toBe('layer-4');
+ expect(first.partition.aboveStrategy).toBe('baked-normal');
+ expect(first.partition.aboveCachedUnits.map((u) => u.group.baseNode.layer.id)).toEqual([
+ 'layer-5',
+ 'layer-6',
+ 'layer-7',
+ 'layer-8',
+ 'layer-9',
+ ]);
+
+ tracker.commit(first.belowSignature, first.aboveSignature);
+
+ // Simulate 5 consecutive brush stroke frames mutating ONLY active layer-4
+ for (let stroke = 1; stroke <= 5; stroke++) {
+ versions.set('layer-4', stroke);
+ const evalRes = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-4',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: true,
+ getLayerContentVersion: getVer,
+ });
+ expect(evalRes.belowDirty).toBe(false);
+ expect(evalRes.aboveDirty).toBe(false);
+ }
+ });
+
+ it('invalidates ONLY below cache when an inactive lower layer changes (content, visibility, opacity, blendMode, mask)', () => {
+ const layers = [
+ makeLayer('top-2'),
+ makeLayer('top-1'),
+ makeLayer('active-mid'),
+ makeLayer('bot-2'),
+ makeLayer('bot-1'),
+ ];
+ const versions = new Map<string, number>();
+ const maskEpochs = new Map<string, number>();
+ const tracker = new LayerStackCacheTracker();
+
+ const runEval = (currentLayers: LayerItem[] = layers) =>
+ tracker.evaluate({
+ layers: currentLayers,
+ activeLayerId: 'active-mid',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: false,
+ getLayerContentVersion: (id) => versions.get(id) ?? 0,
+ getMaskInvalidationEpoch: (id) => maskEpochs.get(id) ?? 0,
+ });
+
+ const init = runEval();
+ tracker.commit(init.belowSignature, init.aboveSignature);
+
+ // 1. Inactive below content edit (e.g. undo/redo or remote peer)
+ versions.set('bot-1', 1);
+ const afterBotContent = runEval();
+ expect(afterBotContent.belowDirty).toBe(true);
+ expect(afterBotContent.aboveDirty).toBe(false);
+ tracker.commit(afterBotContent.belowSignature, afterBotContent.aboveSignature);
+
+ // 2. Inactive below opacity change
+ const opacityLayers = layers.map((l) => (l.id === 'bot-2' ? { ...l, opacity: 0.45 } : l));
+ const afterBotOpacity = runEval(opacityLayers);
+ expect(afterBotOpacity.belowDirty).toBe(true);
+ expect(afterBotOpacity.aboveDirty).toBe(false);
+ tracker.commit(afterBotOpacity.belowSignature, afterBotOpacity.aboveSignature);
+
+ // 3. Inactive below visibility toggle
+ const visLayers = opacityLayers.map((l) => (l.id === 'bot-1' ? { ...l, visible: false } : l));
+ const afterBotVis = runEval(visLayers);
+ expect(afterBotVis.belowDirty).toBe(true);
+ expect(afterBotVis.aboveDirty).toBe(false);
+ tracker.commit(afterBotVis.belowSignature, afterBotVis.aboveSignature);
+
+ // 4. Inactive below blendMode change
+ const blendLayers = visLayers.map((l) => (l.id === 'bot-2' ? { ...l, blendMode: 'multiply' as const } : l));
+ const afterBotBlend = runEval(blendLayers);
+ expect(afterBotBlend.belowDirty).toBe(true);
+ expect(afterBotBlend.aboveDirty).toBe(false);
+ tracker.commit(afterBotBlend.belowSignature, afterBotBlend.aboveSignature);
+
+ // 5. Inactive below mask change
+ const mockMaskCanvas = { width: 1024, height: 1024 } as HTMLCanvasElement;
+ const maskLayers = blendLayers.map((l) =>
+ l.id === 'bot-2' ? { ...l, maskCanvas: mockMaskCanvas, maskEnabled: true, maskVersion: 1 } : l
+ );
+ const afterBotMask = runEval(maskLayers);
+ expect(afterBotMask.belowDirty).toBe(true);
+ expect(afterBotMask.aboveDirty).toBe(false);
+ tracker.commit(afterBotMask.belowSignature, afterBotMask.aboveSignature);
+
+ maskEpochs.set('bot-2', 1);
+ const afterBotMaskEpoch = runEval(maskLayers);
+ expect(afterBotMaskEpoch.belowDirty).toBe(true);
+ expect(afterBotMaskEpoch.aboveDirty).toBe(false);
+ });
+
+ it('invalidates ONLY above cache when an inactive upper layer changes', () => {
+ const layers = [
+ makeLayer('top-2'),
+ makeLayer('top-1'),
+ makeLayer('active-mid'),
+ makeLayer('bot-1'),
+ ];
+ const versions = new Map<string, number>();
+ const tracker = new LayerStackCacheTracker();
+
+ const runEval = (currentLayers: LayerItem[] = layers) =>
+ tracker.evaluate({
+ layers: currentLayers,
+ activeLayerId: 'active-mid',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: false,
+ getLayerContentVersion: (id) => versions.get(id) ?? 0,
+ });
+
+ const init = runEval();
+ tracker.commit(init.belowSignature, init.aboveSignature);
+
+ // 1. Upper layer pixel content change
+ versions.set('top-2', 3);
+ const afterTopContent = runEval();
+ expect(afterTopContent.belowDirty).toBe(false);
+ expect(afterTopContent.aboveDirty).toBe(true);
+ tracker.commit(afterTopContent.belowSignature, afterTopContent.aboveSignature);
+
+ // 2. Upper layer opacity change
+ const opacityLayers = layers.map((l) => (l.id === 'top-1' ? { ...l, opacity: 0.7 } : l));
+ const afterTopOpacity = runEval(opacityLayers);
+ expect(afterTopOpacity.belowDirty).toBe(false);
+ expect(afterTopOpacity.aboveDirty).toBe(true);
+ tracker.commit(afterTopOpacity.belowSignature, afterTopOpacity.aboveSignature);
+
+ // 3. Adding a brand-new layer above active
+ const addedLayers = [makeLayer('top-3'), ...opacityLayers];
+ const afterAddAbove = runEval(addedLayers);
+ expect(afterAddAbove.belowDirty).toBe(false);
+ expect(afterAddAbove.aboveDirty).toBe(true);
+ });
+
+ it('invalidates both slices on active layer switch or camera transform change, and only below on checkerboard change', () => {
+ const layers = [
+ makeLayer('layer-2'),
+ makeLayer('layer-1'),
+ makeLayer('layer-0'),
+ ];
+ const tracker = new LayerStackCacheTracker();
+
+ const init = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: true,
+ getLayerContentVersion: () => 0,
+ });
+ tracker.commit(init.belowSignature, init.aboveSignature);
+
+ // Checkerboard toggle only affects below cache (artboard background is in below)
+ const afterCb = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: baseTransform,
+ showCheckerboard: false,
+ getLayerContentVersion: () => 0,
+ });
+ expect(afterCb.belowDirty).toBe(true);
+ expect(afterCb.aboveDirty).toBe(false);
+ tracker.commit(afterCb.belowSignature, afterCb.aboveSignature);
+
+ // Camera pan/zoom invalidates both caches
+ const afterPan = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: { ...baseTransform, pan: { x: 450, y: 310 } },
+ showCheckerboard: false,
+ getLayerContentVersion: () => 0,
+ });
+ expect(afterPan.belowDirty).toBe(true);
+ expect(afterPan.aboveDirty).toBe(true);
+ tracker.commit(afterPan.belowSignature, afterPan.aboveSignature);
+
+ // Switching active layer from layer-1 -> layer-0 invalidates both below and above
+ const afterSwitch = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-0',
+ viewportW: 800,
+ viewportH: 600,
+ dpr: 1,
+ dimensions: baseDimensions,
+ transform: { ...baseTransform, pan: { x: 450, y: 310 } },
+ showCheckerboard: false,
+ getLayerContentVersion: () => 0,
+ });
+ expect(afterSwitch.belowDirty).toBe(true);
+ expect(afterSwitch.aboveDirty).toBe(true);
+ expect(afterSwitch.partition.belowUnits).toHaveLength(0);
+ expect(afterSwitch.partition.aboveCachedUnits.map((u) => u.group.baseNode.layer.id)).toEqual([
+ 'layer-1',
+ 'layer-2',
+ ]);
+ });
+
+ it('correctly selects baked-single-blend, mixed, pass-through folder flattening, and isolated folder associativity', () => {
+ // Single Multiply layer above active -> baked-single-blend
+ const singleMulLayers = [
+ makeLayer('shadow', { blendMode: 'multiply', opacity: 0.5 }),
+ makeLayer('base'),
+ ];
+ const p1 = partitionLayerStack(singleMulLayers, 'base');
+ expect(p1.aboveStrategy).toBe('baked-single-blend');
+ expect(p1.aboveCacheBlendMode).toBe('multiply');
+ expect(p1.aboveDynamicUnits).toHaveLength(0);
+ expect(p1.aboveCachedUnits).toHaveLength(1);
+
+ // Mixed upper stack: Multiply directly above active, plus 2 Normal layers above that
+ const mixedLayers = [
+ makeLayer('top-normal-2'),
+ makeLayer('top-normal-1'),
+ makeLayer('mid-multiply', { blendMode: 'multiply' }),
+ makeLayer('active-base'),
+ ];
+ const p2 = partitionLayerStack(mixedLayers, 'active-base');
+ expect(p2.aboveStrategy).toBe('mixed');
+ expect(p2.aboveDynamicUnits.map((u) => u.group.baseNode.layer.id)).toEqual(['mid-multiply']);
+ expect(p2.aboveCachedUnits.map((u) => u.group.baseNode.layer.id)).toEqual([
+ 'top-normal-1',
+ 'top-normal-2',
+ ]);
+
+ // Pass-through folder flattens children so active child splits siblings into below & above
+ const folderLayers = [
+ makeLayer('pt-folder', { type: 'folder', blendMode: 'pass-through', opacity: 0.8 }),
+ makeLayer('c-top', { parentId: 'pt-folder' }),
+ makeLayer('c-mid', { parentId: 'pt-folder' }),
+ makeLayer('c-bot', { parentId: 'pt-folder' }),
+ ];
+ const p3 = partitionLayerStack(folderLayers, 'c-mid');
+ expect(p3.belowUnits.map((u) => u.group.baseNode.layer.id)).toEqual(['c-bot']);
+ expect(p3.belowUnits[0].inheritedOpacity).toBeCloseTo(0.8);
+ expect(p3.activeUnit?.group.baseNode.layer.id).toBe('c-mid');
+ expect(p3.aboveCachedUnits.map((u) => u.group.baseNode.layer.id)).toEqual(['c-top']);
+
+ // Isolated folder with normal blend mode above active IS normal-associative even if children use multiply
+ const isoLayers = [
+ makeLayer('iso-folder', { type: 'folder', blendMode: 'normal' }),
+ makeLayer('iso-child', { parentId: 'iso-folder', blendMode: 'multiply' }),
+ makeLayer('active-under'),
+ ];
+ const p4 = partitionLayerStack(isoLayers, 'active-under');
+ expect(p4.aboveStrategy).toBe('baked-normal');
+ expect(p4.aboveCachedUnits).toHaveLength(1);
+ expect(isUnitNormalAssociative(p4.aboveCachedUnits[0])).toBe(true);
+ });
+ });
+
+ describe('WebGL2 Compositor Optimization Verification (Ping-Pong FBOs, Instanced Batching, Zero CPU Premultiply, In-Stack Draft)', () => {
+ function createMockWebGL2Context(options?: { maxArrayLayers?: number }) {
+ const maxArrayLayers = options?.maxArrayLayers ?? 256;
+ const calls: Array<{ name: string; args: any[] }> = [];
+ let activeProgram: any = null;
+ let boundFbo: any = null;
+ let activeTexUnit = 0;
+ let unpackPremultiplyAlpha = false;
+ const boundTex2DByUnit = new Map<number, any>();
+ const fboColorAttachment = new WeakMap<object, any>();
+ const glSpecErrors: string[] = [];
+ const programUniforms = new WeakMap<object, Map<string, any>>();
+ const uniformMeta = new WeakMap<object, { prog: object; name: string }>();
+ let programId = 1;
+ let shaderSourceByObj = new WeakMap<object, string>();
+ const programTag = new WeakMap<object, string>();
+ const drawEvents: Array<{
+ type: 'drawArrays' | 'drawArraysInstanced';
+ programTag: string;
+ count: number;
+ instances?: number;
+ uniforms: Record<string, any>;
+ }> = [];
+
+ const validateWebGL2DrawState = (tag: string, uMap: Map<string, any>) => {
+ // 1. Validate WebGL2 rule: sampler2DArray and sampler2D cannot share the same texture unit
+ if (tag === 'instanced') {
+ const arrUnit = uMap.get('u_tileArrayTexture') ?? 0;
+ const maskUnit = uMap.get('u_maskTexture') ?? 0;
+ const backdropUnit = uMap.get('u_backdropTexture') ?? 0;
+ if (arrUnit === maskUnit || arrUnit === backdropUnit) {
+ glSpecErrors.push(
+ `Sampler type collision in ${tag}: u_tileArrayTexture=${arrUnit}, u_maskTexture=${maskUnit}, u_backdropTexture=${backdropUnit}`
+ );
+ }
+ }
+ // 2. Validate WebGL2 rule: texture attached to active DRAW_FRAMEBUFFER cannot be bound to any active sampler2D unit
+ if (boundFbo) {
+ const attachedTex = fboColorAttachment.get(boundFbo);
+ if (attachedTex) {
+ const sampler2DUniforms =
+ tag === 'instanced'
+ ? ['u_maskTexture', 'u_backdropTexture']
+ : tag === 'blit'
+ ? ['u_blitTexture', 'u_backdropTexture']
+ : tag === 'standard' || tag === 'viewportDraft'
+ ? ['u_tileTexture', 'u_maskTexture', 'u_backdropTexture']
+ : [];
+ for (const sName of sampler2DUniforms) {
+ const unit = uMap.get(sName) ?? 0;
+ if (boundTex2DByUnit.get(unit) === attachedTex) {
+ glSpecErrors.push(
+ `Feedback loop in ${tag}: sampler ${sName} (unit ${unit}) reads texture attached to bound DRAW_FRAMEBUFFER`
+ );
+ }
+ }
+ }
+ }
+ };
+
+ const gl: any = {
+ VERTEX_SHADER: 0x8b31,
+ FRAGMENT_SHADER: 0x8b30,
+ COMPILE_STATUS: 0x8b81,
+ LINK_STATUS: 0x8b82,
+ ARRAY_BUFFER: 0x8892,
+ STATIC_DRAW: 0x88e4,
+ DYNAMIC_DRAW: 0x88e8,
+ FLOAT: 0x1406,
+ TRIANGLES: 0x0004,
+ TEXTURE_2D: 0x0de1,
+ TEXTURE_2D_ARRAY: 0x8c1a,
+ TEXTURE0: 0x84c0,
+ TEXTURE1: 0x84c1,
+ TEXTURE2: 0x84c2,
+ TEXTURE3: 0x84c3,
+ TEXTURE_WRAP_S: 0x2802,
+ TEXTURE_WRAP_T: 0x2803,
+ TEXTURE_MIN_FILTER: 0x2801,
+ TEXTURE_MAG_FILTER: 0x2800,
+ CLAMP_TO_EDGE: 0x812f,
+ LINEAR: 0x2601,
+ LINEAR_MIPMAP_LINEAR: 0x2703,
+ NEAREST: 0x2600,
+ RGBA: 0x1908,
+ RGBA8: 0x8058,
+ UNSIGNED_BYTE: 0x1401,
+ BLEND: 0x0be2,
+ STENCIL_TEST: 0x0b90,
+ ONE: 1,
+ ZERO: 0,
+ ONE_MINUS_SRC_ALPHA: 0x0303,
+ COLOR_BUFFER_BIT: 0x4000,
+ STENCIL_BUFFER_BIT: 0x0400,
+ FRAMEBUFFER: 0x8d40,
+ READ_FRAMEBUFFER: 0x8ca8,
+ DRAW_FRAMEBUFFER: 0x8ca9,
+ FRAMEBUFFER_BINDING: 0x8ca6,
+ COLOR_ATTACHMENT0: 0x8ce0,
+ STENCIL_ATTACHMENT: 0x8d20,
+ RENDERBUFFER: 0x8d41,
+ STENCIL_INDEX8: 0x8d48,
+ FRAMEBUFFER_COMPLETE: 0x8cd5,
+ ALWAYS: 0x0207,
+ EQUAL: 0x0202,
+ KEEP: 0x1e00,
+ REPLACE: 0x1e01,
+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,
+ MAX_ARRAY_TEXTURE_LAYERS: 0x88ff,
+
+ createShader: (type: number) => ({ __shader: type }),
+ shaderSource: (shader: object, src: string) => {
+ shaderSourceByObj.set(shader, src);
+ },
+ compileShader: () => {},
+ getShaderParameter: () => true,
+ getShaderInfoLog: () => '',
+ createProgram: () => {
+ const p = { id: programId++, shaders: [] as string[] };
+ programUniforms.set(p, new Map());
+ return p;
+ },
+ attachShader: (prog: any, shader: object) => {
+ const src = shaderSourceByObj.get(shader) || '';
+ prog.shaders.push(src);
+ if (src === COMPOSITOR_INSTANCED_VERTEX_SHADER) programTag.set(prog, 'instanced');
+ else if (src === VIEWPORT_DRAFT_VERTEX_SHADER) programTag.set(prog, 'viewportDraft');
+ else if (src === COMPOSITOR_VERTEX_SHADER && !programTag.has(prog)) programTag.set(prog, 'standard');
+ else if (src.includes('u_blitTexture')) programTag.set(prog, 'blit');
+ else if (src.includes('u_sceneTexture')) programTag.set(prog, 'softProof');
+ else if (src.includes('u_lutTexture')) programTag.set(prog, 'adjustment');
+ else if (src.includes('POISSON_KERNEL')) programTag.set(prog, 'styles');
+ },
+ linkProgram: () => {},
+ getProgramParameter: () => true,
+ getProgramInfoLog: () => '',
+ getUniformLocation: (prog: object, name: string) => {
+ const loc = { prog, name };
+ uniformMeta.set(loc, { prog, name });
+ return loc;
+ },
+ getAttribLocation: (_prog: object, name: string) => (name === 'a_instanceData' ? 1 : 0),
+ useProgram: (prog: any) => {
+ activeProgram = prog;
+ },
+ createBuffer: () => ({ __buf: true }),
+ bindBuffer: () => {},
+ bufferData: () => {},
+ bufferSubData: (...args: any[]) => calls.push({ name: 'bufferSubData', args }),
+ createVertexArray: () => ({ __vao: true }),
+ bindVertexArray: () => {},
+ deleteVertexArray: () => {},
+ enableVertexAttribArray: () => {},
+ disableVertexAttribArray: () => {},
+ vertexAttribPointer: () => {},
+ vertexAttribDivisor: () => {},
+ createTexture: () => ({ __tex: Math.random() }),
+ deleteTexture: () => {},
+ activeTexture: (unit: number) => {
+ activeTexUnit = unit - 0x84c0;
+ },
+ bindTexture: (...args: any[]) => {
+ calls.push({ name: 'bindTexture', args });
+ if (args[0] === 0x0de1) {
+ boundTex2DByUnit.set(activeTexUnit, args[1]);
+ }
+ },
+ texParameteri: (...args: any[]) => calls.push({ name: 'texParameteri', args }),
+ generateMipmap: (...args: any[]) => calls.push({ name: 'generateMipmap', args }),
+ texImage2D: (...args: any[]) => calls.push({ name: 'texImage2D', args }),
+ texSubImage2D: (...args: any[]) => calls.push({ name: 'texSubImage2D', args }),
+ texStorage3D: (...args: any[]) => calls.push({ name: 'texStorage3D', args }),
+ texSubImage3D: (...args: any[]) => {
+ if (unpackPremultiplyAlpha && ArrayBuffer.isView(args[10])) {
+ glSpecErrors.push(
+ 'GL_INVALID_OPERATION (1282): texSubImage3D with ArrayBufferView cannot use UNPACK_PREMULTIPLY_ALPHA_WEBGL=true'
+ );
+ }
+ calls.push({ name: 'texSubImage3D', args });
+ },
+ copyTexSubImage2D: (...args: any[]) => calls.push({ name: 'copyTexSubImage2D', args }),
+ pixelStorei: (...args: any[]) => {
+ if (args[0] === 0x9241) unpackPremultiplyAlpha = Boolean(args[1]);
+ calls.push({ name: 'pixelStorei', args });
+ },
+ createFramebuffer: () => ({ __fbo: Math.random() }),
+ deleteFramebuffer: () => {},
+ bindFramebuffer: (target: number, fbo: any) => {
+ if (target === 0x8d40 || target === 0x8ca9) boundFbo = fbo;
+ },
+ framebufferTexture2D: (_target: number, attachment: number, _textarget: number, tex: any) => {
+ if (boundFbo && attachment === 0x8ce0) {
+ fboColorAttachment.set(boundFbo, tex);
+ }
+ },
+ checkFramebufferStatus: () => 0x8cd5,
+ blitFramebuffer: (...args: any[]) => calls.push({ name: 'blitFramebuffer', args }),
+ createRenderbuffer: () => ({ __rb: true }),
+ deleteRenderbuffer: () => {},
+ bindRenderbuffer: () => {},
+ renderbufferStorage: () => {},
+ framebufferRenderbuffer: () => {},
+ getParameter: (pname: number) => {
+ if (pname === 0x8ca6) return boundFbo;
+ if (pname === 0x88ff) return maxArrayLayers;
+ return 0;
+ },
+ viewport: () => {},
+ clearColor: () => {},
+ clear: () => {},
+ enable: () => {},
+ disable: () => {},
+ isEnabled: () => false,
+ blendFunc: () => {},
+ stencilMask: () => {},
+ stencilFunc: () => {},
+ stencilOp: () => {},
+ colorMask: () => {},
+ uniform1i: (loc: any, v: number) => {
+ const meta = loc && uniformMeta.get(loc);
+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, v);
+ },
+ uniform1f: (loc: any, v: number) => {
+ const meta = loc && uniformMeta.get(loc);
+ if (meta) programUniforms.get(meta.prog)?.set(meta.name, v);
+ },
+ uniform2f: () => {},
+ uniform3f: () => {},
+ uniform4f: () => {},
+ drawArrays: (_mode: number, _first: number, count: number) => {
+ calls.push({ name: 'drawArrays', args: [_mode, _first, count] });
+ const tag = (activeProgram && programTag.get(activeProgram)) || 'unknown';
+ const uMap = (activeProgram && programUniforms.get(activeProgram)) || new Map();
+ validateWebGL2DrawState(tag, uMap);
+ drawEvents.push({
+ type: 'drawArrays',
+ programTag: tag,
+ count,
+ uniforms: Object.fromEntries(uMap.entries()),
+ });
+ },
+ drawArraysInstanced: (_mode: number, _first: number, count: number, instances: number) => {
+ calls.push({ name: 'drawArraysInstanced', args: [_mode, _first, count, instances] });
+ const tag = (activeProgram && programTag.get(activeProgram)) || 'unknown';
+ const uMap = (activeProgram && programUniforms.get(activeProgram)) || new Map();
+ validateWebGL2DrawState(tag, uMap);
+ drawEvents.push({
+ type: 'drawArraysInstanced',
+ programTag: tag,
+ count,
+ instances,
+ uniforms: Object.fromEntries(uMap.entries()),
+ });
+ },
+ deleteBuffer: () => {},
+ deleteProgram: () => {},
+ };
+
+ const canvas = {
+ width: 800,
+ height: 600,
+ getContext: (type: string) => (type === 'webgl2' ? gl : null),
+ } as unknown as HTMLCanvasElement;
+
+ return { gl, canvas, calls, drawEvents, glSpecErrors };
+ }
+
+ const writeTestPixel = (grid: SparseTileGrid, layerId: string, x: number, y: number, rgba = [200, 100, 50, 128]) => {
+ const buf = new Uint8ClampedArray(16 * 16 * 4);
+ for (let i = 0; i < 16 * 16; i++) {
+ buf[i * 4] = rgba[0];
+ buf[i * 4 + 1] = rgba[1];
+ buf[i * 4 + 2] = rgba[2];
+ buf[i * 4 + 3] = rgba[3];
+ }
+ grid.writeImageData(layerId, { data: buf, width: 16, height: 16 }, x, y, 'color-32bit', true);
+ };
+
+ it('executes ZERO copyTexSubImage2D calls with 15+ Multiply/Overlay/Color-Dodge layers while rendering and drawing', () => {
+ const { canvas, calls } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+
+ const blendModes: LayerItem['blendMode'][] = [
+ 'multiply',
+ 'overlay',
+ 'screen',
+ 'color-dodge',
+ 'hard-light',
+ 'soft-light',
+ ];
+ const layers: LayerItem[] = [];
+ for (let i = 15; i >= 0; i--) {
+ const id = `layer-${i}`;
+ layers.push({
+ id,
+ name: id,
+ type: 'raster',
+ visible: true,
+ opacity: 0.85,
+ blendMode: i === 0 ? 'normal' : blendModes[i % blendModes.length],
+ locked: false,
+ parentId: null,
+ });
+ writeTestPixel(grid, id, 100, 100);
+ }
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ const dims = { width: 1024, height: 1024 };
+
+ // Frame 1: Full render across all 16 layers with custom blend modes
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-8',
+ });
+
+ // Frames 2..6: Live drawing on active layer-8
+ for (let step = 0; step < 5; step++) {
+ writeTestPixel(grid, 'layer-8', 120 + step * 10, 120);
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-8',
+ });
+ }
+
+ const copyCalls = calls.filter((c) => c.name === 'copyTexSubImage2D');
+ const blitCalls = calls.filter((c) => c.name === 'blitFramebuffer');
+ expect(copyCalls.length).toBe(0);
+ expect(blitCalls.length).toBeGreaterThan(0);
+ });
+
+ it('enforces zero WebGL2 sampler-type collisions and zero FBO feedback loops across multi-frame rendering', () => {
+ const { canvas, glSpecErrors } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ {
+ id: 'layer-bg',
+ name: 'Paper',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+ grid.fillLayerSolidWhite('layer-bg', 800, 600, 'color-32bit');
+ writeTestPixel(grid, 'layer-1', 100, 100, [0, 0, 0, 255]);
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ const dims = { width: 800, height: 600 };
+
+ for (let frame = 0; frame < 4; frame++) {
+ writeTestPixel(grid, 'layer-1', 100 + frame * 16, 100, [0, 0, 0, 255]);
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ showCheckerboard: true,
+ activeLayerId: 'layer-1',
+ });
+ }
+
+ expect(glSpecErrors).toEqual([]);
+ });
+
+ it('hits baked below/above stack caches while drawing on active layer in a 25-layer stack', () => {
+ const { canvas, drawEvents } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+
+ const layers: LayerItem[] = [];
+ for (let i = 24; i >= 0; i--) {
+ const id = `layer-${i}`;
+ layers.push({
+ id,
+ name: id,
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: i < 12 && i % 2 === 1 ? 'multiply' : 'normal',
+ locked: false,
+ parentId: null,
+ });
+ writeTestPixel(grid, id, 100, 100);
+ }
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ const dims = { width: 1024, height: 1024 };
+
+ // Cold render builds below & above caches once
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-12',
+ });
+ expect(compositor.getStackCacheStats()).toEqual({
+ belowRebuilds: 1,
+ aboveRebuilds: 1,
+ cacheHits: 0,
+ });
+
+ // Hot drawing frame on active layer-12
+ drawEvents.length = 0;
+ writeTestPixel(grid, 'layer-12', 140, 140);
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-12',
+ });
+
+ expect(compositor.getStackCacheStats()).toEqual({
+ belowRebuilds: 1,
+ aboveRebuilds: 1,
+ cacheHits: 1,
+ });
+ // Only 3 shader draws on the hot path: active layer instanced batch + above cache blit + screen present
+ expect(drawEvents.length).toBe(3);
+ expect(drawEvents[0].type).toBe('drawArraysInstanced');
+ expect(drawEvents[0].programTag).toBe('instanced');
+ expect(drawEvents[1].programTag).toBe('blit');
+ expect(drawEvents[2].programTag).toBe('blit');
+ });
+
+ it('batches visible tiles into a single drawArraysInstanced call and falls back cleanly on TEXTURE_2D_ARRAY overflow', () => {
+ // 1. Batched fast path (pool capacity 256, 6 visible tiles -> 1 instanced draw call)
+ const batchedMock = createMockWebGL2Context({ maxArrayLayers: 256 });
+ const batchedCompositor = new ViewportCompositor(batchedMock.canvas);
+ const grid = new SparseTileGrid();
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-grid',
+ name: 'Grid',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+ // Write 6 distinct 256x256 tiles inside the visible viewport
+ writeTestPixel(grid, 'layer-grid', 10, 10);
+ writeTestPixel(grid, 'layer-grid', 270, 10);
+ writeTestPixel(grid, 'layer-grid', 530, 10);
+ writeTestPixel(grid, 'layer-grid', 10, 270);
+ writeTestPixel(grid, 'layer-grid', 270, 270);
+ writeTestPixel(grid, 'layer-grid', 530, 270);
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ const dims = { width: 800, height: 600 };
+
+ batchedCompositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-grid',
+ });
+
+ const instancedDraws = batchedMock.drawEvents.filter((e) => e.type === 'drawArraysInstanced');
+ expect(instancedDraws.length).toBe(1);
+ expect(instancedDraws[0].instances).toBe(6);
+ // texSubImage3D MUST NOT use UNPACK_PREMULTIPLY_ALPHA_WEBGL=true (WebGL2 GL_INVALID_OPERATION)
+ expect(batchedMock.glSpecErrors).toEqual([]);
+ // Verify TileBuffer straight-alpha data was preserved without CPU premultiplication mutation
+ const readBack = grid.readImageData('layer-grid', 10, 10, 1, 1);
+ expect(Array.from(readBack.data)).toEqual([200, 100, 50, 128]);
+
+ // 2. Overflow fallback (pool capacity = 2, 6 visible tiles -> falls back to 6 standard TEXTURE_2D drawArrays)
+ const overflowMock = createMockWebGL2Context({ maxArrayLayers: 2 });
+ const overflowCompositor = new ViewportCompositor(overflowMock.canvas);
+ overflowCompositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-grid',
+ });
+
+ const overflowInstanced = overflowMock.drawEvents.filter((e) => e.type === 'drawArraysInstanced');
+ const standardTileDraws = overflowMock.drawEvents.filter(
+ (e) => e.type === 'drawArrays' && e.programTag === 'standard' && e.uniforms.u_isBackground === 0
+ );
+ expect(overflowInstanced.length).toBe(0);
+ expect(standardTileDraws.length).toBe(6);
+ expect(overflowMock.glSpecErrors).toEqual([]);
+ const fallbackPremulOn = overflowMock.calls.some(
+ (c) => c.name === 'pixelStorei' && c.args[0] === 0x9241 && c.args[1] === true
+ );
+ expect(fallbackPremulOn).toBe(true);
+ });
+
+ it('composites activeDraftCanvas in-stack UNDERNEATH an upper semi-transparent Multiply layer', () => {
+ const { canvas, calls, drawEvents } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-upper-mul',
+ name: 'Shadow Multiply',
+ type: 'raster',
+ visible: true,
+ opacity: 0.5,
+ blendMode: 'multiply',
+ locked: false,
+ parentId: null,
+ },
+ {
+ id: 'layer-lower-active',
+ name: 'Base Lineart',
+ type: 'raster',
+ visible: true,
+ opacity: 1.0,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+ writeTestPixel(grid, 'layer-upper-mul', 100, 100, [50, 80, 200, 255]);
+ writeTestPixel(grid, 'layer-lower-active', 100, 100, [240, 200, 160, 255]);
+
+ const mockDraftCanvas = {
+ width: 800,
+ height: 600,
+ __draftHasContent: true,
+ __draftVersion: 1,
+ } as unknown as HTMLCanvasElement;
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ const dims = { width: 800, height: 600 };
+
+ // First render to warm below/above caches
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-lower-active',
+ activeDraftLayerId: 'layer-lower-active',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 1,
+ activeDraftSpace: 'viewport',
+ activeDraftOpacity: 1.0,
+ });
+
+ // Second render simulates next live stroke dab on lower layer
+ drawEvents.length = 0;
+ (mockDraftCanvas as any).__draftVersion = 2;
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-lower-active',
+ activeDraftLayerId: 'layer-lower-active',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 2,
+ activeDraftSpace: 'viewport',
+ activeDraftOpacity: 1.0,
+ });
+
+ // Verify exact rendering order:
+ // 0: active lower layer tiles (instanced)
+ // 1: activeDraftCanvas (viewportDraft) — INSIDE the stack on layer-lower-active
+ // 2: baked upper Multiply layer (blit with u_blendMode = multiply(1), u_hasBackdrop = 1) — ON TOP of live stroke!
+ // 3: final present to screen (blit with u_blendMode = 0)
+ const draftIdx = drawEvents.findIndex((e) => e.programTag === 'viewportDraft');
+ const upperMulIdx = drawEvents.findIndex(
+ (e) =>
+ e.programTag === 'blit' &&
+ e.uniforms.u_blendMode === BLEND_MODE_MAP['multiply'] &&
+ e.uniforms.u_hasBackdrop === 1
+ );
+ expect(draftIdx).toBeGreaterThanOrEqual(0);
+ expect(upperMulIdx).toBeGreaterThan(draftIdx);
+
+ // Zero copyTexSubImage2D calls throughout!
+ expect(calls.filter((c) => c.name === 'copyTexSubImage2D').length).toBe(0);
+
+ // Sanity check exported instanced shaders
+ expect(COMPOSITOR_INSTANCED_VERTEX_SHADER).toContain('in vec3 a_instanceData;');
+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain('sampler2DArray u_tileArrayTexture');
+ });
+
+ it('generates trilinear mipmaps for document-space activeDraftCanvas and matches 0.5 monochrome threshold', () => {
+ const { canvas, calls } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1.0,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ expressionColor: 'monochrome',
+ },
+ ];
+ writeTestPixel(grid, 'layer-1', 100, 100, [0, 0, 0, 255]);
+
+ const mockDraftCanvas = {
+ width: 1024,
+ height: 1024,
+ __draftHasContent: true,
+ __draftVersion: 1,
+ __draftSpace: 'document',
+ __draftDocRect: { x: 0, y: 0, width: 2048, height: 2048 },
+ } as unknown as HTMLCanvasElement;
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 0.15, rotation: 0 };
+ const dims = { width: 2048, height: 2048 };
+
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 1,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ expect(calls.some((c) => c.name === 'generateMipmap')).toBe(true);
+ expect(
+ calls.some(
+ (c) => c.name === 'texParameteri' && c.args[1] === 0x2801 && c.args[2] === 0x2703
+ )
+ ).toBe(true);
+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain('step(0.5, finalColor.a)');
+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain('step(0.5, finalColor.a)');
+ });
+ });
});
diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.ts
index 7785ffe..1db5233 100644
--- a/src/utils/__tests__/strokeHandshake.test.ts
+++ b/src/utils/__tests__/strokeHandshake.test.ts
@@ -6,6 +6,7 @@ import {
import { binarizeCanvasRect } from '../colorUtils';
import { TaperEngine } from '../../engine/TaperEngine';
import { COMPOSITOR_FRAGMENT_SHADER } from '../compositor';
+import { extractCoalescedEvents } from '../../components/CanvasArea';
import { LayerPixelSampler } from '../colorMixingEngine';
import {
drawRadialDot,
@@ -367,4 +368,43 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
expect(grid.readImageData(layerId, 10, 10, 1, 1).data[3]).toBe(255);
expect(grid.readImageData(layerId, 50, 50, 1, 1).data[3]).toBe(0);
});
+
+ it('guards against Windows Ink/WebView2 coalesced pointer coordinate drift on pointerdown and pointermove', () => {
+ const downNative = {
+ type: 'pointerdown',
+ clientX: 257,
+ clientY: 55,
+ getCoalescedEvents: () => [{ clientX: 282, clientY: 88 }],
+ } as unknown as PointerEvent;
+ expect(extractCoalescedEvents({ nativeEvent: downNative } as React.PointerEvent<HTMLElement>)).toEqual([
+ downNative,
+ ]);
+
+ const offsetMoveNative = {
+ type: 'pointermove',
+ clientX: 257,
+ clientY: 55,
+ getCoalescedEvents: () => [
+ { clientX: 278, clientY: 82 },
+ { clientX: 282, clientY: 88 },
+ ],
+ } as unknown as PointerEvent;
+ expect(extractCoalescedEvents({ nativeEvent: offsetMoveNative } as React.PointerEvent<HTMLElement>)).toEqual([
+ offsetMoveNative,
+ ]);
+
+ const validCoalesced = [
+ { clientX: 254, clientY: 53 },
+ { clientX: 257.4, clientY: 55.2 },
+ ];
+ const alignedMoveNative = {
+ type: 'pointermove',
+ clientX: 257,
+ clientY: 55,
+ getCoalescedEvents: () => validCoalesced,
+ } as unknown as PointerEvent;
+ expect(extractCoalescedEvents({ nativeEvent: alignedMoveNative } as React.PointerEvent<HTMLElement>)).toEqual(
+ validCoalesced
+ );
+ });
});
diff --git a/src/utils/__tests__/strokePipelineIntegration.test.ts b/src/utils/__tests__/strokePipelineIntegration.test.ts
new file mode 100644
index 0000000..6eaafc7
--- /dev/null
+++ b/src/utils/__tests__/strokePipelineIntegration.test.ts
@@ -0,0 +1,406 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ StrokePipeline,
+ computeClampedBakeDirtyRect,
+ encodePointerType,
+ POINTER_TYPE_MOUSE,
+ POINTER_TYPE_PEN,
+ POINTER_TYPE_TOUCH,
+ ViewportTransform,
+} from '../../engine/StrokePipeline';
+import { CubicBezierSegment } from '../../engine/SplineGenerator';
+import {
+ canUseWebGlForTexturedBrush,
+ canUseWebGlForRadialBrush,
+ renderCompleteTexturedStroke,
+ renderCompleteRadialStroke,
+ TexturedBrushOptions,
+} from '../stampEngine';
+import { WebGlBrushEngine, GpuDab } from '../webglBrushEngine';
+import { Point } from '../../types/editor';
+
+function makeMock2DCtx(w = 1000, h = 1000) {
+ const ops: string[] = [];
+ const ctx = {
+ canvas: { width: w, height: h },
+ strokeStyle: '#000000',
+ fillStyle: '#000000',
+ lineCap: 'round',
+ lineJoin: 'round',
+ lineWidth: 1,
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ imageSmoothingEnabled: true,
+ save: vi.fn(),
+ restore: vi.fn(),
+ resetTransform: vi.fn(),
+ clearRect: vi.fn(() => ops.push('clearRect')),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ bezierCurveTo: vi.fn(() => ops.push('bezier')),
+ stroke: vi.fn(() => ops.push('stroke')),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ scale: vi.fn(),
+ drawImage: vi.fn(() => ops.push('drawImage')),
+ fillRect: vi.fn(),
+ createImageData: (cw: number, ch: number) => ({ width: cw, height: ch, data: new Uint8ClampedArray(cw * ch * 4) }),
+ getImageData: vi.fn((_x: number, _y: number, cw: number, ch: number) => ({
+ width: cw,
+ height: ch,
+ data: new Uint8ClampedArray(cw * ch * 4),
+ })),
+ putImageData: vi.fn(),
+ };
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, raw: ctx, ops };
+}
+
+if (typeof (globalThis as any).document === 'undefined') {
+ (globalThis as any).document = {
+ createElement: () => {
+ const m = makeMock2DCtx(128, 128);
+ return { width: 128, height: 128, getContext: () => m.ctx };
+ },
+ };
+}
+
+describe('StrokePipeline: Ring Buffer, Stabilization, Taper, Prediction & Bake DirtyRect', () => {
+ let pipeline: StrokePipeline;
+
+ beforeEach(() => {
+ pipeline = new StrokePipeline();
+ });
+
+ it('ingests and drains samples via Float64Array ring buffer preserving tilt, twist, pressure and pointerType', () => {
+ pipeline.beginStroke({ stabilizerLevel: 0, brushSize: 12, color: '#000000' });
+ pipeline.enqueueSample(10, 20, 0.4, 15, -10, 45, 100, encodePointerType('pen'));
+ pipeline.enqueueSample(30, 40, 0.8, 25, -5, 90, 116, encodePointerType('touch'));
+ pipeline.enqueueSample(50, 60, 0.5, 0, 0, 0, 132, encodePointerType('mouse'));
+
+ expect(pipeline.getPendingCount()).toBe(3);
+
+ const drainedPts: Array<{ x: number; y: number; tiltX: number; tiltY: number; twist: number; pointerType: string }> = [];
+ const segments: number[] = [];
+
+ const count = pipeline.drain({
+ onPoint: (pt) => {
+ drainedPts.push({
+ x: pt.x,
+ y: pt.y,
+ tiltX: pt.tiltX,
+ tiltY: pt.tiltY,
+ twist: pt.twist,
+ pointerType: pt.pointerType,
+ });
+ },
+ onSegment: () => {
+ segments.push(1);
+ },
+ });
+
+ expect(count).toBe(3);
+ expect(pipeline.getPendingCount()).toBe(0);
+ expect(drainedPts).toHaveLength(3);
+ expect(drainedPts[0]).toMatchObject({ x: 10, y: 20, tiltX: 15, tiltY: -10, twist: 45, pointerType: 'pen' });
+ expect(drainedPts[1]).toMatchObject({ x: 30, y: 40, tiltX: 25, tiltY: -5, twist: 90, pointerType: 'touch' });
+ expect(drainedPts[2]).toMatchObject({ x: 50, y: 60, tiltX: 0, tiltY: 0, twist: 0, pointerType: 'mouse' });
+ // Third knot seals P1 -> P2 segment
+ expect(segments.length).toBe(1);
+ });
+
+ it('handles ring buffer wraparound safely when exceeding BUFFER_CAPACITY (2048) without draining', () => {
+ pipeline.beginStroke({ stabilizerLevel: 0, brushSize: 10 });
+ const total = StrokePipeline.BUFFER_CAPACITY + 120;
+ for (let i = 0; i < total; i++) {
+ pipeline.enqueueSample(i, i * 0.5, 0.6, 0, 0, 0, i * 4, POINTER_TYPE_PEN);
+ }
+
+ // Ring buffer caps unread samples at exact BUFFER_CAPACITY (2048) without overwriting unread tail
+ expect(pipeline.getPendingCount()).toBe(StrokePipeline.BUFFER_CAPACITY);
+
+ const xs: number[] = [];
+ pipeline.drain({
+ onPoint: (pt) => xs.push(pt.x),
+ });
+
+ expect(pipeline.getPendingCount()).toBe(0);
+ // Latest sample MUST be the final enqueued coordinate, and oldest retained is exact wraparound boundary
+ expect(xs[xs.length - 1]).toBe(total - 1);
+ expect(xs[0]).toBe(total - StrokePipeline.BUFFER_CAPACITY);
+ });
+
+ it('applies 1-Euro stabilization and sharp corner snapping when stabilizerLevel > 0', () => {
+ pipeline.beginStroke({ stabilizerLevel: 20, zoom: 1.0, sharpCorners: true, brushSize: 10 });
+
+ let t = 1000;
+ for (let i = 0; i <= 5; i++) {
+ pipeline.enqueueSample(i * 10, 0, 0.7, 0, 0, 0, t, POINTER_TYPE_PEN);
+ t += 16;
+ }
+ // Sharp 90-degree turn upward
+ pipeline.enqueueSample(50, 25, 0.7, 0, 0, 0, t, POINTER_TYPE_PEN);
+
+ const corners: boolean[] = [];
+ const cornerSegs: boolean[] = [];
+ const emittedSegs: Array<{ p0x: number; p0y: number; p3x: number; p3y: number }> = [];
+ const points: Array<{ x: number; y: number }> = [];
+
+ pipeline.drain({
+ onPoint: (pt) => {
+ points.push({ x: pt.x, y: pt.y });
+ corners.push(pt.isCorner);
+ },
+ onSegment: (seg, isCorner) => {
+ cornerSegs.push(isCorner);
+ emittedSegs.push({ p0x: seg.p0.x, p0y: seg.p0.y, p3x: seg.p3.x, p3y: seg.p3.y });
+ },
+ });
+
+ // Intermediate straight points are smoothed (lag slightly behind raw x)
+ expect(points[3].x).toBeLessThan(30);
+ // Sharp 90-degree corner triggers corner snap & sharp corner segment
+ expect(corners[corners.length - 1]).toBe(true);
+ expect(points[points.length - 1].x).toBeCloseTo(50, 0);
+ expect(points[points.length - 1].y).toBeCloseTo(25, 0);
+ expect(cornerSegs).toContain(true);
+ // Zero gaps across every sealed segment leading into the corner apex (C0 continuous!)
+ expect(emittedSegs.length).toBeGreaterThanOrEqual(5);
+ for (let i = 1; i < emittedSegs.length; i++) {
+ expect(emittedSegs[i].p0x).toBeCloseTo(emittedSegs[i - 1].p3x, 4);
+ expect(emittedSegs[i].p0y).toBeCloseTo(emittedSegs[i - 1].p3y, 4);
+ }
+ expect(emittedSegs[emittedSegs.length - 1].p3x).toBeCloseTo(50, 0);
+ expect(emittedSegs[emittedSegs.length - 1].p3y).toBeCloseTo(25, 0);
+ });
+
+ it('emits ballistic flick taper points on fast pointerup finalizeStroke and none on slow release', () => {
+ // 1. Fast flick release
+ pipeline.beginStroke({ stabilizerLevel: 0, brushSize: 20 });
+ pipeline.enqueueSample(0, 100, 0.8, 0, 0, 0, 1000, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(30, 100, 0.8, 0, 0, 0, 1010, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(65, 100, 0.8, 0, 0, 0, 1020, POINTER_TYPE_PEN);
+ pipeline.drain();
+
+ const flickWidths: number[] = [];
+ pipeline.finalizeStroke(1028, {
+ enableFlickTaper: true,
+ onPoint: (pt) => flickWidths.push(pt.width),
+ });
+
+ expect(flickWidths.length).toBeGreaterThanOrEqual(6);
+ for (let i = 1; i < flickWidths.length; i++) {
+ expect(flickWidths[i]).toBeLessThan(flickWidths[i - 1]);
+ }
+
+ // 2. Slow exit release (below minFlickSpeed)
+ pipeline.beginStroke({ stabilizerLevel: 0, brushSize: 20 });
+ pipeline.enqueueSample(0, 100, 0.8, 0, 0, 0, 2000, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(1, 100, 0.8, 0, 0, 0, 2100, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(2, 100, 0.8, 0, 0, 0, 2200, POINTER_TYPE_PEN);
+ pipeline.drain();
+
+ const slowFlickWidths: number[] = [];
+ const sealedTailSegs: CubicBezierSegment[] = [];
+ pipeline.finalizeStroke(2250, {
+ enableFlickTaper: true,
+ onPoint: (pt) => slowFlickWidths.push(pt.width),
+ onSegment: (seg) => sealedTailSegs.push({ p0: { ...seg.p0 }, c1: { ...seg.c1 }, c2: { ...seg.c2 }, p3: { ...seg.p3 } }),
+ });
+
+ expect(slowFlickWidths).toHaveLength(0);
+ expect(sealedTailSegs).toHaveLength(1);
+ });
+
+ it('keeps predicted tail strictly ephemeral (never mutates dirtyRect or leaks into scratch canvas)', () => {
+ const scratch = makeMock2DCtx(800, 600);
+ const predicted = makeMock2DCtx(800, 600);
+ const view: ViewportTransform = {
+ panX: 0,
+ panY: 0,
+ zoom: 1,
+ rotation: 0,
+ canvasWidth: 800,
+ canvasHeight: 600,
+ };
+
+ pipeline.bindContexts(scratch.ctx, predicted.ctx);
+ pipeline.setStabilizerLevel(0);
+ pipeline.setBrushParameters(10, '#000000');
+
+ const makeEvt = (x: number, y: number, ts: number, pred?: Array<{ clientX: number; clientY: number }>) =>
+ ({
+ pointerId: 1,
+ pointerType: 'pen',
+ clientX: x,
+ clientY: y,
+ pressure: 0.7,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ buttons: 1,
+ timeStamp: ts,
+ getCoalescedEvents: () => [],
+ getPredictedEvents: () =>
+ (pred || []).map((p) => ({
+ pointerId: 1,
+ pointerType: 'pen',
+ clientX: p.clientX,
+ clientY: p.clientY,
+ pressure: 0.6,
+ timeStamp: ts + 8,
+ })),
+ }) as unknown as PointerEvent;
+
+ pipeline.onPointerDown(makeEvt(100, 100, 100), view);
+ pipeline.onPointerMove(makeEvt(120, 100, 116, [{ clientX: 600, clientY: 500 }]), view);
+
+ // Predicted overlay drew the speculative stroke, and dirtyRect did NOT expand to (600, 500)
+ expect(predicted.raw.bezierCurveTo).toHaveBeenCalled();
+ expect(pipeline.dirtyRect.maxX).toBeLessThan(300);
+ expect(pipeline.dirtyRect.maxY).toBeLessThan(300);
+
+ // Also verify buildPredictedSegments does not mutate dirtyRect or knotCount
+ const dirtyBefore = { ...pipeline.dirtyRect };
+ const knotsBefore = pipeline.getKnotCount();
+ const predSegs: number[] = [];
+ pipeline.buildPredictedSegments([{ x: 135, y: 100, pressure: 0.5 }], 20, () => predSegs.push(1));
+ expect(predSegs.length).toBeGreaterThanOrEqual(2);
+ expect(pipeline.dirtyRect).toEqual(dirtyBefore);
+ expect(pipeline.getKnotCount()).toBe(knotsBefore);
+
+ // On pointerup, predicted overlay is cleared cleanly
+ pipeline.onPointerUp(makeEvt(125, 100, 132), view);
+ expect(predicted.raw.clearRect).toHaveBeenCalledWith(0, 0, 800, 600);
+ expect(scratch.raw.getImageData).not.toHaveBeenCalled();
+ expect(predicted.raw.getImageData).not.toHaveBeenCalled();
+ });
+
+ it('computes clamped bake DirtyRect on pointerup accurately with brush size and wetEdge margins', () => {
+ // Uninitialized dirty rect returns null
+ expect(computeClampedBakeDirtyRect({ minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }, 4096, 4096, 10)).toBeNull();
+ expect(computeClampedBakeDirtyRect(null, 4096, 4096, 10)).toBeNull();
+
+ // Standard interior dirty rect with brush size 20 -> pad = max(32, 30) = 32
+ const interior = computeClampedBakeDirtyRect({ minX: 100.4, minY: 200.7, maxX: 300.2, maxY: 400.1 }, 4096, 4096, 20, 0);
+ expect(interior).toEqual({
+ x: 68,
+ y: 168,
+ width: 265,
+ height: 265,
+ });
+
+ // Edge-clamped dirty rect at document boundary (0, 0) .. (1024, 768)
+ const clamped = computeClampedBakeDirtyRect({ minX: 5, minY: 10, maxX: 1020, maxY: 760 }, 1024, 768, 40, 0);
+ expect(clamped).toEqual({
+ x: 0,
+ y: 0,
+ width: 1024,
+ height: 768,
+ });
+
+ // Wet edge adds wetEdgeRadius * 2 + 8 extra margin
+ const wet = computeClampedBakeDirtyRect({ minX: 500, minY: 500, maxX: 520, maxY: 520 }, 4096, 4096, 10, 0.5, 5.0);
+ // pad = 32 + (5*2 + 8) = 50 -> min=450, max=570 -> width=120
+ expect(wet).toEqual({
+ x: 450,
+ y: 450,
+ width: 120,
+ height: 120,
+ });
+ });
+
+ it('encodes pointer types deterministically', () => {
+ expect(encodePointerType('pen')).toBe(POINTER_TYPE_PEN);
+ expect(encodePointerType('mouse')).toBe(POINTER_TYPE_MOUSE);
+ expect(encodePointerType('touch')).toBe(POINTER_TYPE_TOUCH);
+ });
+});
+
+describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', () => {
+ const samplePoints: Point[] = [
+ { x: 20, y: 20, pressure: 0.6, width: 14, tiltX: 10, tiltY: 5 },
+ { x: 50, y: 25, pressure: 0.8, width: 18, tiltX: 12, tiltY: 6 },
+ { x: 90, y: 35, pressure: 0.7, width: 16, tiltX: 8, tiltY: 4 },
+ ];
+
+ const mockTipImage = {
+ naturalWidth: 64,
+ naturalHeight: 64,
+ width: 64,
+ height: 64,
+ src: 'data:image/png;base64,stub',
+ } as unknown as HTMLImageElement;
+
+ it('routes textured and soft radial brushes through WebGlBrushEngine batch instancing when GPU is available', () => {
+ const gpu = WebGlBrushEngine.getInstance();
+ const availSpy = vi.spyOn(gpu, 'isAvailable').mockReturnValue(true);
+ const renderedBatches: GpuDab[][] = [];
+ const renderSpy = vi.spyOn(gpu, 'renderDabsToContext').mockImplementation((_ctx, dabs) => {
+ renderedBatches.push([...dabs]);
+ return true;
+ });
+
+ try {
+ // 1. Textured .sut/preset brush
+ const texMock = makeMock2DCtx(256, 256);
+ const texOpts: TexturedBrushOptions = {
+ size: 18,
+ flow: 0.85,
+ spacing: 0.1,
+ antiAlias: 2,
+ useGpu: true,
+ useTilt: true,
+ };
+ expect(canUseWebGlForTexturedBrush(texOpts)).toBe(true);
+ renderCompleteTexturedStroke(texMock.ctx, samplePoints, '#224488', mockTipImage, texOpts);
+
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ expect(renderedBatches[0].length).toBeGreaterThan(5);
+ // Zero per-dab Canvas 2D drawImage calls on CPU when GPU succeeds!
+ expect(texMock.raw.drawImage).not.toHaveBeenCalled();
+
+ // 2. Soft radial brush
+ const radMock = makeMock2DCtx(256, 256);
+ expect(canUseWebGlForRadialBrush({ useGpu: true, antiAlias: 2 })).toBe(true);
+ renderCompleteRadialStroke(radMock.ctx, samplePoints, '#cc2244', 0.35, 0.9, 0.1, false, false, 1.0, 0, {
+ useGpu: true,
+ antiAlias: 2,
+ });
+
+ expect(renderSpy).toHaveBeenCalledTimes(2);
+ expect(renderedBatches[1].length).toBeGreaterThan(5);
+ expect(radMock.raw.drawImage).not.toHaveBeenCalled();
+ } finally {
+ availSpy.mockRestore();
+ renderSpy.mockRestore();
+ }
+ });
+
+ it('falls back cleanly to Canvas 2D for binary pixel AA=0, colorMixingEngine, multi-subTip, or GPU failure', () => {
+ const gpu = WebGlBrushEngine.getInstance();
+ const availSpy = vi.spyOn(gpu, 'isAvailable').mockReturnValue(true);
+ const renderSpy = vi.spyOn(gpu, 'renderDabsToContext').mockReturnValue(false);
+
+ try {
+ // Eligibility gates
+ expect(canUseWebGlForTexturedBrush({ size: 10, antiAlias: 0, useGpu: true })).toBe(false);
+ expect(canUseWebGlForTexturedBrush({ size: 10, colorMixing: true, useGpu: true })).toBe(false);
+ expect(canUseWebGlForTexturedBrush({ size: 10, useGpu: false })).toBe(false);
+ expect(canUseWebGlForTexturedBrush({ size: 10, subTipImages: [mockTipImage, mockTipImage], useGpu: true })).toBe(false);
+ expect(canUseWebGlForRadialBrush({ antiAlias: 0, useGpu: true })).toBe(false);
+ expect(canUseWebGlForRadialBrush({ colorMixing: true, useGpu: true })).toBe(false);
+
+ // When renderDabsToContext returns false (e.g. context lost), falls back to Canvas 2D drawImage
+ const fallbackMock = makeMock2DCtx(256, 256);
+ renderCompleteRadialStroke(fallbackMock.ctx, samplePoints, '#112233', 0.8, 0.9, 0.15, false, false, 1.0, 0, {
+ useGpu: true,
+ antiAlias: 2,
+ });
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ expect(fallbackMock.raw.drawImage).toHaveBeenCalled();
+ } finally {
+ availSpy.mockRestore();
+ renderSpy.mockRestore();
+ }
+ });
+});
diff --git a/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx b/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx
new file mode 100644
index 0000000..787631c
--- /dev/null
+++ b/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx
@@ -0,0 +1,770 @@
+import React, { Profiler, act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ useCanvasNavigation,
+ MIN_ZOOM,
+ MAX_ZOOM,
+ NAV_STATE_COMMIT_DEBOUNCE_MS,
+ CAMERA_CHANGE_EVENT,
+ CameraTransformState,
+ CanvasNavigationHandle,
+} from '../../hooks/useCanvasNavigation';
+import {
+ screenToCanvas,
+ clientToDocument,
+ canvasToScreen,
+ getCanvasToViewportMatrix,
+ getVisibleCanvasBounds,
+} from '../canvasUtils';
+import { SparseTileGrid } from '../tileEngine';
+import { StrokePipeline } from '../../engine/StrokePipeline';
+
+/**
+ * Lightweight DOM shim for running React 19 createRoot + Profiler + DOM events in Vitest Node environment.
+ */
+class MiniElement extends EventTarget {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public ownerDocument: any;
+ public parentNode: any = null;
+ public childNodes: any[] = [];
+ public style: Record<string, string> = {};
+ public isContentEditable = false;
+ public clientWidth = 1200;
+ public clientHeight = 900;
+ private attrs = new Map<string, string>();
+ private rect = {
+ left: 100,
+ top: 50,
+ width: 1200,
+ height: 900,
+ right: 1300,
+ bottom: 950,
+ x: 100,
+ y: 50,
+ toJSON: () => ({}),
+ };
+
+ constructor(tag: string, ownerDocument: any) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ this.ownerDocument = ownerDocument;
+ }
+
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+
+ appendChild(child: any) {
+ if (child.parentNode) {
+ child.parentNode.removeChild(child);
+ }
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild(child: any) {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore(newNode: any, refNode: any) {
+ if (newNode.parentNode) {
+ newNode.parentNode.removeChild(newNode);
+ }
+ newNode.parentNode = this;
+ const idx = refNode ? this.childNodes.indexOf(refNode) : -1;
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 0, newNode);
+ } else {
+ this.childNodes.push(newNode);
+ }
+ return newNode;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+
+ getBoundingClientRect(): DOMRect {
+ return {
+ ...this.rect,
+ width: this.clientWidth,
+ height: this.clientHeight,
+ right: this.rect.left + this.clientWidth,
+ bottom: this.rect.top + this.clientHeight,
+ } as DOMRect;
+ }
+}
+
+class MiniTextNode {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public nodeValue: string;
+ public ownerDocument: any;
+ public parentNode: any = null;
+
+ constructor(text: string, ownerDocument: any) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+class MiniCommentNode {
+ public nodeType = 8;
+ public nodeName = '#comment';
+ public nodeValue: string;
+ public ownerDocument: any;
+ public parentNode: any = null;
+
+ constructor(text: string, ownerDocument: any) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+interface RafQueueController {
+ flushNextFrame: () => void;
+ flushAllFrames: () => void;
+ pendingCount: () => number;
+}
+
+function installMiniDomEnvironment(): {
+ container: MiniElement;
+ raf: RafQueueController;
+ cleanup: () => void;
+} {
+ const prevGlobals: Record<string, any> = {
+ window: (globalThis as any).window,
+ document: (globalThis as any).document,
+ navigator: (globalThis as any).navigator,
+ HTMLElement: (globalThis as any).HTMLElement,
+ ResizeObserver: (globalThis as any).ResizeObserver,
+ requestAnimationFrame: (globalThis as any).requestAnimationFrame,
+ cancelAnimationFrame: (globalThis as any).cancelAnimationFrame,
+ IS_REACT_ACT_ENVIRONMENT: (globalThis as any).IS_REACT_ACT_ENVIRONMENT,
+ };
+
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+ const winTarget = new EventTarget();
+ const docTarget = new EventTarget();
+
+ const mockDoc: any = {
+ nodeType: 9,
+ nodeName: '#document',
+ documentElement: null as any,
+ body: null as any,
+ activeElement: null as any,
+ defaultView: null as any,
+ createElement: (tag: string) => new MiniElement(tag, mockDoc),
+ createElementNS: (_ns: string, tag: string) => new MiniElement(tag, mockDoc),
+ createTextNode: (text: string) => new MiniTextNode(text, mockDoc),
+ createComment: (text: string) => new MiniCommentNode(text, mockDoc),
+ querySelector: () => null,
+ addEventListener: docTarget.addEventListener.bind(docTarget),
+ removeEventListener: docTarget.removeEventListener.bind(docTarget),
+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
+ };
+
+ mockDoc.documentElement = new MiniElement('html', mockDoc);
+ mockDoc.body = new MiniElement('body', mockDoc);
+ mockDoc.documentElement.appendChild(mockDoc.body);
+ mockDoc.activeElement = mockDoc.body;
+
+ class MockHTMLIFrameElement extends MiniElement {}
+
+ let nextRafId = 1;
+ const rafCallbacks = new Map<number, FrameRequestCallback>();
+ let frameTimestamp = 16;
+
+ const requestAnimationFrameMock = (cb: FrameRequestCallback): number => {
+ const id = nextRafId++;
+ rafCallbacks.set(id, cb);
+ return id;
+ };
+
+ const cancelAnimationFrameMock = (id: number): void => {
+ rafCallbacks.delete(id);
+ };
+
+ const mockWin: any = {
+ innerWidth: 1600,
+ innerHeight: 1000,
+ devicePixelRatio: 1,
+ document: mockDoc,
+ Node: MiniElement,
+ Element: MiniElement,
+ HTMLElement: MiniElement,
+ SVGElement: MiniElement,
+ HTMLIFrameElement: MockHTMLIFrameElement,
+ Event,
+ CustomEvent,
+ addEventListener: winTarget.addEventListener.bind(winTarget),
+ removeEventListener: winTarget.removeEventListener.bind(winTarget),
+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
+ requestAnimationFrame: requestAnimationFrameMock,
+ cancelAnimationFrame: cancelAnimationFrameMock,
+ setTimeout: globalThis.setTimeout.bind(globalThis),
+ clearTimeout: globalThis.clearTimeout.bind(globalThis),
+ };
+ mockDoc.defaultView = mockWin;
+
+ class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+
+ Object.defineProperty(globalThis, 'window', { value: mockWin, configurable: true, writable: true });
+ Object.defineProperty(globalThis, 'document', { value: mockDoc, configurable: true, writable: true });
+ Object.defineProperty(globalThis, 'HTMLElement', { value: MiniElement, configurable: true, writable: true });
+ Object.defineProperty(globalThis, 'ResizeObserver', { value: MockResizeObserver, configurable: true, writable: true });
+ Object.defineProperty(globalThis, 'requestAnimationFrame', {
+ value: requestAnimationFrameMock,
+ configurable: true,
+ writable: true,
+ });
+ Object.defineProperty(globalThis, 'cancelAnimationFrame', {
+ value: cancelAnimationFrameMock,
+ configurable: true,
+ writable: true,
+ });
+
+ const container = new MiniElement('div', mockDoc);
+ mockDoc.body.appendChild(container);
+
+ const raf: RafQueueController = {
+ flushNextFrame: () => {
+ const entries = Array.from(rafCallbacks.entries());
+ rafCallbacks.clear();
+ frameTimestamp += 16.67;
+ for (const [, cb] of entries) {
+ cb(frameTimestamp);
+ }
+ },
+ flushAllFrames: () => {
+ while (rafCallbacks.size > 0) {
+ raf.flushNextFrame();
+ }
+ },
+ pendingCount: () => rafCallbacks.size,
+ };
+
+ const cleanup = () => {
+ for (const [k, v] of Object.entries(prevGlobals)) {
+ if (v === undefined) {
+ delete (globalThis as any)[k];
+ } else {
+ Object.defineProperty(globalThis, k, { value: v, configurable: true, writable: true });
+ }
+ }
+ };
+
+ return { container, raf, cleanup };
+}
+
+describe('Zero-Rerender Camera Navigation & Non-Destructive View Flip', () => {
+ describe('React Profiler Render-Counter Verification (Wheel Zoom & Space+Drag)', () => {
+ let env: ReturnType<typeof installMiniDomEnvironment>;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ env = installMiniDomEnvironment();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root!.unmount();
+ });
+ root = null;
+ }
+ env.cleanup();
+ vi.useRealTimers();
+ });
+
+ it('causes ZERO App re-renders per frame during rapid wheel zoom and Space+Drag, committing state once after gesture completion', () => {
+ let appRenderCount = 0;
+ let profilerCommitCount = 0;
+ let exposedNav: ReturnType<typeof useCanvasNavigation> | null = null;
+ const compositorFrames: CameraTransformState[] = [];
+ const customEventsReceived: CameraTransformState[] = [];
+ let artboardEl: MiniElement | null = null;
+
+ window.addEventListener(CAMERA_CHANGE_EVENT, ((e: CustomEvent<CameraTransformState>) => {
+ customEventsReceived.push(e.detail);
+ }) as EventListener);
+
+ const MemoCanvasSubscriber = React.memo(function MemoCanvasSubscriber({
+ navigation,
+ viewportRef,
+ }: {
+ navigation: CanvasNavigationHandle;
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ }) {
+ React.useEffect(() => {
+ return navigation.subscribeCamera((cam) => {
+ compositorFrames.push(cam);
+ if (artboardEl) {
+ const sx = (cam.flipX ? -1 : 1) * cam.zoom;
+ const sy = (cam.flipY ? -1 : 1) * cam.zoom;
+ artboardEl.style.transform = `translate3d(${cam.pan.x}px, ${cam.pan.y}px, 0) rotate(${cam.rotation}deg) scale(${sx}, ${sy})`;
+ }
+ });
+ }, [navigation]);
+
+ return (
+ <div ref={viewportRef as any}>
+ <div
+ ref={(el) => {
+ artboardEl = el as unknown as MiniElement | null;
+ }}
+ />
+ </div>
+ );
+ });
+
+ function MockAppRoot() {
+ appRenderCount++;
+ const nav = useCanvasNavigation({
+ dimensions: { width: 1440, height: 900, dpi: 300 },
+ activeDocumentId: 'doc-main',
+ });
+ exposedNav = nav;
+
+ return (
+ <div>
+ <span data-zoom={nav.zoom} data-flip-x={String(nav.flipX)} />
+ <MemoCanvasSubscriber navigation={nav.navigation} viewportRef={nav.viewportRef} />
+ </div>
+ );
+ }
+
+ root = createRoot(env.container as unknown as HTMLElement);
+ act(() => {
+ root!.render(
+ <Profiler
+ id="AppRoot"
+ onRender={() => {
+ profilerCommitCount++;
+ }}
+ >
+ <MockAppRoot />
+ </Profiler>
+ );
+ });
+
+ expect(exposedNav).not.toBeNull();
+ const viewportEl = exposedNav!.viewportRef.current as unknown as MiniElement;
+ expect(viewportEl).not.toBeNull();
+
+ // Reset counters after initial mount
+ appRenderCount = 0;
+ profilerCommitCount = 0;
+ compositorFrames.length = 0;
+ customEventsReceived.length = 0;
+
+ // 1. Simulate 40 rapid wheel zoom events across 40 animation frames (~8ms apart, < 140ms debounce)
+ for (let frame = 0; frame < 40; frame++) {
+ const wheelEv = new Event('wheel', { bubbles: true, cancelable: true }) as any;
+ wheelEv.clientX = 650;
+ wheelEv.clientY = 480;
+ wheelEv.deltaY = -45;
+ wheelEv.deltaMode = 0;
+ viewportEl.dispatchEvent(wheelEv);
+
+ env.raf.flushNextFrame();
+ vi.advanceTimersByTime(8);
+ }
+
+ // CRITICAL ACCEPTANCE CHECK:
+ // Root App component MUST NOT re-render on any of the 40 wheel + rAF frames!
+ expect(appRenderCount).toBe(0);
+ expect(profilerCommitCount).toBe(0);
+
+ // Meanwhile, direct subscriber & CustomEvent updated DOM transform and compositor on every single frame!
+ expect(compositorFrames.length).toBe(40);
+ expect(customEventsReceived.length).toBe(40);
+ expect(exposedNav!.zoomRef.current).toBeGreaterThan(1.0);
+ expect(artboardEl!.style.transform).toContain(`scale(${exposedNav!.zoomRef.current}, ${exposedNav!.zoomRef.current})`);
+
+ // React state (`nav.zoom`) has not committed yet because wheel inertia just finished < 140ms ago
+ // Advance past debounce window (140ms) -> commits to React UI state ONCE
+ act(() => {
+ vi.advanceTimersByTime(NAV_STATE_COMMIT_DEBOUNCE_MS + 10);
+ });
+
+ expect(appRenderCount).toBe(1);
+ expect(profilerCommitCount).toBe(1);
+ expect(exposedNav!.zoom).toBeCloseTo(exposedNav!.zoomRef.current, 6);
+
+ // 2. Simulate Space + Drag panning across 50 pointermove + rAF frames
+ act(() => {
+ const spaceDown = new Event('keydown', { bubbles: true, cancelable: true }) as any;
+ spaceDown.code = 'Space';
+ spaceDown.key = ' ';
+ window.dispatchEvent(spaceDown);
+ });
+ expect(exposedNav!.isSpaceDown).toBe(true);
+
+ act(() => {
+ exposedNav!.startPan({
+ clientX: 500,
+ clientY: 400,
+ preventDefault: () => {},
+ } as unknown as PointerEvent);
+ });
+ expect(exposedNav!.isPanning).toBe(true);
+
+ // Reset render counters right after drag begins to measure all 50 active drag frames
+ appRenderCount = 0;
+ profilerCommitCount = 0;
+ compositorFrames.length = 0;
+ const panBeforeDrag = { ...exposedNav!.panRef.current };
+
+ for (let i = 1; i <= 50; i++) {
+ const moveEv = new Event('pointermove', { bubbles: true }) as any;
+ moveEv.clientX = 500 + i * 4;
+ moveEv.clientY = 400 + i * 3;
+ window.dispatchEvent(moveEv);
+
+ env.raf.flushNextFrame();
+ vi.advanceTimersByTime(16);
+ }
+
+ // CRITICAL ACCEPTANCE CHECK:
+ // ZERO App re-renders across all 50 frames (800ms > 140ms!) of active Space + Drag panning!
+ expect(appRenderCount).toBe(0);
+ expect(profilerCommitCount).toBe(0);
+ expect(compositorFrames.length).toBe(50);
+ expect(exposedNav!.panRef.current).toEqual({
+ x: panBeforeDrag.x + 200,
+ y: panBeforeDrag.y + 150,
+ });
+
+ // Release pointerup -> commits final pan to React state in 1 batched render
+ act(() => {
+ window.dispatchEvent(new Event('pointerup', { bubbles: true }));
+ });
+
+ expect(appRenderCount).toBe(1);
+ expect(exposedNav!.isPanning).toBe(false);
+ expect(exposedNav!.pan).toEqual({
+ x: panBeforeDrag.x + 200,
+ y: panBeforeDrag.y + 150,
+ });
+
+ // 3. Verify MIN_ZOOM = 0.01 and MAX_ZOOM = 32.0 clamping and resetRotation remain intact
+ act(() => {
+ exposedNav!.setZoom(999);
+ });
+ expect(exposedNav!.zoom).toBe(MAX_ZOOM);
+ expect(exposedNav!.zoomRef.current).toBe(MAX_ZOOM);
+
+ act(() => {
+ exposedNav!.setZoom(0.00001);
+ });
+ expect(exposedNav!.zoom).toBe(MIN_ZOOM);
+ expect(exposedNav!.zoomRef.current).toBe(MIN_ZOOM);
+
+ act(() => {
+ exposedNav!.setRotation(33);
+ });
+ expect(exposedNav!.rotation).toBe(33);
+ act(() => {
+ exposedNav!.resetRotation();
+ });
+ expect(exposedNav!.rotation).toBe(0);
+ expect(exposedNav!.rotationRef.current).toBe(0);
+ });
+
+ it('mirrors viewport non-destructively via toggleFlipHorizontal / toggleFlipVertical / resetViewFlip', () => {
+ let exposedNav: ReturnType<typeof useCanvasNavigation> | null = null;
+ const dims = { width: 1000, height: 800, dpi: 300 };
+
+ function Host() {
+ const nav = useCanvasNavigation({ dimensions: dims, activeDocumentId: 'doc-flip' });
+ exposedNav = nav;
+ return <div ref={nav.viewportRef as any} />;
+ }
+
+ root = createRoot(env.container as unknown as HTMLElement);
+ act(() => {
+ root!.render(<Host />);
+ });
+
+ const viewportEl = exposedNav!.viewportRef.current as unknown as MiniElement;
+ const vRect = viewportEl.getBoundingClientRect(); // left=100, top=50, width=1200, height=900
+
+ // Set an arbitrary off-center, zoomed, rotated camera state
+ act(() => {
+ exposedNav!.setZoom(1.75);
+ exposedNav!.setPan({ x: 680, y: 510 });
+ exposedNav!.setRotation(28);
+ });
+
+ const sampleDocPt = { x: 260, y: 310 };
+ const screenBefore = canvasToScreen(
+ sampleDocPt.x,
+ sampleDocPt.y,
+ exposedNav!.panRef.current,
+ exposedNav!.zoomRef.current,
+ exposedNav!.rotationRef.current,
+ dims,
+ exposedNav!.flipXRef.current,
+ exposedNav!.flipYRef.current
+ );
+
+ // Toggle Horizontal View Flip
+ act(() => {
+ exposedNav!.toggleFlipHorizontal();
+ });
+ expect(exposedNav!.flipX).toBe(true);
+ expect(exposedNav!.flipY).toBe(false);
+ expect(exposedNav!.flipXRef.current).toBe(true);
+
+ const screenAfterFlipH = canvasToScreen(
+ sampleDocPt.x,
+ sampleDocPt.y,
+ exposedNav!.panRef.current,
+ exposedNav!.zoomRef.current,
+ exposedNav!.rotationRef.current,
+ dims,
+ exposedNav!.flipXRef.current,
+ exposedNav!.flipYRef.current
+ );
+
+ // Screen position MUST mirror horizontally across viewport center x = 1200 / 2 = 600, keeping same Y!
+ expect(screenAfterFlipH.x).toBeCloseTo(1200 - screenBefore.x, 5);
+ expect(screenAfterFlipH.y).toBeCloseTo(screenBefore.y, 5);
+
+ // Cursor-to-document mapping at that mirrored screen position MUST hit sampleDocPt!
+ const docUnderMirroredCursor = clientToDocument(
+ vRect.left + screenAfterFlipH.x,
+ vRect.top + screenAfterFlipH.y,
+ vRect,
+ exposedNav!.panRef.current,
+ exposedNav!.zoomRef.current,
+ exposedNav!.rotationRef.current,
+ dims,
+ exposedNav!.flipXRef.current,
+ exposedNav!.flipYRef.current
+ );
+ expect(docUnderMirroredCursor.x).toBeCloseTo(sampleDocPt.x, 5);
+ expect(docUnderMirroredCursor.y).toBeCloseTo(sampleDocPt.y, 5);
+
+ // Toggle Vertical View Flip as well (now H+V)
+ act(() => {
+ exposedNav!.toggleFlipVertical();
+ });
+ expect(exposedNav!.flipX).toBe(true);
+ expect(exposedNav!.flipY).toBe(true);
+
+ const screenAfterFlipHV = canvasToScreen(
+ sampleDocPt.x,
+ sampleDocPt.y,
+ exposedNav!.panRef.current,
+ exposedNav!.zoomRef.current,
+ exposedNav!.rotationRef.current,
+ dims,
+ exposedNav!.flipXRef.current,
+ exposedNav!.flipYRef.current
+ );
+ expect(screenAfterFlipHV.x).toBeCloseTo(1200 - screenBefore.x, 5);
+ expect(screenAfterFlipHV.y).toBeCloseTo(900 - screenBefore.y, 5);
+
+ // Reset View Flip restores exact pre-flip pan, rotation, and flip flags
+ act(() => {
+ exposedNav!.resetViewFlip();
+ });
+ expect(exposedNav!.flipX).toBe(false);
+ expect(exposedNav!.flipY).toBe(false);
+ expect(exposedNav!.pan.x).toBeCloseTo(680, 5);
+ expect(exposedNav!.pan.y).toBeCloseTo(510, 5);
+ expect(exposedNav!.rotation).toBeCloseTo(28, 5);
+ });
+ });
+
+ describe('Flipped View Brush Stroke Precision & Non-Destructive Layer Guarantee', () => {
+ it('places brush strokes directly under the cursor in Flip Horizontal / Vertical View without altering existing layer pixels', () => {
+ const dims = { width: 1000, height: 800, dpi: 300 };
+ const vRect = {
+ left: 80,
+ top: 40,
+ right: 1280,
+ bottom: 940,
+ width: 1200,
+ height: 900,
+ x: 80,
+ y: 40,
+ toJSON: () => ({}),
+ } as DOMRect;
+
+ // 1. Create a layer in SparseTileGrid with existing artwork at (200, 300)
+ const grid = new SparseTileGrid();
+ const layerId = 'layer-ink';
+ const landmarkPatch = new Uint8ClampedArray(4 * 4 * 4);
+ for (let i = 0; i < 16; i++) {
+ landmarkPatch[i * 4] = 20;
+ landmarkPatch[i * 4 + 1] = 40;
+ landmarkPatch[i * 4 + 2] = 220;
+ landmarkPatch[i * 4 + 3] = 255;
+ }
+ grid.writeImageData(layerId, { data: landmarkPatch, width: 4, height: 4 }, 200, 300, 'color-32bit');
+
+ const flipConfigs = [
+ { flipX: true, flipY: false, pan: { x: 560, y: 440 }, zoom: 2.0, rotation: 0 },
+ { flipX: true, flipY: false, pan: { x: 615, y: 470 }, zoom: 1.6, rotation: 35 },
+ { flipX: false, flipY: true, pan: { x: 590, y: 430 }, zoom: 2.25, rotation: -22 },
+ { flipX: true, flipY: true, pan: { x: 640, y: 495 }, zoom: 0.85, rotation: 110 },
+ ];
+
+ for (const cfg of flipConfigs) {
+ // Verify original layer landmark at (200, 300) is STILL at (200, 300) — never destructively mirrored to (800, 300)
+ const existingAt200 = grid.readImageData(layerId, 200, 300, 1, 1);
+ expect(existingAt200.data[2]).toBe(220);
+ expect(existingAt200.data[3]).toBe(255);
+ const mirroredSlot = grid.readImageData(layerId, dims.width - 200 - 4, 300, 1, 1);
+ expect(mirroredSlot.data[3]).toBe(0);
+
+ // User moves stylus/mouse to screen client coordinates (clientX=430, clientY=360) and paints a stroke
+ const cursorClientX = 430;
+ const cursorClientY = 360;
+ const expectedViewportX = cursorClientX - vRect.left; // 350
+ const expectedViewportY = cursorClientY - vRect.top; // 320
+
+ const docStrokePt = screenToCanvas(
+ cursorClientX,
+ cursorClientY,
+ vRect,
+ cfg.pan,
+ cfg.zoom,
+ cfg.rotation,
+ dims,
+ cfg.flipX,
+ cfg.flipY
+ );
+
+ // 1) Verify canvasToScreen maps the painted document point back to the exact cursor viewport coordinate
+ const projectedScreen = canvasToScreen(
+ docStrokePt.x,
+ docStrokePt.y,
+ cfg.pan,
+ cfg.zoom,
+ cfg.rotation,
+ dims,
+ cfg.flipX,
+ cfg.flipY
+ );
+ expect(projectedScreen.x).toBeCloseTo(expectedViewportX, 6);
+ expect(projectedScreen.y).toBeCloseTo(expectedViewportY, 6);
+
+ // 2) Verify draft/predicted Canvas2D transform matrix (`getCanvasToViewportMatrix`) renders the live stroke at the exact cursor pixel (including HiDPI DPR=2)
+ const dpr = 2;
+ const mat = getCanvasToViewportMatrix(
+ cfg.pan,
+ cfg.zoom,
+ cfg.rotation,
+ dims,
+ dpr,
+ dpr,
+ cfg.flipX,
+ cfg.flipY
+ );
+ const draftDeviceX = mat.a * docStrokePt.x + mat.c * docStrokePt.y + mat.e;
+ const draftDeviceY = mat.b * docStrokePt.x + mat.d * docStrokePt.y + mat.f;
+ expect(draftDeviceX).toBeCloseTo(expectedViewportX * dpr, 5);
+ expect(draftDeviceY).toBeCloseTo(expectedViewportY * dpr, 5);
+
+ // 3) Verify visible canvas bounds contain the document point when cursor is inside the viewport
+ const visBounds = getVisibleCanvasBounds(
+ vRect,
+ cfg.pan,
+ cfg.zoom,
+ cfg.rotation,
+ dims,
+ 0,
+ cfg.flipX,
+ cfg.flipY
+ );
+ if (
+ docStrokePt.x >= 0 &&
+ docStrokePt.x <= dims.width &&
+ docStrokePt.y >= 0 &&
+ docStrokePt.y <= dims.height
+ ) {
+ expect(docStrokePt.x).toBeGreaterThanOrEqual(visBounds.minX);
+ expect(docStrokePt.x).toBeLessThanOrEqual(visBounds.maxX);
+ expect(docStrokePt.y).toBeGreaterThanOrEqual(visBounds.minY);
+ expect(docStrokePt.y).toBeLessThanOrEqual(visBounds.maxY);
+ }
+ }
+ });
+
+ it('transforms coordinates accurately in StrokePipeline when flipX / flipY are enabled', () => {
+ const drawnSegments: Array<{ x0: number; y0: number; x3: number; y3: number }> = [];
+ const pipeline = new StrokePipeline((_ctx, seg, _color, _width, isProvisional) => {
+ if (!isProvisional) {
+ drawnSegments.push({
+ x0: seg.p0.x,
+ y0: seg.p0.y,
+ x3: seg.p3.x,
+ y3: seg.p3.y,
+ });
+ }
+ });
+ pipeline.setStabilizerLevel(0);
+ pipeline.bindContexts({} as CanvasRenderingContext2D, {
+ resetTransform: () => {},
+ clearRect: () => {},
+ } as unknown as CanvasRenderingContext2D);
+
+ const view = {
+ panX: 0,
+ panY: 0,
+ zoom: 1,
+ rotation: 0,
+ canvasWidth: 1000,
+ canvasHeight: 800,
+ flipX: true,
+ flipY: false,
+ };
+
+ // Stroke at screen x = 300 (which is 200px left of center 500) -> with flipX=true, document x must be 700 (200px right of center 500)
+ const makePtr = (clientX: number, clientY: number, t: number, buttons = 1) =>
+ ({
+ pointerId: 1,
+ pointerType: 'mouse',
+ clientX,
+ clientY,
+ pressure: 0.5,
+ buttons,
+ timeStamp: t,
+ }) as unknown as PointerEvent;
+
+ pipeline.onPointerDown(makePtr(300, 400, 10), view);
+ pipeline.onPointerMove(makePtr(280, 400, 26), view);
+ pipeline.onPointerMove(makePtr(260, 400, 42), view);
+ pipeline.onPointerUp(makePtr(250, 400, 58, 0), view);
+
+ expect(drawnSegments.length).toBeGreaterThan(0);
+ expect(drawnSegments[0].x0).toBeCloseTo(700, 0);
+ expect(drawnSegments[0].y0).toBeCloseTo(400, 0);
+ });
+ });
+});
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index 136ed93..fcc0e93 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -11,6 +11,7 @@ import {
RadialMixingOptions,
} from './stampEngine';
import { LayerPixelSampler, PaintReservoir } from './colorMixingEngine';
+import { GpuDab } from './webglBrushEngine';
import {
evaluateFastSpline,
applyCspPostCorrection,
@@ -134,7 +135,8 @@ export function drawSmoothCubicBezierSegment(
remainderDist: number = 0,
thickness: number = 1.0,
angleRad: number = 0,
- mixingOptions?: RadialMixingOptions
+ mixingOptions?: RadialMixingOptions,
+ batchGpuDabs?: GpuDab[]
): number {
return drawRadialCubicBezierSegment(
ctx,
@@ -151,7 +153,8 @@ export function drawSmoothCubicBezierSegment(
remainderDist,
thickness,
angleRad,
- mixingOptions
+ mixingOptions,
+ batchGpuDabs
);
}
@@ -197,9 +200,10 @@ export function drawDot(
flow: number = 1.0,
mixingOptions?: RadialMixingOptions,
thickness: number = 1.0,
- angleRad: number = 0
+ angleRad: number = 0,
+ batchGpuDabs?: GpuDab[]
) {
- drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions, thickness, angleRad);
+ drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions, thickness, angleRad, batchGpuDabs);
}
let _sharedThumbCanvas: HTMLCanvasElement | null = null;
@@ -298,15 +302,18 @@ export function formatTime(timestamp: number | Date = Date.now()): string {
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
-export function screenToCanvas(
+export function screenToCanvasInto(
clientX: number,
clientY: number,
viewportRect: DOMRect,
pan: { x: number; y: number },
zoom: number,
rotation: number,
- dimensions: CanvasDimensions
-): { x: number; y: number } {
+ dimensions: CanvasDimensions,
+ out: { x: number; y: number },
+ flipX: boolean = false,
+ flipY: boolean = false
+): void {
const vx = clientX - viewportRect.left;
const vy = clientY - viewportRect.top;
@@ -320,22 +327,46 @@ export function screenToCanvas(
const unrotX = rx * cos + ry * sin;
const unrotY = -rx * sin + ry * cos;
- const x = dimensions.width / 2 + unrotX / zoom;
- const y = dimensions.height / 2 + unrotY / zoom;
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
- return { x, y };
+ out.x = dimensions.width / 2 + (fx * unrotX) / zoom;
+ out.y = dimensions.height / 2 + (fy * unrotY) / zoom;
}
+export function screenToCanvas(
+ clientX: number,
+ clientY: number,
+ viewportRect: DOMRect,
+ pan: { x: number; y: number },
+ zoom: number,
+ rotation: number,
+ dimensions: CanvasDimensions,
+ flipX: boolean = false,
+ flipY: boolean = false
+): { x: number; y: number } {
+ const out = { x: 0, y: 0 };
+ screenToCanvasInto(clientX, clientY, viewportRect, pan, zoom, rotation, dimensions, out, flipX, flipY);
+ return out;
+}
+
+export const clientToDocument = screenToCanvas;
+
export function canvasToScreen(
canvasX: number,
canvasY: number,
pan: { x: number; y: number },
zoom: number,
rotation: number,
- dimensions: CanvasDimensions
+ dimensions: CanvasDimensions,
+ flipX: boolean = false,
+ flipY: boolean = false
): { x: number; y: number } {
- const dx = canvasX - dimensions.width / 2;
- const dy = canvasY - dimensions.height / 2;
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
+
+ const dx = (canvasX - dimensions.width / 2) * fx;
+ const dy = (canvasY - dimensions.height / 2) * fy;
const rad = (rotation * Math.PI) / 180;
const cos = Math.cos(rad);
@@ -375,7 +406,9 @@ export function getCanvasToViewportMatrix(
rotation: number,
dimensions: CanvasDimensions,
scaleX: number = 1,
- scaleY: number = scaleX
+ scaleY: number = scaleX,
+ flipX: boolean = false,
+ flipY: boolean = false
): CanvasTransformMatrix {
const rad = (rotation * Math.PI) / 180;
const cos = Math.cos(rad);
@@ -383,13 +416,15 @@ export function getCanvasToViewportMatrix(
const cx = dimensions.width / 2;
const cy = dimensions.height / 2;
+ const sx = (flipX ? -1 : 1) * zoom;
+ const sy = (flipY ? -1 : 1) * zoom;
- const a = scaleX * zoom * cos;
- const b = scaleY * zoom * sin;
- const c = -scaleX * zoom * sin;
- const d = scaleY * zoom * cos;
- const e = scaleX * (pan.x - zoom * (cx * cos - cy * sin));
- const f = scaleY * (pan.y - zoom * (cx * sin + cy * cos));
+ const a = scaleX * sx * cos;
+ const b = scaleY * sx * sin;
+ const c = -scaleX * sy * sin;
+ const d = scaleY * sy * cos;
+ const e = scaleX * (pan.x - sx * cx * cos + sy * cy * sin);
+ const f = scaleY * (pan.y - sx * cx * sin - sy * cy * cos);
return { a, b, c, d, e, f };
}
@@ -400,12 +435,14 @@ export function getVisibleCanvasBounds(
zoom: number,
rotation: number,
dimensions: CanvasDimensions,
- margin: number = 64
+ margin: number = 64,
+ flipX: boolean = false,
+ flipY: boolean = false
): { minX: number; minY: number; maxX: number; maxY: number } {
- const c1 = screenToCanvas(viewportRect.left, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions);
- const c2 = screenToCanvas(viewportRect.right, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions);
- const c3 = screenToCanvas(viewportRect.right, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions);
- const c4 = screenToCanvas(viewportRect.left, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions);
+ const c1 = screenToCanvas(viewportRect.left, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
+ const c2 = screenToCanvas(viewportRect.right, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
+ const c3 = screenToCanvas(viewportRect.right, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
+ const c4 = screenToCanvas(viewportRect.left, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
const rawMinX = Math.min(c1.x, c2.x, c3.x, c4.x) - margin;
const rawMinY = Math.min(c1.y, c2.y, c3.y, c4.y) - margin;
@@ -569,9 +606,9 @@ export function renderCompleteStroke(
dualBrush: brushSettings.dualBrush,
dualTipImage: brushSettings.dualTipImage,
dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
- useGpu: Boolean(brushSettings.useGpu),
+ useGpu: brushSettings.useGpu !== false,
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,
isEraser: isEraser && !isBgEraser,
isBgEraser,
@@ -598,7 +635,7 @@ export function renderCompleteStroke(
isTransparentInk,
dynamics: brushSettings.dynamics,
secondaryColor: brushSettings.secondaryColor,
- useGpu: Boolean(brushSettings.useGpu),
+ useGpu: brushSettings.useGpu !== false,
dualBrush: brushSettings.dualBrush,
dualTipImage: brushSettings.dualTipImage,
dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index f416be8..c7c3c7c 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -305,6 +305,11 @@ export class LayerPixelSampler {
this.lazyTiles.set(key, buf);
return buf;
}
+ if (this.tileGrid.isLayerIngested(this.layerId)) {
+ buf = new Uint8ClampedArray(TILE_SIZE * TILE_SIZE * 4);
+ this.lazyTiles.set(key, buf);
+ return buf;
+ }
}
buf = new Uint8ClampedArray(TILE_SIZE * TILE_SIZE * 4);
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index f2ab0ae..d29bd51 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -23,6 +23,8 @@ export interface ViewportTransform {
pan: { x: number; y: number };
zoom: number;
rotation: number; // in degrees
+ flipX?: boolean;
+ flipY?: boolean;
}
export const BLEND_MODE_MAP: Record<BlendMode, number> = {
@@ -201,6 +203,7 @@ uniform vec2 u_viewportSize; // viewport width, height
uniform vec2 u_pan;
uniform float u_zoom;
uniform float u_rotationRad;
+uniform vec2 u_flip;
uniform float u_dpr;
out vec2 v_texCoord;
@@ -213,8 +216,8 @@ void main() {
vec2 docPos = u_tileOrigin + a_quadPos * u_tileSize;
v_docCoord = docPos;
- // Center document around (0, 0)
- vec2 centered = docPos - u_docDimensions * 0.5;
+ // Center document around (0, 0) and apply non-destructive view flip
+ vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
// Rotate
float cosR = cos(u_rotationRad);
@@ -410,15 +413,19 @@ void main() {
finalColor.rgb = vec3(gLum);
} else if (u_expressionMode == 2) {
float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ float monoHi = clamp(0.18 * sqrt(max(0.01, u_zoom)) + 0.04, 0.06, 0.25);
+ float monoAlpha = u_zoom >= 0.99
+ ? step(0.5, finalColor.a)
+ : smoothstep(0.02, monoHi, finalColor.a);
if (mLum < u_monoThreshold) {
if (u_monoExpressBlack == 1) {
- finalColor = vec4(0.0, 0.0, 0.0, step(0.1, finalColor.a));
+ finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
} else {
discard;
}
} else {
if (u_monoExpressWhite == 1) {
- finalColor = vec4(1.0, 1.0, 1.0, step(0.1, finalColor.a));
+ finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
} else {
discard;
}
@@ -459,6 +466,320 @@ void main() {
}
`;
+// Instanced Vertex Shader: Batched tile rendering via TEXTURE_2D_ARRAY + drawArraysInstanced
+export const COMPOSITOR_INSTANCED_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+in vec3 a_instanceData; // xy = tileOrigin in document space, z = TEXTURE_2D_ARRAY slice index
+uniform vec2 u_tileSize; // tile size in document space (TILE_SIZE << lod)
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+flat out float v_sliceIndex;
+
+void main() {
+ v_texCoord = a_quadPos;
+ v_sliceIndex = a_instanceData.z;
+
+ vec2 docPos = a_instanceData.xy + a_quadPos * u_tileSize;
+ v_docCoord = docPos;
+
+ vec2 centered = (docPos - u_docDimensions * 0.5) * u_flip;
+
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 rotated = vec2(
+ centered.x * cosR - centered.y * sinR,
+ centered.x * sinR + centered.y * cosR
+ );
+
+ vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
+
+ vec2 clipPos = vec2(
+ (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
+ 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
+ );
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+// Instanced Fragment Shader: Samples TEXTURE_2D_ARRAY slice for batched single-draw-call layer rendering
+export const COMPOSITOR_INSTANCED_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+precision highp sampler2DArray;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+flat in float v_sliceIndex;
+
+uniform sampler2DArray u_tileArrayTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform vec2 u_viewportSize;
+uniform float u_layerOpacity;
+uniform int u_blendMode;
+
+// Screentone Uniforms
+uniform int u_toneEnabled;
+uniform float u_toneFrequency;
+uniform float u_toneAngleRad;
+uniform float u_toneDpi;
+uniform int u_toneDotShape;
+uniform float u_toneDensity;
+uniform int u_toneDensityType;
+uniform float u_zoom;
+
+// Layer Tint Uniforms
+uniform int u_layerColorEnabled;
+uniform vec3 u_layerColor;
+uniform vec3 u_layerSubColor;
+
+// Layer Mask Uniforms
+uniform vec2 u_docDimensions;
+uniform sampler2D u_maskTexture;
+uniform int u_maskEnabled;
+
+// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
+uniform int u_expressionMode;
+uniform float u_monoThreshold;
+uniform int u_monoExpressBlack;
+uniform int u_monoExpressWhite;
+
+out vec4 fragColor;
+
+float fractVal(float x) {
+ return x - floor(x);
+}
+
+float blendChannel(float b, float s, int mode) {
+ if (mode == 1) return b * s;
+ if (mode == 2) return b + s - b * s;
+ if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s));
+ if (mode == 4) return min(b, s);
+ if (mode == 5) return max(b, s);
+ if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)));
+ 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)));
+ if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s));
+ if (mode == 9) {
+ 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);
+ if (mode == 11) return b + s - 2.0 * b * s;
+ if (mode == 13) return max(0.0, b + s - 1.0);
+ if (mode == 14) return min(1.0, b + s);
+ if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s));
+ if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0);
+ 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);
+ }
+
+ float density;
+ if (u_toneDensityType == 0) {
+ density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
+ } else {
+ float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
+ density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
+ }
+
+ if (density <= 0.001) return vec4(0.0);
+ if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
+
+ float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
+ float cosA = cos(u_toneAngleRad);
+ float sinA = sin(u_toneAngleRad);
+
+ float xr = docCoord.x * cosA - docCoord.y * sinA;
+ float yr = docCoord.x * sinA + docCoord.y * cosA;
+
+ float u = fractVal(xr / cellSize) - 0.5;
+ float v = fractVal(yr / cellSize) - 0.5;
+
+ float spot;
+ if (u_toneDotShape == 2) {
+ spot = 1.0 - 2.0 * abs(u);
+ } else if (u_toneDotShape == 3) {
+ spot = 1.0 - (abs(u) + abs(v));
+ } else {
+ float absU = abs(u);
+ float absV = abs(v);
+ if (absU + absV <= 0.5) {
+ spot = 1.0 - 2.0 * (u * u + v * v);
+ } else {
+ float uc = absU - 0.5;
+ float vc = absV - 0.5;
+ spot = 2.0 * (uc * uc + vc * vc);
+ }
+ }
+
+ float diff = spot - (1.0 - density);
+ float halfSpan = min(0.25, 0.75 / cellSize);
+ float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
+ vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
+
+ float moireBlend = smoothstep(0.35, 0.95, u_zoom);
+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);
+ return mix(contColor, halftoneColor, moireBlend);
+}
+
+vec4 applyLayerTint(vec4 color) {
+ if (u_layerColorEnabled == 0) return color;
+ float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
+ return vec4(tinted, color.a);
+}
+
+vec4 sampleTileStraight(vec2 uv, int slice) {
+ if (u_zoom >= 2.0) {
+ ivec2 coord = clamp(ivec2(floor(uv * 256.0)), ivec2(0), ivec2(255));
+ return texelFetch(u_tileArrayTexture, ivec3(coord, slice), 0);
+ }
+ vec2 texCoord = uv * 256.0 - 0.5;
+ ivec2 base = ivec2(floor(texCoord));
+ vec2 f = texCoord - vec2(base);
+ ivec2 c0 = clamp(base, ivec2(0), ivec2(255));
+ ivec2 c1 = clamp(base + ivec2(1), ivec2(0), ivec2(255));
+
+ vec4 t00 = texelFetch(u_tileArrayTexture, ivec3(c0.x, c0.y, slice), 0);
+ vec4 t10 = texelFetch(u_tileArrayTexture, ivec3(c1.x, c0.y, slice), 0);
+ vec4 t01 = texelFetch(u_tileArrayTexture, ivec3(c0.x, c1.y, slice), 0);
+ vec4 t11 = texelFetch(u_tileArrayTexture, ivec3(c1.x, c1.y, slice), 0);
+
+ vec4 pm00 = vec4(t00.rgb * t00.a, t00.a);
+ vec4 pm10 = vec4(t10.rgb * t10.a, t10.a);
+ vec4 pm01 = vec4(t01.rgb * t01.a, t01.a);
+ vec4 pm11 = vec4(t11.rgb * t11.a, t11.a);
+
+ vec4 pm = mix(mix(pm00, pm10, f.x), mix(pm01, pm11, f.x), f.y);
+ if (pm.a < 0.002) {
+ return vec4(0.0);
+ }
+ return vec4(clamp(pm.rgb / pm.a, 0.0, 1.0), pm.a);
+}
+
+void main() {
+ int slice = int(v_sliceIndex + 0.5);
+ vec4 texColor = sampleTileStraight(v_texCoord, slice);
+
+ if (texColor.a < 0.002) {
+ discard;
+ }
+
+ vec4 finalColor = texColor;
+
+ if (u_expressionMode == 1) {
+ float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ finalColor.rgb = vec3(gLum);
+ } else if (u_expressionMode == 2) {
+ float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;
+ if (mLum < u_monoThreshold) {
+ if (u_monoExpressBlack == 1) {
+ finalColor = vec4(0.0, 0.0, 0.0, monoAlpha);
+ } else {
+ discard;
+ }
+ } else {
+ if (u_monoExpressWhite == 1) {
+ finalColor = vec4(1.0, 1.0, 1.0, monoAlpha);
+ } else {
+ discard;
+ }
+ }
+ }
+
+ if (u_toneEnabled == 1) {
+ finalColor = evaluateScreentone(finalColor, v_docCoord);
+ }
+
+ if (u_layerColorEnabled == 1) {
+ finalColor = applyLayerTint(finalColor);
+ }
+
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ finalColor.a *= maskLum;
+ }
+
+ finalColor.a *= u_layerOpacity;
+
+ if (finalColor.a < 0.002) {
+ 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);
+}
+`;
+
+// Viewport-Space Draft Vertex Shader: Maps a viewport-sized Canvas2D draft overlay 1:1 to screen
+// while reconstructing exact document coordinates for screentone & layer mask evaluation in-stack.
+export const VIEWPORT_DRAFT_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1] (0,0 = top-left of viewport)
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform vec2 u_flip;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+
+void main() {
+ v_texCoord = a_quadPos;
+
+ vec2 clipPos = vec2(a_quadPos.x * 2.0 - 1.0, 1.0 - a_quadPos.y * 2.0);
+ vec2 screenPos = a_quadPos * u_viewportSize;
+ vec2 cssScreen = screenPos / max(0.0001, u_dpr);
+ vec2 unscaled = (cssScreen - u_pan) / max(0.0001, u_zoom);
+
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 unrotated = vec2(
+ unscaled.x * cosR + unscaled.y * sinR,
+ -unscaled.x * sinR + unscaled.y * cosR
+ );
+
+ v_docCoord = unrotated * u_flip + u_docDimensions * 0.5;
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
// Fragment Shader: Non-Destructive Adjustment Layers with Real-Time LUT Transform
export const ADJUSTMENT_FRAGMENT_SHADER = `#version 300 es
precision highp float;
@@ -982,28 +1303,431 @@ export interface CompositorOptions {
devicePixelRatio?: number;
onionSkinFrames?: OnionSkinCompositorFrame[];
softProof?: SoftProofSettings;
+ // Active layer identifier for Baked Layer Stack Cache partitioning (below / active / above)
+ activeLayerId?: string | null;
// WYSIWYG In-Stack Live Stroke Compositing
activeDraftCanvas?: HTMLCanvasElement | null;
activeDraftLayerId?: string | null;
activeDraftDirtyRect?: { x: number; y: number; width: number; height: number } | null;
activeDraftVersion?: number;
+ activeDraftSpace?: 'document' | 'viewport';
+ activeDraftOpacity?: number;
+ activeDraftMonochrome?: boolean;
}
-/**
- * Calculates the document-space bounding box visible in the current camera viewport.
- * Performs frustum culling.
- */
-export function calculateVisibleDocumentBounds(
- viewportW: number,
- viewportH: number,
- transform: ViewportTransform,
- docW: number,
- docH: number
-): { minX: number; minY: number; maxX: number; maxY: number } {
- const { pan, zoom, rotation } = transform;
- const rad = (-rotation * Math.PI) / 180;
- const cosR = Math.cos(rad);
+// ============================================================================
+// Baked Layer Stack Cache Partitioning & Invalidation Engine
+// ============================================================================
+
+export interface CompositingUnit {
+ /** Base node and its clipped siblings at this compositing level */
+ group: TreeNodeRenderGroup;
+ /** Accumulated opacity from enclosing pass-through folders */
+ inheritedOpacity: number;
+ /** All layer IDs contained in this unit (base, clipped siblings, and folder descendants) */
+ containedLayerIds: Set<string>;
+}
+
+export type AboveSliceStrategy = 'empty' | 'baked-normal' | 'baked-single-blend' | 'mixed';
+
+export interface LayerStackPartition {
+ /** Units strictly below the active unit (always safe to bake into belowActiveCacheFbo) */
+ belowUnits: CompositingUnit[];
+ /** The active unit containing activeLayerId, or null if none/hidden */
+ activeUnit: CompositingUnit | null;
+ /** Units above active that must render dynamically (non-associative blend modes / adjustments) */
+ aboveDynamicUnits: CompositingUnit[];
+ /** Units above activeDynamicUnits that can be baked into aboveActiveCacheFbo */
+ aboveCachedUnits: CompositingUnit[];
+ /** How aboveActiveCacheFbo should be composited over (below + active + aboveDynamic) */
+ aboveStrategy: AboveSliceStrategy;
+ /** Blend mode for aboveActiveCacheFbo when aboveStrategy === 'baked-single-blend' */
+ aboveCacheBlendMode: BlendMode;
+}
+
+export interface LayerStackCacheInput {
+ layers: LayerItem[];
+ activeLayerId?: string | null;
+ viewportW: number;
+ viewportH: number;
+ dpr: number;
+ dimensions: CanvasDimensions;
+ transform: ViewportTransform;
+ showCheckerboard?: boolean;
+ onionSkinFrames?: OnionSkinCompositorFrame[];
+ getLayerContentVersion: (layerId: string) => number;
+ getMaskInvalidationEpoch?: (layerId: string) => number;
+ gridEpoch?: number;
+}
+
+export interface LayerStackCacheEvaluation {
+ partition: LayerStackPartition;
+ belowSignature: string;
+ aboveSignature: string;
+ belowDirty: boolean;
+ aboveDirty: boolean;
+}
+
+function collectNodeLayerIds(node: LayerTreeNode, out: Set<string>): void {
+ out.add(node.layer.id);
+ for (const child of node.children) {
+ collectNodeLayerIds(child, out);
+ }
+}
+
+/**
+ * Flattens pass-through folders into a bottom-to-top sequence of atomic compositing units
+ * while keeping isolated folders and clipping-mask groups atomic.
+ */
+export function flattenLayerTreeToUnits(
+ nodes: LayerTreeNode[],
+ inheritedOpacity: number = 1.0
+): CompositingUnit[] {
+ const units: CompositingUnit[] = [];
+ const siblingsBottomToTop = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(siblingsBottomToTop);
+
+ for (const group of groups) {
+ const baseLayer = group.baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
+ continue;
+ }
+
+ if (baseLayer.type === 'folder' && baseLayer.blendMode === 'pass-through') {
+ const nested = flattenLayerTreeToUnits(
+ group.baseNode.children,
+ inheritedOpacity * baseLayer.opacity
+ );
+ for (const u of nested) {
+ units.push(u);
+ }
+ continue;
+ }
+
+ const containedLayerIds = new Set<string>();
+ collectNodeLayerIds(group.baseNode, containedLayerIds);
+ for (const cn of group.clippedNodes) {
+ collectNodeLayerIds(cn, containedLayerIds);
+ }
+
+ units.push({
+ group,
+ inheritedOpacity,
+ containedLayerIds,
+ });
+ }
+
+ return units;
+}
+
+/**
+ * Returns true if a compositing unit is strictly Porter-Duff source-over associative
+ * with respect to the backdrop below it (safe to pre-bake onto transparent FBO and composite with 'normal').
+ */
+export function isUnitNormalAssociative(unit: CompositingUnit): boolean {
+ const baseLayer = unit.group.baseNode.layer;
+ if (baseLayer.type === 'adjustment') {
+ return false;
+ }
+ if (baseLayer.type === 'folder') {
+ // Pass-through folders were flattened; an isolated folder isolates its children's blend modes,
+ // so it is normal-associative iff the folder's own blend mode is normal.
+ return baseLayer.blendMode === 'normal';
+ }
+ if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
+ return false;
+ }
+ for (const cn of unit.group.clippedNodes) {
+ const cl = cn.layer;
+ if (!cl.visible || cl.opacity <= 0.001 || cl.type === 'folder') continue;
+ if (cl.blendMode !== 'normal' && cl.blendMode !== 'pass-through') {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * Returns the blend mode if a single non-associative unit can be baked onto transparent
+ * with 'normal' and composited over (below + active) using a single ping-pong blend pass.
+ */
+export function canSingleUnitBakeWithBlendMode(unit: CompositingUnit): BlendMode | null {
+ const baseLayer = unit.group.baseNode.layer;
+ if (baseLayer.type === 'adjustment') {
+ return null;
+ }
+ if (baseLayer.type === 'folder') {
+ if (baseLayer.blendMode !== 'normal' && baseLayer.blendMode !== 'pass-through') {
+ return baseLayer.blendMode;
+ }
+ return null;
+ }
+ const visibleClipped = unit.group.clippedNodes.filter(
+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && cn.layer.type !== 'folder'
+ );
+ if (
+ visibleClipped.length === 0 &&
+ baseLayer.blendMode !== 'normal' &&
+ baseLayer.blendMode !== 'pass-through'
+ ) {
+ return baseLayer.blendMode;
+ }
+ return null;
+}
+
+/**
+ * Partitions the visible layer stack into `below`, `active`, and `above` slices relative to `activeLayerId`.
+ */
+export function partitionLayerStack(
+ layers: LayerItem[],
+ activeLayerId?: string | null
+): LayerStackPartition {
+ const tree = buildLayerTree(layers);
+ const units = flattenLayerTreeToUnits(tree, 1.0);
+
+ let activeIdx = -1;
+ if (activeLayerId) {
+ for (let i = 0; i < units.length; i++) {
+ if (units[i].containedLayerIds.has(activeLayerId)) {
+ activeIdx = i;
+ break;
+ }
+ }
+ }
+
+ if (activeIdx === -1) {
+ return {
+ belowUnits: units,
+ activeUnit: null,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: [],
+ aboveStrategy: 'empty',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ const belowUnits = units.slice(0, activeIdx);
+ const activeUnit = units[activeIdx];
+ const aboveAll = units.slice(activeIdx + 1);
+
+ if (aboveAll.length === 0) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: [],
+ aboveStrategy: 'empty',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ let lastNonAssocIdx = -1;
+ for (let i = 0; i < aboveAll.length; i++) {
+ if (!isUnitNormalAssociative(aboveAll[i])) {
+ lastNonAssocIdx = i;
+ }
+ }
+
+ if (lastNonAssocIdx === -1) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: aboveAll,
+ aboveStrategy: 'baked-normal',
+ aboveCacheBlendMode: 'normal',
+ };
+ }
+
+ if (aboveAll.length === 1) {
+ const singleBlend = canSingleUnitBakeWithBlendMode(aboveAll[0]);
+ if (singleBlend) {
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: [],
+ aboveCachedUnits: aboveAll,
+ aboveStrategy: 'baked-single-blend',
+ aboveCacheBlendMode: singleBlend,
+ };
+ }
+ }
+
+ return {
+ belowUnits,
+ activeUnit,
+ aboveDynamicUnits: aboveAll.slice(0, lastNonAssocIdx + 1),
+ aboveCachedUnits: aboveAll.slice(lastNonAssocIdx + 1),
+ aboveStrategy: 'mixed',
+ aboveCacheBlendMode: 'normal',
+ };
+}
+
+function serializeLayerNodeSignature(
+ node: LayerTreeNode,
+ inheritedOpacity: number,
+ getLayerContentVersion: (layerId: string) => number,
+ getMaskInvalidationEpoch?: (layerId: string) => number
+): string {
+ const l = node.layer;
+ const contentVer = getLayerContentVersion(l.id);
+ const maskEpoch = getMaskInvalidationEpoch ? getMaskInvalidationEpoch(l.id) : 0;
+ const stylesSig = hasActiveLayerStyles(l.styles) ? JSON.stringify(l.styles) : '';
+ const adjSig = l.type === 'adjustment' && l.adjustmentData ? JSON.stringify(l.adjustmentData) : '';
+ const toneSig = l.toneEnabled
+ ? `1:${l.toneFrequency ?? 60}:${l.toneAngle ?? 45}:${l.toneDotShape ?? ''}:${l.toneDensity ?? 40}:${l.toneDensityType ?? ''}`
+ : '0';
+ const tintSig = l.layerColorEnabled
+ ? `1:${l.layerColor ?? ''}:${l.layerSubColor ?? ''}`
+ : '0';
+ const maskSig = l.maskCanvas && l.maskEnabled !== false
+ ? `1:${l.maskVersion ?? 0}:${maskEpoch}:${l.maskCanvas.width}x${l.maskCanvas.height}`
+ : '0';
+ const exprSig = `${l.expressionColor ?? 'color'}:${l.monoThreshold ?? 128}:${l.monoExpressBlack !== false ? 1 : 0}:${l.monoExpressWhite !== false ? 1 : 0}`;
+
+ let sig = `${l.id}|${l.type}|${l.visible ? 1 : 0}|${l.opacity}|${inheritedOpacity}|${l.blendMode}|${l.clipped ? 1 : 0}|v:${contentVer}|m:${maskSig}|t:${toneSig}|c:${tintSig}|e:${exprSig}|s:${stylesSig}|a:${adjSig}`;
+
+ if (node.children.length > 0) {
+ const childSigs: string[] = [];
+ for (const child of node.children) {
+ if (!child.layer.visible || child.layer.opacity <= 0.001) continue;
+ childSigs.push(
+ serializeLayerNodeSignature(child, 1.0, getLayerContentVersion, getMaskInvalidationEpoch)
+ );
+ }
+ sig += `[${childSigs.join(',')}]`;
+ }
+
+ return sig;
+}
+
+function serializeUnitSignature(
+ unit: CompositingUnit,
+ getLayerContentVersion: (layerId: string) => number,
+ getMaskInvalidationEpoch?: (layerId: string) => number
+): string {
+ let sig = serializeLayerNodeSignature(
+ unit.group.baseNode,
+ unit.inheritedOpacity,
+ getLayerContentVersion,
+ getMaskInvalidationEpoch
+ );
+ if (unit.group.clippedNodes.length > 0) {
+ const clippedSigs: string[] = [];
+ for (const cn of unit.group.clippedNodes) {
+ if (!cn.layer.visible || cn.layer.opacity <= 0.001 || cn.layer.type === 'folder') continue;
+ clippedSigs.push(
+ serializeLayerNodeSignature(cn, unit.inheritedOpacity, getLayerContentVersion, getMaskInvalidationEpoch)
+ );
+ }
+ if (clippedSigs.length > 0) {
+ sig += `{clip:${clippedSigs.join(';')}}`;
+ }
+ }
+ return sig;
+}
+
+/**
+ * Pure invalidation tracker for the Baked Layer Stack Cache (`belowActiveCacheFbo` & `aboveActiveCacheFbo`).
+ * Determines independently whether the lower or upper cached FBO needs rebuilding.
+ */
+export class LayerStackCacheTracker {
+ private lastBelowSignature: string | null = null;
+ private lastAboveSignature: string | null = null;
+
+ public evaluate(input: LayerStackCacheInput): LayerStackCacheEvaluation {
+ const partition = partitionLayerStack(input.layers, input.activeLayerId);
+
+ const { transform, dimensions } = input;
+ const viewportSig =
+ `${input.viewportW}x${input.viewportH}@${input.dpr}|` +
+ `${dimensions.width}x${dimensions.height}@${dimensions.dpi ?? 600}|` +
+ `${transform.pan.x},${transform.pan.y},${transform.zoom},${transform.rotation},` +
+ `${transform.flipX ? 1 : 0},${transform.flipY ? 1 : 0}|ep:${input.gridEpoch ?? 0}`;
+
+ // Onion skin frames are baked into the below cache right after the artboard background
+ let onionSig = '';
+ if (input.onionSkinFrames && input.onionSkinFrames.length > 0) {
+ const layerMap = new Map<string, LayerItem>();
+ for (const l of input.layers) layerMap.set(l.id, l);
+ const parts: string[] = [];
+ for (const frame of input.onionSkinFrames) {
+ const target = layerMap.get(frame.layerId);
+ if (target && target.visible) {
+ parts.push(
+ `${frame.layerId}:${frame.tint}:${frame.opacity}:v${input.getLayerContentVersion(frame.layerId)}`
+ );
+ }
+ }
+ onionSig = parts.join(',');
+ }
+
+ const belowUnitSigs = partition.belowUnits.map((u) =>
+ serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
+ );
+ const belowSignature = `${viewportSig}|cb:${input.showCheckerboard ? 1 : 0}|os:${onionSig}|below:[${belowUnitSigs.join('||')}]`;
+
+ let aboveSignature = '';
+ if (partition.aboveCachedUnits.length > 0) {
+ const aboveUnitSigs = partition.aboveCachedUnits.map((u) =>
+ serializeUnitSignature(u, input.getLayerContentVersion, input.getMaskInvalidationEpoch)
+ );
+ aboveSignature = `${viewportSig}|strat:${partition.aboveStrategy}:${partition.aboveCacheBlendMode}|above:[${aboveUnitSigs.join('||')}]`;
+ }
+
+ const belowDirty = belowSignature !== this.lastBelowSignature;
+ const aboveDirty =
+ partition.aboveCachedUnits.length > 0 && aboveSignature !== this.lastAboveSignature;
+
+ return {
+ partition,
+ belowSignature,
+ aboveSignature,
+ belowDirty,
+ aboveDirty,
+ };
+ }
+
+ public commit(belowSignature: string, aboveSignature: string): void {
+ this.lastBelowSignature = belowSignature;
+ this.lastAboveSignature = aboveSignature;
+ }
+
+ public invalidateAll(): void {
+ this.lastBelowSignature = null;
+ this.lastAboveSignature = null;
+ }
+
+ public invalidateBelow(): void {
+ this.lastBelowSignature = null;
+ }
+
+ public invalidateAbove(): void {
+ this.lastAboveSignature = null;
+ }
+
+ public getLastSignatures(): { below: string | null; above: string | null } {
+ return { below: this.lastBelowSignature, above: this.lastAboveSignature };
+ }
+}
+
+/**
+ * Calculates the document-space bounding box visible in the current camera viewport.
+ * Performs frustum culling.
+ */
+export function calculateVisibleDocumentBounds(
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ docW: number,
+ docH: number
+): { minX: number; minY: number; maxX: number; maxY: number } {
+ const { pan, zoom, rotation, flipX = false, flipY = false } = transform;
+ const rad = (-rotation * Math.PI) / 180;
+ const cosR = Math.cos(rad);
const sinR = Math.sin(rad);
+ const fx = flipX ? -1 : 1;
+ const fy = flipY ? -1 : 1;
// Screen corners relative to screen center/pan
const corners = [
@@ -1031,9 +1755,9 @@ export function calculateVisibleDocumentBounds(
const rx = sx * cosR - sy * sinR;
const ry = sx * sinR + sy * cosR;
- // Invert center offset
- const docX = rx + docW * 0.5;
- const docY = ry + docH * 0.5;
+ // Invert view flip and center offset
+ const docX = rx * fx + docW * 0.5;
+ const docY = ry * fy + docH * 0.5;
if (docX < minX) minX = docX;
if (docY < minY) minY = docY;
@@ -1049,6 +1773,57 @@ export function calculateVisibleDocumentBounds(
};
}
+interface FboSurface {
+ fbo: WebGLFramebuffer;
+ texture: WebGLTexture;
+ stencilRb: WebGLRenderbuffer | null;
+ width: number;
+ height: number;
+}
+
+interface PingPongTarget {
+ surfaces: [FboSurface, FboSurface];
+ activeIndex: 0 | 1;
+}
+
+interface LayerUniformLocs {
+ uDocDimensions: WebGLUniformLocation | null;
+ uViewportSize: WebGLUniformLocation | null;
+ uPan: WebGLUniformLocation | null;
+ uZoom: WebGLUniformLocation | null;
+ uRotationRad: WebGLUniformLocation | null;
+ uFlip: WebGLUniformLocation | null;
+ uDpr: WebGLUniformLocation | null;
+ uBackdropTexture: WebGLUniformLocation | null;
+ uHasBackdrop: WebGLUniformLocation | null;
+ uLayerOpacity: WebGLUniformLocation | null;
+ uBlendMode: WebGLUniformLocation | null;
+ uToneEnabled: WebGLUniformLocation | null;
+ uToneFrequency: WebGLUniformLocation | null;
+ uToneAngleRad: WebGLUniformLocation | null;
+ uToneDpi: WebGLUniformLocation | null;
+ uToneDotShape: WebGLUniformLocation | null;
+ uToneDensity: WebGLUniformLocation | null;
+ uToneDensityType: WebGLUniformLocation | null;
+ uLayerColorEnabled: WebGLUniformLocation | null;
+ uLayerColor: WebGLUniformLocation | null;
+ uLayerSubColor: WebGLUniformLocation | null;
+ uMaskTexture: WebGLUniformLocation | null;
+ uMaskEnabled: WebGLUniformLocation | null;
+ uExpressionMode: WebGLUniformLocation | null;
+ uMonoThreshold: WebGLUniformLocation | null;
+ uMonoExpressBlack: WebGLUniformLocation | null;
+ uMonoExpressWhite: WebGLUniformLocation | null;
+}
+
+interface ArrayPoolSlot {
+ sliceIndex: number;
+ currentKey: string | null;
+ version: number;
+ lastUsed: number;
+ lastBatchTick: number;
+}
+
/**
* High-performance WebGL2 Viewport Compositor
*/
@@ -1058,36 +1833,41 @@ export class ViewportCompositor {
private program: WebGLProgram | null = null;
private quadBuffer: WebGLBuffer | null = null;
- // Uniform locations
+ // Standard compositor uniform locations
private uTileOriginLoc: WebGLUniformLocation | null = null;
private uTileSizeLoc: WebGLUniformLocation | null = null;
- private uDocDimensionsLoc: WebGLUniformLocation | null = null;
- private uViewportSizeLoc: WebGLUniformLocation | null = null;
- private uPanLoc: WebGLUniformLocation | null = null;
- private uZoomLoc: WebGLUniformLocation | null = null;
- private uRotationRadLoc: WebGLUniformLocation | null = null;
- private uDprLoc: WebGLUniformLocation | null = null;
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;
-
- // Tone uniform locations
- private uToneEnabledLoc: WebGLUniformLocation | null = null;
- private uToneFrequencyLoc: WebGLUniformLocation | null = null;
- private uToneAngleRadLoc: WebGLUniformLocation | null = null;
- private uToneDpiLoc: WebGLUniformLocation | null = null;
- private uToneDotShapeLoc: WebGLUniformLocation | null = null;
- private uToneDensityLoc: WebGLUniformLocation | null = null;
- private uToneDensityTypeLoc: WebGLUniformLocation | null = null;
-
- // Tint uniform locations
- private uLayerColorEnabledLoc: WebGLUniformLocation | null = null;
- private uLayerColorLoc: WebGLUniformLocation | null = null;
- private uLayerSubColorLoc: WebGLUniformLocation | null = null;
+ private stdLocs: LayerUniformLocs | null = null;
+
+ // Instanced TEXTURE_2D_ARRAY batching program, VAO, buffer, & pool
+ private static readonly DEFAULT_ARRAY_POOL_LAYERS = 256;
+ private instancedProgram: WebGLProgram | null = null;
+ private instancedLocs: LayerUniformLocs | null = null;
+ private uInstTileSizeLoc: WebGLUniformLocation | null = null;
+ private uInstTileArrayLoc: WebGLUniformLocation | null = null;
+ private aInstQuadPosLoc: number = -1;
+ private aInstDataLoc: number = -1;
+ private instancedVao: WebGLVertexArrayObject | null = null;
+ private instanceBuffer: WebGLBuffer | null = null;
+ private instanceFloatScratch: Float32Array = new Float32Array(
+ ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS * 3
+ );
+ private tileArrayTexture: WebGLTexture | null = null;
+ private arrayPoolCapacity: number = 0;
+ private arrayPoolFilterTier: number = -1;
+ private arrayPoolSlots: ArrayPoolSlot[] = [];
+ private arrayPoolByKey: Map<string, ArrayPoolSlot> = new Map();
+ private arrayAccessCounter: number = 0;
+ private arrayBatchCounter: number = 0;
+
+ // Viewport-space draft stroke program (reuses COMPOSITOR_FRAGMENT_SHADER)
+ private viewportDraftProgram: WebGLProgram | null = null;
+ private viewportDraftLocs: LayerUniformLocs | null = null;
+ private uViewportDraftTileTexLoc: WebGLUniformLocation | null = null;
+ private uViewportDraftIsBgLoc: WebGLUniformLocation | null = null;
+ private aViewportDraftQuadPosLoc: number = -1;
// Cached attribute locations (eliminates per-frame gl.getAttribLocation stalls)
private aQuadPosLoc: number = -1;
@@ -1098,17 +1878,13 @@ export class ViewportCompositor {
private onContextLostHandler: ((e: Event) => void) | null = null;
private onContextRestoredHandler: (() => void) | null = null;
- // Mask uniform locations & version-tracked cache
- private uMaskTextureLoc: WebGLUniformLocation | null = null;
- private uMaskEnabledLoc: WebGLUniformLocation | null = null;
- private uExpressionModeLoc: WebGLUniformLocation | null = null;
- private uMonoThresholdLoc: WebGLUniformLocation | null = null;
- private uMonoExpressBlackLoc: WebGLUniformLocation | null = null;
- private uMonoExpressWhiteLoc: WebGLUniformLocation | null = null;
+ // Mask version-tracked cache & invalidation epochs
private maskTextureCache: Map<
string,
{ texture: WebGLTexture; version: number; width: number; height: number }
> = new Map();
+ private maskInvalidationEpochs: Map<string, number> = new Map();
+ private globalMaskEpochCounter: number = 0;
// Live in-stack draft stroke texture cache
private draftTexture: WebGLTexture | null = null;
@@ -1117,7 +1893,14 @@ export class ViewportCompositor {
private lastDraftVersion: number = -1;
private currentOptions: CompositorOptions | null = null;
private currentZoom: number = 1.0;
- private premulScratch: Uint8Array = new Uint8Array(TILE_SIZE * TILE_SIZE * 4);
+ private currentFrameState: {
+ viewportW: number;
+ viewportH: number;
+ dpr: number;
+ dimensions: CanvasDimensions;
+ transform: ViewportTransform;
+ rotRad: number;
+ } | null = null;
// Adjustment program & uniforms
private adjProgram: WebGLProgram | null = null;
@@ -1128,6 +1911,7 @@ export class ViewportCompositor {
private uAdjPanLoc: WebGLUniformLocation | null = null;
private uAdjZoomLoc: WebGLUniformLocation | null = null;
private uAdjRotationRadLoc: WebGLUniformLocation | null = null;
+ private uAdjFlipLoc: WebGLUniformLocation | null = null;
private uAdjDprLoc: WebGLUniformLocation | null = null;
private uAdjSnapshotLoc: WebGLUniformLocation | null = null;
private uAdjLutLoc: WebGLUniformLocation | null = null;
@@ -1136,9 +1920,6 @@ export class ViewportCompositor {
private uAdjMaskEnabledLoc: WebGLUniformLocation | null = null;
private uAdjMaskTextureLoc: WebGLUniformLocation | null = null;
- private snapshotTexture: WebGLTexture | null = null;
- private snapshotWidth: number = 0;
- private snapshotHeight: number = 0;
private lutTexture: WebGLTexture | null = null;
private lastLutKey: string = '';
private lastLutAdjMode: number = 0;
@@ -1150,6 +1931,7 @@ export class ViewportCompositor {
private layerTexture: WebGLTexture | null = null;
private layerFboWidth: number = 0;
private layerFboHeight: number = 0;
+ private layerStylesOutFbo: FboSurface | null = null;
private uStylesLayerTextureLoc: WebGLUniformLocation | null = null;
private uStylesViewportSizeLoc: WebGLUniformLocation | null = null;
@@ -1168,33 +1950,33 @@ export class ViewportCompositor {
private uStylesShadowBlurLoc: WebGLUniformLocation | null = null;
private uStylesShadowSpreadLoc: WebGLUniformLocation | null = null;
- // Folder compositing blit program, uniforms, & FBOs
+ // Folder / Cache blit program & uniforms
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;
- stencilRb: WebGLRenderbuffer | null;
- width: number;
- height: number;
- }[] = [];
- // Soft proofing program, uniforms, & snapshot texture
+ // Ping-Pong FBOs (eliminates all gl.copyTexSubImage2D calls for custom blend modes)
+ private scenePingPong: PingPongTarget | null = null;
+ private folderPingPongs: PingPongTarget[] = [];
+
+ // Baked Layer Stack Cache FBOs (below & above active layer)
+ private belowActiveCacheFbo: FboSurface | null = null;
+ private aboveActiveCacheFbo: FboSurface | null = null;
+ private stackCache: LayerStackCacheTracker = new LayerStackCacheTracker();
+ private stackCacheStats = { belowRebuilds: 0, aboveRebuilds: 0, cacheHits: 0 };
+
+ // Soft proofing program & uniforms
private softProofProgram: WebGLProgram | null = null;
private uProofSceneTextureLoc: WebGLUniformLocation | null = null;
private uProofStandardLoc: WebGLUniformLocation | null = null;
private uProofEnabledLoc: WebGLUniformLocation | null = null;
private uProofGamutWarningLoc: WebGLUniformLocation | null = null;
private uProofGamutWarningColorLoc: WebGLUniformLocation | null = null;
- private proofSnapshotTexture: WebGLTexture | null = null;
- private proofSnapshotWidth: number = 0;
- private proofSnapshotHeight: number = 0;
- // Pre-allocated WebGL Texture Pool for dynamic texture streaming
+ // Pre-allocated WebGL2 Texture2D Pool (overflow fallback for TEXTURE_2D_ARRAY)
private static readonly MAX_TEXTURE_POOL_SIZE = 2048;
private textureAccessCounter: number = 0;
private texturePool: Array<{
@@ -1228,6 +2010,15 @@ export class ViewportCompositor {
this.contextLost = true;
this.gl = null;
this.program = null;
+ this.instancedProgram = null;
+ this.instancedVao = null;
+ this.instanceBuffer = null;
+ this.tileArrayTexture = null;
+ this.arrayPoolSlots = [];
+ this.arrayPoolByKey.clear();
+ this.arrayPoolCapacity = 0;
+ this.arrayPoolFilterTier = -1;
+ this.viewportDraftProgram = null;
this.adjProgram = null;
this.stylesProgram = null;
this.blitProgram = null;
@@ -1235,13 +2026,16 @@ export class ViewportCompositor {
this.texturePool = [];
this.activePoolByKey.clear();
this.maskTextureCache.clear();
- this.folderFbos = [];
+ this.scenePingPong = null;
+ this.folderPingPongs = [];
+ this.belowActiveCacheFbo = null;
+ this.aboveActiveCacheFbo = null;
+ this.layerStylesOutFbo = null;
this.layerFbo = null;
this.layerTexture = null;
- this.snapshotTexture = null;
this.lutTexture = null;
this.draftTexture = null;
- this.proofSnapshotTexture = null;
+ this.stackCache.invalidateAll();
};
this.onContextRestoredHandler = () => {
this.contextLost = false;
@@ -1258,22 +2052,41 @@ export class ViewportCompositor {
return !this.contextLost && this.gl !== null && this.program !== null;
}
+ public getCanvas(): HTMLCanvasElement {
+ return this.canvas;
+ }
+
+ public getStackCacheStats(): { belowRebuilds: number; aboveRebuilds: number; cacheHits: number } {
+ return { ...this.stackCacheStats };
+ }
+
+ /**
+ * Explicitly invalidate baked layer stack caches.
+ */
+ public invalidateStackCache(): void {
+ this.stackCache.invalidateAll();
+ }
+
/**
* Explicitly invalidate a cached layer mask texture (or all masks if layerId omitted).
*/
public invalidateMaskTexture(layerId?: string): void {
+ const nextEpoch = ++this.globalMaskEpochCounter;
if (layerId) {
const item = this.maskTextureCache.get(layerId);
if (item) item.version = -1;
+ this.maskInvalidationEpochs.set(layerId, nextEpoch);
} else {
- for (const item of this.maskTextureCache.values()) {
+ for (const [id, item] of this.maskTextureCache.entries()) {
item.version = -1;
+ this.maskInvalidationEpochs.set(id, nextEpoch);
}
+ this.stackCache.invalidateAll();
}
}
/**
- * Explicitly invalidate and clear all cached tile textures in the pool.
+ * Explicitly invalidate and clear all cached tile textures in both TEXTURE_2D and TEXTURE_2D_ARRAY pools.
*/
public invalidateTileTextures(): void {
if (this.gl) {
@@ -1283,6 +2096,162 @@ export class ViewportCompositor {
}
this.texturePool = [];
this.activePoolByKey.clear();
+ for (const slot of this.arrayPoolSlots) {
+ slot.currentKey = null;
+ slot.version = -1;
+ slot.lastUsed = 0;
+ slot.lastBatchTick = 0;
+ }
+ this.arrayPoolByKey.clear();
+ this.stackCache.invalidateAll();
+ }
+
+ private queryLayerUniformLocs(gl: WebGL2RenderingContext, prog: WebGLProgram): LayerUniformLocs {
+ return {
+ uDocDimensions: gl.getUniformLocation(prog, 'u_docDimensions'),
+ uViewportSize: gl.getUniformLocation(prog, 'u_viewportSize'),
+ uPan: gl.getUniformLocation(prog, 'u_pan'),
+ uZoom: gl.getUniformLocation(prog, 'u_zoom'),
+ uRotationRad: gl.getUniformLocation(prog, 'u_rotationRad'),
+ uFlip: gl.getUniformLocation(prog, 'u_flip'),
+ uDpr: gl.getUniformLocation(prog, 'u_dpr'),
+ uBackdropTexture: gl.getUniformLocation(prog, 'u_backdropTexture'),
+ uHasBackdrop: gl.getUniformLocation(prog, 'u_hasBackdrop'),
+ uLayerOpacity: gl.getUniformLocation(prog, 'u_layerOpacity'),
+ uBlendMode: gl.getUniformLocation(prog, 'u_blendMode'),
+ uToneEnabled: gl.getUniformLocation(prog, 'u_toneEnabled'),
+ uToneFrequency: gl.getUniformLocation(prog, 'u_toneFrequency'),
+ uToneAngleRad: gl.getUniformLocation(prog, 'u_toneAngleRad'),
+ uToneDpi: gl.getUniformLocation(prog, 'u_toneDpi'),
+ uToneDotShape: gl.getUniformLocation(prog, 'u_toneDotShape'),
+ uToneDensity: gl.getUniformLocation(prog, 'u_toneDensity'),
+ uToneDensityType: gl.getUniformLocation(prog, 'u_toneDensityType'),
+ uLayerColorEnabled: gl.getUniformLocation(prog, 'u_layerColorEnabled'),
+ uLayerColor: gl.getUniformLocation(prog, 'u_layerColor'),
+ uLayerSubColor: gl.getUniformLocation(prog, 'u_layerSubColor'),
+ uMaskTexture: gl.getUniformLocation(prog, 'u_maskTexture'),
+ uMaskEnabled: gl.getUniformLocation(prog, 'u_maskEnabled'),
+ uExpressionMode: gl.getUniformLocation(prog, 'u_expressionMode'),
+ uMonoThreshold: gl.getUniformLocation(prog, 'u_monoThreshold'),
+ uMonoExpressBlack: gl.getUniformLocation(prog, 'u_monoExpressBlack'),
+ uMonoExpressWhite: gl.getUniformLocation(prog, 'u_monoExpressWhite'),
+ };
+ }
+
+ private initTileArrayPool(gl: WebGL2RenderingContext): void {
+ if (
+ typeof gl.texStorage3D !== 'function' ||
+ typeof gl.texSubImage3D !== 'function' ||
+ typeof gl.drawArraysInstanced !== 'function' ||
+ typeof gl.vertexAttribDivisor !== 'function' ||
+ !this.quadBuffer
+ ) {
+ return;
+ }
+
+ const instVs = gl.createShader(gl.VERTEX_SHADER);
+ const instFs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!instVs || !instFs) return;
+
+ gl.shaderSource(instVs, COMPOSITOR_INSTANCED_VERTEX_SHADER);
+ gl.compileShader(instVs);
+ gl.shaderSource(instFs, COMPOSITOR_INSTANCED_FRAGMENT_SHADER);
+ gl.compileShader(instFs);
+ if (
+ !gl.getShaderParameter(instVs, gl.COMPILE_STATUS) ||
+ !gl.getShaderParameter(instFs, gl.COMPILE_STATUS)
+ ) {
+ console.error('Instanced tile shader compile error:', gl.getShaderInfoLog(instVs), gl.getShaderInfoLog(instFs));
+ return;
+ }
+
+ const iProg = gl.createProgram();
+ if (!iProg) return;
+ gl.attachShader(iProg, instVs);
+ gl.attachShader(iProg, instFs);
+ gl.linkProgram(iProg);
+ if (!gl.getProgramParameter(iProg, gl.LINK_STATUS)) {
+ console.error('Instanced tile program link error:', gl.getProgramInfoLog(iProg));
+ return;
+ }
+
+ const maxLayersParam = Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS;
+ const capacity = Math.max(1, Math.min(ViewportCompositor.DEFAULT_ARRAY_POOL_LAYERS, maxLayersParam));
+
+ const arrTex = gl.createTexture();
+ const instBuf = gl.createBuffer();
+ if (!arrTex || !instBuf) {
+ if (arrTex) gl.deleteTexture(arrTex);
+ if (instBuf) gl.deleteBuffer(instBuf);
+ gl.deleteProgram(iProg);
+ return;
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, arrTex);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, TILE_SIZE, TILE_SIZE, capacity);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
+
+ this.instanceFloatScratch = new Float32Array(capacity * 3);
+ gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, this.instanceFloatScratch.byteLength, gl.DYNAMIC_DRAW);
+
+ this.instancedProgram = iProg;
+ this.instancedLocs = this.queryLayerUniformLocs(gl, iProg);
+ this.uInstTileSizeLoc = gl.getUniformLocation(iProg, 'u_tileSize');
+ this.uInstTileArrayLoc = gl.getUniformLocation(iProg, 'u_tileArrayTexture');
+ this.aInstQuadPosLoc = gl.getAttribLocation(iProg, 'a_quadPos');
+ this.aInstDataLoc = gl.getAttribLocation(iProg, 'a_instanceData');
+
+ // Immediately bind distinct texture units for sampler2DArray (0) vs sampler2D (1, 2)
+ // to prevent WebGL2 GL_INVALID_OPERATION sampler-type collisions on unit 0.
+ gl.useProgram(iProg);
+ gl.uniform1i(this.uInstTileArrayLoc, 0);
+ gl.uniform1i(this.instancedLocs.uMaskTexture, 1);
+ gl.uniform1i(this.instancedLocs.uBackdropTexture, 2);
+ if (this.program) {
+ gl.useProgram(this.program);
+ }
+
+ this.tileArrayTexture = arrTex;
+ this.instanceBuffer = instBuf;
+ this.arrayPoolCapacity = capacity;
+ this.arrayPoolFilterTier = 1;
+ this.arrayPoolSlots = [];
+ this.arrayPoolByKey.clear();
+ for (let i = 0; i < capacity; i++) {
+ this.arrayPoolSlots.push({
+ sliceIndex: i,
+ currentKey: null,
+ version: -1,
+ lastUsed: 0,
+ lastBatchTick: 0,
+ });
+ }
+
+ if (typeof gl.createVertexArray === 'function') {
+ const vao = gl.createVertexArray();
+ if (vao) {
+ gl.bindVertexArray(vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ if (this.aInstQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aInstQuadPosLoc);
+ gl.vertexAttribPointer(this.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(this.aInstQuadPosLoc, 0);
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
+ if (this.aInstDataLoc >= 0) {
+ gl.enableVertexAttribArray(this.aInstDataLoc);
+ gl.vertexAttribPointer(this.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(this.aInstDataLoc, 1);
+ }
+ gl.bindVertexArray(null);
+ this.instancedVao = vao;
+ }
+ }
}
private initGL(): boolean {
@@ -1321,7 +2290,7 @@ export class ViewportCompositor {
return false;
}
- // Link program
+ // Link standard compositor program
const prog = gl.createProgram();
if (!prog) return false;
gl.attachShader(prog, vs);
@@ -1332,44 +2301,38 @@ export class ViewportCompositor {
return false;
}
this.program = prog;
+ this.stdLocs = this.queryLayerUniformLocs(gl, prog);
- // Cache uniforms
+ // Cache standard-only uniforms
this.uTileOriginLoc = gl.getUniformLocation(prog, 'u_tileOrigin');
this.uTileSizeLoc = gl.getUniformLocation(prog, 'u_tileSize');
- this.uDocDimensionsLoc = gl.getUniformLocation(prog, 'u_docDimensions');
- this.uViewportSizeLoc = gl.getUniformLocation(prog, 'u_viewportSize');
- this.uPanLoc = gl.getUniformLocation(prog, 'u_pan');
- this.uZoomLoc = gl.getUniformLocation(prog, 'u_zoom');
- this.uRotationRadLoc = gl.getUniformLocation(prog, 'u_rotationRad');
- this.uDprLoc = gl.getUniformLocation(prog, 'u_dpr');
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');
-
- this.uToneEnabledLoc = gl.getUniformLocation(prog, 'u_toneEnabled');
- this.uToneFrequencyLoc = gl.getUniformLocation(prog, 'u_toneFrequency');
- this.uToneAngleRadLoc = gl.getUniformLocation(prog, 'u_toneAngleRad');
- this.uToneDpiLoc = gl.getUniformLocation(prog, 'u_toneDpi');
- this.uToneDotShapeLoc = gl.getUniformLocation(prog, 'u_toneDotShape');
- this.uToneDensityLoc = gl.getUniformLocation(prog, 'u_toneDensity');
- this.uToneDensityTypeLoc = gl.getUniformLocation(prog, 'u_toneDensityType');
-
- this.uLayerColorEnabledLoc = gl.getUniformLocation(prog, 'u_layerColorEnabled');
- this.uLayerColorLoc = gl.getUniformLocation(prog, 'u_layerColor');
- this.uLayerSubColorLoc = gl.getUniformLocation(prog, 'u_layerSubColor');
-
- this.uMaskTextureLoc = gl.getUniformLocation(prog, 'u_maskTexture');
- this.uMaskEnabledLoc = gl.getUniformLocation(prog, 'u_maskEnabled');
- this.uExpressionModeLoc = gl.getUniformLocation(prog, 'u_expressionMode');
- this.uMonoThresholdLoc = gl.getUniformLocation(prog, 'u_monoThreshold');
- this.uMonoExpressBlackLoc = gl.getUniformLocation(prog, 'u_monoExpressBlack');
- this.uMonoExpressWhiteLoc = gl.getUniformLocation(prog, 'u_monoExpressWhite');
this.aQuadPosLoc = gl.getAttribLocation(prog, 'a_quadPos');
+ // Compile Viewport-Space Draft Shader Program (shares COMPOSITOR_FRAGMENT_SHADER)
+ const draftVs = gl.createShader(gl.VERTEX_SHADER);
+ if (draftVs) {
+ gl.shaderSource(draftVs, VIEWPORT_DRAFT_VERTEX_SHADER);
+ gl.compileShader(draftVs);
+ if (gl.getShaderParameter(draftVs, gl.COMPILE_STATUS)) {
+ const dProg = gl.createProgram();
+ if (dProg) {
+ gl.attachShader(dProg, draftVs);
+ gl.attachShader(dProg, fs);
+ gl.linkProgram(dProg);
+ if (gl.getProgramParameter(dProg, gl.LINK_STATUS)) {
+ this.viewportDraftProgram = dProg;
+ this.viewportDraftLocs = this.queryLayerUniformLocs(gl, dProg);
+ this.uViewportDraftTileTexLoc = gl.getUniformLocation(dProg, 'u_tileTexture');
+ this.uViewportDraftIsBgLoc = gl.getUniformLocation(dProg, 'u_isBackground');
+ this.aViewportDraftQuadPosLoc = gl.getAttribLocation(dProg, 'a_quadPos');
+ }
+ }
+ }
+ }
+
// Compile Adjustment Shader Program
const adjFs = gl.createShader(gl.FRAGMENT_SHADER);
if (adjFs) {
@@ -1390,6 +2353,7 @@ export class ViewportCompositor {
this.uAdjPanLoc = gl.getUniformLocation(aProg, 'u_pan');
this.uAdjZoomLoc = gl.getUniformLocation(aProg, 'u_zoom');
this.uAdjRotationRadLoc = gl.getUniformLocation(aProg, 'u_rotationRad');
+ this.uAdjFlipLoc = gl.getUniformLocation(aProg, 'u_flip');
this.uAdjDprLoc = gl.getUniformLocation(aProg, 'u_dpr');
this.uAdjSnapshotLoc = gl.getUniformLocation(aProg, 'u_snapshotTexture');
this.uAdjLutLoc = gl.getUniformLocation(aProg, 'u_lutTexture');
@@ -1444,7 +2408,7 @@ export class ViewportCompositor {
}
}
- // Compile Folder Blit Shader Program
+ // Compile Folder / Cache Blit Shader Program
const blitVs = gl.createShader(gl.VERTEX_SHADER);
const blitFs = gl.createShader(gl.FRAGMENT_SHADER);
if (blitVs && blitFs) {
@@ -1539,6 +2503,9 @@ export class ViewportCompositor {
);
this.quadBuffer = quad;
+ // Initialize TEXTURE_2D_ARRAY + instanced batch rendering pipeline
+ this.initTileArrayPool(gl);
+
// Enable blending
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
@@ -1554,9 +2521,12 @@ export class ViewportCompositor {
* Resize viewport canvas to physical screen pixels.
*/
public resize(width: number, height: number): void {
- if (this.canvas.width !== width || this.canvas.height !== height) {
- this.canvas.width = Math.max(1, width);
- this.canvas.height = Math.max(1, height);
+ const nextW = Math.max(1, width);
+ const nextH = Math.max(1, height);
+ if (this.canvas.width !== nextW || this.canvas.height !== nextH) {
+ this.canvas.width = nextW;
+ this.canvas.height = nextH;
+ this.stackCache.invalidateAll();
if (this.gl) {
this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
}
@@ -1577,99 +2547,479 @@ export class ViewportCompositor {
return calculateVisibleDocumentBounds(viewportW, viewportH, transform, docW, docH);
}
- /**
- * Get or upload a WebGLTexture from the pre-allocated texture pool with adaptive zoom filtering.
- * Only tiles currently intersecting the screen frustum are uploaded to GPU memory.
- */
- private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
- if (!this.gl) return null;
- const gl = this.gl;
- const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
- const accessTick = ++this.textureAccessCounter;
-
- let slot = this.activePoolByKey.get(key);
+ // ============================================================================
+ // Ping-Pong FBO & Offscreen Cache Surface Management
+ // ============================================================================
+
+ private createFboSurface(gl: WebGL2RenderingContext, withStencil: boolean = true): FboSurface | null {
+ const fbo = gl.createFramebuffer();
+ const texture = gl.createTexture();
+ if (!fbo || !texture) {
+ if (fbo) gl.deleteFramebuffer(fbo);
+ if (texture) gl.deleteTexture(texture);
+ return null;
+ }
+ const stencilRb =
+ withStencil && typeof gl.createRenderbuffer === 'function' ? gl.createRenderbuffer() : null;
+ return { fbo, texture, stencilRb, width: 0, height: 0 };
+ }
- if (!slot) {
- if (this.texturePool.length < ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
- const tex = gl.createTexture();
- if (!tex) return null;
- slot = {
- texture: tex,
- currentKey: key,
- version: -1,
- lastUsed: accessTick,
- filterTier: -1,
- hasStorage: false,
- hasMipmap: false,
- };
- this.texturePool.push(slot);
- this.activePoolByKey.set(key, slot);
- } else {
- // Reuse least recently used texture slot from pool
- let oldestSlot = this.texturePool[0];
- for (let i = 1; i < this.texturePool.length; i++) {
- if (this.texturePool[i].lastUsed < oldestSlot.lastUsed) {
- oldestSlot = this.texturePool[i];
- }
- }
- slot = oldestSlot;
- if (slot.currentKey) {
- this.activePoolByKey.delete(slot.currentKey);
- }
- slot.currentKey = key;
- slot.version = -1;
- slot.lastUsed = accessTick;
- slot.filterTier = -1;
- slot.hasMipmap = false;
- this.activePoolByKey.set(key, slot);
- }
+ private ensureFboSurfaceSize(
+ gl: WebGL2RenderingContext,
+ surface: FboSurface,
+ width: number,
+ height: number
+ ): boolean {
+ if (surface.width === width && surface.height === height) {
+ return true;
}
- slot.lastUsed = accessTick;
- const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
+ const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
- // Re-upload if dirty or version bumped
- if (slot.version !== tile.version || tile.dirty) {
- gl.bindTexture(gl.TEXTURE_2D, slot.texture);
+ gl.bindTexture(gl.TEXTURE_2D, surface.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);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- const rgbaData = grid.getTileAsRGBA(tile);
- const srcBytes =
- rgbaData instanceof Uint8Array
- ? rgbaData
- : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
- const uploadBytes = this.premulScratch;
- const len = Math.min(srcBytes.length, uploadBytes.length);
- for (let i = 0; i < len; i += 4) {
- const a = srcBytes[i + 3];
- if (a === 255) {
- uploadBytes[i] = srcBytes[i];
- uploadBytes[i + 1] = srcBytes[i + 1];
- uploadBytes[i + 2] = srcBytes[i + 2];
- uploadBytes[i + 3] = 255;
- } else if (a === 0) {
- uploadBytes[i] = 0;
- uploadBytes[i + 1] = 0;
- uploadBytes[i + 2] = 0;
- uploadBytes[i + 3] = 0;
- } else {
- uploadBytes[i] = (srcBytes[i] * a + 127) / 255;
- uploadBytes[i + 1] = (srcBytes[i + 1] * a + 127) / 255;
- uploadBytes[i + 2] = (srcBytes[i + 2] * a + 127) / 255;
- uploadBytes[i + 3] = a;
- }
- }
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surface.fbo);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, surface.texture, 0);
- if (slot.hasStorage && typeof gl.texSubImage2D === 'function') {
- gl.texSubImage2D(
- gl.TEXTURE_2D,
- 0,
- 0,
+ if (surface.stencilRb && typeof gl.bindRenderbuffer === 'function') {
+ gl.bindRenderbuffer(gl.RENDERBUFFER, surface.stencilRb);
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, surface.stencilRb);
+ }
+
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
+
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
+ console.error('Compositor FBO surface incomplete:', status);
+ return false;
+ }
+
+ surface.width = width;
+ surface.height = height;
+ return true;
+ }
+
+ private ensurePingPongTarget(
+ gl: WebGL2RenderingContext,
+ existing: PingPongTarget | null,
+ width: number,
+ height: number
+ ): PingPongTarget | null {
+ let target = existing;
+ if (!target) {
+ const s0 = this.createFboSurface(gl, true);
+ const s1 = this.createFboSurface(gl, true);
+ if (!s0 || !s1) {
+ this.disposeFboSurface(gl, s0);
+ this.disposeFboSurface(gl, s1);
+ return null;
+ }
+ target = { surfaces: [s0, s1], activeIndex: 0 };
+ }
+ if (
+ !this.ensureFboSurfaceSize(gl, target.surfaces[0], width, height) ||
+ !this.ensureFboSurfaceSize(gl, target.surfaces[1], width, height)
+ ) {
+ return null;
+ }
+ return target;
+ }
+
+ private ensureFolderPingPong(
+ gl: WebGL2RenderingContext,
+ depth: number,
+ width: number,
+ height: number
+ ): PingPongTarget | null {
+ while (this.folderPingPongs.length <= depth) {
+ const created = this.ensurePingPongTarget(gl, null, width, height);
+ if (!created) return null;
+ this.folderPingPongs.push(created);
+ }
+ const target = this.ensurePingPongTarget(gl, this.folderPingPongs[depth], width, height);
+ if (!target) return null;
+ this.folderPingPongs[depth] = target;
+ return target;
+ }
+
+ private disposeFboSurface(gl: WebGL2RenderingContext, surface: FboSurface | null): void {
+ if (!surface) return;
+ gl.deleteFramebuffer(surface.fbo);
+ gl.deleteTexture(surface.texture);
+ if (surface.stencilRb && typeof gl.deleteRenderbuffer === 'function') {
+ gl.deleteRenderbuffer(surface.stencilRb);
+ }
+ }
+
+ private disposePingPongTarget(gl: WebGL2RenderingContext, target: PingPongTarget | null): void {
+ if (!target) return;
+ this.disposeFboSurface(gl, target.surfaces[0]);
+ this.disposeFboSurface(gl, target.surfaces[1]);
+ }
+
+ /**
+ * Fast GPU-to-GPU FBO copy via gl.blitFramebuffer (with fullscreen quad fallback).
+ * Eliminates all gl.copyTexSubImage2D calls and preserves stencil buffer when requested.
+ */
+ private copyFboSurface(
+ gl: WebGL2RenderingContext,
+ src: FboSurface,
+ dst: FboSurface,
+ width: number,
+ height: number,
+ copyStencil: boolean = false
+ ): void {
+ if (
+ typeof gl.blitFramebuffer === 'function' &&
+ gl.READ_FRAMEBUFFER !== undefined &&
+ gl.DRAW_FRAMEBUFFER !== undefined
+ ) {
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src.fbo);
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dst.fbo);
+ const mask = copyStencil && src.stencilRb && dst.stencilRb
+ ? (gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)
+ : gl.COLOR_BUFFER_BIT;
+ gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, width, height);
+ return;
+ }
+
+ // Fallback: fullscreen quad copy using blitProgram (zero copyTexSubImage2D)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, width, height);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ if (!this.blitProgram) return;
+
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+ gl.disable(gl.BLEND);
+
+ gl.useProgram(this.blitProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
+ if (this.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, src.texture);
+ gl.uniform1i(this.uBlitTextureLoc, 0);
+ gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(this.uBlitHasBackdropLoc, 0);
+ gl.uniform1i(this.uBlitBlendModeLoc, 0);
+ gl.uniform1f(this.uBlitOpacityLoc, 1.0);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ this.unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ this.restoreStandardProgram(gl);
+ }
+
+ /**
+ * Unbinds offscreen FBO textures from TEXTURE0 and TEXTURE2 so no texture attached
+ * to the next bound DRAW_FRAMEBUFFER can trigger a WebGL2 feedback loop error.
+ */
+ private unbindSceneTextureUnits(gl: WebGL2RenderingContext): void {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ }
+
+ /**
+ * Swaps Ping-Pong FBOs for a programmable blend / adjustment pass:
+ * copies current surface -> opposite surface and returns current surface's immutable texture as backdrop.
+ * ZERO gl.copyTexSubImage2D calls!
+ */
+ private prepareBackdropFromPingPong(
+ gl: WebGL2RenderingContext,
+ target: PingPongTarget,
+ viewportW: number,
+ viewportH: number,
+ preserveStencil: boolean
+ ): WebGLTexture {
+ const src = target.surfaces[target.activeIndex];
+ const nextIdx: 0 | 1 = target.activeIndex === 0 ? 1 : 0;
+ const dst = target.surfaces[nextIdx];
+
+ this.copyFboSurface(gl, src, dst, viewportW, viewportH, preserveStencil);
+ target.activeIndex = nextIdx;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+
+ return src.texture;
+ }
+
+ private restoreStandardProgram(gl: WebGL2RenderingContext): void {
+ if (this.program) {
+ gl.useProgram(this.program);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ }
+ }
+
+ private syncFrameUniforms(gl: WebGL2RenderingContext, locs: LayerUniformLocs): void {
+ const fs = this.currentFrameState;
+ if (!fs) return;
+ gl.uniform2f(locs.uViewportSize, fs.viewportW, fs.viewportH);
+ gl.uniform2f(locs.uDocDimensions, fs.dimensions.width, fs.dimensions.height);
+ gl.uniform2f(locs.uPan, fs.transform.pan.x, fs.transform.pan.y);
+ gl.uniform1f(locs.uZoom, fs.transform.zoom);
+ gl.uniform1f(locs.uRotationRad, fs.rotRad);
+ gl.uniform2f(locs.uFlip, fs.transform.flipX ? -1.0 : 1.0, fs.transform.flipY ? -1.0 : 1.0);
+ gl.uniform1f(locs.uDpr, fs.dpr);
+ }
+
+ private applyLayerUniforms(
+ gl: WebGL2RenderingContext,
+ locs: LayerUniformLocs,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null
+ ): void {
+ gl.uniform1f(locs.uLayerOpacity, effectiveOpacity);
+ gl.uniform1i(locs.uBlendMode, modeCode);
+
+ // Always bind distinct sampler units (mask = 1, backdrop = 2) so sampler2D never
+ // collides with sampler2DArray on unit 0 in WebGL2.
+ gl.uniform1i(locs.uBackdropTexture, 2);
+ gl.uniform1i(locs.uMaskTexture, 1);
+
+ if (backdropTex && modeCode !== 0 && modeCode !== 12) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ gl.uniform1i(locs.uHasBackdrop, 1);
+ } else {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.uniform1i(locs.uHasBackdrop, 0);
+ }
+
+ // Expression Color Uniforms
+ const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
+ const exprMode = isBgLayer
+ ? 0
+ : layer.expressionColor === 'monochrome'
+ ? 2
+ : layer.expressionColor === 'gray'
+ ? 1
+ : 0;
+ gl.uniform1i(locs.uExpressionMode, exprMode);
+ if (exprMode === 2) {
+ gl.uniform1f(locs.uMonoThreshold, (layer.monoThreshold ?? 128) / 255.0);
+ gl.uniform1i(locs.uMonoExpressBlack, layer.monoExpressBlack !== false ? 1 : 0);
+ gl.uniform1i(locs.uMonoExpressWhite, layer.monoExpressWhite !== false ? 1 : 0);
+ }
+
+ // Screentone Uniforms
+ const toneEnabled = Boolean(layer.toneEnabled);
+ gl.uniform1i(locs.uToneEnabled, toneEnabled ? 1 : 0);
+ if (toneEnabled) {
+ gl.uniform1f(locs.uToneFrequency, layer.toneFrequency || 60);
+ gl.uniform1f(locs.uToneAngleRad, ((layer.toneAngle || 45) * Math.PI) / 180);
+ gl.uniform1f(locs.uToneDpi, dimensions.dpi || 600);
+ const dotShapeCode =
+ layer.toneDotShape === 'line'
+ ? 2
+ : layer.toneDotShape === 'diamond'
+ ? 3
+ : layer.toneDotShape === 'euclidean'
+ ? 1
+ : 0;
+ gl.uniform1i(locs.uToneDotShape, dotShapeCode);
+ gl.uniform1f(locs.uToneDensity, (layer.toneDensity ?? 40) / 100);
+ gl.uniform1i(locs.uToneDensityType, layer.toneDensityType === 'image' ? 1 : 0);
+ }
+
+ // Layer Tint Uniforms
+ const tintEnabled = Boolean(layer.layerColorEnabled);
+ gl.uniform1i(locs.uLayerColorEnabled, tintEnabled ? 1 : 0);
+ if (tintEnabled) {
+ const prim = this.parseHexColor(layer.layerColor || '#1c73c2');
+ const sub = this.parseHexColor(layer.layerSubColor || '#ffffff');
+ gl.uniform3f(locs.uLayerColor, prim[0], prim[1], prim[2]);
+ gl.uniform3f(locs.uLayerSubColor, sub[0], sub[1], sub[2]);
+ }
+
+ // Layer Mask Uniforms
+ if (maskTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(locs.uMaskEnabled, 1);
+ } else {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.uniform1i(locs.uMaskEnabled, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ }
+
+ // ============================================================================
+ // Tile Texture Streaming (Zero-CPU Premultiply via UNPACK_PREMULTIPLY_ALPHA_WEBGL)
+ // ============================================================================
+
+ /**
+ * Allocates or updates a slice inside the TEXTURE_2D_ARRAY pool using hardware UNPACK_PREMULTIPLY_ALPHA_WEBGL.
+ * Never evicts slices pinned by the current batchTick.
+ */
+ private getOrUploadArrayTileSlice(
+ gl: WebGL2RenderingContext,
+ tile: TileBuffer,
+ grid: SparseTileGrid,
+ batchTick: number
+ ): number {
+ const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
+ const accessTick = ++this.arrayAccessCounter;
+ let slot = this.arrayPoolByKey.get(key);
+
+ if (!slot) {
+ let oldestSlot: ArrayPoolSlot | null = null;
+ for (let i = 0; i < this.arrayPoolSlots.length; i++) {
+ const candidate = this.arrayPoolSlots[i];
+ if (candidate.lastBatchTick === batchTick) continue;
+ if (candidate.currentKey === null) {
+ oldestSlot = candidate;
+ break;
+ }
+ if (!oldestSlot || candidate.lastUsed < oldestSlot.lastUsed) {
+ oldestSlot = candidate;
+ }
+ }
+ if (!oldestSlot) return -1;
+ slot = oldestSlot;
+ if (slot.currentKey) {
+ this.arrayPoolByKey.delete(slot.currentKey);
+ }
+ slot.currentKey = key;
+ slot.version = -1;
+ this.arrayPoolByKey.set(key, slot);
+ }
+
+ slot.lastUsed = accessTick;
+ slot.lastBatchTick = batchTick;
+
+ if (slot.version !== tile.version || tile.dirty) {
+ const rgbaData = grid.getTileAsRGBA(tile);
+ const srcBytes =
+ rgbaData instanceof Uint8Array
+ ? rgbaData
+ : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
+
+ // Upload straight-alpha RGBA bytes directly into TEXTURE_2D_ARRAY slice
+ // (UNPACK_PREMULTIPLY_ALPHA_WEBGL must be false for texSubImage3D with ArrayBufferView in WebGL2;
+ // premultiplied bilinear filtering is performed in 32-bit float inside the fragment shader.)
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texSubImage3D(
+ gl.TEXTURE_2D_ARRAY,
+ 0,
+ 0,
+ 0,
+ slot.sliceIndex,
+ TILE_SIZE,
+ TILE_SIZE,
+ 1,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ srcBytes
+ );
+
+ slot.version = tile.version;
+ tile.dirty = false;
+ }
+
+ return slot.sliceIndex;
+ }
+
+ /**
+ * Get or upload a WebGLTexture from the fallback TEXTURE_2D pool with adaptive zoom filtering.
+ * Uses gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true) directly — zero CPU premultiply loop!
+ */
+ private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
+ if (!this.gl) return null;
+ const gl = this.gl;
+ const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
+ const accessTick = ++this.textureAccessCounter;
+
+ let slot = this.activePoolByKey.get(key);
+
+ if (!slot) {
+ if (this.texturePool.length < ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
+ const tex = gl.createTexture();
+ if (!tex) return null;
+ slot = {
+ texture: tex,
+ currentKey: key,
+ version: -1,
+ lastUsed: accessTick,
+ filterTier: -1,
+ hasStorage: false,
+ hasMipmap: false,
+ };
+ this.texturePool.push(slot);
+ this.activePoolByKey.set(key, slot);
+ } else {
+ // Reuse least recently used texture slot from pool
+ let oldestSlot = this.texturePool[0];
+ for (let i = 1; i < this.texturePool.length; i++) {
+ if (this.texturePool[i].lastUsed < oldestSlot.lastUsed) {
+ oldestSlot = this.texturePool[i];
+ }
+ }
+ slot = oldestSlot;
+ if (slot.currentKey) {
+ this.activePoolByKey.delete(slot.currentKey);
+ }
+ slot.currentKey = key;
+ slot.version = -1;
+ slot.lastUsed = accessTick;
+ slot.filterTier = -1;
+ slot.hasMipmap = false;
+ this.activePoolByKey.set(key, slot);
+ }
+ }
+
+ slot.lastUsed = accessTick;
+ const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
+
+ // Re-upload if dirty or version bumped (direct GPU unpack premultiplication, zero JS pixel loop)
+ if (slot.version !== tile.version || tile.dirty) {
+ gl.bindTexture(gl.TEXTURE_2D, slot.texture);
+
+ const rgbaData = grid.getTileAsRGBA(tile);
+ const srcBytes =
+ rgbaData instanceof Uint8Array
+ ? rgbaData
+ : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ if (slot.hasStorage && typeof gl.texSubImage2D === 'function') {
+ gl.texSubImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ 0,
0,
TILE_SIZE,
TILE_SIZE,
gl.RGBA,
gl.UNSIGNED_BYTE,
- uploadBytes
+ srcBytes
);
} else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
@@ -1683,10 +3033,11 @@ export class ViewportCompositor {
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
- uploadBytes
+ srcBytes
);
slot.hasStorage = true;
}
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
slot.hasMipmap = false;
slot.version = tile.version;
@@ -1709,55 +3060,6 @@ export class ViewportCompositor {
return slot.texture;
}
- /**
- * 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);
-
- 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);
- }
-
/**
* Hex color parser to RGB normalized float array [r, g, b].
*/
@@ -1775,8 +3077,105 @@ export class ViewportCompositor {
];
}
+ private renderArtboardBackground(
+ gl: WebGL2RenderingContext,
+ dimensions: CanvasDimensions,
+ showCheckerboard: boolean
+ ): void {
+ if (!this.program || !this.stdLocs) return;
+ this.unbindSceneTextureUnits(gl);
+ this.restoreStandardProgram(gl);
+ this.syncFrameUniforms(gl, this.stdLocs);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.stdLocs.uMaskTexture, 1);
+ gl.uniform1i(this.stdLocs.uBackdropTexture, 2);
+ gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
+ gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ gl.uniform1i(this.uIsBackgroundLoc, 1);
+ gl.uniform1i(this.stdLocs.uExpressionMode, 0);
+ gl.uniform1i(this.uShowCheckerboardLoc, showCheckerboard ? 1 : 0);
+ gl.uniform2f(this.uTileOriginLoc, 0, 0);
+ gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.uniform1i(this.uIsBackgroundLoc, 0);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ private renderOnionSkins(
+ gl: WebGL2RenderingContext,
+ layers: LayerItem[],
+ onionSkinFrames: OnionSkinCompositorFrame[] | undefined,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: { minX: number; minY: number; maxX: number; maxY: number },
+ target: PingPongTarget | null
+ ): void {
+ if (!onionSkinFrames || onionSkinFrames.length === 0) return;
+ for (const onion of onionSkinFrames) {
+ const targetLayer = layers.find((l) => l.id === onion.layerId);
+ if (targetLayer && targetLayer.visible) {
+ const virtualOnionLayer: LayerItem = {
+ ...targetLayer,
+ opacity: onion.opacity,
+ layerColorEnabled: true,
+ layerColor: onion.tint,
+ layerSubColor: '#ffffff',
+ blendMode: 'normal',
+ };
+ this.renderSingleLayer(gl, virtualOnionLayer, dimensions, grid, frustum, 1.0, target, false);
+ }
+ }
+ }
+
+ private presentTextureToScreen(
+ gl: WebGL2RenderingContext,
+ texture: WebGLTexture,
+ viewportW: number,
+ viewportH: number,
+ softProof?: SoftProofSettings
+ ): void {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+
+ if (softProof && (softProof.enabled || softProof.gamutWarning) && this.softProofProgram) {
+ this.applySoftProofPass(gl, viewportW, viewportH, softProof, texture);
+ return;
+ }
+
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ if (!this.blitProgram) return;
+ gl.disable(gl.BLEND);
+ gl.useProgram(this.blitProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
+ if (this.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.uniform1i(this.uBlitTextureLoc, 0);
+ gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(this.uBlitHasBackdropLoc, 0);
+ gl.uniform1i(this.uBlitBlendModeLoc, 0);
+ gl.uniform1f(this.uBlitOpacityLoc, 1.0);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ this.unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ this.restoreStandardProgram(gl);
+ }
+
/**
- * Main Render Pass: Composite all visible layers onto the viewport canvas.
+ * Main Render Pass: Composite all visible layers onto the viewport canvas using:
+ * 1. Ping-Pong FBOs (zero gl.copyTexSubImage2D calls for all 16 blend modes, adjustments, & soft proof)
+ * 2. Baked Layer Stack Cache (`belowActiveCacheFbo` + `activeUnit` + `aboveActiveCacheFbo`)
+ * 3. TEXTURE_2D_ARRAY + gl.drawArraysInstanced tile batching
*/
public render(
layers: LayerItem[],
@@ -1789,109 +3188,274 @@ export class ViewportCompositor {
this.currentOptions = _options;
this.currentZoom = transform.zoom;
- if (!gl || !this.program) {
+ if (!gl || !this.program || !this.stdLocs) {
this.render2DFallback(layers, transform, dimensions, grid, _options);
return;
}
- const viewportW = this.canvas.width;
- const viewportH = this.canvas.height;
- gl.viewport(0, 0, viewportW, viewportH);
+ const viewportW = Math.max(1, this.canvas.width);
+ const viewportH = Math.max(1, this.canvas.height);
+ const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+ const rotRad = (transform.rotation * Math.PI) / 180;
- // Clear viewport with transparency or dark workspace
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+ this.currentFrameState = {
+ viewportW,
+ viewportH,
+ dpr,
+ dimensions,
+ transform,
+ rotRad,
+ };
- gl.useProgram(this.program);
+ // Calculate Frustum Culling document bounds
+ const viewportCssW = viewportW / dpr;
+ const viewportCssH = viewportH / dpr;
+ const frustum = this.calculateVisibleDocumentBounds(
+ viewportCssW,
+ viewportCssH,
+ transform,
+ dimensions.width,
+ dimensions.height
+ );
- const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+ // Dynamic Frustum Culling & Memory Budget Sync
+ const activeLayerId = _options.activeLayerId ?? _options.activeDraftLayerId ?? null;
+ const layerVis = new Map<string, boolean>();
+ for (const l of layers) {
+ layerVis.set(l.id, l.visible);
+ }
+ grid.getMemoryManager()?.updateViewport(frustum, activeLayerId, layerVis);
- // Set Viewport and Document Uniforms
- gl.uniform2f(this.uViewportSizeLoc, viewportW, viewportH);
- gl.uniform2f(this.uDocDimensionsLoc, dimensions.width, dimensions.height);
- gl.uniform2f(this.uPanLoc, transform.pan.x, transform.pan.y);
- gl.uniform1f(this.uZoomLoc, transform.zoom);
- const rotRad = (transform.rotation * Math.PI) / 180;
- gl.uniform1f(this.uRotationRadLoc, rotRad);
- gl.uniform1f(this.uDprLoc, dpr);
- gl.uniform1i(this.uTileTextureLoc, 0);
- gl.uniform1i(this.uHasBackdropLoc, 0);
+ // Ensure Ping-Pong Scene FBOs & Baked Layer Stack Cache FBOs
+ const scenePP = this.ensurePingPongTarget(gl, this.scenePingPong, viewportW, viewportH);
+ this.scenePingPong = scenePP;
- // Bind Quad Vertices using cached attribute location
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ let belowCacheReady = false;
+ let aboveCacheReady = false;
+ if (scenePP) {
+ if (!this.belowActiveCacheFbo) {
+ this.belowActiveCacheFbo = this.createFboSurface(gl, false);
+ }
+ if (this.belowActiveCacheFbo) {
+ belowCacheReady = this.ensureFboSurfaceSize(gl, this.belowActiveCacheFbo, viewportW, viewportH);
+ }
+ if (!this.aboveActiveCacheFbo) {
+ this.aboveActiveCacheFbo = this.createFboSurface(gl, false);
+ }
+ if (this.aboveActiveCacheFbo) {
+ aboveCacheReady = this.ensureFboSurfaceSize(gl, this.aboveActiveCacheFbo, viewportW, viewportH);
+ }
}
- // 1. Render artboard background pass (paper white or checkerboard)
- gl.blendFunc(gl.ONE, gl.ZERO);
- gl.uniform1i(this.uIsBackgroundLoc, 1);
- gl.uniform1i(this.uExpressionModeLoc, 0);
- gl.uniform1i(this.uShowCheckerboardLoc, _options.showCheckerboard ? 1 : 0);
- gl.uniform2f(this.uTileOriginLoc, 0, 0);
- gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- gl.uniform1i(this.uIsBackgroundLoc, 0);
+ if (scenePP && belowCacheReady && aboveCacheReady && this.belowActiveCacheFbo && this.aboveActiveCacheFbo) {
+ // Evaluate Baked Layer Stack Cache invalidation (below / active / above)
+ const cacheEval = this.stackCache.evaluate({
+ layers,
+ activeLayerId,
+ viewportW,
+ viewportH,
+ dpr,
+ dimensions,
+ transform,
+ showCheckerboard: Boolean(_options.showCheckerboard),
+ onionSkinFrames: _options.onionSkinFrames,
+ getLayerContentVersion: (id) =>
+ typeof grid.getLayerVersion === 'function' ? grid.getLayerVersion(id) : 0,
+ getMaskInvalidationEpoch: (id) => this.maskInvalidationEpochs.get(id) ?? 0,
+ gridEpoch: typeof grid.getGridEpoch === 'function' ? grid.getGridEpoch() : 0,
+ });
+
+ const { partition } = cacheEval;
+ this.restoreStandardProgram(gl);
+ this.syncFrameUniforms(gl, this.stdLocs);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
+
+ // Step 1: Rebuild aboveActiveCacheFbo ONLY when upper slice metadata/content/camera changed
+ if (cacheEval.aboveDirty && partition.aboveCachedUnits.length > 0) {
+ scenePP.activeIndex = 0;
+ const surf = scenePP.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ const overrideRootBlend = partition.aboveStrategy === 'baked-single-blend';
+ for (const unit of partition.aboveCachedUnits) {
+ this.renderCompositingUnit(
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ overrideRootBlend
+ );
+ }
+
+ this.copyFboSurface(
+ gl,
+ scenePP.surfaces[scenePP.activeIndex],
+ this.aboveActiveCacheFbo,
+ viewportW,
+ viewportH,
+ false
+ );
+ this.stackCacheStats.aboveRebuilds++;
+ }
+
+ // Step 2: Populate scenePP with below slice (either rebuild belowActiveCacheFbo or fast GPU blit)
+ if (cacheEval.belowDirty) {
+ scenePP.activeIndex = 0;
+ const surf = scenePP.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, surf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard));
+ this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
+
+ for (const unit of partition.belowUnits) {
+ this.renderCompositingUnit(
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
+
+ this.copyFboSurface(
+ gl,
+ scenePP.surfaces[scenePP.activeIndex],
+ this.belowActiveCacheFbo,
+ viewportW,
+ viewportH,
+ false
+ );
+ // Ensure scenePP's current surface remains bound for activeUnit
+ gl.bindFramebuffer(gl.FRAMEBUFFER, scenePP.surfaces[scenePP.activeIndex].fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ this.stackCacheStats.belowRebuilds++;
+ } else {
+ scenePP.activeIndex = 0;
+ this.copyFboSurface(
+ gl,
+ this.belowActiveCacheFbo,
+ scenePP.surfaces[0],
+ viewportW,
+ viewportH,
+ false
+ );
+ if (!cacheEval.aboveDirty) {
+ this.stackCacheStats.cacheHits++;
+ }
+ }
- // Calculate Frustum Culling document bounds
- const viewportCssW = viewportW / dpr;
- const viewportCssH = viewportH / dpr;
- const frustum = this.calculateVisibleDocumentBounds(
- viewportCssW,
- viewportCssH,
- transform,
- dimensions.width,
- dimensions.height
- );
+ // Step 3: Render active unit (+ live activeDraftCanvas in-stack!)
+ if (partition.activeUnit) {
+ this.renderCompositingUnit(
+ gl,
+ partition.activeUnit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
- gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ // Step 4: Render any dynamic non-associative upper units (via Ping-Pong FBOs, zero copyTexSubImage2D)
+ for (const unit of partition.aboveDynamicUnits) {
+ this.renderCompositingUnit(
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ false
+ );
+ }
- // Dynamic Frustum Culling & Memory Budget Sync
- const layerVis = new Map<string, boolean>();
- for (const l of layers) {
- layerVis.set(l.id, l.visible);
- }
- grid.getMemoryManager()?.updateViewport(frustum, _options.activeDraftLayerId, layerVis);
-
- // 2. Render colored onion skin cels if active in animation mode
- if (_options.onionSkinFrames && _options.onionSkinFrames.length > 0) {
- for (const onion of _options.onionSkinFrames) {
- const targetLayer = layers.find((l) => l.id === onion.layerId);
- if (targetLayer && targetLayer.visible) {
- const virtualOnionLayer: LayerItem = {
- ...targetLayer,
- opacity: onion.opacity,
- layerColorEnabled: true,
- layerColor: onion.tint,
- layerSubColor: '#ffffff',
- blendMode: 'normal',
- };
- this.renderSingleLayer(gl, virtualOnionLayer, dimensions, grid, frustum);
- }
+ // Step 5: Composite baked aboveActiveCacheFbo (1 single quad / 1 ping-pong blend pass)
+ if (partition.aboveCachedUnits.length > 0) {
+ const aboveBlend: BlendMode =
+ partition.aboveStrategy === 'baked-single-blend'
+ ? partition.aboveCacheBlendMode
+ : 'normal';
+ this.blitFolderTexture(
+ gl,
+ this.aboveActiveCacheFbo.texture,
+ aboveBlend,
+ 1.0,
+ viewportW,
+ viewportH,
+ scenePP,
+ false
+ );
}
- }
- // 3. Render layer hierarchy: Folders support 'pass-through' and isolated blend modes
- const tree = buildLayerTree(layers);
- this.renderNodeList(
- gl,
- tree,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- null,
- 0,
- 1.0
- );
+ this.stackCache.commit(cacheEval.belowSignature, cacheEval.aboveSignature);
- // 4. CMYK Soft Proofing and Gamut Warning post-processing pass
- if (_options.softProof && (_options.softProof.enabled || _options.softProof.gamutWarning)) {
- this.applySoftProofPass(gl, viewportW, viewportH, _options.softProof);
+ // Step 6: Present final composited Ping-Pong surface to screen (with optional CMYK soft proofing)
+ this.presentTextureToScreen(
+ gl,
+ scenePP.surfaces[scenePP.activeIndex].texture,
+ viewportW,
+ viewportH,
+ _options.softProof
+ );
+ } else {
+ // Safe fallback when offscreen FBOs are unsupported in a minimal WebGL context
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard));
+ this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, null);
+
+ const tree = buildLayerTree(layers);
+ this.renderNodeList(
+ gl,
+ tree,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ null,
+ 0,
+ 1.0
+ );
}
// Prune mask textures belonging to deleted layers
@@ -1901,22 +3465,24 @@ export class ViewportCompositor {
const entry = this.maskTextureCache.get(cachedLayerId);
if (entry) gl.deleteTexture(entry.texture);
this.maskTextureCache.delete(cachedLayerId);
+ this.maskInvalidationEpochs.delete(cachedLayerId);
}
}
}
- // Clean up stale textures if pool exceeded limit
+ // Clean up stale textures if fallback pool exceeded limit
if (this.texturePool.length > ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
this.evictStaleTextures();
}
}
/**
- * Recursively composite a layer hierarchy, supporting folder pass-through and isolated offscreen rendering.
+ * Renders a single atomic CompositingUnit (an isolated folder, adjustment layer, or base + clipped group)
+ * into the active Ping-Pong target.
*/
- private renderNodeList(
+ private renderCompositingUnit(
gl: WebGL2RenderingContext,
- nodes: LayerTreeNode[],
+ unit: CompositingUnit,
dimensions: CanvasDimensions,
grid: SparseTileGrid,
frustum: { minX: number; minY: number; maxX: number; maxY: number },
@@ -1924,120 +3490,152 @@ export class ViewportCompositor {
viewportH: number,
transform: ViewportTransform,
dpr: number,
- currentFbo: WebGLFramebuffer | null,
+ target: PingPongTarget | null,
depth: number,
- inheritedOpacity: number
+ overrideRootBlendNormal: boolean
): void {
- const siblingsBottomToTop = nodes.slice().reverse();
- const groups = groupTreeNodesForCompositing(siblingsBottomToTop);
+ const group = unit.group;
+ const baseNode = group.baseNode;
+ const baseLayer = overrideRootBlendNormal
+ ? { ...baseNode.layer, blendMode: 'normal' as BlendMode }
+ : baseNode.layer;
- for (const group of groups) {
- const baseNode = group.baseNode;
- const baseLayer = baseNode.layer;
- if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
- continue;
- }
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) {
+ return;
+ }
- if (baseLayer.type === 'folder') {
- const isPassThrough = baseLayer.blendMode === 'pass-through';
- if (isPassThrough) {
- // Pass-through: children blend directly with background layers below using their own individual blend modes
- this.renderNodeList(
- gl,
- baseNode.children,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- currentFbo,
- depth,
- inheritedOpacity * baseLayer.opacity
- );
- } else {
- // Isolated: children render into isolated offscreen texture, then blend with folder's blend mode
- const folderFboItem = this.ensureFolderFbo(depth, viewportW, viewportH);
- if (!folderFboItem) continue;
+ if (baseLayer.type === 'folder') {
+ const folderTarget = this.ensureFolderPingPong(gl, depth, viewportW, viewportH);
+ if (!folderTarget) return;
- gl.bindFramebuffer(gl.FRAMEBUFFER, folderFboItem.fbo);
- gl.viewport(0, 0, viewportW, viewportH);
- gl.clearColor(0.0, 0.0, 0.0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+ folderTarget.activeIndex = 0;
+ const folderSurf = folderTarget.surfaces[0];
+ gl.bindFramebuffer(gl.FRAMEBUFFER, folderSurf.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.disable(gl.STENCIL_TEST);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ this.renderNodeList(
+ gl,
+ baseNode.children,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ folderTarget,
+ depth + 1,
+ 1.0
+ );
- this.renderNodeList(
- gl,
- baseNode.children,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- folderFboItem.fbo,
- depth + 1,
- 1.0
- );
+ // Restore parent target framebuffer and blit isolated folder result
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
- // Restore previous framebuffer and blit isolated folder texture
- gl.bindFramebuffer(gl.FRAMEBUFFER, currentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
+ this.blitFolderTexture(
+ gl,
+ folderTarget.surfaces[folderTarget.activeIndex].texture,
+ baseLayer.blendMode,
+ baseLayer.opacity * unit.inheritedOpacity,
+ viewportW,
+ viewportH,
+ target,
+ false
+ );
+ return;
+ }
- this.blitFolderTexture(
- gl,
- folderFboItem.texture,
- baseLayer.blendMode,
- baseLayer.opacity * inheritedOpacity,
- viewportW,
- viewportH
- );
- }
- continue;
- }
+ const activeClippedLayers = group.clippedNodes
+ .map((n) => n.layer)
+ .filter((cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder');
+
+ const baseEffectiveOpacity = unit.inheritedOpacity;
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ this.renderAdjustmentLayer(
+ gl,
+ baseLayer,
+ transform,
+ dimensions,
+ viewportW,
+ viewportH,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ return;
+ }
- const activeClippedLayers = group.clippedNodes
- .map((n) => n.layer)
- .filter((cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder');
+ const baseHasStyles = hasActiveLayerStyles(baseLayer.styles);
- const baseEffectiveOpacity = inheritedOpacity;
+ if (activeClippedLayers.length > 0) {
+ // Record base layer silhouette in stencil buffer of the current Ping-Pong surface
+ gl.enable(gl.STENCIL_TEST);
+ gl.clear(gl.STENCIL_BUFFER_BIT);
+ gl.stencilMask(0xFF);
+ gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
- if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
- this.renderAdjustmentLayer(
+ if (baseHasStyles) {
+ // Record base layer silhouette in stencil without writing colors
+ gl.colorMask(false, false, false, false);
+ this.renderSingleLayer(
+ gl,
+ { ...baseLayer, blendMode: 'normal' },
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ gl.colorMask(true, true, true, true);
+
+ // Draw base layer with styles (do not overwrite stencil with shadow/glow)
+ gl.stencilMask(0x00);
+ this.renderLayerWithStyles(
gl,
baseLayer,
- transform,
dimensions,
+ grid,
+ frustum,
viewportW,
viewportH,
+ transform,
dpr,
- baseEffectiveOpacity
+ baseEffectiveOpacity,
+ target,
+ true
);
- continue;
- }
-
- const baseHasStyles = hasActiveLayerStyles(baseLayer.styles);
-
- if (activeClippedLayers.length > 0) {
- // Group successive clipped layers: record base silhouette in stencil buffer
- gl.enable(gl.STENCIL_TEST);
- gl.clear(gl.STENCIL_BUFFER_BIT);
gl.stencilMask(0xFF);
- gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
+ } else {
+ this.renderSingleLayer(
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ true
+ );
+ }
- if (baseHasStyles) {
- // Record base layer silhouette in stencil without writing colors to canvas
- gl.colorMask(false, false, false, false);
- this.renderSingleLayer(gl, baseLayer, dimensions, grid, frustum, baseEffectiveOpacity);
- gl.colorMask(true, true, true, true);
+ // Render clipped layers: only draw over opaque pixels of base layer (stencil == 1)
+ gl.stencilMask(0x00);
+ gl.stencilFunc(gl.EQUAL, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
- // Draw base layer with styles (don't overwrite stencil with shadow/glow)
- gl.stencilMask(0x00);
+ for (const clippedLayer of activeClippedLayers) {
+ if (hasActiveLayerStyles(clippedLayer.styles)) {
this.renderLayerWithStyles(
gl,
- baseLayer,
+ clippedLayer,
dimensions,
grid,
frustum,
@@ -2046,59 +3644,90 @@ export class ViewportCompositor {
transform,
dpr,
baseEffectiveOpacity,
- currentFbo
+ target,
+ true
);
- gl.stencilMask(0xFF);
} else {
- this.renderSingleLayer(gl, baseLayer, dimensions, grid, frustum, baseEffectiveOpacity);
- }
-
- // Render clipped layers: only draw over the opaque pixels of the base layer
- gl.stencilMask(0x00);
- gl.stencilFunc(gl.EQUAL, 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
-
- for (const clippedLayer of activeClippedLayers) {
- if (hasActiveLayerStyles(clippedLayer.styles)) {
- this.renderLayerWithStyles(
- gl,
- clippedLayer,
- dimensions,
- grid,
- frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
- baseEffectiveOpacity,
- currentFbo
- );
- } else {
- this.renderSingleLayer(gl, clippedLayer, dimensions, grid, frustum, baseEffectiveOpacity);
- }
- }
-
- gl.disable(gl.STENCIL_TEST);
- } else {
- gl.disable(gl.STENCIL_TEST);
- if (baseHasStyles) {
- this.renderLayerWithStyles(
+ this.renderSingleLayer(
gl,
- baseLayer,
+ clippedLayer,
dimensions,
grid,
frustum,
- viewportW,
- viewportH,
- transform,
- dpr,
baseEffectiveOpacity,
- currentFbo
+ target,
+ true
);
- } else {
- this.renderSingleLayer(gl, baseLayer, dimensions, grid, frustum, baseEffectiveOpacity);
}
}
+
+ gl.stencilMask(0xFF);
+ gl.disable(gl.STENCIL_TEST);
+ } else {
+ gl.disable(gl.STENCIL_TEST);
+ if (baseHasStyles) {
+ this.renderLayerWithStyles(
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ } else {
+ this.renderSingleLayer(
+ gl,
+ baseLayer,
+ dimensions,
+ grid,
+ frustum,
+ baseEffectiveOpacity,
+ target,
+ false
+ );
+ }
+ }
+ }
+
+ /**
+ * Recursively composite a layer hierarchy, supporting folder pass-through and isolated offscreen rendering.
+ */
+ private renderNodeList(
+ gl: WebGL2RenderingContext,
+ nodes: LayerTreeNode[],
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: { minX: number; minY: number; maxX: number; maxY: number },
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ dpr: number,
+ target: PingPongTarget | null,
+ depth: number,
+ inheritedOpacity: number
+ ): void {
+ const units = flattenLayerTreeToUnits(nodes, inheritedOpacity);
+ for (const unit of units) {
+ this.renderCompositingUnit(
+ gl,
+ unit,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ target,
+ depth,
+ false
+ );
}
}
@@ -2146,7 +3775,7 @@ export class ViewportCompositor {
}
/**
- * Evaluates non-destructive adjustment layers via GPU snapshot and version-cached LUT evaluation.
+ * Evaluates non-destructive adjustment layers via Ping-Pong FBO backdrop and version-cached LUT evaluation.
*/
private renderAdjustmentLayer(
gl: WebGL2RenderingContext,
@@ -2156,12 +3785,14 @@ export class ViewportCompositor {
viewportW: number,
viewportH: number,
dpr: number,
- opacityMultiplier: number = 1.0
+ opacityMultiplier: number = 1.0,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
): void {
- if (!this.adjProgram || !layer.adjustmentData) return;
+ if (!this.adjProgram || !layer.adjustmentData || !target) return;
- // 1. Snapshot lower composite
- this.ensureBackdropSnapshot(gl, viewportW, viewportH);
+ // 1. Ping-Pong swap to sample accumulated backdrop texture without copyTexSubImage2D
+ const backdropTex = this.prepareBackdropFromPingPong(gl, target, viewportW, viewportH, preserveStencil);
// 2. Prepare 256x1 LUT (Cached by AdjustmentLayerData signature)
if (!this.lutTexture) {
@@ -2200,7 +3831,7 @@ export class ViewportCompositor {
lutData[off + 2] = ch === 'rgb' || ch === 'b' ? lLut[i] : i;
lutData[off + 3] = 255;
}
- } else { // color-balance
+ } else {
lutData = new Uint8Array(256 * 4);
for (let i = 0; i < 256; i++) {
const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
@@ -2218,6 +3849,7 @@ export class ViewportCompositor {
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, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
this.lastLutKey = lutKey;
@@ -2226,131 +3858,77 @@ export class ViewportCompositor {
// 3. Switch to Adjustment Program
gl.useProgram(this.adjProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
- // Uniforms
gl.uniform2f(this.uAdjViewportSizeLoc, viewportW, viewportH);
gl.uniform2f(this.uAdjDocDimensionsLoc, dimensions.width, dimensions.height);
gl.uniform2f(this.uAdjPanLoc, transform.pan.x, transform.pan.y);
gl.uniform1f(this.uAdjZoomLoc, transform.zoom);
const rotRad = (transform.rotation * Math.PI) / 180;
gl.uniform1f(this.uAdjRotationRadLoc, rotRad);
+ gl.uniform2f(this.uAdjFlipLoc, transform.flipX ? -1.0 : 1.0, transform.flipY ? -1.0 : 1.0);
gl.uniform1f(this.uAdjDprLoc, dpr);
gl.uniform2f(this.uAdjTileOriginLoc, 0, 0);
gl.uniform2f(this.uAdjTileSizeLoc, dimensions.width, dimensions.height);
gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
gl.uniform1i(this.uAdjSnapshotLoc, 2);
- gl.activeTexture(gl.TEXTURE3);
- gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
- gl.uniform1i(this.uAdjLutLoc, 3);
-
- gl.uniform1i(this.uAdjModeLoc, this.lastLutAdjMode);
- gl.uniform1f(this.uAdjOpacityLoc, layer.opacity * opacityMultiplier);
-
- // Mask for adjustment layer
- const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
- gl.uniform1i(this.uAdjMaskEnabledLoc, hasMask ? 1 : 0);
- if (hasMask && layer.maskCanvas) {
- const maskTex = this.getMaskTexture(layer);
- if (maskTex) {
- gl.activeTexture(gl.TEXTURE1);
- gl.bindTexture(gl.TEXTURE_2D, maskTex);
- gl.uniform1i(this.uAdjMaskTextureLoc, 1);
- }
- }
-
- // Blend: overwrite lower composite with filtered result
- gl.blendFunc(gl.ONE, gl.ZERO);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
-
- // Revert program and blend func
- gl.useProgram(this.program);
- gl.enable(gl.BLEND);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- }
-
- /**
- * 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,
- layer: LayerItem,
- dimensions: CanvasDimensions,
- grid: SparseTileGrid,
- frustum: { minX: number; minY: number; maxX: number; maxY: number },
- opacityMultiplier: number = 1.0
- ): void {
- // Configure Layer Blend Mode & Opacity
- this.setGLBlendMode(layer.blendMode);
- gl.uniform1f(this.uLayerOpacityLoc, layer.opacity * opacityMultiplier);
- gl.uniform1i(this.uBlendModeLoc, BLEND_MODE_MAP[layer.blendMode] ?? 0);
-
- // Configure Expression Color Uniforms
- const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
- const exprMode = isBgLayer
- ? 0
- : layer.expressionColor === 'monochrome'
- ? 2
- : layer.expressionColor === 'gray'
- ? 1
- : 0;
- gl.uniform1i(this.uExpressionModeLoc, exprMode);
- if (exprMode === 2) {
- gl.uniform1f(this.uMonoThresholdLoc, (layer.monoThreshold ?? 128) / 255.0);
- gl.uniform1i(this.uMonoExpressBlackLoc, layer.monoExpressBlack !== false ? 1 : 0);
- gl.uniform1i(this.uMonoExpressWhiteLoc, layer.monoExpressWhite !== false ? 1 : 0);
- }
-
- // Configure Screentone Uniforms
- const toneEnabled = Boolean(layer.toneEnabled);
- gl.uniform1i(this.uToneEnabledLoc, toneEnabled ? 1 : 0);
- if (toneEnabled) {
- gl.uniform1f(this.uToneFrequencyLoc, layer.toneFrequency || 60);
- gl.uniform1f(this.uToneAngleRadLoc, ((layer.toneAngle || 45) * Math.PI) / 180);
- gl.uniform1f(this.uToneDpiLoc, dimensions.dpi || 600);
- const dotShapeCode =
- layer.toneDotShape === 'line'
- ? 2
- : layer.toneDotShape === 'diamond'
- ? 3
- : layer.toneDotShape === 'euclidean'
- ? 1
- : 0;
- gl.uniform1i(this.uToneDotShapeLoc, dotShapeCode);
- gl.uniform1f(this.uToneDensityLoc, (layer.toneDensity ?? 40) / 100);
- gl.uniform1i(this.uToneDensityTypeLoc, layer.toneDensityType === 'image' ? 1 : 0);
- }
-
- // Configure Layer Tint Uniforms
- const tintEnabled = Boolean(layer.layerColorEnabled);
- gl.uniform1i(this.uLayerColorEnabledLoc, tintEnabled ? 1 : 0);
- if (tintEnabled) {
- const prim = this.parseHexColor(layer.layerColor || '#1c73c2');
- const sub = this.parseHexColor(layer.layerSubColor || '#ffffff');
- gl.uniform3f(this.uLayerColorLoc, prim[0], prim[1], prim[2]);
- gl.uniform3f(this.uLayerSubColorLoc, sub[0], sub[1], sub[2]);
- }
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
+ gl.uniform1i(this.uAdjLutLoc, 3);
+
+ gl.uniform1i(this.uAdjModeLoc, this.lastLutAdjMode);
+ gl.uniform1f(this.uAdjOpacityLoc, layer.opacity * opacityMultiplier);
- // Configure Layer Mask
const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
- gl.uniform1i(this.uMaskEnabledLoc, hasMask ? 1 : 0);
+ gl.uniform1i(this.uAdjMaskEnabledLoc, hasMask ? 1 : 0);
if (hasMask && layer.maskCanvas) {
const maskTex = this.getMaskTexture(layer);
if (maskTex) {
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, maskTex);
- gl.uniform1i(this.uMaskTextureLoc, 1);
- } else {
- gl.uniform1i(this.uMaskEnabledLoc, 0);
+ gl.uniform1i(this.uAdjMaskTextureLoc, 1);
}
}
- // Adaptive LOD Selection & Frustum Culling:
- // Select LOD 1 when zoom <= 50%, LOD 2 when zoom <= 25%, LOD 3 when zoom <= 12.5%
+ // Overwrite document region with filtered result
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // Revert program, unbind backdrop texture to avoid feedback loops, and restore blend func
+ this.unbindSceneTextureUnits(gl);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ this.restoreStandardProgram(gl);
+ }
+
+ /**
+ * Renders all visible tiles of a single layer onto WebGL2 context using:
+ * - TEXTURE_2D_ARRAY + gl.drawArraysInstanced batching when all visible tiles fit in the pool
+ * - Safe per-tile TEXTURE_2D fallback on pool overflow
+ * - Ping-Pong FBO backdrop sampling for custom blend modes (zero gl.copyTexSubImage2D)
+ * - In-stack WYSIWYG live draft stroke compositing
+ */
+ private renderSingleLayer(
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: { minX: number; minY: number; maxX: number; maxY: number },
+ opacityMultiplier: number = 1.0,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
+ ): void {
+ if (!this.stdLocs) return;
+
+ // Adaptive LOD Selection & Frustum Culling
const targetLod =
this.currentZoom <= 0.125 ? 3 :
this.currentZoom <= 0.25 ? 2 :
@@ -2359,7 +3937,6 @@ export class ViewportCompositor {
const lodScale = 1 << targetLod;
const lodTileDocSize = TILE_SIZE * lodScale;
- // Convert screen viewport bounding box in canvas coordinates to intersecting tile ranges
const startTileX = Math.floor(frustum.minX / lodTileDocSize);
const endTileX = Math.floor(frustum.maxX / lodTileDocSize);
const startTileY = Math.floor(frustum.minY / lodTileDocSize);
@@ -2378,45 +3955,338 @@ export class ViewportCompositor {
}
}
+ const opts = this.currentOptions;
+ const draftCanvas = opts?.activeDraftLayerId === layer.id ? opts.activeDraftCanvas : null;
+ const hasDraft = Boolean(
+ draftCanvas &&
+ draftCanvas.width > 0 &&
+ draftCanvas.height > 0 &&
+ (draftCanvas as any).__draftHasContent !== false
+ );
+ const draftOp = hasDraft && draftCanvas
+ ? ((draftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
+ : undefined;
+ const needsIsolatedDraftFbo =
+ hasDraft &&
+ draftCanvas !== null &&
+ (draftOp === 'destination-out' || draftOp === 'source-atop');
+
+ if (visibleTiles.length === 0 && !hasDraft) {
+ return;
+ }
+
+ const fs = this.currentFrameState;
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ const maskTex = hasMask && layer.maskCanvas ? this.getMaskTexture(layer) : null;
+ const effectiveOpacity = layer.opacity * opacityMultiplier;
+
+ // Isolated GPU FBO path for WYSIWYG live Eraser (destination-out) and Alpha Lock (source-atop)
+ // Erases/paints strictly against this layer's tiles without affecting underlying layers and with zero getImageData!
+ if (
+ needsIsolatedDraftFbo &&
+ draftCanvas &&
+ target &&
+ fs &&
+ fs.viewportW > 0 &&
+ fs.viewportH > 0 &&
+ this.ensureLayerFbo(fs.viewportW, fs.viewportH) &&
+ this.layerFbo &&
+ this.layerTexture &&
+ this.blitProgram
+ ) {
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
+ gl.viewport(0, 0, fs.viewportW, fs.viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ if (visibleTiles.length > 0) {
+ this.drawTilesFallback2D(
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ 1.0,
+ 0,
+ null,
+ maskTex
+ );
+ }
+
+ if (draftOp === 'destination-out') {
+ gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
+ } else {
+ gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ this.renderActiveDraftForLayer(
+ gl,
+ draftCanvas,
+ layer,
+ dimensions,
+ opts?.activeDraftOpacity ?? 1.0,
+ 0,
+ null,
+ maskTex,
+ opts?.activeDraftVersion,
+ opts?.activeDraftSpace ?? 'document'
+ );
+
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target.surfaces[target.activeIndex].fbo);
+ gl.viewport(0, 0, fs.viewportW, fs.viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+
+ this.blitFolderTexture(
+ gl,
+ this.layerTexture,
+ layer.blendMode,
+ effectiveOpacity,
+ fs.viewportW,
+ fs.viewportH,
+ target,
+ preserveStencil
+ );
+
+ if (this.stdLocs) {
+ if (maskTex) {
+ gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
+ }
+ gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
+ }
+ this.unbindSceneTextureUnits(gl);
+ return;
+ }
+
+ // Prepare Ping-Pong backdrop if custom blend mode is active (zero copyTexSubImage2D)
+ const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
+ let backdropTex: WebGLTexture | null = null;
+ if (modeCode !== 0 && modeCode !== 12 && target && fs && fs.viewportW > 0 && fs.viewportH > 0) {
+ backdropTex = this.prepareBackdropFromPingPong(
+ gl,
+ target,
+ fs.viewportW,
+ fs.viewportH,
+ preserveStencil
+ );
+ }
+
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ // Batched TEXTURE_2D_ARRAY + gl.drawArraysInstanced fast path when all visible tiles fit in pool
+ const canBatch =
+ visibleTiles.length > 0 &&
+ this.instancedProgram !== null &&
+ this.instancedLocs !== null &&
+ this.tileArrayTexture !== null &&
+ this.instanceBuffer !== null &&
+ visibleTiles.length <= this.arrayPoolCapacity;
+
+ if (canBatch && this.instancedProgram && this.instancedLocs && this.tileArrayTexture && this.instanceBuffer) {
+ const batchTick = ++this.arrayBatchCounter;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tileArrayTexture);
+
+ // Adaptive filter mode for the entire array texture
+ const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
+ if (this.arrayPoolFilterTier !== desiredTier) {
+ const filter = desiredTier <= 1 ? gl.LINEAR : gl.NEAREST;
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, filter);
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, filter);
+ this.arrayPoolFilterTier = desiredTier;
+ }
+
+ let instanceCount = 0;
+ let overflowed = false;
+ for (let i = 0; i < visibleTiles.length; i++) {
+ const tile = visibleTiles[i];
+ const sliceIdx = this.getOrUploadArrayTileSlice(gl, tile, grid, batchTick);
+ if (sliceIdx < 0) {
+ overflowed = true;
+ break;
+ }
+ const off = instanceCount * 3;
+ this.instanceFloatScratch[off] = tile.tileX * lodTileDocSize;
+ this.instanceFloatScratch[off + 1] = tile.tileY * lodTileDocSize;
+ this.instanceFloatScratch[off + 2] = sliceIdx;
+ instanceCount++;
+ }
+
+ if (!overflowed && instanceCount > 0) {
+ gl.useProgram(this.instancedProgram);
+ this.syncFrameUniforms(gl, this.instancedLocs);
+ gl.uniform2f(this.uInstTileSizeLoc, lodTileDocSize, lodTileDocSize);
+ gl.uniform1i(this.uInstTileArrayLoc, 0);
+ this.applyLayerUniforms(
+ gl,
+ this.instancedLocs,
+ layer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tileArrayTexture);
+
+ if (this.instancedVao) {
+ gl.bindVertexArray(this.instancedVao);
+ } else {
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ if (this.aInstQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aInstQuadPosLoc);
+ gl.vertexAttribPointer(this.aInstQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(this.aInstQuadPosLoc, 0);
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
+ if (this.aInstDataLoc >= 0) {
+ gl.enableVertexAttribArray(this.aInstDataLoc);
+ gl.vertexAttribPointer(this.aInstDataLoc, 3, gl.FLOAT, false, 0, 0);
+ gl.vertexAttribDivisor(this.aInstDataLoc, 1);
+ }
+ }
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.instanceFloatScratch.subarray(0, instanceCount * 3));
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, instanceCount);
+
+ if (this.instancedVao) {
+ gl.bindVertexArray(null);
+ } else if (this.aInstDataLoc >= 0) {
+ gl.vertexAttribDivisor(this.aInstDataLoc, 0);
+ gl.disableVertexAttribArray(this.aInstDataLoc);
+ }
+ this.restoreStandardProgram(gl);
+ } else if (overflowed) {
+ this.drawTilesFallback2D(
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ }
+ } else if (visibleTiles.length > 0) {
+ // Safe fallback to per-tile TEXTURE_2D pool on overflow or missing WebGL2 array APIs
+ this.drawTilesFallback2D(
+ gl,
+ visibleTiles,
+ grid,
+ layer,
+ dimensions,
+ lodTileDocSize,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ }
+
+ // WYSIWYG In-Stack Live Stroke Compositing
+ if (hasDraft && draftCanvas) {
+ if (draftOp === 'destination-out') {
+ gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
+ } else if (draftOp === 'source-atop') {
+ gl.blendFunc(gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ this.renderActiveDraftForLayer(
+ gl,
+ draftCanvas,
+ layer,
+ dimensions,
+ effectiveOpacity * (opts?.activeDraftOpacity ?? 1.0),
+ modeCode,
+ backdropTex,
+ maskTex,
+ opts?.activeDraftVersion,
+ opts?.activeDraftSpace ?? 'document'
+ );
+ if (draftOp === 'destination-out' || draftOp === 'source-atop') {
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ }
+
+ if (this.stdLocs) {
+ if (maskTex) {
+ gl.uniform1i(this.stdLocs.uMaskEnabled, 0);
+ }
+ gl.uniform1i(this.stdLocs.uHasBackdrop, 0);
+ }
+ this.unbindSceneTextureUnits(gl);
+ }
+
+ /**
+ * Fallback per-tile TEXTURE_2D draw loop when visible tile count exceeds TEXTURE_2D_ARRAY pool capacity.
+ */
+ private drawTilesFallback2D(
+ gl: WebGL2RenderingContext,
+ visibleTiles: TileBuffer[],
+ grid: SparseTileGrid,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ lodTileDocSize: number,
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null
+ ): void {
+ if (!this.stdLocs) return;
+ this.restoreStandardProgram(gl);
+ this.syncFrameUniforms(gl, this.stdLocs);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.uIsBackgroundLoc, 0);
+ this.applyLayerUniforms(
+ gl,
+ this.stdLocs,
+ layer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
gl.uniform2f(this.uTileSizeLoc, lodTileDocSize, lodTileDocSize);
- // Draw each visible intersecting tile with 1 draw call per tile
for (const tile of visibleTiles) {
const tex = this.getTileTexture(tile, grid);
if (!tex) continue;
-
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex);
-
gl.uniform2f(this.uTileOriginLoc, tile.tileX * lodTileDocSize, tile.tileY * lodTileDocSize);
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.
+ * Supports both viewport-space overlays (from CanvasArea) and document-space draft canvases.
*/
private renderActiveDraftForLayer(
gl: WebGL2RenderingContext,
draftCanvas: HTMLCanvasElement,
+ layer: LayerItem,
dimensions: CanvasDimensions,
- draftVersion?: number
+ effectiveOpacity: number,
+ modeCode: number,
+ backdropTex: WebGLTexture | null,
+ maskTex: WebGLTexture | null,
+ draftVersion?: number,
+ draftSpace: 'document' | 'viewport' = 'document'
): void {
if (draftCanvas.width <= 0 || draftCanvas.height <= 0) return;
+ if ((draftCanvas as any).__draftHasContent === false) return;
if (!this.draftTexture) {
this.draftTexture = gl.createTexture();
}
@@ -2426,6 +4296,7 @@ export class ViewportCompositor {
gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
const ver = draftVersion ?? -1;
+ const hasGenerateMipmap = typeof gl.generateMipmap === 'function';
if (
ver === -1 ||
ver !== this.lastDraftVersion ||
@@ -2434,19 +4305,80 @@ export class ViewportCompositor {
) {
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.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ hasGenerateMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ );
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ if (hasGenerateMipmap) {
+ gl.generateMipmap(gl.TEXTURE_2D);
+ }
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);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
+
+ const effectiveDraftLayer: LayerItem =
+ this.currentOptions?.activeDraftMonochrome && layer.expressionColor !== 'monochrome'
+ ? { ...layer, expressionColor: 'monochrome' }
+ : layer;
+
+ if (draftSpace === 'viewport' && this.viewportDraftProgram && this.viewportDraftLocs) {
+ gl.useProgram(this.viewportDraftProgram);
+ this.syncFrameUniforms(gl, this.viewportDraftLocs);
+ gl.uniform1i(this.uViewportDraftTileTexLoc, 0);
+ gl.uniform1i(this.uViewportDraftIsBgLoc, 0);
+ this.applyLayerUniforms(
+ gl,
+ this.viewportDraftLocs,
+ effectiveDraftLayer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ if (this.aViewportDraftQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aViewportDraftQuadPosLoc);
+ gl.vertexAttribPointer(this.aViewportDraftQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ this.restoreStandardProgram(gl);
+ } else if (this.stdLocs) {
+ const docRect = this.currentOptions?.activeDraftDirtyRect;
+ const originX = docRect ? docRect.x : 0;
+ const originY = docRect ? docRect.y : 0;
+ const spanW = docRect ? docRect.width : dimensions.width;
+ const spanH = docRect ? docRect.height : dimensions.height;
+
+ this.restoreStandardProgram(gl);
+ this.syncFrameUniforms(gl, this.stdLocs);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.uIsBackgroundLoc, 0);
+ this.applyLayerUniforms(
+ gl,
+ this.stdLocs,
+ effectiveDraftLayer,
+ dimensions,
+ effectiveOpacity,
+ modeCode,
+ backdropTex,
+ maskTex
+ );
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
+ gl.uniform2f(this.uTileOriginLoc, originX, originY);
+ gl.uniform2f(this.uTileSizeLoc, spanW, spanH);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ }
}
/**
@@ -2477,6 +4409,7 @@ export class ViewportCompositor {
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, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
@@ -2494,58 +4427,8 @@ export class ViewportCompositor {
}
/**
- * Ensures an offscreen framebuffer and texture exist for isolated folder compositing.
- */
- private ensureFolderFbo(depth: number, width: number, height: number): { fbo: WebGLFramebuffer; texture: WebGLTexture } | null {
- if (!this.gl) return null;
- const gl = this.gl;
-
- while (this.folderFbos.length <= depth) {
- const fbo = gl.createFramebuffer();
- const texture = gl.createTexture();
- const stencilRb = typeof gl.createRenderbuffer === 'function' ? gl.createRenderbuffer() : null;
- if (!fbo || !texture) return null;
- this.folderFbos.push({ fbo, texture, stencilRb, width: 0, height: 0 });
- }
-
- const item = this.folderFbos[depth];
- if (item.width !== width || item.height !== height) {
- const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
-
- gl.bindTexture(gl.TEXTURE_2D, item.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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, item.fbo);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, item.texture, 0);
-
- if (item.stencilRb && typeof gl.bindRenderbuffer === 'function') {
- gl.bindRenderbuffer(gl.RENDERBUFFER, item.stencilRb);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, item.stencilRb);
- }
-
- const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
-
- if (status !== gl.FRAMEBUFFER_COMPLETE) {
- console.error('Folder FBO incomplete:', status);
- return null;
- }
-
- item.width = width;
- item.height = height;
- }
-
- return item;
- }
-
- /**
- * Blits an isolated folder offscreen texture back to the current framebuffer
- * with the folder's blend mode and opacity.
+ * Blits an isolated folder or baked cache texture onto the active Ping-Pong target
+ * with full programmable blend mode support and zero gl.copyTexSubImage2D calls.
*/
private blitFolderTexture(
gl: WebGL2RenderingContext,
@@ -2553,26 +4436,32 @@ export class ViewportCompositor {
blendMode: BlendMode,
opacity: number,
viewportW: number,
- viewportH: number
+ viewportH: number,
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
): void {
if (!this.blitProgram) return;
- gl.viewport(0, 0, viewportW, viewportH);
- 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;
- }
+ if (modeCode !== 0 && modeCode !== 12 && target && viewportW > 0 && viewportH > 0) {
+ const backdropTex = this.prepareBackdropFromPingPong(
+ gl,
+ target,
+ viewportW,
+ viewportH,
+ preserveStencil
+ );
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ hasBackdrop = 1;
}
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
gl.useProgram(this.blitProgram);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer || this.quadBuffer);
if (this.aBlitQuadPosLoc >= 0) {
gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
@@ -2588,50 +4477,25 @@ export class ViewportCompositor {
gl.drawArrays(gl.TRIANGLES, 0, 6);
- // Restore standard program and quad buffer
- if (this.program) {
- gl.useProgram(this.program);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- }
+ this.unbindSceneTextureUnits(gl);
+ this.restoreStandardProgram(gl);
}
/**
* Post-processing pass: CMYK Soft Proofing and Gamut Warning.
+ * Samples directly from the Ping-Pong scene FBO texture into the default framebuffer (zero copyTexSubImage2D).
*/
private applySoftProofPass(
gl: WebGL2RenderingContext,
viewportW: number,
viewportH: number,
- settings: SoftProofSettings
+ settings: SoftProofSettings,
+ sceneTexture: WebGLTexture
): void {
if (!this.softProofProgram) return;
- // 1. Prepare snapshot texture for current viewport
- if (!this.proofSnapshotTexture || this.proofSnapshotWidth !== viewportW || this.proofSnapshotHeight !== viewportH) {
- if (this.proofSnapshotTexture) gl.deleteTexture(this.proofSnapshotTexture);
- this.proofSnapshotTexture = gl.createTexture();
- this.proofSnapshotWidth = viewportW;
- this.proofSnapshotHeight = viewportH;
- gl.bindTexture(gl.TEXTURE_2D, this.proofSnapshotTexture);
- 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);
- }
-
- // 2. Snapshot rendered viewport backbuffer into texture
- gl.bindTexture(gl.TEXTURE_2D, this.proofSnapshotTexture);
- gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, viewportW, viewportH);
-
- // 3. Switch to Soft Proof Post-Processing Program
gl.useProgram(this.softProofProgram);
- // 4. Set uniforms
const standardIndex = settings.standard === 'japan-color-2001' ? 0 : settings.standard === 'us-web-coated-swop' ? 1 : 2;
gl.uniform1i(this.uProofStandardLoc, standardIndex);
gl.uniform1i(this.uProofEnabledLoc, settings.enabled ? 1 : 0);
@@ -2641,10 +4505,9 @@ export class ViewportCompositor {
gl.uniform3f(this.uProofGamutWarningColorLoc, warnRgb[0], warnRgb[1], warnRgb[2]);
gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, this.proofSnapshotTexture);
+ gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
gl.uniform1i(this.uProofSceneTextureLoc, 0);
- // 5. Draw fullscreen quad to replace backbuffer with proofed output
gl.disable(gl.STENCIL_TEST);
gl.disable(gl.BLEND);
@@ -2660,16 +4523,10 @@ export class ViewportCompositor {
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
- // 6. Reset state back to compositor defaults
+ this.unbindSceneTextureUnits(gl);
gl.enable(gl.BLEND);
- if (this.program) {
- gl.useProgram(this.program);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
- }
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ this.restoreStandardProgram(gl);
}
/**
@@ -2687,16 +4544,17 @@ export class ViewportCompositor {
transform: ViewportTransform,
dpr: number,
opacityMultiplier: number = 1.0,
- currentFbo: WebGLFramebuffer | null = null
+ target: PingPongTarget | null = null,
+ preserveStencil: boolean = false
): void {
if (!this.ensureLayerFbo(viewportW, viewportH) || !this.stylesProgram) {
- this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier);
+ this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
return;
}
const styles = layer.styles;
if (!styles) {
- this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier);
+ this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier, target, preserveStencil);
return;
}
@@ -2719,22 +4577,47 @@ export class ViewportCompositor {
};
// 1. Render layer into isolated FBO with opacity 1.0 (opacity is modulated by stylesProgram)
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+
gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerFbo);
gl.viewport(0, 0, viewportW, viewportH);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
const virtualLayer: LayerItem = { ...layer, opacity: 1.0, blendMode: 'normal' };
- this.renderSingleLayer(gl, virtualLayer, dimensions, grid, expandedFrustum, 1.0);
+ this.renderSingleLayer(gl, virtualLayer, dimensions, grid, expandedFrustum, 1.0, null, false);
- // 2. Restore active target framebuffer (folder FBO or default screen canvas)
- gl.bindFramebuffer(gl.FRAMEBUFFER, currentFbo);
- gl.viewport(0, 0, viewportW, viewportH);
+ // 2. Determine whether custom blend mode requires routing styled output through Ping-Pong blit
+ const modeCode = BLEND_MODE_MAP[layer.blendMode] ?? 0;
+ const needsCustomBlend = modeCode !== 0 && modeCode !== 12 && target !== null;
- // 3. Set layer blend mode
- this.setGLBlendMode(layer.blendMode);
+ if (needsCustomBlend) {
+ if (!this.layerStylesOutFbo) {
+ this.layerStylesOutFbo = this.createFboSurface(gl, false);
+ }
+ if (this.layerStylesOutFbo && this.ensureFboSurfaceSize(gl, this.layerStylesOutFbo, viewportW, viewportH)) {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.layerStylesOutFbo.fbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ } else {
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+ } else {
+ const parentFbo = target ? target.surfaces[target.activeIndex].fbo : null;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
- // 4. Activate styles program and bind uniforms
+ // 3. Activate styles program and bind uniforms
gl.useProgram(this.stylesProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
@@ -2750,7 +4633,6 @@ export class ViewportCompositor {
gl.uniform2f(this.uStylesViewportSizeLoc, viewportW, viewportH);
gl.uniform1f(this.uStylesLayerOpacityLoc, layer.opacity * opacityMultiplier);
- // Stroke uniforms
const stroke = styles.stroke;
const strokeActive = Boolean(stroke?.enabled && stroke.size > 0 && stroke.opacity > 0);
gl.uniform1i(this.uStylesStrokeEnabledLoc, strokeActive ? 1 : 0);
@@ -2763,7 +4645,6 @@ export class ViewportCompositor {
gl.uniform1i(this.uStylesStrokePositionLoc, posCode);
}
- // Outer Glow uniforms
const glow = styles.outerGlow;
const glowActive = Boolean(glow?.enabled && glow.opacity > 0 && glow.blur > 0);
gl.uniform1i(this.uStylesGlowEnabledLoc, glowActive ? 1 : 0);
@@ -2775,15 +4656,14 @@ export class ViewportCompositor {
gl.uniform1f(this.uStylesGlowSpreadLoc, (glow.spread || 0) / 100);
}
- // Drop Shadow uniforms
const shadow = styles.dropShadow;
const shadowActive = Boolean(shadow?.enabled && shadow.opacity > 0);
gl.uniform1i(this.uStylesShadowEnabledLoc, shadowActive ? 1 : 0);
if (shadowActive && shadow) {
const rad = ((shadow.angle || 0) * Math.PI) / 180;
const distPx = (shadow.distance || 0) * transform.zoom * dpr;
- const dx = Math.cos(rad) * distPx;
- const dy = Math.sin(rad) * distPx;
+ const dx = Math.cos(rad) * distPx * (transform.flipX ? -1 : 1);
+ const dy = Math.sin(rad) * distPx * (transform.flipY ? -1 : 1);
gl.uniform2f(this.uStylesShadowOffsetLoc, dx, -dy);
const shadowBlurPx = (shadow.blur || 0) * transform.zoom * dpr;
gl.uniform1f(this.uStylesShadowBlurLoc, shadowBlurPx);
@@ -2792,18 +4672,31 @@ export class ViewportCompositor {
gl.uniform1f(this.uStylesShadowSpreadLoc, (shadow.spread || 0) / 100);
}
- // 5. Draw fullscreen quad
+ // 4. Draw fullscreen quad
gl.drawArrays(gl.TRIANGLES, 0, 6);
- // 6. Restore standard program and quad buffer
- if (this.program) {
- gl.useProgram(this.program);
- gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- if (this.aQuadPosLoc >= 0) {
- gl.enableVertexAttribArray(this.aQuadPosLoc);
- gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
- }
+ // 5. If custom blend mode was routed to layerStylesOutFbo, composite onto parent Ping-Pong target
+ if (needsCustomBlend && this.layerStylesOutFbo && target) {
+ const parentFbo = target.surfaces[target.activeIndex].fbo;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, parentFbo);
+ gl.viewport(0, 0, viewportW, viewportH);
+ if (stencilWasEnabled) gl.enable(gl.STENCIL_TEST);
+ this.blitFolderTexture(
+ gl,
+ this.layerStylesOutFbo.texture,
+ layer.blendMode,
+ 1.0,
+ viewportW,
+ viewportH,
+ target,
+ preserveStencil
+ );
+ return;
}
+
+ // 6. Restore standard program and quad buffer
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ this.restoreStandardProgram(gl);
}
@@ -2893,13 +4786,86 @@ export class ViewportCompositor {
targetCtx.restore();
}
+ // WYSIWYG 2D fallback in-stack live draft compositing
+ const opts = this.currentOptions;
+ const has2DDraft = Boolean(
+ opts?.activeDraftLayerId === layer.id &&
+ opts.activeDraftCanvas &&
+ (opts.activeDraftCanvas as any).__draftHasContent !== false
+ );
+ const draftOp2D = has2DDraft && opts?.activeDraftCanvas
+ ? ((opts.activeDraftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
+ : undefined;
+
+ if (
+ has2DDraft &&
+ opts?.activeDraftCanvas &&
+ (draftOp2D === 'destination-out' || draftOp2D === 'source-atop') &&
+ typeof document !== 'undefined' &&
+ targetCtx.canvas
+ ) {
+ const iso = document.createElement('canvas');
+ iso.width = targetCtx.canvas.width;
+ iso.height = targetCtx.canvas.height;
+ const isoCtx = iso.getContext('2d');
+ if (isoCtx) {
+ if (typeof targetCtx.getTransform === 'function' && typeof isoCtx.setTransform === 'function') {
+ isoCtx.setTransform(targetCtx.getTransform());
+ }
+ drawTiles(isoCtx);
+ isoCtx.save();
+ isoCtx.globalAlpha = opts.activeDraftOpacity ?? 1.0;
+ isoCtx.globalCompositeOperation = draftOp2D;
+ if (opts.activeDraftSpace === 'viewport' && typeof isoCtx.setTransform === 'function') {
+ isoCtx.setTransform(1, 0, 0, 1, 0, 0);
+ isoCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ } else if (opts.activeDraftDirtyRect) {
+ const dr = opts.activeDraftDirtyRect;
+ isoCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
+ } else {
+ isoCtx.drawImage(
+ opts.activeDraftCanvas,
+ 0,
+ 0,
+ opts.dimensions?.width ?? opts.activeDraftCanvas.width,
+ opts.dimensions?.height ?? opts.activeDraftCanvas.height
+ );
+ }
+ isoCtx.restore();
+
+ targetCtx.save();
+ if (typeof targetCtx.setTransform === 'function') {
+ targetCtx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+ targetCtx.drawImage(iso, 0, 0);
+ targetCtx.restore();
+ targetCtx.restore();
+ return;
+ }
+ }
+
// 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);
+ if (has2DDraft && opts?.activeDraftCanvas) {
+ targetCtx.save();
+ targetCtx.globalAlpha *= opts.activeDraftOpacity ?? 1.0;
+ if (opts.activeDraftSpace === 'viewport' && typeof targetCtx.setTransform === 'function') {
+ targetCtx.setTransform(1, 0, 0, 1, 0, 0);
+ targetCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ } else if (opts.activeDraftDirtyRect) {
+ const dr = opts.activeDraftDirtyRect;
+ targetCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
+ } else {
+ targetCtx.drawImage(
+ opts.activeDraftCanvas,
+ 0,
+ 0,
+ opts.dimensions?.width ?? opts.activeDraftCanvas.width,
+ opts.dimensions?.height ?? opts.activeDraftCanvas.height
+ );
+ }
+ targetCtx.restore();
}
targetCtx.restore();
@@ -3046,7 +5012,10 @@ export class ViewportCompositor {
ctx.scale(dpr, dpr);
ctx.translate(transform.pan.x, transform.pan.y);
ctx.rotate((transform.rotation * Math.PI) / 180);
- ctx.scale(transform.zoom, transform.zoom);
+ ctx.scale(
+ (transform.flipX ? -1 : 1) * transform.zoom,
+ (transform.flipY ? -1 : 1) * transform.zoom
+ );
ctx.translate(-dimensions.width / 2, -dimensions.height / 2);
if (_options.showCheckerboard) {
@@ -3070,76 +5039,95 @@ export class ViewportCompositor {
}
/**
- * Clear all allocated WebGL textures.
+ * Clear all allocated WebGL textures, FBOs, buffers, and programs.
*/
public dispose(): void {
if (this.gl) {
+ const gl = this.gl;
this.invalidateTileTextures();
for (const item of this.maskTextureCache.values()) {
- this.gl.deleteTexture(item.texture);
+ gl.deleteTexture(item.texture);
}
this.maskTextureCache.clear();
+ this.maskInvalidationEpochs.clear();
if (this.draftTexture) {
- this.gl.deleteTexture(this.draftTexture);
+ gl.deleteTexture(this.draftTexture);
this.draftTexture = null;
}
- if (this.snapshotTexture) {
- this.gl.deleteTexture(this.snapshotTexture);
- this.snapshotTexture = null;
- }
if (this.lutTexture) {
- this.gl.deleteTexture(this.lutTexture);
+ gl.deleteTexture(this.lutTexture);
this.lutTexture = null;
}
+ if (this.tileArrayTexture) {
+ gl.deleteTexture(this.tileArrayTexture);
+ this.tileArrayTexture = null;
+ }
+ if (this.instanceBuffer) {
+ gl.deleteBuffer(this.instanceBuffer);
+ this.instanceBuffer = null;
+ }
+ if (this.instancedVao && typeof gl.deleteVertexArray === 'function') {
+ gl.deleteVertexArray(this.instancedVao);
+ this.instancedVao = null;
+ }
if (this.quadBuffer) {
- this.gl.deleteBuffer(this.quadBuffer);
+ gl.deleteBuffer(this.quadBuffer);
this.quadBuffer = null;
}
if (this.program) {
- this.gl.deleteProgram(this.program);
+ gl.deleteProgram(this.program);
this.program = null;
}
+ if (this.instancedProgram) {
+ gl.deleteProgram(this.instancedProgram);
+ this.instancedProgram = null;
+ }
+ if (this.viewportDraftProgram) {
+ gl.deleteProgram(this.viewportDraftProgram);
+ this.viewportDraftProgram = null;
+ }
if (this.adjProgram) {
- this.gl.deleteProgram(this.adjProgram);
+ gl.deleteProgram(this.adjProgram);
this.adjProgram = null;
}
if (this.stylesProgram) {
- this.gl.deleteProgram(this.stylesProgram);
+ gl.deleteProgram(this.stylesProgram);
this.stylesProgram = null;
}
if (this.blitProgram) {
- this.gl.deleteProgram(this.blitProgram);
+ gl.deleteProgram(this.blitProgram);
this.blitProgram = null;
}
if (this.softProofProgram) {
- this.gl.deleteProgram(this.softProofProgram);
+ gl.deleteProgram(this.softProofProgram);
this.softProofProgram = null;
}
- if (this.proofSnapshotTexture) {
- this.gl.deleteTexture(this.proofSnapshotTexture);
- this.proofSnapshotTexture = null;
- }
- for (const item of this.folderFbos) {
- this.gl.deleteFramebuffer(item.fbo);
- this.gl.deleteTexture(item.texture);
- if (item.stencilRb && typeof this.gl.deleteRenderbuffer === 'function') {
- this.gl.deleteRenderbuffer(item.stencilRb);
- }
+ this.disposePingPongTarget(gl, this.scenePingPong);
+ this.scenePingPong = null;
+ for (const fpp of this.folderPingPongs) {
+ this.disposePingPongTarget(gl, fpp);
}
- this.folderFbos = [];
+ this.folderPingPongs = [];
+ this.disposeFboSurface(gl, this.belowActiveCacheFbo);
+ this.belowActiveCacheFbo = null;
+ this.disposeFboSurface(gl, this.aboveActiveCacheFbo);
+ this.aboveActiveCacheFbo = null;
+ this.disposeFboSurface(gl, this.layerStylesOutFbo);
+ this.layerStylesOutFbo = null;
if (this.layerFbo) {
- this.gl.deleteFramebuffer(this.layerFbo);
+ gl.deleteFramebuffer(this.layerFbo);
this.layerFbo = null;
}
if (this.layerTexture) {
- this.gl.deleteTexture(this.layerTexture);
+ gl.deleteTexture(this.layerTexture);
this.layerTexture = null;
}
if (this.stylesQuadBuffer) {
- this.gl.deleteBuffer(this.stylesQuadBuffer);
+ gl.deleteBuffer(this.stylesQuadBuffer);
this.stylesQuadBuffer = null;
}
}
+ this.stackCache.invalidateAll();
if (this.fallbackTileCanvas) {
this.fallbackTileCanvas = null;
}
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
index 22e9dd9..f2e867f 100644
--- a/src/utils/stampEngine.ts
+++ b/src/utils/stampEngine.ts
@@ -1,5 +1,7 @@
import {
Point,
+ BrushSettings,
+ ToolType,
CspSpraySettings,
CspTaperSettings,
CspSubTip,
@@ -18,7 +20,7 @@ import {
rgbToHex,
} from './colorMixingEngine';
import { getPaperGrain } from './pencilEngine';
-import { GpuDab } from './webglBrushEngine';
+import { GpuDab, WebGlBrushEngine } from './webglBrushEngine';
import {
evaluateFastSpline,
dabHashFloat,
@@ -553,6 +555,137 @@ function selectTipImage(
}
}
+/**
+ * Determines whether a textured brush configuration can execute on WebGlBrushEngine
+ * (instanced GPU FBO stamps). Falls back cleanly to Canvas 2D for binary pixel AA=0,
+ * stateful CPU colorMixingEngine, multi-subTip textures, or unavailable WebGL context.
+ */
+export function canUseWebGlForTexturedBrush(options: TexturedBrushOptions): boolean {
+ if (options.useGpu === false) return false;
+ if (options.colorMixing) return false;
+ if ((options.antiAlias ?? 2) === 0) return false;
+ if (options.subTipImages && options.subTipImages.length > 1) return false;
+ return WebGlBrushEngine.getInstance().isAvailable();
+}
+
+/**
+ * Determines whether a radial/soft brush configuration can execute on WebGlBrushEngine.
+ */
+export function canUseWebGlForRadialBrush(options?: RadialMixingOptions): boolean {
+ if (options?.useGpu === false) return false;
+ if (options?.colorMixing) return false;
+ if ((options?.antiAlias ?? 2) === 0) return false;
+ return WebGlBrushEngine.getInstance().isAvailable();
+}
+
+/**
+ * Flushes a collected GpuDab[] batch for a textured brush to targetCtx via WebGlBrushEngine.
+ */
+export function flushTexturedGpuDabs(
+ ctx: CanvasRenderingContext2D,
+ dabs: GpuDab[],
+ tipImage: HTMLImageElement,
+ color: string,
+ options: TexturedBrushOptions
+): boolean {
+ if (dabs.length === 0) return true;
+ const gpu = WebGlBrushEngine.getInstance();
+ if (!gpu.isAvailable()) return false;
+
+ const isEraser = Boolean(options.isEraser);
+ const isBgEraser = Boolean(options.isBgEraser);
+ const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
+ const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
+ size: options.size,
+ minSizeFactor: options.minSizeFactor ?? 0,
+ color,
+ opacity: options.opacity ?? 1.0,
+ flow: options.flow ?? 0.85,
+ spacing: options.spacing ?? 0.08,
+ usePressure: options.usePressure !== false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: options.hardness ?? 1.0,
+ antiAlias: options.antiAlias ?? 2,
+ wetEdge: options.wetEdge ?? 0,
+ grain: options.grain ?? options.textureDensity ?? 0,
+ textureDensity: options.textureDensity,
+ paperTextureMode: options.paperTextureMode,
+ paperTextureBrightness: options.paperTextureBrightness,
+ paperTextureContrast: options.paperTextureContrast,
+ paperTextureInverted: options.paperTextureInverted,
+ paperTextureImage: options.paperTextureImage,
+ paperTextureScale: options.paperTextureScale,
+ paperTextureRotate: options.paperTextureRotate,
+ customTipImage: tipImage,
+ isColorTip: options.isColorTip,
+ subTips: options.subTips,
+ dualBrush: options.dualBrush,
+ dualTipImage: options.dualTipImage,
+ dualBrushCompositeMode: options.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
+ colorMixing: false,
+ isTransparentInk: Boolean(options.isTransparentInk),
+ alphaLocked: Boolean(options.alphaLocked),
+ isBgEraser,
+ };
+
+ const docW = options.underlyingCanvas?.width || ctx.canvas?.width || 1024;
+ const docH = options.underlyingCanvas?.height || ctx.canvas?.height || 1024;
+ return gpu.renderDabsToContext(ctx, dabs, settings, tool, docW, docH, options.underlyingCanvas);
+}
+
+/**
+ * Flushes a collected GpuDab[] batch for a radial/soft brush to targetCtx via WebGlBrushEngine.
+ */
+export function flushRadialGpuDabs(
+ ctx: CanvasRenderingContext2D,
+ dabs: GpuDab[],
+ color: string,
+ hardness: number,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ mixingOptions?: RadialMixingOptions
+): boolean {
+ if (dabs.length === 0) return true;
+ const gpu = WebGlBrushEngine.getInstance();
+ if (!gpu.isAvailable()) return false;
+
+ const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
+ const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
+ size: 10,
+ minSizeFactor: 0,
+ color,
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.08,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness,
+ antiAlias: mixingOptions?.antiAlias ?? 2,
+ wetEdge: 0,
+ grain: mixingOptions?.grain ?? 0,
+ paperTextureMode: mixingOptions?.paperTextureMode,
+ paperTextureBrightness: mixingOptions?.paperTextureBrightness,
+ paperTextureContrast: mixingOptions?.paperTextureContrast,
+ paperTextureInverted: mixingOptions?.paperTextureInverted,
+ paperTextureImage: mixingOptions?.paperTextureImage,
+ paperTextureScale: mixingOptions?.paperTextureScale,
+ paperTextureRotate: mixingOptions?.paperTextureRotate,
+ dualBrush: mixingOptions?.dualBrush,
+ dualTipImage: mixingOptions?.dualTipImage,
+ dualBrushCompositeMode: mixingOptions?.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
+ colorMixing: false,
+ isTransparentInk: Boolean(mixingOptions?.isTransparentInk),
+ alphaLocked: Boolean(mixingOptions?.alphaLocked),
+ isBgEraser,
+ };
+
+ const docW = mixingOptions?.underlyingCanvas?.width || ctx.canvas?.width || 1024;
+ const docH = mixingOptions?.underlyingCanvas?.height || ctx.canvas?.height || 1024;
+ return gpu.renderDabsToContext(ctx, dabs, settings, tool, docW, docH, mixingOptions?.underlyingCanvas);
+}
+
/**
* Draws a single textured dot at pointer down.
*/
@@ -561,7 +694,8 @@ export function drawTexturedDot(
point: Point,
color: string,
tipImage: HTMLImageElement,
- options: TexturedBrushOptions
+ options: TexturedBrushOptions,
+ batchGpuDabs?: GpuDab[]
) {
const isEraser = options.isEraser ?? false;
const isBgEraser = options.isBgEraser ?? false;
@@ -621,9 +755,10 @@ export function drawTexturedDot(
}
}
+ const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
const activeTip = selectTipImage(options.subTipImages, tipImage, options.subTipOrder, 0, 0, point.x, point.y);
const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
- const master = getTintedTipMaster(activeTip, effectiveColor, isColorTip);
+ const master = gpuDabs ? null : getTintedTipMaster(activeTip, effectiveColor, isColorTip);
const aspect = (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1);
const thickness = options.thickness ?? 1.0;
@@ -659,9 +794,9 @@ export function drawTexturedDot(
);
effectiveFlow *= sensorOpacity * sensorDensity;
- // CPU Paper Texture modulation so live preview matches GPU bake
+ // CPU Paper Texture modulation when not rendering on GPU (GPU shader samples paper grain per pixel)
const grainAmount = options.grain ?? options.textureDensity ?? 0;
- if (grainAmount > 0.005) {
+ if (!gpuDabs && grainAmount > 0.005) {
const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
effectiveFlow = applyCspPaperTextureAlpha(
@@ -684,7 +819,7 @@ export function drawTexturedDot(
const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = colorJitterEnabled ? parseColorToRgb(effectiveColor) : null;
+ const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(effectiveColor) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
const aaMode = options.antiAlias ?? 2;
@@ -720,6 +855,9 @@ export function drawTexturedDot(
}
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) {
let salt = 20;
const cd = applyColorDynamics(
@@ -728,7 +866,12 @@ export function drawTexturedDot(
dynamics,
() => dabHashFloat(point.x, point.y, k, salt++)
);
- curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
+ dabR = cd.r;
+ dabG = cd.g;
+ dabB = cd.b;
+ if (!gpuDabs) {
+ curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
+ }
}
let dotRenderW = isVert ? curDabW * curDabThickness : curDabW;
@@ -748,26 +891,64 @@ export function drawTexturedDot(
const u2 = dabHashFloat(curDabX, curDabY, k * 64 + i, 32);
const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, k * 64 + i, 33);
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX + r * Math.cos(th),
- curDabY + r * Math.sin(th),
- isVert ? pSize * curDabThickness : pSize,
- isVert ? pSize * aspect : pSize * aspect * curDabThickness,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk,
- flips.signX,
- flips.signY,
- aaMode,
- options.blendTipsMode
- );
+ const spX = curDabX + r * Math.cos(th);
+ const spY = curDabY + r * Math.sin(th);
+ const spW = isVert ? pSize * curDabThickness : pSize;
+ const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: spX,
+ y: spY,
+ width: spW,
+ height: spH,
+ angle: curDabAngle,
+ r: dabR,
+ g: dabG,
+ b: dabB,
+ alpha: curDabAlpha,
+ pressure: effPressure,
+ strokeDist: 0,
+ flipX: flips.signX,
+ flipY: flips.signY,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx,
+ curMaster,
+ spX,
+ spY,
+ spW,
+ spH,
+ curDabAngle,
+ curDabAlpha,
+ isEraser,
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ options.blendTipsMode
+ );
+ }
}
- } else {
+ } else if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX,
+ y: curDabY,
+ width: dotRenderW,
+ height: dotRenderH,
+ angle: curDabAngle,
+ r: dabR,
+ g: dabG,
+ b: dabB,
+ alpha: curDabAlpha,
+ pressure: effPressure,
+ strokeDist: 0,
+ flipX: flips.signX,
+ flipY: flips.signY,
+ });
+ } else if (curMaster) {
drawSingleStamp(
ctx,
curMaster,
@@ -1455,16 +1636,10 @@ export function renderCompleteTexturedStroke(
if (!options.underlyingCanvas) {
options.underlyingCanvas = ctx.canvas;
}
- if (!options.sampler && options.underlyingCanvas) {
+ if (options.colorMixing && !options.sampler && options.underlyingCanvas) {
options.sampler = new LayerPixelSampler(options.underlyingCanvas);
}
- drawTexturedDot(ctx, points[0], color, tipImage, options);
-
- if (points.length === 1) {
- return;
- }
-
let totalLen = 0;
for (let i = 1; i < points.length; i++) {
totalLen += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
@@ -1472,37 +1647,52 @@ export function renderCompleteTexturedStroke(
options.totalLength = totalLen;
options.currentStrokeDist = 0;
- const batchGpuDabs: GpuDab[] | undefined = undefined;
+ const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
+ options.currentStrokeDist = 0;
+ drawTexturedDot(ctx, points[0], color, tipImage, options, batchGpuDabs);
+ if (points.length === 1) return;
- const dabCounter = { count: 0 };
- let accDist = Math.max(0.15, points[0].width * (options.spacing ?? 0.07));
+ const dabCounter = { count: 0 };
+ let accDist = Math.max(0.15, points[0].width * (options.spacing ?? 0.07));
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
- const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
- drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- } else {
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
- accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
-
- for (let i = 2; i < points.length - 1; i++) {
- const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter, batchGpuDabs);
- options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
- }
-
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ if (points.length === 2) {
+ const p0 = points[0];
+ const p1 = points[1];
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ } else {
+ const p0 = points[0];
+ const p1 = points[1];
+ const p2 = points[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
+
+ for (let i = 2; i < points.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
+ accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
+ }
+
+ const n = points.length;
+ const pPrev2 = points[n - 3];
+ const pPrev = points[n - 2];
+ const pLast = points[n - 1];
+ const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ }
+ };
+
+ if (canUseWebGlForTexturedBrush(options)) {
+ const batchGpuDabs: GpuDab[] = [];
+ emitStroke(batchGpuDabs);
+ if (flushTexturedGpuDabs(ctx, batchGpuDabs, tipImage, color, options)) {
+ return;
+ }
}
+
+ // Clean Canvas 2D fallback (binary AA=0, colorMixingEngine, multi-subTip, or unavailable WebGL)
+ emitStroke(undefined);
}
/**
@@ -1631,7 +1821,8 @@ export function drawRadialDot(
isBgEraser: boolean = false,
mixingOptions?: RadialMixingOptions,
thickness: number = 1.0,
- angleRad: number = 0
+ angleRad: number = 0,
+ batchGpuDabs?: GpuDab[]
) {
const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
let dabColor = isBgEraser ? '#ffffff' : color;
@@ -1735,8 +1926,9 @@ export function drawRadialDot(
dotAngle += (point.twist * Math.PI) / 180;
}
+ const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
const grainAmount = mixingOptions?.grain ?? 0;
- if (grainAmount > 0.005) {
+ if (!gpuDabs && grainAmount > 0.005) {
const scale = Math.max(0.1, mixingOptions?.paperTextureScale ?? 1.0);
const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
dabFlow = applyCspPaperTextureAlpha(
@@ -1751,7 +1943,7 @@ export function drawRadialDot(
);
}
- const master = getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser, dotW, aaMode);
+ const master = gpuDabs ? null : getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser, dotW, aaMode);
const dynamics = mixingOptions?.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
@@ -1761,7 +1953,7 @@ export function drawRadialDot(
const scatter = Math.max(0, Math.min(5, dynamics?.scatter ?? 0));
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(mixingOptions?.secondaryColor || '#ffffff') : null;
for (let k = 0; k < dabCount; k++) {
@@ -1796,6 +1988,9 @@ export function drawRadialDot(
}
let curMaster = master;
+ let rNorm = primRgb ? primRgb.r / 255 : 0;
+ let gNorm = primRgb ? primRgb.g / 255 : 0;
+ let bNorm = primRgb ? primRgb.b / 255 : 0;
if (colorJitterEnabled && primRgb && secRgb && dynamics) {
let salt = 20;
const cd = applyColorDynamics(
@@ -1804,7 +1999,12 @@ export function drawRadialDot(
dynamics,
() => dabHashFloat(point.x, point.y, k, salt++)
);
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
+ rNorm = cd.r;
+ gNorm = cd.g;
+ bNorm = cd.b;
+ if (!gpuDabs) {
+ curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
+ }
}
let finalW = isVert ? curDabW * curDabThickness : curDabW;
@@ -1814,24 +2014,42 @@ export function drawRadialDot(
finalH = (w * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX,
- curDabY,
- finalW,
- finalH,
- curDabRot,
- curDabFlow,
- isEraser,
- isBgEraser,
- mixingOptions?.alphaLocked,
- mixingOptions?.isTransparentInk,
- 1,
- 1,
- aaMode,
- mixingOptions?.blendTipsMode
- );
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX,
+ y: curDabY,
+ width: finalW,
+ height: finalH,
+ angle: curDabRot,
+ r: rNorm,
+ g: gNorm,
+ b: bNorm,
+ alpha: curDabFlow,
+ pressure: point.pressure ?? 1.0,
+ strokeDist: 0,
+ flipX: 1,
+ flipY: 1,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx,
+ curMaster,
+ curDabX,
+ curDabY,
+ finalW,
+ finalH,
+ curDabRot,
+ curDabFlow,
+ isEraser,
+ isBgEraser,
+ mixingOptions?.alphaLocked,
+ mixingOptions?.isTransparentInk,
+ 1,
+ 1,
+ aaMode,
+ mixingOptions?.blendTipsMode
+ );
+ }
}
}
@@ -2186,36 +2404,47 @@ export function renderCompleteRadialStroke(
}
}
- drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions, thickness, angleRad);
- if (points.length === 1) return;
+ const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
+ drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions, thickness, angleRad, batchGpuDabs);
+ if (points.length === 1) return;
- const batchGpuDabs: GpuDab[] | undefined = undefined;
+ const firstWidth = Math.max(0.2, points[0].width);
+ let accDist = Math.max(0.12, firstWidth * spacing);
- const firstWidth = Math.max(0.2, points[0].width);
- let accDist = Math.max(0.12, firstWidth * spacing);
+ if (points.length === 2) {
+ const p0 = points[0];
+ const p1 = points[1];
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ drawRadialCubicBezierSegment(ctx, p0, c1, c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ } else {
+ const p0 = points[0];
+ const p1 = points[1];
+ const p2 = points[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawRadialCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+
+ for (let i = 2; i < points.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
+ accDist = drawRadialCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ }
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
- const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
- drawRadialCubicBezierSegment(ctx, p0, c1, c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- } else {
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
- accDist = drawRadialCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
-
- for (let i = 2; i < points.length - 1; i++) {
- const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawRadialCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- }
-
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawRadialCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ const n = points.length;
+ const pPrev2 = points[n - 3];
+ const pPrev = points[n - 2];
+ const pLast = points[n - 1];
+ const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ drawRadialCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ }
+ };
+
+ if (canUseWebGlForRadialBrush(mixingOptions)) {
+ const batchGpuDabs: GpuDab[] = [];
+ emitStroke(batchGpuDabs);
+ if (flushRadialGpuDabs(ctx, batchGpuDabs, color, hardness, isEraser, isBgEraser, mixingOptions)) {
+ return;
+ }
}
+
+ // Clean Canvas 2D fallback
+ emitStroke(undefined);
}
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index 990768e..f14b90e 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -777,6 +777,7 @@ export class TileMemoryManager {
tile.version++;
this.touchTile(tile);
void this.checkBudgetAndEvict();
+ this.grid.bumpLayerVersion(tile.layerId);
this.grid.notifyChange();
return tile.data;
} finally {
@@ -974,11 +975,26 @@ export class SparseTileGrid {
private thumbCanvas: HTMLCanvasElement | null = null;
private listeners: Set<(immediate?: boolean) => void> = new Set();
private memoryManager: TileMemoryManager | null = null;
+ private layerVersions: Map<string, number> = new Map();
+ private globalVersionCounter: number = 1;
+ private gridEpoch: number = 0;
constructor(memoryManagerOptions?: TileMemoryManagerOptions) {
this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);
}
+ public getLayerVersion(layerId: string): number {
+ return this.layerVersions.get(layerId) ?? 0;
+ }
+
+ public bumpLayerVersion(layerId: string): void {
+ this.layerVersions.set(layerId, ++this.globalVersionCounter);
+ }
+
+ public getGridEpoch(): number {
+ return this.gridEpoch;
+ }
+
public setMemoryManager(manager: TileMemoryManager | null): void {
this.memoryManager = manager;
}
@@ -1061,6 +1077,7 @@ export class SparseTileGrid {
if (tile.lod === 0) {
this.setLayerFormat(layerId, tile.format);
this.markLodAncestorsDirty(layerId, tileX, tileY);
+ this.bumpLayerVersion(layerId);
}
this.notifyChange();
}
@@ -1075,6 +1092,7 @@ export class SparseTileGrid {
this.tiles.delete(key);
if (lod === 0) {
this.markLodAncestorsDirty(layerId, tileX, tileY);
+ this.bumpLayerVersion(layerId);
}
}
}
@@ -1292,6 +1310,7 @@ export class SparseTileGrid {
}
}
+ this.bumpLayerVersion(layerId);
if (!suppressNotify) {
this.notifyChange();
}
@@ -1677,6 +1696,7 @@ export class SparseTileGrid {
this.markLodAncestorsDirty(layerId, tx, ty);
}
}
+ this.bumpLayerVersion(layerId);
this.notifyChange();
}
@@ -1737,6 +1757,7 @@ export class SparseTileGrid {
this.tiles.delete(key);
this.dirtyLodTiles.delete(key);
}
+ this.bumpLayerVersion(layerId);
this.notifyChange();
}
@@ -1935,6 +1956,7 @@ export class SparseTileGrid {
tile.dirty = true;
tile.version++;
this.markLodAncestorsDirty(layerId, tileX, tileY);
+ this.bumpLayerVersion(layerId);
}
}
this.notifyChange();
@@ -1950,6 +1972,8 @@ export class SparseTileGrid {
this.layerFormats.clear();
this.ingestedLayers.clear();
this.dirtyLodTiles.clear();
+ this.layerVersions.clear();
+ this.gridEpoch++;
this.notifyChange(true);
}
@@ -1973,6 +1997,9 @@ export class SparseTileGrid {
if (this.memoryManager) {
this.memoryManager.notifyTileAllocated(tile);
}
+ if ((tile.lod ?? 0) === 0) {
+ this.bumpLayerVersion(tile.layerId);
+ }
}
this.notifyChange(true);
}
diff --git a/src/utils/webglBrushEngine.ts b/src/utils/webglBrushEngine.ts
index 78a3cfb..536855f 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/utils/webglBrushEngine.ts
@@ -453,6 +453,12 @@ export class WebGlBrushEngine {
private builtinPaperTexture: WebGLTexture | null = null;
private canvasLayerTexture: WebGLTexture | null = null;
+ // Offscreen GPU FBO for instanced dab rendering (WebGL2 fast path)
+ private dabFbo: WebGLFramebuffer | null = null;
+ private dabFboTex: WebGLTexture | null = null;
+ private dabFboWidth: number = 0;
+ private dabFboHeight: number = 0;
+
// Dab geometry & instancing buffers (stride 14 floats)
private quadVertexBuffer: WebGLBuffer | null = null;
private extInstanced: {
@@ -479,6 +485,10 @@ export class WebGlBrushEngine {
this.tipTexturesMap.clear();
this.builtinPaperTexture = null;
this.canvasLayerTexture = null;
+ this.dabFbo = null;
+ this.dabFboTex = null;
+ this.dabFboWidth = 0;
+ this.dabFboHeight = 0;
});
c.addEventListener('webglcontextrestored', () => {
this.initGl();
@@ -730,6 +740,44 @@ export class WebGlBrushEngine {
return true;
}
+ private ensureDabFbo(width: number, height: number): boolean {
+ const gl = this.gl;
+ if (!gl || !('blitFramebuffer' in gl)) return false;
+ if (this.dabFbo && this.dabFboTex && this.dabFboWidth === width && this.dabFboHeight === height) {
+ return true;
+ }
+ if (!this.dabFbo) {
+ this.dabFbo = gl.createFramebuffer();
+ }
+ if (!this.dabFboTex) {
+ this.dabFboTex = gl.createTexture();
+ }
+ if (!this.dabFbo || !this.dabFboTex) return false;
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.dabFboTex);
+ 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, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.dabFbo);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.dabFboTex, 0);
+ const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+
+ if (!complete) {
+ this.dabFboWidth = 0;
+ this.dabFboHeight = 0;
+ return false;
+ }
+ this.dabFboWidth = width;
+ this.dabFboHeight = height;
+ return true;
+ }
+
/**
* Retrieves or uploads a brush tip or paper texture to GPU memory.
*/
@@ -980,7 +1028,7 @@ export class WebGlBrushEngine {
public renderDabsToContext(
targetCtx: CanvasRenderingContext2D,
dabs: GpuDab[],
- settings: BrushSettings & { alphaLocked?: boolean },
+ settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean },
tool: ToolType,
_canvasWidth: number,
_canvasHeight: number,
@@ -994,7 +1042,7 @@ export class WebGlBrushEngine {
const gl = this.gl;
const isTransparentInk = Boolean(settings.isTransparentInk);
const isEraser = tool === 'eraser' || isTransparentInk;
- const isBgEraser = tool === 'eraser' && targetCtx.fillStyle === '#ffffff';
+ const isBgEraser = Boolean(settings.isBgEraser) || (tool === 'eraser' && targetCtx.fillStyle === '#ffffff');
const isAlphaLocked = Boolean(settings.alphaLocked);
let minX = Infinity;
@@ -1022,6 +1070,15 @@ export class WebGlBrushEngine {
return false;
}
+ const chunkWMax = Math.min(MAX_TILE_CHUNK, totalW);
+ const chunkHMax = Math.min(MAX_TILE_CHUNK, totalH);
+ if (canvas.width < chunkWMax || canvas.height < chunkHMax) {
+ canvas.width = Math.max(canvas.width, chunkWMax, 512);
+ canvas.height = Math.max(canvas.height, chunkHMax, 512);
+ }
+
+ const useOffscreenFbo = this.ensureDabFbo(canvas.width, canvas.height);
+
// Pack instance buffer once across all dabs (stride 14 floats)
const stride = 14;
const requiredFloats = dabs.length * stride;
@@ -1227,13 +1284,6 @@ export class WebGlBrushEngine {
}
}
- const chunkWMax = Math.min(MAX_TILE_CHUNK, totalW);
- const chunkHMax = Math.min(MAX_TILE_CHUNK, totalH);
- if (canvas.width < chunkWMax || canvas.height < chunkHMax) {
- canvas.width = Math.max(canvas.width, chunkWMax, 512);
- canvas.height = Math.max(canvas.height, chunkHMax, 512);
- }
-
const compositeOp: GlobalCompositeOperation = isBgEraser
? 'source-over'
: isEraser
@@ -1256,6 +1306,10 @@ export class WebGlBrushEngine {
const dw = Math.min(MAX_TILE_CHUNK, fullDirtyMaxX - cx);
const viewY = Math.max(0, canvas.height - dh);
+ if (useOffscreenFbo && this.dabFbo) {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.dabFbo);
+ }
+
gl.viewport(0, viewY, dw, dh);
if (typeof gl.scissor === 'function') {
gl.enable(gl.SCISSOR_TEST);
@@ -1292,6 +1346,25 @@ export class WebGlBrushEngine {
gl.disable(gl.SCISSOR_TEST);
}
+ if (useOffscreenFbo && this.dabFbo) {
+ const gl2 = gl as WebGL2RenderingContext;
+ gl2.bindFramebuffer(gl2.READ_FRAMEBUFFER, this.dabFbo);
+ gl2.bindFramebuffer(gl2.DRAW_FRAMEBUFFER, null);
+ gl2.blitFramebuffer(
+ 0,
+ viewY,
+ dw,
+ viewY + dh,
+ 0,
+ viewY,
+ dw,
+ viewY + dh,
+ gl2.COLOR_BUFFER_BIT,
+ gl2.NEAREST
+ );
+ gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
+ }
+
targetCtx.drawImage(canvas, 0, 0, dw, dh, cx, cy, dw, dh);
}
}