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
feat(canvas): add reusable raster composite export
joshistoast48698e599926
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.tsindex 76da74455c..a7c087ca65 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts@@ -3,6 +3,7 @@ import type { WorkbenchAction } from '@workbench/workbenchState';import type { CanvasEditGate } from './editGate';import type { EngineStores } from './engineStores';+import type { RasterCompositeExportRequest, RasterCompositeExportResult } from './exportRasterComposite';import type { RasterSurface } from './render/raster';import type { Rect, ToolId, Vec2 } from './types';import type { Viewport } from './viewport';@@ -59,11 +60,18 @@ export interface CanvasPreviewCapability {export interface CanvasExportCapability {captureLayerExportGuard(layerId: string): LayerExportGuard | null;exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;+ exportRasterComposite(request: RasterCompositeExportRequest): Promise<RasterCompositeExportResult>;getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;hasExportableLayerContent(layerId: string): boolean;isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;}+export type {+ RasterCompositeExportRequest,+ RasterCompositeExportResult,+ RasterCompositeExportSnapshot,+} from './exportRasterComposite';+export interface ExportLayerPixelsOptions {includeDisabled?: boolean;applyAdjustments?: boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 6175c5bfc4..452692d9af 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -103,6 +103,11 @@ import { RenderController } from '@workbench/canvas-engine/controllers/renderConimport { StructuralLayerController } from '@workbench/canvas-engine/controllers/structuralLayerController';import { createCanvasDiagnostics, type CanvasDiagnosticsSnapshot } from '@workbench/canvas-engine/diagnostics';import { createEngineStores, type EngineStores, type TextToolOptions } from '@workbench/canvas-engine/engineStores';+import {+ exportRasterComposite as exportRasterCompositeWithDeps,+ type RasterCompositeExportRequest,+ type RasterCompositeExportSnapshot,+} from '@workbench/canvas-engine/exportRasterComposite';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';@@ -2664,6 +2669,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetLayerSurface: getLayerSurfaceForExport,uploadImage: (blob) => opts.uploadImage(blob),});+ const exportRasterComposite = (request: RasterCompositeExportRequest) =>+ exportRasterCompositeWithDeps(request, {+ backend,+ captureSnapshot: (): RasterCompositeExportSnapshot => ({+ document: mirror.getDocument(),+ documentGeneration: rasterController.getDocumentGeneration(),+ }),+ getLayerSurface: getLayerSurfaceForExport,+ isSnapshotCurrent: (snapshot) =>+ !disposed &&+ store.getState().activeProjectId === projectId &&+ snapshot.document === mirror.getDocument() &&+ snapshot.documentGeneration === rasterController.getDocumentGeneration(),+ });const surface: CanvasSurfaceCapability = { attach, detach, resize };const viewportCapability: CanvasViewportCapability = { fitToView, getViewport, setBboxGrid };const historyCapability: CanvasHistoryCapability = { clearHistory, redo, undo };@@ -2847,6 +2866,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCexportBakedLayerBlob,exportBakedLayerPixels,exportLayerPixels: rasterizeLayerPixels,+ exportRasterComposite,exportRasterLayersToPsd,extractMaskedArea,getCompositeExecutorDeps,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.tsnew file mode 100644index 0000000000..13ea484ce4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts@@ -0,0 +1,113 @@+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';+import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/types';++import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { describe, expect, it, vi } from 'vitest';++import type { ExportRasterCompositeDeps, RasterCompositeExportSnapshot } from './exportRasterComposite';++import { exportRasterComposite } from './exportRasterComposite';++const imageRef = (imageName: string, width = 64, height = 32): CanvasImageRef => ({ height, imageName, width });++const rasterLayer = (id: string): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: imageRef(id), type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -4, y: 8 },+ type: 'raster',+});++const controlLayer = (id: string): CanvasLayerContract => ({+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: imageRef(id), type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: false,+});++const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 128, width: 128, x: 0, y: 0 },+ height: 128,+ layers,+ selectedLayerId: null,+ version: 2,+ width: 128,+});++const makeDeps = (document: CanvasDocumentContractV2) => {+ const stub = createTestStubRasterBackend();+ const snapshot: RasterCompositeExportSnapshot = { document, documentGeneration: 1 };+ const encodeSurface = vi.fn((surface: RasterSurface, type?: string) => stub.encodeSurface(surface, type));+ const deps: ExportRasterCompositeDeps = {+ backend: {+ createSurface: (width, height) => stub.createSurface(width, height),+ encodeSurface,+ },+ captureSnapshot: vi.fn(() => snapshot),+ getLayerSurface: vi.fn(() =>+ Promise.resolve({+ rect: { height: 32, width: 64, x: 0, y: 0 },+ surface: stub.createSurface(64, 32),+ })+ ),+ isSnapshotCurrent: vi.fn(() => true),+ };+ return { deps, encodeSurface };+};++describe('exportRasterComposite', () => {+ it('exports tight content as a PNG without uploading it', async () => {+ const { deps, encodeSurface } = makeDeps(makeDoc([rasterLayer('raster')]));++ const result = await exportRasterComposite({ bounds: 'content' }, deps);++ expect(result).toMatchObject({ status: 'ok', rect: { x: -4, y: 8, width: 64, height: 32 } });+ expect(encodeSurface).toHaveBeenCalledOnce();+ expect(encodeSurface).toHaveBeenCalledWith(expect.anything(), 'image/png');+ expect(deps).not.toHaveProperty('uploadImage');+ });++ it('exports the exact requested bbox', async () => {+ const { deps } = makeDeps(makeDoc([rasterLayer('raster')]));+ const bbox: Rect = { height: 48, width: 96, x: 12, y: -6 };++ await expect(exportRasterComposite({ bounds: 'rect', rect: bbox }, deps)).resolves.toMatchObject({+ status: 'ok',+ rect: bbox,+ });+ });++ it('returns empty when the document has no enabled raster content', async () => {+ const { deps: noContentDeps } = makeDeps(makeDoc([controlLayer('control')]));++ await expect(exportRasterComposite({ bounds: 'content' }, noContentDeps)).resolves.toEqual({ status: 'empty' });+ });++ it('returns empty for a zero-area requested rect', async () => {+ const { deps } = makeDeps(makeDoc([rasterLayer('raster')]));++ await expect(+ exportRasterComposite({ bounds: 'rect', rect: { x: 0, y: 0, width: 0, height: 32 } }, deps)+ ).resolves.toEqual({ status: 'empty' });+ });++ it('discards an encoded blob if the document changes during export', async () => {+ const { deps } = makeDeps(makeDoc([rasterLayer('raster')]));+ vi.mocked(deps.isSnapshotCurrent).mockReturnValueOnce(true).mockReturnValue(false);++ await expect(exportRasterComposite({ bounds: 'content' }, deps)).resolves.toEqual({ status: 'stale' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.tsnew file mode 100644index 0000000000..9306002547--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts@@ -0,0 +1,67 @@+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';+import type { CanvasDocumentContractV2 } from '@workbench/types';++import { isEmpty } from '@workbench/canvas-engine/math/rect';+import {+ getBaseRasterContentBounds,+ planBaseRasterComposite,+ renderRasterComposite,+ type RenderRasterCompositeDeps,+} from '@workbench/canvas-engine/render/rasterComposite';++export type RasterCompositeExportRequest = { bounds: 'content' } | { bounds: 'rect'; rect: Rect };++export type RasterCompositeExportResult =+ | { status: 'ok'; blob: Blob; rect: Rect }+ | { status: 'empty' | 'stale' | 'not-ready' };++export interface RasterCompositeExportSnapshot {+ document: CanvasDocumentContractV2 | null;+ documentGeneration: number;+}++export interface ExportRasterCompositeDeps extends RenderRasterCompositeDeps {+ backend: RenderRasterCompositeDeps['backend'] & {+ encodeSurface(surface: RasterSurface, type?: string): Promise<Blob>;+ };+ captureSnapshot(): RasterCompositeExportSnapshot;+ isSnapshotCurrent(snapshot: RasterCompositeExportSnapshot): boolean;+}++export const exportRasterComposite = async (+ request: RasterCompositeExportRequest,+ deps: ExportRasterCompositeDeps+): Promise<RasterCompositeExportResult> => {+ const snapshot = deps.captureSnapshot();+ const document = snapshot.document;+ if (!document) {+ return { status: 'not-ready' };+ }++ const rect = request.bounds === 'content' ? getBaseRasterContentBounds(document) : request.rect;+ if (!rect || isEmpty(rect)) {+ return { status: 'empty' };+ }++ const entry = planBaseRasterComposite(document, rect);+ if (entry.layers.length === 0) {+ return { status: 'empty' };+ }++ let surface: RasterSurface;+ try {+ surface = await renderRasterComposite(entry, deps);+ } catch (error) {+ if (!deps.isSnapshotCurrent(snapshot)) {+ return { status: 'stale' };+ }+ throw error;+ }+ if (!deps.isSnapshotCurrent(snapshot)) {+ return { status: 'stale' };+ }++ const blob = await deps.backend.encodeSurface(surface, 'image/png');+ return deps.isSnapshotCurrent(snapshot) ? { status: 'ok', blob, rect } : { status: 'stale' };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.tsnew file mode 100644index 0000000000..ed392ee353--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -0,0 +1,244 @@+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Mat2d, Rect } from '@workbench/canvas-engine/types';+import type {+ CanvasAdjustmentsContract,+ CanvasBlendMode,+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+ CanvasRasterLayerContractV2,+} from '@workbench/types';++import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';+import { 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';++type Ctx = RasterSurface['ctx'];++/** The engine-owned structural subset needed to plan and render a raster layer contribution. */+export interface CompositeLayerRef {+ id: string;+ sourceRef: string;+ contentSize: { width: number; height: number };+ contentOffset: { x: number; y: number };+ transform: { x: number; y: number; scaleX: number; scaleY: number; rotation: number };+ opacity: number;+ blendMode: CanvasBlendMode;+ adjustments?: CanvasAdjustmentsContract;+}++/** The engine-owned structural subset consumed by the raster compositor. */+export interface CompositeEntry {+ bbox: Rect;+ layers: readonly CompositeLayerRef[];+}++export interface BaseRasterCompositeEntry extends CompositeEntry {+ key: string;+ kind: 'base-raster';+ layers: CompositeLayerRef[];+}++export interface RenderRasterCompositeDeps {+ backend: {+ createSurface(width: number, height: number): RasterSurface;+ };+ getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect }>;+ readImageData?(surface: RasterSurface, rect: Rect): ImageData;+ writeImageData?(surface: RasterSurface, imageData: ImageData, x: number, y: number): void;+}++const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>+ surface.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);++const defaultWriteImageData = (surface: RasterSurface, imageData: ImageData, x: number, y: number): void =>+ surface.ctx.putImageData(imageData, x, y);++/** True when a layer is an enabled raster layer with rasterizable, non-empty pixels. */+const isBaseRasterLayer = (layer: CanvasLayerContract): layer is CanvasRasterLayerContractV2 => {+ if (!layer.isEnabled || layer.type !== 'raster') {+ return false;+ }+ if (layer.source.type === 'image') {+ return true;+ }+ return layer.source.type === 'paint' && layer.source.bitmap !== null;+};++/** A stable string identifying a source's pixels (its asset name, or an empty sentinel). */+const sourceRefOf = (source: CanvasLayerSourceContract): string => {+ switch (source.type) {+ case 'image':+ return `image:${source.image.imageName}`;+ case 'paint':+ return source.bitmap ? `paint:${source.bitmap.imageName}` : 'paint:empty';+ default:+ return `${source.type}:unsupported`;+ }+};++/** The native (unscaled) content rect of a base-raster layer's source (layer-local). */+const contentRectOf = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV2): Rect => {+ const { source } = layer;+ if (source.type === 'image') {+ return { height: source.image.height, width: source.image.width, x: 0, y: 0 };+ }+ if (source.type === 'paint' && source.bitmap) {+ const offset = source.offset ?? { x: 0, y: 0 };+ return { height: source.bitmap.height, width: source.bitmap.width, x: offset.x, y: offset.y };+ }+ return { height: doc.height, width: doc.width, x: 0, y: 0 };+};++/** Projects a document layer into its frozen composite contribution. */+const toLayerRef = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV2): CompositeLayerRef => {+ const rect = contentRectOf(layer, doc);+ const hasAdjustments = !isIdentityAdjustments(layer.adjustments);+ return {+ blendMode: layer.blendMode,+ contentOffset: { x: rect.x, y: rect.y },+ contentSize: { height: rect.height, width: rect.width },+ id: layer.id,+ opacity: layer.opacity,+ sourceRef: sourceRefOf(layer.source),+ ...(hasAdjustments && layer.adjustments ? { adjustments: layer.adjustments } : {}),+ transform: {+ rotation: layer.transform.rotation,+ scaleX: layer.transform.scaleX,+ scaleY: layer.transform.scaleY,+ x: layer.transform.x,+ y: layer.transform.y,+ },+ };+};++const rectKey = (rect: Rect): string => `${rect.x},${rect.y},${rect.width},${rect.height}`;++const layerKey = (ref: CompositeLayerRef): string => {+ const t = ref.transform;+ const o = ref.contentOffset;+ return [+ ref.id,+ ref.sourceRef,+ o.x,+ o.y,+ t.x,+ t.y,+ t.scaleX,+ t.scaleY,+ t.rotation,+ ref.opacity,+ ref.blendMode,+ ref.adjustments ? adjustmentsKey(ref.adjustments) : '-',+ ].join(':');+};++/** Union of the provided composite-layer bounds in document space, or `null` when empty. */+export const getCompositeLayerBounds = (layers: readonly CompositeLayerRef[]): Rect | null => {+ let bounds: Rect | null = null;+ for (const ref of layers) {+ const nativeRect: Rect = {+ height: ref.contentSize.height,+ width: ref.contentSize.width,+ x: ref.contentOffset.x,+ y: ref.contentOffset.y,+ };+ const layerBounds = transformBounds(layerMatrix(ref), nativeRect);+ bounds = bounds === null ? layerBounds : union(bounds, layerBounds);+ }+ return bounds;+};++/** Plans the enabled base-raster layers over an exact document-space rectangle. */+export const planBaseRasterComposite = (document: CanvasDocumentContractV2, rect: Rect): BaseRasterCompositeEntry => {+ const layers = document.layers.filter(isBaseRasterLayer).map((layer) => toLayerRef(layer, document));+ return {+ bbox: rect,+ key: `base-raster|${rectKey(rect)}|${layers.map(layerKey).join('|')}`,+ kind: 'base-raster',+ layers,+ };+};++/** Tight outward-rounded bounds of all enabled raster content in the document. */+export const getBaseRasterContentBounds = (document: CanvasDocumentContractV2): Rect | null => {+ const bounds = getCompositeLayerBounds(planBaseRasterComposite(document, document.bbox).layers);+ return bounds === null ? null : roundOut(bounds);+};++/** Document→bbox translate matrix (the "view" the entry is composited under). */+const bboxView = (bbox: Rect): Mat2d => ({ a: 1, b: 0, c: 0, d: 1, e: -bbox.x, f: -bbox.y });++/** Applies a matrix to a 2D context's transform. */+const setTransform = (ctx: Ctx, m: Mat2d): void => {+ ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);+};++/** The layer's local→document transform matrix. */+const layerMatrix = (ref: CompositeLayerRef): Mat2d =>+ fromTRS(+ { x: ref.transform.x, y: ref.transform.y },+ ref.transform.rotation,+ ref.transform.scaleX,+ ref.transform.scaleY+ );++/** Composites an entry's layers, in z-order, onto a fresh bbox-sized surface. */+export const renderRasterComposite = async (+ entry: CompositeEntry,+ deps: RenderRasterCompositeDeps+): Promise<RasterSurface> => {+ const { bbox } = entry;+ const width = Math.max(0, bbox.width);+ const height = Math.max(0, bbox.height);+ const surface = deps.backend.createSurface(width, height);+ const ctx = surface.ctx;+ const readImageData = deps.readImageData ?? defaultReadImageData;+ const writeImageData = deps.writeImageData ?? defaultWriteImageData;++ setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ ctx.clearRect(0, 0, surface.width, surface.height);++ const view = bboxView(bbox);+ // Layers are stored top-first (index 0 = top-most); draw bottom→top.+ for (let i = entry.layers.length - 1; i >= 0; i--) {+ const ref = entry.layers[i];+ if (!ref) {+ continue;+ }+ const layerSurface = await deps.getLayerSurface(ref.id);+ if (ref.adjustments) {+ // Bake non-destructive adjustments so the generated image matches what the+ // user sees: render this layer alone into a bbox temp, apply the LUTs, then+ // composite the adjusted temp with the layer's opacity/blend.+ const temp = deps.backend.createSurface(width, height);+ const tempCtx = temp.ctx;+ setTransform(tempCtx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ tempCtx.clearRect(0, 0, width, height);+ setTransform(tempCtx, multiply(view, layerMatrix(ref)));+ tempCtx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);+ const fullRect: Rect = { height, width, x: 0, y: 0 };+ const pixels = readImageData(temp, fullRect);+ applyAdjustments(pixels, ref.adjustments);+ writeImageData(temp, pixels, 0, 0);+ ctx.save();+ setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ ctx.globalAlpha = ref.opacity;+ ctx.globalCompositeOperation = blendToComposite(ref.blendMode);+ ctx.drawImage(temp.canvas, 0, 0);+ ctx.restore();+ continue;+ }+ ctx.save();+ ctx.globalAlpha = ref.opacity;+ ctx.globalCompositeOperation = blendToComposite(ref.blendMode);+ setTransform(ctx, multiply(view, layerMatrix(ref)));+ // Draw the cache at its layer-local content origin (content-sized paint+ // layers place their pixels off-zero).+ ctx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);+ ctx.restore();+ }++ return surface;+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.tsindex 0b31d3f870..2e23c3b2f7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts@@ -28,17 +28,11 @@import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';-import type {- CompositeEntry,- CompositeLayerRef,- CompositeMaskLayerRef,- CompositePlan,-} from '@workbench/generation/canvas/types';+import type { CompositeEntry, CompositeMaskLayerRef, CompositePlan } from '@workbench/generation/canvas/types';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';-import { transformBounds, union } from '@workbench/canvas-engine/math/rect';-import { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';-import { blendToComposite } from '@workbench/canvas-engine/render/compositor';+import { renderRasterComposite } from '@workbench/canvas-engine/render/rasterComposite';+import { getCompositeLayerBounds } from '@workbench/generation/canvas/compositePlan';type Ctx = RasterSurface['ctx'];@@ -148,15 +142,6 @@ const setTransform = (ctx: Ctx, m: Mat2d): void => {ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);};-/** The layer's local→document transform matrix. */-const layerMatrix = (ref: CompositeLayerRef): Mat2d =>- fromTRS(- { x: ref.transform.x, y: ref.transform.y },- ref.transform.rotation,- ref.transform.scaleX,- ref.transform.scaleY- );-/*** Union of a plan's base-raster content bounds in document space, or `null`* when the plan has no enabled raster content. Pure geometry (no pixels, no@@ -165,23 +150,7 @@ const layerMatrix = (ref: CompositeLayerRef): Mat2d =>*/export const computeCompositeContentBounds = (plan: CompositePlan): Rect | null => {const entry = plan.entries.find((e) => e.kind === 'base-raster');- return entry ? computeContentBounds(entry.layers) : null;-};--/** Union of the entry's layer bounds in document space, or `null` when empty. */-const computeContentBounds = (layers: CompositeLayerRef[]): Rect | null => {- let bounds: Rect | null = null;- for (const ref of layers) {- const nativeRect: Rect = {- height: ref.contentSize.height,- width: ref.contentSize.width,- x: ref.contentOffset.x,- y: ref.contentOffset.y,- };- const layerBounds = transformBounds(layerMatrix(ref), nativeRect);- bounds = bounds === null ? layerBounds : union(bounds, layerBounds);- }- return bounds;+ return entry ? getCompositeLayerBounds(entry.layers) : null;};/** True when every pixel of `imageData` is fully opaque (alpha === 255). Empty → false. */@@ -198,62 +167,6 @@ const isFullyOpaque = (imageData: ImageData): boolean => {return true;};-/** Composites an entry's layers, in z-order, onto a fresh bbox-sized surface. */-const compositeEntry = async (entry: CompositeEntry, deps: ExecuteCompositePlanDeps): Promise<RasterSurface> => {- const { bbox } = entry;- const width = Math.max(0, bbox.width);- const height = Math.max(0, bbox.height);- const surface = deps.backend.createSurface(width, height);- const ctx = surface.ctx;- const readImageData = deps.readImageData ?? defaultReadImageData;- const writeImageData = deps.writeImageData ?? defaultWriteImageData;-- setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- ctx.clearRect(0, 0, surface.width, surface.height);-- const view = bboxView(bbox);- // Layers are stored top-first (index 0 = top-most); draw bottom→top.- for (let i = entry.layers.length - 1; i >= 0; i--) {- const ref = entry.layers[i];- if (!ref) {- continue;- }- const layerSurface = await deps.getLayerSurface(ref.id);- if (ref.adjustments) {- // Bake non-destructive adjustments so the generated image matches what the- // user sees: render this layer alone into a bbox temp, apply the LUTs, then- // composite the adjusted temp with the layer's opacity/blend.- const temp = deps.backend.createSurface(width, height);- const tempCtx = temp.ctx;- setTransform(tempCtx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- tempCtx.clearRect(0, 0, width, height);- setTransform(tempCtx, multiply(view, layerMatrix(ref)));- tempCtx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);- const fullRect: Rect = { height, width, x: 0, y: 0 };- const pixels = readImageData(temp, fullRect);- applyAdjustments(pixels, ref.adjustments);- writeImageData(temp, pixels, 0, 0);- ctx.save();- setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- ctx.globalAlpha = ref.opacity;- ctx.globalCompositeOperation = blendToComposite(ref.blendMode);- ctx.drawImage(temp.canvas, 0, 0);- ctx.restore();- continue;- }- ctx.save();- ctx.globalAlpha = ref.opacity;- ctx.globalCompositeOperation = blendToComposite(ref.blendMode);- setTransform(ctx, multiply(view, layerMatrix(ref)));- // Draw the cache at its layer-local content origin (content-sized paint- // layers place their pixels off-zero).- ctx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);- ctx.restore();- }-- return surface;-};-/*** Composites, scans coverage, encodes, hashes, dedupes, and (when needed)* uploads a single raster-style entry (`base-raster` or `control-layer`).@@ -282,7 +195,7 @@ const executeRasterEntry = async (};}- const surface = await compositeEntry(entry, deps);+ const surface = await renderRasterComposite(entry, deps);const bboxFullyCovered = isFullyOpaque(readImageData(surface, { height: surface.height, width: surface.width, x: 0, y: 0 }));@@ -333,7 +246,7 @@ export const executeCompositePlan = async (throw new Error('executeCompositePlan: plan has no base-raster entry');}- const contentBounds = computeContentBounds(entry.layers);+ const contentBounds = getCompositeLayerBounds(entry.layers);const { bboxFullyCovered, ...base } = await executeRasterEntry(entry, deps);return { base, bboxFullyCovered, contentBounds };diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.tsindex 08a4cd4603..cef05be6db 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.test.ts@@ -11,7 +11,12 @@ import { describe, expect, it } from 'vitest';import type { Rect } from './types';-import { planComposites, planControlComposites, planRegionalMaskComposites } from './compositePlan';+import {+ getBaseRasterContentBounds,+ planComposites,+ planControlComposites,+ planRegionalMaskComposites,+} from './compositePlan';const imageRef = (imageName: string, width = 64, height = 48): CanvasImageRef => ({ height, imageName, width });@@ -359,6 +364,25 @@ describe('planComposites — control-layer exclusion', () => {});});+describe('getBaseRasterContentBounds', () => {+ it('returns rounded transformed bounds for enabled raster content only', () => {+ const document = makeDoc([+ rasterLayer('enabled', {+ source: { image: imageRef('source', 100, 50), type: 'image' },+ transform: { rotation: 0, scaleX: 2, scaleY: 1, x: -10.25, y: 20.5 },+ }),+ { ...controlLayer('control'), isEnabled: true },+ { ...rasterLayer('disabled'), isEnabled: false },+ ]);++ expect(getBaseRasterContentBounds(document)).toEqual({ x: -11, y: 20, width: 201, height: 51 });+ });++ it('returns null when no enabled raster layer has content', () => {+ expect(getBaseRasterContentBounds(makeDoc([controlLayer('control')]))).toBeNull();+ });+});+describe('planControlComposites', () => {it('emits one separate entry per enabled control layer with content', () => {const composites = planControlComposites(makeDoc([controlLayer('c1'), controlLayer('c2')]), BBOX);diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.tsindex c612f105bf..ca5591186f 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/compositePlan.ts@@ -30,34 +30,20 @@ import type {CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasLayerSourceContract,- CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,} from '@workbench/types';-import { adjustmentsKey, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';+import { adjustmentsKey } from '@workbench/canvas-engine/render/adjustments';+import {+ getBaseRasterContentBounds,+ getCompositeLayerBounds,+ planBaseRasterComposite,+} from '@workbench/canvas-engine/render/rasterComposite';import type { CompositeEntry, CompositeLayerRef, CompositeMaskLayerRef, CompositePlan, Rect } from './types';import { DEFAULT_MASK_DENOISE_LIMIT } from './types';-/** True when a layer is an enabled raster layer with rasterizable, non-empty pixels. */-const isBaseRasterLayer = (layer: CanvasLayerContract): layer is CanvasRasterLayerContractV2 => {- if (!layer.isEnabled || layer.type !== 'raster') {- return false;- }- if (layer.source.type === 'image') {- return true;- }- // A paint layer only contributes once it holds pixels. An empty (`bitmap:- // null`) paint layer — e.g. an auto-created layer left blank after the stroke- // was undone — carries no pixels; including it would force a doc-sized- // transparent rect into the composite, so its full-bbox coverage plus scanned- // transparency reads as `outpaint` (unsupported) instead of `txt2img`. The- // orchestrator flushes pending paint uploads before planning, so a bitmap- // still `null` here really is empty rather than merely unpersisted.- return layer.source.type === 'paint' && layer.source.bitmap !== null;-};-/** A stable string identifying a source's pixels (its asset name, or an empty sentinel). */const sourceRefOf = (source: CanvasLayerSourceContract): string => {switch (source.type) {@@ -66,53 +52,10 @@ const sourceRefOf = (source: CanvasLayerSourceContract): string => {case 'paint':return source.bitmap ? `paint:${source.bitmap.imageName}` : 'paint:empty';default:- // Only image/paint layers reach the planner (filtered by isBaseRasterLayer).return `${source.type}:unsupported`;}};-/** The native (unscaled) content rect of a base-raster layer's source (layer-local). */-const contentRectOf = (- layer: CanvasRasterLayerContractV2,- doc: CanvasDocumentContractV2-): { width: number; height: number; x: number; y: number } => {- const { source } = layer;- if (source.type === 'image') {- return { height: source.image.height, width: source.image.width, x: 0, y: 0 };- }- // Paint layers are content-sized: the persisted bitmap dims at its offset. Only- // paint layers WITH a bitmap reach here (empty paint is filtered upstream), but- // default defensively to the document rect when absent.- if (source.type === 'paint' && source.bitmap) {- const offset = source.offset ?? { x: 0, y: 0 };- return { height: source.bitmap.height, width: source.bitmap.width, x: offset.x, y: offset.y };- }- return { height: doc.height, width: doc.width, x: 0, y: 0 };-};--/** Projects a document layer into its frozen composite contribution. */-const toLayerRef = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV2): CompositeLayerRef => {- const rect = contentRectOf(layer, doc);- const hasAdjustments = !isIdentityAdjustments(layer.adjustments);- return {- blendMode: layer.blendMode,- contentOffset: { x: rect.x, y: rect.y },- contentSize: { height: rect.height, width: rect.width },- id: layer.id,- opacity: layer.opacity,- sourceRef: sourceRefOf(layer.source),- // Bake non-destructive adjustments into the generated pixels (and the key).- ...(hasAdjustments && layer.adjustments ? { adjustments: layer.adjustments } : {}),- transform: {- rotation: layer.transform.rotation,- scaleX: layer.transform.scaleX,- scaleY: layer.transform.scaleY,- x: layer.transform.x,- y: layer.transform.y,- },- };-};-/** Serializes a rect into a compact, deterministic key fragment. */const rectKey = (rect: Rect): string => `${rect.x},${rect.y},${rect.width},${rect.height}`;@@ -136,9 +79,7 @@ const layerKey = (ref: CompositeLayerRef): string => {].join(':');};-/** Derives the stable identity key for a base-raster entry. */-const deriveKey = (kind: string, bbox: Rect, layers: CompositeLayerRef[]): string =>- `${kind}|${rectKey(bbox)}|${layers.map(layerKey).join('|')}`;+export { getBaseRasterContentBounds, getCompositeLayerBounds, planBaseRasterComposite };/** True when a layer is an enabled inpaint mask with persisted (non-empty) alpha. */const isActiveInpaintMaskLayer = (layer: CanvasLayerContract): layer is CanvasInpaintMaskLayerContract =>@@ -197,16 +138,7 @@ const deriveMaskKey = (kind: string, bbox: Rect, layers: CompositeMaskLayerRef[]* must NOT be treated as noise 0).*/export const planComposites = (document: CanvasDocumentContractV2, bbox: Rect): CompositePlan => {- const layers = document.layers.filter(isBaseRasterLayer).map((layer) => toLayerRef(layer, document));-- const baseEntry: CompositeEntry = {- bbox,- key: deriveKey('base-raster', bbox, layers),- kind: 'base-raster',- layers,- };-- const entries: CompositeEntry[] = [baseEntry];+ const entries: CompositeEntry[] = [planBaseRasterComposite(document, bbox)];const maskLayers = document.layers.filter(isActiveInpaintMaskLayer);