Skip to content

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

fix(webv2): matte control generation over black

Josh Corbettdff9d02efc21
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index d40d3fbe26..7e2542370a 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2451,12 +2451,12 @@
"cutout": "Cutout with layer below",
"delete": "Delete layer",
"disableAutoNegative": "Disable auto-negative",
- "disableTransparencyEffect": "Disable transparency effect",
+ "disableTransparencyEffect": "Disable transparent preview",
"disabled": "Enable the layer before using this action.",
"duplicate": "Duplicate layer",
"empty": "This layer has no content.",
"enableAutoNegative": "Enable auto-negative",
- "enableTransparencyEffect": "Enable transparency effect",
+ "enableTransparencyEffect": "Enable transparent preview",
"exclude": "Exclude layer below",
"extractMaskedArea": "Extract masked area",
"fitToBbox": "Fit to bbox",
@@ -2483,7 +2483,7 @@
"toggleAutoNegative": "Toggle auto-negative",
"toggleHidden": "Show/hide on canvas",
"toggleLock": "Toggle lock",
- "toggleTransparencyEffect": "Toggle transparency effect",
+ "toggleTransparencyEffect": "Toggle transparent preview",
"toggleVisibility": "Toggle visibility",
"transform": "Transform",
"unsupported": "This action is not supported for this layer.",
@@ -2599,7 +2599,7 @@
"preview": "Preview filter",
"selectModel": "Select a model",
"stepRange": "Step range",
- "transparencyEffect": "Transparency effect",
+ "transparencyEffect": "Transparent preview",
"validation": {
"control_lora_limit": "Only one Control LoRA can be used at a time.",
"flux_fill_control_lora": "Control LoRA is not compatible with FLUX Fill.",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts
new file mode 100644
index 0000000000..60d060b043
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts
@@ -0,0 +1,70 @@
+import type { CompositeEntry } from '@workbench/canvas-operations/generationContracts';
+
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
+import { describe, expect, it } from 'vitest';
+
+import { createCompositeDedupeCache, executeControlComposite } from './compositeForGeneration';
+
+describe('executeControlComposite — real browser pixels', () => {
+ it('uploads erased transparent pixels as opaque black', async () => {
+ const backend = createDomRasterBackend();
+ const layerSurface = backend.createSurface(3, 1);
+ layerSurface.ctx.putImageData(
+ new ImageData(
+ new Uint8ClampedArray([
+ 255,
+ 255,
+ 255,
+ 255, // opaque white control edge
+ 120,
+ 80,
+ 40,
+ 128, // partially transparent antialiasing
+ 255,
+ 255,
+ 255,
+ 0, // erased pixel with non-black hidden RGB
+ ]),
+ 3,
+ 1
+ ),
+ 0,
+ 0
+ );
+ const entry: CompositeEntry = {
+ bbox: { height: 1, width: 3, x: 0, y: 0 },
+ key: 'control-layer|transparent-pixels',
+ kind: 'control-layer',
+ layerId: 'control',
+ layers: [
+ {
+ blendMode: 'normal',
+ contentOffset: { x: 0, y: 0 },
+ contentSize: { height: 1, width: 3 },
+ id: 'control',
+ opacity: 1,
+ sourceRef: 'paint:control.png',
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ },
+ ],
+ };
+ let uploadedPixels: number[] | null = null;
+
+ await executeControlComposite(entry, {
+ backend,
+ dedupe: createCompositeDedupeCache(),
+ getLayerSurface: () => Promise.resolve({ rect: { height: 1, width: 3, x: 0, y: 0 }, surface: layerSurface }),
+ hashBlob: () => Promise.resolve('control-pixels'),
+ uploadImage: async (blob) => {
+ const bitmap = await backend.createImageBitmap(blob);
+ const decoded = backend.createSurface(3, 1);
+ decoded.ctx.drawImage(bitmap, 0, 0);
+ uploadedPixels = [...decoded.ctx.getImageData(0, 0, 3, 1).data];
+ bitmap.close();
+ return { height: 1, imageName: 'control.png', width: 3 };
+ },
+ });
+
+ expect(uploadedPixels).toEqual([255, 255, 255, 255, 60, 40, 20, 255, 0, 0, 0, 255]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts
index f36c43f130..7ae3dd2633 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts
@@ -1,4 +1,5 @@
import type {
+ CanvasControlLayerContract,
CanvasDocumentContractV2,
CanvasImageRef,
CanvasLayerContract,
@@ -10,7 +11,7 @@ import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.t
import type { Rect } from '@workbench/canvas-operations/generationContracts';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
-import { planComposites } from '@workbench/canvas-operations/generationCompositePlan';
+import { planComposites, planControlComposites } from '@workbench/canvas-operations/generationCompositePlan';
import { describe, expect, it, vi } from 'vitest';
import type { ExecuteCompositePlanDeps } from './compositeForGeneration';
@@ -18,6 +19,7 @@ import type { ExecuteCompositePlanDeps } from './compositeForGeneration';
import {
createCompositeDedupeCache,
executeCompositePlan,
+ executeControlComposite,
executeMaskComposite,
toGrayscaleMaskPixels,
} from './compositeForGeneration';
@@ -40,6 +42,21 @@ const rasterLayer = (
...overrides,
});
+const controlLayer = (id: string, overrides: Partial<CanvasControlLayerContract> = {}): CanvasControlLayerContract => ({
+ 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: true,
+ ...overrides,
+});
+
const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({
background: 'transparent',
bbox: { height: 100, width: 100, x: 0, y: 0 },
@@ -267,6 +284,24 @@ describe('executeCompositePlan — upload + dedupe', () => {
});
});
+describe('executeControlComposite', () => {
+ it('flattens transparent control pixels over black without a CPU readback', async () => {
+ const readImageData = vi.fn(() => uniformImageData(100, 100, 0));
+ const harness = makeHarness(readImageData);
+ const control = planControlComposites(makeDoc([controlLayer('control')]), BBOX)[0];
+ expect(control).toBeDefined();
+
+ await executeControlComposite(control!.entry, harness.deps);
+
+ const target = harness.createdTargets[0]!;
+ expect(target.callLog).toContainEqual({ args: ['globalCompositeOperation', 'destination-over'], op: 'set' });
+ expect(target.callLog).toContainEqual({ args: ['fillStyle', 'black'], op: 'set' });
+ expect(target.callLog).toContainEqual({ args: [0, 0, 100, 100], op: 'fillRect' });
+ expect(readImageData).not.toHaveBeenCalled();
+ expect(harness.encodeSurface).toHaveBeenCalledWith(target);
+ });
+});
+
// ---- Grayscale mask composite ---------------------------------------------
const inpaintMask = (
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
index a211a5176b..8dbc2d2499 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
@@ -156,9 +156,11 @@ const reserveComposite = (
layerCount: number
): { release(): void } => {
const pixels = Math.max(0, entry.bbox.width) * Math.max(0, entry.bbox.height);
- // Final/accumulator surface + final scan ImageData, plus one temporary
- // surface and one ImageData buffer for every adjusted/mask layer.
- const reservation = deps.reserve?.(pixels * 4 * (2 + layerCount * 2));
+ // Final/accumulator surface plus a final scan ImageData (except for control
+ // layers, which are made opaque by construction), plus one temporary surface
+ // and one ImageData buffer for every adjusted/mask layer.
+ const finalBuffers = entry.kind === 'control-layer' ? 1 : 2;
+ const reservation = deps.reserve?.(pixels * 4 * (finalBuffers + layerCount * 2));
if (reservation?.status === 'over-budget') {
throw new CompositeOverBudgetError();
}
@@ -221,6 +223,25 @@ const isFullyOpaque = (imageData: ImageData): boolean => {
return true;
};
+/**
+ * Flattens an RGBA control composite over black. Control adapters consume RGB
+ * rather than alpha; leaving transparent pixels in the uploaded PNG lets the
+ * backend's shared channel normalizer matte them over white, which turns an
+ * erased area into strong control signal. Legacy generation rasterized control
+ * layers with `bg: 'black'`, so preserve that model-facing contract here while
+ * editable layer surfaces remain transparent.
+ */
+const flattenControlSurfaceOverBlack = (surface: RasterSurface): void => {
+ const { ctx } = surface;
+ ctx.save();
+ setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = 'destination-over';
+ ctx.fillStyle = 'black';
+ ctx.fillRect(0, 0, surface.width, surface.height);
+ ctx.restore();
+};
+
/**
* Composites, scans coverage, encodes, hashes, dedupes, and (when needed)
* uploads a single raster-style entry (`base-raster` or `control-layer`).
@@ -256,9 +277,14 @@ const executeRasterEntry = async (
);
try {
const surface = await renderRasterComposite(entry, deps);
- const bboxFullyCovered = isFullyOpaque(
- readImageData(surface, { height: surface.height, width: surface.width, x: 0, y: 0 })
- );
+ let bboxFullyCovered: boolean;
+ if (entry.kind === 'control-layer') {
+ flattenControlSurfaceOverBlack(surface);
+ bboxFullyCovered = surface.width > 0 && surface.height > 0;
+ } else {
+ const fullRect: Rect = { height: surface.height, width: surface.width, x: 0, y: 0 };
+ bboxFullyCovered = isFullyOpaque(readImageData(surface, fullRect));
+ }
const blob = await deps.backend.encodeSurface(surface);
const pixelHash = await hashBlob(blob);