Skip to content

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

optimization

sora140d70aaeb73
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 629549b..4e7d678 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -682,7 +682,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
cam.flipY,
rp.dimensions
);
- artboard.style.imageRendering = cam.zoom > 1 ? 'pixelated' : 'auto';
}
const ring = cursorRingRef.current;
@@ -1380,9 +1379,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
dimensions
),
transformOrigin: '0 0',
- boxShadow: '0 0 0 1px #161616, 0 10px 40px rgba(0, 0, 0, 0.55)',
willChange: 'transform',
- imageRendering: liveZoom > 1 ? 'pixelated' : 'auto',
backgroundColor: 'transparent',
backgroundImage: 'none',
}}
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 7103438..1c13237 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -13,8 +13,10 @@ import {
promptExportPngImage,
promptSaveAs,
SaveDocumentData,
+ SaveProgress,
saveToExistingHandle,
} from '../utils/saveManager';
+import { globalTimelapseManager } from '../utils/timelapseEngine';
import { saveRecentDocument, RecentDocument } from '../utils/recentDocumentsManager';
import { enforceColorMode } from '../utils/colorUtils';
import { parseSutFile } from '../utils/sutParser';
@@ -361,10 +363,13 @@ export function useDocumentLifecycle({
colorMode: doc.colorMode,
layers: doc.layers,
activeLayerId: doc.layers[0]?.id || 'layer-1',
- perspectiveRuler: null,
+ perspectiveRuler: doc.perspectiveRuler ?? null,
};
- documentStoreActions.setPerspectiveRuler(null);
+ documentStoreActions.setPerspectiveRuler(doc.perspectiveRuler ?? null);
+ if (doc.animationTimeline !== undefined) {
+ documentStoreActions.setAnimationTimeline(doc.animationTimeline);
+ }
documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
documentStoreActions.setActiveDocumentId(newDocId);
@@ -374,7 +379,7 @@ export function useDocumentLifecycle({
title: file.name,
path: fileWithPath.path || `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
size: file.size || 1048576,
- coverUrl: doc.layers[0]?.thumbnailUrl,
+ coverUrl: doc.previewDataUrl || doc.layers[0]?.thumbnailUrl,
isStarred: false,
fileType: file.name.slice(file.name.lastIndexOf('.')),
isSaved: true,
@@ -608,19 +613,47 @@ export function useDocumentLifecycle({
[handleProcessFile]
);
- const handleSave = useCallback(async () => {
- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
+ const buildSaveData = useCallback(
+ (onProgress?: (p: SaveProgress) => void): SaveDocumentData => {
+ const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
+ const docStoreState = useDocumentStore.getState();
+ const tlStats = globalTimelapseManager.getStats(activeDocumentId);
+ return {
+ name: cleanNameForSave,
+ dimensions,
+ colorMode,
+ layers,
+ layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ tabId: activeDocumentId || undefined,
+ perspectiveRuler: docStoreState.perspectiveRuler,
+ animationTimeline: docStoreState.animationTimeline,
+ timelapse:
+ tlStats.enabled || tlStats.frameCount > 0
+ ? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }
+ : null,
+ onProgress,
+ };
+ },
+ [
+ activeDocumentId,
colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
+ dimensions,
+ documentName,
getEffectiveOpacity,
isLayerEffectivelyVisible,
- tabId: activeDocumentId || undefined,
+ layerCanvasesRef,
+ layers,
+ ]
+ );
+
+ const handleSave = useCallback(async () => {
+ const onProgress = (p: SaveProgress) => {
+ uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
};
+ const docData = buildSaveData(onProgress);
if (!savedFileInfo?.handle) {
try {
@@ -636,8 +669,8 @@ export function useDocumentLifecycle({
id: activeDocumentId || `doc-${Date.now()}`,
title: info.name,
path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
+ size: info.size || 1572864,
+ coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
isSaved: true,
@@ -648,10 +681,12 @@ export function useDocumentLifecycle({
if (msg !== 'Save canceled') {
alert('Failed to save file: ' + msg);
}
+ } finally {
+ uiStoreActions.setLoading(false, '');
}
} else {
try {
- await saveToExistingHandle(docData, savedFileInfo);
+ const saveRes = await saveToExistingHandle(docData, savedFileInfo);
documentStoreActions.setDocumentName(savedFileInfo.name);
documentStoreActions.setDocuments((prev) =>
prev.map((d) =>
@@ -662,8 +697,8 @@ export function useDocumentLifecycle({
id: activeDocumentId || `doc-${Date.now()}`,
title: savedFileInfo.name,
path: `InkStudio\\${savedFileInfo.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
+ size: saveRes.size || 1572864,
+ coverUrl: saveRes.previewDataUrl || layers[0]?.thumbnailUrl,
isStarred: false,
fileType: savedFileInfo.extension,
isSaved: true,
@@ -684,8 +719,8 @@ export function useDocumentLifecycle({
id: activeDocumentId || `doc-${Date.now()}`,
title: info.name,
path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
+ size: info.size || 1572864,
+ coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
isSaved: true,
@@ -697,34 +732,17 @@ export function useDocumentLifecycle({
alert('Failed to save file: ' + msg);
}
}
+ } finally {
+ uiStoreActions.setLoading(false, '');
}
}
- }, [
- activeDocumentId,
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- savedFileInfo,
- showToast,
- ]);
+ }, [activeDocumentId, buildSaveData, layers, savedFileInfo, showToast]);
const handleSaveAs = useCallback(async () => {
- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
- colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- tabId: activeDocumentId || undefined,
+ const onProgress = (p: SaveProgress) => {
+ uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
};
+ const docData = buildSaveData(onProgress);
try {
const defaultExt = savedFileInfo?.extension || '.sora';
@@ -740,8 +758,8 @@ export function useDocumentLifecycle({
id: activeDocumentId || `doc-${Date.now()}`,
title: info.name,
path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
+ size: info.size || 1572864,
+ coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
isSaved: true,
@@ -752,32 +770,17 @@ export function useDocumentLifecycle({
if (msg !== 'Save canceled') {
alert('Failed to save file: ' + msg);
}
+ } finally {
+ uiStoreActions.setLoading(false, '');
}
- }, [
- activeDocumentId,
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- savedFileInfo,
- showToast,
- ]);
+ }, [activeDocumentId, buildSaveData, layers, savedFileInfo, showToast]);
const handleExportImage = useCallback(async () => {
const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
- colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
+ const onProgress = (p: SaveProgress) => {
+ uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
};
+ const docData = buildSaveData(onProgress);
try {
const exportedName = await promptExportPngImage(docData, cleanNameForSave);
@@ -787,17 +790,10 @@ export function useDocumentLifecycle({
if (msg !== 'Export canceled') {
alert('Failed to export image: ' + msg);
}
+ } finally {
+ uiStoreActions.setLoading(false, '');
}
- }, [
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- showToast,
- ]);
+ }, [buildSaveData, documentName, showToast]);
const handleSelectWelcomeDocument = useCallback(
async (doc: RecentDocument) => {
diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsx
index bb70304..6072dd4 100644
--- a/src/components/ModalHost.tsx
+++ b/src/components/ModalHost.tsx
@@ -12,7 +12,7 @@ import { CrashedSessionInfo } from '../services/recoveryService';
import { TonalCorrectionType } from '../utils/tonalEngine';
import { AnyTonalParams } from '../hooks/useTonalAndFilterActions';
import { SaturatedLinesOptions, StreamLinesOptions } from '../utils/mangaEffectsEngine';
-import { compositeCanvas } from '../utils/saveManager';
+import { compositeCanvas, createDocumentRegionRenderer } from '../utils/saveManager';
import { documentStore } from '../utils/documentStore';
import { useDocumentStore, useUiStore, uiStoreActions } from '../stores';
import { CrashRecoveryModal } from './CrashRecoveryModal';
@@ -149,6 +149,8 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
const loadingStatus = useUiStore((s) => s.loadingStatus);
const toastMessage = useUiStore((s) => s.toastMessage);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+
const getWebtoonActiveCanvas = useCallback(
() =>
compositeCanvas(
@@ -158,9 +160,24 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
getEffectiveOpacity,
isLayerEffectivelyVisible,
false,
- documentStore.getActiveTileGrid()
+ documentStore.getActiveTileGrid(),
+ { colorMode }
+ ),
+ [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
+ );
+
+ const createWebtoonRegionRenderer = useCallback(
+ () =>
+ createDocumentRegionRenderer(
+ dimensions,
+ layers,
+ layerCanvasesRef.current,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ documentStore.getActiveTileGrid(),
+ { colorMode }
),
- [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible]
+ [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible, colorMode]
);
const activeDoc = documents.find((d) => d.id === activeDocumentId);
@@ -284,7 +301,9 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
{loadingStatus || 'Opening Document...'}
</span>
<span className="text-[#8a8a8a] text-[10px]">
- Extracting layers and pixel data
+ {loadingStatus && /sav|export|composit|encod/i.test(loadingStatus)
+ ? 'Processing layers and tile data'
+ : 'Extracting layers and pixel data'}
</span>
</div>
</div>
@@ -310,6 +329,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
isOpen={isWebtoonExportModalOpen}
onClose={() => uiStoreActions.setWebtoonExportModalOpen(false)}
getActiveCanvas={getWebtoonActiveCanvas}
+ createRegionRenderer={createWebtoonRegionRenderer}
canvasWidth={dimensions.width}
canvasHeight={dimensions.height}
documentTitle={activeDoc?.name || 'webtoon_chapter'}
diff --git a/src/components/NavigatorPanel.tsx b/src/components/NavigatorPanel.tsx
index 019128b..44e7107 100644
--- a/src/components/NavigatorPanel.tsx
+++ b/src/components/NavigatorPanel.tsx
@@ -353,6 +353,7 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
// Throttled low-LOD preview composite (<= 1 render per ~200ms during rapid brush strokes)
const lastPreviewTsRef = useRef<number>(0);
+ const lastContentVersionRef = useRef<number>(-1);
const previewTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const renderPreviewNow = useCallback(() => {
@@ -371,6 +372,9 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
ViewportCompositor.renderLowResPreview(canvas, curLayers, curDims, curGrid, {
showCheckerboard: curCheck,
});
+ if (typeof curGrid.getContentVersion === 'function') {
+ lastContentVersionRef.current = curGrid.getContentVersion();
+ }
lastPreviewTsRef.current = Date.now();
}, []);
@@ -418,9 +422,16 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
scheduleThrottledPreview();
}, [layers, dimensions, showCheckerboard, tileGrid, scheduleThrottledPreview]);
- // Subscribe to SparseTileGrid changes with 200ms throttle to avoid stroke overhead
+ // Subscribe to SparseTileGrid changes with 200ms throttle, ignoring draft-only redraw notifications
useEffect(() => {
+ lastContentVersionRef.current = -1;
const unsub = tileGrid.subscribe(() => {
+ if (
+ typeof tileGrid.getContentVersion === 'function' &&
+ tileGrid.getContentVersion() === lastContentVersionRef.current
+ ) {
+ return;
+ }
scheduleThrottledPreview();
});
return () => {
diff --git a/src/components/WebtoonExportModal.tsx b/src/components/WebtoonExportModal.tsx
index 51fff6f..b3119c8 100644
--- a/src/components/WebtoonExportModal.tsx
+++ b/src/components/WebtoonExportModal.tsx
@@ -1,11 +1,17 @@
import React, { useState } from 'react';
import { X, Archive, Download, Loader2 } from 'lucide-react';
-import { exportWebtoonChapterZip, downloadWebtoonZip } from '../utils/webtoonExporter';
+import {
+ exportWebtoonChapterZip,
+ exportWebtoonChapterZipFromRenderer,
+ downloadWebtoonZip,
+ WebtoonRegionRenderer,
+} from '../utils/webtoonExporter';
interface WebtoonExportModalProps {
isOpen: boolean;
onClose: () => void;
getActiveCanvas: () => HTMLCanvasElement | null;
+ createRegionRenderer?: () => { renderRegion: WebtoonRegionRenderer; dispose: () => void };
canvasWidth: number;
canvasHeight: number;
documentTitle?: string;
@@ -15,6 +21,7 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({
isOpen,
onClose,
getActiveCanvas,
+ createRegionRenderer,
canvasWidth,
canvasHeight,
documentTitle = 'webtoon_chapter',
@@ -30,21 +37,46 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({
const totalSlices = Math.max(1, Math.ceil(canvasHeight / sliceHeight));
const handleStartExport = async () => {
- const canvas = getActiveCanvas();
- if (!canvas) return;
-
try {
setIsExporting(true);
setProgress({ current: 0, total: totalSlices, percent: 0 });
- const zipBytes = await exportWebtoonChapterZip(canvas, {
- sliceWidth: canvasWidth,
- sliceHeight,
- format,
- quality: quality / 100,
- filePrefix: `${documentTitle.replace(/\s+/g, '_')}_slice_`,
- onProgress: (p) => setProgress(p),
- });
+ let zipBytes: Uint8Array;
+ if (createRegionRenderer) {
+ const renderer = createRegionRenderer();
+ try {
+ zipBytes = await exportWebtoonChapterZipFromRenderer(
+ canvasWidth,
+ canvasHeight,
+ renderer.renderRegion,
+ {
+ sliceWidth: canvasWidth,
+ sliceHeight,
+ format,
+ quality: quality / 100,
+ filePrefix: `${documentTitle.replace(/\s+/g, '_')}_slice_`,
+ onProgress: (p) => setProgress(p),
+ }
+ );
+ } finally {
+ renderer.dispose();
+ }
+ } else {
+ const canvas = getActiveCanvas();
+ if (!canvas) {
+ setIsExporting(false);
+ setProgress(null);
+ return;
+ }
+ zipBytes = await exportWebtoonChapterZip(canvas, {
+ sliceWidth: canvasWidth,
+ sliceHeight,
+ format,
+ quality: quality / 100,
+ filePrefix: `${documentTitle.replace(/\s+/g, '_')}_slice_`,
+ onProgress: (p) => setProgress(p),
+ });
+ }
const zipName = `${documentTitle.replace(/\s+/g, '_')}_slices.zip`;
downloadWebtoonZip(zipBytes, zipName);
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index 34a47be..e8f46cf 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -192,6 +192,7 @@ export class StrokePipeline {
private lastVy: number = 0;
private hasLastRaw: boolean = false;
private stabilizerLevel: number = 0;
+ private zoomScale: number = 1.0;
// Dirty rect tracking (integer bounds in canvas space)
public dirtyRect: DirtyRectBounds = {
@@ -227,6 +228,9 @@ export class StrokePipeline {
}
public setZoomScale(zoom: number): void {
+ if (Number.isFinite(zoom) && zoom > 0) {
+ this.zoomScale = zoom;
+ }
this.stabilizer.setZoomScale(zoom);
}
@@ -338,7 +342,9 @@ export class StrokePipeline {
this.setStabilizerLevel(config.stabilizerLevel);
}
if (config?.zoom !== undefined) {
- this.stabilizer.setZoomScale(config.zoom);
+ this.setZoomScale(config.zoom);
+ } else {
+ this.zoomScale = 1.0;
}
if (config?.sharpCorners !== undefined) {
this.stabilizer.setSharpCorners(config.sharpCorners);
@@ -634,80 +640,95 @@ export class StrokePipeline {
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);
- }
+ let flickCount = 0;
+ let flickPoints: ReturnType<TaperEngine['computeFlickTaper']>['points'] = [];
+ let velX = 0;
+ let velY = 0;
if (options?.enableFlickTaper) {
+ const dwellMs = this.hasLastRaw ? Math.max(0, endTimestampMs - this.lastRawTime) : 0;
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.opacity = fp.alpha;
- 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
+ velX = vel.vx;
+ velY = vel.vy;
+ if (dwellMs <= 32) {
+ const flick = this.taperEngine.computeFlickTaper(
+ this.knotP2.x,
+ this.knotP2.y,
+ this.knotP2.width,
+ this.knotP2.pressure,
+ vel.vx,
+ vel.vy,
+ endTimestampMs,
+ 0,
+ this.zoomScale
);
- this.expandSegmentDirtyRect(flickTailSeg, padExtra);
- if (options.onSegment) {
- options.onSegment(flickTailSeg, false);
- } else if (this.scratchCtx) {
- this.renderSegment(this.scratchCtx, flickTailSeg, false);
- }
+ flickCount = flick.count;
+ flickPoints = flick.points;
+ }
+ }
+
+ if (flickCount > 0) {
+ for (let i = 0; i < flickCount; i++) {
+ const fp = flickPoints[i];
+ const sample = this.scratchSample;
+ sample.x = fp.x;
+ sample.y = fp.y;
+ sample.pressure = fp.pressure;
+ sample.width = fp.width;
+ sample.opacity = fp.alpha;
+ 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 = velX;
+ sample.vy = velY;
+ 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,
+ velX,
+ velY,
+ 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);
+ }
+ } else {
+ // 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);
}
}
}
diff --git a/src/engine/TaperEngine.ts b/src/engine/TaperEngine.ts
index 8e93ded..f9c25fd 100644
--- a/src/engine/TaperEngine.ts
+++ b/src/engine/TaperEngine.ts
@@ -152,14 +152,20 @@ export class TaperEngine {
lastY: number,
lastWidth: number,
lastPressure: number,
- exitVx: number, // px / ms
- exitVy: number, // px / ms
+ exitVx: number, // doc px / ms
+ exitVy: number, // doc px / ms
lastTimestampMs: number,
- angularVelRadPerMs: number = 0
+ angularVelRadPerMs: number = 0,
+ zoomScale: number = 1.0,
+ maxTailLengthDoc?: number
): { points: ExtrapolatedPoint[]; count: number } {
- const exitSpeed = Math.hypot(exitVx, exitVy); // px / ms
+ const exitSpeed = Math.hypot(exitVx, exitVy); // doc px / ms
+ const safeZoom = Number.isFinite(zoomScale) && zoomScale > 0 ? zoomScale : 1.0;
+ // Normalize velocity to screen space so zoomed-out high-DPI canvases (e.g. 6071x8598 at 0.1x)
+ // do not false-trigger flick extrapolation on normal hand speed.
+ const screenSpeed = exitSpeed * safeZoom;
- if (exitSpeed < this.fConfig.minFlickSpeed || lastWidth <= 0.4) {
+ if (screenSpeed < this.fConfig.minFlickSpeed || lastWidth <= 0.4) {
return { points: this.flickPointPool, count: 0 };
}
@@ -167,17 +173,31 @@ export class TaperEngine {
const clampedOmega = Math.max(-0.012, Math.min(0.012, angularVelRadPerMs));
const count = Math.min(this.fConfig.flickPoints, this.flickPointPool.length);
+ const dt = this.fConfig.stepDtMs;
+ const lambda = this.fConfig.decayRate;
+ const dragFactor = Math.exp(-this.fConfig.dragCoefficient * (dt * 0.05));
+
+ // Compute natural extrapolated length and clamp tightly so tips never shoot past liftoff
+ let rawTotalDist = 0;
+ let simSpeed = exitSpeed;
+ for (let i = 0; i < count; i++) {
+ simSpeed *= dragFactor;
+ rawTotalDist += simSpeed * dt;
+ }
+ const defaultMaxTail = Math.min(
+ Math.max(lastWidth * 1.25, 3.0),
+ 14.0 / Math.max(0.05, safeZoom)
+ );
+ const maxTail = maxTailLengthDoc !== undefined ? Math.max(0, maxTailLengthDoc) : defaultMaxTail;
+ const distScale = rawTotalDist > maxTail && rawTotalDist > 1e-6 ? maxTail / rawTotalDist : 1.0;
+
let curX = lastX;
let curY = lastY;
- let curSpeed = exitSpeed;
+ let curSpeed = exitSpeed * distScale;
let curTime = lastTimestampMs;
- const dt = this.fConfig.stepDtMs;
- const lambda = this.fConfig.decayRate;
-
for (let i = 0; i < count; i++) {
// Inertial damping on velocity & gentle curvature continuation (prevents linear kinks on curved flicks)
- const dragFactor = Math.exp(-this.fConfig.dragCoefficient * (dt * 0.05));
curSpeed *= dragFactor;
curAngle += clampedOmega * dt * Math.exp(-0.22 * i);
const stepDist = curSpeed * dt;
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 135cb31..9c0d2b0 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -242,6 +242,7 @@ export function useBrushStrokeSession({
const allStrokePointsRef = useRef<Point[]>([]);
const strokePipelineRef = useRef(new StrokePipeline());
const frameGpuDabsRef = useRef<GpuDab[]>([]);
+ const reusableRegionCanvasRef = useRef<HTMLCanvasElement | null>(null);
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 },
@@ -485,6 +486,75 @@ export function useBrushStrokeSession({
[]
);
+ const resolveLiveAntiAlias = useCallback(
+ (bs: BrushSettings, isMonochrome: boolean, scale: number): number | undefined => {
+ const downscaled = scale < 0.999;
+ if (isMonochrome) {
+ const allowGpuMono = (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false;
+ if (allowGpuMono || downscaled) {
+ return (bs.antiAlias ?? 2) !== 0 ? (bs.antiAlias ?? 2) : 2;
+ }
+ return 0;
+ }
+ if (bs.antiAlias === 0 && downscaled) {
+ return 2;
+ }
+ return bs.antiAlias;
+ },
+ []
+ );
+
+ const buildTouchedTileSpans = useCallback(
+ (
+ sx: number,
+ sy: number,
+ dw: number,
+ dh: number
+ ): Array<{ x: number; y: number; width: number; height: number }> => {
+ if (dw * dh <= TILE_SIZE * TILE_SIZE || touchedTilesRef.current.size === 0) {
+ return [{ x: sx, y: sy, width: dw, height: dh }];
+ }
+ 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];
+ const pushClampedSpan = (s0: number, s1: number) => {
+ const rx = Math.max(sx, s0 * TILE_SIZE);
+ const ry = Math.max(sy, ty * TILE_SIZE);
+ const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
+ const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
+ const rw = rxEnd - rx;
+ const rh = ryEnd - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ };
+ for (let i = 1; i < txList.length; i++) {
+ if (txList[i] <= spanEnd + 1) {
+ spanEnd = txList[i];
+ } else {
+ pushClampedSpan(spanStart, spanEnd);
+ spanStart = txList[i];
+ spanEnd = txList[i];
+ }
+ }
+ pushClampedSpan(spanStart, spanEnd);
+ }
+ return spans.length > 0 ? spans : [{ x: sx, y: sy, width: dw, height: dh }];
+ },
+ []
+ );
+
const buildLiveTexturedOptions = useCallback(
(
bs: BrushSettings,
@@ -496,7 +566,8 @@ export function useBrushStrokeSession({
activeLayer: LayerItem | undefined,
isEraser: boolean,
isBgEraser: boolean,
- isolatedPass: boolean = false
+ isolatedPass: boolean = false,
+ effectiveAntiAlias?: number
): TexturedBrushOptions => ({
size: bs.size,
minSizeFactor: bs.minSizeFactor,
@@ -514,7 +585,7 @@ export function useBrushStrokeSession({
angleDynamics: bs.customTipAngleDynamics,
rotationRandomScale: bs.customTipRotationRandomScale,
hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ antiAlias: effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : bs.antiAlias,
pressureCurve: bs.pressureCurve,
velocityCurve: bs.velocityCurve,
usePressure: bs.usePressure,
@@ -568,7 +639,8 @@ export function useBrushStrokeSession({
isMonochrome: boolean,
canvas: HTMLCanvasElement | null,
activeLayer: LayerItem | undefined,
- isolatedPass: boolean = false
+ isolatedPass: boolean = false,
+ effectiveAntiAlias?: number
): RadialMixingOptions => ({
colorMixing: bs.colorMixing,
perceptualMixing: bs.perceptualMixing,
@@ -592,7 +664,7 @@ export function useBrushStrokeSession({
thicknessVertical: bs.thicknessVertical,
flipH: bs.flipH,
flipV: bs.flipV,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ antiAlias: effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : bs.antiAlias,
angleDynamics: bs.customTipAngleDynamics,
rotationRandomScale: bs.customTipRotationRandomScale,
adjustDensityByGap: bs.adjustDensityByGap,
@@ -700,7 +772,7 @@ export function useBrushStrokeSession({
| null
| undefined;
const draftScale = draftCanvas?.__draftScale ?? 1.0;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
if (bs.customTipImage) {
const tipOptions = buildLiveTexturedOptions(
@@ -708,16 +780,14 @@ export function useBrushStrokeSession({
isMonochrome ? 1.0 : bs.flow ?? 1.0,
bs.spacing ?? 0.08,
strokeHardness,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- true
+ true,
+ liveAA
);
- if (downscaledBinary && tipOptions.antiAlias === 0) {
- tipOptions.antiAlias = 2;
- }
stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
draftCtx,
sStart,
@@ -752,14 +822,12 @@ export function useBrushStrokeSession({
} else {
const radialMixingOptions = buildLiveRadialOptions(
bs,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
- true
+ true,
+ liveAA
);
- if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
- radialMixingOptions.antiAlias = 2;
- }
stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
draftCtx,
sStart,
@@ -784,6 +852,7 @@ export function useBrushStrokeSession({
buildLiveTexturedOptions,
effectiveDraftCanvasRef,
markTouchedTiles,
+ resolveLiveAntiAlias,
]
);
@@ -862,8 +931,7 @@ export function useBrushStrokeSession({
applySelectionCanvasClip(pCtx, selectionRef.current);
let predRem = stampRemainderDistRef.current;
- const predAA =
- isMonochrome && zoomRef.current < 1.0 ? 2 : isMonochrome ? 0 : bs.antiAlias;
+ const predAA = resolveLiveAntiAlias(bs, isMonochrome, zoomRef.current);
const predTipOpts: TexturedBrushOptions | null = bs.customTipImage
? {
size: bs.size,
@@ -940,27 +1008,15 @@ export function useBrushStrokeSession({
: !isPencil && canUseWebGlForRadialBrush(predRadialOpts);
predDabCounterRef.current.count = liveDabCounterRef.current.count;
- const minPredMonoWidth =
- isMonochrome && zoomRef.current < 0.99
- ? 1.35 / Math.max(0.01, zoomRef.current)
- : 0;
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.p0,
seg.c1,
seg.c2,
- p3,
+ seg.p3,
strokeColor,
bs.customTipImage,
predTipOpts,
@@ -972,10 +1028,10 @@ export function useBrushStrokeSession({
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
predRem = drawPencilCubicBezierSegment(
pCtx,
- p0,
+ seg.p0,
seg.c1,
seg.c2,
- p3,
+ seg.p3,
strokeColor,
grade,
isMonochrome ? 1.0 : bs.flow ?? 0.74,
@@ -988,10 +1044,10 @@ export function useBrushStrokeSession({
} else {
predRem = drawSmoothCubicBezierSegment(
pCtx,
- p0,
+ seg.p0,
seg.c1,
seg.c2,
- p3,
+ seg.p3,
strokeColor,
false,
strokeHardness,
@@ -1040,6 +1096,8 @@ export function useBrushStrokeSession({
getTool,
layersRef,
panRef,
+ resolveEffectiveOpacitySensor,
+ resolveLiveAntiAlias,
resolveStrokeColor,
rotationRef,
selectionRef,
@@ -1047,12 +1105,17 @@ export function useBrushStrokeSession({
]
);
- const flushPendingPoints = useCallback(() => {
+ const flushPendingPoints = useCallback((skipDisplayArg?: boolean | number) => {
drawRafIdRef.current = null;
if (!isDrawingRef.current) return;
+ const isSkipDisplay = skipDisplayArg === true;
const pipeline = strokePipelineRef.current;
if (pipeline.getPendingCount() === 0) {
+ if (isSkipDisplay) {
+ latestPredictedRef.current = null;
+ return;
+ }
const predData = latestPredictedRef.current;
latestPredictedRef.current = null;
const vRect = getViewportRect();
@@ -1089,6 +1152,7 @@ export function useBrushStrokeSession({
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 hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
const globalCurve = pipeline.getGlobalPressureCurve();
const hasCustomGlobalCurve = Boolean(
globalCurve && globalCurve.enabled && !isLinearPressureCurve(globalCurve.points)
@@ -1101,37 +1165,33 @@ export function useBrushStrokeSession({
const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
const draftScale = draftCanvas.__draftScale ?? 1.0;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
const liveTipOpts = bs.customTipImage
? buildLiveTexturedOptions(
bs,
isMonochrome ? 1.0 : bs.flow ?? 1.0,
strokeSpacing,
strokeHardness,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- true
+ true,
+ liveAA
)
: null;
- if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
- liveTipOpts.antiAlias = 2;
- }
const liveRadialOpts =
!bs.customTipImage && !isPencil
? buildLiveRadialOptions(
bs,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
- true
+ true,
+ liveAA
)
: null;
- if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
- liveRadialOpts.antiAlias = 2;
- }
const useGpuBatch =
!useWireframeEraser &&
(bs.customTipImage
@@ -1176,7 +1236,7 @@ export function useBrushStrokeSession({
velocityScale,
bs.pressureCurve
);
- if (isMonochrome && width < 1.25) {
+ if (isMonochrome && !hasTaper && width < 1.25) {
width = 1.25;
}
out.pressure = mappedP;
@@ -1310,18 +1370,20 @@ export function useBrushStrokeSession({
onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
}
- if (liveNeedsNotifyRef.current) {
+ if (!isSkipDisplay && liveNeedsNotifyRef.current) {
liveNeedsNotifyRef.current = false;
- activeTileGridRef.current.notifyChange();
+ activeTileGridRef.current.notifyChange(true);
}
const predData = latestPredictedRef.current;
latestPredictedRef.current = null;
- const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0) {
- renderPredictedStroke(predData ? predData.predEvents : [], vRect);
- } else if (isPredictedCanvasDirtyRef.current) {
- clearPredictedCanvas();
+ if (!isSkipDisplay) {
+ const vRect = getViewportRect();
+ if (vRect && allStrokePointsRef.current.length > 0) {
+ renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ } else if (isPredictedCanvasDirtyRef.current) {
+ clearPredictedCanvas();
+ }
}
}, [
activeLayerIdRef,
@@ -1342,6 +1404,7 @@ export function useBrushStrokeSession({
layersRef,
onCollabStrokeChunkRef,
renderPredictedStroke,
+ resolveLiveAntiAlias,
resolveStrokeColor,
]);
@@ -1431,8 +1494,10 @@ export function useBrushStrokeSession({
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 MAX_DRAFT_DIM = 3072;
+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
+ const screenMatchedScale = Math.max(0.05, (zoomRef.current || 1) * dpr * 1.25);
+ const draftScale = Math.min(1.0, screenMatchedScale, 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) {
@@ -1552,7 +1617,8 @@ export function useBrushStrokeSession({
bs.pressureCurve
);
}
- if (isMonochrome && startPoint.width < 1.25) {
+ const hasTaper = Boolean(bs.taper?.useOut || bs.taper?.useIn);
+ if (isMonochrome && !hasTaper && startPoint.width < 1.25) {
startPoint.width = 1.25;
}
@@ -1730,7 +1796,7 @@ export function useBrushStrokeSession({
} else {
const liveColor =
(isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
const gpuBatch = frameGpuDabsRef.current;
gpuBatch.length = 0;
@@ -1740,16 +1806,14 @@ export function useBrushStrokeSession({
isMonochrome ? 1.0 : bs.flow ?? 1.0,
strokeSpacing,
strokeHardness,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- true
+ true,
+ liveAA
);
- if (downscaledBinary && tipOptions.antiAlias === 0) {
- tipOptions.antiAlias = 2;
- }
const useGpu = canUseWebGlForTexturedBrush(tipOptions);
drawTexturedDot(
draftCtx,
@@ -1783,14 +1847,12 @@ export function useBrushStrokeSession({
} else {
const radialMixingOptions = buildLiveRadialOptions(
bs,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
- true
+ true,
+ liveAA
);
- if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
- radialMixingOptions.antiAlias = 2;
- }
const useGpu = canUseWebGlForRadialBrush(radialMixingOptions);
drawDot(
draftCtx,
@@ -1837,37 +1899,33 @@ export function useBrushStrokeSession({
const lineSeg = pipeline
.getSplineGenerator()
.generateCornerSegment(allStrokePointsRef.current[0], startPoint);
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
const liveTipOpts = bs.customTipImage
? buildLiveTexturedOptions(
bs,
isMonochrome ? 1.0 : bs.flow ?? 1.0,
strokeSpacing,
strokeHardness,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
isEraser,
isBgEraser,
- true
+ true,
+ liveAA
)
: null;
- if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
- liveTipOpts.antiAlias = 2;
- }
const liveRadialOpts =
!bs.customTipImage && !isPencil
? buildLiveRadialOptions(
bs,
- downscaledBinary ? false : isMonochrome,
+ isMonochrome,
canvas,
activeLayer,
- true
+ true,
+ liveAA
)
: null;
- if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
- liveRadialOpts.antiAlias = 2;
- }
const useGpuLine =
!useWireframeEraser &&
(bs.customTipImage
@@ -1925,7 +1983,7 @@ export function useBrushStrokeSession({
draftCanvas.__draftHasContent = true;
draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- activeTileGridRef.current.notifyChange();
+ activeTileGridRef.current.notifyChange(true);
liveNeedsNotifyRef.current = false;
if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
@@ -1966,6 +2024,7 @@ export function useBrushStrokeSession({
markTouchedTiles,
onCollabStrokeStartRef,
panRef,
+ resolveLiveAntiAlias,
resolveStrokeColor,
rotationRef,
rulerRef,
@@ -2176,7 +2235,7 @@ export function useBrushStrokeSession({
cancelAnimationFrame(drawRafIdRef.current);
drawRafIdRef.current = null;
}
- flushPendingPoints();
+ flushPendingPoints(true);
const bs = getBrushSettings();
const dims = dimensionsRef.current;
@@ -2218,7 +2277,8 @@ export function useBrushStrokeSession({
Boolean(bs.taper?.useOut);
let addedFlickPoints = false;
- pipeline.finalizeStroke(e.timeStamp || performance.now(), {
+ const tailSegments: CubicBezierSegment[] = [];
+ pipeline.finalizeStroke(e.nativeEvent?.timeStamp || e.timeStamp || performance.now(), {
enableFlickTaper,
dirtyPadExtra: tailPadExtra,
onPoint: (sample) => {
@@ -2236,6 +2296,12 @@ export function useBrushStrokeSession({
});
},
onSegment: (seg) => {
+ tailSegments.push({
+ p0: { ...seg.p0 },
+ c1: { ...seg.c1 },
+ c2: { ...seg.c2 },
+ p3: { ...seg.p3 },
+ });
const segPad = Math.ceil(
Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
);
@@ -2296,6 +2362,7 @@ export function useBrushStrokeSession({
const allPoints = allStrokePointsRef.current;
let createdVectorStroke: VectorStroke | undefined;
+ let postPresentWork: (() => void) | null = null;
if (allPoints.length > 0 && !isMaskModeRef.current) {
const finalPt = allPoints[allPoints.length - 1];
@@ -2366,7 +2433,10 @@ export function useBrushStrokeSession({
const dirtyRect = clampedBakeRect;
const toolForHistory =
currentTool === 'eraser' ? 'eraser' : isPencil ? 'pencil' : 'brush';
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const targetFormat: TileFormat =
+ isMonochrome && !isBackgroundLayerId(currentLayerId)
+ ? 'monochrome-1bit'
+ : 'color-32bit';
const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
const activeSelection = selectionRef.current;
@@ -2568,156 +2638,420 @@ export function useBrushStrokeSession({
);
});
} else {
- const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect);
- const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
- if (regionCanvas && rCtx) {
- const beforeSelectionData = activeSelection?.mask
- ? rCtx.getImageData(0, 0, dw, dh)
- : null;
-
- rCtx.save();
- rCtx.translate(-sx, -sy);
- rCtx.beginPath();
- rCtx.rect(sx, sy, dw, dh);
- rCtx.clip();
- applySelectionCanvasClip(rCtx, activeSelection);
-
- const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
- bs,
- isMonochrome,
- isEraser
- );
- const bakeBs: BrushSettings =
- effectiveOpacitySensor && !bs.opacitySensor
- ? { ...bs, opacitySensor: effectiveOpacitySensor }
- : bs;
-
- const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
- const bakeSampler =
- bakeBs.colorMixing && !isEraser
- ? new LayerPixelSampler(canvas || dims, currentLayerId, grid)
- : undefined;
+ const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
+ const draftScale = draftCanvas?.__draftScale ?? 0;
+ const draftDocRect = draftCanvas?.__draftDocRect;
+ const compositeOp: 'source-over' | 'destination-out' | 'source-atop' =
+ (isEraser && !isBgEraser) || bs.isTransparentInk
+ ? 'destination-out'
+ : activeLayer?.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+ const monoOpts =
+ targetFormat === 'monochrome-1bit'
+ ? {
+ threshold: activeLayer?.monoThreshold ?? 128,
+ expressBlack: activeLayer?.monoExpressBlack ?? true,
+ expressWhite: activeLayer?.monoExpressWhite ?? true,
+ }
+ : undefined;
+ const selMaskOpts = activeSelection?.mask
+ ? { mask: activeSelection.mask, bounds: activeSelection.bounds }
+ : null;
+
+ const canDirectDraftCommit = Boolean(
+ draftCanvas &&
+ draftCtx &&
+ draftScale >= 0.999 &&
+ draftDocRect &&
+ !hasWetEdge &&
+ !bs.colorMixing &&
+ (bs.postCorrection ?? 0) === 0 &&
+ !shouldTaper &&
+ sx >= draftDocRect.x &&
+ sy >= draftDocRect.y &&
+ sx + dw <= draftDocRect.x + draftCanvas.width &&
+ sy + dh <= draftDocRect.y + draftCanvas.height
+ );
+
+ if (canDirectDraftCommit && draftCanvas && draftCtx && draftDocRect) {
+ // Fast path: 1:1 draft canvas already has the rendered stroke; emit only sealed tail segments
+ if (tailSegments.length > 0) {
+ 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 liveAA = resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+ const liveTipOpts = bs.customTipImage
+ ? buildLiveTexturedOptions(
+ bs,
+ isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ )
+ : null;
+ const liveRadialOpts =
+ !bs.customTipImage && !isPencil
+ ? buildLiveRadialOptions(
+ bs,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ true,
+ liveAA
+ )
+ : null;
+ const useGpuTail = bs.customTipImage
+ ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
+ : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts));
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+
+ for (let i = 0; i < tailSegments.length; i++) {
+ emitLiveSegment(
+ draftCtx,
+ tailSegments[i],
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ false,
+ canvas,
+ activeLayer,
+ useGpuTail ? gpuBatch : undefined
+ );
+ }
+
+ if (useGpuTail && 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) {
+ for (let i = 0; i < tailSegments.length; i++) {
+ emitLiveSegment(
+ draftCtx,
+ tailSegments[i],
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ false,
+ canvas,
+ activeLayer,
+ undefined
+ );
+ }
+ }
+ gpuBatch.length = 0;
+ }
+ }
+
+ const beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ const spans = buildTouchedTileSpans(sx, sy, dw, dh);
+ const draftOriginX = Math.round(draftDocRect.x);
+ const draftOriginY = Math.round(draftDocRect.y);
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const spanData = draftCtx.getImageData(
+ sp.x - draftOriginX,
+ sp.y - draftOriginY,
+ sp.width,
+ sp.height
+ );
+ grid.compositeStrokeToTiles({
+ layerId: currentLayerId,
+ strokeData: spanData,
+ destX: sp.x,
+ destY: sp.y,
+ format: targetFormat,
+ compositeOp,
+ opacity: bs.opacity ?? 1.0,
+ monochrome: monoOpts,
+ selectionMask: selMaskOpts,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+
+ postPresentWork = () => {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
+ }
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
+ }
+ }
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ };
+ } else if (!bs.colorMixing) {
+ // Fast isolated 1:1 re-bake: never allocates/unpacks existing tiles via createRegionCanvas
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = get2DContext(bakeCanvas);
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ bCtx.beginPath();
+ bCtx.rect(sx, sy, dw, dh);
+ bCtx.clip();
+ applySelectionCanvasClip(bCtx, activeSelection);
+
+ const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
+ bs,
+ isMonochrome,
+ isEraser
+ );
+ const bakeBs: BrushSettings =
+ effectiveOpacitySensor && !bs.opacitySensor
+ ? { ...bs, opacitySensor: effectiveOpacitySensor }
+ : bs;
+ const allowGpuMonoBake =
+ isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
- if (!needsIsolatedBake) {
renderCompleteStroke(
- rCtx,
+ bCtx,
allPoints,
- bakeBs,
- currentTool,
+ {
+ ...bakeBs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
effectiveMode,
isBgEraser,
canvas || undefined,
- Boolean(activeLayer?.alphaLocked),
- bakeSampler
+ false,
+ undefined,
+ allowGpuMonoBake
);
- } else {
- rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bakeBs.isTransparentInk) {
- rCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- rCtx.globalCompositeOperation = 'source-atop';
- } else {
- rCtx.globalCompositeOperation = 'source-over';
+ 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);
}
- 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 beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ const spans = buildTouchedTileSpans(sx, sy, dw, dh);
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const spanData = bCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
+ grid.compositeStrokeToTiles({
+ layerId: currentLayerId,
+ strokeData: spanData,
+ destX: sp.x,
+ destY: sp.y,
+ format: targetFormat,
+ compositeOp,
+ opacity: bakeBs.opacity ?? 1.0,
+ monochrome: monoOpts,
+ selectionMask: selMaskOpts,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
+ }
+
+ postPresentWork = () => {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
+ }
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
+ }
+ }
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ };
+ }
+ } else {
+ // Wet color-mixing path requires existing layer pixels on the same canvas
+ const canPoolRegion = dw <= 2048 && dh <= 2048;
+ let pooledCanvas: HTMLCanvasElement | null = null;
+ if (canPoolRegion && typeof document !== 'undefined') {
+ if (!reusableRegionCanvasRef.current) {
+ reusableRegionCanvasRef.current = document.createElement('canvas');
+ }
+ pooledCanvas = reusableRegionCanvasRef.current;
+ }
+ const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect, pooledCanvas);
+ const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
+ if (regionCanvas && rCtx) {
+ const beforeSelectionData = activeSelection?.mask
+ ? rCtx.getImageData(0, 0, dw, dh)
+ : null;
+
+ rCtx.save();
+ rCtx.translate(-sx, -sy);
+ rCtx.beginPath();
+ rCtx.rect(sx, sy, dw, dh);
+ rCtx.clip();
+ applySelectionCanvasClip(rCtx, activeSelection);
+
+ const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
+ bs,
+ isMonochrome,
+ isEraser
+ );
+ const bakeBs: BrushSettings =
+ effectiveOpacitySensor && !bs.opacitySensor
+ ? { ...bs, opacitySensor: effectiveOpacitySensor }
+ : bs;
+
+ const allowGpuMonoBake =
+ isMonochrome && (bakeBs.antiAlias ?? 2) !== 0 && bakeBs.useGpu !== false;
+ const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+ const bakeSampler = !isEraser
+ ? new LayerPixelSampler(canvas || dims, currentLayerId, grid)
+ : undefined;
+
+ if (!needsIsolatedBake) {
renderCompleteStroke(
- bCtx,
+ rCtx,
allPoints,
- {
- ...bakeBs,
- opacity: 1.0,
- isTransparentInk: false,
- wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
- },
- isEraser && !isBgEraser ? 'brush' : currentTool,
+ bakeBs,
+ currentTool,
effectiveMode,
isBgEraser,
canvas || undefined,
- false,
- bakeSampler
+ Boolean(activeLayer?.alphaLocked),
+ bakeSampler,
+ allowGpuMonoBake
);
- 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
+ } else {
+ rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
+ rCtx.globalCompositeOperation = compositeOp;
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = get2DContext(bakeCanvas);
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bakeBs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ canvas || undefined,
+ false,
+ bakeSampler,
+ allowGpuMonoBake
);
- bCtx.putImageData(bakeImg, 0, 0);
- }
-
- rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
-
- rCtx.restore();
-
- if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = rCtx.getImageData(0, 0, dw, dh);
- applySelectionMaskToImageData(
- beforeSelectionData,
- fullAfter,
- sx,
- sy,
- activeSelection
- );
- rCtx.putImageData(fullAfter, 0, 0);
- }
+ 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);
+ }
- 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);
+ rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
- 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];
- const pushClampedSpan = (s0: number, s1: number) => {
- const rx = Math.max(sx, s0 * TILE_SIZE);
- const ry = Math.max(sy, ty * TILE_SIZE);
- const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
- const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
- const rw = rxEnd - rx;
- const rh = ryEnd - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
- };
- for (let i = 1; i < txList.length; i++) {
- if (txList[i] <= spanEnd + 1) {
- spanEnd = txList[i];
- } else {
- pushClampedSpan(spanStart, spanEnd);
- spanStart = txList[i];
- spanEnd = txList[i];
- }
- }
- pushClampedSpan(spanStart, spanEnd);
+ rCtx.restore();
+
+ if (beforeSelectionData && activeSelection?.mask) {
+ const fullAfter = rCtx.getImageData(0, 0, dw, dh);
+ applySelectionMaskToImageData(
+ beforeSelectionData,
+ fullAfter,
+ sx,
+ sy,
+ activeSelection
+ );
+ rCtx.putImageData(fullAfter, 0, 0);
}
+ const spans = buildTouchedTileSpans(sx, sy, dw, dh);
const beforeSnapshot = new Map<
string,
{ format: TileFormat; data: Uint8Array | null }
@@ -2729,7 +3063,7 @@ export function useBrushStrokeSession({
if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
}
const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
- if (isMonochrome) {
+ if (targetFormat === 'monochrome-1bit') {
binarizeImageDataBuffer(
spanData,
activeLayer?.monoThreshold ?? 128,
@@ -2740,59 +3074,33 @@ export function useBrushStrokeSession({
grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
}
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas
- );
- });
- } else {
- const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = rCtx.getImageData(0, 0, dw, dh);
- if (isMonochrome) {
- binarizeImageDataBuffer(
- afterData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
+ if (!canPoolRegion) {
+ releaseTemporaryCanvas(regionCanvas);
}
- grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- const tileDeltas = grid.computeDeltasFromSnapshot(
- beforeSnapshot,
- currentLayerId,
- dirtyRect
- );
-
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- label,
- null,
- null,
- currentLayerId,
- dirtyRect,
- tileDeltas
- );
- });
- }
- releaseTemporaryCanvas(regionCanvas);
-
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
- }
+ postPresentWork = () => {
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
+ }
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
+ }
+ }
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ };
}
}
}
@@ -2822,6 +3130,7 @@ export function useBrushStrokeSession({
clearPredictedCanvas();
grid.notifyChange(true);
+ postPresentWork?.();
if (currentStrokeIdRef.current) {
onCollabStrokeFinishRef.current?.(
@@ -2876,11 +3185,15 @@ export function useBrushStrokeSession({
[
activeLayerIdRef,
activeTileGridRef,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
+ buildTouchedTileSpans,
clearPredictedCanvas,
colorModeRef,
dimensionsRef,
effectiveDraftCanvasRef,
emitConstraintAxisChange,
+ emitLiveSegment,
enqueueHistoryTask,
flushPendingPoints,
getBrushSettings,
@@ -2898,6 +3211,8 @@ export function useBrushStrokeSession({
onUpdateLayerThumbnail,
onUpdateMaskThumbnailRef,
pushHistoryStep,
+ resolveEffectiveOpacitySensor,
+ resolveLiveAntiAlias,
resolveStrokeColor,
selectionRef,
]
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index c6aeeb9..fabf814 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -2221,9 +2221,10 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
grid = session.tileGrid;
}
+ const restoredFormats = doc.tileGrid ? doc.tileGrid.getAllLayerFormats() : null;
if (!skipIngest) {
if (doc.tileGrid && doc.tileGrid !== grid) {
- grid.restoreFromSnapshot(doc.tileGrid.getAllTiles(), doc.tileGrid.getAllLayerFormats());
+ grid.restoreFromSnapshot(doc.tileGrid.getAllTiles(), restoredFormats || undefined);
doc.tileGrid.clearAll();
} else if (!doc.tileGrid) {
grid.clearAll();
@@ -2238,8 +2239,15 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
for (const l of doc.layers) {
if (hasTileBackedLayer(l)) {
- const isMono = l.expressionColor === 'monochrome';
- grid.setLayerFormat(l.id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const existingFormat = restoredFormats?.get(l.id);
+ const inferredFormat =
+ existingFormat ??
+ (l.expressionColor === 'monochrome'
+ ? 'monochrome-1bit'
+ : l.expressionColor === 'gray'
+ ? 'grayscale-8bit'
+ : 'color-32bit');
+ grid.setLayerFormat(l.id, inferredFormat);
grid.markLayerIngested(l.id);
}
}
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 3750a20..ccb1510 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -860,6 +860,14 @@ export interface NewCanvasOptions {
defaultFrequency?: number;
}
+export interface SoraTimelapseMetadata {
+ enabled: boolean;
+ frameCount: number;
+ fps?: number;
+ resolution?: '720p' | '1080p';
+ aspectRatio?: 'original' | '16:9' | '9:16' | '1:1';
+}
+
export interface LoadedDocument {
name: string;
dimensions: CanvasDimensions;
@@ -867,6 +875,10 @@ export interface LoadedDocument {
layers: LayerItem[];
layerCanvases?: Map<string, HTMLCanvasElement>;
tileGrid?: SparseTileGrid;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: SoraTimelapseMetadata | null;
+ previewDataUrl?: string;
}
export type CmykStandard = 'japan-color-2001' | 'us-web-coated-swop' | 'iso-coated-v2';
diff --git a/src/utils/__tests__/compositor.test.ts b/src/utils/__tests__/compositor.test.ts
index 592d9c1..248e319 100644
--- a/src/utils/__tests__/compositor.test.ts
+++ b/src/utils/__tests__/compositor.test.ts
@@ -1390,6 +1390,102 @@ describe('Unified GPU Viewport Compositor', () => {
expect(COMPOSITOR_FRAGMENT_SHADER).toContain('step(0.5, finalColor.a)');
expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain('step(0.5, finalColor.a)');
});
+
+ it('renders 6071x8598 manga canvas with zero empty-tile LOD thrashing, fast solid-tile LOD pyramid, and texSubImage2D draft updates', () => {
+ const { canvas, calls, glSpecErrors } = createMockWebGL2Context({ maxArrayLayers: 512 });
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+ const dims = { width: 6071, height: 8598, dpi: 600 };
+
+ // Solid white background (816 LOD 0 tiles) + completely empty ink layer
+ grid.fillLayerSolidWhite('layer-bg', dims.width, dims.height, 'color-32bit');
+ grid.setLayerFormat('layer-ink', 'monochrome-1bit');
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-ink',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ expressionColor: 'monochrome',
+ },
+ {
+ id: 'layer-bg',
+ name: 'Paper',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ // Fit-to-screen zoom (~0.10 -> LOD 3)
+ const fitTransform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 0.1, rotation: 0 };
+ const t0 = performance.now();
+ compositor.render(layers, fitTransform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-ink',
+ });
+ const firstFrameMs = performance.now() - t0;
+
+ // Empty ink layer must have 0 tiles and 0 populated LOD entries
+ expect(grid.hasLayerTiles('layer-ink')).toBe(false);
+ expect(grid.hasPopulatedLodTile('layer-ink', 0, 0, 3)).toBe(false);
+ // Solid-tile fast path should build LOD 3 for 6071x8598 rapidly
+ expect(firstFrameMs).toBeLessThan(250);
+
+ // 30 consecutive live-draft frames on empty ink layer at zoom = 1.0 must reuse texSubImage2D & skip mipmaps
+ const mockDraftCanvas = {
+ width: 512,
+ height: 512,
+ __draftHasContent: true,
+ __draftVersion: 1,
+ __draftSpace: 'document',
+ __draftDocRect: { x: 0, y: 0, width: 512, height: 512 },
+ } as unknown as HTMLCanvasElement;
+
+ const zoom1Transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+ compositor.render(layers, zoom1Transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-ink',
+ activeDraftLayerId: 'layer-ink',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 1,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ calls.length = 0;
+ for (let v = 2; v <= 10; v++) {
+ (mockDraftCanvas as any).__draftVersion = v;
+ compositor.render(layers, zoom1Transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-ink',
+ activeDraftLayerId: 'layer-ink',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: v,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+ }
+
+ expect(calls.filter((c) => c.name === 'texSubImage2D').length).toBe(9);
+ expect(calls.filter((c) => c.name === 'texImage2D').length).toBe(0);
+ expect(calls.filter((c) => c.name === 'generateMipmap').length).toBe(0);
+ expect(glSpecErrors).toEqual([]);
+ // Instanced fragment shader uses single hardware texture() fetch instead of 4x manual texelFetch
+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain('texture(u_tileArrayTexture, vec3(v_texCoord, v_sliceIndex))');
+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).not.toContain('texelFetch');
+ });
});
});
diff --git a/src/utils/__tests__/soraV2AndGpuExport.test.ts b/src/utils/__tests__/soraV2AndGpuExport.test.ts
new file mode 100644
index 0000000..6955e9e
--- /dev/null
+++ b/src/utils/__tests__/soraV2AndGpuExport.test.ts
@@ -0,0 +1,870 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { zipSync, unzipSync } from 'fflate';
+import {
+ AnimationTimeline,
+ LayerItem,
+ TextLayerData,
+ VectorStroke,
+} from '../../types/editor';
+import type { PerspectiveRuler } from '../../types/perspective';
+import { createDefaultSpeechBalloon } from '../balloonEngine';
+import { createRectFrame } from '../frameEngine';
+import {
+ SparseTileGrid,
+ InMemoryScratchDiskDriver,
+ BYTES_1BIT,
+ BYTES_8BIT,
+ BYTES_32BIT,
+ setPixel1Bit,
+ getPixel1Bit,
+} from '../tileEngine';
+import { ViewportCompositor } from '../compositor';
+import {
+ buildGpuExportTilePlan,
+ buildSoraProjectPayload,
+ compositeCanvas,
+ compositeCanvasAsync,
+ computeMaxLayerStyleMargin,
+ createDocumentRegionRenderer,
+ exportImage,
+ extractSoraPreview,
+ isSoraV2Bytes,
+ parseSoraProject,
+ SaveProgress,
+ serializeDocument,
+ serializeSoraV2,
+} from '../saveManager';
+
+function createMockMaskCanvas(width: number, height: number, fillFn: (x: number, y: number) => number): HTMLCanvasElement {
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const v = fillFn(x, y);
+ const off = (y * width + x) * 4;
+ rgba[off] = v;
+ rgba[off + 1] = v;
+ rgba[off + 2] = v;
+ rgba[off + 3] = 255;
+ }
+ }
+ return {
+ width,
+ height,
+ getContext: (type: string) =>
+ type === '2d'
+ ? {
+ getImageData: () => ({ data: rgba, width, height }),
+ }
+ : null,
+ } as unknown as HTMLCanvasElement;
+}
+
+describe('.sora v2 Binary Format & Round-Trip Serialization', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('round-trips 1-bit, 8-bit, 32-bit native SparseTileGrid tiles, masks, vectors, text, balloons, frames, perspective, animation, and timelapse without toDataURL', async () => {
+ const grid = new SparseTileGrid();
+
+ // 1. 1-bit monochrome ink tile at (2, 3)
+ const monoTile = grid.getOrCreateTile('layer-mono', 2, 3, 'monochrome-1bit', 0);
+ setPixel1Bit(monoTile.data!, 5, 7, 1);
+ setPixel1Bit(monoTile.data!, 200, 123, 1);
+ monoTile.version = 9;
+ grid.setLayerFormat('layer-mono', 'monochrome-1bit');
+
+ // 2. 8-bit grayscale tone tile at (0, 1)
+ const grayTile = grid.getOrCreateTile('layer-gray', 0, 1, 'grayscale-8bit', 0);
+ grayTile.data![0] = 42;
+ grayTile.data![256 * 10 + 15] = 199;
+ grayTile.data![BYTES_8BIT - 1] = 255;
+ grayTile.version = 4;
+ grid.setLayerFormat('layer-gray', 'grayscale-8bit');
+
+ // 3. 32-bit RGBA color tile at (1, 0) + negative/offset tile at (4, 5)
+ const colorTile = grid.getOrCreateTile('layer-color', 1, 0, 'color-32bit', 0);
+ colorTile.data![0] = 220;
+ colorTile.data![1] = 40;
+ colorTile.data![2] = 90;
+ colorTile.data![3] = 255;
+ colorTile.data![BYTES_32BIT - 4] = 12;
+ colorTile.data![BYTES_32BIT - 3] = 34;
+ colorTile.data![BYTES_32BIT - 2] = 56;
+ colorTile.data![BYTES_32BIT - 1] = 180;
+ colorTile.version = 12;
+ grid.setLayerFormat('layer-color', 'color-32bit');
+
+ const vectorStroke: VectorStroke = {
+ id: 'vs-1',
+ layerId: 'layer-vector',
+ tool: 'brush',
+ knots: [
+ { x: 10, y: 20, pressure: 0.7, width: 5, timestamp: 1000 },
+ { x: 120, y: 180, pressure: 0.9, width: 8, timestamp: 1016 },
+ ],
+ color: '#112233',
+ baseWidth: 6,
+ opacity: 0.95,
+ bounds: { minX: 10, minY: 20, maxX: 120, maxY: 180 },
+ };
+
+ const textData: TextLayerData = {
+ x: 300,
+ y: 220,
+ text: 'SORA V2!\nLINE TWO',
+ fontFamily: 'Anime Ace',
+ fontSize: 36,
+ lineSpacing: 1.4,
+ bold: true,
+ italic: false,
+ align: 'center',
+ color: '#000000',
+ outline: true,
+ outlineColor: '#ffffff',
+ outlineWidth: 3,
+ writingMode: 'vertical-rl',
+ };
+
+ const balloon = createDefaultSpeechBalloon(500, 400, 260, 180, 'jagged-flash');
+ balloon.text = 'BOOM!';
+ balloon.vertical = true;
+ balloon.tail.tip = { x: 460, y: 650, pressure: 1, width: 4 };
+
+ const frame = createRectFrame('frame-folder-1', 80, 80, 1600, 2200, {
+ dpi: 600,
+ borderWidth: 8,
+ gutterVerticalPx: 70,
+ gutterHorizontalPx: 110,
+ });
+
+ const maskCanvas = createMockMaskCanvas(16, 8, (x, y) => (x + y * 16) % 256);
+
+ const perspectiveRuler: PerspectiveRuler = {
+ id: 'persp-1',
+ type: '2-point',
+ enabled: true,
+ locked: false,
+ snapEnabled: true,
+ horizonAngle: 0,
+ guideRayCount: 8,
+ vps: [
+ { id: 'vp1', x: 200, y: 900, label: 'VP1', color: '#8b5cf6' },
+ { id: 'vp2', x: 1800, y: 900, label: 'VP2', color: '#06b6d4' },
+ ],
+ grid: {
+ enabled: true,
+ density: 16,
+ plane: 'ground',
+ opacity: 0.3,
+ },
+ };
+
+ const animationTimeline: AnimationTimeline = {
+ fps: 24,
+ totalFrames: 48,
+ currentFrame: 5,
+ cels: {
+ 1: 'layer-mono',
+ 5: 'layer-color',
+ },
+ onionSkin: {
+ enabled: true,
+ prevFrames: 2,
+ nextFrames: 2,
+ prevTint: '#3b82f6',
+ nextTint: '#10b981',
+ opacity: 0.45,
+ },
+ };
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-adj',
+ name: 'Curves Adj',
+ type: 'adjustment',
+ visible: true,
+ opacity: 0.8,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ adjustmentData: {
+ type: 'levels',
+ blackPoint: 12,
+ gamma: 1.15,
+ whitePoint: 244,
+ },
+ },
+ {
+ id: 'layer-text',
+ name: 'SORA V2!',
+ type: 'text',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ textData,
+ },
+ {
+ id: 'layer-balloon',
+ name: 'Balloon',
+ type: 'balloon',
+ visible: true,
+ opacity: 0.9,
+ blendMode: 'normal',
+ locked: false,
+ parentId: 'frame-folder-1',
+ balloonData: balloon,
+ },
+ {
+ id: 'frame-folder-1',
+ name: 'Panel 1',
+ type: 'frame-folder',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ comicFrames: [frame],
+ },
+ {
+ id: 'layer-vector',
+ name: 'Vectors',
+ type: 'vector',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: 'frame-folder-1',
+ vectorStrokes: [vectorStroke],
+ },
+ {
+ id: 'layer-mono',
+ name: 'Inks 1-bit',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'linear-burn',
+ locked: false,
+ parentId: 'frame-folder-1',
+ expressionColor: 'monochrome',
+ monoThreshold: 140,
+ monoExpressBlack: true,
+ monoExpressWhite: false,
+ layerColorEnabled: true,
+ layerColor: '#1c73c2',
+ layerSubColor: '#ffffff',
+ maskCanvas,
+ maskEnabled: true,
+ maskLinked: true,
+ },
+ {
+ id: 'layer-gray',
+ name: 'Screentone 8-bit',
+ type: 'raster',
+ visible: true,
+ opacity: 0.85,
+ blendMode: 'multiply',
+ locked: false,
+ parentId: 'frame-folder-1',
+ expressionColor: 'gray',
+ toneEnabled: true,
+ toneFrequency: 65,
+ toneAngle: 45,
+ toneDotShape: 'euclidean',
+ toneDensity: 40,
+ toneDensityType: 'image',
+ },
+ {
+ id: 'layer-color',
+ name: 'Glow FX 32-bit',
+ type: 'raster',
+ visible: true,
+ opacity: 0.9,
+ blendMode: 'add-glow',
+ locked: false,
+ parentId: null,
+ styles: {
+ stroke: { enabled: true, size: 4, color: '#ff0044', position: 'outside', opacity: 1 },
+ dropShadow: { enabled: true, color: '#000000', opacity: 0.6, angle: 120, distance: 12, blur: 16, spread: 10 },
+ outerGlow: { enabled: true, color: '#00ffff', opacity: 0.75, blur: 20, spread: 5 },
+ },
+ },
+ ];
+
+ const progressLog: SaveProgress[] = [];
+ const serialized = await serializeSoraV2(
+ {
+ name: 'Manga Page 01',
+ dimensions: { width: 7016, height: 9921, dpi: 600 },
+ colorMode: 'color',
+ layers,
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ perspectiveRuler,
+ animationTimeline,
+ timelapse: { enabled: true, frameCount: 312, fps: 30, resolution: '1080p', aspectRatio: 'original' },
+ onProgress: (p) => progressLog.push(p),
+ },
+ grid
+ );
+
+ // Must be compact ZIP binary starting with PK\x03\x04
+ expect(isSoraV2Bytes(serialized.bytes)).toBe(true);
+ expect(serialized.bytes[0]).toBe(0x50);
+ expect(serialized.bytes[1]).toBe(0x4b);
+
+ // Inspect ZIP structure directly: manifest + native tile files + mask file
+ const entries = unzipSync(serialized.bytes);
+ expect(entries['manifest.json']).toBeDefined();
+ expect(entries['tiles/layer-mono/2_3.bin']).toBeDefined();
+ expect(entries['tiles/layer-gray/0_1.bin']).toBeDefined();
+ expect(entries['tiles/layer-color/1_0.bin']).toBeDefined();
+ expect(entries['masks/layer-mono.bin']).toBeDefined();
+
+ // Progress indicator reached 100%
+ expect(progressLog.length).toBeGreaterThanOrEqual(3);
+ expect(progressLog[progressLog.length - 1].phase).toBe('done');
+ expect(progressLog[progressLog.length - 1].percent).toBe(100);
+
+ // Round-trip parse with auto-detection
+ const parsed = await parseSoraProject(serialized.bytes);
+ expect(parsed.format).toBe('v2');
+ expect(parsed.version).toBe('2.0');
+ expect(parsed.name).toBe('Manga Page 01');
+ expect(parsed.dimensions).toEqual({ width: 7016, height: 9921, dpi: 600 });
+ expect(parsed.layers).toHaveLength(8);
+ expect(parsed.tileGrid).toBeDefined();
+
+ // Verify 1-bit tile exact binary round-trip
+ const restoredMono = parsed.tileGrid!.getTile('layer-mono', 2, 3, 0);
+ expect(restoredMono).toBeDefined();
+ expect(restoredMono!.format).toBe('monochrome-1bit');
+ expect(restoredMono!.data!.byteLength).toBe(BYTES_1BIT);
+ expect(getPixel1Bit(restoredMono!.data!, 5, 7)).toBe(1);
+ expect(getPixel1Bit(restoredMono!.data!, 200, 123)).toBe(1);
+ expect(getPixel1Bit(restoredMono!.data!, 0, 0)).toBe(0);
+ expect(restoredMono!.version).toBe(9);
+
+ // Verify 8-bit tile exact binary round-trip
+ const restoredGray = parsed.tileGrid!.getTile('layer-gray', 0, 1, 0);
+ expect(restoredGray).toBeDefined();
+ expect(restoredGray!.format).toBe('grayscale-8bit');
+ expect(restoredGray!.data!.byteLength).toBe(BYTES_8BIT);
+ expect(restoredGray!.data![0]).toBe(42);
+ expect(restoredGray!.data![256 * 10 + 15]).toBe(199);
+ expect(restoredGray!.data![BYTES_8BIT - 1]).toBe(255);
+ expect(restoredGray!.version).toBe(4);
+
+ // Verify 32-bit tile exact binary round-trip
+ const restoredColor = parsed.tileGrid!.getTile('layer-color', 1, 0, 0);
+ expect(restoredColor).toBeDefined();
+ expect(restoredColor!.format).toBe('color-32bit');
+ expect(restoredColor!.data!.byteLength).toBe(BYTES_32BIT);
+ expect(Array.from(restoredColor!.data!.subarray(0, 4))).toEqual([220, 40, 90, 255]);
+ expect(Array.from(restoredColor!.data!.subarray(BYTES_32BIT - 4))).toEqual([12, 34, 56, 180]);
+ expect(restoredColor!.version).toBe(12);
+
+ // Verify binary mask round-trip
+ const restoredMask = parsed.masksBinary?.get('layer-mono');
+ expect(restoredMask).toBeDefined();
+ expect(restoredMask!.width).toBe(16);
+ expect(restoredMask!.height).toBe(8);
+ expect(restoredMask!.data[0]).toBe(0);
+ expect(restoredMask!.data[17]).toBe(17);
+ expect(restoredMask!.data[127]).toBe(127);
+
+ // Verify non-destructive vector, text, balloon, frame, styles, screentone, perspective, animation, timelapse
+ expect(parsed.layers.find((l) => l.id === 'layer-vector')?.vectorStrokes).toEqual([vectorStroke]);
+ expect(parsed.layers.find((l) => l.id === 'layer-text')?.textData).toEqual(textData);
+ expect(parsed.layers.find((l) => l.id === 'layer-balloon')?.balloonData?.text).toBe('BOOM!');
+ expect(parsed.layers.find((l) => l.id === 'frame-folder-1')?.comicFrames?.[0].polygon).toEqual(frame.polygon);
+ expect(parsed.layers.find((l) => l.id === 'layer-color')?.styles?.dropShadow?.distance).toBe(12);
+ expect(parsed.layers.find((l) => l.id === 'layer-gray')?.toneFrequency).toBe(65);
+ expect(parsed.perspectiveRuler).toEqual(perspectiveRuler);
+ expect(parsed.animationTimeline).toEqual(animationTimeline);
+ expect(parsed.timelapse).toEqual({
+ enabled: true,
+ frameCount: 312,
+ fps: 30,
+ resolution: '1080p',
+ aspectRatio: 'original',
+ });
+ });
+
+ it('hydrates paged-out scratch disk tiles cleanly during .sora v2 save without data loss', async () => {
+ const driver = new InMemoryScratchDiskDriver();
+ const grid = new SparseTileGrid({
+ sessionId: 'paged-save-test',
+ budgetMb: 1,
+ driver,
+ });
+
+ const tile = grid.getOrCreateTile('layer-1', 0, 0, 'grayscale-8bit', 0);
+ tile.data![100] = 177;
+ tile.data![5000] = 88;
+ const rawCopy = new Uint8Array(tile.data!);
+
+ // Simulate SSD scratch eviction: write tile to scratch driver and drop RAM pointer
+ await driver.writeTiles('paged-save-test', [
+ { layerId: 'layer-1', tileX: 0, tileY: 0, data: rawCopy },
+ ]);
+ tile.data = null;
+ tile.isPagedToDisk = true;
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Paged Layer',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ expressionColor: 'gray',
+ },
+ ];
+
+ const saved = await serializeSoraV2(
+ {
+ name: 'Paged Doc',
+ dimensions: { width: 512, height: 512, dpi: 300 },
+ colorMode: 'grayscale',
+ layers,
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ },
+ grid
+ );
+
+ const parsed = await parseSoraProject(saved.bytes);
+ const restored = parsed.tileGrid!.getTile('layer-1', 0, 0, 0);
+ expect(restored?.data?.[100]).toBe(177);
+ expect(restored?.data?.[5000]).toBe(88);
+ });
+
+ it('auto-detects legacy v1.2 JSON (string & UTF-8 bytes with BOM) and preserves backward compatibility', async () => {
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-bg',
+ name: 'Background',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ const v1Payload = buildSoraProjectPayload({
+ name: 'Legacy Project',
+ dimensions: { width: 1440, height: 900, dpi: 300 },
+ colorMode: 'color',
+ layers,
+ layerCanvasesMap: new Map(),
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ });
+ const jsonString = JSON.stringify(v1Payload);
+
+ // String input
+ const parsedStr = await parseSoraProject(jsonString);
+ expect(parsedStr.format).toBe('v1');
+ expect(parsedStr.version).toBe('1.2');
+ expect(parsedStr.name).toBe('Legacy Project');
+ expect(parsedStr.layers).toHaveLength(1);
+
+ // UTF-8 ArrayBuffer with BOM
+ const utf8WithBom = new Uint8Array([0xef, 0xbb, 0xbf, ...new TextEncoder().encode(jsonString)]);
+ expect(isSoraV2Bytes(utf8WithBom)).toBe(false);
+ const parsedBytes = await parseSoraProject(utf8WithBom.buffer);
+ expect(parsedBytes.format).toBe('v1');
+ expect(parsedBytes.name).toBe('Legacy Project');
+ });
+
+ it('extracts preview.png via extractSoraPreview without decompressing tiles, and supports SORA magic wrapper', async () => {
+ const fakePng = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]);
+ const manifest = {
+ format: 'sora-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: 256,
+ name: 'Preview Test',
+ dimensions: { width: 512, height: 512, dpi: 300 },
+ colorMode: 'color',
+ layers: [],
+ layerFormats: {},
+ layerTileKeys: {},
+ masksMeta: {},
+ preview: { path: 'preview.png', width: 256, height: 256 },
+ savedAt: Date.now(),
+ };
+
+ const zipBytes = zipSync({
+ 'manifest.json': new TextEncoder().encode(JSON.stringify(manifest)),
+ 'preview.png': fakePng,
+ });
+
+ // Direct ZIP
+ expect(Array.from(extractSoraPreview(zipBytes)!)).toEqual(Array.from(fakePng));
+
+ // With optional 8-byte SORA\x00\x02 header prefix
+ const wrapped = new Uint8Array(8 + zipBytes.byteLength);
+ wrapped.set([0x53, 0x4f, 0x52, 0x41, 0x00, 0x02, 0x00, 0x00], 0);
+ wrapped.set(zipBytes, 8);
+ expect(isSoraV2Bytes(wrapped)).toBe(true);
+ expect(Array.from(extractSoraPreview(wrapped)!)).toEqual(Array.from(fakePng));
+
+ const parsed = await parseSoraProject(wrapped);
+ expect(parsed.format).toBe('v2');
+ expect(parsed.previewDataUrl).toMatch(/^data:image\/png;base64,/);
+ });
+
+ it('sanitizes unsafe layer IDs and rejects path traversal and corrupted tile payloads', async () => {
+ const grid = new SparseTileGrid();
+ const weirdId = '../bad/layer:name\\0';
+ const tile = grid.getOrCreateTile(weirdId, 0, 0, 'monochrome-1bit', 0);
+ setPixel1Bit(tile.data!, 3, 4, 1);
+
+ const saved = await serializeSoraV2(
+ {
+ name: 'Safe Keys',
+ dimensions: { width: 256, height: 256, dpi: 300 },
+ colorMode: 'monochrome',
+ layers: [
+ {
+ id: weirdId,
+ name: 'Weird',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ],
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ },
+ grid
+ );
+
+ const parsed = await parseSoraProject(saved.bytes);
+ const restored = parsed.tileGrid!.getTile(weirdId, 0, 0, 0);
+ expect(restored).toBeDefined();
+ expect(getPixel1Bit(restored!.data!, 3, 4)).toBe(1);
+
+ // Path traversal archive rejected
+ const evilZip = zipSync({
+ 'manifest.json': new TextEncoder().encode(
+ JSON.stringify({ dimensions: { width: 256, height: 256 }, layers: [] })
+ ),
+ '../escape.bin': new Uint8Array([1, 2, 3]),
+ });
+ await expect(parseSoraProject(evilZip)).rejects.toThrow(/Unsafe archive path/);
+
+ // Truncated / mismatched tile payload rejected
+ const corruptZip = zipSync({
+ 'manifest.json': new TextEncoder().encode(
+ JSON.stringify({
+ dimensions: { width: 256, height: 256 },
+ layers: [{ id: 'l1', name: 'L1', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: null }],
+ layerTileKeys: { l1: 'l1' },
+ })
+ ),
+ 'tiles/l1/0_0.bin': new Uint8Array([0, 1, 0, 0, 0, 0, 32, 0, 0, 0xff]), // claims 8192 bytes, only 1 byte present
+ });
+ await expect(parseSoraProject(corruptZip)).rejects.toThrow(/length mismatch/);
+ });
+
+ it('serializeDocument writes binary .sora v2 Blob instead of legacy JSON', async () => {
+ const grid = new SparseTileGrid();
+ const t = grid.getOrCreateTile('l1', 0, 0, 'monochrome-1bit', 0);
+ setPixel1Bit(t.data!, 10, 10, 1);
+
+ const res = await serializeDocument(
+ {
+ name: 'Doc',
+ dimensions: { width: 512, height: 512, dpi: 600 },
+ colorMode: 'monochrome',
+ layers: [
+ {
+ id: 'l1',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ],
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ },
+ '.sora'
+ );
+
+ expect(res.data).toBeInstanceOf(Blob);
+ const buf = await (res.data as Blob).arrayBuffer();
+ expect(isSoraV2Bytes(buf)).toBe(true);
+ const parsed = await parseSoraProject(buf);
+ expect(parsed.format).toBe('v2');
+ expect(getPixel1Bit(parsed.tileGrid!.getTile('l1', 0, 0, 0)!.data!, 10, 10)).toBe(1);
+ });
+});
+
+describe('Pixel-Accurate GPU Tiled Export & CPU Fallback', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('computes exact tile geometry and Layer Style halo margins for large documents', () => {
+ const layers: LayerItem[] = [
+ {
+ id: 'l1',
+ name: 'Styled',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'add-glow',
+ locked: false,
+ parentId: null,
+ styles: {
+ stroke: { enabled: true, size: 10, color: '#000000', position: 'outside', opacity: 1 },
+ dropShadow: { enabled: true, color: '#000000', opacity: 0.5, angle: 90, distance: 20, blur: 16, spread: 0 },
+ },
+ },
+ {
+ id: 'l2',
+ name: 'Hidden Huge Glow',
+ type: 'raster',
+ visible: false,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ styles: {
+ outerGlow: { enabled: true, color: '#ffffff', opacity: 1, blur: 100, spread: 0 },
+ },
+ },
+ ];
+
+ const margin = computeMaxLayerStyleMargin(layers);
+ // dropShadow extent = ceil(20 + 16 * 1.5) + 2 = 46; hidden layer ignored
+ expect(margin).toBe(46);
+
+ const plan = buildGpuExportTilePlan(4500, 3000, 2048, margin);
+ // innerStep = 2048 - 92 = 1956 -> ceil(4500/1956) = 3 cols, ceil(3000/1956) = 2 rows = 6 tiles
+ expect(plan.tiles).toHaveLength(6);
+ expect(plan.fboWidth).toBeLessThanOrEqual(2048);
+ expect(plan.fboHeight).toBeLessThanOrEqual(2048);
+
+ // Top-left tile has 0 left/top pad, positive right/bottom halo pad
+ expect(plan.tiles[0].padLeft).toBe(0);
+ expect(plan.tiles[0].padTop).toBe(0);
+ expect(plan.tiles[0].padRight).toBe(margin);
+ expect(plan.tiles[0].padBottom).toBe(margin);
+
+ // Interior/second column tile has left halo pad for seamless shadow/stroke stitching
+ expect(plan.tiles[1].padLeft).toBe(margin);
+ expect(plan.tiles[1].originX).toBe(plan.tiles[1].tileX - margin);
+
+ // Exact full-canvas coverage with zero gaps or overlaps
+ const totalArea = plan.tiles.reduce((acc, t) => acc + t.width * t.height, 0);
+ expect(totalArea).toBe(4500 * 3000);
+ });
+
+ it('uses ViewportCompositor tiled GPU rendering when WebGL2 is available, passing exact 1:1 pan/zoom/transparentBackground', async () => {
+ const drawImageCalls: Array<{
+ sx: number;
+ sy: number;
+ sw: number;
+ sh: number;
+ dx: number;
+ dy: number;
+ dw: number;
+ dh: number;
+ }> = [];
+
+ const mock2dCtx = {
+ drawImage: (
+ _src: unknown,
+ sx: number,
+ sy: number,
+ sw: number,
+ sh: number,
+ dx: number,
+ dy: number,
+ dw: number,
+ dh: number
+ ) => {
+ drawImageCalls.push({ sx, sy, sw, sh, dx, dy, dw, dh });
+ },
+ fillRect: vi.fn(),
+ clearRect: vi.fn(),
+ save: vi.fn(),
+ restore: vi.fn(),
+ };
+
+ vi.stubGlobal('document', {
+ createElement: (tag: string) => {
+ if (tag !== 'canvas') return {};
+ return {
+ width: 0,
+ height: 0,
+ getContext: (type: string) => (type === '2d' ? mock2dCtx : null),
+ toBlob: (cb: (b: Blob | null) => void, mime?: string) => {
+ cb(new Blob([new Uint8Array([1, 2, 3, 4])], { type: mime || 'image/png' }));
+ },
+ };
+ },
+ });
+
+ vi.spyOn(ViewportCompositor.prototype, 'isReady').mockReturnValue(true);
+ vi.spyOn(ViewportCompositor.prototype, 'getMaxTextureSize').mockReturnValue(2048);
+ const renderSpy = vi.spyOn(ViewportCompositor.prototype, 'render').mockImplementation(() => {});
+ const disposeSpy = vi.spyOn(ViewportCompositor.prototype, 'dispose').mockImplementation(() => {});
+
+ const grid = new SparseTileGrid();
+ grid.getOrCreateTile('glow-layer', 0, 0, 'color-32bit', 0);
+
+ const layers: LayerItem[] = [
+ {
+ id: 'glow-layer',
+ name: 'Glow + Tone + Tint',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'color-dodge-glow',
+ locked: false,
+ parentId: null,
+ toneEnabled: true,
+ layerColorEnabled: true,
+ layerColor: '#ff3366',
+ styles: {
+ outerGlow: { enabled: true, color: '#00ffee', opacity: 0.8, blur: 10, spread: 0 },
+ },
+ },
+ ];
+
+ // 1. Sync compositeCanvas (transparent PNG) on a 3000x1500 doc -> splits horizontally into 2 tiles
+ const outCanvas = compositeCanvas(
+ { width: 3000, height: 1500, dpi: 600 },
+ layers,
+ new Map(),
+ (l) => l.opacity,
+ (l) => l.visible,
+ false,
+ grid
+ );
+ expect(outCanvas.width).toBe(3000);
+ expect(outCanvas.height).toBe(1500);
+ expect(renderSpy).toHaveBeenCalledTimes(2);
+ expect(drawImageCalls).toHaveLength(2);
+ expect(disposeSpy).toHaveBeenCalledTimes(1);
+
+ // Verify 1:1 zoom, dpr=1, bypassStackCache, transparentBackground=true
+ const firstCallArgs = renderSpy.mock.calls[0];
+ expect(firstCallArgs[1].zoom).toBe(1);
+ expect(firstCallArgs[1].rotation).toBe(0);
+ expect(firstCallArgs[4]?.transparentBackground).toBe(true);
+ expect(firstCallArgs[4]?.bypassStackCache).toBe(true);
+ expect(firstCallArgs[4]?.devicePixelRatio).toBe(1);
+
+ // Verify stitched regions cover exact [0..3000] x [0..1500]
+ expect(drawImageCalls[0].dx).toBe(0);
+ expect(drawImageCalls[0].dw + drawImageCalls[1].dw).toBe(3000);
+ expect(drawImageCalls[1].dx).toBe(drawImageCalls[0].dw);
+
+ // 2. Async exportImage for JPEG -> transparentBackground=false (white background)
+ renderSpy.mockClear();
+ const exported = await exportImage(
+ {
+ name: 'Artwork',
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ colorMode: 'color',
+ layers,
+ layerCanvasesMap: new Map(),
+ tileGrid: grid,
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ },
+ { format: 'jpg', quality: 0.9 }
+ );
+
+ expect(exported.usedGpu).toBe(true);
+ expect(exported.mimeType).toBe('image/jpeg');
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ expect(renderSpy.mock.calls[0][4]?.transparentBackground).toBe(false);
+
+ // 3. Reusable region renderer for tall Webtoon slices
+ renderSpy.mockClear();
+ const renderer = createDocumentRegionRenderer(
+ { width: 800, height: 5000, dpi: 300 },
+ layers,
+ new Map(),
+ (l) => l.opacity,
+ (l) => l.visible,
+ grid
+ );
+ expect(renderer.usedGpu).toBe(true);
+ const sliceTarget = document.createElement('canvas');
+ sliceTarget.width = 800;
+ sliceTarget.height = 1280;
+ renderer.renderRegion(0, 1280, 800, 1280, sliceTarget, true);
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ expect(renderSpy.mock.calls[0][4]?.transparentBackground).toBe(false);
+ renderer.dispose();
+ });
+
+ it('falls back cleanly to CPU compositor when WebGL2 is unavailable', async () => {
+ const fillRectSpy = vi.fn();
+ const mock2dCtx = {
+ fillStyle: '',
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ fillRect: fillRectSpy,
+ clearRect: vi.fn(),
+ drawImage: vi.fn(),
+ save: vi.fn(),
+ restore: vi.fn(),
+ };
+
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ width: 0,
+ height: 0,
+ getContext: (type: string) => (type === '2d' ? mock2dCtx : null),
+ }),
+ });
+
+ vi.spyOn(ViewportCompositor.prototype, 'isReady').mockReturnValue(false);
+
+ const res = await compositeCanvasAsync(
+ { width: 512, height: 512, dpi: 300 },
+ [],
+ new Map(),
+ (l) => l.opacity,
+ (l) => l.visible,
+ true
+ );
+
+ expect(res.usedGpu).toBe(false);
+ expect(res.canvas.width).toBe(512);
+ expect(res.canvas.height).toBe(512);
+ expect(fillRectSpy).toHaveBeenCalledWith(0, 0, 512, 512);
+ });
+});
diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.ts
index 1db5233..073aee4 100644
--- a/src/utils/__tests__/strokeHandshake.test.ts
+++ b/src/utils/__tests__/strokeHandshake.test.ts
@@ -5,7 +5,7 @@ import {
} from '../tileEngine';
import { binarizeCanvasRect } from '../colorUtils';
import { TaperEngine } from '../../engine/TaperEngine';
-import { COMPOSITOR_FRAGMENT_SHADER } from '../compositor';
+import { COMPOSITOR_FRAGMENT_SHADER, COMPOSITOR_INSTANCED_FRAGMENT_SHADER } from '../compositor';
import { extractCoalescedEvents } from '../../components/CanvasArea';
import { LayerPixelSampler } from '../colorMixingEngine';
import {
@@ -174,10 +174,13 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
grid.writeImageData(layerId, { data: stroke1, width: 20, height: 20 }, 300, 300, 'monochrome-1bit');
// 3. Query zoomed-out LOD 1, LOD 2, and LOD 3 tiles (simulating fit-to-screen viewport compositor)
+ // Display LOD > 0 tiles use box-filtered color-32bit coverage to match live mipmapped drafts
+ // without bitwise-OR dilation, while canonical LOD 0 tiles remain 1-bit.
+ expect(grid.getTile(layerId, 1, 1, 0)!.format).toBe('monochrome-1bit');
for (const lod of [1, 2, 3]) {
const lodTile = grid.generateLodTile(layerId, 0, 0, lod);
expect(lodTile).not.toBeNull();
- expect(lodTile!.format).toBe('monochrome-1bit');
+ expect(lodTile!.format).toBe('color-32bit');
const rgba = grid.getTileAsRGBA(lodTile!);
let inkPixels = 0;
for (let i = 3; i < rgba.length; i += 4) {
@@ -407,4 +410,32 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
validCoalesced
);
});
+
+ it('uses identical monochrome alpha curve in draft and instanced shaders and box-filters 1-bit LOD coverage', () => {
+ // Draft (COMPOSITOR_FRAGMENT_SHADER) and baked tiles (COMPOSITOR_INSTANCED_FRAGMENT_SHADER)
+ // must use the exact same monochrome alpha expression (no edge-bloating smoothstep on draft).
+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain(
+ 'float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;'
+ );
+ expect(COMPOSITOR_INSTANCED_FRAGMENT_SHADER).toContain(
+ 'float monoAlpha = u_zoom >= 0.99 ? step(0.5, finalColor.a) : finalColor.a;'
+ );
+ expect(COMPOSITOR_FRAGMENT_SHADER).not.toContain('smoothstep(0.02, monoHi');
+
+ // A single 1-bit ink pixel in a 2x2 block must produce 1/4 alpha coverage (64), NOT bitwise-OR 255
+ const layerId = 'layer-mono-lod-cov';
+ const dot = new Uint8ClampedArray(4);
+ dot[3] = 255;
+ grid.writeImageData(layerId, { data: dot, width: 1, height: 1 }, 10, 10, 'monochrome-1bit');
+
+ const lod1 = grid.generateLodTile(layerId, 0, 0, 1);
+ expect(lod1).not.toBeNull();
+ expect(lod1!.format).toBe('color-32bit');
+ const rgba = grid.getTileAsRGBA(lod1!);
+ const idx = (5 * TILE_SIZE + 5) * 4;
+ expect(rgba[idx]).toBe(0);
+ expect(rgba[idx + 1]).toBe(0);
+ expect(rgba[idx + 2]).toBe(0);
+ expect(rgba[idx + 3]).toBe(64);
+ });
});
diff --git a/src/utils/__tests__/strokePipelineIntegration.test.ts b/src/utils/__tests__/strokePipelineIntegration.test.ts
index 6eaafc7..78ff30d 100644
--- a/src/utils/__tests__/strokePipelineIntegration.test.ts
+++ b/src/utils/__tests__/strokePipelineIntegration.test.ts
@@ -17,7 +17,8 @@ import {
TexturedBrushOptions,
} from '../stampEngine';
import { WebGlBrushEngine, GpuDab } from '../webglBrushEngine';
-import { Point } from '../../types/editor';
+import { renderCompleteStroke } from '../canvasUtils';
+import { BrushSettings, Point } from '../../types/editor';
function makeMock2DCtx(w = 1000, h = 1000) {
const ops: string[] = [];
@@ -403,4 +404,125 @@ describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', ()
renderSpy.mockRestore();
}
});
+
+ it('does not elongate tips on zoomed-out 6071x8598 strokes or paused releases, and tightly caps true flicks', () => {
+ // 1. Zoomed-out manga canvas (zoom = 0.1): 4 doc px/ms is only 0.4 screen px/ms (< 0.70 threshold)
+ const pipeZoomedOut = new StrokePipeline();
+ pipeZoomedOut.beginStroke({ stabilizerLevel: 0, zoom: 0.1, brushSize: 12 });
+ pipeZoomedOut.seedKnot(1000, 1000, 0.6, 8, 0, 0, 0, 0);
+ pipeZoomedOut.enqueueSample(1032, 1000, 0.55, 0, 0, 0, 8, POINTER_TYPE_PEN);
+ pipeZoomedOut.enqueueSample(1064, 1000, 0.5, 0, 0, 0, 16, POINTER_TYPE_PEN);
+ pipeZoomedOut.drain();
+
+ const flickPointsZoomedOut: Array<{ x: number; y: number; width: number }> = [];
+ pipeZoomedOut.finalizeStroke(20, {
+ enableFlickTaper: true,
+ onPoint: (s) => flickPointsZoomedOut.push({ x: s.x, y: s.y, width: s.width }),
+ });
+ expect(flickPointsZoomedOut.length).toBe(0);
+
+ // 2. True fast flick at zoom = 0.1 (15 doc px/ms = 1.5 screen px/ms): tightly capped near brush width
+ const pipeFastFlick = new StrokePipeline();
+ pipeFastFlick.beginStroke({ stabilizerLevel: 0, zoom: 0.1, brushSize: 12 });
+ pipeFastFlick.seedKnot(1000, 1000, 0.6, 8, 0, 0, 0, 0);
+ pipeFastFlick.enqueueSample(1120, 1000, 0.55, 0, 0, 0, 8, POINTER_TYPE_PEN);
+ pipeFastFlick.enqueueSample(1240, 1000, 0.5, 0, 0, 0, 16, POINTER_TYPE_PEN);
+ pipeFastFlick.drain();
+
+ const fastFlickPts: Array<{ x: number; y: number; width: number }> = [];
+ pipeFastFlick.finalizeStroke(20, {
+ enableFlickTaper: true,
+ onPoint: (s) => fastFlickPts.push({ x: s.x, y: s.y, width: s.width }),
+ });
+ expect(fastFlickPts.length).toBeGreaterThanOrEqual(6);
+ const tailLen = Math.hypot(
+ fastFlickPts[fastFlickPts.length - 1].x - 1240,
+ fastFlickPts[fastFlickPts.length - 1].y - 1000
+ );
+ expect(tailLen).toBeLessThanOrEqual(16);
+
+ // 3. Dwell gate (>32ms pause before pointerup) suppresses flick completely even at 1.0x zoom
+ const pipeDwell = new StrokePipeline();
+ pipeDwell.beginStroke({ stabilizerLevel: 0, zoom: 1.0, brushSize: 12 });
+ pipeDwell.seedKnot(100, 100, 0.6, 8, 0, 0, 0, 0);
+ pipeDwell.enqueueSample(140, 100, 0.55, 0, 0, 0, 8, POINTER_TYPE_PEN);
+ pipeDwell.enqueueSample(180, 100, 0.5, 0, 0, 0, 16, POINTER_TYPE_PEN);
+ pipeDwell.drain();
+
+ const dwellFlickPts: Array<{ x: number; y: number }> = [];
+ pipeDwell.finalizeStroke(80, {
+ enableFlickTaper: true,
+ onPoint: (s) => dwellFlickPts.push({ x: s.x, y: s.y }),
+ });
+ expect(dwellFlickPts.length).toBe(0);
+ });
+
+ it('routes monochrome pointerup bakes via GPU when allowGpuForMonochrome is enabled and preserves tapered tips', () => {
+ 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.map((d) => ({ ...d })));
+ return true;
+ });
+
+ try {
+ const taperedPoints: Point[] = [
+ { x: 10, y: 10, pressure: 0.8, width: 10 },
+ { x: 30, y: 10, pressure: 0.6, width: 6 },
+ { x: 50, y: 10, pressure: 0.1, width: 0.5 },
+ ];
+ const gPenSettings = {
+ size: 12,
+ opacity: 1,
+ flow: 1,
+ hardness: 1,
+ spacing: 0.05,
+ color: '#000000',
+ antiAlias: 2,
+ useGpu: true,
+ customTipImage: mockTipImage,
+ taper: { useIn: true, useOut: true, inLength: 10, outLength: 10 },
+ } as unknown as BrushSettings;
+
+ const mockCtx = makeMock2DCtx(256, 256);
+ renderCompleteStroke(
+ mockCtx.ctx,
+ taperedPoints,
+ gPenSettings,
+ 'brush',
+ 'monochrome',
+ false,
+ undefined,
+ false,
+ undefined,
+ true
+ );
+
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ expect(mockCtx.raw.drawImage).not.toHaveBeenCalled();
+ // Tapered tail width (<1.25px) must NOT be inflated back to 1.25px
+ const lastDab = renderedBatches[0][renderedBatches[0].length - 1];
+ expect(lastDab.width).toBeLessThan(1.25);
+
+ // Dot Pen (antiAlias: 0) still stays on CPU even with allowGpuForMonochrome = true
+ const dotPenCtx = makeMock2DCtx(256, 256);
+ renderCompleteStroke(
+ dotPenCtx.ctx,
+ taperedPoints,
+ { ...gPenSettings, antiAlias: 0, customTipImage: undefined },
+ 'brush',
+ 'monochrome',
+ false,
+ undefined,
+ false,
+ undefined,
+ true
+ );
+ expect(renderSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ availSpy.mockRestore();
+ renderSpy.mockRestore();
+ }
+ });
});
diff --git a/src/utils/__tests__/tileEngine.test.ts b/src/utils/__tests__/tileEngine.test.ts
index 54be5c5..2e40689 100644
--- a/src/utils/__tests__/tileEngine.test.ts
+++ b/src/utils/__tests__/tileEngine.test.ts
@@ -208,5 +208,128 @@ describe('Sparse Virtual Tile Engine', () => {
expect(redoTile).not.toBeNull();
expect(getPixel1Bit(redoTile!.data!, 10, 10)).toBe(1);
});
+
+ it('packs partial unaligned sub-rects directly into 1-bit tiles without clobbering untouched bits', () => {
+ grid.setLayerFormat('mono-sub', 'monochrome-1bit');
+ const tile = grid.getOrCreateTile('mono-sub', 0, 0, 'monochrome-1bit');
+ // Seed sentinel bits immediately outside the target sub-rect [5..21) x [3..5)
+ setPixel1Bit(tile.data!, 4, 3, true);
+ setPixel1Bit(tile.data!, 21, 3, true);
+ setPixel1Bit(tile.data!, 10, 2, true);
+ setPixel1Bit(tile.data!, 10, 5, true);
+
+ const w = 16; // covers local x = 5..20 (unaligned start=5, aligned middle 8..15, trailing 16..20)
+ const h = 2;
+ const rgba = new Uint8ClampedArray(w * h * 4);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const off = (y * w + x) * 4;
+ if ((x + y) % 2 === 0) {
+ rgba[off] = 0;
+ rgba[off + 1] = 0;
+ rgba[off + 2] = 0;
+ rgba[off + 3] = 255;
+ }
+ }
+ }
+
+ grid.writeImageData('mono-sub', { data: rgba, width: w, height: h }, 5, 3, 'monochrome-1bit', true);
+
+ // Sentinel bits must remain intact
+ expect(getPixel1Bit(tile.data!, 4, 3)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 21, 3)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 10, 2)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 10, 5)).toBe(1);
+
+ // Checkerboard inside [5..20] x [3..4] must match exactly
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ expect(getPixel1Bit(tile.data!, 5 + x, 3 + y)).toBe((x + y) % 2 === 0 ? 1 : 0);
+ }
+ }
+ });
+
+ it('compositeStrokeToTiles composites directly onto 1-bit and 32-bit tiles, skipping untouched tiles', () => {
+ // 1. Monochrome 1-bit source-over + destination-out + snapshot isolation
+ const monoLayer = 'mono-comp';
+ const w = 4;
+ const h = 4;
+ const stroke = new Uint8ClampedArray(w * h * 4);
+ // (0,0): black alpha 200 (>=128 -> ink 1), (1,0): black alpha 100 (<128 -> stays 0)
+ stroke[3] = 200;
+ stroke[7] = 100;
+
+ const snap1 = new Map<string, { format: 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit'; data: Uint8Array | null }>();
+ const mod1 = grid.compositeStrokeToTiles({
+ layerId: monoLayer,
+ strokeData: { data: stroke, width: w, height: h },
+ destX: 10,
+ destY: 10,
+ format: 'monochrome-1bit',
+ compositeOp: 'source-over',
+ opacity: 1.0,
+ monochrome: { threshold: 128, expressBlack: true, expressWhite: true },
+ snapshotOut: snap1,
+ suppressNotify: true,
+ });
+ expect(mod1).toBe(true);
+ expect(snap1.size).toBe(1);
+ const monoTile = grid.getTile(monoLayer, 0, 0, 0)!;
+ expect(getPixel1Bit(monoTile.data!, 10, 10)).toBe(1);
+ expect(getPixel1Bit(monoTile.data!, 11, 10)).toBe(0);
+
+ // Erase (10,10) with destination-out
+ const snapErase = new Map<string, { format: 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit'; data: Uint8Array | null }>();
+ grid.compositeStrokeToTiles({
+ layerId: monoLayer,
+ strokeData: { data: stroke, width: w, height: h },
+ destX: 10,
+ destY: 10,
+ format: 'monochrome-1bit',
+ compositeOp: 'destination-out',
+ opacity: 1.0,
+ monochrome: { threshold: 128, expressBlack: true, expressWhite: true },
+ snapshotOut: snapErase,
+ suppressNotify: true,
+ });
+ expect(getPixel1Bit(monoTile.data!, 10, 10)).toBe(0);
+
+ // Undo erase restores bit 1
+ const eraseDeltas = grid.computeDeltasFromSnapshot(snapErase, monoLayer);
+ expect(eraseDeltas.length).toBe(1);
+ grid.applyTileDeltas(eraseDeltas, 'undo');
+ expect(getPixel1Bit(grid.getTile(monoLayer, 0, 0, 0)!.data!, 10, 10)).toBe(1);
+
+ // 2. Color 32-bit semi-transparent source-over + source-atop
+ const colorLayer = 'color-comp';
+ const basePx = new Uint8ClampedArray([0, 0, 255, 255]); // opaque blue
+ grid.compositeStrokeToTiles({
+ layerId: colorLayer,
+ strokeData: { data: basePx, width: 1, height: 1 },
+ destX: 20,
+ destY: 20,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 1.0,
+ suppressNotify: true,
+ });
+ const redPx = new Uint8ClampedArray([255, 0, 0, 255]);
+ grid.compositeStrokeToTiles({
+ layerId: colorLayer,
+ strokeData: { data: redPx, width: 1, height: 1 },
+ destX: 20,
+ destY: 20,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.5,
+ suppressNotify: true,
+ });
+ const blended = grid.readImageData(colorLayer, 20, 20, 1, 1).data;
+ expect(blended[0]).toBeGreaterThanOrEqual(126);
+ expect(blended[0]).toBeLessThanOrEqual(130);
+ expect(blended[2]).toBeGreaterThanOrEqual(126);
+ expect(blended[2]).toBeLessThanOrEqual(130);
+ expect(blended[3]).toBe(255);
+ });
});
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index c6c1477..8e62dae 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -486,7 +486,15 @@ export function getReusableBakeCanvas(minWidth: number, minHeight: number): HTML
}
const targetW = Math.max(256, Math.ceil(minWidth));
const targetH = Math.max(256, Math.ceil(minHeight));
- if (_reusableBakeCanvas.width < targetW || _reusableBakeCanvas.height < targetH) {
+ const MAX_PERSISTENT_BAKE_PIXELS = 2048 * 2048;
+ const currentPixels = _reusableBakeCanvas.width * _reusableBakeCanvas.height;
+ if (
+ currentPixels > MAX_PERSISTENT_BAKE_PIXELS &&
+ targetW * targetH <= MAX_PERSISTENT_BAKE_PIXELS
+ ) {
+ _reusableBakeCanvas.width = targetW;
+ _reusableBakeCanvas.height = targetH;
+ } else if (_reusableBakeCanvas.width < targetW || _reusableBakeCanvas.height < targetH) {
_reusableBakeCanvas.width = Math.max(_reusableBakeCanvas.width, targetW);
_reusableBakeCanvas.height = Math.max(_reusableBakeCanvas.height, targetH);
}
@@ -550,7 +558,8 @@ export function renderCompleteStroke(
isBgEraser: boolean = false,
underlyingCanvas?: HTMLCanvasElement,
alphaLocked: boolean = false,
- explicitSampler?: LayerPixelSampler
+ explicitSampler?: LayerPixelSampler,
+ allowGpuForMonochrome: boolean = false
) {
if (!points || points.length === 0) return;
@@ -561,9 +570,11 @@ export function renderCompleteStroke(
? applyCspPostCorrection(points, postCorrLevel, brushSettings.sharpCorners !== false)
: points;
- const effectivePoints = isMono
- ? postCorrectedPoints.map((p) => (p.width < 1.25 ? { ...p, width: 1.25 } : p))
- : postCorrectedPoints;
+ const hasTaper = Boolean(brushSettings.taper?.useOut || brushSettings.taper?.useIn);
+ const effectivePoints =
+ isMono && !hasTaper
+ ? postCorrectedPoints.map((p) => (p.width < 1.25 ? { ...p, width: 1.25 } : p))
+ : postCorrectedPoints;
const isEraser = tool === 'eraser';
const isPencil = !isEraser && !brushSettings.customTipImage && (brushSettings.preset?.startsWith('pencil') ?? false);
@@ -573,6 +584,11 @@ export function renderCompleteStroke(
const strokeSpacing = brushSettings.spacing ?? 0.08;
const isTransparentInk = Boolean(brushSettings.isTransparentInk);
const useTilt = Boolean(brushSettings.useTilt);
+ const effectiveAntiAlias = isMono
+ ? allowGpuForMonochrome && (brushSettings.antiAlias ?? 2) !== 0 && brushSettings.useGpu !== false
+ ? (brushSettings.antiAlias ?? 2)
+ : 0
+ : brushSettings.antiAlias;
// Textured Custom Tip (Clip Studio Paint SUT Brush & Procedural Tip Presets)
if (brushSettings.customTipImage) {
@@ -593,7 +609,7 @@ export function renderCompleteStroke(
angleDynamics: brushSettings.customTipAngleDynamics,
rotationRandomScale: brushSettings.customTipRotationRandomScale,
hardness: strokeHardness,
- antiAlias: isMono ? 0 : brushSettings.antiAlias,
+ antiAlias: effectiveAntiAlias,
pressureCurve: brushSettings.pressureCurve,
velocityCurve: brushSettings.velocityCurve,
usePressure: brushSettings.usePressure,
@@ -671,7 +687,7 @@ export function renderCompleteStroke(
thicknessVertical: brushSettings.thicknessVertical,
flipH: brushSettings.flipH,
flipV: brushSettings.flipV,
- antiAlias: isMono ? 0 : brushSettings.antiAlias,
+ antiAlias: effectiveAntiAlias,
angleDynamics: brushSettings.customTipAngleDynamics,
rotationRandomScale: brushSettings.customTipRotationRandomScale,
adjustDensityByGap: brushSettings.adjustDensityByGap,
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 3cb5ada..3243f4c 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -435,6 +435,25 @@ vec4 applyLayerTint(vec4 color) {
void main() {
if (u_isBackground == 1) {
+ vec2 outsideDoc = max(vec2(0.0) - v_docCoord, v_docCoord - u_docDimensions);
+ if (outsideDoc.x > 0.0 || outsideDoc.y > 0.0) {
+ float safeZoom = max(0.01, u_zoom);
+ vec2 outsidePx = outsideDoc * safeZoom;
+ float borderDist = max(outsidePx.x, outsidePx.y);
+ if (borderDist <= 1.0) {
+ fragColor = vec4(0.086, 0.086, 0.086, 1.0);
+ return;
+ }
+ vec2 shadowCoord = v_docCoord - vec2(0.0, 10.0 / safeZoom);
+ vec2 shadowOutside = max(vec2(0.0) - shadowCoord, shadowCoord - u_docDimensions);
+ float shadowDist = length(shadowOutside * safeZoom);
+ float shadowA = 0.55 * exp(-shadowDist * shadowDist / 520.0) * smoothstep(48.0, 0.0, shadowDist);
+ if (shadowA < 0.002) {
+ discard;
+ }
+ fragColor = vec4(0.0, 0.0, 0.0, shadowA);
+ return;
+ }
if (u_showCheckerboard == 1) {
vec2 checkCoord = floor(v_docCoord / 16.0);
float check = mod(checkCoord.x + checkCoord.y, 2.0);
@@ -460,10 +479,7 @@ 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);
+ 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);
@@ -697,42 +713,15 @@ vec4 applyLayerTint(vec4 color) {
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);
+ // Single hardware TMU fetch on premultiplied RGBA8 TEXTURE_2D_ARRAY
+ vec4 rawTex = texture(u_tileArrayTexture, vec3(v_texCoord, v_sliceIndex));
- if (texColor.a < 0.002) {
+ if (rawTex.a < 0.002) {
discard;
}
+ vec4 texColor = vec4(clamp(rawTex.rgb / rawTex.a, 0.0, 1.0), rawTex.a);
vec4 finalColor = texColor;
if (u_expressionMode == 1) {
@@ -1347,6 +1336,8 @@ export interface CompositorOptions {
dimensions: CanvasDimensions;
colorMode?: CanvasColorMode;
showCheckerboard?: boolean;
+ transparentBackground?: boolean;
+ bypassStackCache?: boolean;
devicePixelRatio?: number;
onionSkinFrames?: OnionSkinCompositorFrame[];
softProof?: SoftProofSettings;
@@ -1401,6 +1392,8 @@ export interface LayerStackCacheInput {
dimensions: CanvasDimensions;
transform: ViewportTransform;
showCheckerboard?: boolean;
+ transparentBackground?: boolean;
+ colorMode?: CanvasColorMode;
onionSkinFrames?: OnionSkinCompositorFrame[];
getLayerContentVersion: (layerId: string) => number;
getMaskInvalidationEpoch?: (layerId: string) => number;
@@ -1711,17 +1704,18 @@ export class LayerStackCacheTracker {
onionSig = parts.join(',');
}
+ const modeTag = input.colorMode ?? 'color';
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('||')}]`;
+ const belowSignature = `${viewportSig}|cm:${modeTag}|cb:${input.showCheckerboard ? 1 : 0}|tb:${input.transparentBackground ? 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('||')}]`;
+ aboveSignature = `${viewportSig}|cm:${modeTag}|strat:${partition.aboveStrategy}:${partition.aboveCacheBlendMode}|above:[${aboveUnitSigs.join('||')}]`;
}
const belowDirty = belowSignature !== this.lastBelowSignature;
@@ -1891,7 +1885,7 @@ export class ViewportCompositor {
private stdLocs: LayerUniformLocs | null = null;
// Instanced TEXTURE_2D_ARRAY batching program, VAO, buffer, & pool
- private static readonly DEFAULT_ARRAY_POOL_LAYERS = 256;
+ private static readonly DEFAULT_ARRAY_POOL_LAYERS = 512;
private instancedProgram: WebGLProgram | null = null;
private instancedLocs: LayerUniformLocs | null = null;
private uInstTileSizeLoc: WebGLUniformLocation | null = null;
@@ -1907,9 +1901,12 @@ export class ViewportCompositor {
private arrayPoolCapacity: number = 0;
private arrayPoolFilterTier: number = -1;
private arrayPoolSlots: ArrayPoolSlot[] = [];
+ private freeArraySlots: ArrayPoolSlot[] = [];
private arrayPoolByKey: Map<string, ArrayPoolSlot> = new Map();
private arrayAccessCounter: number = 0;
private arrayBatchCounter: number = 0;
+ private uploadPremulScratch: Uint8Array = new Uint8Array(TILE_SIZE * TILE_SIZE * 4);
+ private readonly preserveDrawingBuffer: boolean;
// Viewport-space draft stroke program (reuses COMPOSITOR_FRAGMENT_SHADER)
private viewportDraftProgram: WebGLProgram | null = null;
@@ -2064,8 +2061,9 @@ export class ViewportCompositor {
> = new Map();
private fallbackTileCanvas: HTMLCanvasElement | null = null;
- constructor(canvas: HTMLCanvasElement) {
+ constructor(canvas: HTMLCanvasElement, options?: { preserveDrawingBuffer?: boolean }) {
this.canvas = canvas;
+ this.preserveDrawingBuffer = Boolean(options?.preserveDrawingBuffer);
if (typeof canvas.addEventListener === 'function') {
this.onContextLostHandler = (e: Event) => {
e.preventDefault();
@@ -2077,6 +2075,7 @@ export class ViewportCompositor {
this.instanceBuffer = null;
this.tileArrayTexture = null;
this.arrayPoolSlots = [];
+ this.freeArraySlots = [];
this.arrayPoolByKey.clear();
this.arrayPoolCapacity = 0;
this.arrayPoolFilterTier = -1;
@@ -2118,6 +2117,13 @@ export class ViewportCompositor {
return this.canvas;
}
+ public getMaxTextureSize(): number {
+ if (!this.gl) return 2048;
+ const maxTex = Number(this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE)) || 2048;
+ const maxRb = Number(this.gl.getParameter(this.gl.MAX_RENDERBUFFER_SIZE)) || maxTex;
+ return Math.max(256, Math.min(maxTex, maxRb));
+ }
+
public getStackCacheStats(): { belowRebuilds: number; aboveRebuilds: number; cacheHits: number } {
return { ...this.stackCacheStats };
}
@@ -2158,11 +2164,14 @@ export class ViewportCompositor {
}
this.texturePool = [];
this.activePoolByKey.clear();
- for (const slot of this.arrayPoolSlots) {
+ this.freeArraySlots = [];
+ for (let i = this.arrayPoolSlots.length - 1; i >= 0; i--) {
+ const slot = this.arrayPoolSlots[i];
slot.currentKey = null;
slot.version = -1;
slot.lastUsed = 0;
slot.lastBatchTick = 0;
+ this.freeArraySlots.push(slot);
}
this.arrayPoolByKey.clear();
this.stackCache.invalidateAll();
@@ -2283,15 +2292,20 @@ export class ViewportCompositor {
this.arrayPoolCapacity = capacity;
this.arrayPoolFilterTier = 1;
this.arrayPoolSlots = [];
+ this.freeArraySlots = [];
this.arrayPoolByKey.clear();
for (let i = 0; i < capacity; i++) {
- this.arrayPoolSlots.push({
+ const slot: ArrayPoolSlot = {
sliceIndex: i,
currentKey: null,
version: -1,
lastUsed: 0,
lastBatchTick: 0,
- });
+ };
+ this.arrayPoolSlots.push(slot);
+ }
+ for (let i = capacity - 1; i >= 0; i--) {
+ this.freeArraySlots.push(this.arrayPoolSlots[i]);
}
if (typeof gl.createVertexArray === 'function') {
@@ -2326,7 +2340,8 @@ export class ViewportCompositor {
antialias: false,
depth: false,
stencil: true,
- preserveDrawingBuffer: true,
+ preserveDrawingBuffer: this.preserveDrawingBuffer,
+ powerPreference: 'high-performance',
});
if (!gl) return false;
@@ -2906,11 +2921,12 @@ export class ViewportCompositor {
// Expression Color Uniforms
const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
+ const docColorMode = this.currentOptions?.colorMode;
const exprMode = isBgLayer
? 0
- : layer.expressionColor === 'monochrome'
+ : layer.expressionColor === 'monochrome' || docColorMode === 'monochrome'
? 2
- : layer.expressionColor === 'gray'
+ : layer.expressionColor === 'gray' || docColorMode === 'grayscale'
? 1
: 0;
gl.uniform1i(locs.uExpressionMode, exprMode);
@@ -2972,6 +2988,38 @@ export class ViewportCompositor {
* 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 premultiplyTileBytes(srcBytes: Uint8Array, tile: TileBuffer): Uint8Array {
+ // 1-bit monochrome, 8-bit grayscale, and opaque solid-fill tiles only contain alpha 0 or 255
+ // so straight-alpha bytes are already premultiplied (zero-copy fast path).
+ if (
+ tile.format === 'monochrome-1bit' ||
+ tile.format === 'grayscale-8bit' ||
+ (tile.solidColorU32 !== undefined && srcBytes[3] === 255)
+ ) {
+ return srcBytes;
+ }
+
+ const dst = this.uploadPremulScratch;
+ const len = srcBytes.byteLength;
+ const src32 = new Uint32Array(srcBytes.buffer, srcBytes.byteOffset, len >> 2);
+ const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, len >> 2);
+
+ for (let p = 0, i = 0; i < len; p++, i += 4) {
+ const a = srcBytes[i + 3];
+ if (a === 255) {
+ dst32[p] = src32[p];
+ } else if (a === 0) {
+ dst32[p] = 0;
+ } else {
+ dst[i] = ((srcBytes[i] * a + 128) * 257) >> 16;
+ dst[i + 1] = ((srcBytes[i + 1] * a + 128) * 257) >> 16;
+ dst[i + 2] = ((srcBytes[i + 2] * a + 128) * 257) >> 16;
+ dst[i + 3] = a;
+ }
+ }
+ return dst;
+ }
+
private getOrUploadArrayTileSlice(
gl: WebGL2RenderingContext,
tile: TileBuffer,
@@ -2983,24 +3031,26 @@ export class ViewportCompositor {
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 (slot) {
+ // O(1) LRU promotion via JS Map insertion order
+ this.arrayPoolByKey.delete(key);
+ this.arrayPoolByKey.set(key, slot);
+ } else {
+ if (this.freeArraySlots.length > 0) {
+ slot = this.freeArraySlots.pop()!;
+ } else {
+ // Evict oldest unpinned slot from front of Map (O(1) amortized)
+ for (const candidate of this.arrayPoolByKey.values()) {
+ if (candidate.lastBatchTick !== batchTick) {
+ slot = candidate;
+ break;
+ }
}
- if (!oldestSlot || candidate.lastUsed < oldestSlot.lastUsed) {
- oldestSlot = candidate;
+ if (!slot) return -1;
+ if (slot.currentKey) {
+ this.arrayPoolByKey.delete(slot.currentKey);
}
}
- 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);
@@ -3016,9 +3066,9 @@ export class ViewportCompositor {
? 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.)
+ // Premultiply once on upload into reusable scratch buffer (TileBuffer remains straight-alpha;
+ // UNPACK_PREMULTIPLY_ALPHA_WEBGL stays false for WebGL2 spec compliance on texSubImage3D).
+ const uploadBytes = this.premultiplyTileBytes(srcBytes, tile);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.texSubImage3D(
gl.TEXTURE_2D_ARRAY,
@@ -3031,7 +3081,7 @@ export class ViewportCompositor {
1,
gl.RGBA,
gl.UNSIGNED_BYTE,
- srcBytes
+ uploadBytes
);
slot.version = tile.version;
@@ -3054,7 +3104,11 @@ export class ViewportCompositor {
let slot = this.activePoolByKey.get(key);
- if (!slot) {
+ if (slot) {
+ // O(1) LRU promotion via JS Map insertion order
+ this.activePoolByKey.delete(key);
+ this.activePoolByKey.set(key, slot);
+ } else {
if (this.texturePool.length < ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
const tex = gl.createTexture();
if (!tex) return null;
@@ -3070,16 +3124,13 @@ export class ViewportCompositor {
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);
+ // O(1) LRU eviction from front of activePoolByKey Map
+ const oldestEntry = this.activePoolByKey.entries().next();
+ if (!oldestEntry.done) {
+ slot = oldestEntry.value[1];
+ this.activePoolByKey.delete(oldestEntry.value[0]);
+ } else {
+ slot = this.texturePool[0];
}
slot.currentKey = key;
slot.version = -1;
@@ -3175,7 +3226,8 @@ export class ViewportCompositor {
private renderArtboardBackground(
gl: WebGL2RenderingContext,
dimensions: CanvasDimensions,
- showCheckerboard: boolean
+ showCheckerboard: boolean,
+ drawShadow: boolean = true
): void {
if (!this.program || !this.stdLocs) return;
this.unbindSceneTextureUnits(gl);
@@ -3186,12 +3238,22 @@ export class ViewportCompositor {
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.blendFunc(gl.ONE, drawShadow ? gl.ONE_MINUS_SRC_ALPHA : 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);
+ if (drawShadow) {
+ const marginDoc = 56 / Math.max(0.01, this.currentZoom);
+ gl.uniform2f(this.uTileOriginLoc, -marginDoc, -marginDoc);
+ gl.uniform2f(
+ this.uTileSizeLoc,
+ dimensions.width + marginDoc * 2,
+ dimensions.height + marginDoc * 2
+ );
+ } else {
+ 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);
@@ -3328,9 +3390,10 @@ export class ViewportCompositor {
const scenePP = this.ensurePingPongTarget(gl, this.scenePingPong, viewportW, viewportH);
this.scenePingPong = scenePP;
+ const bypassStackCache = Boolean(_options.bypassStackCache);
let belowCacheReady = false;
let aboveCacheReady = false;
- if (scenePP) {
+ if (scenePP && !bypassStackCache) {
if (!this.belowActiveCacheFbo) {
this.belowActiveCacheFbo = this.createFboSurface(gl, false);
}
@@ -3345,7 +3408,49 @@ export class ViewportCompositor {
}
}
- if (scenePP && belowCacheReady && aboveCacheReady && this.belowActiveCacheFbo && this.aboveActiveCacheFbo) {
+ if (bypassStackCache && scenePP) {
+ this.restoreStandardProgram(gl);
+ this.syncFrameUniforms(gl, this.stdLocs);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.stdLocs.uHasBackdrop, 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);
+
+ if (!_options.transparentBackground) {
+ this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard), false);
+ }
+ this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
+
+ const tree = buildLayerTree(layers);
+ this.renderNodeList(
+ gl,
+ tree,
+ dimensions,
+ grid,
+ frustum,
+ viewportW,
+ viewportH,
+ transform,
+ dpr,
+ scenePP,
+ 0,
+ 1.0
+ );
+
+ this.presentTextureToScreen(
+ gl,
+ scenePP.surfaces[scenePP.activeIndex].texture,
+ viewportW,
+ viewportH,
+ _options.softProof
+ );
+ } else if (scenePP && belowCacheReady && aboveCacheReady && this.belowActiveCacheFbo && this.aboveActiveCacheFbo) {
// Evaluate Baked Layer Stack Cache invalidation (below / active / above)
const cacheEval = this.stackCache.evaluate({
layers,
@@ -3356,6 +3461,8 @@ export class ViewportCompositor {
dimensions,
transform,
showCheckerboard: Boolean(_options.showCheckerboard),
+ transparentBackground: Boolean(_options.transparentBackground),
+ colorMode: _options.colorMode,
onionSkinFrames: _options.onionSkinFrames,
getLayerContentVersion: (id) =>
typeof grid.getLayerVersion === 'function' ? grid.getLayerVersion(id) : 0,
@@ -3419,7 +3526,9 @@ export class ViewportCompositor {
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));
+ if (!_options.transparentBackground) {
+ this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard));
+ }
this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, scenePP);
for (const unit of partition.belowUnits) {
@@ -3537,7 +3646,9 @@ export class ViewportCompositor {
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));
+ if (!_options.transparentBackground) {
+ this.renderArtboardBackground(gl, dimensions, Boolean(_options.showCheckerboard), false);
+ }
this.renderOnionSkins(gl, layers, _options.onionSkinFrames, dimensions, grid, frustum, null);
const tree = buildLayerTree(layers);
@@ -4184,14 +4295,23 @@ export class ViewportCompositor {
const endTileY = Math.floor(frustum.maxY / lodTileDocSize);
const visibleTiles: TileBuffer[] = [];
- for (let ty = startTileY; ty <= endTileY; ty++) {
- for (let tx = startTileX; tx <= endTileX; tx++) {
- let tile = grid.getTile(layer.id, tx, ty, targetLod);
- if (targetLod > 0 && (!tile || grid.isLodTileDirty(layer.id, tx, ty, targetLod))) {
- tile = grid.generateLodTile(layer.id, tx, ty, targetLod);
- }
- if (tile) {
- visibleTiles.push(tile);
+ const hasLayerTiles =
+ typeof grid.hasLayerTiles === 'function' ? grid.hasLayerTiles(layer.id) : true;
+ const hasOccCheck = typeof grid.hasPopulatedLodTile === 'function';
+
+ if (hasLayerTiles) {
+ for (let ty = startTileY; ty <= endTileY; ty++) {
+ for (let tx = startTileX; tx <= endTileX; tx++) {
+ if (targetLod > 0 && hasOccCheck && !grid.hasPopulatedLodTile(layer.id, tx, ty, targetLod)) {
+ continue;
+ }
+ let tile = grid.getTile(layer.id, tx, ty, targetLod);
+ if (targetLod > 0 && (!tile || tile.data === null || grid.isLodTileDirty(layer.id, tx, ty, targetLod))) {
+ tile = grid.generateLodTile(layer.id, tx, ty, targetLod);
+ }
+ if (tile) {
+ visibleTiles.push(tile);
+ }
}
}
}
@@ -4538,28 +4658,37 @@ export class ViewportCompositor {
const ver = draftVersion ?? -1;
const hasGenerateMipmap = typeof gl.generateMipmap === 'function';
- if (
- ver === -1 ||
- ver !== this.lastDraftVersion ||
- this.draftTexWidth !== draftCanvas.width ||
- this.draftTexHeight !== draftCanvas.height
- ) {
+ const needsMipmap = hasGenerateMipmap && draftSpace === 'document' && this.currentZoom < 0.99;
+ const sizeChanged =
+ this.draftTexWidth !== draftCanvas.width || this.draftTexHeight !== draftCanvas.height;
+
+ if (ver === -1 || ver !== this.lastDraftVersion || sizeChanged) {
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,
- hasGenerateMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ needsMipmap ? 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);
+ if (!sizeChanged && this.draftTexWidth > 0 && typeof gl.texSubImage2D === 'function') {
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ } else {
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ }
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- if (hasGenerateMipmap) {
+ if (needsMipmap) {
gl.generateMipmap(gl.TEXTURE_2D);
}
this.draftTexWidth = draftCanvas.width;
this.draftTexHeight = draftCanvas.height;
this.lastDraftVersion = ver;
+ } else {
+ gl.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ );
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
@@ -5362,6 +5491,7 @@ export class ViewportCompositor {
}
private static previewTileCanvas: HTMLCanvasElement | null = null;
+ private static previewTileImgData: ImageData | null = null;
private static previewScratchCanvas: HTMLCanvasElement | null = null;
/**
@@ -5441,11 +5571,15 @@ export class ViewportCompositor {
dstCtx.globalCompositeOperation = compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);
dstCtx.imageSmoothingEnabled = true;
+ if (!ViewportCompositor.previewTileImgData) {
+ ViewportCompositor.previewTileImgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ }
+ const reusedImgData = ViewportCompositor.previewTileImgData;
+
for (const tile of tiles) {
const rgba = grid.getTileAsRGBA(tile);
- const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
- imgData.data.set(rgba);
- tileCtx.putImageData(imgData, 0, 0);
+ reusedImgData.data.set(rgba);
+ tileCtx.putImageData(reusedImgData, 0, 0);
const dx = tile.tileX * lodDocSize * scaleX;
const dy = tile.tileY * lodDocSize * scaleY;
diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.ts
index f78e602..3f89672 100644
--- a/src/utils/imageLoader.ts
+++ b/src/utils/imageLoader.ts
@@ -2,7 +2,8 @@ import { LoadedDocument, LayerItem, CanvasColorMode, isFolderLikeLayer } from '.
import { createCanvasThumbnail } from './canvasUtils';
import { renderVectorLayer } from './vectorEngine';
import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';
-import { parseSoraProjectJson } from './saveManager';
+import { parseSoraProject } from './saveManager';
+import { releaseTemporaryCanvas } from './tileEngine';
/**
* Loads standard raster/vector image formats (.png, .jpg, .jpeg, .webp, .bmp, .gif, .svg).
@@ -106,14 +107,63 @@ export async function openFile(file: File): Promise<LoadedDocument> {
if (ext === '.ink' || ext === '.sora' || ext === '.json') {
try {
- const text = await file.text();
- const project = parseSoraProjectJson(text);
+ const buffer = await file.arrayBuffer();
+ const project = await parseSoraProject(buffer);
if (project.layers && Array.isArray(project.layers)) {
const width = project.dimensions.width;
const height = project.dimensions.height;
const dpi = project.dimensions.dpi || 300;
const colorMode: CanvasColorMode = project.colorMode || 'color';
const layers: LayerItem[] = project.layers;
+
+ // Fast native binary v2 path: tiles are already populated directly into SparseTileGrid
+ if (project.format === 'v2' && project.tileGrid) {
+ const grid = project.tileGrid;
+ if (typeof document !== 'undefined') {
+ for (const layer of layers) {
+ if (grid.hasLayerTiles(layer.id)) continue;
+ if (layer.type === 'text' && layer.textData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = width;
+ temp.height = height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ grid.ingestCanvas(layer.id, temp, grid.getLayerFormat(layer.id));
+ releaseTemporaryCanvas(temp);
+ }
+ }
+ }
+
+ return {
+ name: project.name || file.name.replace(/\.[^/.]+$/, ''),
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid: grid,
+ perspectiveRuler: project.perspectiveRuler ?? null,
+ animationTimeline: project.animationTimeline ?? null,
+ timelapse: project.timelapse ?? null,
+ previewDataUrl: project.previewDataUrl,
+ };
+ }
+
+ // Legacy v1.2 JSON path: reconstruct canvases from base64 PNG data URLs
const layerCanvases = new Map<string, HTMLCanvasElement>();
const loadPromises = layers.map((layer) => {
@@ -203,7 +253,7 @@ export async function openFile(file: File): Promise<LoadedDocument> {
};
}
} catch (err) {
- console.warn('Failed to parse .sora project JSON, falling back to image loader:', err);
+ console.warn('Failed to parse .sora project, falling back to image loader:', err);
}
}
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index 4e7c101..2804e2a 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -3,27 +3,55 @@ import type {
Layer as AgPsdLayer,
LayerMaskData as AgPsdMaskData,
} from 'ag-psd';
+import { Zip, ZipDeflate, ZipPassThrough, unzipSync } from 'fflate';
import {
CanvasDimensions,
LayerItem,
CanvasColorMode,
BlendMode,
+ AnimationTimeline,
+ SoraTimelapseMetadata,
isFolderLikeLayer,
hasTileBackedLayer,
} from '../types/editor';
+import type { PerspectiveRuler } from '../types/perspective';
import { getCanvasCompositeOperation } from './canvasUtils';
-import { buildLayerTree, groupTreeNodesForCompositing, LayerTreeNode } from './compositor';
+import {
+ buildLayerTree,
+ groupTreeNodesForCompositing,
+ LayerTreeNode,
+ ViewportCompositor,
+ ViewportTransform,
+} from './compositor';
import { applyAdjustment } from './tonalEngine';
import { applyMultiFrameClip, renderFrameBorder } from './frameEngine';
+import { renderVectorLayer } from './vectorEngine';
import { renderBalloonLayerData, renderTextLayerData } from './vectorLayerRenderer';
import { recoveryService } from '../services/recoveryService';
-import { SparseTileGrid, TILE_SIZE, releaseTemporaryCanvas } from './tileEngine';
+import {
+ SparseTileGrid,
+ TILE_SIZE,
+ TileBuffer,
+ TileFormat,
+ getTileByteSize,
+ releaseTemporaryCanvas,
+} from './tileEngine';
import { documentStore } from './documentStore';
export interface SavedFileInfo {
handle?: any; // FileSystemFileHandle
name: string;
extension: string;
+ size?: number;
+ previewDataUrl?: string;
+}
+
+export interface SaveProgress {
+ phase: 'preparing' | 'preview' | 'tiles' | 'masks' | 'compositing' | 'encoding' | 'finalizing' | 'done';
+ current: number;
+ total: number;
+ percent: number;
+ message: string;
}
export interface SaveDocumentData {
@@ -36,6 +64,218 @@ export interface SaveDocumentData {
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
tabId?: string;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: SoraTimelapseMetadata | null;
+ onProgress?: (progress: SaveProgress) => void;
+ compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
+}
+
+export interface SoraV2Manifest {
+ format: 'sora-v2';
+ app: string;
+ version: '2.0';
+ tileSize: number;
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: Array<Omit<LayerItem, 'maskCanvas'>>;
+ layerFormats: Record<string, TileFormat>;
+ layerTileKeys: Record<string, string>;
+ masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }>;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: SoraTimelapseMetadata | null;
+ preview: { path: string; width: number; height: number } | null;
+ savedAt: number;
+}
+
+export interface ParsedSoraProject {
+ format: 'v2' | 'v1';
+ app: string;
+ version: string;
+ name: string;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ tileGrid?: SparseTileGrid;
+ canvases: Record<string, string>;
+ masks: Record<string, string>;
+ masksBinary?: Map<string, { width: number; height: number; data: Uint8Array }>;
+ perspectiveRuler?: PerspectiveRuler | null;
+ animationTimeline?: AnimationTimeline | null;
+ timelapse?: SoraTimelapseMetadata | null;
+ previewBytes?: Uint8Array | null;
+ previewDataUrl?: string;
+}
+
+export interface ExportImageOptions {
+ format?: 'png' | 'jpg' | 'jpeg' | 'webp';
+ quality?: number;
+ fillWhiteBackground?: boolean;
+ tileSize?: number;
+ onProgress?: (progress: SaveProgress) => void;
+}
+
+export interface ExportImageResult {
+ blob: Blob;
+ mimeType: string;
+ width: number;
+ height: number;
+ usedGpu: boolean;
+}
+
+export interface CompositeCanvasOptions {
+ tileSize?: number;
+ colorMode?: CanvasColorMode;
+ onProgress?: (progress: SaveProgress) => void;
+}
+
+export const SORA_V2_DEFAULT_TILE_EXPORT_SIZE = 2048;
+
+const SORA_V2_FORMAT_TO_BYTE: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 1,
+ 'color-32bit': 2,
+};
+
+const SORA_V2_BYTE_TO_FORMAT: Record<number, TileFormat> = {
+ 0: 'monochrome-1bit',
+ 1: 'grayscale-8bit',
+ 2: 'color-32bit',
+};
+
+const TILE_BINARY_HEADER_BYTES = 9; // [format:u8][version:u32 LE][dataLen:u32 LE]
+const MASK_BINARY_HEADER_BYTES = 8; // [width:u32 LE][height:u32 LE]
+const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
+const MAX_DOCUMENT_DIM = 65536;
+const MAX_TILE_ENTRIES = 120000;
+const CHUNK_YIELD_INTERVAL = 8;
+const MAX_STYLE_MARGIN_PX = 256;
+const PREVIEW_MAX_DIM = 512;
+
+function yieldToMainThread(): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+function bytesToBase64(bytes: Uint8Array): string {
+ if (typeof btoa === 'function') {
+ const chunkSize = 0x8000;
+ let binary = '';
+ for (let i = 0; i < bytes.length; i += chunkSize) {
+ const slice = bytes.subarray(i, Math.min(i + chunkSize, bytes.length));
+ binary += String.fromCharCode(...slice);
+ }
+ return btoa(binary);
+ }
+ let out = '';
+ for (let i = 0; i < bytes.length; i += 3) {
+ const a = bytes[i];
+ const b = i + 1 < bytes.length ? bytes[i + 1] : 0;
+ const c = i + 2 < bytes.length ? bytes[i + 2] : 0;
+ const triple = (a << 16) | (b << 8) | c;
+ out += BASE64_ALPHABET[(triple >> 18) & 63];
+ out += BASE64_ALPHABET[(triple >> 12) & 63];
+ out += i + 1 < bytes.length ? BASE64_ALPHABET[(triple >> 6) & 63] : '=';
+ out += i + 2 < bytes.length ? BASE64_ALPHABET[triple & 63] : '=';
+ }
+ return out;
+}
+
+function toPngDataUrl(bytes: Uint8Array | null | undefined): string | undefined {
+ if (!bytes || bytes.byteLength === 0) return undefined;
+ const b64 = bytesToBase64(bytes);
+ return b64 ? `data:image/png;base64,${b64}` : undefined;
+}
+
+function toSafeZipKey(rawId: string, usedKeys: Set<string>): string {
+ let base = rawId.replace(/[^a-zA-Z0-9._-]/g, '_');
+ if (!base || base === '.' || base === '..') {
+ base = 'layer';
+ }
+ // Prevent hidden or traversal-looking segments
+ base = base.replace(/\.{2,}/g, '_');
+ let candidate = base;
+ let suffix = 1;
+ while (usedKeys.has(candidate)) {
+ candidate = `${base}_${suffix++}`;
+ }
+ usedKeys.add(candidate);
+ return candidate;
+}
+
+function isSafeZipPath(path: string): boolean {
+ if (!path || path.includes('\0') || path.includes('\\') || path.startsWith('/')) {
+ return false;
+ }
+ const segments = path.split('/');
+ for (const seg of segments) {
+ if (!seg || seg === '.' || seg === '..') {
+ return false;
+ }
+ }
+ return true;
+}
+
+function sanitizeJsonLayer(raw: any): LayerItem {
+ const clean: any = Object.create(null);
+ for (const key of Object.keys(raw)) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
+ clean[key] = raw[key];
+ }
+ const normalized: LayerItem = { ...clean };
+ if (normalized.maskCanvas && typeof normalized.maskCanvas.getContext !== 'function') {
+ normalized.maskCanvas = undefined;
+ }
+ return normalized;
+}
+
+/**
+ * Checks whether binary input begins with `.sora` v2 container magic bytes:
+ * - Standard ZIP local file header (`PK\x03\x04`) or empty ZIP (`PK\x05\x06`)
+ * - Optional explicit `SORA\x00\x02` wrapper prefix
+ */
+export function isSoraV2Bytes(input: Uint8Array | ArrayBuffer): boolean {
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (bytes.byteLength < 4) return false;
+ // PK\x03\x04 or PK\x05\x06 (ZIP container)
+ if (
+ bytes[0] === 0x50 &&
+ bytes[1] === 0x4b &&
+ ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
+ ) {
+ return true;
+ }
+ // Optional SORA\x00\x02 wrapper prefix
+ if (
+ bytes.byteLength >= 8 &&
+ bytes[0] === 0x53 &&
+ bytes[1] === 0x4f &&
+ bytes[2] === 0x52 &&
+ bytes[3] === 0x41 &&
+ bytes[4] === 0x00 &&
+ bytes[5] === 0x02
+ ) {
+ return true;
+ }
+ return false;
+}
+
+function unwrapZipPayload(bytes: Uint8Array): Uint8Array {
+ if (
+ bytes.byteLength >= 8 &&
+ bytes[0] === 0x53 &&
+ bytes[1] === 0x4f &&
+ bytes[2] === 0x52 &&
+ bytes[3] === 0x41 &&
+ bytes[4] === 0x00 &&
+ bytes[5] === 0x02
+ ) {
+ return bytes.subarray(8);
+ }
+ return bytes;
}
/**
@@ -119,7 +359,6 @@ function attachRasterPixelsForPsd(
tileGrid: SparseTileGrid | undefined,
tempCanvases: HTMLCanvasElement[]
): void {
- // Prefer direct sparse tile bbox read when backed by SparseTileGrid (no full-size canvas allocation)
const isVectorText =
(layer.type === 'text' && Boolean(layer.textData)) ||
(layer.type === 'balloon' && Boolean(layer.balloonData));
@@ -185,7 +424,6 @@ function buildPsdLayerTree(
): AgPsdLayer[] {
const result: AgPsdLayer[] = [];
- // ag-psd expects bottom-to-top order; Ink Studio layer tree is top-to-bottom
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
const layer = node.layer;
@@ -255,7 +493,6 @@ function acquireLayerExportCanvas(
layerCanvasesMap: Map<string, HTMLCanvasElement>,
tileGrid?: SparseTileGrid
): { canvas: HTMLCanvasElement | null; isTemporary: boolean } {
- // Always render non-destructive text/balloon layers crisply from vector metadata when available
if (layer.type === 'text' && layer.textData && typeof document !== 'undefined') {
const temp = document.createElement('canvas');
temp.width = dimensions.width;
@@ -283,11 +520,594 @@ function acquireLayerExportCanvas(
return { canvas: null, isTemporary: false };
}
+// ============================================================================
+// Pixel-Accurate GPU Tiled Export Engine (ViewportCompositor FBO Pipeline)
+// ============================================================================
+
/**
- * Composites all visible layers with their blend modes, opacities, frame-folder polygon clipping,
- * and non-destructive vector text/balloon layers onto a single canvas.
+ * Computes the maximum pixel halo margin required around export tiles so GPU
+ * Layer Styles (Stroke, Drop Shadow, Outer Glow) render seamlessly across tile seams.
*/
-export function compositeCanvas(
+export function computeMaxLayerStyleMargin(layers: LayerItem[]): number {
+ let maxMargin = 0;
+ for (const layer of layers) {
+ if (!layer.visible || layer.opacity <= 0.001 || !layer.styles) continue;
+ const { stroke, dropShadow, outerGlow } = layer.styles;
+ if (stroke?.enabled && stroke.size > 0 && stroke.opacity > 0) {
+ maxMargin = Math.max(maxMargin, Math.ceil(stroke.size) + 2);
+ }
+ if (dropShadow?.enabled && dropShadow.opacity > 0) {
+ const extent = Math.ceil((dropShadow.distance || 0) + (dropShadow.blur || 0) * 1.5) + 2;
+ maxMargin = Math.max(maxMargin, extent);
+ }
+ if (outerGlow?.enabled && outerGlow.opacity > 0 && outerGlow.blur > 0) {
+ const extent = Math.ceil(outerGlow.blur * 1.5) + 2;
+ maxMargin = Math.max(maxMargin, extent);
+ }
+ }
+ return Math.min(MAX_STYLE_MARGIN_PX, Math.max(0, maxMargin));
+}
+
+function inferLayerTileFormat(layer: LayerItem): TileFormat {
+ if (layer.expressionColor === 'monochrome') return 'monochrome-1bit';
+ if (layer.expressionColor === 'gray') return 'grayscale-8bit';
+ return 'color-32bit';
+}
+
+/**
+ * Prepares a SparseTileGrid containing all visible tile-backed layers for GPU compositing.
+ * Zero-copy fast path when `tileGrid` already holds all visible raster/vector/text/balloon layers.
+ */
+function prepareExportTileGrid(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ tileGrid?: SparseTileGrid
+): { grid: SparseTileGrid; isTemporary: boolean } {
+ const missingLayers: LayerItem[] = [];
+
+ for (const layer of layers) {
+ if (!layer.visible || layer.opacity <= 0.001) continue;
+ if (!hasTileBackedLayer(layer)) continue;
+ const hasTiles = Boolean(tileGrid && tileGrid.hasLayerTiles(layer.id));
+ if (hasTiles) continue;
+
+ const hasVectorSource =
+ (layer.type === 'text' && Boolean(layer.textData)) ||
+ (layer.type === 'balloon' && Boolean(layer.balloonData)) ||
+ (layer.type === 'vector' && Boolean(layer.vectorStrokes && layer.vectorStrokes.length > 0));
+ if (hasVectorSource || layerCanvasesMap.has(layer.id)) {
+ missingLayers.push(layer);
+ }
+ }
+
+ if (tileGrid && missingLayers.length === 0) {
+ return { grid: tileGrid, isTemporary: false };
+ }
+
+ const tempGrid = new SparseTileGrid();
+ if (tileGrid) {
+ // Share existing TileBuffer references without duplicating pixel buffers
+ for (const [layerId, fmt] of tileGrid.getAllLayerFormats().entries()) {
+ tempGrid.setLayerFormat(layerId, fmt);
+ }
+ for (const tile of tileGrid.getAllTiles()) {
+ if ((tile.lod ?? 0) === 0) {
+ tempGrid.setTile(tile.layerId, tile.tileX, tile.tileY, tile);
+ }
+ }
+ }
+
+ if (typeof document !== 'undefined') {
+ for (const layer of missingLayers) {
+ const fmt = inferLayerTileFormat(layer);
+ if (layer.type === 'text' && layer.textData) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderTextLayerData(ctx, layer.textData);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ } else if (layer.type === 'balloon' && layer.balloonData) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderBalloonLayerData(ctx, layer.balloonData);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ } else {
+ const existingCanvas = layerCanvasesMap.get(layer.id);
+ if (existingCanvas) {
+ tempGrid.ingestCanvas(layer.id, existingCanvas, fmt);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const temp = document.createElement('canvas');
+ temp.width = dimensions.width;
+ temp.height = dimensions.height;
+ const ctx = temp.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ tempGrid.ingestCanvas(layer.id, temp, fmt);
+ releaseTemporaryCanvas(temp);
+ }
+ }
+ }
+ }
+
+ return { grid: tempGrid, isTemporary: true };
+}
+
+/**
+ * Ensures any tiles paged out to SSD scratch disk for visible layers are hydrated in RAM
+ * before GPU or CPU export begins.
+ */
+async function hydratePagedTilesForLayers(
+ tileGrid: SparseTileGrid | undefined,
+ layers: LayerItem[],
+ visibleOnly: boolean
+): Promise<void> {
+ if (!tileGrid) return;
+ const mm = tileGrid.getMemoryManager();
+ if (!mm) return;
+
+ for (const layer of layers) {
+ if (visibleOnly && (!layer.visible || layer.opacity <= 0.001)) continue;
+ if (!hasTileBackedLayer(layer)) continue;
+ const tiles = tileGrid.getLayerTiles(layer.id, 0);
+ for (const tile of tiles) {
+ if (tile.data === null && tile.isPagedToDisk) {
+ await mm.requestTileData(tile);
+ }
+ }
+ }
+}
+
+export interface GpuTilePlanEntry {
+ tileX: number;
+ tileY: number;
+ width: number;
+ height: number;
+ padLeft: number;
+ padTop: number;
+ padRight: number;
+ padBottom: number;
+ originX: number;
+ originY: number;
+ fboWidth: number;
+ fboHeight: number;
+}
+
+/**
+ * Pure geometry planner for tiled GPU FBO export with seam-free Layer Style halo padding.
+ */
+export function buildGpuExportTilePlan(
+ docWidth: number,
+ docHeight: number,
+ maxTileSize: number = SORA_V2_DEFAULT_TILE_EXPORT_SIZE,
+ styleMargin: number = 0
+): { fboWidth: number; fboHeight: number; tiles: GpuTilePlanEntry[] } {
+ const safeMaxTile = Math.max(256, Math.floor(maxTileSize));
+ const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((safeMaxTile - 256) / 2)));
+ const innerStep = Math.max(256, safeMaxTile - clampedMargin * 2);
+
+ const tiles: GpuTilePlanEntry[] = [];
+ let maxFboW = 1;
+ let maxFboH = 1;
+
+ for (let tileY = 0; tileY < docHeight; tileY += innerStep) {
+ const height = Math.min(innerStep, docHeight - tileY);
+ const padTop = Math.min(clampedMargin, tileY);
+ const padBottom = Math.min(clampedMargin, docHeight - (tileY + height));
+ const fboHeight = height + padTop + padBottom;
+ if (fboHeight > maxFboH) maxFboH = fboHeight;
+
+ for (let tileX = 0; tileX < docWidth; tileX += innerStep) {
+ const width = Math.min(innerStep, docWidth - tileX);
+ const padLeft = Math.min(clampedMargin, tileX);
+ const padRight = Math.min(clampedMargin, docWidth - (tileX + width));
+ const fboWidth = width + padLeft + padRight;
+ if (fboWidth > maxFboW) maxFboW = fboWidth;
+
+ tiles.push({
+ tileX,
+ tileY,
+ width,
+ height,
+ padLeft,
+ padTop,
+ padRight,
+ padBottom,
+ originX: tileX - padLeft,
+ originY: tileY - padTop,
+ fboWidth,
+ fboHeight,
+ });
+ }
+ }
+
+ return { fboWidth: maxFboW, fboHeight: maxFboH, tiles };
+}
+
+function tryCompositeCanvasGpuSync(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ fillWhiteBackground: boolean,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || dimensions.width <= 0 || dimensions.height <= 0) {
+ return null;
+ }
+
+ const probeCanvas = document.createElement('canvas');
+ const requestedTileSize = options?.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
+ probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
+ probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
+
+ const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
+ if (!compositor.isReady()) {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ return null;
+ }
+
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+ const exportCanvas = document.createElement('canvas');
+ exportCanvas.width = dimensions.width;
+ exportCanvas.height = dimensions.height;
+ const dstCtx = exportCanvas.getContext('2d');
+
+ try {
+ if (!dstCtx) {
+ return exportCanvas;
+ }
+
+ const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
+
+ if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
+ if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
+
+ const total = plan.tiles.length;
+ for (let i = 0; i < total; i++) {
+ const entry = plan.tiles[i];
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - entry.originX,
+ y: dimensions.height * 0.5 - entry.originY,
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(
+ probeCanvas,
+ entry.padLeft,
+ entry.padTop,
+ entry.width,
+ entry.height,
+ entry.tileX,
+ entry.tileY,
+ entry.width,
+ entry.height
+ );
+
+ if (options?.onProgress) {
+ const done = i + 1;
+ options.onProgress({
+ phase: 'compositing',
+ current: done,
+ total,
+ percent: Math.round((done / total) * 100),
+ message: `Compositing GPU tile ${done}/${total}...`,
+ });
+ }
+ }
+
+ return exportCanvas;
+ } catch (err) {
+ console.warn('GPU tiled export failed, falling back to CPU compositor:', err);
+ releaseTemporaryCanvas(exportCanvas);
+ return null;
+ } finally {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ }
+}
+
+/**
+ * Asynchronous tiled GPU compositor with paged-tile hydration, progress reporting,
+ * and event-loop yields between tiles. Falls back to CPU only when WebGL2 is unavailable.
+ */
+export async function compositeCanvasAsync(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): Promise<{ canvas: HTMLCanvasElement; usedGpu: boolean }> {
+ await hydratePagedTilesForLayers(tileGrid, layers, true);
+
+ if (typeof document !== 'undefined' && dimensions.width > 0 && dimensions.height > 0) {
+ const requestedTileSize = options?.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
+ const probeCanvas = document.createElement('canvas');
+ probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
+ probeCanvas.height = Math.min(requestedTileSize, dimensions.height);
+
+ const compositor = new ViewportCompositor(probeCanvas, { preserveDrawingBuffer: true });
+ if (compositor.isReady()) {
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+ const exportCanvas = document.createElement('canvas');
+ exportCanvas.width = dimensions.width;
+ exportCanvas.height = dimensions.height;
+ const dstCtx = exportCanvas.getContext('2d');
+
+ try {
+ if (dstCtx) {
+ const maxGpuTile = Math.min(requestedTileSize, compositor.getMaxTextureSize());
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const plan = buildGpuExportTilePlan(dimensions.width, dimensions.height, maxGpuTile, styleMargin);
+
+ if (probeCanvas.width !== plan.fboWidth) probeCanvas.width = plan.fboWidth;
+ if (probeCanvas.height !== plan.fboHeight) probeCanvas.height = plan.fboHeight;
+
+ const total = plan.tiles.length;
+ for (let i = 0; i < total; i++) {
+ const entry = plan.tiles[i];
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - entry.originX,
+ y: dimensions.height * 0.5 - entry.originY,
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(
+ probeCanvas,
+ entry.padLeft,
+ entry.padTop,
+ entry.width,
+ entry.height,
+ entry.tileX,
+ entry.tileY,
+ entry.width,
+ entry.height
+ );
+
+ if (options?.onProgress) {
+ const done = i + 1;
+ options.onProgress({
+ phase: 'compositing',
+ current: done,
+ total,
+ percent: Math.round((done / total) * 85),
+ message: `Compositing GPU tile ${done}/${total}...`,
+ });
+ }
+
+ if (i + 1 < total) {
+ await yieldToMainThread();
+ }
+ }
+ }
+ return { canvas: exportCanvas, usedGpu: true };
+ } catch (err) {
+ console.warn('Async GPU tiled export failed, falling back to CPU compositor:', err);
+ releaseTemporaryCanvas(exportCanvas);
+ } finally {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ }
+ } else {
+ compositor.dispose();
+ releaseTemporaryCanvas(probeCanvas);
+ }
+ }
+
+ const cpuCanvas = compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+ return { canvas: cpuCanvas, usedGpu: false };
+}
+
+/**
+ * Creates a reusable GPU region renderer (with CPU fallback) for rendering arbitrary
+ * document strips (e.g., tall 800x50,000px Webtoon chapter slices without allocating
+ * a monolithic full-height canvas). Caller MUST call `dispose()` when done.
+ */
+export function createDocumentRegionRenderer(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ tileGrid?: SparseTileGrid,
+ options?: { colorMode?: CanvasColorMode; maxTileSize?: number }
+): {
+ usedGpu: boolean;
+ renderRegion: (
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ targetCanvas: HTMLCanvasElement,
+ fillWhiteBackground: boolean
+ ) => void;
+ dispose: () => void;
+} {
+ const maxTileSize = options?.maxTileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE;
+ const styleMargin = computeMaxLayerStyleMargin(layers);
+ const prepared = prepareExportTileGrid(dimensions, layers, layerCanvasesMap, tileGrid);
+
+ let gpuCanvas: HTMLCanvasElement | null = null;
+ let compositor: ViewportCompositor | null = null;
+ let usedGpu = false;
+ let cpuFullCache: HTMLCanvasElement | null = null;
+ let cpuFullCacheWhite = false;
+
+ if (typeof document !== 'undefined') {
+ gpuCanvas = document.createElement('canvas');
+ gpuCanvas.width = Math.min(maxTileSize, Math.max(1, dimensions.width));
+ gpuCanvas.height = Math.min(maxTileSize, Math.max(1, dimensions.height));
+ const candidate = new ViewportCompositor(gpuCanvas, { preserveDrawingBuffer: true });
+ if (candidate.isReady()) {
+ compositor = candidate;
+ usedGpu = true;
+ } else {
+ candidate.dispose();
+ releaseTemporaryCanvas(gpuCanvas);
+ gpuCanvas = null;
+ }
+ }
+
+ const renderRegion = (
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ targetCanvas: HTMLCanvasElement,
+ fillWhiteBackground: boolean
+ ): void => {
+ const dstCtx = targetCanvas.getContext('2d');
+ if (!dstCtx || width <= 0 || height <= 0) return;
+
+ if (fillWhiteBackground) {
+ dstCtx.fillStyle = '#ffffff';
+ dstCtx.fillRect(0, 0, width, height);
+ } else {
+ dstCtx.clearRect(0, 0, width, height);
+ }
+
+ if (compositor && gpuCanvas) {
+ const maxGpuTile = Math.min(maxTileSize, compositor.getMaxTextureSize());
+ const clampedMargin = Math.max(0, Math.min(styleMargin, Math.floor((maxGpuTile - 256) / 2)));
+ const innerStep = Math.max(256, maxGpuTile - clampedMargin * 2);
+
+ for (let sy = 0; sy < height; sy += innerStep) {
+ const subH = Math.min(innerStep, height - sy);
+ const docY = y + sy;
+ const padTop = Math.min(clampedMargin, docY);
+ const padBottom = Math.min(clampedMargin, Math.max(0, dimensions.height - (docY + subH)));
+
+ for (let sx = 0; sx < width; sx += innerStep) {
+ const subW = Math.min(innerStep, width - sx);
+ const docX = x + sx;
+ const padLeft = Math.min(clampedMargin, docX);
+ const padRight = Math.min(clampedMargin, Math.max(0, dimensions.width - (docX + subW)));
+
+ const fboW = subW + padLeft + padRight;
+ const fboH = subH + padTop + padBottom;
+ if (gpuCanvas.width < fboW) gpuCanvas.width = fboW;
+ if (gpuCanvas.height < fboH) gpuCanvas.height = fboH;
+
+ const transform: ViewportTransform = {
+ pan: {
+ x: dimensions.width * 0.5 - (docX - padLeft),
+ y: dimensions.height * 0.5 - (docY - padTop),
+ },
+ zoom: 1.0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ };
+
+ compositor.render(layers, transform, dimensions, prepared.grid, {
+ dimensions,
+ colorMode: options?.colorMode,
+ showCheckerboard: false,
+ transparentBackground: !fillWhiteBackground,
+ bypassStackCache: true,
+ devicePixelRatio: 1,
+ });
+
+ dstCtx.drawImage(gpuCanvas, padLeft, padTop, subW, subH, sx, sy, subW, subH);
+ }
+ }
+ return;
+ }
+
+ // CPU fallback when WebGL2 is unavailable
+ if (!cpuFullCache || cpuFullCacheWhite !== fillWhiteBackground) {
+ if (cpuFullCache) releaseTemporaryCanvas(cpuFullCache);
+ cpuFullCache = compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+ cpuFullCacheWhite = fillWhiteBackground;
+ }
+ dstCtx.drawImage(cpuFullCache, x, y, width, height, 0, 0, width, height);
+ };
+
+ const dispose = (): void => {
+ if (compositor) {
+ compositor.dispose();
+ compositor = null;
+ }
+ if (gpuCanvas) {
+ releaseTemporaryCanvas(gpuCanvas);
+ gpuCanvas = null;
+ }
+ if (cpuFullCache) {
+ releaseTemporaryCanvas(cpuFullCache);
+ cpuFullCache = null;
+ }
+ if (prepared.isTemporary) {
+ prepared.grid.clearAll();
+ }
+ };
+
+ return { usedGpu, renderRegion, dispose };
+}
+
+/**
+ * CPU 2D fallback compositor — used strictly when WebGL2 is unavailable.
+ */
+export function compositeCanvasCpuFallback(
dimensions: CanvasDimensions,
layers: LayerItem[],
layerCanvasesMap: Map<string, HTMLCanvasElement>,
@@ -493,6 +1313,108 @@ export function compositeCanvas(
return exportCanvas;
}
+/**
+ * Composites all visible layers using tiled offscreen WebGL2 rendering via `ViewportCompositor`
+ * (preserving 100% of GPU blend modes, Layer Styles, Screentones, Layer Color Tint,
+ * Expression Color, Frame Folders, and Adjustment Layers).
+ * Falls back to 2D CPU compositing strictly when WebGL2 is unavailable.
+ */
+export function compositeCanvas(
+ dimensions: CanvasDimensions,
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ getEffectiveOpacity: (layer: LayerItem) => number,
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid,
+ options?: CompositeCanvasOptions
+): HTMLCanvasElement {
+ const gpuResult = tryCompositeCanvasGpuSync(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ fillWhiteBackground,
+ tileGrid,
+ options
+ );
+ if (gpuResult) {
+ return gpuResult;
+ }
+
+ return compositeCanvasCpuFallback(
+ dimensions,
+ layers,
+ layerCanvasesMap,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ fillWhiteBackground,
+ tileGrid
+ );
+}
+
+/**
+ * Pixel-accurate tiled GPU image exporter (PNG / JPEG / WebP) with automatic
+ * CPU fallback when WebGL2 is unavailable.
+ */
+export async function exportImage(
+ data: SaveDocumentData,
+ options: ExportImageOptions = {}
+): Promise<ExportImageResult> {
+ const format = options.format ?? 'png';
+ const isJpeg = format === 'jpg' || format === 'jpeg';
+ const isWebp = format === 'webp';
+ const mimeType = isJpeg ? 'image/jpeg' : isWebp ? 'image/webp' : 'image/png';
+ const quality = isJpeg || isWebp ? (options.quality ?? 0.92) : undefined;
+ const fillWhite = options.fillWhiteBackground ?? isJpeg;
+ const tileGrid =
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
+
+ const onProgress = options.onProgress ?? data.onProgress;
+
+ const { canvas, usedGpu } = await compositeCanvasAsync(
+ data.dimensions,
+ data.layers,
+ data.layerCanvasesMap,
+ data.getEffectiveOpacity,
+ data.isLayerEffectivelyVisible,
+ fillWhite,
+ tileGrid,
+ {
+ tileSize: options.tileSize ?? SORA_V2_DEFAULT_TILE_EXPORT_SIZE,
+ colorMode: data.colorMode,
+ onProgress,
+ }
+ );
+
+ try {
+ onProgress?.({
+ phase: 'encoding',
+ current: 1,
+ total: 1,
+ percent: 92,
+ message: `Encoding ${format.toUpperCase()}...`,
+ });
+ const blob = await canvasToBlob(canvas, mimeType, quality);
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Export complete',
+ });
+ return {
+ blob,
+ mimeType,
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ usedGpu,
+ };
+ } finally {
+ releaseTemporaryCanvas(canvas);
+ }
+}
+
/**
* Converts a canvas element into a Blob with the specified mime-type.
*/
@@ -513,6 +1435,10 @@ export function canvasToBlob(
});
}
+// ============================================================================
+// Binary `.sora` v2 Container (fflate ZIP) & Legacy v1.2 JSON Support
+// ============================================================================
+
export interface SerializedSoraProject {
app: string;
version: string;
@@ -525,8 +1451,7 @@ export interface SerializedSoraProject {
}
/**
- * Pure serializer for native `.sora` / `.ink` project JSON, preserving non-destructive
- * text, speech balloon, vector, adjustment, and frame-folder metadata.
+ * Legacy v1.2 JSON serializer — kept exported for backward compatibility and tests.
*/
export function buildSoraProjectPayload(
data: SaveDocumentData,
@@ -562,28 +1487,22 @@ export function buildSoraProjectPayload(
}
/**
- * Pure parser for `.sora` / `.ink` JSON strings validating structural integrity
- * and restoring non-destructive text, balloon, and frame-folder layer metadata.
+ * Pure parser for legacy `.sora` / `.ink` v1.x JSON strings.
*/
export function parseSoraProjectJson(jsonText: string): SerializedSoraProject {
- const parsed = JSON.parse(jsonText);
+ const cleanText = jsonText.charCodeAt(0) === 0xfeff ? jsonText.slice(1) : jsonText;
+ const parsed = JSON.parse(cleanText);
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.layers)) {
throw new Error('Invalid .sora project payload: missing layers array');
}
- const layers = parsed.layers.map((l: any) => {
- const clean = { ...l };
- if (clean.maskCanvas && typeof clean.maskCanvas.getContext !== 'function') {
- clean.maskCanvas = undefined;
- }
- return clean;
- });
+ const layers = parsed.layers.map((l: any) => sanitizeJsonLayer(l));
return {
app: typeof parsed.app === 'string' ? parsed.app : 'Ink Studio',
version: typeof parsed.version === 'string' ? parsed.version : '1.0',
name: typeof parsed.name === 'string' ? parsed.name : 'Untitled',
dimensions: {
- width: Number(parsed.dimensions?.width) || 1440,
- height: Number(parsed.dimensions?.height) || 900,
+ width: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.width) || 1440)),
+ height: Math.max(1, Math.min(MAX_DOCUMENT_DIM, Number(parsed.dimensions?.height) || 900)),
dpi: Number(parsed.dimensions?.dpi) || 300,
},
colorMode: parsed.colorMode || 'color',
@@ -593,18 +1512,712 @@ export function parseSoraProjectJson(jsonText: string): SerializedSoraProject {
};
}
+function encodeNativeTileRecord(tile: TileBuffer, rawBytes: Uint8Array): Uint8Array {
+ const fmtByte = SORA_V2_FORMAT_TO_BYTE[tile.format] ?? 2;
+ const out = new Uint8Array(TILE_BINARY_HEADER_BYTES + rawBytes.byteLength);
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
+ view.setUint8(0, fmtByte);
+ view.setUint32(1, tile.version >>> 0, true);
+ view.setUint32(5, rawBytes.byteLength >>> 0, true);
+ out.set(rawBytes, TILE_BINARY_HEADER_BYTES);
+ return out;
+}
+
+function decodeNativeTileRecord(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ payload: Uint8Array
+): TileBuffer {
+ if (payload.byteLength < TILE_BINARY_HEADER_BYTES) {
+ throw new Error(`Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): header truncated`);
+ }
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const fmtByte = view.getUint8(0);
+ const format = SORA_V2_BYTE_TO_FORMAT[fmtByte];
+ if (!format) {
+ throw new Error(`Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): unknown format byte ${fmtByte}`);
+ }
+ const version = view.getUint32(1, true);
+ const dataLen = view.getUint32(5, true);
+ const expectedLen = getTileByteSize(format);
+ if (dataLen !== expectedLen || payload.byteLength !== TILE_BINARY_HEADER_BYTES + expectedLen) {
+ throw new Error(
+ `Corrupted .sora v2 tile (${layerId} ${tileX}_${tileY}): length mismatch (expected ${expectedLen}, got ${dataLen}/${payload.byteLength - TILE_BINARY_HEADER_BYTES})`
+ );
+ }
+ const data = new Uint8Array(expectedLen);
+ data.set(payload.subarray(TILE_BINARY_HEADER_BYTES, TILE_BINARY_HEADER_BYTES + expectedLen));
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version: version || 1,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ };
+}
+
+function encodeMaskBinary(maskCanvas: HTMLCanvasElement): { width: number; height: number; record: Uint8Array } | null {
+ const w = maskCanvas.width;
+ const h = maskCanvas.height;
+ if (w <= 0 || h <= 0 || w > MAX_DOCUMENT_DIM || h > MAX_DOCUMENT_DIM) return null;
+ const ctx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx || typeof ctx.getImageData !== 'function') return null;
+
+ const src = ctx.getImageData(0, 0, w, h).data;
+ const pixelCount = w * h;
+ const record = new Uint8Array(MASK_BINARY_HEADER_BYTES + pixelCount);
+ const view = new DataView(record.buffer, record.byteOffset, record.byteLength);
+ view.setUint32(0, w >>> 0, true);
+ view.setUint32(4, h >>> 0, true);
+
+ for (let p = 0, i = 0; p < pixelCount; p++, i += 4) {
+ record[MASK_BINARY_HEADER_BYTES + p] = Math.round(
+ ((0.299 * src[i] + 0.587 * src[i + 1] + 0.114 * src[i + 2]) * src[i + 3]) / 255
+ );
+ }
+ return { width: w, height: h, record };
+}
+
+function decodeMaskBinary(payload: Uint8Array): { width: number; height: number; data: Uint8Array } {
+ if (payload.byteLength < MASK_BINARY_HEADER_BYTES) {
+ throw new Error('Corrupted .sora v2 mask: header truncated');
+ }
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
+ const width = view.getUint32(0, true);
+ const height = view.getUint32(4, true);
+ if (width === 0 || height === 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
+ throw new Error(`Invalid .sora v2 mask dimensions: ${width}x${height}`);
+ }
+ const expectedPixels = width * height;
+ if (payload.byteLength !== MASK_BINARY_HEADER_BYTES + expectedPixels) {
+ throw new Error(
+ `Corrupted .sora v2 mask: expected ${expectedPixels} bytes, got ${payload.byteLength - MASK_BINARY_HEADER_BYTES}`
+ );
+ }
+ const data = new Uint8Array(expectedPixels);
+ data.set(payload.subarray(MASK_BINARY_HEADER_BYTES));
+ return { width, height, data };
+}
+
+function createMaskCanvasFromAlpha(width: number, height: number, alpha: Uint8Array): HTMLCanvasElement | undefined {
+ if (typeof document === 'undefined') return undefined;
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof ctx.putImageData !== 'function') return undefined;
+
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let p = 0, i = 0; p < alpha.length; p++, i += 4) {
+ const v = alpha[p];
+ rgba[i] = v;
+ rgba[i + 1] = v;
+ rgba[i + 2] = v;
+ rgba[i + 3] = 255;
+ }
+ if (typeof ImageData !== 'undefined') {
+ ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
+ } else if (typeof ctx.createImageData === 'function') {
+ const imgData = ctx.createImageData(width, height);
+ imgData.data.set(rgba);
+ ctx.putImageData(imgData, 0, 0);
+ }
+ return canvas;
+}
+
+async function generatePreviewPng(
+ data: SaveDocumentData,
+ tileGrid: SparseTileGrid | undefined
+): Promise<{ bytes: Uint8Array; width: number; height: number } | null> {
+ if (typeof document === 'undefined' || data.dimensions.width <= 0 || data.dimensions.height <= 0) {
+ return null;
+ }
+ const scale = Math.min(1, PREVIEW_MAX_DIM / Math.max(data.dimensions.width, data.dimensions.height));
+ const outW = Math.max(1, Math.round(data.dimensions.width * scale));
+ const outH = Math.max(1, Math.round(data.dimensions.height * scale));
+ const previewCanvas = document.createElement('canvas');
+ previewCanvas.width = outW;
+ previewCanvas.height = outH;
+
+ if (typeof previewCanvas.toBlob !== 'function') {
+ releaseTemporaryCanvas(previewCanvas);
+ return null;
+ }
+
+ try {
+ if (tileGrid) {
+ ViewportCompositor.renderLowResPreview(previewCanvas, data.layers, data.dimensions, tileGrid, {
+ showCheckerboard: false,
+ });
+ } else {
+ const ctx = previewCanvas.getContext('2d');
+ if (!ctx) return null;
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, outW, outH);
+ for (let i = data.layers.length - 1; i >= 0; i--) {
+ const layer = data.layers[i];
+ if (!layer.visible || layer.opacity <= 0.001) continue;
+ const src = data.layerCanvasesMap.get(layer.id);
+ if (!src) continue;
+ ctx.save();
+ ctx.globalAlpha = Math.max(0, Math.min(1, layer.opacity));
+ ctx.drawImage(src, 0, 0, outW, outH);
+ ctx.restore();
+ }
+ }
+
+ const blob = await canvasToBlob(previewCanvas, 'image/png');
+ const buf = await blob.arrayBuffer();
+ const bytes = new Uint8Array(buf);
+ if (bytes.byteLength === 0) return null;
+ return { bytes, width: outW, height: outH };
+ } catch {
+ return null;
+ } finally {
+ releaseTemporaryCanvas(previewCanvas);
+ }
+}
+
+function concatUint8Arrays(chunks: Uint8Array[]): Uint8Array {
+ let total = 0;
+ for (const c of chunks) total += c.byteLength;
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const c of chunks) {
+ out.set(c, offset);
+ offset += c.byteLength;
+ }
+ return out;
+}
+
+/**
+ * Serializes a document into the compact binary `.sora` v2 ZIP container:
+ * - `manifest.json` (metadata: document, layers, folders, masks, vectors, text, balloons, perspective, animation, timelapse)
+ * - `preview.png` (downscaled preview for Recent Documents)
+ * - `tiles/<layerKey>/<tx>_<ty>.bin` (native 1-bit/8-bit/32-bit SparseTileGrid buffers, zero `toDataURL`, zero full-canvas assembly)
+ * - `masks/<layerKey>.bin` (8-bit mask luminance buffers)
+ *
+ * Uses chunked non-blocking streaming compression via `fflate.Zip` with progress reporting.
+ */
+export async function serializeSoraV2(
+ data: SaveDocumentData,
+ tileGrid?: SparseTileGrid
+): Promise<{
+ bytes: Uint8Array;
+ previewBytes: Uint8Array | null;
+ previewDataUrl?: string;
+ manifest: SoraV2Manifest;
+}> {
+ const onProgress = data.onProgress;
+ const tileCompressionLevel = data.compressionLevel ?? 3;
+ const resolvedGrid =
+ tileGrid ??
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : undefined);
+
+ onProgress?.({
+ phase: 'preparing',
+ current: 0,
+ total: 1,
+ percent: 2,
+ message: 'Preparing project metadata...',
+ });
+
+ const usedKeys = new Set<string>();
+ const layerTileKeys: Record<string, string> = {};
+ const layerFormats: Record<string, TileFormat> = {};
+ const masksMeta: Record<string, { width: number; height: number; format: 'alpha-8bit' }> = {};
+ const encodedMasks: Array<{ path: string; record: Uint8Array }> = [];
+
+ // Fallback temporary tile grid strictly for legacy layers only present in layerCanvasesMap
+ let fallbackTempGrid: SparseTileGrid | null = null;
+
+ type PendingTileSource = {
+ path: string;
+ tile: TileBuffer;
+ sourceGrid: SparseTileGrid;
+ };
+ const pendingTiles: PendingTileSource[] = [];
+
+ const serializableLayers: Array<Omit<LayerItem, 'maskCanvas'>> = [];
+
+ for (const layer of data.layers) {
+ const safeKey = toSafeZipKey(layer.id, usedKeys);
+ layerTileKeys[layer.id] = safeKey;
+
+ if (hasTileBackedLayer(layer)) {
+ const gridHasTiles = Boolean(resolvedGrid && resolvedGrid.hasLayerTiles(layer.id));
+ if (resolvedGrid && gridHasTiles) {
+ const tiles = resolvedGrid.getLayerTiles(layer.id, 0);
+ const fmt = tiles[0]?.format ?? resolvedGrid.getLayerFormat(layer.id);
+ layerFormats[layer.id] = fmt;
+ for (const tile of tiles) {
+ pendingTiles.push({
+ path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
+ tile,
+ sourceGrid: resolvedGrid,
+ });
+ }
+ } else {
+ const fmt = resolvedGrid?.getLayerFormat(layer.id) ?? inferLayerTileFormat(layer);
+ layerFormats[layer.id] = fmt;
+
+ // Legacy fallback when raster data exists only on layerCanvasesMap (no toDataURL!)
+ const canvas = data.layerCanvasesMap.get(layer.id);
+ if (canvas && canvas.width > 0 && canvas.height > 0) {
+ if (!fallbackTempGrid) {
+ fallbackTempGrid = new SparseTileGrid();
+ }
+ fallbackTempGrid.ingestCanvas(layer.id, canvas, fmt);
+ const tiles = fallbackTempGrid.getLayerTiles(layer.id, 0);
+ for (const tile of tiles) {
+ pendingTiles.push({
+ path: `tiles/${safeKey}/${tile.tileX}_${tile.tileY}.bin`,
+ tile,
+ sourceGrid: fallbackTempGrid,
+ });
+ }
+ }
+ }
+ }
+
+ if (layer.maskCanvas) {
+ const encodedMask = encodeMaskBinary(layer.maskCanvas);
+ if (encodedMask) {
+ masksMeta[layer.id] = {
+ width: encodedMask.width,
+ height: encodedMask.height,
+ format: 'alpha-8bit',
+ };
+ encodedMasks.push({
+ path: `masks/${safeKey}.bin`,
+ record: encodedMask.record,
+ });
+ }
+ }
+
+ const { maskCanvas: _mc, ...rest } = layer;
+ serializableLayers.push(rest);
+ }
+
+ // Generate downscaled preview.png
+ onProgress?.({
+ phase: 'preview',
+ current: 0,
+ total: 1,
+ percent: 8,
+ message: 'Generating preview thumbnail...',
+ });
+ const preview = await generatePreviewPng(data, resolvedGrid);
+
+ const manifest: SoraV2Manifest = {
+ format: 'sora-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: TILE_SIZE,
+ name: data.name,
+ dimensions: {
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ dpi: data.dimensions.dpi ?? 300,
+ },
+ colorMode: data.colorMode,
+ layers: serializableLayers,
+ layerFormats,
+ layerTileKeys,
+ masksMeta,
+ perspectiveRuler: data.perspectiveRuler ?? null,
+ animationTimeline: data.animationTimeline ?? null,
+ timelapse: data.timelapse ?? null,
+ preview: preview ? { path: 'preview.png', width: preview.width, height: preview.height } : null,
+ savedAt: Date.now(),
+ };
+
+ const encoder = new TextEncoder();
+ const manifestBytes = encoder.encode(JSON.stringify(manifest));
+
+ const chunks: Uint8Array[] = [];
+ let zipError: Error | null = null;
+ const zip = new Zip((err, chunk, _final) => {
+ if (err) {
+ zipError = err;
+ return;
+ }
+ if (chunk && chunk.byteLength > 0) {
+ chunks.push(chunk);
+ }
+ });
+
+ try {
+ // 1. manifest.json
+ const manifestEntry = new ZipDeflate('manifest.json', { level: 6 });
+ zip.add(manifestEntry);
+ manifestEntry.push(manifestBytes, true);
+ if (zipError) throw zipError;
+
+ // 2. preview.png (store uncompressed — PNG is already DEFLATE-compressed)
+ if (preview) {
+ const previewEntry = new ZipPassThrough('preview.png');
+ zip.add(previewEntry);
+ previewEntry.push(preview.bytes, true);
+ if (zipError) throw zipError;
+ }
+
+ // 3. Stream native SparseTileGrid tiles in non-blocking chunks
+ const totalTiles = pendingTiles.length;
+ for (let i = 0; i < totalTiles; i++) {
+ const item = pendingTiles[i];
+ const { tile, sourceGrid, path } = item;
+
+ let rawBytes: Uint8Array | null = tile.data;
+ if (!rawBytes && tile.isPagedToDisk) {
+ const mm = sourceGrid.getMemoryManager();
+ if (mm) {
+ // Read directly from scratch driver without inflating RAM cache
+ rawBytes = await mm.getDriver().readTile(mm.getSessionId(), tile.layerId, tile.tileX, tile.tileY);
+ }
+ }
+ if (!rawBytes) {
+ rawBytes = new Uint8Array(getTileByteSize(tile.format));
+ }
+
+ const record = encodeNativeTileRecord(tile, rawBytes);
+ const entry = new ZipDeflate(path, { level: tileCompressionLevel });
+ zip.add(entry);
+ entry.push(record, true);
+ if (zipError) throw zipError;
+
+ const done = i + 1;
+ if (done % CHUNK_YIELD_INTERVAL === 0 || done === totalTiles) {
+ const pct = 10 + Math.round((done / Math.max(1, totalTiles)) * 75);
+ onProgress?.({
+ phase: 'tiles',
+ current: done,
+ total: totalTiles,
+ percent: Math.min(85, pct),
+ message: `Saving tiles (${done}/${totalTiles})...`,
+ });
+ if (done < totalTiles) {
+ await yieldToMainThread();
+ }
+ }
+ }
+
+ // 4. Layer masks
+ const totalMasks = encodedMasks.length;
+ for (let i = 0; i < totalMasks; i++) {
+ const m = encodedMasks[i];
+ const entry = new ZipDeflate(m.path, { level: tileCompressionLevel });
+ zip.add(entry);
+ entry.push(m.record, true);
+ if (zipError) throw zipError;
+
+ const done = i + 1;
+ onProgress?.({
+ phase: 'masks',
+ current: done,
+ total: totalMasks,
+ percent: 85 + Math.round((done / Math.max(1, totalMasks)) * 10),
+ message: `Saving layer masks (${done}/${totalMasks})...`,
+ });
+ if (done % CHUNK_YIELD_INTERVAL === 0 && done < totalMasks) {
+ await yieldToMainThread();
+ }
+ }
+
+ onProgress?.({
+ phase: 'finalizing',
+ current: 1,
+ total: 1,
+ percent: 96,
+ message: 'Finalizing .sora archive...',
+ });
+
+ zip.end();
+ if (zipError) throw zipError;
+
+ const bytes = concatUint8Arrays(chunks);
+ const previewBytes = preview ? preview.bytes : null;
+ const previewDataUrl = toPngDataUrl(previewBytes);
+
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Saved successfully',
+ });
+
+ return { bytes, previewBytes, previewDataUrl, manifest };
+ } finally {
+ if (fallbackTempGrid) {
+ fallbackTempGrid.clearAll();
+ }
+ }
+}
+
+/**
+ * Fast preview-only extraction from a `.sora` v2 archive for Recent Documents.
+ * Inflates ONLY `preview.png` without decompressing any tile payloads.
+ */
+export function extractSoraPreview(input: ArrayBuffer | Uint8Array): Uint8Array | null {
+ const raw = input instanceof Uint8Array ? input : new Uint8Array(input);
+ if (!isSoraV2Bytes(raw)) return null;
+ try {
+ const zipBytes = unwrapZipPayload(raw);
+ const extracted = unzipSync(zipBytes, {
+ filter: (file) => file.name === 'preview.png',
+ });
+ const png = extracted['preview.png'];
+ return png && png.byteLength > 0 ? png : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Parses a `.sora` / `.ink` project with automatic format detection:
+ * - Binary `.sora` v2 (ZIP container magic bytes) -> restores native SparseTileGrid tiles, masks, preview, and full metadata
+ * - Legacy v1.2 JSON -> falls back to `parseSoraProjectJson` seamlessly
+ */
+export async function parseSoraProject(
+ input: ArrayBuffer | Uint8Array | string,
+ options?: { onProgress?: (progress: SaveProgress) => void }
+): Promise<ParsedSoraProject> {
+ const onProgress = options?.onProgress;
+
+ if (typeof input === 'string') {
+ const v1 = parseSoraProjectJson(input);
+ return {
+ format: 'v1',
+ ...v1,
+ };
+ }
+
+ const rawBytes = input instanceof Uint8Array ? input : new Uint8Array(input);
+
+ // Automatic format detection: v2 binary magic bytes vs legacy JSON v1.2
+ if (!isSoraV2Bytes(rawBytes)) {
+ const text = new TextDecoder('utf-8').decode(rawBytes);
+ const v1 = parseSoraProjectJson(text);
+ return {
+ format: 'v1',
+ ...v1,
+ };
+ }
+
+ onProgress?.({
+ phase: 'preparing',
+ current: 0,
+ total: 1,
+ percent: 5,
+ message: 'Unpacking .sora v2 container...',
+ });
+
+ const zipBytes = unwrapZipPayload(rawBytes);
+ const files = unzipSync(zipBytes);
+
+ // Validate all entry paths against path traversal attacks
+ const fileNames = Object.keys(files);
+ for (const name of fileNames) {
+ if (!isSafeZipPath(name)) {
+ throw new Error(`Unsafe archive path in .sora v2 file: "${name}"`);
+ }
+ }
+
+ const manifestRaw = files['manifest.json'];
+ if (!manifestRaw || manifestRaw.byteLength === 0) {
+ throw new Error('Invalid .sora v2 project: missing manifest.json');
+ }
+ if (manifestRaw.byteLength > MAX_MANIFEST_BYTES) {
+ throw new Error('Invalid .sora v2 project: manifest.json exceeds size limit');
+ }
+
+ const manifestText = new TextDecoder('utf-8').decode(manifestRaw);
+ const parsedManifest = JSON.parse(manifestText);
+ if (
+ !parsedManifest ||
+ typeof parsedManifest !== 'object' ||
+ !Array.isArray(parsedManifest.layers)
+ ) {
+ throw new Error('Invalid .sora v2 manifest: missing layers array');
+ }
+
+ const width = Math.floor(Number(parsedManifest.dimensions?.width) || 0);
+ const height = Math.floor(Number(parsedManifest.dimensions?.height) || 0);
+ if (width <= 0 || height <= 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM) {
+ throw new Error(`Invalid .sora v2 dimensions: ${width}x${height}`);
+ }
+ const dpi = Number(parsedManifest.dimensions?.dpi) || 300;
+ const colorMode: CanvasColorMode = parsedManifest.colorMode || 'color';
+ const layers: LayerItem[] = parsedManifest.layers.map((l: any) => sanitizeJsonLayer(l));
+
+ // Reverse map safeKey -> layerId from manifest
+ const keyToLayerId = new Map<string, string>();
+ if (parsedManifest.layerTileKeys && typeof parsedManifest.layerTileKeys === 'object') {
+ for (const [layerId, safeKey] of Object.entries(parsedManifest.layerTileKeys)) {
+ if (typeof safeKey === 'string' && safeKey.length > 0) {
+ keyToLayerId.set(safeKey, layerId);
+ }
+ }
+ }
+ for (const layer of layers) {
+ if (!keyToLayerId.has(layer.id)) {
+ keyToLayerId.set(layer.id, layer.id);
+ }
+ }
+
+ const layerFormats = new Map<string, TileFormat>();
+ if (parsedManifest.layerFormats && typeof parsedManifest.layerFormats === 'object') {
+ for (const [layerId, fmt] of Object.entries(parsedManifest.layerFormats)) {
+ if (fmt === 'monochrome-1bit' || fmt === 'grayscale-8bit' || fmt === 'color-32bit') {
+ layerFormats.set(layerId, fmt);
+ }
+ }
+ }
+
+ const tileRegex = /^tiles\/([^/]+)\/(-?\d+)_(-?\d+)\.bin$/;
+ const maskRegex = /^masks\/([^/]+)\.bin$/;
+
+ const tileEntries: Array<{ path: string; layerId: string; tx: number; ty: number }> = [];
+ const maskEntries: Array<{ path: string; layerId: string }> = [];
+
+ for (const path of fileNames) {
+ const tileMatch = tileRegex.exec(path);
+ if (tileMatch) {
+ const safeKey = tileMatch[1];
+ const layerId = keyToLayerId.get(safeKey);
+ if (!layerId) continue;
+ const tx = parseInt(tileMatch[2], 10);
+ const ty = parseInt(tileMatch[3], 10);
+ if (!Number.isSafeInteger(tx) || !Number.isSafeInteger(ty)) {
+ throw new Error(`Invalid tile coordinates in .sora v2 archive: ${path}`);
+ }
+ tileEntries.push({ path, layerId, tx, ty });
+ continue;
+ }
+
+ const maskMatch = maskRegex.exec(path);
+ if (maskMatch) {
+ const safeKey = maskMatch[1];
+ const layerId = keyToLayerId.get(safeKey);
+ if (layerId) {
+ maskEntries.push({ path, layerId });
+ }
+ }
+ }
+
+ if (tileEntries.length > MAX_TILE_ENTRIES) {
+ throw new Error(`Invalid .sora v2 project: tile count ${tileEntries.length} exceeds limit`);
+ }
+
+ const restoredTiles: TileBuffer[] = [];
+ for (let i = 0; i < tileEntries.length; i++) {
+ const entry = tileEntries[i];
+ const payload = files[entry.path];
+ const tile = decodeNativeTileRecord(entry.layerId, entry.tx, entry.ty, payload);
+ restoredTiles.push(tile);
+ if (!layerFormats.has(entry.layerId)) {
+ layerFormats.set(entry.layerId, tile.format);
+ }
+
+ const done = i + 1;
+ if (done % (CHUNK_YIELD_INTERVAL * 2) === 0 && done < tileEntries.length) {
+ onProgress?.({
+ phase: 'tiles',
+ current: done,
+ total: tileEntries.length,
+ percent: 15 + Math.round((done / tileEntries.length) * 70),
+ message: `Loading tiles (${done}/${tileEntries.length})...`,
+ });
+ await yieldToMainThread();
+ }
+ }
+
+ const tileGrid = new SparseTileGrid();
+ tileGrid.restoreFromSnapshot(restoredTiles, layerFormats);
+ for (const layer of layers) {
+ if (hasTileBackedLayer(layer)) {
+ const fmt = layerFormats.get(layer.id) ?? inferLayerTileFormat(layer);
+ tileGrid.setLayerFormat(layer.id, fmt);
+ tileGrid.markLayerIngested(layer.id);
+ }
+ }
+
+ const masksBinary = new Map<string, { width: number; height: number; data: Uint8Array }>();
+ const layerById = new Map<string, LayerItem>();
+ for (const l of layers) layerById.set(l.id, l);
+
+ for (const mEntry of maskEntries) {
+ const decoded = decodeMaskBinary(files[mEntry.path]);
+ masksBinary.set(mEntry.layerId, decoded);
+ const layer = layerById.get(mEntry.layerId);
+ if (layer) {
+ const maskCanvas = createMaskCanvasFromAlpha(decoded.width, decoded.height, decoded.data);
+ if (maskCanvas) {
+ layer.maskCanvas = maskCanvas;
+ layer.maskVersion = (layer.maskVersion || 0) + 1;
+ }
+ }
+ }
+
+ const previewPath =
+ typeof parsedManifest.preview?.path === 'string' && isSafeZipPath(parsedManifest.preview.path)
+ ? parsedManifest.preview.path
+ : 'preview.png';
+ const previewRaw = files[previewPath];
+ const previewBytes = previewRaw && previewRaw.byteLength > 0 ? new Uint8Array(previewRaw) : null;
+ const previewDataUrl = toPngDataUrl(previewBytes);
+
+ onProgress?.({
+ phase: 'done',
+ current: 1,
+ total: 1,
+ percent: 100,
+ message: 'Project loaded',
+ });
+
+ return {
+ format: 'v2',
+ app: typeof parsedManifest.app === 'string' ? parsedManifest.app : 'Ink Studio',
+ version: typeof parsedManifest.version === 'string' ? parsedManifest.version : '2.0',
+ name: typeof parsedManifest.name === 'string' ? parsedManifest.name : 'Untitled',
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid,
+ canvases: {},
+ masks: {},
+ masksBinary,
+ perspectiveRuler: parsedManifest.perspectiveRuler ?? null,
+ animationTimeline: parsedManifest.animationTimeline ?? null,
+ timelapse: parsedManifest.timelapse ?? null,
+ previewBytes,
+ previewDataUrl,
+ };
+}
+
/**
* Serializes the document according to the requested file extension.
*/
export async function serializeDocument(
data: SaveDocumentData,
extension: string
-): Promise<{ data: Blob | ArrayBuffer; mimeType: string }> {
+): Promise<{ data: Blob | ArrayBuffer; mimeType: string; previewDataUrl?: string }> {
const ext = extension.toLowerCase();
- const tileGrid = data.tileGrid ?? (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
+ const tileGrid =
+ data.tileGrid ??
+ (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
// 1. PSD/PSB format with full folder hierarchy, blend modes, clipping, alphaLock, and masks
if (ext === '.psd' || ext === '.psb') {
+ await hydratePagedTilesForLayers(tileGrid, data.layers, false);
const tempCanvases: HTMLCanvasElement[] = [];
try {
const tree = buildLayerTree(data.layers);
@@ -651,70 +2264,40 @@ export async function serializeDocument(
}
}
- // 2. Native Ink Studio Project (.ink, .sora) format
+ // 2. Native Ink Studio Project (.sora, .ink) — Binary v2 container
if (ext === '.ink' || ext === '.sora') {
- const projectData = buildSoraProjectPayload(data, tileGrid);
- const json = JSON.stringify(projectData);
+ const result = await serializeSoraV2(data, tileGrid);
return {
- data: new Blob([json], { type: 'application/json' }),
- mimeType: 'application/json',
+ data: new Blob([result.bytes as BlobPart], { type: 'application/octet-stream' }),
+ mimeType: 'application/octet-stream',
+ previewDataUrl: result.previewDataUrl,
};
}
- // 3. JPEG format
+ // 3. JPEG format (tiled GPU compositor with white background)
if (ext === '.jpg' || ext === '.jpeg') {
- const compCanvas = compositeCanvas(
- data.dimensions,
- data.layers,
- data.layerCanvasesMap,
- data.getEffectiveOpacity,
- data.isLayerEffectivelyVisible,
- true, // white background for JPEG
- tileGrid
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'jpg', quality: 0.92, fillWhiteBackground: true }
);
- try {
- const blob = await canvasToBlob(compCanvas, 'image/jpeg', 0.92);
- return { data: blob, mimeType: 'image/jpeg' };
- } finally {
- releaseTemporaryCanvas(compCanvas);
- }
+ return { data: exported.blob, mimeType: exported.mimeType };
}
- // 4. WebP format
+ // 4. WebP format (tiled GPU compositor with transparency)
if (ext === '.webp') {
- const compCanvas = compositeCanvas(
- data.dimensions,
- data.layers,
- data.layerCanvasesMap,
- data.getEffectiveOpacity,
- data.isLayerEffectivelyVisible,
- false,
- tileGrid
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'webp', quality: 0.92, fillWhiteBackground: false }
);
- try {
- const blob = await canvasToBlob(compCanvas, 'image/webp', 0.92);
- return { data: blob, mimeType: 'image/webp' };
- } finally {
- releaseTemporaryCanvas(compCanvas);
- }
+ return { data: exported.blob, mimeType: exported.mimeType };
}
- // 5. Default: PNG format
- const compCanvas = compositeCanvas(
- data.dimensions,
- data.layers,
- data.layerCanvasesMap,
- data.getEffectiveOpacity,
- data.isLayerEffectivelyVisible,
- false,
- tileGrid
+ // 5. Default: PNG format (tiled GPU compositor with transparency)
+ const exported = await exportImage(
+ { ...data, tileGrid },
+ { format: 'png', fillWhiteBackground: false }
);
- try {
- const blob = await canvasToBlob(compCanvas, 'image/png');
- return { data: blob, mimeType: 'image/png' };
- } finally {
- releaseTemporaryCanvas(compCanvas);
- }
+ return { data: exported.blob, mimeType: exported.mimeType };
}
/**
@@ -738,6 +2321,10 @@ export function downloadFile(
}, 200);
}
+function getSerializedByteSize(content: Blob | ArrayBuffer): number {
+ return content instanceof Blob ? content.size : content.byteLength;
+}
+
/**
* Prompts user to select save location and extension via File System Access API or fallback.
*/
@@ -752,7 +2339,7 @@ export async function promptSaveAs(
const types = [
{
description: 'Ink Studio Layered Project (*.sora, *.ink)',
- accept: { 'application/json': ['.sora', '.ink'] },
+ accept: { 'application/octet-stream': ['.sora', '.ink'] },
},
{
description: 'Photoshop Document with Layers (*.psd)',
@@ -797,6 +2384,8 @@ export async function promptSaveAs(
handle,
name: fileName,
extension: ext,
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
};
} catch (err: any) {
if (err.name === 'AbortError') {
@@ -806,7 +2395,6 @@ export async function promptSaveAs(
}
}
- // Fallback if File System Access API is unavailable or rejected
if (fallbackToDownload) {
const ext = defaultExtension;
const serialized = await serializeDocument(data, ext);
@@ -819,6 +2407,8 @@ export async function promptSaveAs(
return {
name: suggestedName,
extension: ext,
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
};
}
@@ -831,7 +2421,7 @@ export async function promptSaveAs(
export async function saveToExistingHandle(
data: SaveDocumentData,
fileInfo: SavedFileInfo
-): Promise<void> {
+): Promise<{ size: number; previewDataUrl?: string }> {
if (!fileInfo.handle || typeof fileInfo.handle.createWritable !== 'function') {
throw new Error('No valid file handle to save to');
}
@@ -844,10 +2434,15 @@ export async function saveToExistingHandle(
if (data.tabId) {
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
}
+
+ return {
+ size: getSerializedByteSize(serialized.data),
+ previewDataUrl: serialized.previewDataUrl,
+ };
}
/**
- * Prompts user to choose a download/save path specifically for a PNG image.
+ * Prompts user to choose a download/save path specifically for an exported image (PNG / JPG / WebP).
*/
export async function promptExportPngImage(
data: SaveDocumentData,
@@ -861,6 +2456,14 @@ export async function promptExportPngImage(
description: 'PNG Image (*.png)',
accept: { 'image/png': ['.png'] },
},
+ {
+ description: 'JPEG Image (*.jpg, *.jpeg)',
+ accept: { 'image/jpeg': ['.jpg', '.jpeg'] },
+ },
+ {
+ description: 'WebP Image (*.webp)',
+ accept: { 'image/webp': ['.webp'] },
+ },
];
if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
@@ -870,12 +2473,16 @@ export async function promptExportPngImage(
types,
});
- const serialized = await serializeDocument(data, '.png');
+ const fileName: string = handle.name;
+ const ext = fileName.includes('.')
+ ? fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
+ : '.png';
+ const serialized = await serializeDocument(data, ext);
const writable = await handle.createWritable();
await writable.write(serialized.data);
await writable.close();
- return handle.name;
+ return fileName;
} catch (err: any) {
if (err.name === 'AbortError') {
throw new Error('Export canceled');
@@ -884,7 +2491,6 @@ export async function promptExportPngImage(
}
}
- // Fallback download
const serialized = await serializeDocument(data, '.png');
downloadFile(serialized.data, suggestedName, 'image/png');
return suggestedName;
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index 382be25..c02d579 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -30,6 +30,7 @@ export interface TileBuffer {
isPagedToDisk: boolean;
lastAccessTimestamp: number;
lod: number; // 0 = 1:1 (256x256 doc area), 1 = 1/2 (512x512), 2 = 1/4 (1024x1024), 3 = 1/8 (2048x2048)
+ solidColorU32?: number; // When defined on a color-32bit tile, all 65,536 pixels share this exact U32 RGBA value
}
export function getTileByteSize(format: TileFormat): number {
@@ -213,29 +214,48 @@ export function packRGBATo1Bit(
dst1Bit: Uint8Array,
threshold: number = 128
): void {
- dst1Bit.fill(0);
+ const thresh1000 = threshold * 1000;
+ const src32 =
+ srcRGBA.byteOffset % 4 === 0
+ ? new Uint32Array(srcRGBA.buffer, srcRGBA.byteOffset, TILE_PIXELS)
+ : null;
let srcOffset = 0;
- let dstByte = 0;
for (let i = 0; i < BYTES_1BIT; i++) {
+ if (src32 !== null) {
+ const p = i << 3;
+ if (
+ (src32[p] |
+ src32[p + 1] |
+ src32[p + 2] |
+ src32[p + 3] |
+ src32[p + 4] |
+ src32[p + 5] |
+ src32[p + 6] |
+ src32[p + 7]) === 0
+ ) {
+ dst1Bit[i] = 0;
+ srcOffset += 32;
+ continue;
+ }
+ }
let byteVal = 0;
for (let bit = 7; bit >= 0; bit--) {
- const r = srcRGBA[srcOffset];
- const g = srcRGBA[srcOffset + 1];
- const b = srcRGBA[srcOffset + 2];
const a = srcRGBA[srcOffset + 3];
-
if (a >= 24) {
- // Luminance: 0.299*R + 0.587*G + 0.114*B
- const lum = (r * 299 + g * 587 + b * 114) / 1000;
+ // Luminance: 0.299*R + 0.587*G + 0.114*B (integer scaled x1000)
+ const lum1000 =
+ srcRGBA[srcOffset] * 299 +
+ srcRGBA[srcOffset + 1] * 587 +
+ srcRGBA[srcOffset + 2] * 114;
// Dark pixels become ink (1), light pixels transparent (0)
- if (lum < threshold) {
+ if (lum1000 < thresh1000) {
byteVal |= 1 << bit;
}
}
srcOffset += 4;
}
- dst1Bit[dstByte++] = byteVal;
+ dst1Bit[i] = byteVal;
}
}
@@ -397,6 +417,14 @@ const _lut1BitByteToNibble = (() => {
return lut;
})();
+// Fast 2-bit popcount and coverage RGBA LUT for box-filtering monochrome-1bit -> color-32bit LOD tiles
+const _pop2 = new Uint8Array([0, 1, 1, 2]);
+const _monoCovU32 = new Uint32Array(
+ isLittleEndian
+ ? [0x00000000, 0x40000000, 0x80000000, 0xbf000000, 0xff000000]
+ : [0x00000000, 0x00000040, 0x00000080, 0x000000bf, 0x000000ff]
+);
+
/**
* Downsample 4 child tiles (2x2 cluster) at LOD k-1 into a single destination tile at LOD k.
* Reuses pre-allocated scratch buffers for zero 256KB heap allocations during zoom-out LOD builds.
@@ -405,18 +433,49 @@ export function downsample2x2ToParentTile(
childTiles: [TileBuffer | null, TileBuffer | null, TileBuffer | null, TileBuffer | null],
dstTile: TileBuffer
): boolean {
- if (!dstTile.data) {
- dstTile.data = new Uint8Array(getTileByteSize(dstTile.format));
+ const c0 = childTiles[0];
+ const c1 = childTiles[1];
+ const c2 = childTiles[2];
+ const c3 = childTiles[3];
+ if (
+ (!c0 || c0.data === null) &&
+ (!c1 || c1.data === null) &&
+ (!c2 || c2.data === null) &&
+ (!c3 || c3.data === null)
+ ) {
+ dstTile.solidColorU32 = undefined;
+ return false;
}
- dstTile.data.fill(0);
- const hasAnyChild = childTiles.some((c) => c && c.data !== null);
- if (!hasAnyChild) {
- return false;
+ if (!dstTile.data) {
+ dstTile.data = new Uint8Array(getTileByteSize(dstTile.format));
}
const format = dstTile.format;
const dst = dstTile.data;
+ dstTile.solidColorU32 = undefined;
+
+ // Fast path #1: All 4 child tiles are identical solid color-32bit tiles (e.g. solid white paper)
+ if (
+ format === 'color-32bit' &&
+ c0 && c1 && c2 && c3 &&
+ c0.solidColorU32 !== undefined &&
+ c0.solidColorU32 === c1.solidColorU32 &&
+ c0.solidColorU32 === c2.solidColorU32 &&
+ c0.solidColorU32 === c3.solidColorU32
+ ) {
+ const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS);
+ dst32.fill(c0.solidColorU32);
+ dstTile.solidColorU32 = c0.solidColorU32;
+ dstTile.dirty = false;
+ dstTile.version++;
+ return true;
+ }
+
+ dst.fill(0);
+ const dst32 = format === 'color-32bit'
+ ? new Uint32Array(dst.buffer, dst.byteOffset, TILE_PIXELS)
+ : null;
for (let q = 0; q < 4; q++) {
const child = childTiles[q];
@@ -427,7 +486,36 @@ export function downsample2x2ToParentTile(
const yBase = (q >= 2) ? 128 : 0;
if (format === 'color-32bit') {
- if (child.format === 'monochrome-1bit') {
+ // Fast path #2: Uniform solid quadrant
+ if (child.solidColorU32 !== undefined && dst32) {
+ const fillU32 = child.solidColorU32;
+ for (let ly = 0; ly < 128; ly++) {
+ const rowStart = (yBase + ly) * TILE_SIZE + xBase;
+ dst32.fill(fillU32, rowStart, rowStart + 128);
+ }
+ continue;
+ }
+
+ if (child.format === 'monochrome-1bit' && dst32) {
+ // Fast zero-unpack 2x2 bit-counting box filter: 1-bit ink -> anti-aliased black coverage RGBA
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const srcRow0 = sy0 << 5;
+ const srcRow1 = (sy0 + 1) << 5;
+ const dstRowBase = (yBase + ly) * TILE_SIZE + xBase;
+ for (let bx = 0; bx < 32; bx++) {
+ const b0 = childData[srcRow0 + bx];
+ const b1 = childData[srcRow1 + bx];
+ if ((b0 | b1) === 0) continue;
+ const outOff = dstRowBase + (bx << 2);
+ dst32[outOff] = _monoCovU32[_pop2[(b0 >> 6) & 3] + _pop2[(b1 >> 6) & 3]];
+ dst32[outOff + 1] = _monoCovU32[_pop2[(b0 >> 4) & 3] + _pop2[(b1 >> 4) & 3]];
+ dst32[outOff + 2] = _monoCovU32[_pop2[(b0 >> 2) & 3] + _pop2[(b1 >> 2) & 3]];
+ dst32[outOff + 3] = _monoCovU32[_pop2[b0 & 3] + _pop2[b1 & 3]];
+ }
+ }
+ continue;
+ } else if (child.format === 'monochrome-1bit') {
unpack1BitToRGBA(childData, _downsampleRgbaScratch);
childData = _downsampleRgbaView;
} else if (child.format === 'grayscale-8bit') {
@@ -436,22 +524,17 @@ export function downsample2x2ToParentTile(
}
for (let ly = 0; ly < 128; ly++) {
const sy0 = ly << 1;
- const sy1 = sy0 + 1;
const dy = yBase + ly;
- const dstRowOffset = dy * TILE_SIZE;
+ const dstRowOffset = dy * TILE_SIZE + xBase;
const srcRowOffset0 = sy0 * TILE_SIZE;
- const srcRowOffset1 = sy1 * TILE_SIZE;
+ const srcRowOffset1 = (sy0 + 1) * TILE_SIZE;
for (let lx = 0; lx < 128; lx++) {
const sx0 = lx << 1;
- const sx1 = sx0 + 1;
- const dx = xBase + lx;
-
const p00 = (srcRowOffset0 + sx0) << 2;
- const p10 = (srcRowOffset0 + sx1) << 2;
+ const p10 = p00 + 4;
const p01 = (srcRowOffset1 + sx0) << 2;
- const p11 = (srcRowOffset1 + sx1) << 2;
- const outIdx = (dstRowOffset + dx) << 2;
+ const p11 = p01 + 4;
const a0 = childData[p00 + 3];
const a1 = childData[p10 + 3];
@@ -460,26 +543,20 @@ export function downsample2x2ToParentTile(
const sumA = a0 + a1 + a2 + a3;
if (sumA === 0) {
- dst[outIdx] = 0;
- dst[outIdx + 1] = 0;
- dst[outIdx + 2] = 0;
- dst[outIdx + 3] = 0;
- } else if (sumA === 1020) {
+ continue; // dst is already zero-initialized
+ }
+ const outIdx = (dstRowOffset + lx) << 2;
+ if (sumA === 1020) {
dst[outIdx] = (childData[p00] + childData[p10] + childData[p01] + childData[p11] + 2) >> 2;
dst[outIdx + 1] = (childData[p00 + 1] + childData[p10 + 1] + childData[p01 + 1] + childData[p11 + 1] + 2) >> 2;
dst[outIdx + 2] = (childData[p00 + 2] + childData[p10 + 2] + childData[p01 + 2] + childData[p11 + 2] + 2) >> 2;
dst[outIdx + 3] = 255;
} else {
+ const halfA = sumA >> 1;
dst[outIdx + 3] = sumA >> 2;
- dst[outIdx] = Math.round(
- (childData[p00] * a0 + childData[p10] * a1 + childData[p01] * a2 + childData[p11] * a3) / sumA
- );
- dst[outIdx + 1] = Math.round(
- (childData[p00 + 1] * a0 + childData[p10 + 1] * a1 + childData[p01 + 1] * a2 + childData[p11 + 1] * a3) / sumA
- );
- dst[outIdx + 2] = Math.round(
- (childData[p00 + 2] * a0 + childData[p10 + 2] * a1 + childData[p01 + 2] * a2 + childData[p11 + 2] * a3) / sumA
- );
+ dst[outIdx] = ((childData[p00] * a0 + childData[p10] * a1 + childData[p01] * a2 + childData[p11] * a3 + halfA) / sumA) | 0;
+ dst[outIdx + 1] = ((childData[p00 + 1] * a0 + childData[p10 + 1] * a1 + childData[p01 + 1] * a2 + childData[p11 + 1] * a3 + halfA) / sumA) | 0;
+ dst[outIdx + 2] = ((childData[p00 + 2] * a0 + childData[p10 + 2] * a1 + childData[p01 + 2] * a2 + childData[p11 + 2] * a3 + halfA) / sumA) | 0;
}
}
}
@@ -1143,9 +1220,26 @@ export function releaseTemporaryCanvas(canvas: HTMLCanvasElement | null | undefi
* Sole authoritative backing store for all layer pixel data in Ink Studio.
* Completely deprecates multi-gigabyte full-sized DOM layer canvases.
*/
+const TILE_COORD_BIAS = 32768;
+const TILE_COORD_STRIDE = 65536;
+
+function packTileCoord(tx: number, ty: number): number {
+ return (ty + TILE_COORD_BIAS) * TILE_COORD_STRIDE + (tx + TILE_COORD_BIAS);
+}
+
+function unpackTileCoordX(packed: number): number {
+ return (packed % TILE_COORD_STRIDE) - TILE_COORD_BIAS;
+}
+
+function unpackTileCoordY(packed: number): number {
+ return Math.floor(packed / TILE_COORD_STRIDE) - TILE_COORD_BIAS;
+}
+
export class SparseTileGrid {
private readonly gridId: number = nextSparseTileGridId++;
private tiles: Map<string, TileBuffer> = new Map();
+ private layerLod0Tiles: Map<string, Set<TileBuffer>> = new Map();
+ private layerLodOccupancy: Map<string, [Map<number, number>, Map<number, number>, Map<number, number>]> = new Map();
private layerFormats: Map<string, TileFormat> = new Map();
private ingestedLayers: Set<string> = new Set();
private dirtyLodTiles: Set<string> = new Set();
@@ -1156,23 +1250,87 @@ export class SparseTileGrid {
private memoryManager: TileMemoryManager | null = null;
private layerVersions: Map<string, number> = new Map();
private globalVersionCounter: number = 1;
+ private contentVersion: number = 1;
private gridEpoch: number = 0;
constructor(memoryManagerOptions?: TileMemoryManagerOptions) {
this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);
}
+ private registerLod0Tile(tile: TileBuffer): void {
+ if ((tile.lod ?? 0) !== 0) return;
+ let set = this.layerLod0Tiles.get(tile.layerId);
+ if (!set) {
+ set = new Set<TileBuffer>();
+ this.layerLod0Tiles.set(tile.layerId, set);
+ }
+ if (set.has(tile)) return;
+ set.add(tile);
+
+ let occ = this.layerLodOccupancy.get(tile.layerId);
+ if (!occ) {
+ occ = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()];
+ this.layerLodOccupancy.set(tile.layerId, occ);
+ }
+ let tx = tile.tileX;
+ let ty = tile.tileY;
+ for (let i = 0; i < 3; i++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const pk = packTileCoord(tx, ty);
+ occ[i].set(pk, (occ[i].get(pk) ?? 0) + 1);
+ }
+ }
+
+ private unregisterLod0Tile(tile: TileBuffer): void {
+ if ((tile.lod ?? 0) !== 0) return;
+ const set = this.layerLod0Tiles.get(tile.layerId);
+ if (!set || !set.delete(tile)) return;
+ if (set.size === 0) {
+ this.layerLod0Tiles.delete(tile.layerId);
+ }
+
+ const occ = this.layerLodOccupancy.get(tile.layerId);
+ if (!occ) return;
+ let tx = tile.tileX;
+ let ty = tile.tileY;
+ for (let i = 0; i < 3; i++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const pk = packTileCoord(tx, ty);
+ const next = (occ[i].get(pk) ?? 0) - 1;
+ if (next <= 0) {
+ occ[i].delete(pk);
+ } else {
+ occ[i].set(pk, next);
+ }
+ }
+ if (set.size === 0) {
+ this.layerLodOccupancy.delete(tile.layerId);
+ }
+ }
+
public getGridId(): number {
return this.gridId;
}
public hasLayerTiles(layerId: string): boolean {
- for (const tile of this.tiles.values()) {
- if (tile.layerId === layerId && (tile.lod ?? 0) === 0) {
- return true;
- }
+ const set = this.layerLod0Tiles.get(layerId);
+ return set !== undefined && set.size > 0;
+ }
+
+ public hasPopulatedLodTile(layerId: string, tileX: number, tileY: number, lod: number): boolean {
+ if (lod <= 0) {
+ return this.tiles.has(getTileKey(layerId, tileX, tileY, 0));
}
- return false;
+ const idx = lod - 1;
+ if (idx < 0 || idx > 2) return false;
+ const occ = this.layerLodOccupancy.get(layerId);
+ return occ !== undefined && (occ[idx].get(packTileCoord(tileX, tileY)) ?? 0) > 0;
+ }
+
+ public getContentVersion(): number {
+ return this.contentVersion;
}
public getLayerVersion(layerId: string): number {
@@ -1181,6 +1339,7 @@ export class SparseTileGrid {
public bumpLayerVersion(layerId: string): void {
this.layerVersions.set(layerId, ++this.globalVersionCounter);
+ this.contentVersion++;
}
public getGridEpoch(): number {
@@ -1245,6 +1404,9 @@ export class SparseTileGrid {
const fmt = format || this.getLayerFormat(layerId);
tile = createTileBuffer(layerId, tileX, tileY, fmt, lod);
this.tiles.set(key, tile);
+ if (lod === 0) {
+ this.registerLod0Tile(tile);
+ }
if (this.memoryManager) {
this.memoryManager.notifyTileAllocated(tile);
}
@@ -1259,10 +1421,18 @@ export class SparseTileGrid {
public setTile(layerId: string, tileX: number, tileY: number, tile: TileBuffer): void {
const key = getTileKey(layerId, tileX, tileY, tile.lod);
const existing = this.tiles.get(key);
- if (existing && this.memoryManager) {
- this.memoryManager.notifyTileFreed(existing);
+ if (existing) {
+ if ((existing.lod ?? 0) === 0) {
+ this.unregisterLod0Tile(existing);
+ }
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileFreed(existing);
+ }
}
this.tiles.set(key, tile);
+ if ((tile.lod ?? 0) === 0) {
+ this.registerLod0Tile(tile);
+ }
if (this.memoryManager) {
this.memoryManager.notifyTileAllocated(tile);
}
@@ -1278,6 +1448,9 @@ export class SparseTileGrid {
const key = getTileKey(layerId, tileX, tileY, lod);
const tile = this.tiles.get(key);
if (tile) {
+ if ((tile.lod ?? 0) === 0) {
+ this.unregisterLod0Tile(tile);
+ }
if (this.memoryManager) {
this.memoryManager.notifyTileFreed(tile);
}
@@ -1290,6 +1463,10 @@ export class SparseTileGrid {
}
public getLayerTiles(layerId: string, lod: number = 0): TileBuffer[] {
+ if (lod === 0) {
+ const set = this.layerLod0Tiles.get(layerId);
+ return set ? Array.from(set) : [];
+ }
const result: TileBuffer[] = [];
for (const tile of this.tiles.values()) {
if (tile.layerId === layerId && (tile.lod ?? 0) === lod) {
@@ -1307,6 +1484,9 @@ export class SparseTileGrid {
maxY: number,
lod: number = 0
): TileBuffer[] {
+ if (lod === 0 && !this.hasLayerTiles(layerId)) {
+ return [];
+ }
const minTileX = pixelToTileCoord(minX, lod);
const minTileY = pixelToTileCoord(minY, lod);
const maxTileX = pixelToTileCoord(maxX, lod);
@@ -1315,6 +1495,11 @@ export class SparseTileGrid {
const result: TileBuffer[] = [];
for (let ty = minTileY; ty <= maxTileY; ty++) {
for (let tx = minTileX; tx <= maxTileX; tx++) {
+ if (lod > 0 && !this.hasPopulatedLodTile(layerId, tx, ty, lod)) {
+ const direct = this.getTile(layerId, tx, ty, lod);
+ if (direct) result.push(direct);
+ continue;
+ }
let tile = this.getTile(layerId, tx, ty, lod);
if (lod > 0 && (!tile || this.isLodTileDirty(layerId, tx, ty, lod))) {
tile = this.generateLodTile(layerId, tx, ty, lod);
@@ -1403,6 +1588,10 @@ export class SparseTileGrid {
const tileScratch = this.writeScratchRGBA;
const srcData = imgData.data;
+ const src32 =
+ srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
+ ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
+ : null;
for (let ty = minTileY; ty <= maxTileY; ty++) {
const tileDocY = ty * TILE_SIZE;
@@ -1419,13 +1608,25 @@ export class SparseTileGrid {
let existingTile = this.getTile(layerId, tx, ty, 0);
if (!existingTile) {
let hasNonZero = false;
- outer: for (let sy = srcStartY; sy < srcEndY; sy++) {
- let idx = (sy * w + srcStartX) * 4;
- const endIdx = (sy * w + srcEndX) * 4;
- for (; idx < endIdx; idx += 4) {
- if (srcData[idx + 3] !== 0 || srcData[idx] !== 0 || srcData[idx + 1] !== 0 || srcData[idx + 2] !== 0) {
- hasNonZero = true;
- break outer;
+ if (src32 !== null) {
+ outer32: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const rowOff = sy * w;
+ for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
+ if (src32[sx] !== 0) {
+ hasNonZero = true;
+ break outer32;
+ }
+ }
+ }
+ } else {
+ outer: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ let idx = (sy * w + srcStartX) * 4;
+ const endIdx = (sy * w + srcEndX) * 4;
+ for (; idx < endIdx; idx += 4) {
+ if (srcData[idx + 3] !== 0 || srcData[idx] !== 0 || srcData[idx + 1] !== 0 || srcData[idx + 2] !== 0) {
+ hasNonZero = true;
+ break outer;
+ }
}
}
}
@@ -1461,23 +1662,98 @@ export class SparseTileGrid {
);
}
} else if (tile.format === 'monochrome-1bit') {
- unpack1BitToRGBA(tile.data, tileScratch);
+ const dst = tile.data;
+ const localStartX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+ const localEndX = localStartX + copyWidth;
for (let sy = srcStartY; sy < srcEndY; sy++) {
const tileLocalY = destY + sy - tileDocY;
- const tileLocalX = destX + srcStartX - tileDocX;
- const copyWidth = srcEndX - srcStartX;
+ const rowByteBase = tileLocalY << 5; // TILE_SIZE / 8 = 32
+ let lx = localStartX;
+ let srcPixIdx = sy * w + srcStartX;
+ let srcOff = srcPixIdx << 2;
+
+ // Leading unaligned pixels before an 8-pixel boundary
+ if ((lx & 7) !== 0) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ let byteVal = dst[byteIdx];
+ const stop = Math.min(localEndX, (lx + 7) & ~7);
+ while (lx < stop) {
+ const mask = 1 << (7 - (lx & 7));
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= mask;
+ } else {
+ byteVal &= ~mask;
+ }
+ lx++;
+ srcPixIdx++;
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ }
- const srcByteOffset = (sy * w + srcStartX) * 4;
- const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+ // Full 8-pixel aligned bytes
+ while (lx + 8 <= localEndX) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ if (
+ src32 !== null &&
+ (src32[srcPixIdx] |
+ src32[srcPixIdx + 1] |
+ src32[srcPixIdx + 2] |
+ src32[srcPixIdx + 3] |
+ src32[srcPixIdx + 4] |
+ src32[srcPixIdx + 5] |
+ src32[srcPixIdx + 6] |
+ src32[srcPixIdx + 7]) === 0
+ ) {
+ dst[byteIdx] = 0;
+ lx += 8;
+ srcPixIdx += 8;
+ srcOff += 32;
+ continue;
+ }
+ let byteVal = 0;
+ for (let bit = 7; bit >= 0; bit--) {
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= 1 << bit;
+ }
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ lx += 8;
+ srcPixIdx += 8;
+ }
- tileScratch.set(
- srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
- tileByteOffset
- );
+ // Trailing unaligned pixels
+ if (lx < localEndX) {
+ const byteIdx = rowByteBase + (lx >> 3);
+ let byteVal = dst[byteIdx];
+ while (lx < localEndX) {
+ const mask = 1 << (7 - (lx & 7));
+ const a = srcData[srcOff + 3];
+ if (
+ a >= 24 &&
+ srcData[srcOff] * 299 + srcData[srcOff + 1] * 587 + srcData[srcOff + 2] * 114 < 128000
+ ) {
+ byteVal |= mask;
+ } else {
+ byteVal &= ~mask;
+ }
+ lx++;
+ srcOff += 4;
+ }
+ dst[byteIdx] = byteVal;
+ }
}
-
- packRGBATo1Bit(tileScratch, tile.data);
} else {
unpack8BitToRGBA(tile.data, tileScratch);
for (let sy = srcStartY; sy < srcEndY; sy++) {
@@ -1496,6 +1772,7 @@ export class SparseTileGrid {
packRGBATo8Bit(tileScratch, tile.data);
}
+ tile.solidColorU32 = undefined;
tile.dirty = true;
tile.version++;
this.markLodAncestorsDirty(layerId, tx, ty);
@@ -1509,6 +1786,374 @@ export class SparseTileGrid {
return { minTileX, minTileY, maxTileX, maxTileY };
}
+ /**
+ * Composites an isolated stroke RGBA buffer directly onto LOD 0 tiles in-place,
+ * avoiding full-region canvas allocation, existing-tile unpacking, and separate
+ * binarization passes. Records pre-edit tile snapshots into `snapshotOut` only
+ * for tiles with non-zero stroke pixels.
+ */
+ public compositeStrokeToTiles(options: {
+ layerId: string;
+ strokeData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number };
+ destX: number;
+ destY: number;
+ format: TileFormat;
+ compositeOp: 'source-over' | 'destination-out' | 'source-atop';
+ opacity: number;
+ monochrome?: {
+ threshold: number;
+ expressBlack: boolean;
+ expressWhite: boolean;
+ };
+ selectionMask?: {
+ mask: Uint8Array;
+ bounds: { x: number; y: number; width: number; height: number };
+ } | null;
+ snapshotOut?: Map<string, { format: TileFormat; data: Uint8Array | null }>;
+ suppressNotify?: boolean;
+ }): boolean {
+ const {
+ layerId,
+ strokeData,
+ destX,
+ destY,
+ format: targetFormat,
+ compositeOp,
+ monochrome,
+ selectionMask,
+ snapshotOut,
+ suppressNotify = false,
+ } = options;
+ const opacity = Math.max(0, Math.min(1, options.opacity));
+ const w = strokeData.width;
+ const h = strokeData.height;
+ if (w <= 0 || h <= 0 || opacity <= 0.001) return false;
+
+ this.ingestedLayers.add(layerId);
+ this.setLayerFormat(layerId, targetFormat);
+
+ const minTileX = pixelToTileCoord(destX, 0);
+ const minTileY = pixelToTileCoord(destY, 0);
+ const maxTileX = pixelToTileCoord(destX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(destY + h - 1, 0);
+
+ const srcData = strokeData.data;
+ const src32 =
+ srcData.byteOffset % 4 === 0 && srcData.byteLength >= w * h * 4
+ ? new Uint32Array(srcData.buffer, srcData.byteOffset, w * h)
+ : null;
+
+ const monoThresh = Math.max(1, Math.min(255, monochrome?.threshold ?? 128));
+ const monoExpressBlack = monochrome?.expressBlack !== false;
+ const hasSelMask = Boolean(selectionMask?.mask);
+ const selMask = selectionMask?.mask ?? null;
+ const selBx = selectionMask ? Math.floor(selectionMask.bounds.x) : 0;
+ const selBy = selectionMask ? Math.floor(selectionMask.bounds.y) : 0;
+ const selBw = selectionMask ? Math.ceil(selectionMask.bounds.width) : 0;
+ const selBh = selectionMask ? Math.ceil(selectionMask.bounds.height) : 0;
+ const fullOpacity = opacity >= 0.999;
+
+ let anyModified = false;
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+
+ const srcStartX = Math.max(0, tileDocX - destX);
+ const srcStartY = Math.max(0, tileDocY - destY);
+ const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
+ const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
+ if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
+
+ let existingTile = this.getTile(layerId, tx, ty, 0);
+
+ // Erasing or alpha-locking against an empty tile is a no-op
+ if ((compositeOp === 'destination-out' || compositeOp === 'source-atop') && (!existingTile || !existingTile.data)) {
+ continue;
+ }
+
+ // Fast zero-scan: skip tiles where the stroke overlap is completely transparent
+ let hasNonZero = false;
+ if (src32 !== null) {
+ outerZero32: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const rowOff = sy * w;
+ for (let sx = rowOff + srcStartX, end = rowOff + srcEndX; sx < end; sx++) {
+ if ((src32[sx] >>> 24) !== 0) {
+ hasNonZero = true;
+ break outerZero32;
+ }
+ }
+ }
+ } else {
+ outerZero8: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ let off = (sy * w + srcStartX) << 2;
+ const endOff = (sy * w + srcEndX) << 2;
+ for (; off < endOff; off += 4) {
+ if (srcData[off + 3] !== 0) {
+ hasNonZero = true;
+ break outerZero8;
+ }
+ }
+ }
+ }
+ if (!hasNonZero) continue;
+
+ // Snapshot pre-edit tile state before mutating
+ if (snapshotOut) {
+ const tileKey = getTileKey(layerId, tx, ty, 0);
+ if (!snapshotOut.has(tileKey)) {
+ snapshotOut.set(tileKey, {
+ format: existingTile ? existingTile.format : targetFormat,
+ data: existingTile?.data ? new Uint8Array(existingTile.data) : null,
+ });
+ }
+ }
+
+ const tile = existingTile ?? this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (tile.format !== targetFormat) {
+ const prevRGBA = tile.data ? new Uint8Array(this.getTileAsRGBA(tile)) : null;
+ if (tile.data !== null) {
+ this.memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = targetFormat;
+ tile.data = new Uint8Array(getTileByteSize(targetFormat));
+ if (prevRGBA) {
+ if (targetFormat === 'color-32bit') {
+ tile.data.set(prevRGBA);
+ } else if (targetFormat === 'monochrome-1bit') {
+ packRGBATo1Bit(prevRGBA, tile.data, monoThresh);
+ } else {
+ packRGBATo8Bit(prevRGBA, tile.data);
+ }
+ }
+ this.memoryManager?.notifyTileAllocated(tile);
+ } else if (tile.data === null) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ this.memoryManager?.notifyTileAllocated(tile);
+ }
+
+ const localStartX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ if (tile.format === 'monochrome-1bit') {
+ const dst = tile.data;
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const docY = destY + sy;
+ const rowByteBase = tileLocalY << 5;
+ let srcOff = (sy * w + srcStartX) << 2;
+ const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
+ const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
+
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+
+ let effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (hasSelMask) {
+ const docX = destX + srcStartX + dx;
+ if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
+ const ma = selMask![selRowOff + (docX - selBx)];
+ if (ma === 0) continue;
+ if (ma < 255) {
+ effA = Math.round((effA * ma) / 255);
+ }
+ }
+
+ const lx = localStartX + dx;
+ const byteIdx = rowByteBase + (lx >> 3);
+ const mask = 1 << (7 - (lx & 7));
+
+ if (compositeOp === 'destination-out') {
+ if (effA >= 128) {
+ dst[byteIdx] &= ~mask;
+ }
+ } else if (compositeOp === 'source-atop') {
+ if ((dst[byteIdx] & mask) === 0) continue;
+ const r = srcData[srcOff];
+ const g = srcData[srcOff + 1];
+ const b = srcData[srcOff + 2];
+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
+ const outLum = (lum * effA) / 255;
+ if (outLum < monoThresh && monoExpressBlack) {
+ dst[byteIdx] |= mask;
+ } else {
+ dst[byteIdx] &= ~mask;
+ }
+ } else {
+ const hadInk = (dst[byteIdx] & mask) !== 0;
+ const r = srcData[srcOff];
+ const g = srcData[srcOff + 1];
+ const b = srcData[srcOff + 2];
+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
+ if (!hadInk) {
+ if (effA >= 128 && lum < monoThresh && monoExpressBlack) {
+ dst[byteIdx] |= mask;
+ }
+ } else {
+ const outLum = (lum * effA) / 255;
+ if (outLum >= monoThresh || !monoExpressBlack) {
+ dst[byteIdx] &= ~mask;
+ }
+ }
+ }
+ }
+ }
+ } else if (tile.format === 'color-32bit') {
+ const dst = tile.data;
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const docY = destY + sy;
+ let srcOff = (sy * w + srcStartX) << 2;
+ let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
+ const selRowValid = hasSelMask && docY >= selBy && docY < selBy + selBh;
+ const selRowOff = selRowValid ? (docY - selBy) * selBw : 0;
+
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+
+ let effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (effA === 0) continue;
+
+ let maskFrac = 1.0;
+ if (hasSelMask) {
+ const docX = destX + srcStartX + dx;
+ if (!selRowValid || docX < selBx || docX >= selBx + selBw) continue;
+ const ma = selMask![selRowOff + (docX - selBx)];
+ if (ma === 0) continue;
+ if (ma < 255) maskFrac = ma / 255;
+ }
+
+ const sr = srcData[srcOff];
+ const sg = srcData[srcOff + 1];
+ const sb = srcData[srcOff + 2];
+ const da = dst[dstOff + 3];
+
+ let outR = dst[dstOff];
+ let outG = dst[dstOff + 1];
+ let outB = dst[dstOff + 2];
+ let outA = da;
+
+ if (compositeOp === 'destination-out') {
+ if (da === 0) continue;
+ if (effA === 255) {
+ outR = 0;
+ outG = 0;
+ outB = 0;
+ outA = 0;
+ } else {
+ outA = Math.round(da * (1 - effA / 255));
+ if (outA === 0) {
+ outR = 0;
+ outG = 0;
+ outB = 0;
+ }
+ }
+ } else if (compositeOp === 'source-atop') {
+ if (da === 0) continue;
+ if (effA === 255) {
+ outR = sr;
+ outG = sg;
+ outB = sb;
+ } else {
+ const sA = effA / 255;
+ const inv = 1 - sA;
+ outR = Math.round(sr * sA + outR * inv);
+ outG = Math.round(sg * sA + outG * inv);
+ outB = Math.round(sb * sA + outB * inv);
+ }
+ } else {
+ if (effA === 255 || da === 0) {
+ outR = sr;
+ outG = sg;
+ outB = sb;
+ outA = effA;
+ } else {
+ const sA = effA / 255;
+ const dA = da / 255;
+ const invSA = 1 - sA;
+ const compA = sA + dA * invSA;
+ if (compA > 0) {
+ const invOut = 1 / compA;
+ outR = Math.round((sr * sA + outR * dA * invSA) * invOut);
+ outG = Math.round((sg * sA + outG * dA * invSA) * invOut);
+ outB = Math.round((sb * sA + outB * dA * invSA) * invOut);
+ outA = Math.round(compA * 255);
+ }
+ }
+ }
+
+ if (maskFrac < 1.0) {
+ const invM = 1 - maskFrac;
+ const bA = da / 255;
+ const aA = outA / 255;
+ const mixA = bA * invM + aA * maskFrac;
+ if (mixA <= 0.0001) {
+ dst[dstOff] = 0;
+ dst[dstOff + 1] = 0;
+ dst[dstOff + 2] = 0;
+ dst[dstOff + 3] = 0;
+ } else {
+ const invMixA = 1 / mixA;
+ dst[dstOff] = Math.round((dst[dstOff] * bA * invM + outR * aA * maskFrac) * invMixA);
+ dst[dstOff + 1] = Math.round((dst[dstOff + 1] * bA * invM + outG * aA * maskFrac) * invMixA);
+ dst[dstOff + 2] = Math.round((dst[dstOff + 2] * bA * invM + outB * aA * maskFrac) * invMixA);
+ dst[dstOff + 3] = Math.round(mixA * 255);
+ }
+ } else {
+ dst[dstOff] = outR;
+ dst[dstOff + 1] = outG;
+ dst[dstOff + 2] = outB;
+ dst[dstOff + 3] = outA;
+ }
+ }
+ }
+ } else {
+ // grayscale-8bit fallback
+ const tileScratch = this.writeScratchRGBA;
+ unpack8BitToRGBA(tile.data, tileScratch);
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ let srcOff = (sy * w + srcStartX) << 2;
+ let dstOff = (tileLocalY * TILE_SIZE + localStartX) << 2;
+ for (let dx = 0; dx < copyWidth; dx++, srcOff += 4, dstOff += 4) {
+ const sa = srcData[srcOff + 3];
+ if (sa === 0) continue;
+ const effA = fullOpacity ? sa : Math.round(sa * opacity);
+ if (compositeOp === 'destination-out') {
+ tileScratch[dstOff + 3] = Math.round(tileScratch[dstOff + 3] * (1 - effA / 255));
+ } else if (effA > 0) {
+ const sA = effA / 255;
+ const inv = 1 - sA;
+ tileScratch[dstOff] = Math.round(srcData[srcOff] * sA + tileScratch[dstOff] * inv);
+ tileScratch[dstOff + 1] = Math.round(srcData[srcOff + 1] * sA + tileScratch[dstOff + 1] * inv);
+ tileScratch[dstOff + 2] = Math.round(srcData[srcOff + 2] * sA + tileScratch[dstOff + 2] * inv);
+ tileScratch[dstOff + 3] = Math.min(255, Math.round(tileScratch[dstOff + 3] * inv + effA));
+ }
+ }
+ }
+ packRGBATo8Bit(tileScratch, tile.data);
+ }
+
+ tile.solidColorU32 = undefined;
+ tile.dirty = true;
+ tile.version++;
+ this.markLodAncestorsDirty(layerId, tx, ty);
+ anyModified = true;
+ }
+ }
+
+ if (anyModified) {
+ this.bumpLayerVersion(layerId);
+ if (!suppressNotify) {
+ this.notifyChange();
+ }
+ }
+ return anyModified;
+ }
+
public readImageData(
layerId: string,
x: number,
@@ -1608,27 +2253,67 @@ export class SparseTileGrid {
}
/**
- * Allocates a temporary HTMLCanvasElement strictly sized to `rect` and populates it from tiles.
- * Caller must release it via `releaseTemporaryCanvas(canvas)` when finished.
+ * Populates a temporary (or caller-supplied pooled) HTMLCanvasElement strictly sized to `rect` from tiles.
+ * When `targetCanvas` is omitted, caller must release the returned canvas via `releaseTemporaryCanvas(canvas)`.
*/
public createRegionCanvas(
layerId: string,
- rect: { x: number; y: number; width: number; height: number }
+ rect: { x: number; y: number; width: number; height: number },
+ targetCanvas?: HTMLCanvasElement | null
): HTMLCanvasElement | null {
if (typeof document === 'undefined' || rect.width <= 0 || rect.height <= 0) return null;
const w = Math.max(1, Math.ceil(rect.width));
const h = Math.max(1, Math.ceil(rect.height));
- const canvas = document.createElement('canvas');
- canvas.width = w;
- canvas.height = h;
+ const canvas = targetCanvas || document.createElement('canvas');
+ const resized = canvas.width !== w || canvas.height !== h;
+ if (canvas.width !== w) canvas.width = w;
+ if (canvas.height !== h) canvas.height = h;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return canvas;
+ if (!resized) {
+ ctx.clearRect(0, 0, w, h);
+ }
- if (this.hasLayerTiles(layerId)) {
- const region = this.readImageData(layerId, Math.floor(rect.x), Math.floor(rect.y), w, h);
- if (typeof ImageData !== 'undefined') {
- const imgData = new ImageData(new Uint8ClampedArray(region.data.buffer as ArrayBuffer, region.data.byteOffset, region.data.byteLength), w, h);
- ctx.putImageData(imgData, 0, 0);
+ if (this.hasLayerTiles(layerId) && typeof ImageData !== 'undefined') {
+ const originX = Math.floor(rect.x);
+ const originY = Math.floor(rect.y);
+ const minTileX = pixelToTileCoord(originX, 0);
+ const minTileY = pixelToTileCoord(originY, 0);
+ const maxTileX = pixelToTileCoord(originX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(originY + h - 1, 0);
+
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const interStartY = Math.max(originY, tileDocY);
+ const interEndY = Math.min(originY + h, tileDocY + TILE_SIZE);
+ const dirtyH = interEndY - interStartY;
+ if (dirtyH <= 0) continue;
+ const dirtyY = interStartY - tileDocY;
+
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tile = this.getTile(layerId, tx, ty, 0);
+ if (!tile) continue;
+
+ const tileDocX = tx * TILE_SIZE;
+ const interStartX = Math.max(originX, tileDocX);
+ const interEndX = Math.min(originX + w, tileDocX + TILE_SIZE);
+ const dirtyW = interEndX - interStartX;
+ if (dirtyW <= 0) continue;
+ const dirtyX = interStartX - tileDocX;
+
+ const rgba = this.getTileAsRGBA(tile);
+ const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
+ const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
+ ctx.putImageData(
+ imgData,
+ tileDocX - originX,
+ tileDocY - originY,
+ dirtyX,
+ dirtyY,
+ dirtyW,
+ dirtyH
+ );
+ }
}
}
return canvas;
@@ -1658,27 +2343,16 @@ export class SparseTileGrid {
return this.getLayerTiles(layerId);
}
- const lodCoords = new Map<string, { tx: number; ty: number }>();
-
- for (const tile of this.tiles.values()) {
- if (tile.layerId !== layerId) continue;
- if ((tile.lod ?? 0) === 0) {
- const ltx = tile.tileX >> lod;
- const lty = tile.tileY >> lod;
- const k = `${ltx}:${lty}`;
- if (!lodCoords.has(k)) {
- lodCoords.set(k, { tx: ltx, ty: lty });
- }
- } else if (tile.lod === lod) {
- const k = `${tile.tileX}:${tile.tileY}`;
- if (!lodCoords.has(k)) {
- lodCoords.set(k, { tx: tile.tileX, ty: tile.tileY });
- }
- }
+ const occ = this.layerLodOccupancy.get(layerId);
+ const lodOccMap = occ ? occ[lod - 1] : null;
+ if (!lodOccMap || lodOccMap.size === 0) {
+ return this.getLayerTiles(layerId, lod);
}
const result: TileBuffer[] = [];
- for (const { tx, ty } of lodCoords.values()) {
+ for (const packed of lodOccMap.keys()) {
+ const tx = unpackTileCoordX(packed);
+ const ty = unpackTileCoordY(packed);
let tile = this.getTile(layerId, tx, ty, lod);
if (!tile || tile.data === null || this.isLodTileDirty(layerId, tx, ty, lod)) {
tile = this.generateLodTile(layerId, tx, ty, lod);
@@ -1832,6 +2506,20 @@ export class SparseTileGrid {
return this.getTile(layerId, lodTx, lodTy, 0);
}
+ const key = getTileKey(layerId, lodTx, lodTy, targetLod);
+
+ // O(1) empty-region fast-out: if no LOD 0 tile exists anywhere under this LOD node,
+ // never recurse or allocate a temporary 256KB TileBuffer.
+ if (!this.hasPopulatedLodTile(layerId, lodTx, lodTy, targetLod)) {
+ const stale = this.tiles.get(key);
+ if (stale) {
+ this.memoryManager?.notifyTileFreed(stale);
+ this.tiles.delete(key);
+ }
+ this.dirtyLodTiles.delete(key);
+ return null;
+ }
+
const childLod = targetLod - 1;
const cX0 = lodTx << 1;
const cY0 = lodTy << 1;
@@ -1842,25 +2530,56 @@ export class SparseTileGrid {
let c11 = this.getTile(layerId, cX0 + 1, cY0 + 1, childLod);
if (childLod > 0) {
- if (!c00 || this.isLodTileDirty(layerId, cX0, cY0, childLod)) {
- c00 = this.generateLodTile(layerId, cX0, cY0, childLod);
+ if (this.hasPopulatedLodTile(layerId, cX0, cY0, childLod)) {
+ if (!c00 || c00.data === null || this.isLodTileDirty(layerId, cX0, cY0, childLod)) {
+ c00 = this.generateLodTile(layerId, cX0, cY0, childLod);
+ }
+ } else {
+ c00 = null;
}
- if (!c10 || this.isLodTileDirty(layerId, cX0 + 1, cY0, childLod)) {
- c10 = this.generateLodTile(layerId, cX0 + 1, cY0, childLod);
+ if (this.hasPopulatedLodTile(layerId, cX0 + 1, cY0, childLod)) {
+ if (!c10 || c10.data === null || this.isLodTileDirty(layerId, cX0 + 1, cY0, childLod)) {
+ c10 = this.generateLodTile(layerId, cX0 + 1, cY0, childLod);
+ }
+ } else {
+ c10 = null;
}
- if (!c01 || this.isLodTileDirty(layerId, cX0, cY0 + 1, childLod)) {
- c01 = this.generateLodTile(layerId, cX0, cY0 + 1, childLod);
+ if (this.hasPopulatedLodTile(layerId, cX0, cY0 + 1, childLod)) {
+ if (!c01 || c01.data === null || this.isLodTileDirty(layerId, cX0, cY0 + 1, childLod)) {
+ c01 = this.generateLodTile(layerId, cX0, cY0 + 1, childLod);
+ }
+ } else {
+ c01 = null;
}
- if (!c11 || this.isLodTileDirty(layerId, cX0 + 1, cY0 + 1, childLod)) {
- c11 = this.generateLodTile(layerId, cX0 + 1, cY0 + 1, childLod);
+ if (this.hasPopulatedLodTile(layerId, cX0 + 1, cY0 + 1, childLod)) {
+ if (!c11 || c11.data === null || this.isLodTileDirty(layerId, cX0 + 1, cY0 + 1, childLod)) {
+ c11 = this.generateLodTile(layerId, cX0 + 1, cY0 + 1, childLod);
+ }
+ } else {
+ c11 = null;
}
}
- const firstChild = c00 || c10 || c01 || c11;
- const format = firstChild ? firstChild.format : this.getLayerFormat(layerId);
+ const firstChild =
+ (c00 && c00.data !== null ? c00 : null) ||
+ (c10 && c10.data !== null ? c10 : null) ||
+ (c01 && c01.data !== null ? c01 : null) ||
+ (c11 && c11.data !== null ? c11 : null);
- const key = getTileKey(layerId, lodTx, lodTy, targetLod);
let tile = this.tiles.get(key);
+ if (!firstChild) {
+ if (tile) {
+ this.memoryManager?.notifyTileFreed(tile);
+ this.tiles.delete(key);
+ }
+ this.dirtyLodTiles.delete(key);
+ return null;
+ }
+
+ // Ephemeral display LOD > 0 tiles for monochrome-1bit layers use box-filtered color-32bit
+ // coverage instead of bitwise-OR dilation so zoomed-out lines match live mipmapped drafts.
+ const format: TileFormat =
+ firstChild.format === 'monochrome-1bit' ? 'color-32bit' : firstChild.format;
let allocatedNew = false;
if (!tile) {
@@ -2015,7 +2734,9 @@ export class SparseTileGrid {
const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
if (validW === TILE_SIZE && validH === TILE_SIZE) {
dst32.fill(pixelU32);
+ tile.solidColorU32 = pixelU32;
} else {
+ tile.solidColorU32 = undefined;
dst32.fill(0);
for (let y = 0; y < validH; y++) {
const rowStart = y * TILE_SIZE;
@@ -2023,6 +2744,7 @@ export class SparseTileGrid {
}
}
} else if (tile.format === 'grayscale-8bit') {
+ tile.solidColorU32 = undefined;
if (validW === TILE_SIZE && validH === TILE_SIZE) {
tile.data.fill(grayVal);
} else {
@@ -2033,6 +2755,7 @@ export class SparseTileGrid {
}
}
} else {
+ tile.solidColorU32 = undefined;
tile.data.fill(0);
for (let y = 0; y < validH; y++) {
for (let x = 0; x < validW; x++) {
@@ -2079,14 +2802,23 @@ export class SparseTileGrid {
this.memoryManager?.notifyTileAllocated(tile);
}
if (validW === TILE_SIZE && validH === TILE_SIZE) {
- tile.data.fill(255);
+ if (tile.format === 'color-32bit') {
+ new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS).fill(PAPER_WHITE_U32);
+ tile.solidColorU32 = PAPER_WHITE_U32;
+ } else {
+ tile.data.fill(255);
+ tile.solidColorU32 = undefined;
+ }
} else if (tile.format === 'color-32bit') {
- tile.data.fill(0);
+ tile.solidColorU32 = undefined;
+ const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
+ dst32.fill(0);
for (let y = 0; y < validH; y++) {
- const rowStart = y * TILE_SIZE * 4;
- tile.data.fill(255, rowStart, rowStart + validW * 4);
+ const rowStart = y * TILE_SIZE;
+ dst32.fill(PAPER_WHITE_U32, rowStart, rowStart + validW);
}
} else {
+ tile.solidColorU32 = undefined;
tile.data.fill(0);
for (let y = 0; y < validH; y++) {
const rowStart = y * TILE_SIZE;
@@ -2145,6 +2877,8 @@ export class SparseTileGrid {
public clearLayer(layerId: string): void {
this.ingestedLayers.delete(layerId);
+ this.layerLod0Tiles.delete(layerId);
+ this.layerLodOccupancy.delete(layerId);
const prefix = `${layerId}:`;
const toDelete: string[] = [];
for (const [key, tile] of this.tiles.entries()) {
@@ -2186,6 +2920,7 @@ export class SparseTileGrid {
isPagedToDisk: false,
lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
lod: 0,
+ solidColorU32: srcTile.solidColorU32,
};
this.setTile(dstLayerId, srcTile.tileX, srcTile.tileY, clonedTile);
}
@@ -2316,20 +3051,34 @@ export class SparseTileGrid {
const currentTile = this.getTile(layerId, tileX, tileY, 0);
const beforeData = before ? before.data : null;
- const afterData = currentTile && currentTile.data ? new Uint8Array(currentTile.data) : null;
+ const currentData = currentTile && currentTile.data ? currentTile.data : null;
const format = currentTile ? currentTile.format : (before ? before.format : this.getLayerFormat(layerId));
- if (beforeData === null && afterData === null) continue;
+ if (beforeData === null && currentData === null) continue;
let changed = false;
- if ((beforeData === null) !== (afterData === null)) {
+ if ((beforeData === null) !== (currentData === null)) {
changed = true;
- } else if (beforeData && afterData) {
- if (beforeData.byteLength !== afterData.byteLength) {
+ } else if (beforeData && currentData) {
+ if (beforeData.byteLength !== currentData.byteLength) {
changed = true;
+ } else if (
+ beforeData.byteLength % 4 === 0 &&
+ beforeData.byteOffset % 4 === 0 &&
+ currentData.byteOffset % 4 === 0
+ ) {
+ const len32 = beforeData.byteLength >>> 2;
+ const b32 = new Uint32Array(beforeData.buffer, beforeData.byteOffset, len32);
+ const c32 = new Uint32Array(currentData.buffer, currentData.byteOffset, len32);
+ for (let i = 0; i < len32; i++) {
+ if (b32[i] !== c32[i]) {
+ changed = true;
+ break;
+ }
+ }
} else {
for (let i = 0; i < beforeData.byteLength; i++) {
- if (beforeData[i] !== afterData[i]) {
+ if (beforeData[i] !== currentData[i]) {
changed = true;
break;
}
@@ -2342,7 +3091,7 @@ export class SparseTileGrid {
key,
format,
beforeData,
- afterData,
+ afterData: currentData ? new Uint8Array(currentData) : null,
});
}
}
@@ -2370,6 +3119,7 @@ export class SparseTileGrid {
this.memoryManager?.notifyTileAllocated(tile);
}
tile.data.set(targetData);
+ tile.solidColorU32 = undefined;
tile.format = delta.format;
this.setLayerFormat(layerId, delta.format);
tile.dirty = true;
@@ -2388,11 +3138,14 @@ export class SparseTileGrid {
}
}
this.tiles.clear();
+ this.layerLod0Tiles.clear();
+ this.layerLodOccupancy.clear();
this.layerFormats.clear();
this.ingestedLayers.clear();
this.dirtyLodTiles.clear();
this.layerVersions.clear();
this.gridEpoch++;
+ this.contentVersion++;
this.notifyChange(true);
}
@@ -2413,6 +3166,9 @@ export class SparseTileGrid {
}
for (const tile of tiles) {
this.tiles.set(getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0), tile);
+ if ((tile.lod ?? 0) === 0) {
+ this.registerLod0Tile(tile);
+ }
if (this.memoryManager) {
this.memoryManager.notifyTileAllocated(tile);
}
diff --git a/src/utils/webglBrushEngine.ts b/src/utils/webglBrushEngine.ts
index d59f15c..dedb51b 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/utils/webglBrushEngine.ts
@@ -1313,11 +1313,84 @@ export class WebGlBrushEngine {
targetCtx.imageSmoothingEnabled = false;
}
- // Tile across dirty bounding box in <= 2048x2048 chunks so 70MP B4 600DPI strokes NEVER clip at 4096px!
- for (let cy = fullDirtyY; cy < fullDirtyMaxY; cy += MAX_TILE_CHUNK) {
- const dh = Math.min(MAX_TILE_CHUNK, fullDirtyMaxY - cy);
- for (let cx = fullDirtyX; cx < fullDirtyMaxX; cx += MAX_TILE_CHUNK) {
- const dw = Math.min(MAX_TILE_CHUNK, fullDirtyMaxX - cx);
+ // Tile across dirty bounding box in <= 2048x2048 chunks so 70MP B4 600DPI strokes NEVER clip at 4096px.
+ // For multi-chunk strokes (e.g. diagonal strokes on 6071x8598), pre-bin dab bounds per chunk so empty
+ // chunks are skipped completely and populated chunks use tightened viewports/readbacks.
+ const chunkCols = Math.ceil(totalW / MAX_TILE_CHUNK);
+ const chunkRows = Math.ceil(totalH / MAX_TILE_CHUNK);
+ const isMultiChunk = chunkCols > 1 || chunkRows > 1;
+ let cMinX: Float32Array | null = null;
+ let cMinY: Float32Array | null = null;
+ let cMaxX: Float32Array | null = null;
+ let cMaxY: Float32Array | null = null;
+
+ if (isMultiChunk) {
+ const chunkCount = chunkCols * chunkRows;
+ cMinX = new Float32Array(chunkCount);
+ cMinY = new Float32Array(chunkCount);
+ cMaxX = new Float32Array(chunkCount);
+ cMaxY = new Float32Array(chunkCount);
+ cMinX.fill(Infinity);
+ cMinY.fill(Infinity);
+ cMaxX.fill(-Infinity);
+ cMaxY.fill(-Infinity);
+
+ for (let i = 0; i < dabs.length; i++) {
+ const off = i * stride;
+ const dx = arr[off];
+ const dy = arr[off + 1];
+ const rad = Math.max(arr[off + 2], arr[off + 3]) * 0.75 + 4;
+ const x0 = dx - rad;
+ const y0 = dy - rad;
+ const x1 = dx + rad;
+ const y1 = dy + rad;
+
+ const col0 = Math.max(0, Math.floor((x0 - fullDirtyX) / MAX_TILE_CHUNK));
+ const col1 = Math.min(chunkCols - 1, Math.floor((x1 - fullDirtyX) / MAX_TILE_CHUNK));
+ const row0 = Math.max(0, Math.floor((y0 - fullDirtyY) / MAX_TILE_CHUNK));
+ const row1 = Math.min(chunkRows - 1, Math.floor((y1 - fullDirtyY) / MAX_TILE_CHUNK));
+
+ for (let r = row0; r <= row1; r++) {
+ const rowBase = r * chunkCols;
+ for (let c = col0; c <= col1; c++) {
+ const idx = rowBase + c;
+ if (x0 < cMinX[idx]) cMinX[idx] = x0;
+ if (y0 < cMinY[idx]) cMinY[idx] = y0;
+ if (x1 > cMaxX[idx]) cMaxX[idx] = x1;
+ if (y1 > cMaxY[idx]) cMaxY[idx] = y1;
+ }
+ }
+ }
+ }
+
+ for (let row = 0; row < chunkRows; row++) {
+ const cy = fullDirtyY + row * MAX_TILE_CHUNK;
+ const chunkMaxY = Math.min(fullDirtyMaxY, cy + MAX_TILE_CHUNK);
+ for (let col = 0; col < chunkCols; col++) {
+ const cx = fullDirtyX + col * MAX_TILE_CHUNK;
+ const chunkMaxX = Math.min(fullDirtyMaxX, cx + MAX_TILE_CHUNK);
+
+ let rx = cx;
+ let ry = cy;
+ let dw = chunkMaxX - cx;
+ let dh = chunkMaxY - cy;
+
+ if (isMultiChunk && cMinX && cMinY && cMaxX && cMaxY) {
+ const idx = row * chunkCols + col;
+ if (cMinX[idx] >= cMaxX[idx] || cMinY[idx] >= cMaxY[idx]) {
+ continue;
+ }
+ rx = Math.max(cx, Math.floor(cMinX[idx]));
+ ry = Math.max(cy, Math.floor(cMinY[idx]));
+ const rxEnd = Math.min(chunkMaxX, Math.ceil(cMaxX[idx]));
+ const ryEnd = Math.min(chunkMaxY, Math.ceil(cMaxY[idx]));
+ dw = rxEnd - rx;
+ dh = ryEnd - ry;
+ if (dw <= 0 || dh <= 0) {
+ continue;
+ }
+ }
+
const viewY = Math.max(0, canvas.height - dh);
if (useOffscreenFbo && this.dabFbo) {
@@ -1334,7 +1407,7 @@ export class WebGlBrushEngine {
gl.uniform2f(this.uCanvasResolutionLoc, dw, dh);
if (this.uDirtyOffsetLoc) {
- gl.uniform2f(this.uDirtyOffsetLoc, cx, cy);
+ gl.uniform2f(this.uDirtyOffsetLoc, rx, ry);
}
if (useInstanced && this.extInstanced) {
@@ -1379,7 +1452,7 @@ export class WebGlBrushEngine {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
}
- targetCtx.drawImage(canvas, 0, 0, dw, dh, cx, cy, dw, dh);
+ targetCtx.drawImage(canvas, 0, 0, dw, dh, rx, ry, dw, dh);
}
}
diff --git a/src/utils/webtoonExporter.ts b/src/utils/webtoonExporter.ts
index a1988fc..9cdda92 100644
--- a/src/utils/webtoonExporter.ts
+++ b/src/utils/webtoonExporter.ts
@@ -9,6 +9,7 @@
*/
import { zipSync } from 'fflate';
+import { releaseTemporaryCanvas } from './tileEngine';
export interface WebtoonSliceOptions {
sliceWidth?: number;
@@ -19,6 +20,15 @@ export interface WebtoonSliceOptions {
onProgress?: (progress: { current: number; total: number; percent: number }) => void;
}
+export type WebtoonRegionRenderer = (
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ targetCanvas: HTMLCanvasElement,
+ fillWhiteBackground: boolean
+) => void;
+
/**
* Extracts a Uint8Array from a canvas slice
*/
@@ -113,9 +123,65 @@ export async function exportWebtoonChapterZip(
// Synchronously pack into ZIP archive
const zipBytes = zipSync(zipFiles, { level: 6 });
+ releaseTemporaryCanvas(sliceCanvas);
return zipBytes;
}
+/**
+ * Renders and slices a tall Webtoon directly via a tiled GPU region renderer (e.g. from
+ * `createDocumentRegionRenderer`), preserving 100% of GPU blend modes, Layer Styles,
+ * Screentones, Layer Color Tint, Expression Color, and Adjustment Layers without ever
+ * allocating a monolithic full-height canvas.
+ */
+export async function exportWebtoonChapterZipFromRenderer(
+ totalWidth: number,
+ totalHeight: number,
+ renderRegion: WebtoonRegionRenderer,
+ options: WebtoonSliceOptions = {}
+): Promise<Uint8Array> {
+ const sliceHeight = options.sliceHeight || 1280;
+ const format = options.format || 'jpg';
+ const quality = options.quality ?? 0.92;
+ const filePrefix = options.filePrefix || 'slice_';
+ const ext = format === 'jpg' ? 'jpg' : 'png';
+ const fillWhite = format === 'jpg';
+
+ const sliceWidth = options.sliceWidth || totalWidth;
+ const totalSlices = Math.max(1, Math.ceil(totalHeight / sliceHeight));
+
+ const zipFiles: Record<string, Uint8Array> = {};
+ const sliceCanvas = document.createElement('canvas');
+ sliceCanvas.width = sliceWidth;
+
+ try {
+ for (let i = 0; i < totalSlices; i++) {
+ const srcY = i * sliceHeight;
+ const currentSliceH = Math.min(sliceHeight, totalHeight - srcY);
+ sliceCanvas.height = currentSliceH;
+
+ renderRegion(0, srcY, sliceWidth, currentSliceH, sliceCanvas, fillWhite);
+
+ const bytes = await canvasSliceToBytes(sliceCanvas, format, quality);
+ const fileName = `${filePrefix}${String(i + 1).padStart(3, '0')}.${ext}`;
+ zipFiles[fileName] = bytes;
+
+ if (options.onProgress) {
+ options.onProgress({
+ current: i + 1,
+ total: totalSlices,
+ percent: Math.round(((i + 1) / totalSlices) * 100),
+ });
+ }
+
+ await new Promise((r) => setTimeout(r, 4));
+ }
+
+ return zipSync(zipFiles, { level: 6 });
+ } finally {
+ releaseTemporaryCanvas(sliceCanvas);
+ }
+}
+
/**
* Triggers a browser download of the generated Webtoon ZIP package.
*/