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): make composite damage explicit and compose previews inside group scopes
Josh Corbett09da5501d2b1
diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.tsindex 5a2d72ce9f..3f8e564072 100644--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts@@ -84,7 +84,6 @@ const SEAM_ONLY_SYMBOLS = ['repairSelectedLayerId', 'moveNodesWithinSiblings', '/** Production planners that consume the document model; dropping the import would reopen an ad-hoc path. */const MODEL_CONSUMERS = ['workbench/canvas-engine/render/compositor.ts',- 'workbench/canvas-engine/render/frameDemand.ts','workbench/canvas-engine/render/overlayFrame.ts','workbench/canvas-engine/render/floatingSelectionFrame.ts','workbench/canvas-engine/render/rasterComposite.ts',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 4aa426aab4..e7f2cafe80 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -97,11 +97,13 @@ Canvas invocation first crosses the paint-flush barrier, then captures the post-## Frame demand before allocation-`calculateActiveFrameLayerIds` is a pure pre-allocation pass. For each enabled renderable layer it combines persisted source bounds with any larger live cache rect, applies the committed or transient transform (including rotation), respects isolation, and intersects the result with the document-space viewport. An explicitly isolated operation target is the one exception to normal document visibility: it remains demanded and drawable when disabled or display-hidden because the user is acting on that named layer directly.+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): the leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, the isolated group scopes, and each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until the document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix or live cache extent does. Frame demand, compositing and color sampling all read the same description, so placement is never recomputed per consumer.++`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: it intersects each drawable leaf's bounds with the document-space viewport. An explicitly isolated operation target is the one exception to normal document visibility: it remains demanded and drawable when disabled or display-hidden because the user is acting on that named layer directly.The render path computes this set before `ensureLayerCaches`. Only demanded layers are rasterized for the frame. Offscreen enabled layers are not eagerly allocated; they remain on-demand and LRU-evictable, then rasterize again when panning or a transform reveals them.-The frame's demanded layers form its working set. After drawing, `RasterController.enforceBudget` reclaims memory in a fixed order:+The frame's demanded layers form its working set. After drawing, `RasterController.enforceBudget` reclaims memory in a fixed order (a bounded or empty repaint reads only part of the working set, so its usage window stays open from the last full repaint):1. derived and group artifacts the frame did not read (obsolete parameter variants, inactive groups);2. least-recently-used base caches that are outside the working set and unprotected.@@ -134,6 +136,16 @@ Paint persistence protects dirty pixels until the latest generation of them is aStaged results use a separate compressed-Blob cache rather than retaining a decoded surface for every candidate. Once a candidate's thumbnail settles, the UI asks the engine to prefetch its full-resolution bytes with at most two full-image requests in flight. Selecting a queued candidate promotes it immediately and preempts stale work, while completed/in-flight requests and concurrent decodes of the same image are coalesced. The per-engine cache is LRU-bounded to 24 entries and 64 MiB, retries a failed selected request once as foreground demand, and releases outstanding work on engine cooldown or disposal.+## Composition, damage and overlays++Damage is explicit: `FrameDamage` is a full repaint, no visible repaint, or layer-local regions. The scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. The compositor resolves regions through the frame's matrices into one padded screen rect: regions entirely off the target clear and draw nothing, and a bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.++Compositing always renders through the canonical `RasterBackend`; there is no approximate backend-free path. Filter previews and the floating selection of a grouped member compose inside the group's isolated surface, under the group's opacity, blend and adjustments, exactly as the member's committed pixels would; display, sampling and export share one set of composition semantics.++A group surface is keyed by everything except its members' pixels (scope shape, member appearance and matrices, in-scope previews and float). While that key and the bounds hold, the cache refreshes in place: it unions the damage each member's cache recorded since the version it last drew, clears that region (padded for resampling) and redraws every contributor there, then applies the group's per-pixel adjustments to the region alone. Unknown member damage, a changed member set or new bounds redraw the whole surface, reallocating only when its size changed; a new key reuses the least-recently-used of a group's two slots once both are taken.++The overlay renders in CSS pixels. It receives the document→CSS view, the CSS viewport size and the device-pixel ratio, clears the backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches the CSS-pixel hit tests. The viewport owns the ratio (capped at `MAX_DPR`, sub-one ratios kept) and both the backing-store size and the composite view matrix derive from it.+## Derived surfaces and invalidationEvery display-only pixel effect uses `DerivedSurfaceCache`. A slot is identified by layer ID and effect kind, and guarded by source surface identity, monotonic source version, and a deterministic parameter key. Reuse is safe only when every guard matches. Source replacement therefore cannot publish or reuse a surface produced for an older preview.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.tsindex 59e8560304..d840d2946d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts@@ -112,7 +112,7 @@ describe('real browser raster acceptance', () => {]),caches,IDENTITY,- { clipRect: { height: 8, width: 4, x: 0, y: 0 } }+ { backend, clipRect: { height: 8, width: 4, x: 0, y: 0 } });expectPixel(target, 1, 1, [255, 0, 0, 255]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 1934cb37a9..79d9f420d9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -476,6 +476,12 @@ export interface CanvasDiagnosticsSnapshot {readonly compositeFrames: number;readonly overlayFrames: number;readonly rasterOverageBytes: number;+ /** Group composite backing stores allocated or resized. */+ readonly groupSurfaceAllocations: number;+ /** Whole-surface group redraws (new content, geometry, or unknown member damage). */+ readonly groupSurfaceRebuilds: number;+ /** Group redraws limited to the region members damaged. */+ readonly groupSurfaceRefreshes: number;}export interface CanvasEngineToolCapability extends CanvasToolCapability {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.tsindex 9950d1b719..3f2ebcd35f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts@@ -5,6 +5,7 @@ import type { GroupCompositeScope } from '@workbench/canvas-engine/render/groupCimport { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { identity } from '@workbench/canvas-engine/math/mat2d';+import { NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -56,7 +57,7 @@ describe('RasterController', () => {groupScope,[{ id: 'a', layer: adjustedLayer('a') } as unknown as SemanticLeaf],[identity()],- new Set()+ NO_GROUP_CONTENT);expect(controller.memory.snapshot()).toMatchObject({@@ -145,7 +146,7 @@ describe('RasterController', () => {for (let frame = 0; frame < 5; frame += 1) {const usage = controller.beginFrame();- controller.groups.get(groupScope, members, [identity()], new Set());+ controller.groups.get(groupScope, members, [identity()], NO_GROUP_CONTENT);expect(controller.enforceBudget(new Set(['member']), usage).overageBytes).toBe(SURFACE_BYTES);}@@ -169,12 +170,12 @@ describe('RasterController', () => {const controller = createController(SURFACE_BYTES);publish(controller, 'member');const members = [{ id: 'member', layer: adjustedLayer('member') } as unknown as SemanticLeaf];- controller.groups.get(groupScope, members, [identity()], new Set());+ controller.groups.get(groupScope, members, [identity()], NO_GROUP_CONTENT);controller.enforceBudget(new Set(['member']), controller.beginFrame());expect(controller.memory.snapshot().groupBytes).toBe(0);- controller.groups.get(groupScope, members, [identity()], new Set());+ controller.groups.get(groupScope, members, [identity()], NO_GROUP_CONTENT);controller.releaseReconstructible();expect(controller.memory.snapshot()).toMatchObject({ baseBytes: 0, derivedBytes: 0, groupBytes: 0 });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex 40b4e86a26..bffafc59f0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -104,6 +104,8 @@ export class RasterController {);this.groups = createGroupSurfaceCache({createSurface: (width, height) => options.backend.createSurface(width, height),+ damageSince: (layerId, version) => this.layers.damageSince(layerId, version),+ diagnostics: options.diagnostics,getAdjustedSurface: (layer, entry) => this.getAdjustedSurface(layer, entry),getCacheEntry: (layerId) => this.layers.get(layerId),onBytesChange: (bytes) => memory.setCategoryBytes('group', bytes),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.tsindex a4c8df534e..67b5479c22 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts@@ -20,6 +20,9 @@ const zeroSnapshot = (): MutableCanvasDiagnosticsSnapshot => ({derivedCacheEvictions: 0,derivedCacheHits: 0,derivedCacheMisses: 0,+ groupSurfaceAllocations: 0,+ groupSurfaceRebuilds: 0,+ groupSurfaceRefreshes: 0,imageDataReads: 0,imageDataWrites: 0,layersConsidered: 0,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.tsindex 87262b81fd..3525ab94b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts@@ -119,6 +119,7 @@ const setup = (const composite = (): RasterSurface => {const target = backend.createSurface(document.width, document.height);compositeDocument(target, document, layers, IDENTITY, {+ backend,adjustedSurface: (candidate, candidateEntry) =>controller.isOpenFor([candidate.id])? nulldiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.tsindex 7e7738e9eb..90df0f55b9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts@@ -7,6 +7,7 @@ import {layerContract,} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -73,7 +74,7 @@ const createEngine = (bitmapStore?: BitmapStore) => {{ adjustments: [], blendMode: 'normal', children: [], end: 1, id: 'group', opacity: 0.5, start: 0 },leaves,leaves.map((leaf) => leaf.worldTransform),- new Set()+ NO_GROUP_CONTENT);return { engine, raster };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex fc0e9f22e2..473227d2ad 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -2500,6 +2500,21 @@ describe('createCanvasEngine', () => {engine.lifecycle.dispose();});+ it('sizes the backing stores by the same sub-one or fractional ratio the view matrix uses', () => {+ for (const dpr of [0.5, 1.5]) {+ const { engine } = createEngine();+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.surface.attach(screen.element, overlay.element);+ engine.surface.resize(100, 80, dpr);++ expect(engine.viewport.getViewport().getDpr()).toBe(dpr);+ expect([screen.element.width, screen.element.height]).toEqual([100 * dpr, 80 * dpr]);+ expect([overlay.element.width, overlay.element.height]).toEqual([100 * dpr, 80 * dpr]);+ engine.lifecycle.dispose();+ }+ });+it('dispose removes both store subscriptions', () => {const { engine, unsubscribe } = createEngine();expect(unsubscribe).not.toHaveBeenCalled();@@ -8690,7 +8705,10 @@ describe('setStagedPreview', () => {const { store } = createReactiveStore(emptyDoc({ height: 100, width: 100, x: 5, y: 7 }));const resolver = vi.fn(() => Promise.resolve(new Blob()));const engine = createCanvasEngine({- backend: createTestStubRasterBackend(),+ backend: {+ ...createTestStubRasterBackend(),+ createImageBitmap: () => Promise.resolve({ close: vi.fn(), height: 17, width: 23 } as unknown as ImageBitmap),+ },imageResolver: resolver,projectId: 'p1',store,@@ -8703,7 +8721,7 @@ describe('setStagedPreview', () => {raf.flush();expect(resolver).toHaveBeenCalledWith('staged-candidate', expect.any(AbortSignal));- // The decoded (stub, 0-sized) surface is drawn at the current bbox origin.+ // The decoded surface is drawn at the current bbox origin.expect(stagedDraws(screen.surface).at(-1)!.slice(1, 3)).toEqual([5, 7]);engine.lifecycle.dispose();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex f30bcad574..753667b375 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -164,7 +164,8 @@ import { createSamTool } from '@workbench/canvas-engine/tools/samTool';import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';import { createTextTool } from '@workbench/canvas-engine/tools/textTool';import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';-import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';+import { FULL_DAMAGE } from '@workbench/canvas-engine/types';+import { createViewport, type Viewport } from '@workbench/canvas-engine/viewport';import type { ImagePatchApply } from './history/imagePatch';import type { CanvasProjectMutation } from './mutationContracts';@@ -469,8 +470,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCrasterController.getAdjustedSurface(layer, entry);const groupSurfaces = rasterController.groups;- const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, excludeIds) =>- groupSurfaces.get(scope, members, matrices, excludeIds);+ const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, content) =>+ groupSurfaces.get(scope, members, matrices, content);// Completed-stroke subscribers (persistence P2.2, history P2.3).const strokeListeners = new Set<(event: StrokeCommittedEvent) => void>();@@ -1288,7 +1289,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn;}const doc = mirror.getDocument();- const view = viewport.viewMatrix(viewport.getDpr());+ const dpr = viewport.getDpr();+ const view = viewport.viewMatrix(dpr);if (!doc) {clearSurface(screen);@@ -1305,8 +1307,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcompositeFrame.draw(screen, doc, view, floatRender, samPreview, flags.damage);}- // Redraw the screen-space overlay on every frame to match the composite's view transform.- renderOverlay(overlay, overlayFrame.describe(doc, view, floatRender, samPreview));+ // Redraw the overlay every frame in CSS pixels, scaled by the same device-pixel ratio as the composite.+ const cssSize = viewport.getViewportSize();+ const viewportSize = cssSize.width > 0 ? cssSize : { height: overlay.height / dpr, width: overlay.width / dpr };+ renderOverlay(+ overlay,+ overlayFrame.describe(doc, { dpr, view: viewport.viewMatrix(1), viewportSize }, floatRender, samPreview)+ );};const renderController = new RenderController({@@ -1920,13 +1927,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsuppressViewportInvalidate = true;viewport.setViewportSize(cssWidth, cssHeight, dpr);suppressViewportInvalidate = false;- const backingDpr = Math.min(dpr, MAX_DPR);+ // The viewport owns the clamped ratio so the backing size and every view matrix agree.+ const backingDpr = viewport.getDpr();const backingWidth = Math.round(cssWidth * backingDpr);const backingHeight = Math.round(cssHeight * backingDpr);renderController.resize(backingWidth, backingHeight);// Resize clears canvas pixels; force full recomposition in the same task to prevent a blank browser frame.// Detached rendering is a no-op.- render({ all: true, damage: null, layers: new Set<string>(), overlay: true, view: true });+ render({ all: true, damage: FULL_DAMAGE, layers: new Set<string>(), overlay: true, view: true });};let hasEverFitToView = false;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.tsindex ca815ccd29..92b52f3d64 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts@@ -44,7 +44,7 @@ describe('color sampling with real browser rasterization', () => {caches.publishPixels('far-layer');const doc = documentWith(layer(20));const viewport = backend.createSurface(24, 8);- compositeDocument(viewport, doc, caches, IDENTITY);+ compositeDocument(viewport, doc, caches, IDENTITY, { backend });expect([...viewport.ctx.getImageData(20, 0, 1, 1).data]).toEqual(EXPECTED_PIXEL);expect(createColorSampler(backend).sample(doc, caches, { x: 20, y: 0 })).toEqual(EXPECTED_COLOR);@@ -59,7 +59,7 @@ describe('color sampling with real browser rasterization', () => {caches.publishPixels('far-layer');const doc = documentWith(layer(0), 32);const viewport = backend.createSurface(32, 8);- compositeDocument(viewport, doc, caches, IDENTITY);+ compositeDocument(viewport, doc, caches, IDENTITY, { backend });expect([...viewport.ctx.getImageData(20, 0, 1, 1).data]).toEqual(EXPECTED_PIXEL);expect(createColorSampler(backend).sample(doc, caches, { x: 20, y: 0 })).toEqual(EXPECTED_COLOR);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.tsnew file mode 100644index 0000000000..64e37ceeb1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts@@ -0,0 +1,107 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { FrameDamage } from '@workbench/canvas-engine/types';++import { PreviewStateController } from '@workbench/canvas-engine/controllers/previewStateController';+import { RasterController } from '@workbench/canvas-engine/controllers/rasterController';+import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';+import {+ documentFrom,+ groupContract,+ layerContract,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createEngineStores } from '@workbench/canvas-engine/engineStores';+import { identity } from '@workbench/canvas-engine/math/mat2d';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { createViewport } from '@workbench/canvas-engine/viewport';+import { describe, expect, it } from 'vitest';++import { createCompositeFrame } from './compositeFrame';++const SURFACE_BYTES = 10 * 10 * 4;++const adjusted = (id: string, x = 0): CanvasLayerContract =>+ layerContract(id, 'raster', {+ adjustments: [{ brightness: 0.5, contrast: 0, id: `${id}-bc`, isEnabled: true, type: 'brightness-contrast' }],+ source: { image: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },+ } as Partial<CanvasLayerContract>);++// Two base caches fit by default; their derived and group artifacts are steady overage.+const scene = (budgetBytes = SURFACE_BYTES * 2) => {+ const backend = createTestStubRasterBackend();+ const diagnostics = createCanvasDiagnostics(true);+ const raster = new RasterController({ backend, budgetBytes, diagnostics });+ const document = documentFrom([+ groupContract('group', [adjusted('member')], { opacity: 0.5 }),+ adjusted('plain', 40),+ ]);+ for (const id of ['member', 'plain']) {+ raster.layers.getOrCreateRect(id, { height: 10, width: 10, x: 0, y: 0 });+ raster.layers.publishPixels(id);+ }+ const viewport = createViewport();+ viewport.setViewportSize(100, 100, 1);+ const stores = createEngineStores();+ stores.checkerboard.set(false);+ const frame = createCompositeFrame({+ backend,+ derivedSurfaceCache: raster.derived,+ diagnostics,+ getAdjustedSurface: (layer, entry) => raster.getAdjustedSurface(layer, entry),+ getCheckerboardTile: () => backend.createSurface(1, 1),+ getGroupSurface: (scope, members, matrices, content) => raster.groups.get(scope, members, matrices, content),+ getMaskPatternTile: () => null,+ layerCache: raster.layers,+ previews: new PreviewStateController(),+ raster,+ rasterizeLayer: () => {+ throw new Error('caches are published');+ },+ stores,+ transformOverrides: new Map(),+ viewport,+ });+ const screen = backend.createSurface(100, 100);+ const draw = (damage?: FrameDamage) => frame.draw(screen, document, identity(), null, null, damage);+ const builds = () => {+ const snapshot = diagnostics.snapshot();+ return {+ derived: snapshot.derivedCacheMisses,+ groups: snapshot.groupSurfaceAllocations + snapshot.groupSurfaceRebuilds,+ };+ };+ return { builds, diagnostics, draw, raster };+};++describe('composite frame working set under steady overage', () => {+ it('keeps the visible artifacts across empty and bounded repaints instead of rebuilding them', () => {+ const { builds, draw, raster } = scene();+ draw();+ const afterFullFrame = builds();+ expect(afterFullFrame).toEqual({ derived: 2, groups: 1 });+ expect(raster.memory.snapshot().overageBytes).toBeGreaterThan(0);++ draw({ kind: 'regions', regions: [{ layerId: 'plain', rect: { height: 10, width: 10, x: 5000, y: 0 } }] });+ draw({ kind: 'regions', regions: [{ layerId: 'plain', rect: { height: 2, width: 2, x: 0, y: 0 } }] });+ expect(raster.memory.snapshot()).toMatchObject({ derivedBytes: SURFACE_BYTES * 2, groupBytes: SURFACE_BYTES });++ draw();+ expect(builds()).toEqual(afterFullFrame);+ });++ it('refreshes only the damaged region of a stable group surface while a member is painted', () => {+ const { diagnostics, draw, raster } = scene(SURFACE_BYTES * 100);+ draw();+ for (let tick = 0; tick < 5; tick += 1) {+ const rect = { height: 2, width: 2, x: tick, y: tick };+ raster.layers.publishPixels('member', rect);+ draw({ kind: 'regions', regions: [{ layerId: 'member', rect }] });+ }++ expect(diagnostics.snapshot()).toMatchObject({+ groupSurfaceAllocations: 1,+ groupSurfaceRebuilds: 0,+ groupSurfaceRefreshes: 5,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex ade54e0fb2..1e29e60015 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -5,22 +5,26 @@ import type {} from '@workbench/canvas-engine/controllers/previewStateController';import type { RasterController } from '@workbench/canvas-engine/controllers/rasterController';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';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 { LayerDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';+import type { FrameDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';-import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import {compositeDocument,+ prepareComposite,shouldSmoothAtZoom,+ transformOverridesKey,type CompositeOptions,+ type CompositePreparation,} from '@workbench/canvas-engine/render/compositor';-import { calculateActiveFrameLayerIds } from '@workbench/canvas-engine/render/frameDemand';+import { calculateActiveFrameLayerIds, committedLeafBounds } from '@workbench/canvas-engine/render/frameDemand';+import { FULL_DAMAGE } from '@workbench/canvas-engine/types';import type { FloatingSelectionFrame } from './floatingSelectionFrame';import type { LayerTransformOverrides } from './overlayFrame';@@ -51,14 +55,21 @@ export interface CompositeFrame {view: Mat2d,floatFrame: FloatingSelectionFrame | null,samPreview: SamPreviewState | null,- /**- * Layer-local repaint regions; null means full repaint. Partial damage is valid only when every invalidation- * named its region.- */- damage?: LayerDamage[] | null+ /** What must be repainted; absent repaints everything. */+ damage?: FrameDamage): void;}+interface LeafBoundsMemo {+ readonly layer: SemanticLeaf['layer'];+ readonly matrix: Mat2d;+ readonly live: Rect | undefined;+ readonly bounds: Rect | null;+}++const sameOptionalRect = (a: Rect | undefined, b: Rect | undefined): boolean =>+ a === b || (!!a && !!b && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height);+/*** Composite only for pixel/order/view changes. Rasterize demanded visible layers and protect them during post-draw* eviction. SAM isolation restricts drawing and clipping to its layer/rect, suppressing unrelated previews, floats@@ -71,9 +82,13 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF* Create missing caches and rasterize stale ones, but never resize existing entries here: unflushed paint may* exceed persisted bounds. Rasterization owns bounds changes.*/- const ensureLayerCaches = (doc: CanvasDocumentContractV3, activeFrameLayerIds: ReadonlySet<string>): void => {- for (const layer of getDocumentLeaves(doc)) {- if (!isLayerContributing(layer) || !renderableSourceOf(layer) || !activeFrameLayerIds.has(layer.id)) {+ const ensureLayerCaches = (+ doc: CanvasDocumentContractV3,+ frame: CompositePreparation,+ activeFrameLayerIds: ReadonlySet<string>+ ): void => {+ for (const { layer } of frame.leaves) {+ if (!activeFrameLayerIds.has(layer.id) || !isLayerContributing(layer) || !renderableSourceOf(layer)) {continue;}if (!isRenderableLayer(layer)) {@@ -102,6 +117,52 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF};};+ // The frame description is reused until the document, isolation or override contents change; each leaf's+ // bounds until its contract, placement or live cache extent does.+ let preparation: CompositePreparation | null = null;+ // A bounded or empty repaint reads only part of the working set; the usage window stays open from the last full+ // repaint so artifacts it skipped are not evicted as unused.+ let fullFrameUsage: ReturnType<typeof raster.beginFrame> | null = null;+ let boundsMemo = new Map<string, LeafBoundsMemo>();++ const describeFrame = (+ doc: CanvasDocumentContractV3,+ isolationLayerId: string | null,+ overrides: CompositeOptions['transformOverrides']+ ): CompositePreparation => {+ if (+ preparation?.document !== doc ||+ preparation.isolationLayerId !== isolationLayerId ||+ preparation.overridesKey !== transformOverridesKey(overrides)+ ) {+ preparation = prepareComposite(doc, {+ groupSurface: deps.getGroupSurface,+ isolationLayerId,+ transformOverrides: overrides,+ });+ }+ const plan = preparation;+ const nextMemo = new Map<string, LeafBoundsMemo>();+ const bounds = plan.leaves.map((leaf, index) => {+ const matrix = plan.matrices[index]!;+ const live = layerCache.peek(leaf.id)?.rect;+ const previous = boundsMemo.get(leaf.id);+ const memo =+ previous && previous.layer === leaf.layer && previous.matrix === matrix && sameOptionalRect(previous.live, live)+ ? previous+ : {+ bounds: committedLeafBounds(leaf, matrix, doc, live),+ layer: leaf.layer,+ live: live && { ...live },+ matrix,+ };+ nextMemo.set(leaf.id, memo);+ return memo.bounds;+ });+ boundsMemo = nextMemo;+ return { ...plan, bounds };+ };+/** Evict after drawing; the frame's demanded layers and the artifacts it read form the working set. */const enforceBudget = (activeFrameLayerIds: ReadonlySet<string>,@@ -119,27 +180,22 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst stagedPreview = previews.getStaged();const stagedPlacement = stagedPreview?.placement;const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;- const isolatedIds = isolatedGuard ? new Set([isolatedGuard.layerId]) : null;-- const liveCacheRects = new Map<string, Rect>();- for (const layer of getDocumentLeaves(doc)) {- const rect = layerCache.peek(layer.id)?.rect;- if (rect) {- liveCacheRects.set(layer.id, rect);- }- }+ const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;+ const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides);const activeFrameLayerIds = calculateActiveFrameLayerIds({document: doc,- isolationLayerIds: isolatedIds ?? undefined,- liveCacheRects,- transformOverrides: !isolatedGuard ? transformOverrides : undefined,+ preparation: frame,viewport: visibleDocumentRect(screen),});- ensureLayerCaches(doc, activeFrameLayerIds);+ ensureLayerCaches(doc, frame, activeFrameLayerIds);+ const frameDamage = isolatedGuard ? FULL_DAMAGE : (damage ?? FULL_DAMAGE);const usage = raster.beginFrame();+ if (frameDamage.kind === 'full' || !fullFrameUsage) {+ fullFrameUsage = usage;+ }compositeDocument(screen, doc, layerCache, view, {- damage: isolatedGuard ? null : damage,+ damage: frameDamage,adjustedSurface: deps.getAdjustedSurface,groupSurface: deps.getGroupSurface,backend: deps.backend,@@ -154,6 +210,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF// Snapshot filter previews only when active, avoiding an empty map allocation every frame.layerPreviews: !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null,maskPatternTile: deps.getMaskPatternTile,+ preparation: frame,// Screen frames are display-time: the region tint may draw.regionOverlays: true,// Candidate-specific placement wins for final images. Progress frames@@ -175,10 +232,10 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF: null,// Skip the edited text layer because its portal renders live content.skipLayerId: stores.textEditSession.get()?.layerId ?? null,- transformOverrides: !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null,+ transformOverrides: overrides,});- enforceBudget(activeFrameLayerIds, usage);+ enforceBudget(activeFrameLayerIds, fullFrameUsage);},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex 942073b882..7fd14de552 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -9,7 +9,7 @@ import type {import type { Mat2d } from '@workbench/canvas-engine/types';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { identity } from '@workbench/canvas-engine/math/mat2d';import { describe, expect, it, vi } from 'vitest';@@ -108,7 +108,7 @@ describe('compositeDocument', () => {const bottomCache = caches.getOrCreate('bottom', 10, 10);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([top, bottom]), caches, VIEW);+ compositeDocument(target, makeDoc([top, bottom]), caches, VIEW, { backend });const log = target.callLog;// First op is a clearRect (after the outer save + identity setTransform).@@ -129,7 +129,7 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);const doc = makeDoc([rasterLayer('a', { isEnabled: false }), rasterLayer('b')]);- compositeDocument(target, doc, caches, VIEW);+ compositeDocument(target, doc, caches, VIEW, { backend });const drawImages = target.callLog.filter((e) => e.op === 'drawImage');expect(drawImages).toHaveLength(1);@@ -146,6 +146,7 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);compositeDocument(target, makeDoc([rasterLayer('isolated'), rasterLayer('other')]), caches, VIEW, {+ backend,layerPreviews: new Map([['isolated', { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: filterPreview }]]),isolationLayerId: 'isolated',stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged },@@ -169,7 +170,7 @@ describe('compositeDocument', () => {makeDoc([rasterLayer('disabled', { isEnabled: false }), rasterLayer('visible')]),caches,VIEW,- { stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged } }+ { backend, stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged } });const drawImages = target.callLog.filter((entry) => entry.op === 'drawImage');@@ -184,7 +185,7 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);const doc = makeDoc([rasterLayer('a'), rasterLayer('b')]);- compositeDocument(target, doc, caches, VIEW, { skipLayerId: 'a' });+ compositeDocument(target, doc, caches, VIEW, { backend, skipLayerId: 'a' });const drawImages = target.callLog.filter((e) => e.op === 'drawImage');// 'a' is skipped (its live text is shown by the contenteditable portal); only 'b' draws.@@ -199,7 +200,7 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);// 'b' has no cache; only 'a' should draw.- compositeDocument(target, makeDoc([rasterLayer('a'), rasterLayer('b')]), caches, VIEW);+ compositeDocument(target, makeDoc([rasterLayer('a'), rasterLayer('b')]), caches, VIEW, { backend });expect(target.callLog.filter((e) => e.op === 'drawImage')).toHaveLength(1);});@@ -210,7 +211,9 @@ describe('compositeDocument', () => {const target = backend.createSurface(200, 200);const blend: CanvasBlendMode = 'multiply';- compositeDocument(target, makeDoc([rasterLayer('a', { blendMode: blend, opacity: 0.4 })]), caches, VIEW);+ compositeDocument(target, makeDoc([rasterLayer('a', { blendMode: blend, opacity: 0.4 })]), caches, VIEW, {+ backend,+ });expect(findSet(target.callLog, 'globalAlpha')).toContain(0.4);expect(findSet(target.callLog, 'globalCompositeOperation')).toContain('multiply');@@ -247,7 +250,7 @@ describe('compositeDocument', () => {caches.getOrCreate('a', 10, 10);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([rasterLayer('a', { blendMode: 'normal' })]), caches, VIEW);+ compositeDocument(target, makeDoc([rasterLayer('a', { blendMode: 'normal' })]), caches, VIEW, { backend });expect(findSet(target.callLog, 'globalCompositeOperation')).toContain('source-over');});@@ -257,7 +260,10 @@ describe('compositeDocument', () => {const tile = createCheckerboardTile(backend);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([], { background: 'transparent' }), caches, VIEW, { checkerboardTile: tile });+ compositeDocument(target, makeDoc([], { background: 'transparent' }), caches, VIEW, {+ backend,+ checkerboardTile: tile,+ });// The pattern is created once from the tile (cheap: no per-cell fill loop).const patternCalls = target.callLog.filter((e) => e.op === 'createPattern');@@ -284,7 +290,7 @@ describe('compositeDocument', () => {// covers the whole screen because it is screen-anchored, not doc-anchored.const view: Mat2d = { a: 3, b: 0, c: 0, d: 3, e: -500, f: 220 };const target = backend.createSurface(320, 240);- compositeDocument(target, makeDoc([], { height: 8, width: 8 }), caches, view, { checkerboardTile: tile });+ compositeDocument(target, makeDoc([], { height: 8, width: 8 }), caches, view, { backend, checkerboardTile: tile });const fills = target.callLog.filter((e) => e.op === 'fillRect');expect(fills).toHaveLength(1);@@ -296,7 +302,7 @@ describe('compositeDocument', () => {const caches = createLayerCacheStore(backend);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([], { background: 'transparent' }), caches, VIEW);+ compositeDocument(target, makeDoc([], { background: 'transparent' }), caches, VIEW, { backend });// No tile → no pattern and no fill; the cleared surface shows the widget's bg.inset.expect(target.callLog.some((e) => e.op === 'createPattern')).toBe(false);@@ -312,6 +318,7 @@ describe('compositeDocument', () => {const solidTarget = backend.createSurface(200, 200);// Document background no longer renders; checkerboard still fills the viewport.compositeDocument(solidTarget, makeDoc([], { background: { color: '#123456' } }), caches, VIEW, {+ backend,checkerboardTile: createCheckerboardTile(backend),});const patternCalls = solidTarget.callLog.filter((e) => e.op === 'createPattern');@@ -331,20 +338,7 @@ describe('compositeDocument', () => {expect(styles).toEqual(['#111111', '#222222']);});- it('draws mask-bearing layers as a tinted fill of the mask color (backend-less fallback)', () => {- const backend = createTestStubRasterBackend();- const caches = createLayerCacheStore(backend);- caches.getOrCreate('rg', 10, 10);- const target = backend.createSurface(200, 200);-- compositeDocument(target, makeDoc([maskLayer('rg')]), caches, VIEW);-- // Without a backend the mask draws its coverage then tints with a flat fill.- expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(true);- expect(findSet(target.callLog, 'fillStyle')).toContain('#ff0000');- });-- it('colorizes the mask alpha via source-in on an intermediate surface when a backend is supplied', () => {+ it('colorizes the mask alpha via source-in on an intermediate surface', () => {const base = createTestStubRasterBackend();const created: StubRasterSurface[] = [];const backend = {@@ -578,7 +572,7 @@ describe('compositeDocument', () => {caches.getOrCreate('a', 10, 10);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { imageSmoothing: false });+ compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { backend, imageSmoothing: false });expect(findSet(target.callLog, 'imageSmoothingEnabled')).toEqual([false]);});@@ -588,11 +582,11 @@ describe('compositeDocument', () => {caches.getOrCreate('a', 10, 10);const defaulted = backend.createSurface(200, 200);- compositeDocument(defaulted, makeDoc([rasterLayer('a')]), caches, VIEW);+ compositeDocument(defaulted, makeDoc([rasterLayer('a')]), caches, VIEW, { backend });expect(findSet(defaulted.callLog, 'imageSmoothingEnabled')).toEqual([true]);const explicit = backend.createSurface(200, 200);- compositeDocument(explicit, makeDoc([rasterLayer('a')]), caches, VIEW, { imageSmoothing: true });+ compositeDocument(explicit, makeDoc([rasterLayer('a')]), caches, VIEW, { backend, imageSmoothing: true });expect(findSet(explicit.callLog, 'imageSmoothingEnabled')).toEqual([true]);});@@ -603,6 +597,7 @@ describe('compositeDocument', () => {const staged = backend.createSurface(50, 50);compositeDocument(target, makeDoc([]), caches, VIEW, {+ backend,stagedPreview: { rect: { height: 40, width: 40, x: 5, y: 5 }, surface: staged },});@@ -618,6 +613,7 @@ describe('compositeDocument', () => {const staged = backend.createSurface(23, 17);compositeDocument(target, makeDoc([]), caches, VIEW, {+ backend,stagedPreview: {opacity: 0.35,rect: { height: 34, width: 46, x: -8, y: 13 },@@ -646,6 +642,7 @@ describe('compositeDocument — raster adjustments', () => {const target = backend.createSurface(200, 200);compositeDocument(target, makeDoc([layer]), caches, VIEW, {+ backend,adjustedSurface: (l) => (l.id === 'a' ? adjusted : null),});@@ -663,7 +660,7 @@ describe('compositeDocument — raster adjustments', () => {const cache = caches.getOrCreate('a', 10, 10);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([layer]), caches, VIEW, { adjustedSurface: () => null });+ compositeDocument(target, makeDoc([layer]), caches, VIEW, { backend, adjustedSurface: () => null });const drawImages = target.callLog.filter((e) => e.op === 'drawImage');expect(drawImages[0]!.args[0]).toBe(cache.surface.canvas);@@ -700,7 +697,7 @@ describe('compositeDocument — floating selection', () => {const float = floatOf(backend, 'bottom');const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([top, bottom]), caches, VIEW, { floatingSelection: float });+ compositeDocument(target, makeDoc([top, bottom]), caches, VIEW, { backend, floatingSelection: float });const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);expect(drawn).toEqual([bottomCache.surface.canvas, float.surface.canvas, topCache.surface.canvas]);@@ -714,7 +711,7 @@ describe('compositeDocument — floating selection', () => {const target = backend.createSurface(200, 200);const doc = makeDoc([rasterLayer('a', { blendMode: 'multiply' as CanvasBlendMode, opacity: 0.5 })]);- compositeDocument(target, doc, caches, VIEW, { floatingSelection: float });+ compositeDocument(target, doc, caches, VIEW, { backend, floatingSelection: float });// Twice: once for the layer's own cache, once for the float over it.expect(findSet(target.callLog, 'globalAlpha').filter((value) => value === 0.5)).toHaveLength(2);@@ -730,7 +727,7 @@ describe('compositeDocument — floating selection', () => {const float = floatOf(backend, 'a');const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { floatingSelection: float });+ compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { backend, floatingSelection: float });const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);expect(drawn).toEqual([float.surface.canvas]);@@ -743,7 +740,7 @@ describe('compositeDocument — floating selection', () => {const float = floatOf(backend, 'gone');const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { floatingSelection: float });+ compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { backend, floatingSelection: float });const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);expect(drawn).toEqual([cache.surface.canvas]);@@ -790,6 +787,7 @@ describe('compositeDocument — hidden layers', () => {const target = backend.createSurface(200, 200);compositeDocument(target, makeDoc([rasterLayer('isolated', { isEnabled: false })]), caches, VIEW, {+ backend,isolationLayerId: 'isolated',});@@ -843,3 +841,82 @@ describe('compositeDocument — prepared plans', () => {expect(drawn()).toEqual([bottom.surface.canvas, top.surface.canvas, bottom.surface.canvas]);});});++describe('compositeDocument — damage', () => {+ const scene = () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ const a = caches.getOrCreateRect('a', { height: 10, width: 10, x: 0, y: 0 });+ const b = caches.getOrCreateRect('b', { height: 10, width: 10, x: 0, y: 0 });+ const doc = makeDoc([+ rasterLayer('a'),+ rasterLayer('b', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 50, y: 50 } }),+ ]);+ const target = backend.createSurface(100, 100);+ const ops = (op: string) => target.callLog.filter((entry) => entry.op === op);+ return { a, b, backend, caches, doc, ops, target };+ };++ it('performs no clears and no draws when every damaged region is offscreen', () => {+ const { backend, caches, doc, ops, target } = scene();+ const diagnostics = createCanvasDiagnostics(true);++ compositeDocument(target, doc, caches, VIEW, {+ backend,+ damage: { kind: 'regions', regions: [{ layerId: 'a', rect: { height: 10, width: 10, x: 1000, y: 0 } }] },+ diagnostics,+ });+ compositeDocument(target, doc, caches, VIEW, { backend, damage: { kind: 'none' }, diagnostics });++ expect(target.callLog).toEqual([]);+ expect(ops('clearRect')).toEqual([]);+ expect(diagnostics.snapshot().compositeFrames).toBe(0);+ });++ it('clears only the damaged screen region and skips layers outside it', () => {+ const { a, backend, caches, doc, ops, target } = scene();++ compositeDocument(target, doc, caches, VIEW, {+ backend,+ damage: { kind: 'regions', regions: [{ layerId: 'a', rect: { height: 4, width: 4, x: 2, y: 2 } }] },+ });++ expect(ops('clearRect').map((entry) => entry.args)).toEqual([[1, 1, 6, 6]]);+ expect(ops('drawImage').map((entry) => entry.args[0])).toEqual([a.surface.canvas]);+ });++ it('repaints everything when damage names a layer the document no longer has', () => {+ const { backend, caches, doc, ops, target } = scene();++ compositeDocument(target, doc, caches, VIEW, {+ backend,+ damage: { kind: 'regions', regions: [{ layerId: 'gone', rect: { height: 4, width: 4, x: 2, y: 2 } }] },+ });++ expect(ops('clearRect').map((entry) => entry.args)).toEqual([[0, 0, 100, 100]]);+ expect(ops('drawImage')).toHaveLength(2);+ });++ it('never asks for a group composite whose members miss the repaint region', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ caches.getOrCreateRect('member', { height: 10, width: 10, x: 0, y: 0 });+ caches.getOrCreateRect('other', { height: 10, width: 10, x: 0, y: 0 });+ const doc = makeDoc([], {+ stacks: stacksFrom([+ groupContract('g', [rasterLayer('member')], { opacity: 0.5 }),+ rasterLayer('other', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 60, y: 60 } }),+ ]),+ });+ const groupSurface = vi.fn(() => null);+ const target = backend.createSurface(100, 100);++ compositeDocument(target, doc, caches, VIEW, {+ backend,+ damage: { kind: 'regions', regions: [{ layerId: 'other', rect: { height: 10, width: 10, x: 0, y: 0 } }] },+ groupSurface,+ });++ expect(groupSurface).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 1286e52992..0f405626e6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -12,7 +12,7 @@ import type {} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';-import type { LayerDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { FrameDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import {@@ -23,7 +23,7 @@ import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import type { DerivedSurfaceCache } from './derivedSurfaceCache';-import type { GroupCompositeScope } from './groupCompositeScopes';+import type { GroupCompositeScope, GroupSurfaceContent } from './groupCompositeScopes';import type { LayerCacheEntry, LayerCacheStore } from './layerCache';import type { RasterBackend, RasterSurface } from './raster';@@ -53,11 +53,8 @@ export interface CheckerColors {/** Dark checker fallback before React supplies semantic theme colors, and for DOM-free callers. */export const DEFAULT_CHECKER_COLORS: CheckerColors = { a: '#2a2a2a', b: '#363636' };-/**- * Without a backend, approximate masks with coverage plus flat tint. Production uses source-in colorization at- * layer opacity.- */-export const MASK_TINT_ALPHA = 0.5;+/** Opacity of the display-only regenerate tint drawn over a raster layer's coverage. */+export const REGION_OVERLAY_ALPHA = 0.5;/** Dashed outline drawn around a staged-generation preview so it reads as pending, not committed. */const STAGED_PREVIEW_OUTLINE_COLOR = '#3b82f6';@@ -66,6 +63,8 @@ const STAGED_PREVIEW_OUTLINE_DASH = 6;/** Optional inputs to {@link compositeDocument}. */export interface CompositeOptions {+ /** Allocates mask, control-effect and group intermediates; every composite renders through it. */+ backend: RasterBackend;/** Clips document layers to this document-space rect without clipping the background or staged preview. */clipRect?: Rect | null;/** A staged generation candidate to draw at its placement (document space). */@@ -81,10 +80,10 @@ export interface CompositeOptions {*/imageSmoothing?: boolean;/**- * Layer-local damage clips clear, checkerboard and layer draws to its screen union, retaining other pixels.- * Null/absence repaints the whole target.+ * Bounded damage clips clear, checkerboard and every draw to the screen union of its regions and culls+ * contributors outside it; damage resolving offscreen draws nothing. Absence repaints the whole target.*/- damage?: LayerDamage[] | null;+ damage?: FrameDamage;/*** Transient transforms override committed values without changing the mirror. Missing scale/rotation retain* committed values, supporting position-only move previews.@@ -95,11 +94,6 @@ export interface CompositeOptions {> | null;/** Skip an edited text layer to avoid drawing beneath its live portal; null/absence skips nothing. */skipLayerId?: string | null;- /**- * Backend supplies mask source-in intermediates. Absence uses {@link MASK_TINT_ALPHA} approximation; production- * always supplies it.- */- backend?: RasterBackend | null;/** Cached mask pattern by style/color; null means direct solid fill. Without a provider, only solid fills render. */maskPatternTile?: ((style: string, color: string) => RasterSurface | null) | null;/**@@ -128,19 +122,21 @@ export interface CompositeOptions {floatingSelection?: { layerId: string; surface: RasterSurface; rect: Rect; matrix: Mat2d } | null;/** Optional deterministic render counters; omitted in the normal zero-overhead path. */diagnostics?: CanvasDiagnostics | null;- /** Reused draw plan from {@link prepareComposite}; ignored unless it was prepared for this document and isolation. */+ /**+ * Reused frame description from {@link prepareComposite}; ignored unless it was prepared for this document,+ * isolation, grouping and transform overrides.+ */preparation?: CompositePreparation | null;/**- * An adjusted group's document-space composite (stack applied), `null` when- * it has no drawable content; `excludeIds` members are left out for the- * caller to draw separately. Absent ⇒ members draw flat.+ * An isolated group's document-space composite (stack applied), `null` when it has no drawable content. Filter+ * previews and the float of its members draw inside it. Absent ⇒ members draw flat.*/groupSurface?:| ((scope: GroupCompositeScope,members: readonly SemanticLeaf[],memberMatrices: readonly Mat2d[],- excludeIds: ReadonlySet<string>+ content: GroupSurfaceContent) => { surface: RasterSurface; rect: Rect } | null)| null;}@@ -154,19 +150,55 @@ export const blendToComposite = (mode: CanvasBlendMode): GlobalCompositeOperatioconst isIsolated = (opts: CompositeOptions): boolean =>opts.isolationLayerId !== null && opts.isolationLayerId !== undefined;-/** The leaves and group scopes one document composites with; stable while the document and isolation are. */+type TransformOverrides = NonNullable<CompositeOptions['transformOverrides']>;++/** A stable key for override contents; engines mutate one map in place, so identity cannot tell revisions apart. */+export const transformOverridesKey = (overrides: TransformOverrides | null | undefined): string => {+ if (!overrides || overrides.size === 0) {+ return '';+ }+ let key = '';+ for (const [id, o] of overrides) {+ key += `${id}:${o.x},${o.y},${o.scaleX ?? '-'},${o.scaleY ?? '-'},${o.rotation ?? '-'};`;+ }+ return key;+};++/**+ * One frame description: the leaves drawn (bottom first), their effective matrices with overrides applied, the+ * isolated group scopes, and optionally each leaf's document-space bounds this frame. Stable while the document,+ * isolation, grouping and override contents are, so frame demand, compositing and sampling share it.+ */export interface CompositePreparation {readonly document: CanvasDocumentContractV3;readonly isolationLayerId: string | null;readonly grouped: boolean;+ readonly overridesKey: string;readonly leaves: readonly SemanticLeaf[];+ readonly matrices: readonly Mat2d[];readonly scopes: readonly GroupCompositeScope[];+ /** Document-space bounds a leaf's pixels can cover this frame (a superset is safe); null bounds draw nothing. */+ readonly bounds?: readonly (Rect | null)[];}-/** Plans the draw order and isolated group scopes for `doc`, for callers compositing it repeatedly. */+const effectiveMatrix = (leaf: SemanticLeaf, overrides: TransformOverrides | null | undefined): Mat2d => {+ const override = overrides?.get(leaf.id);+ if (!override) {+ return leaf.worldTransform;+ }+ const { layer } = leaf;+ return fromTRS(+ { x: override.x, y: override.y },+ override.rotation ?? layer.transform.rotation,+ override.scaleX ?? layer.transform.scaleX,+ override.scaleY ?? layer.transform.scaleY+ );+};++/** Plans the draw order, placement and isolated group scopes for `doc`, for callers compositing it repeatedly. */export const prepareComposite = (doc: CanvasDocumentContractV3,- opts: Pick<CompositeOptions, 'groupSurface' | 'isolationLayerId'> = {}+ opts: Pick<CompositeOptions, 'groupSurface' | 'isolationLayerId' | 'transformOverrides'> = {}): CompositePreparation => {const isolationLayerId = opts.isolationLayerId ?? null;// The plan lists the leaves to draw bottom first; the `stagedPreview` lands on top of every stack.@@ -177,7 +209,16 @@ export const prepareComposite = (// Isolation mode inspects raw members, so scopes are bypassed while active.const grouped = !!opts.groupSurface && isolationLayerId === null;const scopes = grouped ? planGroupCompositeScopes(leaves, collectCompositedGroups(doc)) : [];- return { document: doc, grouped, isolationLayerId, leaves, scopes };+ const overrides = opts.transformOverrides ?? null;+ return {+ document: doc,+ grouped,+ isolationLayerId,+ leaves,+ matrices: leaves.map((leaf) => effectiveMatrix(leaf, overrides)),+ overridesKey: transformOverridesKey(overrides),+ scopes,+ };};const isPreparedFor = (@@ -188,7 +229,8 @@ const isPreparedFor = (!!preparation &&preparation.document === doc &&preparation.isolationLayerId === (opts.isolationLayerId ?? null) &&- preparation.grouped === (!!opts.groupSurface && !isIsolated(opts));+ preparation.grouped === (!!opts.groupSurface && !isIsolated(opts)) &&+ preparation.overridesKey === transformOverridesKey(opts.transformOverrides);const setTransformFromMat = (ctx: Ctx, m: Mat2d): void => {ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);@@ -198,34 +240,6 @@ const identityTransform = (ctx: Ctx): void => {ctx.setTransform(1, 0, 0, 1, 0, 0);};-const getEffectiveLayerMatrix = (leaf: SemanticLeaf, opts: CompositeOptions): Mat2d => {- const override = opts.transformOverrides?.get(leaf.id);- if (!override) {- return leaf.worldTransform;- }- const { layer } = leaf;- return fromTRS(- { x: override?.x ?? layer.transform.x, y: override?.y ?? layer.transform.y },- override?.rotation ?? layer.transform.rotation,- override?.scaleX ?? layer.transform.scaleX,- override?.scaleY ?? layer.transform.scaleY- );-};--const isDefinitelyOffscreen = (- leaf: SemanticLeaf,- entry: LayerCacheEntry,- view: Mat2d,- target: RasterSurface,- opts: CompositeOptions-): boolean => {- const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(leaf, opts)), entry.rect);- if (![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) {- return false;- }- return intersect(bounds, { height: target.height, width: target.width, x: 0, y: 0 }) === null;-};-/** Build a reusable 2x2 checker tile through {@link RasterBackend}; frames use patterns instead of per-cell fills. */export const createCheckerboardTile = (backend: RasterBackend,@@ -263,31 +277,38 @@ const drawBackground = (ctx: Ctx, tile: RasterSurface | null, bounds: Rect): voictx.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);};+type ScreenDamage = { kind: 'full' } | { kind: 'none' } | { kind: 'rect'; rect: Rect };+/**- * Transform local damage by view*layerMatrix into screen bounds. Missing layers force full repaint. Round outward- * and pad one pixel to cover antialiased seams.+ * Transform local damage by view*layerMatrix into screen bounds, rounded outward with a one-pixel pad for+ * antialiased seams. Unknown layers or non-finite geometry repaint everything; regions off the target repaint+ * nothing.*/const resolveDamage = (- doc: CanvasDocumentContractV3,+ plan: CompositePreparation,view: Mat2d,target: RasterSurface,- opts: CompositeOptions-): Rect | null => {- const damage = opts.damage;- if (!damage || damage.length === 0) {- return null;+ damage: FrameDamage | undefined+): ScreenDamage => {+ if (!damage || damage.kind === 'full') {+ return { kind: 'full' };+ }+ if (damage.kind === 'none') {+ return { kind: 'none' };}let accumulated: Rect | null = null;- for (const region of damage) {- const leaf = lookupDocumentLeaf(doc, region.layerId);+ for (const region of damage.regions) {+ const index = plan.leaves.findIndex((leaf) => leaf.id === region.layerId);+ const leaf = index >= 0 ? plan.leaves[index] : lookupDocumentLeaf(plan.document, region.layerId);if (!leaf) {- return null;+ return { kind: 'full' };}- const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(leaf, opts)), region.rect);+ const matrix = index >= 0 ? plan.matrices[index]! : leaf.worldTransform;+ const bounds = transformBounds(multiply(view, matrix), region.rect);accumulated = accumulated ? union(accumulated, bounds) : bounds;}if (!accumulated) {- return null;+ return { kind: 'none' };}const grown = roundOut({height: accumulated.height + 2,@@ -295,18 +316,12 @@ const resolveDamage = (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;+ // A degenerate matrix yields NaN, which compares false against every bound; widen rather than skip drawing.+ if (![grown.x, grown.y, grown.width, grown.height].every(Number.isFinite)) {+ return { kind: 'full' };}- return intersect(grown, { height: target.height, width: target.width, x: 0, y: 0 });+ const visible = intersect(grown, { height: target.height, width: target.width, x: 0, y: 0 });+ return visible && !isEmpty(visible) ? { kind: 'rect', rect: visible } : { kind: 'none' };};const isMaskLayer = (@@ -314,10 +329,7 @@ const isMaskLayer = (): layer is Extract<CanvasLayerContract, { type: 'regional_guidance' | 'inpaint_mask' }> =>layer.type === 'regional_guidance' || layer.type === 'inpaint_mask';-/**- * Colorize mask alpha with fill/pattern on a source-in intermediate, then draw with the current layer- * transform/opacity. Without a backend, approximate with coverage and flat tint.- */+/** Colorize mask alpha with fill/pattern on a source-in intermediate, then draw with the current layer transform. */const drawMaskLayer = (ctx: Ctx,layer: Extract<CanvasLayerContract, { type: 'regional_guidance' | 'inpaint_mask' }>,@@ -327,32 +339,25 @@ const drawMaskLayer = (opts: CompositeOptions): void => {const fill = layer.mask.fill;- if (opts.backend) {- const tile = opts.maskPatternTile ? opts.maskPatternTile(fill.style, fill.color) : null;- const colorized = opts.derivedSurfaces- ? opts.derivedSurfaces.get({- create: (target) => colorizeMask(opts.backend!, surface, surface.width, surface.height, fill, tile, target),- kind: 'mask-fill',- layerId: layer.id,- paramsKey: `${fill.style}:${fill.color}`,- source: surface,- sourceVersion,- })- : colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile);- // Draw at local content origin; the outer context already applies layer opacity.- ctx.drawImage(colorized.canvas, origin.x, origin.y);- return;- }- // Backend-less fallback (bare test call): coverage + flat translucent fill.- ctx.drawImage(surface.canvas, origin.x, origin.y);- ctx.globalAlpha = layer.opacity * MASK_TINT_ALPHA;- ctx.fillStyle = fill.color;- ctx.fillRect(origin.x, origin.y, surface.width, surface.height);+ const tile = opts.maskPatternTile ? opts.maskPatternTile(fill.style, fill.color) : null;+ const colorized = opts.derivedSurfaces+ ? opts.derivedSurfaces.get({+ create: (target) => colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile, target),+ kind: 'mask-fill',+ layerId: layer.id,+ paramsKey: `${fill.style}:${fill.color}`,+ source: surface,+ sourceVersion,+ })+ : colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile);+ // Draw at local content origin; the outer context already applies layer opacity.+ ctx.drawImage(colorized.canvas, origin.x, origin.y);};const drawCachedLayer = (ctx: Ctx,leaf: SemanticLeaf,+ matrix: Mat2d,entry: LayerCacheEntry,view: Mat2d,opts: CompositeOptions@@ -361,9 +366,7 @@ const drawCachedLayer = (ctx.save();ctx.globalAlpha = layer.opacity;ctx.globalCompositeOperation = blendToComposite(layer.blendMode);-- const layerMat = getEffectiveLayerMatrix(leaf, opts);- setTransformFromMat(ctx, multiply(view, layerMat));+ setTransformFromMat(ctx, multiply(view, matrix));// The cache surface holds pixels for `entry.rect` in layer-local space; draw// it at that local origin (offset paint/mask layers place their content off-zero).@@ -373,12 +376,12 @@ const drawCachedLayer = (// Draw the full filter output at its local rect with the same control-transparency display effect as committed// pixels.const displayPreview =- layer.type === 'control' && layer.withTransparencyEffect && opts.backend+ layer.type === 'control' && layer.withTransparencyEffect? opts.derivedSurfaces? opts.derivedSurfaces.get({create: (target) =>renderControlTransparency(- opts.backend!,+ opts.backend,preview.surface,preview.surface.width,preview.surface.height,@@ -395,11 +398,11 @@ const drawCachedLayer = (ctx.drawImage(displayPreview.canvas, preview.rect.x, preview.rect.y);} else if (isMaskLayer(layer)) {drawMaskLayer(ctx, layer, entry.surface, entry.version, origin, opts);- } else if (layer.type === 'control' && layer.withTransparencyEffect && opts.backend) {+ } else if (layer.type === 'control' && layer.withTransparencyEffect) {const effect = opts.derivedSurfaces? opts.derivedSurfaces.get({create: (target) =>- renderControlTransparency(opts.backend!, entry.surface, entry.surface.width, entry.surface.height, target),+ renderControlTransparency(opts.backend, entry.surface, entry.surface.width, entry.surface.height, target),kind: 'control-transparency',layerId: layer.id,paramsKey: 'committed',@@ -434,34 +437,28 @@ const drawRegionCoverage = (opts: CompositeOptions): void => {ctx.globalCompositeOperation = 'source-over';- ctx.globalAlpha = MASK_TINT_ALPHA;- if (opts.backend) {- const tile = opts.maskPatternTile ? opts.maskPatternTile(fill.style, fill.color) : null;- const colorized = opts.derivedSurfaces- ? opts.derivedSurfaces.get({- create: (target) =>- colorizeMask(- opts.backend!,- coverage.surface,- coverage.surface.width,- coverage.surface.height,- fill,- tile,- target- ),- kind: 'region-fill',- layerId,- paramsKey: `${fill.style}:${fill.color}`,- source: coverage.surface,- sourceVersion: coverage.version,- })- : colorizeMask(opts.backend, coverage.surface, coverage.surface.width, coverage.surface.height, fill, tile);- ctx.drawImage(colorized.canvas, coverage.rect.x, coverage.rect.y);- return;- }- ctx.fillStyle = fill.color;- ctx.drawImage(coverage.surface.canvas, coverage.rect.x, coverage.rect.y);- ctx.fillRect(coverage.rect.x, coverage.rect.y, coverage.rect.width, coverage.rect.height);+ ctx.globalAlpha = REGION_OVERLAY_ALPHA;+ const tile = opts.maskPatternTile ? opts.maskPatternTile(fill.style, fill.color) : null;+ const colorized = opts.derivedSurfaces+ ? opts.derivedSurfaces.get({+ create: (target) =>+ colorizeMask(+ opts.backend,+ coverage.surface,+ coverage.surface.width,+ coverage.surface.height,+ fill,+ tile,+ target+ ),+ kind: 'region-fill',+ layerId,+ paramsKey: `${fill.style}:${fill.color}`,+ source: coverage.surface,+ sourceVersion: coverage.version,+ })+ : colorizeMask(opts.backend, coverage.surface, coverage.surface.width, coverage.surface.height, fill, tile);+ ctx.drawImage(colorized.canvas, coverage.rect.x, coverage.rect.y);};/**@@ -472,46 +469,73 @@ const drawRegionCoverage = (const drawFloatingSelection = (ctx: Ctx,leaf: SemanticLeaf,+ matrix: Mat2d,view: Mat2d,- opts: CompositeOptions,float: NonNullable<CompositeOptions['floatingSelection']>): void => {const { layer } = leaf;ctx.save();ctx.globalAlpha = layer.opacity;ctx.globalCompositeOperation = blendToComposite(layer.blendMode);- setTransformFromMat(ctx, multiply(multiply(view, getEffectiveLayerMatrix(leaf, opts)), float.matrix));+ setTransformFromMat(ctx, multiply(multiply(view, matrix), float.matrix));ctx.drawImage(float.surface.canvas, float.rect.x, float.rect.y);ctx.restore();};+/** Document-space bounds a leaf can cover this frame: committed pixels joined with its preview and float. */+const leafBounds = (leaf: SemanticLeaf, matrix: Mat2d, committed: Rect | null, opts: CompositeOptions): Rect | null => {+ const preview = isIsolated(opts) ? null : (opts.layerPreviews?.get(leaf.id) ?? null);+ let bounds = committed;+ if (preview) {+ const previewBounds = transformBounds(matrix, preview.rect);+ bounds = bounds ? union(bounds, previewBounds) : previewBounds;+ }+ const float = !isIsolated(opts) && opts.floatingSelection?.layerId === leaf.id ? opts.floatingSelection : null;+ if (float && !isEmpty(float.rect)) {+ const landing = transformBounds(multiply(matrix, float.matrix), float.rect);+ bounds = bounds ? union(bounds, landing) : landing;+ }+ return bounds;+};++/** Whether document-space `bounds` reach the screen region; non-finite geometry counts as visible. */+const reaches = (bounds: Rect | null, view: Mat2d, region: Rect): boolean => {+ if (!bounds) {+ return false;+ }+ const screen = transformBounds(view, bounds);+ if (![screen.x, screen.y, screen.width, screen.height].every(Number.isFinite)) {+ return true;+ }+ return intersect(screen, region) !== null;+};+export const compositeDocument = (target: RasterSurface,doc: CanvasDocumentContractV3,caches: LayerCacheStore,view: Mat2d,- opts: CompositeOptions = {}+ opts: CompositeOptions): void => {+ const plan = isPreparedFor(opts.preparation, doc, opts) ? opts.preparation : prepareComposite(doc, opts);+ const targetRect: Rect = { height: target.height, width: target.width, x: 0, y: 0 };+ const damage = resolveDamage(plan, view, target, opts.damage);+ if (damage.kind === 'none') {+ return;+ }const ctx = target.ctx;opts.diagnostics?.increment('compositeFrames');+ const repaint = damage.kind === 'rect' ? damage.rect : targetRect;ctx.save();-// Set smoothing once under the outer save; nested layer restores preserve it.ctx.imageSmoothingEnabled = opts.imageSmoothing ?? true;- // Clear and checker-fill the viewport, clipping all draws to declared damage. Unchanged pixels retain the- // previous frame; empty visible damage leaves the target untouched.+ // Clear and checker-fill the repaint region, clipping every draw to it. Unchanged pixels keep the previous frame.identityTransform(ctx);- 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) {+ if (damage.kind === 'rect') {ctx.beginPath();- ctx.rect(damageScreen.x, damageScreen.y, damageScreen.width, damageScreen.height);+ ctx.rect(repaint.x, repaint.y, repaint.width, repaint.height);ctx.clip();}ctx.clearRect(repaint.x, repaint.y, repaint.width, repaint.height);@@ -525,47 +549,67 @@ export const compositeDocument = (ctx.clip();}- const plan = isPreparedFor(opts.preparation, doc, opts) ? opts.preparation : prepareComposite(doc, opts);- const { scopes } = plan;+ const { leaves, matrices, scopes } = plan;+ const boundsAt = (index: number): Rect | null => {+ const leaf = leaves[index]!;+ const matrix = matrices[index]!;+ let committed = plan.bounds?.[index];+ if (committed === undefined) {+ const entry = caches.peek(leaf.id);+ committed = entry && !isEmpty(entry.rect) ? transformBounds(matrix, entry.rect) : null;+ }+ return leafBounds(leaf, matrix, committed, opts);+ };+ const previews = isIsolated(opts) ? null : (opts.layerPreviews ?? null);+ const float = isIsolated(opts) ? null : (opts.floatingSelection ?? null);let scopeIndex = 0;- const drawLeafFlat = (leaf: SemanticLeaf): void => {+ const drawLeafFlat = (index: number): void => {+ const leaf = leaves[index]!;opts.diagnostics?.increment('layersConsidered');- const float = opts.floatingSelection?.layerId === leaf.id ? opts.floatingSelection : null;- const entry = caches.get(leaf.id);- // Skip layers with no cache or an empty content rect (a brand-new / cleared- // paint / mask layer holds no pixels — nothing to draw). A float still draws:- // its pixels are detached, so an emptied source layer must not hide them.- if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {- if (float) {- drawFloatingSelection(ctx, leaf, view, opts, float);- }- return;- }- if (isDefinitelyOffscreen(leaf, entry, view, target, opts) && !float) {+ if (!reaches(boundsAt(index), view, repaint)) {opts.diagnostics?.increment('layersCulled');return;}- drawCachedLayer(ctx, leaf, entry, view, opts);- if (float) {- drawFloatingSelection(ctx, leaf, view, opts, float);+ const matrix = matrices[index]!;+ const entry = caches.get(leaf.id);+ // A float still draws over an emptied source: its pixels are detached.+ if (entry && entry.rect.width > 0 && entry.rect.height > 0) {+ drawCachedLayer(ctx, leaf, matrix, entry, view, opts);+ opts.diagnostics?.increment('layersDrawn');+ }+ if (float?.layerId === leaf.id) {+ drawFloatingSelection(ctx, leaf, matrix, view, float);+ }+ };++ const content = (start: number, end: number): GroupSurfaceContent => {+ const excludeIds = new Set<string>();+ for (let index = start; index < end; index += 1) {+ if (leaves[index]!.id === opts.skipLayerId) {+ excludeIds.add(leaves[index]!.id);+ }}- opts.diagnostics?.increment('layersDrawn');+ return { excludeIds, float, previews };};- for (let index = 0; index < plan.leaves.length; index += 1) {+ for (let index = 0; index < leaves.length; index += 1) {const scope = scopeIndex < scopes.length ? scopes[scopeIndex]! : null;if (scope && index === scope.start) {- const members = plan.leaves.slice(scope.start, scope.end);- const matrices = members.map((member) => getEffectiveLayerMatrix(member, opts));- // Skip targets and filter previews draw separately, without the group stack.- const excluded = new Set<string>();- for (const member of members) {- if (member.id === opts.skipLayerId || opts.layerPreviews?.has(member.id)) {- excluded.add(member.id);- }+ scopeIndex += 1;+ let scopeBounds: Rect | null = null;+ for (let member = scope.start; member < scope.end; member += 1) {+ const bounds = leaves[member]!.id === opts.skipLayerId ? null : boundsAt(member);+ scopeBounds = bounds ? (scopeBounds ? union(scopeBounds, bounds) : bounds) : scopeBounds;+ }+ if (!reaches(scopeBounds, view, repaint)) {+ opts.diagnostics?.increment('layersCulled');+ index = scope.end - 1;+ continue;}- const result = opts.groupSurface!(scope, members, matrices, excluded);+ const members = leaves.slice(scope.start, scope.end);+ const memberMatrices = matrices.slice(scope.start, scope.end);+ const result = opts.groupSurface!(scope, members, memberMatrices, content(scope.start, scope.end));if (result) {ctx.save();ctx.globalAlpha = scope.opacity;@@ -574,49 +618,34 @@ export const compositeDocument = (ctx.drawImage(result.surface.canvas, result.rect.x, result.rect.y);ctx.restore();opts.diagnostics?.increment('layersDrawn');- // A float whose member is in the composite draws alone.- for (const member of members) {- if (member.id === opts.skipLayerId) {- continue;- }- if (excluded.has(member.id)) {- drawLeafFlat(member);- } else if (opts.floatingSelection?.layerId === member.id) {- drawFloatingSelection(ctx, member, view, opts, opts.floatingSelection);- }+ }+ // Region overlays are display-only, so they ride ABOVE the group+ // composite rather than being baked into (and staled with) its memo.+ for (let member = scope.start; opts.regionOverlays && member < scope.end; member += 1) {+ const { layer } = leaves[member]!;+ if (+ layer.id === opts.skipLayerId ||+ previews?.has(layer.id) ||+ layer.type !== 'raster' ||+ !layer.inpaint?.isEnabled+ ) {+ continue;}- // Region overlays are display-only, so they ride ABOVE the group- // composite rather than being baked into (and staled with) its memo.- for (let memberIndex = 0; opts.regionOverlays && memberIndex < members.length; memberIndex += 1) {- const member = members[memberIndex]!;- const { layer } = member;- if (- excluded.has(member.id) ||- member.id === opts.skipLayerId ||- layer.type !== 'raster' ||- !layer.inpaint?.isEnabled- ) {- continue;- }- const memberEntry = caches.get(member.id);- if (memberEntry && memberEntry.rect.width > 0 && memberEntry.rect.height > 0) {- ctx.save();- setTransformFromMat(ctx, multiply(view, matrices[memberIndex]!));- drawRegionCoverage(ctx, layer.id, layer.inpaint.fill, memberEntry, opts);- ctx.restore();- }+ const memberEntry = caches.get(layer.id);+ if (memberEntry && memberEntry.rect.width > 0 && memberEntry.rect.height > 0) {+ ctx.save();+ setTransformFromMat(ctx, multiply(view, matrices[member]!));+ drawRegionCoverage(ctx, layer.id, layer.inpaint.fill, memberEntry, opts);+ ctx.restore();}- index = scope.end - 1;- scopeIndex += 1;- continue;}- scopeIndex += 1;+ index = scope.end - 1;+ continue;}- const leaf = plan.leaves[index]!;- if (leaf.id === opts.skipLayerId) {+ if (leaves[index]!.id === opts.skipLayerId) {continue;}- drawLeafFlat(leaf);+ drawLeafFlat(index);}if (opts.clipRect) {@@ -625,7 +654,7 @@ export const compositeDocument = (// Draw staged preview in document space with a dashed outline distinguishing pending pixels.const staged = isIsolated(opts) ? null : opts.stagedPreview;- if (staged) {+ if (staged && reaches(staged.rect, view, repaint)) {ctx.save();setTransformFromMat(ctx, view);ctx.globalAlpha = staged.opacity ?? 1;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.tsindex 445e81412f..21265e0be7 100644--- 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@@ -93,7 +93,7 @@ describe('damage-clipped compositing matches a full repaint', () => {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 };+ const opts = { backend, checkerboardTile: tile, imageSmoothing: false };// Seed both with an identical full composite.compositeDocument(full, doc, caches, view, opts);@@ -102,7 +102,10 @@ describe('damage-clipped compositing matches a full repaint', () => {for (const step of steps) {const damage = step();compositeDocument(full, doc, caches, view, opts);- compositeDocument(clipped, doc, caches, view, { ...opts, damage: [damage] });+ compositeDocument(clipped, doc, caches, view, {+ ...opts,+ damage: { kind: 'regions', regions: [damage] } as const,+ });}return { clipped: pixelsOf(clipped), full: pixelsOf(full) };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.tsindex a000ddfaf6..ee2e6349af 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts@@ -76,13 +76,13 @@ describe('calculateActiveFrameLayerIds', () => {const viewport = { height: 200, width: 200, x: 0, y: 0 };expect(calculateActiveFrameLayerIds({ document: doc, viewport })).toEqual(new Set(['base']));- expect(calculateActiveFrameLayerIds({ document: doc, isolationLayerIds: new Set(['hidden']), viewport })).toEqual(+ expect(calculateActiveFrameLayerIds({ document: doc, isolationLayerId: 'hidden', viewport })).toEqual(new Set(['hidden']));expect(calculateActiveFrameLayerIds({document: document([{ ...hiddenControl('off'), isEnabled: false }]),- isolationLayerIds: new Set(['off']),+ isolationLayerId: 'off',viewport,})).toEqual(new Set(['off']));@@ -94,7 +94,7 @@ describe('calculateActiveFrameLayerIds', () => {expect(calculateActiveFrameLayerIds({document: doc,- isolationLayerIds: new Set(['isolated']),+ isolationLayerId: 'isolated',viewport: { height: 200, width: 200, x: 0, y: 0 },})).toEqual(new Set(['isolated']));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.tsindex 512fd2f2b8..b0f73b1ebe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts@@ -1,58 +1,57 @@import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';-import type { Rect } from '@workbench/canvas-engine/types';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { Mat2d, Rect } from '@workbench/canvas-engine/types';-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';-import { isLeafDrawableForScreen } from '@workbench/canvas-engine/document-model/screenComposition';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';-import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { intersect, isEmpty, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import { prepareComposite, type CompositeOptions, type CompositePreparation } from './compositor';+export interface FrameDemandInput {readonly document: CanvasDocumentContractV3;- readonly isolationLayerIds?: ReadonlySet<string>;+ readonly isolationLayerId?: string | null;readonly liveCacheRects?: ReadonlyMap<string, Rect>;- readonly transformOverrides?: ReadonlyMap<- string,- { x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }- >;+ readonly transformOverrides?: CompositeOptions['transformOverrides'];readonly viewport: Rect;+ /** The frame description to plan against; prepared from the other inputs when absent. */+ readonly preparation?: CompositePreparation;}-/** Calculates the enabled raster caches whose transformed pixels intersect the next frame. */-export const calculateActiveFrameLayerIds = ({- document,- isolationLayerIds,- liveCacheRects,- transformOverrides,- viewport,-}: FrameDemandInput): Set<string> => {+/**+ * Document-space bounds of a leaf's committed pixels: its persisted source bounds joined with any larger live+ * cache, through its effective matrix. Null when the leaf has no rasterizable source.+ */+export const committedLeafBounds = (+ leaf: SemanticLeaf,+ matrix: Mat2d,+ document: CanvasDocumentContractV3,+ liveRect: Rect | undefined+): Rect | null => {+ if (!renderableSourceOf(leaf.layer)) {+ return null;+ }+ const sourceRect = getSourceContentRect(leaf.layer, document);+ const localRect =+ liveRect && !isEmpty(liveRect) ? (isEmpty(sourceRect) ? liveRect : union(sourceRect, liveRect)) : sourceRect;+ return transformBounds(matrix, localRect);+};++/** Calculates the drawable raster caches whose transformed pixels intersect the next frame. */+export const calculateActiveFrameLayerIds = (input: FrameDemandInput): Set<string> => {+ const plan =+ input.preparation ??+ prepareComposite(input.document, {+ isolationLayerId: input.isolationLayerId ?? null,+ transformOverrides: input.transformOverrides,+ });const active = new Set<string>();- for (const leaf of compileDocumentLeaves(document)) {- const { layer } = leaf;- const isIsolated = isolationLayerIds?.has(layer.id) ?? false;- if (- !isLeafDrawableForScreen(leaf, isIsolated) ||- !renderableSourceOf(layer) ||- (isolationLayerIds && !isIsolated)- ) {- continue;- }- const sourceRect = getSourceContentRect(layer, document);- const liveRect = liveCacheRects?.get(layer.id);- const localRect =- liveRect && !isEmpty(liveRect) ? (isEmpty(sourceRect) ? liveRect : union(sourceRect, liveRect)) : sourceRect;- const override = transformOverrides?.get(layer.id);- const matrix = override- ? fromTRS(- { x: override.x, y: override.y },- override.rotation ?? layer.transform.rotation,- override.scaleX ?? layer.transform.scaleX,- override.scaleY ?? layer.transform.scaleY- )- : leaf.worldTransform;- if (intersect(transformBounds(matrix, localRect), viewport)) {- active.add(layer.id);+ plan.leaves.forEach((leaf, index) => {+ const bounds =+ plan.bounds?.[index] ??+ committedLeafBounds(leaf, plan.matrices[index]!, input.document, input.liveCacheRects?.get(leaf.id));+ if (bounds && intersect(bounds, input.viewport)) {+ active.add(leaf.id);}- }+ });return active;};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.tsindex 0f19029e79..ff83eea9e0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts@@ -120,7 +120,11 @@ const scene = (layers: CanvasLayerContract[], paint: Record<string, { rect: Rectreturn { backend, caches };};-const render = (layers: CanvasLayerContract[], paint: Parameters<typeof scene>[1], options: CompositeOptions = {}) => {+const render = (+ layers: CanvasLayerContract[],+ paint: Parameters<typeof scene>[1],+ options: Partial<CompositeOptions> = {}+) => {const { backend, caches } = scene(layers, paint);const target = backend.createSurface(WIDTH, HEIGHT);compositeDocument(target, doc(layers), caches, identity(), {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.tsindex 58bf03c07c..498bdf255f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts@@ -2,11 +2,12 @@ import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@woimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { identity } from '@workbench/canvas-engine/math/mat2d';import { createColorSampler } from '@workbench/canvas-engine/render/colorSample';import { compositeDocument } from '@workbench/canvas-engine/render/compositor';-import { createGroupSurfaceCache } from '@workbench/canvas-engine/render/groupSurfaceCache';+import { createGroupSurfaceCache, NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { planBaseRasterComposite, renderRasterComposite } from '@workbench/canvas-engine/render/rasterComposite';@@ -118,13 +119,14 @@ describe('group adjustment composite', () => {const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => scene.backend.createSurface(w, h),getAdjustedSurface: () => null,+ damageSince: (id, version) => scene.caches.damageSince(id, version),getCacheEntry: (id) => scene.caches.get(id),});const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, document, scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);@@ -137,7 +139,7 @@ describe('group adjustment composite', () => {const again = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(again, document, scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});expect(centerPixel(again)).toEqual(screenPx);});@@ -163,12 +165,13 @@ describe('group adjustment composite', () => {const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => scene.backend.createSurface(w, h),getAdjustedSurface: () => null,+ damageSince: (id, version) => scene.caches.damageSince(id, version),getCacheEntry: (id) => scene.caches.get(id),});const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, document, scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});expect(Math.abs(centerPixel(screen)[0]! - 221)).toBeLessThanOrEqual(3);});@@ -179,6 +182,7 @@ describe('group adjustment composite', () => {const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => scene.backend.createSurface(w, h),getAdjustedSurface: () => null,+ damageSince: (id, version) => scene.caches.damageSince(id, version),getCacheEntry: (id) => scene.caches.get(id),});const point = { x: WIDTH / 2, y: HEIGHT / 2 };@@ -186,7 +190,7 @@ describe('group adjustment composite', () => {const raw = sampler.sample(document, scene.caches, point);expect(raw?.r).toBe(0x40);const adjusted = sampler.sample(document, scene.caches, point, {- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});expect(adjusted?.r).toBe(255 - 0x40);});@@ -209,12 +213,13 @@ describe('group adjustment composite', () => {const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => scene.backend.createSurface(w, h),getAdjustedSurface: () => null,+ damageSince: (id, version) => scene.caches.damageSince(id, version),getCacheEntry: (id) => scene.caches.get(id),});const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, document, scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});const screenPx = centerPixel(screen);const exportPx = centerPixel(exported);@@ -244,12 +249,13 @@ describe('group adjustment composite', () => {const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => nestedScene.backend.createSurface(w, h),getAdjustedSurface: () => null,+ damageSince: (id, version) => nestedScene.caches.damageSince(id, version),getCacheEntry: (id) => nestedScene.caches.get(id),});const screen = nestedScene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, nested, nestedScene.caches, identity(), {backend: nestedScene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});const screenPx = centerPixel(screen);const exportPx = centerPixel(nestedExport);@@ -267,6 +273,7 @@ describe('group adjustment composite', () => {return scene.backend.createSurface(w, h);},getAdjustedSurface: () => null,+ damageSince: (id, version) => scene.caches.damageSince(id, version),getCacheEntry: (id) => scene.caches.get(id),});const compositeAt = (opacity: number) => {@@ -274,7 +281,7 @@ describe('group adjustment composite', () => {const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, document, scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});return centerPixel(screen);};@@ -287,15 +294,15 @@ describe('group adjustment composite', () => {expect(Math.abs(at90[3]! - 230)).toBeLessThanOrEqual(2);});- it('holds two keys per group so alternating consumers (frame vs overview) stop rebuilding', () => {- // Frame/session and settled Overview matrices alternate two keys; two slots retain them, while a third evicts.+ it('holds two keys per group so alternating consumers (frame vs overview) stop redrawing', () => {+ // Frame/session and settled Overview matrices alternate two keys; two slots retain them, while a third+ // repaints the least-recently-used slot in place instead of allocating.const scene = sceneFor({ red: '#ff0000' });- let builds = 0;+ const diagnostics = createCanvasDiagnostics(true);const groupSurfaces = createGroupSurfaceCache({- createSurface: (w, h) => {- builds += 1;- return scene.backend.createSurface(w, h);- },+ createSurface: (w, h) => scene.backend.createSurface(w, h),+ damageSince: (id, version) => scene.caches.damageSince(id, version),+ diagnostics,getAdjustedSurface: () => null,getCacheEntry: (id) => scene.caches.get(id),});@@ -309,38 +316,41 @@ describe('group adjustment composite', () => {const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, docAt(x), scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),});return screen;};+ const draws = () => {+ const { groupSurfaceAllocations, groupSurfaceRebuilds } = diagnostics.snapshot();+ return { allocations: groupSurfaceAllocations, rebuilds: groupSurfaceRebuilds };+ };const first = centerPixel(composite(0));composite(1);- expect(builds).toBe(2);+ expect(draws()).toEqual({ allocations: 2, rebuilds: 0 });composite(0);composite(1);composite(0);- expect(builds).toBe(2);+ expect(draws()).toEqual({ allocations: 2, rebuilds: 0 });expect(centerPixel(composite(0))).toEqual(first);composite(2);- expect(builds).toBe(3);- // x:2 evicted the least-recently-used slot (x:1); x:0 is still warm.+ expect(draws()).toEqual({ allocations: 2, rebuilds: 1 });+ // x:2 took over the least-recently-used slot (x:1); x:0 is still warm.composite(0);- expect(builds).toBe(3);+ expect(draws()).toEqual({ allocations: 2, rebuilds: 1 });composite(1);- expect(builds).toBe(4);+ expect(draws()).toEqual({ allocations: 2, rebuilds: 2 });- // A null build (all members excluded, e.g. under a filter preview) must not- // evict the warm slots the other consumer still needs.+ // A null build (every member excluded) must not evict the warm slots the other consumer still needs.const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, docAt(1), scene.caches, identity(), {backend: scene.backend,- groupSurface: (scope, members, matrices) => groupSurfaces.get(scope, members, matrices, new Set(['red'])),+ groupSurface: (scope, members, matrices) =>+ groupSurfaces.get(scope, members, matrices, { ...NO_GROUP_CONTENT, excludeIds: new Set(['red']) }),});- const buildsAfterNull = builds;composite(1);- expect(builds).toBe(buildsAfterNull);+ expect(draws()).toEqual({ allocations: 2, rebuilds: 2 });});it('keeps identity and pass-through groups on the flat path and keys the plan by group stacks', () => {@@ -353,3 +363,86 @@ describe('group adjustment composite', () => {expect(planBaseRasterComposite(adjusted, BBOX).key).not.toBe(planBaseRasterComposite(inverted, BBOX).key);});});++describe('group-scoped previews and partial refresh', () => {+ const groupedScene = () => {+ const scene = sceneFor({ member: '#00ff00', under: '#0000ff' });+ const groupSurfaces = createGroupSurfaceCache({+ createSurface: (w, h) => scene.backend.createSurface(w, h),+ damageSince: (id, version) => scene.caches.damageSince(id, version),+ getAdjustedSurface: () => null,+ getCacheEntry: (id) => scene.caches.get(id),+ });+ const document = docWith([groupContract('g', [raster('member')], { opacity: 0.5 }), raster('under')]);+ const composite = (options: Partial<Parameters<typeof compositeDocument>[4]> = {}) => {+ const screen = scene.backend.createSurface(WIDTH, HEIGHT);+ compositeDocument(screen, document, scene.caches, identity(), {+ backend: scene.backend,+ groupSurface: (scope, members, matrices, content) => groupSurfaces.get(scope, members, matrices, content),+ ...options,+ });+ return screen;+ };+ return { composite, groupSurfaces, scene };+ };++ it('draws a member filter preview inside its group, under the group opacity', () => {+ const { composite, scene } = groupedScene();+ const committed = centerPixel(composite());+ const previewSurface = scene.backend.createSurface(WIDTH, HEIGHT);+ previewSurface.ctx.fillStyle = '#ff0000';+ previewSurface.ctx.fillRect(0, 0, WIDTH, HEIGHT);++ const previewed = centerPixel(+ composite({ layerPreviews: new Map([['member', { rect: BBOX, surface: previewSurface }]]) })+ );++ // Green and red at the group's 50% over blue: the preview replaces the member, never the group's opacity.+ expect(committed[1]).toBeGreaterThan(120);+ expect(committed[1]).toBeLessThan(135);+ expect(previewed[0]).toBeGreaterThan(120);+ expect(previewed[0]).toBeLessThan(135);+ expect(previewed[2]).toBeGreaterThan(120);+ expect(previewed[3]).toBe(255);+ });++ it('draws a floating selection inside its group, under the group opacity', () => {+ const { composite, scene } = groupedScene();+ const lifted = scene.backend.createSurface(8, 8);+ lifted.ctx.fillStyle = '#ffffff';+ lifted.ctx.fillRect(0, 0, 8, 8);++ const screen = composite({+ floatingSelection: {+ layerId: 'member',+ matrix: identity(),+ rect: { height: 8, width: 8, x: WIDTH / 2 - 4, y: HEIGHT / 2 - 4 },+ surface: lifted,+ },+ });++ // White at 50% over blue, not opaque white drawn above the group.+ const [r, g, b] = centerPixel(screen);+ expect(Math.abs(r! - 128)).toBeLessThanOrEqual(2);+ expect(Math.abs(g! - 128)).toBeLessThanOrEqual(2);+ expect(Math.abs(b! - 255)).toBeLessThanOrEqual(2);+ });++ it('refreshes a damaged member region to the same pixels as a full rebuild', () => {+ const { composite, scene } = groupedScene();+ composite();+ const entry = scene.caches.get('member')!;+ entry.surface.ctx.fillStyle = '#ff00ff';+ entry.surface.ctx.fillRect(10, 12, 7, 5);+ scene.caches.publishPixels('member', { height: 5, width: 7, x: 10, y: 12 });++ const refreshed = composite().ctx.getImageData(0, 0, WIDTH, HEIGHT).data;+ const rebuilt = groupedScene();+ const fresh = rebuilt.scene.caches.get('member')!;+ fresh.surface.ctx.fillStyle = '#ff00ff';+ fresh.surface.ctx.fillRect(10, 12, 7, 5);+ rebuilt.scene.caches.publishPixels('member');++ expect([...refreshed]).toEqual([...rebuilt.composite().ctx.getImageData(0, 0, WIDTH, HEIGHT).data]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.tsindex c196342d72..ae4e0080bd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts@@ -8,6 +8,8 @@ import type {CanvasBlendMode,CanvasDocumentContractV3,} from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';@@ -28,6 +30,21 @@ export interface GroupCompositeScope {readonly children: readonly GroupCompositeScope[];}+/** What a group composite draws beyond its members' committed caches. */+export interface GroupSurfaceContent {+ /** Members left out entirely (the text layer whose live portal replaces it). */+ readonly excludeIds: ReadonlySet<string>;+ /** Filter previews drawn in place of their member's committed pixels, at layer-local output bounds. */+ readonly previews: ReadonlyMap<string, { readonly surface: RasterSurface; readonly rect: Rect }> | null;+ /** Lifted pixels drawn directly above their source member, through the member's and the float's matrices. */+ readonly float: {+ readonly layerId: string;+ readonly surface: RasterSurface;+ readonly rect: Rect;+ readonly matrix: Mat2d;+ } | null;+}+export interface GroupCompositeFacts {readonly adjustments: CanvasAdjustmentsContract;readonly opacity: number;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.tsindex bd929475cb..991ce972c7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts@@ -1,21 +1,23 @@/**- * Document-space group composites cache scope shape and member versions, appearance and effective matrices. Own- * opacity/blend apply at draw time. Document-resolution buffers resample transformed members twice and upscale- * above 100% zoom.+ * Document-space group composites keyed by scope shape, member appearance, effective matrices and in-scope+ * previews. Own opacity/blend apply at draw time. A stable slot refreshes in place: only the region its members+ * damaged since the last draw is cleared and redrawn, and geometry changes redraw without reallocating when the+ * size holds. Document-resolution buffers resample transformed members twice and upscale above 100% zoom.*/import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import { multiply } from '@workbench/canvas-engine/math/mat2d';-import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';-import type { GroupCompositeScope } from './groupCompositeScopes';+import type { GroupCompositeScope, GroupSurfaceContent } from './groupCompositeScopes';export interface GroupSurfaceResult {readonly surface: RasterSurface;@@ -25,11 +27,14 @@ export interface GroupSurfaceResult {export interface GroupSurfaceDeps {createSurface(width: number, height: number): RasterSurface;- /** Receives the running byte total after every build and release. */+ /** Receives the running byte total after every allocation, resize and release. */onBytesChange?(bytes: number): void;getCacheEntry(layerId: string): LayerCacheEntry | undefined;+ /** Surface-local damage a member's cache received since `version`, or null when unknown. */+ damageSince(layerId: string, version: number): Rect | null;/** The member's own adjusted pixels (its personal stack), or null for raw. */getAdjustedSurface(layer: CanvasRasterLayerContractV2, entry: LayerCacheEntry): RasterSurface | null;+ diagnostics?: CanvasDiagnostics;}export interface GroupSurfaceCache {@@ -39,7 +44,7 @@ export interface GroupSurfaceCache {scope: GroupCompositeScope,members: readonly SemanticLeaf[],memberMatrices: readonly Mat2d[],- excludeIds: ReadonlySet<string>+ content: GroupSurfaceContent): GroupSurfaceResult | null;/** Drops every cached group not named; call when document structure changes. */prune(liveGroupIds: ReadonlySet<string>): void;@@ -50,7 +55,15 @@ export interface GroupSurfaceCache {clear(): void;}+export const NO_GROUP_CONTENT: GroupSurfaceContent = { excludeIds: new Set(), float: null, previews: null };+const matKey = (m: Mat2d): string => `${m.a},${m.b},${m.c},${m.d},${m.e},${m.f}`;+const rectKey = (r: Rect): string => `${r.x},${r.y},${r.width},${r.height}`;+const sameRect = (a: Rect, b: Rect): boolean =>+ a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;++/** Destination pixels a changed source pixel can reach through interpolation. */+const RESAMPLE_MARGIN = 2;// The frame composites with live session matrices while the overview composites// the settled contract, so one group legitimately holds two keys at once; two@@ -58,18 +71,32 @@ const matKey = (m: Mat2d): string => `${m.a},${m.b},${m.c},${m.d},${m.e},${m.f}`const SLOTS_PER_GROUP = 2;interface GroupSlot {- readonly key: string;- readonly result: GroupSurfaceResult;+ shapeKey: string;+ rect: Rect;+ readonly surface: RasterSurface;+ /** Cache version of every member pixel source the surface currently shows. */+ versions: ReadonlyMap<string, number>;lastUsed: number;}-const slotBytes = (slot: GroupSlot): number => slot.result.surface.width * slot.result.surface.height * 4;+const surfaceBytes = (surface: RasterSurface): number => surface.width * surface.height * 4;export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCache => {const cache = new Map<string, GroupSlot[]>();+ const objectIds = new WeakMap<object, number>();+ let nextObjectId = 1;let clock = 0;let totalBytes = 0;+ const objectId = (value: object): number => {+ let id = objectIds.get(value);+ if (id === undefined) {+ id = nextObjectId++;+ objectIds.set(value, id);+ }+ return id;+ };+const adjustBytes = (delta: number): void => {if (delta === 0) {return;@@ -79,13 +106,13 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac};const dropSlots = (slots: readonly GroupSlot[]): void => {- adjustBytes(-slots.reduce((bytes, slot) => bytes + slotBytes(slot), 0));+ adjustBytes(-slots.reduce((bytes, slot) => bytes + surfaceBytes(slot.surface), 0));};// A scope's OWN opacity/blend are applied by the consumer when the surface// lands, so they stay out of its shape key (an opacity scrub reuses the- // surface); a CHILD scope's opacity/blend are baked in here by `drawRange`,- // so children key with them.+ // surface); a CHILD scope's opacity/blend are baked in here, so children key+ // with them.const childScopeKey = (scope: GroupCompositeScope): string =>`${scopeShapeKey(scope)}:${scope.opacity}:${scope.blendMode}`;const scopeShapeKey = (scope: GroupCompositeScope): string =>@@ -93,19 +120,60 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac.map(childScopeKey).join(',')})`;- const buildKey = (+ /** Everything a surface depends on except member pixels, which are tracked by version and damage. */+ const shapeKeyOf = (scope: GroupCompositeScope,members: readonly SemanticLeaf[],memberMatrices: readonly Mat2d[],- excludeIds: ReadonlySet<string>+ content: GroupSurfaceContent,+ baseIndex: number): string => {- const memberKeys = members.map((leaf, index) => {- const layer = leaf.layer;- const entry = deps.getCacheEntry(leaf.id);+ const memberKeys: string[] = [];+ for (let i = scope.start; i < scope.end; i += 1) {+ const leaf = members[i - baseIndex]!;+ if (content.excludeIds.has(leaf.id)) {+ memberKeys.push(`${leaf.id}:x`);+ continue;+ }+ const { layer } = leaf;const own = layer.type === 'raster' ? adjustmentsKey(layer.adjustments) : '-';- return `${leaf.id}:${entry?.version ?? -1}:${layer.opacity}:${layer.blendMode}:${matKey(memberMatrices[index]!)}:${own}`;- });- return `${scopeShapeKey(scope)}|${memberKeys.join('|')}|x:${[...excludeIds].sort().join(',')}`;+ const preview = content.previews?.get(leaf.id);+ const float = content.float?.layerId === leaf.id ? content.float : null;+ const previewKey = preview ? `:p${objectId(preview.surface)}@${rectKey(preview.rect)}` : '';+ const floatKey = float ? `:f${objectId(float.surface)}@${rectKey(float.rect)}*${matKey(float.matrix)}` : '';+ const appearance = `${layer.opacity}:${layer.blendMode}:${matKey(memberMatrices[i - baseIndex]!)}:${own}`;+ memberKeys.push(`${leaf.id}:${appearance}${previewKey}${floatKey}`);+ }+ return `${scopeShapeKey(scope)}|${memberKeys.join('|')}`;+ };++ /** Members whose committed cache pixels the surface shows, with their document-space bounds. */+ const drawnEntries = (+ scope: GroupCompositeScope,+ members: readonly SemanticLeaf[],+ memberMatrices: readonly Mat2d[],+ content: GroupSurfaceContent,+ baseIndex: number+ ): { leaf: SemanticLeaf; matrix: Mat2d; entry: LayerCacheEntry | null; bounds: Rect | null }[] => {+ const drawn: { leaf: SemanticLeaf; matrix: Mat2d; entry: LayerCacheEntry | null; bounds: Rect | null }[] = [];+ for (let i = scope.start; i < scope.end; i += 1) {+ const leaf = members[i - baseIndex]!;+ if (content.excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {+ continue;+ }+ const matrix = memberMatrices[i - baseIndex]!;+ const preview = content.previews?.get(leaf.id);+ const entry = deps.getCacheEntry(leaf.id) ?? null;+ const pixels = preview ? preview.rect : entry && !isEmpty(entry.rect) ? entry.rect : null;+ let bounds = pixels ? transformBounds(matrix, pixels) : null;+ const float = content.float?.layerId === leaf.id ? content.float : null;+ if (float && !isEmpty(float.rect)) {+ const landing = transformBounds(multiply(matrix, float.matrix), float.rect);+ bounds = bounds ? union(bounds, landing) : landing;+ }+ drawn.push({ bounds, entry: preview ? null : entry, leaf, matrix });+ }+ return drawn;};/** Draws `[from, to)` (absolute plan indices, bottom first); `baseIndex` = absolute index of `members[0]`. */@@ -114,7 +182,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacview: Mat2d,members: readonly SemanticLeaf[],memberMatrices: readonly Mat2d[],- excludeIds: ReadonlySet<string>,+ content: GroupSurfaceContent,baseIndex: number,from: number,to: number,@@ -124,7 +192,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacfor (let i = from; i < to;) {const child = childIndex < children.length ? children[childIndex]! : null;if (child && i >= child.start && i < child.end) {- const nested = build(child, members, memberMatrices, excludeIds, baseIndex);+ const nested = resolve(child, members, memberMatrices, content, baseIndex);if (nested) {ctx.save();ctx.globalAlpha = child.opacity;@@ -140,65 +208,179 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacconst leaf = members[i - baseIndex]!;const matrix = memberMatrices[i - baseIndex]!;i += 1;- if (excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {+ if (content.excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {continue;}- const entry = deps.getCacheEntry(leaf.id);- if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {- continue;- }- const adjusted = deps.getAdjustedSurface(leaf.layer, entry);+ const placed = multiply(view, matrix);+ const preview = content.previews?.get(leaf.id);+ const entry = preview ? undefined : deps.getCacheEntry(leaf.id);ctx.save();ctx.globalAlpha = leaf.layer.opacity;ctx.globalCompositeOperation = blendToComposite(leaf.layer.blendMode);- const m = multiply(view, matrix);- ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);- ctx.drawImage((adjusted ?? entry.surface).canvas, entry.rect.x, entry.rect.y);+ ctx.setTransform(placed.a, placed.b, placed.c, placed.d, placed.e, placed.f);+ if (preview) {+ ctx.drawImage(preview.surface.canvas, preview.rect.x, preview.rect.y);+ } else if (entry && !isEmpty(entry.rect)) {+ const adjusted = deps.getAdjustedSurface(leaf.layer, entry);+ ctx.drawImage((adjusted ?? entry.surface).canvas, entry.rect.x, entry.rect.y);+ }+ const float = content.float?.layerId === leaf.id ? content.float : null;+ if (float) {+ const floated = multiply(placed, float.matrix);+ ctx.setTransform(floated.a, floated.b, floated.c, floated.d, floated.e, floated.f);+ ctx.drawImage(float.surface.canvas, float.rect.x, float.rect.y);+ }ctx.restore();}};- const build = (+ /** Clears and redraws `region` (surface-local) of a slot, then applies the scope's own adjustments there. */+ const paint = (+ slot: GroupSlot,+ region: Rect,scope: GroupCompositeScope,members: readonly SemanticLeaf[],memberMatrices: readonly Mat2d[],- excludeIds: ReadonlySet<string>,+ content: GroupSurfaceContent,baseIndex: number- ): GroupSurfaceResult | null => {- let bounds: Rect | null = null;- for (let i = scope.start; i < scope.end; i += 1) {- const leaf = members[i - baseIndex]!;- if (excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {+ ): void => {+ const ctx = slot.surface.ctx;+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.beginPath();+ ctx.rect(region.x, region.y, region.width, region.height);+ ctx.clip();+ ctx.clearRect(region.x, region.y, region.width, region.height);+ const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -slot.rect.x, f: -slot.rect.y };+ drawRange(ctx, view, members, memberMatrices, content, baseIndex, scope.start, scope.end, scope.children);+ ctx.restore();+ // Every adjustment is per-pixel, so a region-limited pass equals a whole-surface one there.+ if (!isIdentityAdjustments(scope.adjustments)) {+ const pixels = ctx.getImageData(region.x, region.y, region.width, region.height);+ applyAdjustments(pixels, scope.adjustments);+ ctx.putImageData(pixels, region.x, region.y);+ }+ };++ /** Document-space region the members changed since the slot was drawn; null when only a full redraw is safe. */+ const damagedRegion = (slot: GroupSlot, drawn: ReturnType<typeof drawnEntries>): { region: Rect | null } | null => {+ if (drawn.filter((item) => item.entry).length !== slot.versions.size) {+ return null;+ }+ let region: Rect | null = null;+ for (const { entry, leaf, matrix } of drawn) {+ if (!entry) {continue;}- const entry = deps.getCacheEntry(leaf.id);- if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {+ const drawnVersion = slot.versions.get(leaf.id);+ if (drawnVersion === undefined) {+ return null;+ }+ if (drawnVersion === entry.version) {continue;}- const memberBounds = transformBounds(memberMatrices[i - baseIndex]!, entry.rect);- bounds = bounds === null ? memberBounds : union(bounds, memberBounds);+ const local = deps.damageSince(leaf.id, drawnVersion);+ if (!local) {+ return null;+ }+ const changed = transformBounds(matrix, {+ height: local.height,+ width: local.width,+ x: entry.rect.x + local.x,+ y: entry.rect.y + local.y,+ });+ region = region ? union(region, changed) : changed;+ }+ return { region };+ };++ const versionsOf = (drawn: ReturnType<typeof drawnEntries>): ReadonlyMap<string, number> =>+ new Map(drawn.flatMap(({ entry, leaf }) => (entry ? [[leaf.id, entry.version] as const] : [])));++ function resolve(+ scope: GroupCompositeScope,+ members: readonly SemanticLeaf[],+ memberMatrices: readonly Mat2d[],+ content: GroupSurfaceContent,+ baseIndex: number+ ): GroupSurfaceResult | null {+ clock += 1;+ const drawn = drawnEntries(scope, members, memberMatrices, content, baseIndex);+ let bounds: Rect | null = null;+ for (const item of drawn) {+ if (item.bounds) {+ bounds = bounds ? union(bounds, item.bounds) : item.bounds;+ }}if (bounds === null) {+ // Keys fully determine validity, so warm slots stay for the other consumer.return null;}const rect = roundOut(bounds);if (rect.width <= 0 || rect.height <= 0) {return null;}- const surface = deps.createSurface(rect.width, rect.height);- const ctx = surface.ctx;- ctx.setTransform(1, 0, 0, 1, 0, 0);- ctx.clearRect(0, 0, rect.width, rect.height);- const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y };- drawRange(ctx, view, members, memberMatrices, excludeIds, baseIndex, scope.start, scope.end, scope.children);- // Opacity/blend-only groups have identity adjustments; skip pixel readback.- if (!isIdentityAdjustments(scope.adjustments)) {- const pixels = ctx.getImageData(0, 0, rect.width, rect.height);- applyAdjustments(pixels, scope.adjustments);- ctx.putImageData(pixels, 0, 0);+ const shapeKey = shapeKeyOf(scope, members, memberMatrices, content, baseIndex);+ const slots = cache.get(scope.id) ?? [];+ const matching = slots.find((candidate) => candidate.shapeKey === shapeKey) ?? null;+ const whole: Rect = { height: rect.height, width: rect.width, x: 0, y: 0 };+ let slot: GroupSlot;++ if (matching && sameRect(matching.rect, rect)) {+ slot = matching;+ const damage = damagedRegion(slot, drawn);+ const region = damage+ ? damage.region &&+ intersect(+ roundOut({+ height: damage.region.height + RESAMPLE_MARGIN * 2,+ width: damage.region.width + RESAMPLE_MARGIN * 2,+ x: damage.region.x - rect.x - RESAMPLE_MARGIN,+ y: damage.region.y - rect.y - RESAMPLE_MARGIN,+ }),+ whole+ )+ : whole;+ if (region && !isEmpty(region)) {+ paint(slot, region, scope, members, memberMatrices, content, baseIndex);+ deps.diagnostics?.increment(damage ? 'groupSurfaceRefreshes' : 'groupSurfaceRebuilds');+ }+ } else if (matching || slots.length >= SLOTS_PER_GROUP) {+ // New bounds or content reuse a slot's backing store, reallocating only when the size changed.+ slot = matching ?? slots[slots.length - 1]!;+ if (slot.surface.width !== rect.width || slot.surface.height !== rect.height) {+ const before = surfaceBytes(slot.surface);+ slot.surface.resize(rect.width, rect.height);+ adjustBytes(surfaceBytes(slot.surface) - before);+ deps.diagnostics?.increment('groupSurfaceAllocations');+ }+ slot.rect = rect;+ slot.shapeKey = shapeKey;+ paint(slot, whole, scope, members, memberMatrices, content, baseIndex);+ deps.diagnostics?.increment('groupSurfaceRebuilds');+ } else {+ slot = {+ lastUsed: clock,+ rect,+ shapeKey,+ surface: deps.createSurface(rect.width, rect.height),+ versions: new Map(),+ };+ adjustBytes(surfaceBytes(slot.surface));+ deps.diagnostics?.increment('groupSurfaceAllocations');+ paint(slot, whole, scope, members, memberMatrices, content, baseIndex);+ slots.unshift(slot);+ cache.set(scope.id, slots);}- return { rect, surface };- };+ slot.versions = versionsOf(drawn);+ slot.lastUsed = clock;+ const index = slots.indexOf(slot);+ if (index > 0) {+ slots.splice(index, 1);+ slots.unshift(slot);+ }+ return { rect: slot.rect, surface: slot.surface };+ }return {byteSize: () => totalBytes,@@ -231,33 +413,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac}return evicted;},- get: (scope, members, memberMatrices, excludeIds) => {- const key = buildKey(scope, members, memberMatrices, excludeIds);- const slots = cache.get(scope.id) ?? [];- clock += 1;- const hitIndex = slots.findIndex((slot) => slot.key === key);- if (hitIndex >= 0) {- const hit = slots[hitIndex]!;- hit.lastUsed = clock;- if (hitIndex > 0) {- slots.splice(hitIndex, 1);- slots.unshift(hit);- }- return hit.result;- }- const result = build(scope, members, memberMatrices, excludeIds, scope.start);- if (result) {- const slot: GroupSlot = { key, lastUsed: clock, result };- adjustBytes(slotBytes(slot));- slots.unshift(slot);- dropSlots(slots.splice(SLOTS_PER_GROUP));- cache.set(scope.id, slots);- }- // A null build (every member excluded or unrasterized) keeps existing- // slots: keys fully determine validity, so a warm slot held by the other- // consumer can only ever hit when genuinely valid.- return result;- },+ get: (scope, members, memberMatrices, content) => resolve(scope, members, memberMatrices, content, scope.start),prune: (liveGroupIds) => {for (const [id, slots] of cache) {if (!liveGroupIds.has(id)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.tsindex bf1c87a34a..37dc4cd4a2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts@@ -12,6 +12,7 @@ import type { FloatingSelectionFrame } from './floatingSelectionFrame';import { createOverlayFrame, type CreateOverlayFrameDeps } from './overlayFrame';const VIEW = [1, 0, 0, 1, 0, 0] as unknown as Mat2d;+const SCREEN = { dpr: 1, view: VIEW, viewportSize: { height: 64, width: 64 } };const layer = (id: string, overrides: Record<string, unknown> = {}) => ({id,@@ -78,7 +79,7 @@ const describeOverlay = (doc = documentOf(),floatFrame: FloatingSelectionFrame | null = null,sam: Parameters<ReturnType<typeof createOverlayFrame>['describe']>[3] = null-) => createOverlayFrame(harness.deps).describe(doc, VIEW, floatFrame, sam);+) => createOverlayFrame(harness.deps).describe(doc, SCREEN, floatFrame, sam);beforeEach(() => {harness = makeHarness();@@ -231,7 +232,7 @@ describe('SAM', () => {data: { id: 'mask' },rect: { height: 4, width: 4, x: 1, y: 1 },} as unknown as SamPreviewState;- expect(createOverlayFrame(harness.deps).describe(documentOf(), VIEW, null, sam).samPreview).toEqual({+ expect(createOverlayFrame(harness.deps).describe(documentOf(), SCREEN, null, sam).samPreview).toEqual({opacity: 0.45,outline: null,phase: 0,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex 25647c8234..17c2a8f340 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -8,7 +8,7 @@ import type {} from '@workbench/canvas-engine/render/overlayRenderer';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';-import type { Mat2d, ToolId, Vec2 } from '@workbench/canvas-engine/types';+import type { ToolId, Vec2 } from '@workbench/canvas-engine/types';import { lookupDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentIndex, type CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';@@ -51,12 +51,15 @@ export interface OverlayFrame {/** Everything the overlay renderer draws this frame, gathered from live state. */describe(doc: CanvasDocumentContractV3,- view: Mat2d,+ screen: OverlayScreen,floatFrame: FloatingSelectionFrame | null,samPreview: SamPreviewState | null): OverlayState;}+/** The overlay's screen: document→CSS transform, CSS viewport size and device-pixel ratio. */+export type OverlayScreen = Pick<OverlayState, 'dpr' | 'view' | 'viewportSize'>;+/*** Pure projection of engine state into overlay descriptors. Live previews replace committed geometry; stale frames* are suppressed. The overlay owns no interaction state.@@ -131,7 +134,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =};return {- describe: (doc, view, floatFrame, samPreview) => {+ describe: (doc, screen, floatFrame, samPreview) => {const activeTool = getActiveToolId();const bboxPreview = stores.bboxPreview.get();const samSession = stores.samInteraction.get();@@ -169,7 +172,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =showBbox: stores.showBbox.get() || activeTool === 'bbox',showGrid: stores.showGrid.get(),transformFrame: transformFrame(doc),- view,+ ...screen,};},};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.tsnew file mode 100644index 0000000000..bf750f5177--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts@@ -0,0 +1,89 @@+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { transformOverlayGeometry, transformTargetAt } from '@workbench/canvas-engine/transform/transformMath';+import { createViewport } from '@workbench/canvas-engine/viewport';+import { describe, expect, it } from 'vitest';++import { renderOverlay } from './overlayRenderer';++const CSS_SIZE = 200;+const RECT = { height: 50, width: 50, x: 50, y: 50 };+const IDENTITY_TRANSFORM = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++/** Renders bbox and transform chrome at `dpr` the way the engine does: CSS view and size, DPR base. */+const renderAt = (dpr: number) => {+ const viewport = createViewport();+ viewport.setViewportSize(CSS_SIZE, CSS_SIZE, dpr);+ const target = createDomRasterBackend().createSurface(+ Math.round(CSS_SIZE * viewport.getDpr()),+ Math.round(CSS_SIZE * viewport.getDpr())+ );+ renderOverlay(target, {+ bbox: RECT,+ bboxHandles: true,+ dpr: viewport.getDpr(),+ transformFrame: transformOverlayGeometry(IDENTITY_TRANSFORM, RECT),+ view: viewport.viewMatrix(1),+ viewportSize: viewport.getViewportSize(),+ });+ return { target, viewport };+};++/** Opaque white backing pixels across one row through the west bbox handle. */+const whiteRunAt = (target: ReturnType<typeof renderAt>['target'], dpr: number): number => {+ const y = Math.round(75 * dpr);+ const row = target.ctx.getImageData(Math.round(40 * dpr), y, Math.round(20 * dpr), 1).data;+ let white = 0;+ for (let i = 0; i < row.length; i += 4) {+ if (row[i] === 255 && row[i + 1] === 255 && row[i + 2] === 255 && row[i + 3] === 255) {+ white += 1;+ }+ }+ return white;+};++describe('overlay chrome across device-pixel ratios', () => {+ it('keeps handle sizes constant in CSS pixels at DPR 1, 1.5 and 2', () => {+ const cssWidths = [1, 1.5, 2].map((dpr) => whiteRunAt(renderAt(dpr).target, dpr) / dpr);++ expect(cssWidths[0]).toBeGreaterThan(0);+ for (const width of cssWidths) {+ expect(Math.abs(width - cssWidths[0]!)).toBeLessThanOrEqual(1);+ }+ });++ it('draws the rotation knob where pointer hit testing finds the rotate target', () => {+ for (const dpr of [1, 1.5, 2]) {+ const { target, viewport } = renderAt(dpr);+ // The knob is the only white fill between the canvas top and the north scale handle (top edge at 46 CSS px).+ const x = Math.round(75 * dpr);+ const column = target.ctx.getImageData(x, 0, 1, Math.floor(44 * dpr)).data;+ const whiteRows: number[] = [];+ for (let row = 0; row < column.length / 4; row += 1) {+ if (column[row * 4] === 255 && column[row * 4 + 1] === 255 && column[row * 4 + 3] === 255) {+ whiteRows.push(row);+ }+ }+ expect(whiteRows.length).toBeGreaterThan(0);+ const knobCss = { x: 75, y: (whiteRows[0]! + whiteRows.at(-1)!) / 2 / dpr };++ expect(+ transformTargetAt({+ point: knobCss,+ rect: RECT,+ toScreen: (point) => viewport.documentToScreen(point),+ transform: IDENTITY_TRANSFORM,+ })+ ).toEqual({ handle: 'n', kind: 'rotate' });+ expect(Math.abs(knobCss.y - (50 - 18))).toBeLessThanOrEqual(1);+ }+ });++ it('sizes the backing store by a fractional or sub-one ratio and maps the view through the same ratio', () => {+ for (const dpr of [0.75, 1.5]) {+ const { target, viewport } = renderAt(dpr);+ expect(viewport.getDpr()).toBe(dpr);+ expect(target.width).toBe(Math.round(CSS_SIZE * dpr));+ expect(viewport.viewMatrix(viewport.getDpr()).a).toBe(dpr);+ }+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.tsindex cc9fd720ec..35cbc5001c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts@@ -16,7 +16,9 @@ const findSet = (log: RasterCallLogEntry[], prop: string): unknown[] =>const baseState = (overrides: Partial<OverlayState> = {}): OverlayState => ({bbox: BBOX,+ dpr: 1,view: identity(),+ viewportSize: { height: 200, width: 200 },...overrides,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 39b5925f4c..5af03155d5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -1,12 +1,13 @@/**- * Interaction overlays render in screen space through `view`, keeping strokes and handles constant-sized at any- * zoom. The unbounded plane has no document outline; all drawing uses {@link RasterSurface} contexts.+ * Interaction overlays render in CSS pixels through `view` under a device-pixel-ratio base transform, keeping+ * strokes and handles constant in CSS pixels at any zoom and DPR, where pointer hit testing measures them. The+ * unbounded plane has no document outline; all drawing uses {@link RasterSurface} contexts.*/import type { ParametricShapeKind } from '@workbench/canvas-engine/contracts';import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';-import { applyToPoint, getScale, invert } from '@workbench/canvas-engine/math/mat2d';+import { applyToPoint, getScale, invert, multiply } from '@workbench/canvas-engine/math/mat2d';import { transformBounds } from '@workbench/canvas-engine/math/rect';import { buildParametricShapePath } from '@workbench/canvas-engine/render/rasterizers/shapeRasterizer';import { drawMarchingAnts, type MarchingAntsRender } from '@workbench/canvas-engine/selection/marchingAnts';@@ -56,8 +57,12 @@ export interface RectShapePreview {/** Everything the overlay needs to draw a frame. */export interface OverlayState {- /** Document→screen transform. */+ /** Document→CSS-pixel transform. */view: Mat2d;+ /** Backing-store pixels per CSS pixel. */+ dpr: number;+ /** The viewport in CSS pixels. */+ viewportSize: { readonly width: number; readonly height: number };/** Generation bounding box in document space. */bbox: Rect;/** Whether to draw the eight bbox resize handles (bbox tool active). */@@ -137,7 +142,7 @@ const strokeRectScreen = (ctx: Ctx, screenRect: Rect): void => {* Project viewport bounds into document space and snap outward to grid cells for seamless pan/zoom. Skip overly* dense grids; never clip to document bounds.*/-const drawGrid = (ctx: Ctx, state: OverlayState, target: RasterSurface): void => {+const drawGrid = (ctx: Ctx, state: OverlayState): void => {const gridSize = state.gridSize ?? 0;if (gridSize <= 0) {return;@@ -155,9 +160,9 @@ const drawGrid = (ctx: Ctx, state: OverlayState, target: RasterSurface): void =>// Document-space bounds of the viewport's four screen corners.const corners = [applyToPoint(inv, { x: 0, y: 0 }),- applyToPoint(inv, { x: target.width, y: 0 }),- applyToPoint(inv, { x: 0, y: target.height }),- applyToPoint(inv, { x: target.width, y: target.height }),+ applyToPoint(inv, { x: state.viewportSize.width, y: 0 }),+ applyToPoint(inv, { x: 0, y: state.viewportSize.height }),+ applyToPoint(inv, { x: state.viewportSize.width, y: state.viewportSize.height }),];const xs = corners.map((p) => p.x);const ys = corners.map((p) => p.y);@@ -401,19 +406,19 @@ const SAM_EXCLUDE_COLOR = '#ef4444';const SAM_POINT_RADIUS_PX = 5;const SAM_HANDLE_DRAW_PX = 8;-const drawSamPreview = (ctx: Ctx, state: OverlayState): void => {+const drawSamPreview = (ctx: Ctx, state: OverlayState, base: Mat2d): void => {const preview = state.samPreview;if (!preview) {return;}- const { view } = state;+ const placed = multiply(base, state.view);ctx.save();- ctx.setTransform(view.a, view.b, view.c, view.d, view.e, view.f);+ ctx.setTransform(placed.a, placed.b, placed.c, placed.d, placed.e, placed.f);ctx.globalAlpha = preview.opacity;ctx.drawImage(preview.surface.canvas, preview.rect.x, preview.rect.y, preview.rect.width, preview.rect.height);ctx.restore();if (preview.outline) {- drawMarchingAnts(ctx, state.view, { matrix: null, paths: [preview.outline], phase: preview.phase });+ drawMarchingAnts(ctx, state.view, { matrix: null, paths: [preview.outline], phase: preview.phase }, base);}};@@ -460,7 +465,7 @@ const drawSamGeometry = (ctx: Ctx, state: OverlayState): void => {* Even-odd viewport/bbox fill shades outside the generation frame; globalAlpha controls opacity independently of* theme color.*/-const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState, target: RasterSurface): void => {+const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState): void => {if (!state.bboxOverlay) {return;}@@ -469,7 +474,7 @@ const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState, target: RasterSurfactx.globalAlpha = BBOX_OVERLAY_ALPHA;ctx.fillStyle = state.bboxOverlayColor ?? BBOX_OVERLAY_FILL;ctx.beginPath();- ctx.rect(0, 0, target.width, target.height);+ ctx.rect(0, 0, state.viewportSize.width, state.viewportSize.height);ctx.rect(bboxScreen.x, bboxScreen.y, bboxScreen.width, bboxScreen.height);ctx.fill('evenodd');ctx.restore();@@ -517,20 +522,22 @@ const drawBboxHandles = (ctx: Ctx, state: OverlayState): void => {ctx.restore();};-/** Clears and redraws the entire overlay for the given `state`. */+/** Clears the backing store, then redraws the overlay in CSS pixels under the state's device-pixel ratio. */export const renderOverlay = (target: RasterSurface, state: OverlayState): void => {const ctx = target.ctx;+ const base: Mat2d = { a: state.dpr, b: 0, c: 0, d: state.dpr, e: 0, f: 0 };ctx.save();ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, target.width, target.height);+ ctx.setTransform(base.a, base.b, base.c, base.d, base.e, base.f);// Shade outside bbox first, then draw overlay chrome above it. The unbounded plane has no document outline.- drawBboxOverlayShade(ctx, state, target);+ drawBboxOverlayShade(ctx, state);// Grid next (behind the bbox), spanning the whole viewport.if (state.showGrid) {- drawGrid(ctx, state, target);+ drawGrid(ctx, state);}// Rule-of-thirds guides sit inside the bbox, behind its frame.@@ -544,13 +551,13 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): voidctx.setLineDash([]);}- drawSamPreview(ctx, state);+ drawSamPreview(ctx, state, base);drawSamGeometry(ctx, state);drawLayerOutline(ctx, state);drawBboxHandles(ctx, state);drawTransformFrame(ctx, state);if (state.marchingAnts) {- drawMarchingAnts(ctx, state.view, state.marchingAnts);+ drawMarchingAnts(ctx, state.view, state.marchingAnts, base);}drawLassoPreview(ctx, state);drawRectShapePreview(ctx, state, state.marqueePreview);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.tsindex 5db859eb45..1cf08853ab 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@@ -314,7 +314,7 @@ describe('damage coalescing', () => {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)]);+ expect(flagsOf(render).damage).toEqual({ kind: 'regions', regions: [damage('a', 0), damage('a', 40)] });});it('keeps overlay-only invalidations from widening the frame', () => {@@ -324,7 +324,7 @@ describe('damage coalescing', () => {scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });scheduler.invalidate({ overlay: true });raf.flush();- expect(flagsOf(render).damage).toEqual([damage('a', 0)]);+ expect(flagsOf(render).damage).toEqual({ kind: 'regions', regions: [damage('a', 0)] });});it.each([@@ -336,7 +336,7 @@ describe('damage coalescing', () => {scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });scheduler.invalidate(payload);raf.flush();- expect(flagsOf(render).damage).toBeNull();+ expect(flagsOf(render).damage).toEqual({ kind: 'full' });});it('stays widened once something in the frame could not name its damage', () => {@@ -344,7 +344,14 @@ describe('damage coalescing', () => {scheduler.invalidate({ view: true });scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });raf.flush();- expect(flagsOf(render).damage).toBeNull();+ expect(flagsOf(render).damage).toEqual({ kind: 'full' });+ });++ it('reports no composite damage for an overlay-only frame', () => {+ const { raf, render, scheduler } = setup();+ scheduler.invalidate({ overlay: true });+ raf.flush();+ expect(flagsOf(render).damage).toEqual({ kind: 'none' });});it('ignores damage that does not name the single invalidated layer', () => {@@ -353,25 +360,25 @@ describe('damage coalescing', () => {const { raf, render, scheduler } = setup();scheduler.invalidate({ damage: damage('a', 0), layers: ['a', 'b'] });raf.flush();- expect(flagsOf(render).damage).toBeNull();+ expect(flagsOf(render).damage).toEqual({ kind: 'full' });});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();+ expect(flagsOf(render).damage).toEqual({ kind: 'full' });});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();+ expect(flagsOf(render).damage).toEqual({ kind: 'full' });render.mockClear();scheduler.invalidate({ damage: damage('a', 0), layers: ['a'] });raf.flush();- expect(flagsOf(render).damage).toEqual([damage('a', 0)]);+ expect(flagsOf(render).damage).toEqual({ kind: 'regions', regions: [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.tsindex 500739352f..0a2dc205ab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts@@ -3,7 +3,9 @@* tests; default browser functions resolve lazily.*/-import type { LayerDamage, RenderFlags } from '@workbench/canvas-engine/types';+import type { FrameDamage, LayerDamage, RenderFlags } from '@workbench/canvas-engine/types';++import { FULL_DAMAGE, NO_DAMAGE } from '@workbench/canvas-engine/types';/** The partial invalidation payload accepted by {@link RenderScheduler.invalidate}. */export interface InvalidatePayload {@@ -53,12 +55,19 @@ export interface RenderScheduler {const createEmptyFlags = (): RenderFlags => ({all: false,- damage: [],+ damage: NO_DAMAGE,layers: new Set<string>(),overlay: false,view: false,});+const addDamage = (pending: FrameDamage, damage: LayerDamage | null): FrameDamage => {+ if (!damage || pending.kind === 'full') {+ return FULL_DAMAGE;+ }+ return { kind: 'regions', regions: pending.kind === 'regions' ? [...pending.regions, damage] : [damage] };+};+const hasPending = (flags: RenderFlags): boolean => flags.all || flags.view || flags.overlay || flags.layers.size > 0;const defaultRequestFrame = (callback: FrameRequestCallback): number => globalThis.requestAnimationFrame(callback);@@ -132,12 +141,12 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderSchedule// performance for correctness.if (payload.all) {pending.all = true;- pending.damage = null;+ pending.damage = FULL_DAMAGE;}if (payload.view) {// The whole viewport moves under a pan/zoom; no layer-local rect survives it.pending.view = true;- pending.damage = null;+ pending.damage = FULL_DAMAGE;}if (payload.overlay) {// The overlay is its own canvas, redrawn whole every frame — it neither@@ -152,11 +161,7 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderSchedulepayload.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);- }+ pending.damage = addDamage(pending.damage, damage);}schedule();};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.tsindex 9bc8ec55c7..ff4d924afc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts@@ -7,7 +7,9 @@import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d } from '@workbench/canvas-engine/types';-import { getScale, multiply } from '@workbench/canvas-engine/math/mat2d';+import { getScale, identity, multiply } from '@workbench/canvas-engine/math/mat2d';++const IDENTITY = identity();/** Dash length in screen pixels; the offset advances by {@link ANTS_STEP_PX} per tick. */export const ANTS_DASH_PX = 4;@@ -32,11 +34,20 @@ export interface MarchingAntsRender {matrix?: Mat2d | null;}-export const drawMarchingAnts = (ctx: RasterSurface['ctx'], view: Mat2d, render: MarchingAntsRender): void => {+/**+ * `view` maps document to CSS pixels; `base` maps CSS to backing pixels, so dash and width stay CSS-constant at any+ * device-pixel ratio.+ */+export const drawMarchingAnts = (+ ctx: RasterSurface['ctx'],+ view: Mat2d,+ render: MarchingAntsRender,+ base: Mat2d = IDENTITY+): void => {if (render.paths.length === 0) {return;}- const transform = render.matrix ? multiply(view, render.matrix) : view;+ const transform = multiply(base, render.matrix ? multiply(view, render.matrix) : view);// Line width and dash stay screen-constant, so they follow the VIEW scale// only — a float scaled up must not thicken its own outline.const scale = getScale(view) || 1;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.tsindex 282d52e4c1..4de906e532 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts@@ -88,13 +88,22 @@ export interface RenderFlags {overlay: boolean;/** Force a full repaint, ignoring the other flags. */all: boolean;- /**- * Partial damage requires every contributing invalidation to name a region; null/default or any unknown damage- * forces full repaint.- */- damage: LayerDamage[] | null;+ /** What of the composite must be repainted; any invalidation without a region widens it to full. */+ damage: FrameDamage;}+/**+ * Composite repaint extent: everything, nothing visible, or the screen bounds of layer-local regions. Regions that+ * resolve offscreen repaint nothing.+ */+export type FrameDamage =+ | { readonly kind: 'full' }+ | { readonly kind: 'none' }+ | { readonly kind: 'regions'; readonly regions: readonly LayerDamage[] };++export const FULL_DAMAGE: FrameDamage = { kind: 'full' };+export const NO_DAMAGE: FrameDamage = { kind: 'none' };+/** Changed region in layer-local coordinates; compositor applies the effective layer matrix to reach screen space. */export interface LayerDamage {layerId: string;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.tsindex 0d862e44e8..e9f52792a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts@@ -97,6 +97,16 @@ describe('createViewport', () => {expect(vp.getState().pan).toEqual({ x: 15, y: 1 });});+ it('keeps sub-one and fractional ratios and reads an invalid ratio as one', () => {+ const vp = createViewport();+ vp.setViewportSize(800, 600, 0.75);+ expect(vp.getDpr()).toBe(0.75);+ vp.setViewportSize(800, 600, 1.25);+ expect(vp.getDpr()).toBe(1.25);+ vp.setViewportSize(800, 600, 0);+ expect(vp.getDpr()).toBe(1);+ });+it('setViewportSize clamps dpr to the max and notifies on change', () => {const vp = createViewport();const listener = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.tsindex acdec5c162..3fb186dffb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts@@ -53,7 +53,7 @@ export interface Viewport {panBy(screenDelta: Vec2): void;/** Centers and zooms to fit `documentRect` within `viewportSize` (minus `padding`). */fitToView(documentRect: Rect, viewportSize: Size, padding?: number): void;- /** Records the CSS viewport size and device-pixel ratio (dpr clamped to {@link MAX_DPR}). */+ /** Records the CSS viewport size and device-pixel ratio (capped at {@link MAX_DPR}; invalid ratios read as 1). */setViewportSize(width: number, height: number, dpr: number): void;/** Subscribes to any view change. Returns an unsubscribe function. */subscribe(listener: () => void): () => void;@@ -123,7 +123,8 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {};const setViewportSize = (width: number, height: number, nextDpr: number): void => {- const clampedDpr = Math.max(1, Math.min(MAX_DPR, nextDpr));+ // Ratios below one (browser zoom-out) are real: the backing store must not exceed the device pixels.+ const clampedDpr = Number.isFinite(nextDpr) && nextDpr > 0 ? Math.min(MAX_DPR, nextDpr) : 1;if (size.width === width && size.height === height && dpr === clampedDpr) {return;}