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.

perf(webv2): composite only the region a frame changed

joshistoastd128245ca989
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 60e92bbb63..07bfe6da62 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1168,7 +1168,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// the ants through the matching document-space transform.
const floatRender = floatingSelectionFrame(floatingSelection.get(), doc);
if (flags.all || flags.view || flags.layers.size > 0) {
- compositeFrame.draw(screen, doc, view, floatRender, samPreview);
+ compositeFrame.draw(screen, doc, view, floatRender, samPreview, flags.damage);
}
// The overlay is cheap (a handful of screen-space strokes, independent of
@@ -1764,7 +1764,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// a flash/strobe. A same-task repaint lands before the browser paints, so the
// canvas never shows empty. `all: true` forces the composite through the T22
// dirty gate; `render` no-ops when detached (no surfaces).
- render({ all: true, layers: new Set<string>(), overlay: true, view: true });
+ render({ all: true, damage: null, layers: new Set<string>(), overlay: true, view: true });
};
const fitToView = (): void => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
index 31b489dbef..0fd13c91dd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
@@ -9,7 +9,7 @@ import type { EngineStores } from '@workbench/canvas-engine/engineStores';
import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';
import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
-import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
+import type { LayerDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
@@ -46,7 +46,14 @@ export interface CompositeFrame {
doc: CanvasDocumentContractV2,
view: Mat2d,
floatFrame: FloatingSelectionFrame | null,
- samPreview: SamPreviewState | null
+ samPreview: SamPreviewState | null,
+ /**
+ * The regions this frame must repaint, in their layers' local spaces, or
+ * `null` to repaint everything. Supplied by the render scheduler, which only
+ * produces a non-null value when every invalidation in the frame named the
+ * region it changed.
+ */
+ damage?: LayerDamage[] | null
): void;
}
@@ -144,7 +151,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
};
return {
- draw: (screen, doc, view, floatFrame, samPreview) => {
+ draw: (screen, doc, view, floatFrame, samPreview, damage) => {
const stagedPreview = previews.getStaged();
const stagedPlacement = stagedPreview?.placement;
const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;
@@ -170,6 +177,9 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
? { ...doc, layers: doc.layers.filter((layer) => isolatedIds.has(layer.id)) }
: doc;
compositeDocument(screen, compositeDoc, layerCache, view, {
+ // Confines the clear, the checkerboard and every layer blit to the pixels
+ // that actually changed; `null` repaints the whole viewport.
+ damage: isolatedGuard ? null : damage,
// Memoized adjusted surfaces for raster layers with brightness/contrast/
// saturation/curves (not recomputed per frame — see adjustedSurfaceCache).
adjustedSurface: deps.getAdjustedSurface,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index 81a3c52bc7..9ec8b68246 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -19,11 +19,11 @@ import type {
CanvasLayerContract,
} from '@workbench/canvas-engine/contracts';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
-import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
+import type { LayerDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
import { isLayerHidden, LAYER_GROUP_COUNT, layerGroupRank } from '@workbench/canvas-engine/document/sources';
import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';
-import { intersect, transformBounds } from '@workbench/canvas-engine/math/rect';
+import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import type { DerivedSurfaceCache } from './derivedSurfaceCache';
import type { LayerCacheEntry, LayerCacheStore } from './layerCache';
@@ -106,6 +106,17 @@ export interface CompositeOptions {
* {@link shouldSmoothAtZoom} so zoomed-in frames composite crisp and cheap.
*/
imageSmoothing?: boolean;
+ /**
+ * The regions this composite must repaint, each in its layer's local space.
+ * When present, the clear, the checkerboard and every layer blit are clipped
+ * to their union on screen and the rest of the target keeps the previous
+ * frame — which is the difference between resampling a whole doc-sized layer
+ * to screen scale and resampling a few hundred pixels of it.
+ *
+ * `undefined` or `null` repaints the whole target, which is what every caller
+ * that cannot name its damage gets.
+ */
+ damage?: LayerDamage[] | null;
/**
* Transient per-layer transform overrides (a live move/transform preview): a
* layer with an entry here is drawn through the overridden transform instead of
@@ -247,7 +258,7 @@ export const createCheckerboardTile = (
* the pattern to the stage — so it stays visually stable and never swims or
* scales while panning/zooming.
*/
-const drawBackground = (ctx: Ctx, target: RasterSurface, tile: RasterSurface | null): void => {
+const drawBackground = (ctx: Ctx, tile: RasterSurface | null, bounds: Rect): void => {
if (!tile) {
// Checkerboard disabled: leave the cleared surface showing `bg.inset`.
return;
@@ -257,7 +268,63 @@ const drawBackground = (ctx: Ctx, target: RasterSurface, tile: RasterSurface | n
return;
}
ctx.fillStyle = pattern;
- ctx.fillRect(0, 0, target.width, target.height);
+ ctx.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
+};
+
+/**
+ * Resolves {@link CompositeOptions.damage} to the screen-space rect a frame may
+ * confine itself to, or `null` for "repaint everything".
+ *
+ * Each region arrives in its layer's local space, so it is carried to the screen
+ * through the same `view × layerMatrix` the layer itself is drawn with — which
+ * keeps this correct for moved, scaled and rotated layers without the reporter
+ * needing to know any of that. A region naming a layer that is no longer in the
+ * document cannot be placed, so the frame falls back to a full repaint.
+ *
+ * The result is rounded outward and grown by a pixel: the layer blit is
+ * antialiased at the seam, and a clip that lands mid-pixel would leave a hairline
+ * of the previous frame behind.
+ */
+const resolveDamage = (
+ doc: CanvasDocumentContractV2,
+ view: Mat2d,
+ target: RasterSurface,
+ opts: CompositeOptions
+): Rect | null => {
+ const damage = opts.damage;
+ if (!damage || damage.length === 0) {
+ return null;
+ }
+ let accumulated: Rect | null = null;
+ for (const region of damage) {
+ const layer = doc.layers.find((candidate) => candidate.id === region.layerId);
+ if (!layer) {
+ return null;
+ }
+ const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(layer, opts)), region.rect);
+ accumulated = accumulated ? union(accumulated, bounds) : bounds;
+ }
+ if (!accumulated) {
+ return null;
+ }
+ const grown = roundOut({
+ height: accumulated.height + 2,
+ width: accumulated.width + 2,
+ x: accumulated.x - 1,
+ y: accumulated.y - 1,
+ });
+ // A degenerate matrix would put NaN in here, and a NaN rect compares false
+ // against every bound — which would quietly skip the frame's drawing rather
+ // than widen it. Repaint everything instead.
+ if (
+ !Number.isFinite(grown.x) ||
+ !Number.isFinite(grown.y) ||
+ !Number.isFinite(grown.width) ||
+ !Number.isFinite(grown.height)
+ ) {
+ return null;
+ }
+ return intersect(grown, { height: target.height, width: target.width, x: 0, y: 0 });
};
const isMaskLayer = (
@@ -424,13 +491,29 @@ export const compositeDocument = (
// zoomed in keeps magnified pixels crisp and skips the costly bilinear upscale.
ctx.imageSmoothingEnabled = opts.imageSmoothing ?? true;
- // Clear the whole target in screen space, then lay the checkerboard across the
- // entire viewport — the canvas is an unbounded plane, so the checker is the
- // world, not a document backdrop. With the checkerboard off the cleared surface
- // shows the widget's themed `bg.inset` through it.
+ // Clear the target in screen space, then lay the checkerboard across it — the
+ // canvas is an unbounded plane, so the checker is the world, not a document
+ // backdrop. With the checkerboard off the cleared surface shows the widget's
+ // themed `bg.inset` through it.
+ //
+ // When the frame declared its damage, both are confined to it and a clip keeps
+ // every layer blit below inside it too, so the untouched majority of the target
+ // simply keeps the previous frame's pixels. Damage that resolves to an empty
+ // rect means nothing visible changed: leave the target entirely alone.
identityTransform(ctx);
- ctx.clearRect(0, 0, target.width, target.height);
- drawBackground(ctx, target, opts.checkerboardTile ?? null);
+ const damageScreen = resolveDamage(doc, view, target, opts);
+ if (damageScreen && isEmpty(damageScreen)) {
+ ctx.restore();
+ return;
+ }
+ const repaint: Rect = damageScreen ?? { height: target.height, width: target.width, x: 0, y: 0 };
+ if (damageScreen) {
+ ctx.beginPath();
+ ctx.rect(damageScreen.x, damageScreen.y, damageScreen.width, damageScreen.height);
+ ctx.clip();
+ }
+ ctx.clearRect(repaint.x, repaint.y, repaint.width, repaint.height);
+ drawBackground(ctx, opts.checkerboardTile ?? null, repaint);
if (opts.clipRect) {
ctx.save();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts
new file mode 100644
index 0000000000..a22d5ccb10
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts
@@ -0,0 +1,214 @@
+/**
+ * The correctness guard for damage-clipped compositing.
+ *
+ * A damage-clipped frame leaves everything outside the damage rect showing the
+ * PREVIOUS frame. That is the whole point, and also the whole risk: if the
+ * damage under-reports by even a pixel, the target keeps stale content, and no
+ * assertion about draw-call order would notice. So these tests run every case
+ * twice against real canvases — once repainting in full, once damage-clipped
+ * on top of the previous frame — and demand the two are pixel-identical.
+ */
+
+import type {
+ CanvasDocumentContractV2,
+ CanvasLayerContract,
+ CanvasRasterLayerContractV2,
+} from '@workbench/canvas-engine/contracts';
+import type { LayerDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';
+
+import { fromTRS, identity } from '@workbench/canvas-engine/math/mat2d';
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
+import { describe, expect, it } from 'vitest';
+
+import { compositeDocument, createCheckerboardTile } from './compositor';
+
+const SCREEN_W = 480;
+const SCREEN_H = 360;
+
+const rasterLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { image: { height: 10, imageName: id, width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ ...overrides,
+});
+
+/** A fresh backend + cache with each layer's surface painted a flat colour. */
+const scene = (layers: CanvasLayerContract[], rects: Record<string, Rect>, colors: Record<string, string>) => {
+ const backend = createDomRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ for (const layer of layers) {
+ const rect = rects[layer.id]!;
+ caches.growToRect(layer.id, rect);
+ const entry = caches.get(layer.id)!;
+ entry.surface.ctx.fillStyle = colors[layer.id]!;
+ entry.surface.ctx.fillRect(0, 0, rect.width, rect.height);
+ caches.publishPixels(layer.id);
+ }
+ return { backend, caches };
+};
+
+/** Paints `rect` (layer-local) of a layer's cache a new colour. */
+const repaint = (
+ caches: ReturnType<typeof createLayerCacheStore>,
+ layerId: string,
+ rect: Rect,
+ color: string
+): LayerDamage => {
+ const entry = caches.get(layerId)!;
+ const ctx = entry.surface.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.fillStyle = color;
+ ctx.fillRect(rect.x - entry.rect.x, rect.y - entry.rect.y, rect.width, rect.height);
+ caches.publishPixels(layerId);
+ return { layerId, rect };
+};
+
+const pixelsOf = (surface: { ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D }) =>
+ surface.ctx.getImageData(0, 0, SCREEN_W, SCREEN_H).data;
+
+const countDifferences = (a: Uint8ClampedArray, b: Uint8ClampedArray): { differing: number; worst: number } => {
+ let differing = 0;
+ let worst = 0;
+ for (let i = 0; i < a.length; i++) {
+ const delta = Math.abs(a[i]! - b[i]!);
+ if (delta > 0) {
+ differing++;
+ worst = Math.max(worst, delta);
+ }
+ }
+ return { differing, worst };
+};
+
+describe('damage-clipped compositing matches a full repaint', () => {
+ /**
+ * Composites `steps` twice: once always in full, once with each step's damage
+ * clipped on top of the previous frame. Returns both screens' pixels.
+ */
+ const run = (
+ doc: CanvasDocumentContractV2,
+ caches: ReturnType<typeof createLayerCacheStore>,
+ backend: ReturnType<typeof createDomRasterBackend>,
+ view: Mat2d,
+ steps: (() => LayerDamage)[],
+ checkerboard: boolean
+ ) => {
+ const full = backend.createSurface(SCREEN_W, SCREEN_H);
+ const clipped = backend.createSurface(SCREEN_W, SCREEN_H);
+ const tile = checkerboard ? createCheckerboardTile(backend, { a: '#2a2a2a', b: '#363636' }) : null;
+ const opts = { checkerboardTile: tile, imageSmoothing: false };
+
+ // Seed both with an identical full composite.
+ compositeDocument(full, doc, caches, view, opts);
+ compositeDocument(clipped, doc, caches, view, opts);
+
+ for (const step of steps) {
+ const damage = step();
+ compositeDocument(full, doc, caches, view, opts);
+ compositeDocument(clipped, doc, caches, view, { ...opts, damage: [damage] });
+ }
+ return { clipped: pixelsOf(clipped), full: pixelsOf(full) };
+ };
+
+ const IDENTITY_VIEW = identity();
+
+ it('tracks repeated edits to one layer', () => {
+ const layers = [rasterLayer('a')];
+ const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };
+ const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = Array.from(
+ { length: 6 },
+ (_, i) => () => repaint(caches, 'a', { height: 30, width: 40, x: 60 + i * 30, y: 60 + i * 20 }, '#ef4444')
+ );
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+
+ it('tracks an edit under a translated + scaled layer transform', () => {
+ // The damage arrives layer-local, so the compositor has to carry it through
+ // the layer matrix. A wrong mapping leaves the repainted area stale.
+ const layers = [rasterLayer('a', { transform: { rotation: 0, scaleX: 1.7, scaleY: 1.3, x: 55, y: 25 } })];
+ const rects = { a: { height: 160, width: 220, x: 0, y: 0 } };
+ const { backend, caches } = scene(layers, rects, { a: '#22c55e' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = [
+ () => repaint(caches, 'a', { height: 40, width: 50, x: 20, y: 20 }, '#eab308'),
+ () => repaint(caches, 'a', { height: 25, width: 25, x: 120, y: 90 }, '#a855f7'),
+ ];
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+
+ it('tracks an edit under a rotated layer transform', () => {
+ const layers = [rasterLayer('a', { transform: { rotation: 0.4, scaleX: 1, scaleY: 1, x: 90, y: 60 } })];
+ const rects = { a: { height: 150, width: 200, x: 0, y: 0 } };
+ const { backend, caches } = scene(layers, rects, { a: '#06b6d4' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = [() => repaint(caches, 'a', { height: 40, width: 60, x: 30, y: 40 }, '#f97316')];
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+
+ it('tracks an edit to a lower layer with others stacked over it', () => {
+ // The damaged layer is overdrawn by a translucent one above, so the clipped
+ // frame has to redraw the whole stack inside the rect, not just that layer.
+ const layers = [rasterLayer('top', { opacity: 0.5 }), rasterLayer('bottom')];
+ const rects = {
+ bottom: { height: 220, width: 320, x: 20, y: 20 },
+ top: { height: 140, width: 180, x: 90, y: 70 },
+ };
+ const { backend, caches } = scene(layers, rects, { bottom: '#3b82f6', top: '#f43f5e' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = [
+ () => repaint(caches, 'bottom', { height: 60, width: 60, x: 100, y: 80 }, '#facc15'),
+ () => repaint(caches, 'bottom', { height: 40, width: 200, x: 40, y: 200 }, '#14b8a6'),
+ ];
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+
+ it('tracks edits under a zoomed and panned viewport', () => {
+ const layers = [rasterLayer('a')];
+ const rects = { a: { height: 180, width: 240, x: 10, y: 10 } };
+ const { backend, caches } = scene(layers, rects, { a: '#8b5cf6' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ for (const view of [fromTRS({ x: -120, y: -80 }, 0, 3, 3), fromTRS({ x: 40, y: 30 }, 0, 0.6, 0.6)]) {
+ const steps = [() => repaint(caches, 'a', { height: 30, width: 30, x: 50, y: 45 }, '#fb7185')];
+ const { clipped, full } = run(doc, caches, backend, view, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ }
+ });
+
+ it('repaints in full when the damage names a layer that is gone', () => {
+ // A stale id cannot be placed, so the frame must widen rather than guess.
+ const layers = [rasterLayer('a')];
+ const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };
+ const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = [
+ () => {
+ repaint(caches, 'a', { height: 80, width: 90, x: 60, y: 60 }, '#ef4444');
+ return { layerId: 'nonexistent', rect: { height: 1, width: 1, x: 0, y: 0 } };
+ },
+ ];
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+
+ it('holds with the checkerboard off', () => {
+ const layers = [rasterLayer('a')];
+ const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };
+ const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });
+ const doc = { layers } as unknown as CanvasDocumentContractV2;
+ const steps = [() => repaint(caches, 'a', { height: 50, width: 50, x: 70, y: 70 }, '#ef4444')];
+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, false);
+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts
index 6de196fb26..d93f1dbd43 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts
@@ -1,4 +1,4 @@
-import type { RenderFlags } from '@workbench/canvas-engine/types';
+import type { LayerDamage, RenderFlags } from '@workbench/canvas-engine/types';
import { describe, expect, it, vi } from 'vitest';
@@ -212,3 +212,89 @@ describe('createRenderScheduler', () => {
expect(scheduler.isPaused).toBe(false);
});
});
+
+describe('damage coalescing', () => {
+ const setup = () => {
+ const raf = createFakeRaf();
+ const render = vi.fn();
+ const scheduler = createRenderScheduler({
+ cancelFrame: raf.cancelFrame,
+ render,
+ requestFrame: raf.requestFrame,
+ });
+ return { raf, render, scheduler };
+ };
+
+ const flagsOf = (render: ReturnType<typeof vi.fn>) => render.mock.calls[0]![0] as RenderFlags;
+
+ const damage = (layerId: string, x: number): LayerDamage => ({
+ layerId,
+ rect: { height: 10, width: 10, x, y: 0 },
+ });
+
+ it('carries damage through when every invalidation names its region', () => {
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });
+ scheduler.invalidate({ damage: damage('a', 40), layers: ['a'] });
+ raf.flush();
+ expect(flagsOf(render).damage).toEqual([damage('a', 0), damage('a', 40)]);
+ });
+
+ it('keeps overlay-only invalidations from widening the frame', () => {
+ // The overlay is a separate canvas redrawn whole; it says nothing about
+ // which composited pixels changed.
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });
+ scheduler.invalidate({ overlay: true });
+ raf.flush();
+ expect(flagsOf(render).damage).toEqual([damage('a', 0)]);
+ });
+
+ it.each([
+ ['a bare layer invalidation', { layers: ['a'] }],
+ ['a viewport change', { view: true } as const],
+ ['a forced full repaint', { all: true } as const],
+ ])('widens to a full repaint after %s', (_label, payload) => {
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });
+ scheduler.invalidate(payload);
+ raf.flush();
+ expect(flagsOf(render).damage).toBeNull();
+ });
+
+ it('stays widened once something in the frame could not name its damage', () => {
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ view: true });
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });
+ raf.flush();
+ expect(flagsOf(render).damage).toBeNull();
+ });
+
+ it('ignores damage that does not name the single invalidated layer', () => {
+ // Damage describes one layer's region; anything else in the same payload
+ // changed without a region, so the frame cannot be narrowed.
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a', 'b'] });
+ raf.flush();
+ expect(flagsOf(render).damage).toBeNull();
+ });
+
+ it('ignores damage naming a different layer than the one invalidated', () => {
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ damage: damage('b', 0), layers: ['a'] });
+ raf.flush();
+ expect(flagsOf(render).damage).toBeNull();
+ });
+
+ it('starts each frame with a fresh damage set', () => {
+ const { raf, render, scheduler } = setup();
+ scheduler.invalidate({ all: true });
+ raf.flush();
+ expect(flagsOf(render).damage).toBeNull();
+
+ render.mockClear();
+ scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });
+ raf.flush();
+ expect(flagsOf(render).damage).toEqual([damage('a', 0)]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts
index 1e8ba1e1a4..22417531e6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts
@@ -11,7 +11,7 @@
* time (never at import) and are always overridden in tests.
*/
-import type { RenderFlags } from '@workbench/canvas-engine/types';
+import type { LayerDamage, RenderFlags } from '@workbench/canvas-engine/types';
/** The partial invalidation payload accepted by {@link RenderScheduler.invalidate}. */
export interface InvalidatePayload {
@@ -23,6 +23,15 @@ export interface InvalidatePayload {
overlay?: true;
/** Force a full repaint next frame. */
all?: true;
+ /**
+ * The layer-local region this invalidation changed — purely an optimisation,
+ * letting the frame repaint only those pixels.
+ *
+ * It is honoured ONLY when it names the single layer in `layers`; anything
+ * else (a bare `layers`, a `view`, an `all`) widens the frame back to a full
+ * repaint. Callers therefore opt in, and omitting it is always safe.
+ */
+ damage?: LayerDamage;
}
/** Dependencies for {@link createRenderScheduler}; the rAF pair is injectable for tests. */
@@ -51,6 +60,7 @@ export interface RenderScheduler {
const createEmptyFlags = (): RenderFlags => ({
all: false,
+ damage: [],
layers: new Set<string>(),
overlay: false,
view: false,
@@ -111,19 +121,38 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderSchedule
if (disposed) {
return;
}
+ // Damage merging is deliberately pessimistic: a frame may repaint only part
+ // of the viewport just when EVERY invalidation in it named the region it
+ // changed. A repaint-everything flag, or a layer invalidation without a
+ // region, drops the frame back to full — so a caller that forgets to report
+ // damage costs performance, never correctness.
if (payload.all) {
pending.all = true;
+ pending.damage = null;
}
if (payload.view) {
+ // The whole viewport moves under a pan/zoom; no layer-local rect survives it.
pending.view = true;
+ pending.damage = null;
}
if (payload.overlay) {
+ // The overlay is its own canvas, redrawn whole every frame — it neither
+ // needs nor invalidates composite damage.
pending.overlay = true;
}
if (payload.layers) {
for (const id of payload.layers) {
pending.layers.add(id);
}
+ const damage =
+ payload.damage && payload.layers.length === 1 && payload.layers[0] === payload.damage.layerId
+ ? payload.damage
+ : null;
+ if (!damage) {
+ pending.damage = null;
+ } else if (pending.damage) {
+ pending.damage.push(damage);
+ }
}
schedule();
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
index 3abf3af755..45a39de93b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
@@ -116,4 +116,22 @@ export interface RenderFlags {
overlay: boolean;
/** Force a full repaint, ignoring the other flags. */
all: boolean;
+ /**
+ * The regions that changed, when every contributing invalidation could name
+ * one — letting the composite repaint just those pixels instead of the whole
+ * viewport. `null` means "repaint everything", and is the default: an
+ * invalidation that does not carry damage widens the frame back to full.
+ */
+ damage: LayerDamage[] | null;
+}
+
+/**
+ * A changed region, in the LAYER-LOCAL space of `layerId` — the same space a
+ * layer's cache rect lives in, so a caller that already knows its dirty rect
+ * (the stroke session does) can report it without knowing the layer's transform.
+ * The compositor maps it to the screen through that layer's effective matrix.
+ */
+export interface LayerDamage {
+ layerId: string;
+ rect: Rect;
}