Skip to content

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.

fix(canvas): share capture sampling and explain memory limits

Josh Corbettc3f5685ba83c
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 421359fdb8..a1d2c25487 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -99,7 +99,7 @@ Snapshots create a deliberate transaction boundary:
2. After successful invocation detachment, ordinary editing may continue. Composite, upload, graph compilation, queue submission read only frozen contract and detached surfaces.
3. Wholesale canvas replacement stays a separate session, identified by `documentRevision`; completed results from an older session are dropped.
-Canvas invocation first crosses paint-flush barrier, then captures post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. It passes the generation bbox as the capture's optional document-space `region`. For unrotated layers at native resolution (signed unit scales, including reflections), capture copies only intersecting source pixels plus one pixel of sampling margin, rounded outward on the source's pixel grid. Translation and paint offsets remain layer-local. The snapshot keeps each layer's actual whole-source `sourceRect` for content bounds and mode detection; its `rect` places the detached pixels. Disjoint sources keep a transparent one-pixel surface and an empty detached rect. Reservations estimate these bounded copies and top up actual extents before allocation, so a small frame on a resident large map does not require a second map-sized surface.
+Canvas invocation first crosses paint-flush barrier, then captures post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. It passes the generation bbox as the capture's optional document-space `region`. For unrotated layers at native resolution (signed unit scales, including reflections), capture copies only intersecting source pixels plus one pixel of sampling margin, rounded outward on the source's pixel grid. `render/rasterComposite.ts` owns the capture extent through `getRasterSnapshotCaptureRect`: the same source-region policy drives actual adjustment drawing and scratch reservations, and the same whole-source requirement drives group frames and capture's indexed ancestor check. Capture owns leases and allocations; it does not reproduce inverse-transform, sampling-margin or spatial-context rules. The renderer first rounds the sampled region in layer-local coordinates, then capture's owner boundary rounds that region outward on the source pixel grid, so fractional paint origins cannot clip adjustment samples. Translation and paint offsets remain layer-local. The snapshot keeps each layer's actual whole-source `sourceRect` for content bounds and mode detection; its `rect` places the detached pixels. Disjoint sources keep a transparent one-pixel surface and an empty detached rect. Reservations estimate these bounded copies and top up actual extents before allocation, so a small frame on a resident large map does not require a second map-sized surface.
Rotation or rescaling retains whole-source capture: changing a Canvas2D source's origin can change transformed sampling, so these paths preserve the original source grid exactly. Spatial layer stacks and all members of a spatial raster group also retain whole sources because their adjustments depend on that context. Callers omitting `region` (including PSD) retain whole-layer capture. This bounds detached generation inputs, not initial source rasterization: an uncached large source, a transformed layer, or spatial adjustment work can still exceed the unchanged 512 MiB budget. Composite dedupe writes stage in transaction-local maps. They publish to persistent per-engine dedupe cache only after all frozen compositing, uploads, compilation, and queue dispatch complete; stale or failed captures leave no persistent dedupe entries.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts
index fa2c15d946..7b4e087c9c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts
@@ -249,6 +249,19 @@ describe('region snapshots through real Canvas2D compositing', () => {
it('keeps members of a spatial group on their full sources', async () => {
await compare(scene(identity, noise, spatial), true);
});
+ it.each([true, false])(
+ 'shares nested group source context with enabled spatial adjustments: %s',
+ async (isEnabled) => {
+ const s = scene(identity, noise);
+ const outerAdjustments = spatial.map((entry) => ({ ...entry, isEnabled }));
+ s.canvas.document.stacks = stacksFrom([
+ groupContract('outer', [groupContract('inner', [s.layer], { adjustments: color })], {
+ adjustments: outerAdjustments,
+ }),
+ ]);
+ await compare(s, isEnabled);
+ }
+ );
});
it.each([origin, { x: -19.4, y: -11.6 }])(
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index f0c9ed4e18..015844d8db 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -12,33 +12,12 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/documentModel';
-import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';
-import { fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
-import { expand, intersect, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
-import { hasSpatialAdjustments } from '@workbench/canvas-engine/render/adjustments';
+import { getRasterSnapshotCaptureRect } from '@workbench/canvas-engine/render/rasterComposite';
const BYTES_PER_PIXEL = 4;
-/** Select whole source pixels, preserving their grid even when the layer-local content origin is fractional. */
-const captureRect = (content: Rect, region: Rect | undefined): Rect => {
- if (!region) {
- return { ...content };
- }
- // Adjustments sample an outward-rounded layer-local region; cover it before snapping to the source pixel grid.
- const local = roundOut(expand(region, 1));
- const sampled = intersect(roundOut({ ...local, x: local.x - content.x, y: local.y - content.y }), {
- x: 0,
- y: 0,
- width: content.width,
- height: content.height,
- });
- return sampled
- ? { ...sampled, x: sampled.x + content.x, y: sampled.y + content.y }
- : { x: content.x, y: content.y, width: 0, height: 0 };
-};
-
// A disjoint layer keeps a transparent pixel so downstream Canvas2D drawing remains valid.
const rectBytes = (rect: Rect): number => Math.max(1, rect.width) * Math.max(1, rect.height) * BYTES_PER_PIXEL;
@@ -121,9 +100,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const document = documentSnapshot.canvas.document;
const uniqueLayerIds = [...new Set(layerIds)];
- const regions = new Map<string, Rect>();
const estimatedBytes = new Map<string, number>();
- const index = getDocumentIndex(document);
let requestedBytes = 0;
for (const layerId of uniqueLayerIds) {
const layer = lookupDocumentLayer(document, layerId);
@@ -131,27 +108,9 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
if (!layer || !source || !isSupportedExportSource(source)) {
return { status: 'not-ready' };
}
- if (options?.region) {
- // Spatial stacks need the owner's whole source, including every member of a spatial group.
- const spatial =
- layer.type === 'raster' &&
- (hasSpatialAdjustments(layer.adjustments) ||
- index.byId.get(layerId)!.path.some((id) => {
- const ancestor = index.byId.get(id)!.node;
- return ancestor.type === 'group' && hasSpatialAdjustments(ancestor.adjustments);
- }));
- const t = layer.transform;
- // Rotating or scaling a cropped Canvas2D source can change sampling; retain the original pixel grid.
- const unitScale = Math.abs(t.scaleX) === 1 && Math.abs(t.scaleY) === 1;
- const inverse = !spatial && unitScale && t.rotation === 0 && invert(fromTRS(t, t.rotation, t.scaleX, t.scaleY));
- if (inverse) {
- regions.set(layerId, transformBounds(inverse, options.region));
- }
- }
const content = getSourceContentRect(layer, document);
- const bytes = regions.has(layerId)
- ? rectBytes(captureRect(content, regions.get(layerId)))
- : content.width * content.height * BYTES_PER_PIXEL;
+ const rect = getRasterSnapshotCaptureRect(document, layer, options?.region, content);
+ const bytes = options?.region ? rectBytes(rect) : content.width * content.height * BYTES_PER_PIXEL;
estimatedBytes.set(layerId, bytes);
requestedBytes += bytes;
}
@@ -211,8 +170,16 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
}
capturedGuards.push(live.guard);
try {
- const region = regions.get(layerId);
- const rect = captureRect({ ...live.rect, width: live.surface.width, height: live.surface.height }, region);
+ const rect = getRasterSnapshotCaptureRect(
+ document,
+ lookupDocumentLayer(document, layerId)!,
+ options?.region,
+ {
+ ...live.rect,
+ width: live.surface.width,
+ height: live.surface.height,
+ }
+ );
const actualBytes = rectBytes(rect);
// The up-front reservation was an estimate from the source; a surface
// that rasterized larger has to be paid for before it is detached.
@@ -231,7 +198,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
detached.ctx.drawImage(live.surface.canvas, live.rect.x - rect.x, live.rect.y - rect.y);
}
layerSurfaces.set(layerId, {
- rect: region ? rect : { ...live.rect },
+ rect: options?.region ? rect : { ...live.rect },
...(options?.region ? { sourceRect: { ...live.rect } } : {}),
surface: detached,
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
index 04ec02db4b..4a1516e46c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -13,6 +13,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';
import { fromTRS, invert, multiply } from '@workbench/canvas-engine/math/mat2d';
import { expand, intersect, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
@@ -308,7 +309,7 @@ const setTransform = (ctx: Ctx, m: Mat2d): void => {
};
/** The layer's local→document transform matrix. */
-const layerMatrix = (ref: CompositeLayerRef): Mat2d =>
+const layerMatrix = (ref: Pick<CompositeLayerRef, 'transform'>): Mat2d =>
fromTRS(
{ x: ref.transform.x, y: ref.transform.y },
ref.transform.rotation,
@@ -316,13 +317,65 @@ const layerMatrix = (ref: CompositeLayerRef): Mat2d =>
ref.transform.scaleY
);
-/** The layer-local region of `content` an output over `frame` samples, with one pixel of resampling margin. */
-const sampledLayerRegion = (ref: CompositeLayerRef, frame: Rect, content: Rect): Rect | null => {
+/** Source-context policy shared by layer sampling, isolated group frames, and immutable capture. */
+const requiresWholeSource = (adjustments: CanvasAdjustmentsContract | undefined): boolean =>
+ hasSpatialAdjustments(adjustments);
+
+/** Whole source for context-dependent stacks; otherwise the output's layer-local samples plus resampling margin. */
+const layerSourceRegion = (
+ ref: Pick<CompositeLayerRef, 'transform' | 'adjustments'>,
+ frame: Rect,
+ content: Rect
+): Rect | null => {
+ if (requiresWholeSource(ref.adjustments)) {
+ return content;
+ }
const inverse = invert(multiply(bboxView(frame), layerMatrix(ref)));
const output: Rect = { height: Math.max(0, frame.height), width: Math.max(0, frame.width), x: 0, y: 0 };
return inverse ? intersect(roundOut(expand(transformBounds(inverse, output), 1)), content) : content;
};
+/**
+ * Detached source pixels sufficient for this renderer, including enclosing groups' source context. Capture aligns
+ * the renderer's already-rounded sample region to the source pixel grid so fractional paint origins never clip it.
+ * Rotation/rescaling keeps the full source: changing Canvas2D's source origin can change transformed sampling.
+ */
+export const getRasterSnapshotCaptureRect = (
+ document: CanvasDocumentContractV3,
+ layer: CanvasLayerContract,
+ frame: Rect | undefined,
+ content: Rect
+): Rect => {
+ const t = layer.transform;
+ if (!frame || t.rotation !== 0 || Math.abs(t.scaleX) !== 1 || Math.abs(t.scaleY) !== 1) {
+ return { ...content };
+ }
+ if (layer.type === 'raster') {
+ const index = getDocumentIndex(document);
+ if (
+ index.byId.get(layer.id)!.path.some((id) => {
+ const ancestor = index.byId.get(id)!.node;
+ return ancestor.type === 'group' && requiresWholeSource(ancestor.adjustments);
+ })
+ ) {
+ return { ...content };
+ }
+ }
+ const sampled = layerSourceRegion(layer, frame, content);
+ if (!sampled) {
+ return { x: content.x, y: content.y, width: 0, height: 0 };
+ }
+ const pixels = intersect(roundOut({ ...sampled, x: sampled.x - content.x, y: sampled.y - content.y }), {
+ x: 0,
+ y: 0,
+ width: content.width,
+ height: content.height,
+ });
+ return pixels
+ ? { ...pixels, x: pixels.x + content.x, y: pixels.y + content.y }
+ : { x: content.x, y: content.y, width: 0, height: 0 };
+};
+
const areaOf = (rect: Rect | null): number => (rect ? Math.max(0, rect.width) * Math.max(0, rect.height) : 0);
/**
@@ -331,10 +384,10 @@ const areaOf = (rect: Rect | null): number => (rect ? Math.max(0, rect.width) *
* output when the layer is downscaled, and a spatial stack adjusts all of `content`.
*/
const layerScratchPixels = (ref: CompositeLayerRef, frame: Rect, content: Rect): number => {
- if (hasSpatialAdjustments(ref.adjustments)) {
- return areaOf(content);
+ if (requiresWholeSource(ref.adjustments)) {
+ return areaOf(layerSourceRegion(ref, frame, content));
}
- const sampled = isPositionDependentAdjustments(ref.adjustments) ? sampledLayerRegion(ref, frame, content) : null;
+ const sampled = isPositionDependentAdjustments(ref.adjustments) ? layerSourceRegion(ref, frame, content) : null;
return Math.max(areaOf(frame), areaOf(sampled));
};
@@ -374,7 +427,7 @@ export const compositeScratchPixels = (entry: CompositeEntry): number => {
for (; index < scope.start; index += 1) {
pixels += leafScratch(index, frame);
}
- const inner = hasSpatialAdjustments(scope.adjustments) ? plannedScopeExtent(entry, scope) : frame;
+ const inner = requiresWholeSource(scope.adjustments) ? plannedScopeExtent(entry, scope) : frame;
if (inner) {
pixels += areaOf(inner) + scratchOf(scope.start, scope.end, scope.children, inner);
}
@@ -494,24 +547,20 @@ export const renderRasterComposite = async (
// adjusts after resampling, keeping the work bounded by the output. Noise must stay layer-local so
// resampling averages it exactly as the display does, so its work is the sampled region.
const shared = deps.adjustedSurface?.(ref.id, source, ref.adjustments) ?? null;
+ const sampled = shared ? null : layerSourceRegion(ref, frame, origin);
if (shared) {
source = shared;
- } else if (hasSpatialAdjustments(ref.adjustments)) {
- if (areaOf(origin) === 0) {
- return;
- }
- extra = reserveExcess(areaOf(origin), layerScratchPixels(ref, frame, plannedContent(ref)));
- const local = deps.backend.createSurface(origin.width, origin.height);
+ } else if (!sampled || areaOf(sampled) === 0) {
+ return;
+ } else if (requiresWholeSource(ref.adjustments)) {
+ extra = reserveExcess(areaOf(sampled), layerScratchPixels(ref, frame, plannedContent(ref)));
+ const local = deps.backend.createSurface(sampled.width, sampled.height);
setTransform(local.ctx, IDENTITY);
local.ctx.drawImage(source.canvas, 0, 0);
- const pixels = readImageData(local, fullRectOf(origin));
- writeImageData(local, await evaluate(pixels, ref.adjustments, origin, ref.id), 0, 0);
+ const pixels = readImageData(local, fullRectOf(sampled));
+ writeImageData(local, await evaluate(pixels, ref.adjustments, sampled, ref.id), 0, 0);
source = local;
} else {
- const sampled = sampledLayerRegion(ref, frame, origin);
- if (!sampled) {
- return;
- }
if (areaOf(sampled) > areaOf(frame) && !isPositionDependentAdjustments(ref.adjustments)) {
drawAdjustedAtOutput(ctx, frame, ref, source, origin, placed, ref.adjustments);
return;
@@ -635,7 +684,7 @@ export const renderRasterComposite = async (
for (let i = end - 1; i >= start;) {
const scope = scopeIndex >= 0 ? scopes[scopeIndex]! : null;
if (scope && i >= scope.start && i < scope.end) {
- if (hasSpatialAdjustments(scope.adjustments)) {
+ if (requiresWholeSource(scope.adjustments)) {
await drawSpatialScope(ctx, frame, scope, leased);
} else {
const output = fullRectOf(frame);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index 89b4ad2ee2..6374f6be1c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -712,6 +712,10 @@ describe('runCanvasInvocation', () => {
'“Sky” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again.',
],
[{ status: 'not-ready' } as const, 'Some layers are still loading. Wait a moment, then invoke again.'],
+ [
+ { status: 'over-budget' } as const,
+ 'Generation exceeds the browser’s canvas-memory limit. Try again after layers finish loading. If it still fails, crop or resize large source images, or disable unnecessary layers. A smaller generation frame alone may not help.',
+ ],
])('explains a %o capture and dispatches nothing', async (result, message) => {
const harness = makeHarness();
harness.deps.composeForGeneration = () => Promise.resolve(result);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 282f50fa5e..887a71c4c7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -374,7 +374,9 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
? `“${composed.layerName}” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again.`
: composed.status === 'not-ready'
? 'Some layers are still loading. Wait a moment, then invoke again.'
- : `The canvas could not be captured for generation (${composed.status}).`
+ : composed.status === 'over-budget'
+ ? 'Generation exceeds the browser’s canvas-memory limit. Try again after layers finish loading. If it still fails, crop or resize large source images, or disable unnecessary layers. A smaller generation frame alone may not help.'
+ : `The canvas could not be captured for generation (${composed.status}).`
);
return;
}