Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(webv2): trace stroke paths directly instead of via an SVG string
joshistoast94c3d6cf427a
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex 4ad52e838c..74c2f05e11 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -244,7 +244,15 @@ const setupEngine = (doc: CanvasDocumentContractV2) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const reactive = createReactiveStore(doc);const engine = createCanvasEngine({@@ -383,7 +391,15 @@ describe('mask invert', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const reactive = createReactiveStore(maskDoc());const base = createTestStubRasterBackend();@@ -446,7 +462,15 @@ describe('mask invert', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const doc = maskDoc();doc.layers.push({blendMode: 'normal',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex cb2355f4c1..bdc1e09fcc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -652,7 +652,15 @@ describe('createCanvasEngine', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const layer = {...rasterLayer('a'),source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },@@ -1688,7 +1696,15 @@ describe('createCanvasEngine', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const document = paintDoc();const layer = document.layers[0];if (!layer || layer.type !== 'raster') {@@ -2061,7 +2077,15 @@ describe('createCanvasEngine', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const paint = {...rasterLayer('paint'),source: { bitmap: { height: 10, imageName: 'paint', width: 10 }, type: 'paint' as const },@@ -2670,7 +2694,15 @@ const createControlPaintHarness = (const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { source, ...layerOverrides } = overrides;const layer: CanvasControlLayerContract = {@@ -3410,7 +3442,15 @@ describe('engine-owned history: stroke → undo → redo', () => {vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);// The engine builds real `Path2D`s for stroke outlines; node lacks it.- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const base = createTestStubRasterBackend();@@ -3499,7 +3539,15 @@ describe('engine-owned history: stroke → undo → redo', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const base = createTestStubRasterBackend();@@ -3574,7 +3622,15 @@ describe('engine-owned history: stroke → undo → redo', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { setDocument, store } = createReactiveStore(paintDoc());const bitmapStore = createSpyBitmapStore();@@ -3608,7 +3664,15 @@ describe('engine-owned history: stroke → undo → redo', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { setDocument, store } = createReactiveStore(paintDoc());const bitmapStore = createSpyBitmapStore();@@ -3703,7 +3767,15 @@ describe('engine-owned history: undo/redo guarded during an active gesture', ()const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const base = createTestStubRasterBackend();@@ -5196,7 +5268,15 @@ describe('boolean raster operations', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const emptyPaint = (id: string): CanvasRasterLayerContractV2 => ({blendMode: 'normal',id,@@ -7298,7 +7378,15 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(imageSelectedDoc());const dispatch = store.dispatch as Mock;@@ -8140,7 +8228,15 @@ describe('commitRasterFilterResult', () => {const createRealBitmapStoreHarness = async (uploadImage: (blob: Blob) => Promise<{ height: number; imageName: string; width: number }>) => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const source: CanvasRasterLayerContractV2 = {...filterLayer('source'),source: {@@ -9762,7 +9858,15 @@ describe('commitGeneratedImageResult', () => {});it('returns stale when unpersisted paint pixels change while the generated image resolves', async () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const source: CanvasRasterLayerContractV2 = {...workflowRaster(),source: {@@ -10183,7 +10287,15 @@ describe('replaceSelectionFromImage', () => {imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;seedSelection?: boolean;} = {}) => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const layer = sourceLayer();const document = sourceDocument(layer);const reactive = createReactiveStore(document);@@ -10444,7 +10556,15 @@ describe('replaceSelectionFromImage', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const decoded = createDeferred<Blob>();const document = paintDoc();const { projectId, store } = createReducerBackedStore(document);@@ -12262,7 +12382,15 @@ describe('guarded filter previews', () => {});it('clears an already-published guarded preview when live paint advances the cache version', async () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const paint: CanvasRasterLayerContractV2 = {...guardableLayer('L'),source: { bitmap: { height: 10, imageName: 'paint-source', width: 10 }, type: 'paint' },@@ -12314,7 +12442,15 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { setDocument, store } = createReactiveStore(paintDoc());const base = createTestStubRasterBackend();@@ -12362,7 +12498,15 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { projectId, store } = createReducerBackedStore(paintDoc());const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12388,7 +12532,15 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const reducer = createReducerBackedStore(paintDoc());let throwAfterBitmapCommit = false;const unsubscribeThrower = reducer.store.subscribe(() => {@@ -12706,7 +12858,15 @@ describe('hasExportableLayerContent', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { setDocument, store } = createReactiveStore({...makeDoc(),@@ -12908,7 +13068,15 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const dispatch = store.dispatch as Mock;@@ -12971,7 +13139,15 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(twoPaintDoc());const dispatch = store.dispatch as Mock;@@ -13020,7 +13196,15 @@ describe('brush cursor ring: live size updates', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const engine = createCanvasEngine({@@ -13057,7 +13241,15 @@ describe('brush cursor ring: live size updates', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const engine = createCanvasEngine({@@ -14004,7 +14196,15 @@ const lockedPaintDoc = (): CanvasDocumentContractV2 => ({describe('engine selection: select all / deselect / invert + hasSelection store', () => {it('selectAll sets hasSelection; deselect clears it', () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createFakeStore(paintDoc());const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -14022,7 +14222,15 @@ describe('engine selection: select all / deselect / invert + hasSelection store'});it('invertSelection of an empty selection selects everything', () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createFakeStore(paintDoc());const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -14039,7 +14247,15 @@ describe('engine selection: select all / deselect / invert + hasSelection store'describe('engine selection: fill / erase', () => {const makeEngine = (doc: CanvasDocumentContractV2) => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createFakeStore(doc);const bitmapStore = createSpyBitmapStore();const engine = createCanvasEngine({@@ -14568,7 +14784,15 @@ describe('engine selection: marching ants animation + overlay-only', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const engine = createCanvasEngine({@@ -14605,7 +14829,15 @@ describe('engine selection: marching ants animation + overlay-only', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const engine = createCanvasEngine({@@ -14647,7 +14879,15 @@ describe('engine selection: lasso commit through the pipeline', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { store } = createReactiveStore(paintDoc());const dispatch = store.dispatch as Mock;@@ -14680,7 +14920,15 @@ describe('engine selection: lasso commit through the pipeline', () => {describe('engine selection: document replace clears the selection', () => {it('a wholesale document swap deselects', () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { setDocument, store } = createReactiveStore(paintDoc());const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -14910,7 +15158,15 @@ describe('text edit session', () => {});it('drops the session on a wholesale document replace', () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const { engine, setDocument } = makeEngine(textDoc());engine.tools.setTool('text');engine.layers.openTextEdit('txt1');@@ -15092,7 +15348,15 @@ describe('Select Object canvas engine integration', () => {});const createOpaqueSamBackend = () => {- vi.stubGlobal('Path2D', class FakePath2D {});+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];const backend: StubRasterBackend = {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 07bfe6da62..6b4a4875cd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -663,7 +663,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbitmapStore.markLayerDirty(layerId);};- const createPath2DImpl: CreatePath2D = (d) => new Path2D(d);+ const createPath2DImpl: CreatePath2D = (d) => (d === undefined ? new Path2D() : new Path2D(d));/** Bumps a layer's cache version after a direct paint (pixels stay fresh) and recomposites. */const notifyLayerPainted = (layerId: string): void => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.tsindex f41ce9fb97..7c6cdbecca 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts@@ -5,13 +5,12 @@ import {decimateSamples,MAX_SAMPLE_SPACING,outlineSmoothing,- PATH_ROUNDING_TOLERANCE,polygonBounds,- polygonToSmoothSvgPath,polygonToSvgPath,sampleSpacing,strokeOutlinePolygon,strokeToPath,+ traceSmoothPolygon,TARGET_VERTEX_SPACING,} from '@workbench/canvas-engine/freehand';import { describe, expect, it } from 'vitest';@@ -262,9 +261,35 @@ describe('polygonToSvgPath', () => {});});-describe('polygonToSmoothSvgPath', () => {+/**+ * A node-safe `Path2D` double that records the commands traced onto it, so the+ * curve can be asserted without a DOM.+ */+const recordingPath = () => {+ const commands: string[] = [];+ const points: Vec2[] = [];+ const path = {+ closePath: () => commands.push('Z'),+ lineTo: (x: number, y: number) => {+ commands.push(`L ${x} ${y}`);+ points.push({ x, y });+ },+ moveTo: (x: number, y: number) => {+ commands.push(`M ${x} ${y}`);+ points.push({ x, y });+ },+ quadraticCurveTo: (cx: number, cy: number, x: number, y: number) => {+ commands.push(`Q ${cx} ${cy} ${x} ${y}`);+ points.push({ x: cx, y: cy }, { x, y });+ },+ };+ return { commands, path: path as unknown as Path2D, points };+};++describe('traceSmoothPolygon', () => {it('runs a quadratic through each vertex, between its edge midpoints', () => {- const path = polygonToSmoothSvgPath([+ const { commands, path } = recordingPath();+ traceSmoothPolygon(path, [{ x: 0, y: 0 },{ x: 10, y: 0 },{ x: 10, y: 10 },@@ -272,56 +297,59 @@ describe('polygonToSmoothSvgPath', () => {]);// Starts on the seam midpoint (between the last and first vertices) so the// ring closes as smoothly as it turns.- expect(path).toBe('M 0 5 Q 0 0 5 0 Q 10 0 10 5 Q 10 10 5 10 Q 0 10 0 5 Z');+ expect(commands.join(' ')).toBe('M 0 5 Q 0 0 5 0 Q 10 0 10 5 Q 10 10 5 10 Q 0 10 0 5 Z');});it('falls back to straight segments when there is no curvature to describe', () => {- expect(polygonToSmoothSvgPath([])).toBe('');- expect(polygonToSmoothSvgPath([{ x: 1, y: 2 }])).toBe('M 1 2 Z');- expect(- polygonToSmoothSvgPath([- { x: 0, y: 0 },- { x: 4, y: 0 },- ])- ).toBe('M 0 0 L 4 0 Z');+ const empty = recordingPath();+ traceSmoothPolygon(empty.path, []);+ expect(empty.commands).toEqual([]);++ const dot = recordingPath();+ traceSmoothPolygon(dot.path, [{ x: 1, y: 2 }]);+ expect(dot.commands.join(' ')).toBe('M 1 2 Z');++ const line = recordingPath();+ traceSmoothPolygon(line.path, [+ { x: 0, y: 0 },+ { x: 4, y: 0 },+ ]);+ expect(line.commands.join(' ')).toBe('M 0 0 L 4 0 Z');});it('stays within the polygon bounds, so the dirty rect still encloses it', () => {// Every control point is a polygon vertex and every on-curve point an edge// midpoint, so the curve cannot leave the polygon's convex hull — which is- // what lets `strokeToPath` keep reporting the polygon's bounds. Serializing- // rounds coordinates, which can move one half a step outside; the caller- // rounds the dirty rect outward to whole pixels, absorbing it.+ // what lets `strokeToPath` keep reporting the polygon's bounds.const polygon = strokeOutlinePolygon(arc(1000, Math.PI / 2), { last: true, size: 400, thinning: 0 });const bounds = polygonBounds(polygon);- const epsilon = PATH_ROUNDING_TOLERANCE;- for (const match of polygonToSmoothSvgPath(polygon).matchAll(/(-?[\d.]+) (-?[\d.]+)/g)) {- const x = Number(match[1]);- const y = Number(match[2]);- expect(x).toBeGreaterThanOrEqual(bounds.x - epsilon);- expect(x).toBeLessThanOrEqual(bounds.x + bounds.width + epsilon);- expect(y).toBeGreaterThanOrEqual(bounds.y - epsilon);- expect(y).toBeLessThanOrEqual(bounds.y + bounds.height + epsilon);+ const { path, points } = recordingPath();+ traceSmoothPolygon(path, polygon);+ expect(points.length).toBeGreaterThan(2);+ for (const point of points) {+ expect(point.x).toBeGreaterThanOrEqual(bounds.x);+ expect(point.x).toBeLessThanOrEqual(bounds.x + bounds.width);+ expect(point.y).toBeGreaterThanOrEqual(bounds.y);+ expect(point.y).toBeLessThanOrEqual(bounds.y + bounds.height);}});});describe('strokeToPath', () => {- it('builds the path via the injected factory and returns the polygon bounds', () => {- const seen: string[] = [];- const marker = { __brand: 'path' } as unknown as Path2D;- const createPath2D = (d?: string): Path2D => {- seen.push(d ?? '');- return marker;+ it('traces onto a path from the injected factory and returns the polygon bounds', () => {+ const recorder = recordingPath();+ let calls = 0;+ const createPath2D = (): Path2D => {+ calls++;+ return recorder.path;};const result = strokeToPath(horizontalLine(0.5), { size: 20, thinning: 0 }, createPath2D);- expect(result.path).toBe(marker);- expect(seen).toHaveLength(1);- expect(seen[0]).toMatch(/^M /);- // The smooth serialization — straight joins would show as facets at size.- expect(seen[0]).toContain(' Q ');- expect(seen[0]).toBe(polygonToSmoothSvgPath(result.polygon));+ expect(result.path).toBe(recorder.path);+ expect(calls).toBe(1);+ expect(recorder.commands[0]).toMatch(/^M /);+ // The smooth form — straight joins would show as facets at size.+ expect(recorder.commands.some((command) => command.startsWith('Q '))).toBe(true);expect(result.polygon.length).toBeGreaterThan(2);expect(result.bounds).toEqual(polygonBounds(result.polygon));});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.tsindex e8ddc23da8..2cb9fd520b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts@@ -5,8 +5,8 @@* The polygon math ({@link strokeOutlinePolygon}) is pure and DOM-free, so it is* fully unit-testable in node. `Path2D` does not exist in node, so building the* fillable path is split out into {@link strokeToPath}, which takes an injected- * `createPath2D` factory (the engine passes `(d) => new Path2D(d)`; tests pass a- * stub). This keeps the interesting geometry testable without a DOM.+ * `createPath2D` factory (the engine passes `() => new Path2D()`; tests pass a+ * recording stub). This keeps the interesting geometry testable without a DOM.** ## Why this isn't a bare `getStroke` call*@@ -37,8 +37,8 @@* the two library stages separately lets that gate keep its small absolute* value while the outline stage gets the real diameter.*- * Finally, the outline is serialized with quadratic curves- * ({@link polygonToSmoothSvgPath}) rather than the straight segments the lasso+ * Finally, the outline is traced as quadratic curves+ * ({@link traceSmoothPolygon}) rather than the straight segments the lasso* wants, so whatever facets remain read as curves.** Zero React, zero import-time side effects.@@ -84,11 +84,11 @@ const DEFAULT_THINNING = 0.5;* Target spacing (document units) between adjacent outline vertices, held* roughly constant across brush sizes by {@link outlineSmoothing}.*- * Chosen against the QUADRATIC serialization, not straight segments: at this- * spacing the rendered curve strays from the true offset curve by under 0.2- * document pixels even where the stroke turns on a 60px radius. Going finer- * only multiplies vertices — the outline is re-tessellated, re-serialized and- * re-filled on every pointer batch, so vertex count is squarely on the hot path.+ * Chosen against the QUADRATIC curve, not straight segments: at this spacing the+ * rendered curve strays from the true offset curve by under 0.2 document pixels+ * even where the stroke turns on a 60px radius. Going finer only multiplies+ * vertices — the outline is re-tessellated and re-filled on every pointer batch,+ * so vertex count is squarely on the hot path.*/export const TARGET_VERTEX_SPACING = 24;@@ -111,27 +111,6 @@ const SAMPLE_SPACING_RATIO = 0.02;*/export const START_GATE_SIZE = 24;-/**- * Coordinate precision (decimal places) used when serializing a stroke path.- *- * Layer caches are 1:1 with document pixels, so a hundredth of a unit is two- * orders of magnitude below anything the rasterizer can resolve — while full- * float precision costs ~25 characters per vertex in a string that is rebuilt- * and re-parsed into a `Path2D` on every pointer batch.- */-const PATH_PRECISION = 100;--/**- * The most a serialized coordinate can move from its exact value — half a- * precision step. A serialized path can therefore sit this far outside- * {@link polygonBounds}, which callers absorb by rounding the rect outward- * (`roundOut`) before using it as a dirty region.- */-export const PATH_ROUNDING_TOLERANCE = 0.5 / PATH_PRECISION;--/** Rounds a coordinate to {@link PATH_PRECISION} for path serialization. */-const round = (value: number): number => Math.round(value * PATH_PRECISION) / PATH_PRECISION;-/** Squared distance between two sample points. */const dist2 = (a: StrokeSamplePoint, b: StrokeSamplePoint): number => {const dx = a.x - b.x;@@ -238,37 +217,49 @@ export const polygonToSvgPath = (polygon: readonly Vec2[]): string => {};/**- * Serializes an outline polygon to a smooth closed SVG path, treating each+ * Traces an outline polygon onto `path` as a smooth closed curve, treating each* vertex as the control point of a quadratic segment running between the* midpoints of its two edges.** The curve stays inside the convex hull of the polygon, so- * {@link polygonBounds} of the polygon bounds the rendered shape to within- * {@link PATH_ROUNDING_TOLERANCE} — which is what the dirty-rect accounting in- * the stroke session relies on, and why it rounds that rect outward. Collinear- * runs are reproduced exactly, so this only differs from- * {@link polygonToSvgPath} where the outline actually turns.+ * {@link polygonBounds} of the polygon bounds the rendered shape — which is what+ * the dirty-rect accounting in the stroke session relies on. Collinear runs are+ * reproduced exactly, so this only differs from {@link polygonToSvgPath} where+ * the outline actually turns.+ *+ * Drawn with direct path calls rather than by building an SVG string for the+ * browser to re-parse. A stroke's outline is re-traced on every pointer batch+ * and runs to thousands of vertices, and at that size the round trip through a+ * string costs an order of magnitude more than the drawing does — 3.31ms versus+ * 0.18ms at 6000 samples — while describing exactly the same curve.** Polygons with fewer than three vertices have no meaningful curvature and fall- * back to the straight-segment form.+ * back to straight segments.*/-export const polygonToSmoothSvgPath = (polygon: readonly Vec2[]): string => {+export const traceSmoothPolygon = (path: Path2D, polygon: readonly Vec2[]): void => {const n = polygon.length;+ if (n === 0) {+ return;+ }if (n < 3) {- return polygonToSvgPath(polygon);+ const [first, ...rest] = polygon;+ path.moveTo(first!.x, first!.y);+ for (const point of rest) {+ path.lineTo(point.x, point.y);+ }+ path.closePath();+ return;}- const midX = (a: Vec2, b: Vec2): number => round((a.x + b.x) / 2);- const midY = (a: Vec2, b: Vec2): number => round((a.y + b.y) / 2);// Start on the seam midpoint so the ring closes as smoothly as it turns.const seamA = polygon[n - 1]!;const seamB = polygon[0]!;- let d = `M ${midX(seamA, seamB)} ${midY(seamA, seamB)}`;+ path.moveTo((seamA.x + seamB.x) / 2, (seamA.y + seamB.y) / 2);for (let i = 0; i < n; i++) {const control = polygon[i]!;const next = polygon[(i + 1) % n]!;- d += ` Q ${round(control.x)} ${round(control.y)} ${midX(control, next)} ${midY(control, next)}`;+ path.quadraticCurveTo(control.x, control.y, (control.x + next.x) / 2, (control.y + next.y) / 2);}- return `${d} Z`;+ path.closePath();};/** Axis-aligned bounds of an outline polygon; an empty polygon yields a zero-size rect. */@@ -303,10 +294,10 @@ export const polygonBounds = (polygon: readonly Vec2[]): Rect => {* path and the polygon's document-space {@link Rect} bounds so the caller can* derive the dirty region without recomputing the outline.*- * The path is the smooth ({@link polygonToSmoothSvgPath}) serialization — the- * outline is a coarse sampling of a curve, so joining its vertices with straight- * lines would show as facets at large brush sizes. The returned bounds still- * come from the polygon, which encloses the curve.+ * The path is the smooth ({@link traceSmoothPolygon}) form — the outline is a+ * coarse sampling of a curve, so joining its vertices with straight lines would+ * show as facets at large brush sizes. The returned bounds still come from the+ * polygon, which encloses the curve.*/export const strokeToPath = (points: readonly StrokeSamplePoint[],@@ -314,6 +305,7 @@ export const strokeToPath = (createPath2D: CreatePath2D): { path: Path2D; polygon: Vec2[]; bounds: Rect } => {const polygon = strokeOutlinePolygon(points, opts);- const path = createPath2D(polygonToSmoothSvgPath(polygon));+ const path = createPath2D();+ traceSmoothPolygon(path, polygon);return { bounds: polygonBounds(polygon), path, polygon };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex 3803a86c78..8c1f7697bd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -148,7 +148,10 @@ const createHarness = (createdIds.push(id);return id;},- createPath2D: (d) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },dispatch: (action) => dispatched.push(action),emitStrokeCommitted: (event) => {painted.push(event.layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.tsindex c041ee7c4e..093f1da4a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts@@ -46,7 +46,10 @@ const runStroke = (opts: { withMask: boolean }) => {const ctx = {backend,- createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },emitStrokeCommitted,invalidate: vi.fn(),layers,@@ -119,7 +122,10 @@ describe('strokeSession: bbox-clipped painting', () => {const entry: LayerCacheEntry = layers.getOrCreate('L', 100, 100);const ctx = {backend,- createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,@@ -200,7 +206,10 @@ describe('strokeSession: content-sized cache growth', () => {const notifyLayerPainted = vi.fn();const ctx = {backend,- createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },emitStrokeCommitted,invalidate: vi.fn(),layers,@@ -318,7 +327,10 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)entry.stale = false;const ctx = {backend,- createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,@@ -367,7 +379,10 @@ describe('incremental "before" snapshot', () => {layers.getOrCreate('L', 0, 0);const ctx = {backend,- createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 43a3a700c3..00cd3770a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -411,32 +411,48 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession);}- // 4. Render the whole accumulated stroke into the scratch surface at full- // alpha — one filled polygon, so no self-overlap darkening. The scratch is- // region-local: translate the (layer-local) path by -region.origin.+ // 4. Render the accumulated stroke into the scratch surface at full alpha.+ // The path is filled in ONE pass, so overlapping parts of a stroke union+ // rather than compounding — filling it in pieces across frames would let+ // the antialiased edges of successive batches blend into each other and+ // leave seams. The scratch is region-local: translate the (layer-local)+ // path by -region.origin.//- // This stays whole-region rather than incremental: filling the complete- // outline every frame is what guarantees the scratch holds ONE flat-alpha- // silhouette. Accumulating it in pieces would let the antialiased edges of- // successive batches blend into each other and leave seams inside the- // stroke. It is also the cheap half of the frame — the readback was not.+ // Only the changed band is refreshed. The scratch persists between+ // frames, and outside that band the silhouette is by definition the same+ // one already sitting there — so re-clearing and re-filling the whole+ // region was redrawing pixels to their existing values. A region change+ // resizes the scratch, which clears it, so that case still refills whole.+ const scratchCleared = !previousRect || !sameRect(previousRect, region);+ const refresh = scratchCleared ? region : changed;const scratch = ensureStroke(region.width, region.height);const strokeCtx = scratch.ctx;strokeCtx.setTransform(1, 0, 0, 1, -region.x, -region.y);- strokeCtx.clearRect(region.x, region.y, region.width, region.height);+ strokeCtx.save();+ strokeCtx.beginPath();+ strokeCtx.rect(refresh.x, refresh.y, refresh.width, refresh.height);+ strokeCtx.clip();+ strokeCtx.clearRect(refresh.x, refresh.y, refresh.width, refresh.height);strokeCtx.globalCompositeOperation = 'source-over';strokeCtx.globalAlpha = 1;strokeCtx.fillStyle = color;strokeCtx.fill(path);+ strokeCtx.restore();// 4b. Selection clip: keep only the stroke pixels inside the selection mask.// The mask is a placed surface; draw it at (maskOrigin - regionOrigin) in- // the scratch's region-local space.+ // the scratch's region-local space. Confined to the same band — masking+ // already-masked pixels a second time would multiply their alpha again.if (clipMask) {strokeCtx.setTransform(1, 0, 0, 1, 0, 0);+ strokeCtx.save();+ strokeCtx.beginPath();+ strokeCtx.rect(refresh.x - region.x, refresh.y - region.y, refresh.width, refresh.height);+ strokeCtx.clip();strokeCtx.globalCompositeOperation = 'destination-in';strokeCtx.globalAlpha = 1;strokeCtx.drawImage(clipMask.surface.canvas, clipMask.rect.x - region.x, clipMask.rect.y - region.y);+ strokeCtx.restore();}// 5. Composite the scratch stroke into the cache at the stroke opacity, using