A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
ww2
Soracc130a7da2b3
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.tsindex 53a07aa..0138912 100644--- a/src/hooks/useCanvasDrawing.ts+++ b/src/hooks/useCanvasDrawing.ts@@ -13,8 +13,8 @@ import {} from '../types/editor';import {calculateStrokeWidth,- getMidPoint,- drawSmoothBezierSegment,+ drawSmoothCubicBezierSegment,+ catmullRomToBezier,drawDot,screenToCanvas,createCanvasThumbnail,@@ -24,10 +24,10 @@ import {getReusableBakeCanvas,renderCompleteStroke,} from '../utils/canvasUtils';-import { enforceColorMode, applyColorModeToCanvas } from '../utils/colorUtils';-import { drawPencilBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';+import { enforceColorMode, binarizeCanvasRect } from '../utils/colorUtils';+import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';import {- drawTexturedBezierSegment,+ drawTexturedCubicBezierSegment,drawTexturedDot,TexturedBrushOptions,} from '../utils/stampEngine';@@ -170,7 +170,10 @@ export function useCanvasDrawing({// Sliding window of points for real-time Bézier smoothing on the draft overlay canvasconst strokePointsRef = useRef<Point[]>([]);- // Stabilizer tracking ref for exponential moving average (EMA)+ // Raw points window buffer for symmetric Gaussian FIR stabilization+ const rawPointsBufferRef = useRef<{ x: number; y: number; pressure: number; pointerType: string }[]>([]);++ // Stabilizer tracking refconst stabilizedPointRef = useRef<Point | null>(null);// Distance accumulator for textured brush dab stepping@@ -180,9 +183,25 @@ export function useCanvasDrawing({const activeReservoirRef = useRef<PaintReservoir | null>(null);const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);const strokeBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const dedicatedBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);++ const getDedicatedBackupCanvas = useCallback((width: number, height: number): HTMLCanvasElement => {+ if (!dedicatedBackupCanvasRef.current) {+ dedicatedBackupCanvasRef.current = document.createElement('canvas');+ }+ const c = dedicatedBackupCanvasRef.current;+ if (c.width !== width || c.height !== height) {+ c.width = width;+ c.height = height;+ }+ return c;+ }, []);+const isWetColorStrokeRef = useRef<boolean>(false);const drewDirectlyOnLayerCanvasRef = useRef<boolean>(false);const lastPointTimeRef = useRef<number>(0);+ const recentPointsTrailRef = useRef<{ x: number; y: number; t: number; pressure: number; width: number }[]>([]);+ const strokeTotalDistanceRef = useRef<number>(0);// Dirty bounding box for the active strokeconst dirtyRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);@@ -193,8 +212,6 @@ export function useCanvasDrawing({const drawRafIdRef = useRef<number | null>(null);const clearDraftRafRef = useRef<number | null>(null);- // If raster layer eraser is active, we temporarily hide the layer while erasing live on the draft canvas- const hiddenLayerCanvasRef = useRef<HTMLCanvasElement | null>(null);// Undo / Redo history stack of rich history itemsconst historyRef = useRef<HistoryItem[]>([]);@@ -360,9 +377,58 @@ export function useCanvasDrawing({[getActiveCanvas, layerCanvasesRef, syncHistoryState]);+ // Abort any in-progress stroke session immediately+ const abortActiveStroke = useCallback(() => {+ if (!isDrawingRef.current) return;+ if (drawRafIdRef.current !== null) {+ cancelAnimationFrame(drawRafIdRef.current);+ drawRafIdRef.current = null;+ }+ const draftCanvas = effectiveDraftCanvasRef?.current;+ if (draftCanvas) {+ const dCtx = get2DContext(draftCanvas);+ if (dCtx) {+ try {+ dCtx.restore();+ } catch (_) {}+ dCtx.resetTransform();+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);+ }+ }+ if (drewDirectlyOnLayerCanvasRef.current && strokeBackupCanvasRef.current) {+ const currentLayerId = activeLayerIdRef.current;+ const canvas = layerCanvasesRef.current.get(currentLayerId) || getActiveCanvas();+ if (canvas && strokeBackupCanvasRef.current) {+ const cCtx = get2DContext(canvas);+ if (cCtx) {+ cCtx.clearRect(0, 0, canvas.width, canvas.height);+ cCtx.drawImage(strokeBackupCanvasRef.current, 0, 0);+ }+ }+ }+ isDrawingRef.current = false;+ activePointerIdRef.current = null;+ allStrokePointsRef.current = [];+ strokePointsRef.current = [];+ stabilizedPointRef.current = null;+ lastProcessedPointRef.current = null;+ dirtyRectRef.current = null;+ pendingPointsQueueRef.current = [];+ drewDirectlyOnLayerCanvasRef.current = false;+ isToneStrokeRef.current = false;+ strokeBackupCanvasRef.current = null;+ layerPixelSamplerRef.current = null;+ activeReservoirRef.current = null;+ snapSessionRef.current.endStroke();+ onActiveConstraintAxisChangeRef.current?.(null);+ }, [effectiveDraftCanvasRef, getActiveCanvas, layerCanvasesRef]);+// Jump directly to any past or future history stepconst jumpToHistoryIndex = useCallback((targetIndex: number) => {+ if (isDrawingRef.current) {+ abortActiveStroke();+ }if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;const currentIndex = historyIndexRef.current;if (targetIndex === currentIndex) return;@@ -376,40 +442,72 @@ export function useCanvasDrawing({const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);- const hasEffect = Boolean(- (targetLayer?.toneEnabled ||- targetLayer?.layerColorEnabled ||- (targetLayer?.expressionColor && targetLayer.expressionColor !== 'color')) &&- sourceCanvas- );- const destCanvas = hasEffect && sourceCanvas ? sourceCanvas : canvas;+ const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);- if (destCanvas) {- const ctx = get2DContext(destCanvas);- if (ctx) {+ if (isToneStep && sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ if (sCtx) {if (item.dirtyRect && item.beforeImageData) {- ctx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);+ sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);} else if (item.beforeImageData) {- ctx.putImageData(item.beforeImageData, 0, 0);+ sCtx.putImageData(item.beforeImageData, 0, 0);} else if (item.type === 'initial') {if (targetLayerId === 'layer-bg') {- ctx.fillStyle = '#ffffff';- ctx.fillRect(0, 0, destCanvas.width, destCanvas.height);+ sCtx.fillStyle = '#ffffff';+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);} else {- ctx.clearRect(0, 0, destCanvas.width, destCanvas.height);+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);}}}- }- if (hasEffect && sourceCanvas && canvas && targetLayer) {- applyLayerEffects(- sourceCanvas,- canvas,- targetLayer,- dimensionsRef.current.dpi ?? 600,- item.dirtyRect- );+ if (canvas && targetLayer) {+ applyLayerEffects(+ sourceCanvas,+ canvas,+ targetLayer,+ dimensionsRef.current.dpi ?? 600,+ item.dirtyRect+ );+ }+ } else {+ // Direct canvas restoration for monochrome, color, gray, normal pen, eraser, etc.+ if (canvas) {+ const cCtx = get2DContext(canvas);+ if (cCtx) {+ if (item.dirtyRect && item.beforeImageData) {+ cCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);+ } else if (item.beforeImageData) {+ cCtx.putImageData(item.beforeImageData, 0, 0);+ } else if (item.type === 'initial') {+ if (targetLayerId === 'layer-bg') {+ cCtx.fillStyle = '#ffffff';+ cCtx.fillRect(0, 0, canvas.width, canvas.height);+ } else {+ cCtx.clearRect(0, 0, canvas.width, canvas.height);+ }+ }+ }+ }++ // Keep sourceCanvas synchronized if present+ if (sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ if (sCtx) {+ if (item.dirtyRect && item.beforeImageData) {+ sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);+ } else if (item.beforeImageData) {+ sCtx.putImageData(item.beforeImageData, 0, 0);+ } else if (item.type === 'initial') {+ if (targetLayerId === 'layer-bg') {+ sCtx.fillStyle = '#ffffff';+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);+ } else {+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);+ }+ }+ }+ }}if (canvas) {@@ -427,40 +525,72 @@ export function useCanvasDrawing({const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);- const hasEffect = Boolean(- (targetLayer?.toneEnabled ||- targetLayer?.layerColorEnabled ||- (targetLayer?.expressionColor && targetLayer.expressionColor !== 'color')) &&- sourceCanvas- );- const destCanvas = hasEffect && sourceCanvas ? sourceCanvas : canvas;+ const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);- if (destCanvas) {- const ctx = get2DContext(destCanvas);- if (ctx) {+ if (isToneStep && sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ if (sCtx) {if (item.dirtyRect && dataToApply) {- ctx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);+ sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);} else if (dataToApply) {- ctx.putImageData(dataToApply, 0, 0);+ sCtx.putImageData(dataToApply, 0, 0);} else if (item.type === 'initial') {if (targetLayerId === 'layer-bg') {- ctx.fillStyle = '#ffffff';- ctx.fillRect(0, 0, destCanvas.width, destCanvas.height);+ sCtx.fillStyle = '#ffffff';+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);} else {- ctx.clearRect(0, 0, destCanvas.width, destCanvas.height);+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);}}}- }- if (hasEffect && sourceCanvas && canvas && targetLayer) {- applyLayerEffects(- sourceCanvas,- canvas,- targetLayer,- dimensionsRef.current.dpi ?? 600,- item.dirtyRect- );+ if (canvas && targetLayer) {+ applyLayerEffects(+ sourceCanvas,+ canvas,+ targetLayer,+ dimensionsRef.current.dpi ?? 600,+ item.dirtyRect+ );+ }+ } else {+ // Direct canvas restoration for monochrome, color, gray, normal pen, eraser, etc.+ if (canvas) {+ const cCtx = get2DContext(canvas);+ if (cCtx) {+ if (item.dirtyRect && dataToApply) {+ cCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);+ } else if (dataToApply) {+ cCtx.putImageData(dataToApply, 0, 0);+ } else if (item.type === 'initial') {+ if (targetLayerId === 'layer-bg') {+ cCtx.fillStyle = '#ffffff';+ cCtx.fillRect(0, 0, canvas.width, canvas.height);+ } else {+ cCtx.clearRect(0, 0, canvas.width, canvas.height);+ }+ }+ }+ }++ // Keep sourceCanvas synchronized if present+ if (sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ if (sCtx) {+ if (item.dirtyRect && dataToApply) {+ sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);+ } else if (dataToApply) {+ sCtx.putImageData(dataToApply, 0, 0);+ } else if (item.type === 'initial') {+ if (targetLayerId === 'layer-bg') {+ sCtx.fillStyle = '#ffffff';+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);+ } else {+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);+ }+ }+ }+ }}if (canvas) {@@ -473,20 +603,26 @@ export function useCanvasDrawing({historyIndexRef.current = targetIndex;syncHistoryState();},- [activeLayerId, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]+ [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]);// Undo actionconst undo = useCallback(() => {+ if (isDrawingRef.current) {+ abortActiveStroke();+ }if (historyIndexRef.current <= 0) return;jumpToHistoryIndex(historyIndexRef.current - 1);- }, [jumpToHistoryIndex]);+ }, [abortActiveStroke, jumpToHistoryIndex]);// Redo actionconst redo = useCallback(() => {+ if (isDrawingRef.current) {+ abortActiveStroke();+ }if (historyIndexRef.current >= historyRef.current.length - 1) return;jumpToHistoryIndex(historyIndexRef.current + 1);- }, [jumpToHistoryIndex]);+ }, [abortActiveStroke, jumpToHistoryIndex]);// Clear active layer actionconst clearCanvas = useCallback(() => {@@ -559,14 +695,22 @@ export function useCanvasDrawing({dims);- const pressure = e.pressure !== undefined && e.pressure > 0 ? e.pressure : 0.5;+ let pressure = 0;+ if (e.pointerType === 'mouse') {+ pressure = (e.buttons & 1) ? 0.5 : 0;+ } else {+ pressure = e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;+ }+const width = calculateStrokeWidth(bs.size,pressure,bs.minSizeFactor,bs.usePressure,e.pointerType,- bs.pressureCurveGamma ?? 1.0+ bs.pressureCurveGamma ?? 1.0,+ 1.0,+ bs.pressureCurve);return { x, y, pressure, width };@@ -574,14 +718,39 @@ export function useCanvasDrawing({[getViewportRect]);- // Render a single smooth segment onto the draft overlay context+ // Render a single smooth segment onto the draft overlay context using Catmull-Rom cubic splinesconst renderDraftSegment = useCallback((draftCtx: CanvasRenderingContext2D, point: Point) => {const pts = strokePointsRef.current;pts.push(point);- if (pts.length > 8) {- pts.splice(0, pts.length - 8);++ if (pts.length < 3) {+ return;+ }++ let k0: Point, k1: Point, k2: Point, k3: Point;+ if (pts.length === 3) {+ // First segment: P0 -> P1 with knots (P0, P0, P1, P2)+ k0 = pts[0];+ k1 = pts[0];+ k2 = pts[1];+ k3 = pts[2];+ } else {+ // Subsequent segments: P_{n-2} -> P_{n-1} with knots (P_{n-3}, P_{n-2}, P_{n-1}, P_n)+ const n = pts.length;+ k0 = pts[n - 4];+ k1 = pts[n - 3];+ k2 = pts[n - 2];+ k3 = pts[n - 1];}+ if (pts.length > 5) {+ pts.shift();+ }++ const { c1, c2 } = catmullRomToBezier(k0, k1, k2, k3);+ const segStart = k1;+ const segEnd = k2;+const isEraser = toolRef.current === 'eraser';const isBgEraser = isEraser && activeLayerIdRef.current === 'layer-bg';const bs = brushSettingsRef.current;@@ -589,25 +758,30 @@ export function useCanvasDrawing({const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);const canvas = getActiveCanvas();const currentLayerId = activeLayerIdRef.current;+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);+ const isToneLayer = Boolean(activeLayer?.toneEnabled);+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';+ const isMonochrome = mode === 'monochrome' || isMonoLayer;const isTone = isToneStrokeRef.current;const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;const isWetColor = isWetColorStrokeRef.current;+ const isTranslucentBrush = !isEraser && !isMonochrome && (bs.opacity ?? 1.0) < 0.999;+ const isDirectRender = isMonochrome || isWetColor || isEraser || (!isTranslucentBrush && !isToneLayer);- let targetCtx: CanvasRenderingContext2D | null = draftCtx;- if (isTone && sourceCanvas) {+ let targetCtx: CanvasRenderingContext2D | null = null;+ if (isToneLayer && sourceCanvas) {targetCtx = get2DContext(sourceCanvas);drewDirectlyOnLayerCanvasRef.current = true;- } else if (isWetColor && canvas) {+ } else if (isDirectRender && canvas) {targetCtx = get2DContext(canvas);drewDirectlyOnLayerCanvasRef.current = true;+ } else {+ targetCtx = draftCtx;}if (!targetCtx) return;- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);- const isToneLayer = Boolean(activeLayer?.toneEnabled);- const extraPreviewCtx = (isTone && sourceCanvas && draftCtx && targetCtx !== draftCtx && !isEraser && !isToneLayer) ? draftCtx : null;- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, mode);- const strokeHardness = mode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0);+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);const strokeFlow = bs.flow ?? 1.0;const strokeSpacing = bs.spacing ?? 0.08;@@ -624,9 +798,10 @@ export function useCanvasDrawing({angleDynamics: bs.customTipAngleDynamics,rotationRandomScale: bs.customTipRotationRandomScale,hardness: strokeHardness,- antiAlias: bs.antiAlias,+ antiAlias: isMonochrome ? 0 : bs.antiAlias,pressureCurve: bs.pressureCurve,velocityCurve: bs.velocityCurve,+ usePressure: bs.usePressure,useVelocity: bs.useVelocity,subTips: bs.subTips,subTipOrder: bs.subTipOrder,@@ -652,226 +827,51 @@ export function useCanvasDrawing({reservoir: activeReservoirRef.current || undefined,isEraser: isEraser && !isBgEraser,isBgEraser,+ currentStrokeDist: strokeTotalDistanceRef.current,};- if (pts.length >= 3) {- const p0 = pts[pts.length - 3];- const p1 = pts[pts.length - 2];- const p2 = pts[pts.length - 1];-- const startMid = getMidPoint(p0, p1);- const endMid = getMidPoint(p1, p2);-- stampRemainderDistRef.current = drawTexturedBezierSegment(- targetCtx,- startMid,- p1,- endMid,- strokeColor,- bs.customTipImage,- tipOptions,- stampRemainderDistRef.current- );- if (extraPreviewCtx) {- drawTexturedBezierSegment(- extraPreviewCtx,- startMid,- p1,- endMid,- strokeColor,- bs.customTipImage,- tipOptions,- stampRemainderDistRef.current- );- }- } else if (pts.length === 2) {- const p0 = pts[0];- const p1 = pts[1];- const mid = getMidPoint(p0, p1);-- stampRemainderDistRef.current = drawTexturedBezierSegment(- targetCtx,- p0,- p0,- mid,- strokeColor,- bs.customTipImage,- tipOptions,- stampRemainderDistRef.current- );- if (extraPreviewCtx) {- drawTexturedBezierSegment(- extraPreviewCtx,- p0,- p0,- mid,- strokeColor,- bs.customTipImage,- tipOptions,- stampRemainderDistRef.current- );- }- }+ stampRemainderDistRef.current = drawTexturedCubicBezierSegment(+ targetCtx,+ segStart,+ c1,+ c2,+ segEnd,+ strokeColor,+ bs.customTipImage,+ tipOptions,+ stampRemainderDistRef.current+ );} else if (isPencil) {const grade = (bs.preset as PencilGrade) || 'pencil-2b';const pFlow = bs.flow ?? 0.74;const pGrain = bs.grain ?? 1.0;- if (pts.length >= 3) {- const p0 = pts[pts.length - 3];- const p1 = pts[pts.length - 2];- const p2 = pts[pts.length - 1];-- const startMid = getMidPoint(p0, p1);- const endMid = getMidPoint(p1, p2);-- drawPencilBezierSegment(- targetCtx,- startMid,- p1,- endMid,- strokeColor,- grade,- pFlow,- pGrain,- bs.hardness- );- if (extraPreviewCtx) {- drawPencilBezierSegment(- extraPreviewCtx,- startMid,- p1,- endMid,- strokeColor,- grade,- pFlow,- pGrain,- bs.hardness- );- }- } else if (pts.length === 2) {- const p0 = pts[0];- const p1 = pts[1];- const mid = getMidPoint(p0, p1);-- drawPencilBezierSegment(- targetCtx,- p0,- p0,- mid,- strokeColor,- grade,- pFlow,- pGrain,- bs.hardness- );- if (extraPreviewCtx) {- drawPencilBezierSegment(- extraPreviewCtx,- p0,- p0,- mid,- strokeColor,- grade,- pFlow,- pGrain,- bs.hardness- );- }- }- } else if (bs.smoothing) {- if (pts.length >= 3) {- const p0 = pts[pts.length - 3];- const p1 = pts[pts.length - 2];- const p2 = pts[pts.length - 1];-- const startMid = getMidPoint(p0, p1);- const endMid = getMidPoint(p1, p2);-- drawSmoothBezierSegment(- targetCtx,- startMid,- p1,- endMid,- strokeColor,- isEraser && !isBgEraser,- strokeHardness,- strokeFlow,- strokeSpacing- );- if (extraPreviewCtx) {- drawSmoothBezierSegment(- extraPreviewCtx,- startMid,- p1,- endMid,- strokeColor,- false,- strokeHardness,- strokeFlow,- strokeSpacing- );- }- } else if (pts.length === 2) {- const p0 = pts[0];- const p1 = pts[1];- const mid = getMidPoint(p0, p1);-- drawSmoothBezierSegment(- targetCtx,- p0,- p0,- mid,- strokeColor,- isEraser && !isBgEraser,- strokeHardness,- strokeFlow,- strokeSpacing- );- if (extraPreviewCtx) {- drawSmoothBezierSegment(- extraPreviewCtx,- p0,- p0,- mid,- strokeColor,- false,- strokeHardness,- strokeFlow,- strokeSpacing- );- }- }+ drawPencilCubicBezierSegment(+ targetCtx,+ segStart,+ c1,+ c2,+ segEnd,+ strokeColor,+ grade,+ pFlow,+ pGrain,+ bs.hardness+ );} else {- if (pts.length >= 2) {- const pPrev = pts[pts.length - 2];- const pCurr = pts[pts.length - 1];-- targetCtx.save();- targetCtx.lineCap = 'round';- targetCtx.lineJoin = 'round';- if (strokeFlow < 0.999) {- targetCtx.globalAlpha = Math.max(0.01, Math.min(1.0, strokeFlow));- }- if (isBgEraser) {- targetCtx.globalCompositeOperation = 'source-over';- targetCtx.strokeStyle = '#ffffff';- } else if (isEraser) {- targetCtx.globalCompositeOperation = 'destination-out';- targetCtx.strokeStyle = 'rgba(0, 0, 0, 1)';- } else {- targetCtx.globalCompositeOperation = 'source-over';- targetCtx.strokeStyle = strokeColor;- }- targetCtx.lineWidth = (pPrev.width + pCurr.width) / 2;- targetCtx.beginPath();- targetCtx.moveTo(pPrev.x, pPrev.y);- targetCtx.lineTo(pCurr.x, pCurr.y);- targetCtx.stroke();- targetCtx.restore();- }+ drawSmoothCubicBezierSegment(+ targetCtx,+ segStart,+ c1,+ c2,+ segEnd,+ strokeColor,+ isEraser && !isBgEraser,+ strokeHardness,+ strokeFlow,+ strokeSpacing+ );}-}, [getActiveCanvas]);// Stabilize and render point onto draft canvas@@ -892,8 +892,11 @@ export function useCanvasDrawing({velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));}+ rawPointsBufferRef.current.push({ x: rawX, y: rawY, pressure: rawPressure, pointerType });+let pt: Point;- if (stab <= 0 || !stabilizedPointRef.current) {+ if (stab <= 0) {+ rawPointsBufferRef.current.length = 0;const width = calculateStrokeWidth(bs.size,rawPressure,@@ -901,16 +904,32 @@ export function useCanvasDrawing({bs.usePressure,pointerType,bs.pressureCurveGamma ?? 1.0,- velocityScale+ velocityScale,+ bs.pressureCurve);pt = { x: rawX, y: rawY, pressure: rawPressure, width };stabilizedPointRef.current = pt;} else {- const alpha = Math.max(0.04, 1 / (1 + stab * 0.22));- const prev = stabilizedPointRef.current;- const smoothX = prev.x + (rawX - prev.x) * alpha;- const smoothY = prev.y + (rawY - prev.y) * alpha;- const smoothPressure = prev.pressure + (rawPressure - prev.pressure) * alpha;+ const W = Math.min(9, Math.max(3, 1 + 2 * Math.floor(stab / 7)));+ if (rawPointsBufferRef.current.length < W) {+ return;+ }++ const buf = rawPointsBufferRef.current;+ const mid = Math.floor(W / 2);+ let sumX = 0, sumY = 0, sumP = 0, sumW = 0;+ for (let i = 0; i < W; i++) {+ const w = Math.pow(2, mid - Math.abs(i - mid));+ sumX += buf[i].x * w;+ sumY += buf[i].y * w;+ sumP += buf[i].pressure * w;+ sumW += w;+ }+ buf.shift();++ const smoothX = sumX / sumW;+ const smoothY = sumY / sumW;+ const smoothPressure = sumP / sumW;const smoothWidth = calculateStrokeWidth(bs.size,smoothPressure,@@ -918,15 +937,26 @@ export function useCanvasDrawing({bs.usePressure,pointerType,bs.pressureCurveGamma ?? 1.0,- velocityScale+ velocityScale,+ bs.pressureCurve);pt = { x: smoothX, y: smoothY, pressure: smoothPressure, width: smoothWidth };stabilizedPointRef.current = pt;}+ // Track recent trail for exit velocity & tangent calculation+ if (allStrokePointsRef.current.length > 0) {+ const lastPt = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];+ strokeTotalDistanceRef.current += Math.hypot(pt.x - lastPt.x, pt.y - lastPt.y);+ }+ recentPointsTrailRef.current.push({ x: pt.x, y: pt.y, t: now, pressure: pt.pressure, width: pt.width });+ if (recentPointsTrailRef.current.length > 16) {+ recentPointsTrailRef.current.shift();+ }+// Expand dirty rectangle in canvas coordinatesconst blurMargin = (1 - (bs.hardness ?? 1.0)) * (pt.width * 1.5);- const r = Math.max(8, Math.ceil(pt.width / 2 + blurMargin + 8));+ const r = Math.max(24, Math.ceil(pt.width + blurMargin + 24));if (dirtyRectRef.current) {dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, Math.floor(pt.x - r)));dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, Math.floor(pt.y - r)));@@ -975,33 +1005,67 @@ export function useCanvasDrawing({}}- if (isToneStrokeRef.current && batchMinX <= batchMaxX) {+ if (batchMinX <= batchMaxX) {const currentLayerId = activeLayerIdRef.current;- const sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId);const canvas = getActiveCanvas();const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);- if (sourceCanvas && canvas && activeLayer) {- const dims = dimensionsRef.current;- const freq = activeLayer.toneFrequency ?? 60;- const cellSize = Math.max(3.5, (dims.dpi ?? 600) / freq);- const margin = Math.ceil(maxStrokeWidth * 0.75 + Math.max(cellSize * 2, 16));- const segMinX = Math.max(0, Math.floor(batchMinX - margin));- const segMinY = Math.max(0, Math.floor(batchMinY - margin));- const segMaxX = Math.min(dims.width, Math.ceil(batchMaxX + margin));- const segMaxY = Math.min(dims.height, Math.ceil(batchMaxY + margin));- if (segMaxX > segMinX && segMaxY > segMinY) {- applyLayerEffects(- sourceCanvas,- canvas,- activeLayer,- dims.dpi ?? 600,- {- x: segMinX,- y: segMinY,- width: segMaxX - segMinX,- height: segMaxY - segMinY,+ const isToneLayer = Boolean(activeLayer?.toneEnabled);+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';+ const isMonochrome = colorModeRef.current === 'monochrome' || isMonoLayer;+ const dims = dimensionsRef.current;+ const margin = Math.ceil(maxStrokeWidth * 1.5 + 32);+ const segMinX = Math.max(0, Math.floor(batchMinX - margin));+ const segMinY = Math.max(0, Math.floor(batchMinY - margin));+ const segMaxX = Math.min(dims.width, Math.ceil(batchMaxX + margin));+ const segMaxY = Math.min(dims.height, Math.ceil(batchMaxY + margin));+ const segW = segMaxX - segMinX;+ const segH = segMaxY - segMinY;++ if (dirtyRectRef.current) {+ dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, segMinX);+ dirtyRectRef.current.minY = Math.min(dirtyRectRef.current.minY, segMinY);+ dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, segMaxX);+ dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, segMaxY);+ }++ if (segW > 0 && segH > 0 && canvas) {+ if (isMonochrome) {+ const cCtx = get2DContext(canvas);+ if (cCtx) {+ binarizeCanvasRect(+ cCtx,+ { x: segMinX, y: segMinY, width: segW, height: segH },+ activeLayer?.monoThreshold ?? 128,+ activeLayer?.monoExpressBlack ?? true,+ activeLayer?.monoExpressWhite ?? true+ );+ }+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {+ const sourceCanvas = layerSourceCanvasesRef.current.get(currentLayerId);+ if (sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ if (sCtx) {+ sCtx.clearRect(segMinX, segMinY, segW, segH);+ sCtx.drawImage(canvas, segMinX, segMinY, segW, segH, segMinX, segMinY, segW, segH);+ }}- );+ }+ } else if (isToneLayer && isToneStrokeRef.current) {+ const sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId);+ if (sourceCanvas && activeLayer) {+ applyLayerEffects(+ sourceCanvas,+ canvas,+ activeLayer,+ dims.dpi ?? 600,+ {+ x: segMinX,+ y: segMinY,+ width: segW,+ height: segH,+ }+ );+ }}}}@@ -1077,6 +1141,14 @@ export function useCanvasDrawing({const currentLayerId = activeLayerIdRef.current;const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);+ const bs = brushSettingsRef.current;+ const mode = colorModeRef.current;+ const dims = dimensionsRef.current;+ const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);++ const isToneLayer = Boolean(activeLayer?.toneEnabled);+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';+ const isMonochrome = mode === 'monochrome' || isMonoLayer;const isTone = Boolean(activeLayer?.toneEnabled ||activeLayer?.layerColorEnabled ||@@ -1097,13 +1169,6 @@ export function useCanvasDrawing({}}- // For transparent layer erasing: copy current layer into draft overlay and hide base layer during gesture- if (isEraser && !isBgEraser && !isTone) {- draftCtx.drawImage(canvas, 0, 0);- canvas.style.visibility = 'hidden';- hiddenLayerCanvasRef.current = canvas;- }-if (interactionRef.current) {try {interactionRef.current.setPointerCapture(e.pointerId);@@ -1118,19 +1183,28 @@ export function useCanvasDrawing({allStrokePointsRef.current = [startPoint];strokePointsRef.current = [startPoint];+ rawPointsBufferRef.current = [{+ x: startPoint.x,+ y: startPoint.y,+ pressure: startPoint.pressure,+ pointerType: e.pointerType,+ }];stabilizedPointRef.current = { ...startPoint };lastProcessedPointRef.current = { x: startPoint.x, y: startPoint.y };pendingPointsQueueRef.current = [];+ recentPointsTrailRef.current = [{+ x: startPoint.x,+ y: startPoint.y,+ t: performance.now(),+ pressure: startPoint.pressure,+ width: startPoint.width,+ }];+ strokeTotalDistanceRef.current = 0;dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);- const bs = brushSettingsRef.current;- const mode = colorModeRef.current;- const dims = dimensionsRef.current;- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);-const blurMargin = (1 - (bs.hardness ?? 1.0)) * (startPoint.width * 1.5);- const r = Math.max(8, Math.ceil(startPoint.width / 2 + blurMargin + 8));+ const r = Math.max(32, Math.ceil(startPoint.width + blurMargin + 32));dirtyRectRef.current = {minX: Math.max(0, Math.floor(startPoint.x - r)),minY: Math.max(0, Math.floor(startPoint.y - r)),@@ -1138,14 +1212,18 @@ export function useCanvasDrawing({maxY: Math.min(dims.height, Math.ceil(startPoint.y + r)),};- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, mode);+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);const isWetColor = !isEraser && Boolean(bs.colorMixing) && Boolean(bs.customTipImage);isWetColorStrokeRef.current = isWetColor;++ const isTranslucentBrush = !isEraser && !isMonochrome && (bs.opacity ?? 1.0) < 0.999;+ const isDirectRender = isMonochrome || isWetColor || isEraser || (!isTranslucentBrush && !isToneLayer);drewDirectlyOnLayerCanvasRef.current = false;- if (isTone && sourceCanvas) {- const backupCanvas = getReusableBakeCanvas(sourceCanvas.width, sourceCanvas.height);+ if (isToneLayer && sourceCanvas) {+ const backupCanvas = getDedicatedBackupCanvas(sourceCanvas.width, sourceCanvas.height);const backupCtx = get2DContext(backupCanvas);if (backupCtx) {backupCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);@@ -1154,16 +1232,21 @@ export function useCanvasDrawing({}layerPixelSamplerRef.current = null;activeReservoirRef.current = null;- } else if (isWetColor && canvas) {- const backupCanvas = getReusableBakeCanvas(canvas.width, canvas.height);+ } else if ((isDirectRender || isWetColor) && canvas) {+ const backupCanvas = getDedicatedBackupCanvas(canvas.width, canvas.height);const backupCtx = get2DContext(backupCanvas);if (backupCtx) {backupCtx.clearRect(0, 0, canvas.width, canvas.height);backupCtx.drawImage(canvas, 0, 0);strokeBackupCanvasRef.current = backupCanvas;}- layerPixelSamplerRef.current = new LayerPixelSampler(canvas);- activeReservoirRef.current = new PaintReservoir(strokeColor);+ if (isWetColor) {+ layerPixelSamplerRef.current = new LayerPixelSampler(canvas);+ activeReservoirRef.current = new PaintReservoir(strokeColor);+ } else {+ layerPixelSamplerRef.current = null;+ activeReservoirRef.current = null;+ }} else {strokeBackupCanvasRef.current = null;layerPixelSamplerRef.current = null;@@ -1174,9 +1257,11 @@ export function useCanvasDrawing({currentStrokeIdRef.current = strokeId;onCollabStrokeStartRef.current?.(strokeId, activeLayerIdRef.current, bs, toolRef.current, startPoint);- stampRemainderDistRef.current = 0;+ stampRemainderDistRef.current = Math.max(0.2, startPoint.width * (bs.spacing ?? 0.08));- const targetStartCtx = isTone && sourceCanvas ? get2DContext(sourceCanvas) : (isWetColor && canvas ? get2DContext(canvas) : draftCtx);+ const targetStartCtx = isToneLayer && sourceCanvas+ ? get2DContext(sourceCanvas)+ : (isDirectRender && canvas ? get2DContext(canvas) : draftCtx);if (targetStartCtx && targetStartCtx !== draftCtx) {drewDirectlyOnLayerCanvasRef.current = true;}@@ -1193,8 +1278,8 @@ export function useCanvasDrawing({angle: bs.customTipAngle,angleDynamics: bs.customTipAngleDynamics,rotationRandomScale: bs.customTipRotationRandomScale,- hardness: bs.hardness ?? 0.8,- antiAlias: bs.antiAlias,+ hardness: strokeHardness,+ antiAlias: isMonochrome ? 0 : bs.antiAlias,pressureCurve: bs.pressureCurve,velocityCurve: bs.velocityCurve,useVelocity: bs.useVelocity,@@ -1246,13 +1331,30 @@ export function useCanvasDrawing({startPoint,strokeColor,isEraser && !isBgEraser,- mode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),+ strokeHardness,bs.flow ?? 1.0);}}- if (isTone && sourceCanvas && canvas && activeLayer) {+ if (isMonochrome && canvas && dirtyRectRef.current) {+ const dotDirty = dirtyRectRef.current;+ const dw = dotDirty.maxX - dotDirty.minX;+ const dh = dotDirty.maxY - dotDirty.minY;+ if (dw > 0 && dh > 0) {+ binarizeCanvasRect(+ get2DContext(canvas)!,+ { x: dotDirty.minX, y: dotDirty.minY, width: dw, height: dh },+ activeLayer?.monoThreshold ?? 128,+ activeLayer?.monoExpressBlack ?? true,+ activeLayer?.monoExpressWhite ?? true+ );+ if (sourceCanvas && targetStartCtx !== get2DContext(sourceCanvas)) {+ const sCtx = get2DContext(sourceCanvas);+ sCtx?.drawImage(canvas, dotDirty.minX, dotDirty.minY, dw, dh, dotDirty.minX, dotDirty.minY, dw, dh);+ }+ }+ } else if (isToneLayer && sourceCanvas && canvas && activeLayer) {applyLayerEffects(sourceCanvas,canvas,@@ -1315,16 +1417,18 @@ export function useCanvasDrawing({const last = lastProcessedPointRef.current;if (last && !isLast) {const distSq = (cx - last.x) * (cx - last.x) + (cy - last.y) * (cy - last.y);- if (distSq < 0.5) {+ if (distSq < 2.0) {continue;}}lastProcessedPointRef.current = { x: cx, y: cy };- const cPressure =- cEvent.pressure !== undefined && cEvent.pressure > 0- ? cEvent.pressure- : 0.5;+ let cPressure = 0;+ if (cEvent.pointerType === 'mouse') {+ cPressure = (cEvent.buttons & 1) ? 0.5 : 0;+ } else {+ cPressure = cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;+ }pendingPointsQueueRef.current.push({x: cx,@@ -1349,6 +1453,14 @@ export function useCanvasDrawing({onActiveConstraintAxisChangeRef.current?.(snapRes.axis);}+ const last = lastProcessedPointRef.current;+ if (last) {+ const distSq = (finalX - last.x) * (finalX - last.x) + (finalY - last.y) * (finalY - last.y);+ if (distSq < 1.0) {+ return;+ }+ }+lastProcessedPointRef.current = { x: finalX, y: finalY };pendingPointsQueueRef.current.push({x: finalX,@@ -1387,30 +1499,48 @@ export function useCanvasDrawing({flushPendingPoints();const bs = brushSettingsRef.current;- const stab = bs.stabilization ?? 0;const endPoint = getCanvasPoint(e);const draftCanvas = effectiveDraftCanvasRef?.current;const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;const canvas = getActiveCanvas();- // Catch-up smoothing trail to pen release point- if (stab > 0 && stabilizedPointRef.current && draftCtx) {- const curr = stabilizedPointRef.current;- const distToEnd = Math.hypot(endPoint.x - curr.x, endPoint.y - curr.y);-- if (distToEnd > 0.5) {- const catchUpSteps = Math.min(4, Math.max(2, Math.ceil(distToEnd / 6)));- for (let i = 1; i <= catchUpSteps; i++) {- const t = i / catchUpSteps;- const interpX = curr.x + (endPoint.x - curr.x) * t;- const interpY = curr.y + (endPoint.y - curr.y) * t;- const interpP = curr.pressure + (endPoint.pressure - curr.pressure) * t;- applyStabilizedPointAndRender(draftCtx, interpX, interpY, interpP, e.pointerType);- }+ // Drain any buffered raw points through the stabilizer+ while (rawPointsBufferRef.current.length > 0) {+ const buf = rawPointsBufferRef.current;+ const len = buf.length;+ const mid = Math.floor(len / 2);+ let sumX = 0, sumY = 0, sumP = 0, sumW = 0;+ for (let i = 0; i < len; i++) {+ const w = Math.pow(2, mid - Math.abs(i - mid));+ sumX += buf[i].x * w;+ sumY += buf[i].y * w;+ sumP += buf[i].pressure * w;+ sumW += w;+ }+ const ptType = buf[0].pointerType;+ buf.shift();++ const sX = sumX / sumW;+ const sY = sumY / sumW;+ const sP = sumP / sumW;+ const sW = calculateStrokeWidth(+ bs.size,+ sP,+ bs.minSizeFactor,+ bs.usePressure,+ ptType,+ bs.pressureCurveGamma ?? 1.0,+ 1.0,+ bs.pressureCurve+ );+ const pt: Point = { x: sX, y: sY, pressure: sP, width: sW };+ allStrokePointsRef.current.push(pt);+ if (draftCtx) {+ renderDraftSegment(draftCtx, pt);}}- // Finalize tail segment on draft canvas+ // Finalize tail segment on draft canvas using Catmull-Rom cubic Bézierconst pts = strokePointsRef.current;const currentTool = toolRef.current;const currentLayerId = activeLayerIdRef.current;@@ -1422,15 +1552,27 @@ export function useCanvasDrawing({const isTone = isToneStrokeRef.current;const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);const isToneLayer = Boolean(activeLayer?.toneEnabled);+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';+ const isMonochrome = mode === 'monochrome' || isMonoLayer;const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;- const isWetColor = isWetColorStrokeRef.current;- const targetTailCtx = isTone && sourceCanvas ? get2DContext(sourceCanvas) : (isWetColor && canvas ? get2DContext(canvas) : draftCtx);+ const targetTailCtx = isToneLayer && sourceCanvas+ ? get2DContext(sourceCanvas)+ : (drewDirectlyOnLayerCanvasRef.current && canvas ? get2DContext(canvas) : draftCtx);if (targetTailCtx && pts.length >= 2) {const pLast = pts[pts.length - 1];const pPrev = pts[pts.length - 2];- const lastMid = getMidPoint(pPrev, pLast);- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, mode);+ const pPrev2 = pts.length >= 3 ? pts[pts.length - 3] : pPrev;++ // If stylus pen is lifted, naturally taper pressure to 0 at release point+ if (bs.usePressure && e.pointerType === 'pen') {+ pLast.pressure = 0;+ pLast.width = Math.max(0.1, bs.size * (bs.minSizeFactor ?? 0));+ }++ const { c1, c2 } = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);if (bs.customTipImage) {const tipOptions: TexturedBrushOptions = {@@ -1444,10 +1586,11 @@ export function useCanvasDrawing({angle: bs.customTipAngle,angleDynamics: bs.customTipAngleDynamics,rotationRandomScale: bs.customTipRotationRandomScale,- hardness: bs.hardness ?? 0.8,- antiAlias: bs.antiAlias,+ hardness: strokeHardness,+ antiAlias: isMonochrome ? 0 : bs.antiAlias,pressureCurve: bs.pressureCurve,velocityCurve: bs.velocityCurve,+ usePressure: bs.usePressure,useVelocity: bs.useVelocity,subTips: bs.subTips,subTipOrder: bs.subTipOrder,@@ -1473,38 +1616,26 @@ export function useCanvasDrawing({reservoir: activeReservoirRef.current || undefined,isEraser: isEraser && !isBgEraser,isBgEraser,+ currentStrokeDist: strokeTotalDistanceRef.current,};- drawTexturedBezierSegment(+ drawTexturedCubicBezierSegment(targetTailCtx,- lastMid,- pLast,+ pPrev,+ c1,+ c2,pLast,strokeColor,bs.customTipImage,tipOptions,stampRemainderDistRef.current);- if ((isTone || isWetColor) && targetTailCtx !== draftCtx) {- drewDirectlyOnLayerCanvasRef.current = true;- }- if (isTone && sourceCanvas && draftCtx && targetTailCtx !== draftCtx && !isEraser && !isToneLayer) {- drawTexturedBezierSegment(- draftCtx,- lastMid,- pLast,- pLast,- strokeColor,- bs.customTipImage,- tipOptions,- stampRemainderDistRef.current- );- }} else if (isPencil) {const grade = (bs.preset as PencilGrade) || 'pencil-2b';- drawPencilBezierSegment(+ drawPencilCubicBezierSegment(targetTailCtx,- lastMid,- pLast,+ pPrev,+ c1,+ c2,pLast,strokeColor,grade,@@ -1512,43 +1643,56 @@ export function useCanvasDrawing({bs.grain ?? 1.0,bs.hardness);- if (isTone && sourceCanvas && draftCtx && targetTailCtx !== draftCtx && !isEraser && !isToneLayer) {- drawPencilBezierSegment(- draftCtx,- lastMid,- pLast,- pLast,- strokeColor,- grade,- bs.flow ?? 0.74,- bs.grain ?? 1.0,- bs.hardness- );- }} else if (bs.smoothing) {- drawSmoothBezierSegment(+ drawSmoothCubicBezierSegment(targetTailCtx,- lastMid,- pLast,+ pPrev,+ c1,+ c2,pLast,strokeColor,isEraser && !isBgEraser,- mode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),+ strokeHardness,bs.flow ?? 1.0,bs.spacing ?? 0.08);- if (isTone && sourceCanvas && draftCtx && targetTailCtx !== draftCtx && !isEraser && !isToneLayer) {- drawSmoothBezierSegment(- draftCtx,- lastMid,- pLast,- pLast,- strokeColor,- false,- mode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),- bs.flow ?? 1.0,- bs.spacing ?? 0.08- );+ }+ }++ if (pts.length >= 2) {+ const pLast = pts[pts.length - 1];+ const pPrev = pts[pts.length - 2];+ const tailMargin = Math.ceil(Math.max(pLast.width, pPrev.width) * 1.5 + 32);+ const tMinX = Math.max(0, Math.floor(Math.min(pLast.x, pPrev.x) - tailMargin));+ const tMinY = Math.max(0, Math.floor(Math.min(pLast.y, pPrev.y) - tailMargin));+ const tMaxX = Math.min(canvas ? canvas.width : dimensionsRef.current.width, Math.ceil(Math.max(pLast.x, pPrev.x) + tailMargin));+ const tMaxY = Math.min(canvas ? canvas.height : dimensionsRef.current.height, Math.ceil(Math.max(pLast.y, pPrev.y) + tailMargin));++ if (dirtyRectRef.current) {+ dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, tMinX);+ dirtyRectRef.current.minY = Math.min(dirtyRectRef.current.minY, tMinY);+ dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, tMaxX);+ dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, tMaxY);+ }++ if (isMonochrome && canvas) {+ const tW = tMaxX - tMinX;+ const tH = tMaxY - tMinY;+ if (tW > 0 && tH > 0) {+ const cCtx = get2DContext(canvas);+ if (cCtx) {+ binarizeCanvasRect(+ cCtx,+ { x: tMinX, y: tMinY, width: tW, height: tH },+ activeLayer?.monoThreshold ?? 128,+ activeLayer?.monoExpressBlack ?? true,+ activeLayer?.monoExpressWhite ?? true+ );+ }+ if (sourceCanvas) {+ const sCtx = get2DContext(sourceCanvas);+ sCtx?.drawImage(canvas, tMinX, tMinY, tW, tH, tMinX, tMinY, tW, tH);+ }}}}@@ -1556,11 +1700,11 @@ export function useCanvasDrawing({// BAKE STROKE INTO HIGH-RESOLUTION BASE CANVAS (Dirty Rect only)const dirty = dirtyRectRef.current;- if (isTone && sourceCanvas && canvas) {+ if (isToneLayer && sourceCanvas && canvas) {if (activeLayer) {const freq = activeLayer?.toneFrequency ?? 60;const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);- const cellMargin = Math.ceil(cellSize * 2);+ const cellMargin = Math.ceil(cellSize * 2 + 32);applyLayerEffects(sourceCanvas,canvas,@@ -1578,10 +1722,11 @@ export function useCanvasDrawing({const allPoints = allStrokePointsRef.current;if (canvas && dirty && allPoints.length > 0) {- const sx = Math.max(0, Math.floor(dirty.minX));- const sy = Math.max(0, Math.floor(dirty.minY));- const maxX = Math.min(canvas.width, Math.ceil(dirty.maxX));- const maxY = Math.min(canvas.height, Math.ceil(dirty.maxY));+ const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));+ const sx = Math.max(0, Math.floor(dirty.minX - pad));+ const sy = Math.max(0, Math.floor(dirty.minY - pad));+ const maxX = Math.min(canvas.width, Math.ceil(dirty.maxX + pad));+ const maxY = Math.min(canvas.height, Math.ceil(dirty.maxY + pad));const dw = maxX - sx;const dh = maxY - sy;@@ -1589,47 +1734,33 @@ export function useCanvasDrawing({const ctx = get2DContext(canvas);if (ctx) {let beforeData: ImageData | null = null;+ let afterData: ImageData | null = null;- if (isTone && strokeBackupCanvasRef.current && sourceCanvas) {+ if (isToneLayer && strokeBackupCanvasRef.current && sourceCanvas) {const bCtx = get2DContext(strokeBackupCanvasRef.current);beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;const sCtx = get2DContext(sourceCanvas);- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;-- let label = 'Brush Stroke';- if (currentTool === 'eraser') {- label = 'Eraser';- } else if (bs.brushName) {- label = bs.brushName;- } else if (bs.preset === 'pencil-f') {- label = 'Pencil (F)';- } else if (bs.preset === 'pencil-2b') {- label = 'Pencil (2B)';- } else if (bs.preset === 'pencil-4b') {- label = 'Pencil (4B)';- } else if (bs.preset === 'pencil-hb') {- label = 'Pencil (HB)';- } else {- label = 'Tone Stroke';- }-- if (beforeData && afterData) {- pushHistoryStep(- currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush'),- label,- beforeData,- afterData,- currentLayerId,- { x: sx, y: sy, width: dw, height: dh }- );- }- } else if (isWetColor && strokeBackupCanvasRef.current && drewDirectlyOnLayerCanvasRef.current) {- // The stroke has already been painted onto canvas with full real-time color mixing!- // beforeData is extracted from the pre-stroke backup canvas+ afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;+ } else if (drewDirectlyOnLayerCanvasRef.current && strokeBackupCanvasRef.current) {+ // Direct render: stroke is ALREADY drawn on canvas with real-time binarization/effects!+ // Zero re-rendering, zero delay, zero lag, zero flicker!const bCtx = get2DContext(strokeBackupCanvasRef.current);beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;+ afterData = ctx.getImageData(sx, sy, dw, dh);++ // Synchronize dirty bounding box to sourceCanvas so tone can be toggled without losing edits+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);+ if (existingSource) {+ const sCtx = get2DContext(existingSource);+ if (sCtx) {+ sCtx.clearRect(sx, sy, dw, dh);+ sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);+ }+ }+ }} else {- // For non-wet brushes (pencils, inking pens):+ // Translucent brushes drawn onto draft canvas overlay:beforeData = ctx.getImageData(sx, sy, dw, dh);ctx.save();@@ -1637,46 +1768,23 @@ export function useCanvasDrawing({ctx.rect(sx, sy, dw, dh);ctx.clip();- const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;-- if (isTranslucentBrush) {- const bakeCanvas = getReusableBakeCanvas(dw, dh);- const bCtx = bakeCanvas.getContext('2d', { alpha: true });- if (bCtx) {- bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);- bCtx.save();- bCtx.translate(-sx, -sy);- renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser);- bCtx.restore();-- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));- ctx.globalCompositeOperation = 'source-over';- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);- }- } else {- renderCompleteStroke(ctx, allPoints, bs, currentTool, mode, isBgEraser);+ const bakeCanvas = getReusableBakeCanvas(dw, dh);+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });+ if (bCtx) {+ bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);+ bCtx.save();+ bCtx.translate(-sx, -sy);+ renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser);+ bCtx.restore();++ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));+ ctx.globalCompositeOperation = 'source-over';+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);}ctx.restore();- }-- if (mode === 'monochrome') {- applyColorModeToCanvas(canvas, 'monochrome', { x: sx, y: sy, width: dw, height: dh });- }-- // Snapshot afterImageData ONLY for the dirty bounding box- const afterData = ctx.getImageData(sx, sy, dw, dh);- // Synchronize dirty bounding box to sourceCanvas so tone can be toggled without losing edits- if (!isTone && layerSourceCanvasesRef?.current?.has(currentLayerId)) {- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);- if (existingSource) {- const sCtx = get2DContext(existingSource);- if (sCtx) {- sCtx.clearRect(sx, sy, dw, dh);- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);- }- }+ afterData = ctx.getImageData(sx, sy, dw, dh);}let label = 'Brush Stroke';@@ -1699,10 +1807,10 @@ export function useCanvasDrawing({} else if (bs.preset === 'blend-smudge') {label = 'Smudge & Blender';} else {- label = 'Round Brush';+ label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';}- if (beforeData) {+ if (beforeData && afterData) {pushHistoryStep(currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush'),label,@@ -1716,32 +1824,21 @@ export function useCanvasDrawing({}}- // Restore active layer visibility after baking has finished on base canvas- if (hiddenLayerCanvasRef.current) {- hiddenLayerCanvasRef.current.style.visibility = 'visible';- hiddenLayerCanvasRef.current = null;- }-- // Clear the Draft Overlay Canvas atomically:- // Bake the completed stroke directly into the active base canvas layer first.- // Clear the overlay canvas ONLY immediately after the base canvas draw call finishes,- // using requestAnimationFrame to guarantee zero visible gap or blink.+ // Synchronously clear draftCanvas immediately in the exact same render turn to guarantee zero flickerif (clearDraftRafRef.current !== null) {cancelAnimationFrame(clearDraftRafRef.current);- }- clearDraftRafRef.current = requestAnimationFrame(() => {clearDraftRafRef.current = null;- if (draftCanvas) {- const dCtx = get2DContext(draftCanvas);- if (dCtx) {- try {- dCtx.restore(); // Restore artboard clip- } catch (_) {}- dCtx.resetTransform();- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);- }+ }+ if (draftCanvas) {+ const dCtx = get2DContext(draftCanvas);+ if (dCtx) {+ try {+ dCtx.restore(); // Restore artboard clip+ } catch (_) {}+ dCtx.resetTransform();+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);}- });+ }if (currentStrokeIdRef.current) {onCollabStrokeFinishRef.current?.(diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex cdeeb8e..c96a205 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -194,6 +194,10 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerPropcollapsed: false,parentId,thumbnailUrl: '',+ expressionColor: activeLayer?.expressionColor === 'monochrome' ? 'monochrome' : activeLayer?.expressionColor === 'gray' ? 'gray' : 'color',+ monoThreshold: activeLayer?.monoThreshold ?? 128,+ monoExpressBlack: activeLayer?.monoExpressBlack ?? true,+ monoExpressWhite: activeLayer?.monoExpressWhite ?? true,};createdLayer = newLayer;@@ -1044,6 +1048,10 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerPropparentId: null,thumbnailUrl: '',toneFrequency: defaultToneFrequencyRef.current,+ expressionColor: _mode === 'monochrome' ? 'monochrome' : _mode === 'grayscale' ? 'gray' : 'color',+ monoThreshold: 128,+ monoExpressBlack: true,+ monoExpressWhite: true,},{id: bgId,diff --git a/src/types/editor.ts b/src/types/editor.tsindex 8fc041c..07a1142 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -54,10 +54,14 @@ export interface CspSpraySettings {}export interface CspTaperSettings {+ useIn?: boolean;inLength: number;inRatio: number;+ useOut?: boolean;outLength: number;outRatio: number;+ inOutType?: number;+ inOutBySpeed?: boolean;}export interface CspBrush {diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.tsindex 961cb76..cbe2a2f 100644--- a/src/utils/canvasUtils.ts+++ b/src/utils/canvasUtils.ts@@ -1,7 +1,8 @@import { Point, CanvasDimensions, BlendMode, ToolType, BrushSettings, CanvasColorMode, LayerItem } from '../types/editor';import { enforceColorMode } from './colorUtils';-import { drawPencilBezierSegment, drawPencilDot, PencilGrade } from './pencilEngine';+import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from './pencilEngine';import { renderCompleteTexturedStroke, TexturedBrushOptions } from './stampEngine';+import { evaluateCspSpline } from './sutParser';export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {alpha: true,@@ -20,8 +21,8 @@ export function get2DContext(}/**- * Calculates stroke width based on base brush size, pressure, and minimum size ratio.- * Mouse events typically give pressure = 0.5 or 0. If unmeasured or mouse, fallback gracefully.+ * Calculates stroke width based on base brush size, pressure, pressure curve, and minimum size ratio.+ * Follows Clip Studio Paint's exact dynamics calculation.*/export function calculateStrokeWidth(baseSize: number,@@ -30,27 +31,35 @@ export function calculateStrokeWidth(usePressure: boolean,pointerType: string,pressureCurveGamma: number = 1.0,- velocityScale: number = 1.0+ velocityScale: number = 1.0,+ pressureCurve?: [number, number][]): number {- if (!usePressure || pointerType === 'mouse') {- return Math.max(1, baseSize * velocityScale);+ if (!usePressure) {+ return Math.max(0.2, baseSize * velocityScale);}- // Tablet stylus pressure+ // Tablet stylus pressure vs mouse fallbacklet effectivePressure = pressure;- if (effectivePressure <= 0 || Number.isNaN(effectivePressure)) {+ if (pointerType === 'mouse') {effectivePressure = 0.5;+ } else {+ if (Number.isNaN(effectivePressure) || effectivePressure === undefined) {+ effectivePressure = 0;+ }+ effectivePressure = Math.max(0, Math.min(1.0, effectivePressure));}- // Clamp pressure between 0.01 and 1.0 to preserve full dynamic range- const clampedPressure = Math.min(Math.max(effectivePressure, 0.01), 1.0);- // Apply CSP pressure response curve gamma (e.g. 0.6 soft, 1.0 linear, 1.6 hard)- const gammaPressure = pressureCurveGamma !== 1.0- ? Math.pow(clampedPressure, pressureCurveGamma)- : clampedPressure;+ // Evaluate through authentic CSP cubic Hermite spline curve if available+ let curvePressure = effectivePressure;+ if (pressureCurve && pressureCurve.length > 0) {+ curvePressure = evaluateCspSpline(effectivePressure, pressureCurve);+ } else if (pressureCurveGamma !== 1.0) {+ curvePressure = Math.pow(Math.max(0, effectivePressure), pressureCurveGamma);+ }- const minWidth = baseSize * minSizeFactor;- return Math.max(0.5, (minWidth + (baseSize - minWidth) * gammaPressure) * velocityScale);+ const minRatio = Math.max(0, Math.min(1.0, minSizeFactor ?? 0));+ const dynamicWidth = baseSize * (minRatio + (1.0 - minRatio) * curvePressure) * velocityScale;+ return Math.max(0.1, dynamicWidth);}/**@@ -87,28 +96,81 @@ export function getQuadraticBezierPoint(}/**- * Draws a smooth tapered segment along a quadratic Bézier curve.- * Optimized for instant, zero-lag rendering at 120+ FPS like Clip Studio Paint.+ * Converts 4 Catmull-Rom spline knots (p0, p1, p2, p3) into cubic Bézier control points (c1, c2)+ * for the segment from p1 to p2.+ * Includes centripetal chord bounding to prevent overshooting or loops on tight turns.*/-export function drawSmoothBezierSegment(+export function catmullRomToBezier(+ p0: Point,+ p1: Point,+ p2: Point,+ p3: Point+): { c1: Point; c2: Point } {+ const dChord = Math.hypot(p2.x - p1.x, p2.y - p1.y);++ let dx1 = (p2.x - p0.x) / 6;+ let dy1 = (p2.y - p0.y) / 6;+ let dx2 = (p3.x - p1.x) / 6;+ let dy2 = (p3.y - p1.y) / 6;++ // Prevent overshoot on tight turns or uneven knot spacing+ if (dChord > 0.001) {+ const maxHandle = dChord * 0.5;+ const len1 = Math.hypot(dx1, dy1);+ if (len1 > maxHandle) {+ const s = maxHandle / len1;+ dx1 *= s;+ dy1 *= s;+ }+ const len2 = Math.hypot(dx2, dy2);+ if (len2 > maxHandle) {+ const s = maxHandle / len2;+ dx2 *= s;+ dy2 *= s;+ }+ }++ const c1: Point = {+ x: p1.x + dx1,+ y: p1.y + dy1,+ pressure: p1.pressure + (p2.pressure - p0.pressure) / 6,+ width: p1.width + (p2.width - p0.width) / 6,+ };++ const c2: Point = {+ x: p2.x - dx2,+ y: p2.y - dy2,+ pressure: p2.pressure - (p3.pressure - p1.pressure) / 6,+ width: p2.width - (p3.width - p1.width) / 6,+ };++ return { c1, c2 };+}++/**+ * Draws a smooth tapered segment along a cubic Bézier curve.+ * Gives 120+ FPS instantaneous rendering like Clip Studio Paint.+ */+export function drawSmoothCubicBezierSegment(ctx: CanvasRenderingContext2D,- start: Point,- control: Point,- end: Point,+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,color: string,isEraser: boolean = false,hardness: number = 1.0,flow: number = 1.0,_spacing: number = 0.1) {- const dx = end.x - start.x;- const dy = end.y - start.y;+ const dx = p3.x - p0.x;+ const dy = p3.y - p0.y;const dist = Math.hypot(dx, dy);- if (dist < 0.2) return;+ if (dist < 0.15) return;- const avgWidth = (start.width + end.width) / 2;- const widthDiff = Math.abs(end.width - start.width);+ const avgWidth = (p0.width + p3.width) / 2;+ const widthDiff = Math.abs(p3.width - p0.width);ctx.save();ctx.lineCap = 'round';@@ -132,38 +194,74 @@ export function drawSmoothBezierSegment(ctx.shadowColor = isEraser ? 'rgba(0, 0, 0, 1)' : color;}- // Fast-path: single quadratic curve when width change is small or distance is short- // Gives 0.003ms instant rendering per stroke segment (zero latency like CSP)- if (widthDiff <= 1.5 || dist <= 8) {+ // Fast-path: native cubic Bézier when width change is small+ if (widthDiff <= 1.5 || dist <= 12) {ctx.beginPath();ctx.lineWidth = avgWidth;- ctx.moveTo(start.x, start.y);- ctx.quadraticCurveTo(control.x, control.y, end.x, end.y);+ ctx.moveTo(p0.x, p0.y);+ ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p3.x, p3.y);ctx.stroke();ctx.restore();return;}- // Tapered stroke when width changes significantly: at most 2 or 3 adaptive steps- const steps = dist > 24 ? 3 : 2;- let prevPoint = { x: start.x, y: start.y, width: start.width };+ // Tapered stroke when width changes significantly: adaptive cubic steps+ const steps = dist > 32 ? 4 : 2;+ let prevPt = { x: p0.x, y: p0.y, width: p0.width };for (let i = 1; i <= steps; i++) {const t = i / steps;- const currPoint = getQuadraticBezierPoint(start, control, end, t);+ const invT = 1.0 - t;+ const invT2 = invT * invT;+ const invT3 = invT2 * invT;+ const t2 = t * t;+ const t3 = t2 * t;++ const currX = invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x;+ const currY = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;+ const currWidth = invT * p0.width + t * p3.width;ctx.beginPath();- ctx.lineWidth = (prevPoint.width + currPoint.width) / 2;- ctx.moveTo(prevPoint.x, prevPoint.y);- ctx.lineTo(currPoint.x, currPoint.y);+ ctx.lineWidth = (prevPt.width + currWidth) / 2;+ ctx.moveTo(prevPt.x, prevPt.y);+ ctx.lineTo(currX, currY);ctx.stroke();- prevPoint = currPoint;+ prevPt = { x: currX, y: currY, width: currWidth };}ctx.restore();}+/**+ * Draws a smooth tapered segment along a quadratic Bézier curve by elevating to cubic.+ */+export function drawSmoothBezierSegment(+ ctx: CanvasRenderingContext2D,+ start: Point,+ control: Point,+ end: Point,+ color: string,+ isEraser: boolean = false,+ hardness: number = 1.0,+ flow: number = 1.0,+ spacing: number = 0.1+) {+ const c1: Point = {+ x: start.x + (2.0 / 3.0) * (control.x - start.x),+ y: start.y + (2.0 / 3.0) * (control.y - start.y),+ pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),+ width: start.width + (2.0 / 3.0) * (control.width - start.width),+ };+ const c2: Point = {+ x: end.x + (2.0 / 3.0) * (control.x - end.x),+ y: end.y + (2.0 / 3.0) * (control.y - end.y),+ pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),+ width: end.width + (2.0 / 3.0) * (control.width - end.width),+ };+ drawSmoothCubicBezierSegment(ctx, start, c1, c2, end, color, isEraser, hardness, flow, spacing);+}+/*** Draws a single dot (e.g. on pointer down without movement).*/@@ -551,52 +649,54 @@ export function renderCompleteStroke(if (points.length === 2) {const p0 = points[0];const p1 = points[1];- const mid = getMidPoint(p0, p1);- drawPencilBezierSegment(ctx, p0, p0, mid, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);- drawPencilBezierSegment(ctx, mid, p1, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);+ const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);+ drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);return;}const p0 = points[0];const p1 = points[1];- const mid0 = getMidPoint(p0, p1);- drawPencilBezierSegment(ctx, p0, p0, mid0, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);+ const p2 = points[2];+ const first = catmullRomToBezier(p0, p0, p1, p2);+ drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);- for (let i = 2; i < points.length; i++) {- const startMid = getMidPoint(points[i - 2], points[i - 1]);- const endMid = getMidPoint(points[i - 1], points[i]);- drawPencilBezierSegment(ctx, startMid, points[i - 1], endMid, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);+ for (let i = 2; i < points.length - 1; i++) {+ const seg = catmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);+ drawPencilCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], strokeColor, grade, pFlow, pGrain, brushSettings.hardness);}- const pLast = points[points.length - 1];- const pPrev = points[points.length - 2];- const lastMid = getMidPoint(pPrev, pLast);- drawPencilBezierSegment(ctx, lastMid, pLast, pLast, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);+ const n = points.length;+ const pPrev2 = points[n - 3];+ const pPrev = points[n - 2];+ const pLast = points[n - 1];+ const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);+ drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);} else if (brushSettings.smoothing) {if (points.length === 2) {const p0 = points[0];const p1 = points[1];- const mid = getMidPoint(p0, p1);- drawSmoothBezierSegment(ctx, p0, p0, mid, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);- drawSmoothBezierSegment(ctx, mid, p1, p1, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);+ const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);+ drawSmoothCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);return;}const p0 = points[0];const p1 = points[1];- const mid0 = getMidPoint(p0, p1);- drawSmoothBezierSegment(ctx, p0, p0, mid0, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);+ const p2 = points[2];+ const first = catmullRomToBezier(p0, p0, p1, p2);+ drawSmoothCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);- for (let i = 2; i < points.length; i++) {- const startMid = getMidPoint(points[i - 2], points[i - 1]);- const endMid = getMidPoint(points[i - 1], points[i]);- drawSmoothBezierSegment(ctx, startMid, points[i - 1], endMid, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);+ for (let i = 2; i < points.length - 1; i++) {+ const seg = catmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);+ drawSmoothCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);}- const pLast = points[points.length - 1];- const pPrev = points[points.length - 2];- const lastMid = getMidPoint(pPrev, pLast);- drawSmoothBezierSegment(ctx, lastMid, pLast, pLast, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);+ const n = points.length;+ const pPrev2 = points[n - 3];+ const pPrev = points[n - 2];+ const pLast = points[n - 1];+ const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);+ drawSmoothCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);} else {ctx.save();ctx.lineCap = 'round';diff --git a/src/utils/colorUtils.ts b/src/utils/colorUtils.tsindex a043f17..a19dc7d 100644--- a/src/utils/colorUtils.ts+++ b/src/utils/colorUtils.ts@@ -83,29 +83,75 @@ export function applyColorModeToImageData(imageData: ImageData, mode: CanvasColofor (let i = 0; i < len; i += 4) {const alpha = data[i + 3];if (alpha === 0) continue;- const lum = Math.round(0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]);+ const lum = (19595 * data[i] + 38470 * data[i + 1] + 7471 * data[i + 2] + 32768) >> 16;data[i] = lum;data[i + 1] = lum;data[i + 2] = lum;}} else if (mode === 'monochrome') {- // Manga 1-bit crisp binary thresholding- for (let i = 0; i < len; i += 4) {- const alpha = data[i + 3];+ // Manga 1-bit crisp binary thresholding (Uint32Array fast-path)+ const u32 = new Uint32Array(imageData.data.buffer);+ const u32Len = u32.length;+ for (let i = 0; i < u32Len; i++) {+ const pix = u32[i];+ const alpha = (pix >>> 24) & 0xFF;if (alpha < 128) {- data[i + 3] = 0; // transparent+ u32[i] = 0;continue;}- const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];- const val = lum >= 128 ? 255 : 0;- data[i] = val;- data[i + 1] = val;- data[i + 2] = val;- data[i + 3] = 255; // solid+ const r = pix & 0xFF;+ const g = (pix >>> 8) & 0xFF;+ const b = (pix >>> 16) & 0xFF;+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;+ u32[i] = lum >= 128 ? 0xFFFFFFFF : 0xFF000000;}}}+/**+ * Ultra-fast 32-bit in-place binary thresholding on a canvas context rect.+ * Converts anti-aliased stroke edges to 1-bit crisp binary output in real time (<0.05ms).+ */+export function binarizeCanvasRect(+ ctx: CanvasRenderingContext2D,+ rect: { x: number; y: number; width: number; height: number },+ threshold: number = 128,+ expressBlack: boolean = true,+ expressWhite: boolean = true+) {+ const sx = Math.max(0, Math.floor(rect.x));+ const sy = Math.max(0, Math.floor(rect.y));+ const sw = Math.min(ctx.canvas.width - sx, Math.ceil(rect.width));+ const sh = Math.min(ctx.canvas.height - sy, Math.ceil(rect.height));++ if (sw <= 0 || sh <= 0) return;++ const imgData = ctx.getImageData(sx, sy, sw, sh);+ const u32 = new Uint32Array(imgData.data.buffer);+ const len = u32.length;+ const thresh = Math.max(1, Math.min(255, threshold));++ for (let i = 0; i < len; i++) {+ const pix = u32[i];+ const alpha = (pix >>> 24) & 0xFF;+ if (alpha < 128) {+ u32[i] = 0; // transparent+ continue;+ }+ const r = pix & 0xFF;+ const g = (pix >>> 8) & 0xFF;+ const b = (pix >>> 16) & 0xFF;+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;+ if (lum < thresh) {+ u32[i] = expressBlack ? 0xFF000000 : 0;+ } else {+ u32[i] = expressWhite ? 0xFFFFFFFF : 0;+ }+ }++ ctx.putImageData(imgData, sx, sy);+}+/*** Processes an HTMLCanvasElement in-place to conform with the given color mode.* Supports an optional dirtyRect to avoid full-canvas buffer readbacks on high-res canvases.diff --git a/src/utils/layerEffectsEngine.ts b/src/utils/layerEffectsEngine.tsindex b4596b6..c709861 100644--- a/src/utils/layerEffectsEngine.ts+++ b/src/utils/layerEffectsEngine.ts@@ -81,31 +81,23 @@ export function applyExpressionColorToImageData(data[i + 2] = lum;}} else if (mode === 'monochrome') {- for (let i = 0; i < len; i += 4) {- const a = data[i + 3];- if (a === 0) continue;-- const lum = (19595 * data[i] + 38470 * data[i + 1] + 7471 * data[i + 2] + 32768) >> 16;+ const u32 = new Uint32Array(imgData.data.buffer);+ const u32Len = u32.length;+ for (let i = 0; i < u32Len; i++) {+ const pix = u32[i];+ const a = (pix >>> 24) & 0xFF;+ if (a < 64) {+ u32[i] = 0;+ continue;+ }+ const r = pix & 0xFF;+ const g = (pix >>> 8) & 0xFF;+ const b = (pix >>> 16) & 0xFF;+ const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;if (lum < threshold) {- // Dark tone- if (expressBlack) {- data[i] = 0;- data[i + 1] = 0;- data[i + 2] = 0;- data[i + 3] = a >= 64 ? 255 : 0;- } else {- data[i + 3] = 0; // transparent- }+ u32[i] = expressBlack ? 0xFF000000 : 0;} else {- // Light tone- if (expressWhite) {- data[i] = 255;- data[i + 1] = 255;- data[i + 2] = 255;- data[i + 3] = a >= 64 ? 255 : 0;- } else {- data[i + 3] = 0; // transparent (drops white background!)- }+ u32[i] = expressWhite ? 0xFFFFFFFF : 0;}}}diff --git a/src/utils/pencilEngine.ts b/src/utils/pencilEngine.tsindex 3c810e7..5f41c70 100644--- a/src/utils/pencilEngine.ts+++ b/src/utils/pencilEngine.ts@@ -201,7 +201,7 @@ export function parseRgba(colorStr: string): [number, number, number, number] {/*** Evaluates a quadratic Bézier curve at parameter t (0 <= t <= 1).*/-function getQuadraticBezierPoint(+export function getQuadraticBezierPoint(p0: Point,control: Point,p2: Point,@@ -232,14 +232,38 @@ function getPencilNoise(seed: number): number {}/**- * Draws a real pencil mark along a quadratic Bézier curve.- * Accurately models graphite flakes catching on world-anchored paper tooth ridges.+ * Evaluates a cubic Bézier point at parameter t (0 <= t <= 1).*/-export function drawPencilBezierSegment(+export function getCubicBezierPoint(+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,+ t: number+): Point {+ const invT = 1.0 - t;+ const invT2 = invT * invT;+ const invT3 = invT2 * invT;+ const t2 = t * t;+ const t3 = t2 * t;++ return {+ x: invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x,+ y: invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y,+ pressure: invT * p0.pressure + t * p3.pressure,+ width: invT * p0.width + t * p3.width,+ };+}++/**+ * Draws a real pencil mark along a cubic Bézier curve.+ */+export function drawPencilCubicBezierSegment(ctx: CanvasRenderingContext2D,- start: Point,- control: Point,- end: Point,+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,color: string,grade: PencilGrade = 'pencil-2b',userFlow: number = 0.75,@@ -248,15 +272,15 @@ export function drawPencilBezierSegment() {const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];- const dx = end.x - start.x;- const dy = end.y - start.y;+ const dx = p3.x - p0.x;+ const dy = p3.y - p0.y;const dist = Math.hypot(dx, dy);if (dist < 0.15) return;const [cr, cg, cb] = parseRgba(color);// Dynamic spacing: smaller width = tighter micro-stamps for silky continuity- const avgWidth = Math.max(1, (start.width + end.width) / 2);+ const avgWidth = Math.max(1, (p0.width + p3.width) / 2);const stepDist = Math.max(0.45, Math.min(1.8, avgWidth * 0.18));const numSteps = Math.max(2, Math.ceil(dist / stepDist));@@ -271,7 +295,7 @@ export function drawPencilBezierSegment(for (let i = 0; i <= numSteps; i++) {const t = i / numSteps;- const pt = getQuadraticBezierPoint(start, control, end, t);+ const pt = getCubicBezierPoint(p0, c1, c2, p3, t);const radius = Math.max(0.6, pt.width / 2);const pressure = Math.min(Math.max(pt.pressure || 0.5, 0.05), 1.0);@@ -330,6 +354,35 @@ export function drawPencilBezierSegment(ctx.restore();}+/**+ * Draws a real pencil mark along a quadratic Bézier curve by elevating to cubic.+ */+export function drawPencilBezierSegment(+ ctx: CanvasRenderingContext2D,+ start: Point,+ control: Point,+ end: Point,+ color: string,+ grade: PencilGrade = 'pencil-2b',+ userFlow: number = 0.75,+ grainIntensity: number = 1.0,+ userHardness?: number+) {+ const c1: Point = {+ x: start.x + (2.0 / 3.0) * (control.x - start.x),+ y: start.y + (2.0 / 3.0) * (control.y - start.y),+ pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),+ width: start.width + (2.0 / 3.0) * (control.width - start.width),+ };+ const c2: Point = {+ x: end.x + (2.0 / 3.0) * (control.x - end.x),+ y: end.y + (2.0 / 3.0) * (control.y - end.y),+ pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),+ width: end.width + (2.0 / 3.0) * (control.width - end.width),+ };+ drawPencilCubicBezierSegment(ctx, start, c1, c2, end, color, grade, userFlow, grainIntensity, userHardness);+}+/*** Draws a real pencil dot (e.g. single tap / initial contact).*/diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.tsindex 1c7d7fc..32f4d18 100644--- a/src/utils/stampEngine.ts+++ b/src/utils/stampEngine.ts@@ -23,6 +23,7 @@ export interface TexturedBrushOptions {antiAlias?: number;pressureCurve?: [number, number][];velocityCurve?: [number, number][];+ usePressure?: boolean;useVelocity?: boolean;subTips?: CspSubTip[];subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';@@ -160,9 +161,12 @@ export function drawSingleStamp(isEraser: boolean = false,isBgEraser: boolean = false) {- if (width <= 0 || height <= 0 || alpha <= 0.002) return;+ if (width < 0.1 || height < 0.1 || alpha <= 0.002) return;- const effAlpha = Math.max(0.005, Math.min(1.0, alpha));+ const subpixelScale = width < 1.0 ? Math.max(0.1, width) : 1.0;+ const effAlpha = Math.max(0.003, Math.min(1.0, alpha * subpixelScale));+ const renderW = Math.max(0.6, width);+ const renderH = Math.max(0.6, height);// Ultra-fast path for unrotated normal stampsif (Math.abs(angleRad) < 0.001 && !isEraser && !isBgEraser) {@@ -170,7 +174,7 @@ export function drawSingleStamp(const prevOp = ctx.globalCompositeOperation;ctx.globalCompositeOperation = 'source-over';ctx.globalAlpha = effAlpha;- ctx.drawImage(stampSource, x - width / 2, y - height / 2, width, height);+ ctx.drawImage(stampSource, x - renderW / 2, y - renderH / 2, renderW, renderH);ctx.globalAlpha = prevAlpha;ctx.globalCompositeOperation = prevOp;return;@@ -331,64 +335,126 @@ export function drawTexturedDot(}// --------------------------------------------------------------// Quadratic Bézier Evaluation and Gauss-Legendre Arc Length+// Cubic Bézier Evaluation and Arc Length Parameterization// --------------------------------------------------------------function evalQuadraticBezier(+export function evalCubicBezier(p0: Point,- control: Point,- p2: Point,+ c1: Point,+ c2: Point,+ p3: Point,t: number): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number } {const invT = 1.0 - t;const invT2 = invT * invT;+ const invT3 = invT2 * invT;const t2 = t * t;- const twoInvTT = 2.0 * invT * t;-- const x = invT2 * p0.x + twoInvTT * control.x + t2 * p2.x;- const y = invT2 * p0.y + twoInvTT * control.y + t2 * p2.y;- const width = invT * p0.width + t * p2.width;- const pressure = invT * p0.pressure + t * p2.pressure;-- const dx = 2.0 * invT * (control.x - p0.x) + 2.0 * t * (p2.x - control.x);- const dy = 2.0 * invT * (control.y - p0.y) + 2.0 * t * (p2.y - control.y);+ const t3 = t2 * t;++ const a = invT3;+ const b = 3.0 * invT2 * t;+ const c = 3.0 * invT * t2;+ const d = t3;++ const x = a * p0.x + b * c1.x + c * c2.x + d * p3.x;+ const y = a * p0.y + b * c1.y + c * c2.y + d * p3.y;+ const width = invT * p0.width + t * p3.width;+ const pressure = invT * p0.pressure + t * p3.pressure;++ const d01x = c1.x - p0.x;+ const d01y = c1.y - p0.y;+ const d12x = c2.x - c1.x;+ const d12y = c2.y - c1.y;+ const d23x = p3.x - c2.x;+ const d23y = p3.y - c2.y;++ const dx = 3.0 * invT2 * d01x + 6.0 * invT * t * d12x + 3.0 * t2 * d23x;+ const dy = 3.0 * invT2 * d01y + 6.0 * invT * t * d12y + 3.0 * t2 * d23y;const speed = Math.hypot(dx, dy);return { x, y, width, pressure, dx, dy, speed };}-function computeQuadraticArcLength(p0: Point, control: Point, p2: Point): number {- const nodes = [0.046910077, 0.230765345, 0.5, 0.769234655, 0.953089923];- const weights = [0.118463442, 0.239314335, 0.284444444, 0.239314335, 0.118463442];+interface ArcLengthTable {+ totalLength: number;+ distances: number[];+}++function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {+ const steps = 8;+ const distances: number[] = [0];+ let total = 0;+ let prevX = p0.x;+ let prevY = p0.y;- let length = 0;- for (let i = 0; i < 5; i++) {- const t = nodes[i];+ for (let i = 1; i <= steps; i++) {+ const t = i / steps;const invT = 1.0 - t;- const dx = 2.0 * invT * (control.x - p0.x) + 2.0 * t * (p2.x - control.x);- const dy = 2.0 * invT * (control.y - p0.y) + 2.0 * t * (p2.y - control.y);- length += weights[i] * Math.hypot(dx, dy);+ const invT2 = invT * invT;+ const invT3 = invT2 * invT;+ const t2 = t * t;+ const t3 = t2 * t;++ const x = invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x;+ const y = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;++ total += Math.hypot(x - prevX, y - prevY);+ distances.push(total);+ prevX = x;+ prevY = y;+ }++ return { totalLength: total, distances };+}++function getCubicPointAtArcLength(+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,+ targetDist: number,+ table: ArcLengthTable+): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number } {+ const { totalLength, distances } = table;+ if (totalLength <= 0.0001 || targetDist <= 0) {+ return evalCubicBezier(p0, c1, c2, p3, 0);+ }+ if (targetDist >= totalLength) {+ return evalCubicBezier(p0, c1, c2, p3, 1.0);+ }++ let idx = 0;+ while (idx < 8 && distances[idx + 1] < targetDist) {+ idx++;}- return length;++ const d0 = distances[idx];+ const d1 = distances[idx + 1];+ const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;+ const t = (idx + frac) / 8.0;++ return evalCubicBezier(p0, c1, c2, p3, Math.max(0, Math.min(1.0, t)));}/**- * Draws textured brush stamps along a quadratic Bézier curve using true arc-length parameterization.+ * Draws textured brush stamps along a cubic Bézier curve using arc-length parameterization.* Supports multi-tips, spline pressure curve, spray particle scattering, and wet edge.*/-export function drawTexturedBezierSegment(+export function drawTexturedCubicBezierSegment(ctx: CanvasRenderingContext2D,- start: Point,- control: Point,- end: Point,+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,color: string,tipImage: HTMLImageElement,options: TexturedBrushOptions,remainderDist: number = 0,dabCounter: { count: number } = { count: 0 }): number {- const totalCurveLength = computeQuadraticArcLength(start, control, end);- if (totalCurveLength < 0.15) {+ const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);+ const totalCurveLength = arcTable.totalLength;+ if (totalCurveLength < 0.1) {return remainderDist;}@@ -410,167 +476,254 @@ export function drawTexturedBezierSegment(const spacingRatio = Math.max(0.015, Math.min(1.0, options.spacing ?? 0.07));const thickness = options.thickness ?? 1.0;const rotationRandomScale = options.rotationRandomScale ?? 0;- const minSizeFactor = options.minSizeFactor ?? 0.2;let smoothCos = Math.cos(baseAngleRad);let smoothSin = Math.sin(baseAngleRad);- let currentDist = -remainderDist;- let t = 0;+ let currentDist = remainderDist > 0 ? remainderDist : 0;- while (currentDist < totalCurveLength) {- const rawT = Math.max(0, Math.min(1.0, (currentDist + remainderDist) / totalCurveLength));- const interpPressure = start.pressure * (1.0 - rawT) + end.pressure * rawT;- const effPressure = evaluateCspSpline(interpPressure, options.pressureCurve);+ while (currentDist <= totalCurveLength) {+ const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);+ const effPressure = evaluateCspSpline(pt.pressure, options.pressureCurve);+ const minFactor = Math.max(0, Math.min(1.0, options.minSizeFactor ?? 0));- let curWidth = Math.max(1, options.size * (minSizeFactor + (1.0 - minSizeFactor) * effPressure));+ let curWidth = options.usePressure !== false+ ? options.size * (minFactor + (1.0 - minFactor) * effPressure)+ : options.size;- // Stroke taper modulation- if (options.taper && options.totalLength && options.totalLength > 0) {- const distFromStart = (options.currentStrokeDist ?? 0) + currentDist;- const distFromEnd = options.totalLength - distFromStart;- if (options.taper.inLength > 0 && distFromStart < options.taper.inLength) {- const inFactor = distFromStart / options.taper.inLength;- curWidth *= Math.max(0.1, inFactor);+ // Stroke taper modulation (Clip Studio Paint style)+ if (options.taper) {+ const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;+ const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);+ if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {+ const inFactor = Math.max(0.01, Math.min(1.0, strokeDist / inLen));+ curWidth *= Math.pow(inFactor, 0.75);}- if (options.taper.outLength > 0 && distFromEnd < options.taper.outLength) {- const outFactor = distFromEnd / options.taper.outLength;- curWidth *= Math.max(0.05, outFactor);+ if (options.totalLength && options.totalLength > 0) {+ const distFromEnd = options.totalLength - strokeDist;+ const outLen = options.taper.outLength || (options.taper.outRatio ? options.taper.outRatio * 3.0 : 0);+ if (options.taper.useOut && outLen > 0 && distFromEnd < outLen) {+ const outFactor = Math.max(0.01, Math.min(1.0, distFromEnd / outLen));+ curWidth *= Math.pow(outFactor, 0.85);+ }}}- const requiredStep = Math.max(0.75, curWidth * spacingRatio);- currentDist += requiredStep;- if (currentDist > totalCurveLength) {- break;+ curWidth = Math.max(0.1, curWidth);++ let stampAngle = baseAngleRad;+ if (options.angleDynamics === 'direction' && pt.speed > 0.05) {+ const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;+ const tCos = Math.cos(targetAngle);+ const tSin = Math.sin(targetAngle);+ smoothCos = smoothCos * 0.65 + tCos * 0.35;+ smoothSin = smoothSin * 0.65 + tSin * 0.35;+ stampAngle = Math.atan2(smoothSin, smoothCos);+ } else if (options.angleDynamics === 'random') {+ stampAngle = baseAngleRad + (Math.random() - 0.5) * Math.PI * 2;}- if (currentDist >= 0) {- t = Math.max(0, Math.min(1.0, currentDist / totalCurveLength));- const pt = evalQuadraticBezier(start, control, end, t);-- let stampAngle = baseAngleRad;- if (options.angleDynamics === 'direction' && pt.speed > 0.05) {- const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;- const tCos = Math.cos(targetAngle);- const tSin = Math.sin(targetAngle);- smoothCos = smoothCos * 0.65 + tCos * 0.35;- smoothSin = smoothSin * 0.65 + tSin * 0.35;- stampAngle = Math.atan2(smoothSin, smoothCos);- } else if (options.angleDynamics === 'random') {- stampAngle = baseAngleRad + (Math.random() - 0.5) * Math.PI * 2;- }+ if (rotationRandomScale > 0) {+ stampAngle += (Math.random() - 0.5) * Math.PI * 2 * rotationRandomScale;+ }- if (rotationRandomScale > 0) {- stampAngle += (Math.random() - 0.5) * Math.PI * 2 * rotationRandomScale;- }+ let dabColor = baseColor;+ let dabAlpha = baseFlow;- let dabColor = baseColor;- let dabAlpha = baseFlow;-- if (isColorMixing && reservoir) {- let sampled = { r: 255, g: 255, b: 255, a: 0 };- if (sampler) {- sampled = sampler.sampleColor(pt.x, pt.y, curWidth * 0.45);- } else {- const sampleCanvas = options.underlyingCanvas || ctx.canvas;- const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;- if (sampleCtx) {- sampled = sampleCanvasColor(sampleCtx, pt.x, pt.y, curWidth * 0.45);- }+ if (isColorMixing && reservoir) {+ let sampled = { r: 255, g: 255, b: 255, a: 0 };+ if (sampler) {+ sampled = sampler.sampleColor(pt.x, pt.y, curWidth * 0.45);+ } else {+ const sampleCanvas = options.underlyingCanvas || ctx.canvas;+ const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;+ if (sampleCtx) {+ sampled = sampleCanvasColor(sampleCtx, pt.x, pt.y, curWidth * 0.45);}+ }- const mixed = reservoir.mixWithCanvas(- sampled,- options.amountOfPaint ?? 0.65,- options.densityOfPaint ?? 0.9,- options.colorStretch ?? 0.75,- options.mixingMode ?? 'blend',- effPressure,- baseFlow,- requiredStep- );+ const mixed = reservoir.mixWithCanvas(+ sampled,+ options.amountOfPaint ?? 0.65,+ options.densityOfPaint ?? 0.9,+ options.colorStretch ?? 0.75,+ options.mixingMode ?? 'blend',+ effPressure,+ baseFlow,+ Math.max(0.2, curWidth * spacingRatio)+ );- dabColor = mixed.colorHex;- dabAlpha = mixed.alpha;-- if (sampler) {- sampler.depositDab(- pt.x,- pt.y,- curWidth * 0.45,- mixed.r,- mixed.g,- mixed.b,- mixed.alpha- );- }- }+ dabColor = mixed.colorHex;+ dabAlpha = mixed.alpha;- // Wet Edge rim boost- if (options.wetEdge && options.wetEdge > 0) {- dabAlpha = Math.min(1.0, dabAlpha * (1.0 + options.wetEdge * 0.25));+ if (sampler) {+ sampler.depositDab(+ pt.x,+ pt.y,+ curWidth * 0.45,+ mixed.r,+ mixed.g,+ mixed.b,+ mixed.alpha+ );}+ }- // Select tip from multi-tip array- const activeTip = selectTipImage(- options.subTipImages,- tipImage,- options.subTipOrder,- dabCounter.count++,- stampAngle- );- const isColorTip = Boolean(options.subTips && options.subTips[0]?.isColor);- const master = getTintedTipMaster(activeTip, dabColor, isColorTip);-- const stampW = curWidth;- const stampH = curWidth * aspect * thickness;-- if (options.spray?.enabled) {- const pCount = options.spray.density;- const pSize = Math.max(1, options.spray.size);- const radius = curWidth / 2;- for (let sp = 0; sp < pCount; sp++) {- const u1 = Math.random();- const u2 = Math.random();- const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));- const th = Math.PI * 2 * Math.random();- drawSingleStamp(- ctx,- master,- pt.x + r * Math.cos(th),- pt.y + r * Math.sin(th),- pSize,- pSize * aspect * thickness,- stampAngle,- dabAlpha,- isEraser,- isBgEraser- );- }- } else {+ // Wet Edge rim boost+ if (options.wetEdge && options.wetEdge > 0) {+ dabAlpha = Math.min(1.0, dabAlpha * (1.0 + options.wetEdge * 0.25));+ }++ // Select tip from multi-tip array+ const activeTip = selectTipImage(+ options.subTipImages,+ tipImage,+ options.subTipOrder,+ dabCounter.count++,+ stampAngle+ );+ const isColorTip = Boolean(options.subTips && options.subTips[0]?.isColor);+ const master = getTintedTipMaster(activeTip, dabColor, isColorTip);++ const stampW = curWidth;+ const stampH = curWidth * aspect * thickness;++ if (options.spray?.enabled) {+ const pCount = options.spray.density;+ const pSize = Math.max(1, options.spray.size);+ const radius = curWidth / 2;+ for (let sp = 0; sp < pCount; sp++) {+ const u1 = Math.random();+ const u2 = Math.random();+ const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));+ const th = Math.PI * 2 * Math.random();drawSingleStamp(ctx,master,- pt.x,- pt.y,- stampW,- stampH,+ pt.x + r * Math.cos(th),+ pt.y + r * Math.sin(th),+ pSize,+ pSize * aspect * thickness,stampAngle,dabAlpha,isEraser,isBgEraser);}+ } else {+ drawSingleStamp(+ ctx,+ master,+ pt.x,+ pt.y,+ stampW,+ stampH,+ stampAngle,+ dabAlpha,+ isEraser,+ isBgEraser+ );}++ const requiredStep = Math.max(0.2, curWidth * spacingRatio);+ currentDist += requiredStep;}- const remainder = totalCurveLength - (currentDist - Math.max(0.75, end.width * spacingRatio));- return Math.max(0, remainder);+ const nextRemainder = currentDist - totalCurveLength;+ return Math.max(0, nextRemainder);}/**- * Renders an entire completed textured stroke onto the target Canvas2D context.+ * Draws textured brush stamps along a quadratic Bézier curve by elevating to cubic.+ */+export function drawTexturedBezierSegment(+ ctx: CanvasRenderingContext2D,+ start: Point,+ control: Point,+ end: Point,+ color: string,+ tipImage: HTMLImageElement,+ options: TexturedBrushOptions,+ remainderDist: number = 0,+ dabCounter: { count: number } = { count: 0 }+): number {+ const c1: Point = {+ x: start.x + (2.0 / 3.0) * (control.x - start.x),+ y: start.y + (2.0 / 3.0) * (control.y - start.y),+ pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),+ width: start.width + (2.0 / 3.0) * (control.width - start.width),+ };+ const c2: Point = {+ x: end.x + (2.0 / 3.0) * (control.x - end.x),+ y: end.y + (2.0 / 3.0) * (control.y - end.y),+ pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),+ width: end.width + (2.0 / 3.0) * (control.width - end.width),+ };+ return drawTexturedCubicBezierSegment(+ ctx,+ start,+ c1,+ c2,+ end,+ color,+ tipImage,+ options,+ remainderDist,+ dabCounter+ );+}++/**+ * Converts 4 Catmull-Rom spline knots into cubic Bézier control points.+ */+function catmullRomToCubicKnots(+ p0: Point,+ p1: Point,+ p2: Point,+ p3: Point+): { c1: Point; c2: Point } {+ const dChord = Math.hypot(p2.x - p1.x, p2.y - p1.y);++ let dx1 = (p2.x - p0.x) / 6;+ let dy1 = (p2.y - p0.y) / 6;+ let dx2 = (p3.x - p1.x) / 6;+ let dy2 = (p3.y - p1.y) / 6;++ if (dChord > 0.001) {+ const maxHandle = dChord * 0.5;+ const len1 = Math.hypot(dx1, dy1);+ if (len1 > maxHandle) {+ const s = maxHandle / len1;+ dx1 *= s;+ dy1 *= s;+ }+ const len2 = Math.hypot(dx2, dy2);+ if (len2 > maxHandle) {+ const s = maxHandle / len2;+ dx2 *= s;+ dy2 *= s;+ }+ }++ const c1: Point = {+ x: p1.x + dx1,+ y: p1.y + dy1,+ pressure: p1.pressure + (p2.pressure - p0.pressure) / 6,+ width: p1.width + (p2.width - p0.width) / 6,+ };++ const c2: Point = {+ x: p2.x - dx2,+ y: p2.y - dy2,+ pressure: p2.pressure - (p3.pressure - p1.pressure) / 6,+ width: p2.width - (p3.width - p1.width) / 6,+ };++ return { c1, c2 };+}++/**+ * Renders an entire completed textured stroke onto the target Canvas2D context using Catmull-Rom cubic splines.*/export function renderCompleteTexturedStroke(ctx: CanvasRenderingContext2D,@@ -598,61 +751,35 @@ export function renderCompleteTexturedStroke(return;}- let accDist = 0;const dabCounter = { count: 0 };+ let accDist = Math.max(0.2, points[0].width * (options.spacing ?? 0.07));if (points.length === 2) {const p0 = points[0];const p1 = points[1];- const mid = {- x: (p0.x + p1.x) / 2,- y: (p0.y + p1.y) / 2,- pressure: (p0.pressure + p1.pressure) / 2,- width: (p0.width + p1.width) / 2,- };- accDist = drawTexturedBezierSegment(ctx, p0, p0, mid, color, tipImage, options, accDist, dabCounter);- drawTexturedBezierSegment(ctx, mid, p1, p1, color, tipImage, options, accDist, dabCounter);+ const { c1, c2 } = catmullRomToCubicKnots(p0, p0, p1, p1);+ drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter);return;}+ // First segment: P0 -> P1 using (P0, P0, P1, P2)const p0 = points[0];const p1 = points[1];- const mid0 = {- x: (p0.x + p1.x) / 2,- y: (p0.y + p1.y) / 2,- pressure: (p0.pressure + p1.pressure) / 2,- width: (p0.width + p1.width) / 2,- };- accDist = drawTexturedBezierSegment(ctx, p0, p0, mid0, color, tipImage, options, accDist, dabCounter);-- for (let i = 2; i < points.length; i++) {- const pPrev = points[i - 2];- const pMid = points[i - 1];- const pNext = points[i];-- const startMid = {- x: (pPrev.x + pMid.x) / 2,- y: (pPrev.y + pMid.y) / 2,- pressure: (pPrev.pressure + pMid.pressure) / 2,- width: (pPrev.width + pMid.width) / 2,- };- const endMid = {- x: (pMid.x + pNext.x) / 2,- y: (pMid.y + pNext.y) / 2,- pressure: (pMid.pressure + pNext.pressure) / 2,- width: (pMid.width + pNext.width) / 2,- };-- accDist = drawTexturedBezierSegment(ctx, startMid, pMid, endMid, color, tipImage, options, accDist, dabCounter);+ const p2 = points[2];+ const first = catmullRomToCubicKnots(p0, p0, p1, p2);+ accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter);++ // Intermediate segments: P_{i-1} -> P_i using (P_{i-2}, P_{i-1}, P_i, P_{i+1})+ for (let i = 2; i < points.length - 1; i++) {+ const seg = catmullRomToCubicKnots(points[i - 2], points[i - 1], points[i], points[i + 1]);+ accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter);}- const pLast = points[points.length - 1];- const pSecondLast = points[points.length - 2];- const lastMid = {- x: (pSecondLast.x + pLast.x) / 2,- y: (pSecondLast.y + pLast.y) / 2,- pressure: (pSecondLast.pressure + pLast.pressure) / 2,- width: (pSecondLast.width + pLast.width) / 2,- };- drawTexturedBezierSegment(ctx, lastMid, pLast, pLast, color, tipImage, options, accDist, dabCounter);+ // Last segment: P_{N-2} -> P_{N-1} using (P_{N-3}, P_{N-2}, P_{N-1}, P_{N-1})+ const n = points.length;+ const pPrev2 = points[n - 3];+ const pPrev = points[n - 2];+ const pLast = points[n - 1];+ const last = catmullRomToCubicKnots(pPrev2, pPrev, pLast, pLast);+ drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter);}diff --git a/src/utils/sutParser.ts b/src/utils/sutParser.tsindex 6b3afe1..151a5fe 100644--- a/src/utils/sutParser.ts+++ b/src/utils/sutParser.ts@@ -922,12 +922,25 @@ export async function parseSutFile(// Taper (In / Out)const rawUseIn = getVal(['BrushUseIn']);const rawUseOut = getVal(['BrushUseOut']);- if (Boolean(rawUseIn) || Boolean(rawUseOut)) {+ const useIn = rawUseIn !== null ? Boolean(rawUseIn) : false;+ const useOut = rawUseOut !== null ? Boolean(rawUseOut) : false;+ const inLength = Number(getVal(['BrushInLength']) || 0);+ const inRatio = Number(getVal(['BrushInRatio']) || 0);+ const outLength = Number(getVal(['BrushOutLength']) || 0);+ const outRatio = Number(getVal(['BrushOutRatio']) || 0);+ const inOutType = Number(getVal(['BrushInOutType']) || 0);+ const inOutBySpeed = Boolean(getVal(['BrushInOutBySpeed']));++ if (useIn || useOut || inLength > 0 || outLength > 0 || inRatio > 0 || outRatio > 0) {taper = {- inLength: getVal(['BrushInLength']) || 0,- inRatio: getVal(['BrushInRatio']) || 0,- outLength: getVal(['BrushOutLength']) || 0,- outRatio: getVal(['BrushOutRatio']) || 0,+ useIn,+ inLength,+ inRatio,+ useOut,+ outLength,+ outRatio,+ inOutType,+ inOutBySpeed,};}