Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): add shared layer pixel export primitive

joshistoastfbceff5c70af
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index c6c2aae759..31081b84bc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -253,6 +253,61 @@ describe('createCanvasEngine', () => {
engine.dispose();
});
+ it('exportLayerPixels rasterizes a visible layer and returns its cache surface plus content rect', async () => {
+ const { engine } = createEngine();
+
+ const result = await engine.exportLayerPixels('a');
+
+ expect(result.status).toBe('ok');
+ if (result.status === 'ok') {
+ expect(result.rect).toEqual({ height: 10, width: 10, x: 0, y: 0 });
+ expect(result.surface.width).toBe(10);
+ expect(result.surface.height).toBe(10);
+ expect((result.surface as StubRasterSurface).callLog.some((entry) => entry.op === 'drawImage')).toBe(true);
+ }
+ engine.dispose();
+ });
+
+ it('exportLayerPixels refuses hidden layers unless includeDisabled is set', async () => {
+ const hidden = { ...rasterLayer('hidden'), isEnabled: false };
+ const { store } = createFakeStore({ ...makeDoc(), layers: [hidden] });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+
+ expect(await engine.exportLayerPixels('hidden')).toEqual({ status: 'disabled' });
+ expect((await engine.exportLayerPixels('hidden', { includeDisabled: true })).status).toBe('ok');
+ engine.dispose();
+ });
+
+ it('exportLayerPixels refuses a layer while its cache is already rasterizing', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const pendingResolve = createDeferred<Blob>();
+ const { store } = createReactiveStore(makeDoc());
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => pendingResolve.promise,
+ projectId: 'p1',
+ store,
+ });
+ const screen = createFakeCanvas();
+ const overlay = createFakeCanvas();
+
+ engine.attach(screen.element, overlay.element);
+ raf.flush();
+
+ expect(await engine.exportLayerPixels('a')).toEqual({ status: 'not-ready' });
+
+ pendingResolve.resolve(new Blob());
+ await flushMicrotasks();
+ engine.dispose();
+ });
+
it('setTool switches the active tool and updates the store', () => {
const { engine } = createEngine();
const listener = vi.fn();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index dfc9bb5b69..5aafd9f943 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -138,6 +138,15 @@ export type MergeVisibleResult = 'merged' | 'not-ready' | 'nothing';
*/
export type PsdExportResult = 'exported' | 'nothing' | 'too-large' | 'not-ready';
+export interface ExportLayerPixelsOptions {
+ /** Export disabled/hidden layers too. Used by PSD/save-layer actions. */
+ includeDisabled?: boolean;
+}
+
+export type ExportLayerPixelsResult =
+ | { status: 'ok'; surface: RasterSurface; rect: Rect }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' };
+
/** The minimal workbench store the engine depends on. */
export interface EngineStore {
getState(): WorkbenchState;
@@ -274,6 +283,13 @@ export interface CanvasEngine {
* the download name (extension appended if absent).
*/
exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;
+ /**
+ * Ensures one layer's pixels are rasterized in the shared layer cache and returns
+ * the cache surface plus its layer-local content rect. Read-only: no dispatches,
+ * no history entry, no document mutation. Returns `not-ready` rather than racing
+ * an already in-flight rasterize, so callers never export stale/blank pixels.
+ */
+ exportLayerPixels(layerId: string, options?: ExportLayerPixelsOptions): Promise<ExportLayerPixelsResult>;
/**
* Rasterizes a parametric (shape/gradient/text) layer to a paint layer: bakes its
* current appearance into a content-sized paint bitmap (persisted through the
@@ -1017,42 +1033,64 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
};
- /**
- * Rasterizes a single layer on demand and returns its cache surface plus the
- * content rect (layer-local origin/size) those pixels occupy, for the
- * composite-for-generation executor. Rasterize-or-throw: a missing layer, a
- * non-raster/control layer, or an unsupported source throws a descriptive error
- * rather than returning a blank surface, so an invoke can never silently drop a
- * contributing layer. Only invoked for layers the pure planner already selected
- * (enabled image/paint rasters).
- */
- const getLayerSurfaceForExport = async (layerId: string): Promise<{ surface: RasterSurface; rect: Rect }> => {
+ const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {
+ if (source.type === 'shape') {
+ return source.kind !== 'polygon';
+ }
+ return true;
+ };
+
+ const rasterizeLayerPixels = async (
+ layerId: string,
+ options: ExportLayerPixelsOptions = {}
+ ): Promise<ExportLayerPixelsResult> => {
const doc = mirror.getDocument();
if (!doc) {
- throw new Error(`Cannot rasterize layer ${layerId} for generation: no active canvas document.`);
+ return { status: 'missing' };
}
const layer = doc.layers.find((candidate) => candidate.id === layerId);
- // Raster/control layers rasterize their own source; inpaint-mask layers
- // rasterize their alpha bitmap through the shared paint view (`renderableSourceOf`),
- // so the grayscale mask composite can read a mask's alpha exactly like a paint layer.
const source = layer ? renderableSourceOf(layer) : null;
if (!layer || !source) {
- throw new Error(
- `Cannot rasterize layer ${layerId} for generation: layer is missing or has no rasterizable source.`
- );
+ return { status: 'missing' };
+ }
+ if (!options.includeDisabled && !layer.isEnabled) {
+ return { status: 'disabled' };
+ }
+ if (!isSupportedExportSource(source)) {
+ return { status: 'unsupported' };
+ }
+ const contentRect = getSourceContentRect(layer, doc);
+ if (isEmpty(contentRect)) {
+ return { status: 'empty' };
}
- if (!isRenderableLayer(layer)) {
- throw new Error(`Cannot rasterize layer ${layerId} for generation: unsupported source type "${source.type}".`);
+ if (inFlight.has(layer.id)) {
+ return { status: 'not-ready' };
}
- const entry = layerCache.getOrCreateRect(layerId, getSourceContentRect(layer, doc));
+ const entry = layerCache.getOrCreateRect(layerId, contentRect);
if (entry.stale) {
- // Rasterize synchronously into the cache; a failure (e.g. asset resolve)
- // propagates so the executor aborts with a meaningful message.
const result = await rasterizeSource(source, rasterizeDeps(doc), entry.surface);
entry.rect = result.rect;
entry.stale = false;
+ stores.thumbnailVersion.set(layer.id, layerCache.version(layer.id));
}
- return { rect: entry.rect, surface: entry.surface };
+ return { rect: entry.rect, status: 'ok', surface: entry.surface };
+ };
+
+ /**
+ * Rasterizes a single layer on demand and returns its cache surface plus the
+ * content rect (layer-local origin/size) those pixels occupy, for the
+ * composite-for-generation executor. Rasterize-or-throw: a missing layer, a
+ * non-raster/control layer, or an unsupported source throws a descriptive error
+ * rather than returning a blank surface, so an invoke can never silently drop a
+ * contributing layer. Only invoked for layers the pure planner already selected
+ * (enabled image/paint rasters).
+ */
+ const getLayerSurfaceForExport = async (layerId: string): Promise<{ surface: RasterSurface; rect: Rect }> => {
+ const result = await rasterizeLayerPixels(layerId);
+ if (result.status === 'ok') {
+ return { rect: result.rect, surface: result.surface };
+ }
+ throw new Error(`Cannot rasterize layer ${layerId} for generation: ${result.status}.`);
};
const releaseBitmapIfUnreferenced = (imageName: string): void => {
@@ -2023,22 +2061,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
* from the source.
*/
const getLayerSurfaceForPsd = async (layerId: string): Promise<{ surface: RasterSurface; rect: Rect }> => {
- const doc = mirror.getDocument();
- if (!doc) {
- throw new Error(`Cannot rasterize layer ${layerId} for PSD export: no active canvas document.`);
- }
- const layer = doc.layers.find((candidate) => candidate.id === layerId);
- const source = layer ? renderableSourceOf(layer) : null;
- if (!layer || !source) {
- throw new Error(`Cannot rasterize layer ${layerId} for PSD export: layer is missing or has no source.`);
- }
- const entry = layerCache.getOrCreateRect(layerId, getSourceContentRect(layer, doc));
- if (entry.stale) {
- const result = await rasterizeSource(source, rasterizeDeps(doc), entry.surface);
- entry.rect = result.rect;
- entry.stale = false;
+ const result = await rasterizeLayerPixels(layerId, { includeDisabled: true });
+ if (result.status === 'ok') {
+ return { rect: result.rect, surface: result.surface };
}
- return { rect: entry.rect, surface: entry.surface };
+ throw new Error(`Cannot rasterize layer ${layerId} for PSD export: ${result.status}.`);
};
const exportRasterLayersToPsd = async (fileName: string): Promise<PsdExportResult> => {
@@ -3090,6 +3117,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
drawLayerThumbnail,
eraseSelection,
exportRasterLayersToPsd,
+ exportLayerPixels: rasterizeLayerPixels,
fillSelection,
fitToView,
flushPendingUploads: () => bitmapStore.flushPendingUploads(),