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
fix(canvas): paint through the layer transform
Josh Corbett195a80209bc1
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 8ed9352867..a06d49632e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -22,6 +22,7 @@ import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/docuimport { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { isLeafPaintable, isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';import { isMaskLayer } from '@workbench/canvas-engine/document/sources';+import { fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';import type { StrokeCommittedEvent, Tool, ToolContext } from './tool';@@ -75,6 +76,13 @@ interface PaintTarget {* silently attenuate the mask (a ~50% denoise, invisible in the tinted overlay).*/forceOpaque?: boolean;+ /**+ * The target layer's committed transform. The session paints layer-local+ * pixels through its inverse so the stroke lands under the cursor even on a+ * moved, scaled or rotated layer. Absent ⇒ identity (a freshly auto-created+ * layer).+ */+ transform?: CanvasLayerContract['transform'];}/** Resolves (or auto-creates) the paint target for a gesture, or `null` to no-op. */@@ -108,6 +116,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetcancel: () => undefined,commit: (event) => ctx.emitStrokeCommitted(event),layerId: selected.id,+ transform: selected.transform,transparencyLocked: selected.isTransparencyLocked === true,};}@@ -127,6 +136,9 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetcancel: transaction.cancel,commit: transaction.commitStroke,layerId: transaction.layerId,+ // No transform on purpose: materialization BAKES the layer's placement+ // into document-space pixels and resets the layer to identity, so the+ // session's document coordinates already are the cache's coordinates.};}@@ -151,6 +163,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetcommit: (event) => ctx.emitStrokeCommitted(event),forceOpaque: true,layerId: selected.id,+ transform: selected.transform,};}@@ -163,6 +176,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetcancel: transaction.cancel,commit: transaction.commitStroke,layerId: transaction.layerId,+ // No transform on purpose: see the materialized-eraser branch above.};}@@ -273,6 +287,18 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {return;}const composite = resolvedTarget.transparencyLocked && spec.id === 'brush' ? 'source-atop' : spec.composite;+ const layerTransform = resolvedTarget.transform+ ? fromTRS(+ { x: resolvedTarget.transform.x, y: resolvedTarget.transform.y },+ resolvedTarget.transform.rotation,+ resolvedTarget.transform.scaleX,+ resolvedTarget.transform.scaleY+ )+ : null;+ if (layerTransform && !invert(layerTransform)) {+ // A zero-scale layer has no paintable geometry to invert into.+ return;+ }target = resolvedTarget;try {session = createStrokeSession({@@ -286,6 +312,7 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {createdLayer: target.createdLayer ?? null,ctx,layerId: target.layerId,+ layerTransform,// Mask strokes are forced opaque (an alpha stencil is all-or-nothing); a// brush-opacity mask stroke would silently attenuate the denoise strength.opacity: target.forceOpaque ? 1 : spec.opacity(ctx),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 205210c928..5c9077b607 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@@ -3,6 +3,7 @@ import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engimport type { ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';+import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createStrokeSession } from '@workbench/canvas-engine/tools/strokeSession';@@ -550,3 +551,52 @@ describe('strokeSession: pressure-dependent opacity', () => {expect(scratch.callLog.filter((e) => e.op === 'fill')).toHaveLength(2);});});++describe('layer transforms', () => {+ const sessionOn = (layerTransform: ReturnType<typeof fromTRS> | null, point: { x: number; y: number }) => {+ const { backend } = createCapturingBackend();+ const layers = createLayerCacheStore(backend);+ const ctx = {+ backend,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },+ emitStrokeCommitted: vi.fn(),+ invalidate: vi.fn(),+ layers,+ notifyLayerPainted: vi.fn(),+ } as unknown as ToolContext;+ const session = createStrokeSession({+ color: '#ff0000',+ composite: 'source-over',+ ctx,+ layerId: 'L',+ layerTransform,+ opacity: 1,+ pressureOpacity: false,+ size: 8,+ thinning: 0,+ tool: 'brush',+ });+ session.addPoints([pointer(point.x, point.y)]);+ return session.commit();+ };++ it('maps document points through the layer inverse, so the stroke lands under the cursor', () => {+ // Translated layer: doc (1010, 10) is layer-local (10, 10).+ const translated = sessionOn(fromTRS({ x: 1000, y: 0 }, 0, 1, 1), { x: 1010, y: 10 });+ expect(translated?.dirtyRect.x).toBe(0);+ expect(translated?.dirtyRect.y).toBe(0);++ // Scaled layer: doc (300, 300) on a 2x layer is layer-local (150, 150).+ const scaled = sessionOn(fromTRS({ x: 0, y: 0 }, 0, 2, 2), { x: 300, y: 300 });+ expect(scaled?.dirtyRect.x).toBe(128);+ expect(scaled?.dirtyRect.y).toBe(128);++ // Identity stays byte-for-byte where it always painted.+ const plain = sessionOn(null, { x: 300, y: 300 });+ expect(plain?.dirtyRect.x).toBe(256);+ expect(plain?.dirtyRect.y).toBe(256);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 991c422ea0..4534a62ed2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -41,10 +41,11 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { Mat2d, PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';import { strokeToPath, type StrokeSamplePoint } from '@workbench/canvas-engine/freehand';-import { expand, intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';+import { applyToPoint, getScale, identity, invert, multiply } from '@workbench/canvas-engine/math/mat2d';+import { expand, intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { getPressureBands } from '@workbench/canvas-engine/pressureBands';import type { StrokeCommittedEvent, ToolContext } from './tool';@@ -78,11 +79,12 @@ export interface StrokeSessionConfig {createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor } | null;/*** The bounded selection mask to clip the stroke to (resolved once by the tool- * on pointer-down when a selection exists), as a placed surface in document- * (= layer-local) space. When set, the paint region is intersected with the- * mask bounds and the scratch stroke is masked (`destination-in`) before- * compositing, so pixels outside the selection are never written and the cache- * only grows within the selection. Absent ⇒ the no-selection hot path.+ * on pointer-down when a selection exists), as a placed surface in DOCUMENT+ * space. When set, the paint region is intersected with the mask bounds+ * (mapped through the layer inverse) and the scratch stroke is masked+ * (`destination-in`) before compositing, so pixels outside the selection are+ * never written and the cache only grows within the selection. Absent ⇒ the+ * no-selection hot path.*/clipMask?: PlacedSurface | null;/**@@ -97,6 +99,15 @@ export interface StrokeSessionConfig {* Absent/`null` ⇒ unclipped (the default, and the hot path).*/clipRect?: Rect | null;+ /**+ * The target layer's local→document transform. Inputs and clips arrive in+ * DOCUMENT space while the session runs in LAYER-LOCAL space (the cache, the+ * damage it reports and the history patches all are), so every input crosses+ * this boundary through the inverse — the compositor then carries the painted+ * pixels back to the screen through the layer's own matrix. Absent ⇒+ * identity, the untransformed-layer hot path.+ */+ layerTransform?: Mat2d | null;}/** The imperative handle a tool drives across a gesture. */@@ -109,12 +120,6 @@ export interface StrokeSession {cancel(): void;}-const toSample = (input: PointerInput): StrokeSamplePoint => ({- pressure: input.pressure,- x: input.documentPoint.x,- y: input.documentPoint.y,-});-/*** Cache/scratch growth is snapped OUTWARD to this pixel grid. Without it, an* outward brush drag extends the paint region by a few pixels on every batch, so@@ -166,8 +171,9 @@ const padToChunk = (r: Rect, chunk: number): Rect => {type SurfaceContext = RasterSurface['ctx'];/**- * Extra slack (document units) around the changed geometry, covering the- * antialiased edge and the outward rounding of the bounds themselves.+ * Extra slack (layer-local units, the space the stroke rasterizes in) around+ * the changed geometry, covering the antialiased edge and the outward rounding+ * of the bounds themselves.*/const CHANGE_MARGIN = 2;@@ -314,6 +320,24 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession} = config;const layers: LayerCacheStore = ctx.layers;+ // The document→layer-local boundary. The owning tool refuses degenerate+ // (zero-scale) transforms before opening a session; the identity fallback+ // keeps this total for direct callers.+ const toLocal = (config.layerTransform && invert(config.layerTransform)) ?? identity();+ // Brush geometry is authored in document units; in layer space it scales by+ // the inverse (exact under rotation and uniform scale, the geometric mean+ // under non-uniform — the stroke then stretches with the layer's own pixels).+ const localSize = size * getScale(toLocal);+ const clipMaskLocalRect = clipMask ? roundOut(transformBounds(toLocal, clipMask.rect)) : null;+ const clipRectLocal = clipRect ? roundOut(transformBounds(toLocal, clipRect)) : null;+ // Axis-aligned layers get the rect clip for free from the region clamp; a+ // rotated/sheared layer's clamp is only the AABB, so the exact rect must also+ // be cut out of the scratch like the selection mask is.+ const clipRectNeedsMask = !!clipRect && (toLocal.b !== 0 || toLocal.c !== 0);+ const toSample = (input: PointerInput): StrokeSamplePoint => {+ const local = applyToPoint(toLocal, input.documentPoint);+ return { pressure: input.pressure, x: local.x, y: local.y };+ };// A per-frame scratch surface for the filled stroke, sized to the paint region.let stroke: RasterSurface | null = null;@@ -324,7 +348,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionlet beforeImageData: ImageData | null = null;let accumRect: Rect | null = null;let previousPolygon: Vec2[] | null = null;- const chunk = growthChunk(size);+ const chunk = growthChunk(localSize);/** Ensures the scratch surface is at least `w`×`h`. */const ensureStroke = (w: number, h: number): RasterSurface => {@@ -340,15 +364,15 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionif (points.length === 0) {return;}- const { bounds, path, polygon } = strokeToPath(points, { last, size, thinning }, ctx.createPath2D);+ const { bounds, path, polygon } = strokeToPath(points, { last, size: localSize, thinning }, ctx.createPath2D);let dirty: Rect | null = roundOut(bounds);// Selection clip: only the region inside the selection can ever change, so// bound the dirty/growth region to the mask extent (and skip empty results).- if (clipMask) {- dirty = intersect(dirty, clipMask.rect);+ if (clipMaskLocalRect) {+ dirty = intersect(dirty, clipMaskLocalRect);}- if (dirty && clipRect) {- dirty = intersect(dirty, clipRect);+ if (dirty && clipRectLocal) {+ dirty = intersect(dirty, clipRectLocal);}if (!dirty || isEmpty(dirty)) {return;@@ -363,17 +387,17 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// consumer stays coherent. When a selection clips the stroke, clamp the padded// region back to the mask so growth still never escapes the selection.let region = padToChunk(accumRect ? roundOut(union(accumRect, dirty)) : dirty, chunk);- if (clipMask) {- const clamped = intersect(region, clipMask.rect);+ if (clipMaskLocalRect) {+ const clamped = intersect(region, clipMaskLocalRect);if (clamped) {region = clamped;}}- if (clipRect) {+ if (clipRectLocal) {// Clamping the region IS the bbox clip: the scratch is sized to the region// and the path is drawn translated into it, so anything beyond the rect// lands outside the surface and never reaches the cache.- const clamped = intersect(region, clipRect);+ const clamped = intersect(region, clipRectLocal);if (clamped) {region = clamped;}@@ -481,7 +505,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// full-alpha fill below exists to prevent. Replacing means the later (newer) band wins// in the overlap, which is the pressure the user is applying now.for (const band of getPressureBands(points)) {- const bandPath = strokeToPath(band.points, { last, size, thinning }, ctx.createPath2D).path;+ const bandPath = strokeToPath(band.points, { last, size: localSize, thinning }, ctx.createPath2D).path;strokeCtx.globalCompositeOperation = 'destination-out';strokeCtx.globalAlpha = 1;@@ -510,7 +534,30 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionstrokeCtx.clip();strokeCtx.globalCompositeOperation = 'destination-in';strokeCtx.globalAlpha = 1;- strokeCtx.drawImage(clipMask.surface.canvas, clipMask.rect.x - region.x, clipMask.rect.y - region.y);+ // The mask is document-space; drawing it through the layer inverse keeps+ // its exact shape clipping even on a rotated or scaled layer.+ const maskMatrix = multiply({ a: 1, b: 0, c: 0, d: 1, e: -region.x, f: -region.y }, toLocal);+ strokeCtx.setTransform(maskMatrix.a, maskMatrix.b, maskMatrix.c, maskMatrix.d, maskMatrix.e, maskMatrix.f);+ strokeCtx.drawImage(clipMask.surface.canvas, clipMask.rect.x, clipMask.rect.y);+ strokeCtx.restore();+ }++ // 4c. Bbox clip on a rotated/sheared layer: the region clamp above only+ // bounds the AABB, so keep exactly the pixels inside the document-space+ // rect, drawn through the same inverse the mask uses.+ if (clipRect && clipRectNeedsMask) {+ 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;+ const rectMatrix = multiply({ a: 1, b: 0, c: 0, d: 1, e: -region.x, f: -region.y }, toLocal);+ strokeCtx.setTransform(rectMatrix.a, rectMatrix.b, rectMatrix.c, rectMatrix.d, rectMatrix.e, rectMatrix.f);+ strokeCtx.beginPath();+ strokeCtx.rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);+ strokeCtx.fill();strokeCtx.restore();}