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(canvas): keep mask hatching stable across zoom levels (#10337)

Valeri Che387825f611ce
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index f764f7158f..978a826ffc 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -37,7 +37,7 @@ A tool that cannot change the selected layer says so instead of doing nothing: t
| **Marquee select** / **Lasso select** | **M** / **L** | Select an area of pixels. Press **M** again to switch between rectangle and ellipse, or **L** again for freehand and polygon. |
| **Color picker** | **I** | Pick a color from the canvas (see below). |
-The Shape and Select buttons hold several tools. Click to use the current one, or press and hold (or right-click, or press **→** on) the button to choose another from a menu that lists each tool with its shortcut. To pick a color from the canvas, hold **Alt** with the Brush, Eraser, Gradient, Text or Pan tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame, Shape and the selection tools use **Alt** themselves, so holding it there changes their drag instead. While you pick, a round **loupe** follows the pointer: it magnifies the pixels around it, boxes the pixel that will be picked in the center, and shows that pixel's RGB values. The pointer itself is hidden, so aim with the boxed pixel. You can drag to sample as you go; the color is set when you release, and **Escape** cancels the pick and restores the previous color. The picked color goes to what you are editing:
+The Shape and Select buttons hold several tools. Click to use the current one, or press and hold (or right-click, or press **→** on) the button to choose another from a menu that lists each tool with its shortcut. To pick a color from the canvas, hold **Alt** with the Brush, Eraser, Gradient, Text or Pan tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame, Shape and the selection tools use **Alt** themselves, so holding it there changes their drag instead. While you pick, a round **loupe** follows the pointer: it magnifies the pixels around it, boxes the pixel that will be picked in the center, and shows that pixel's RGB values. The loupe and picker read the image beneath Inpaint Mask and Regional Guidance overlays. To reuse a mask's fill color, select the mask and open its Fill color control in Properties. The pointer itself is hidden, so aim with the boxed pixel. You can drag to sample as you go; the color is set when you release, and **Escape** cancels the pick and restores the previous color. The picked color goes to what you are editing:
* the selected mask's tint, while **Mask tint** is chosen in the [Color](/users-guide/canvas/layers-panel/#color) tab;
* the selected shape layer's fill when the foreground chip is active, or its stroke when the background chip is active. A pick never turns on a fill or stroke the shape doesn't have; it sets the active color instead;
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index 0272b5e777..a7fbc98d91 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -27,7 +27,7 @@ The **Color** tab edits the two painting colors: the **Foreground color**, which
* The color wheel, or a box picker via **Switch to box picker**, and the hex value, always shown. The format button next to it cycles through hex only, RGB, HSB and HSL, adding a field for each channel.
* **Swap foreground and background colors** (**X**) and **Reset colors to black and white** (**D**).
-* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas with the Brush, Eraser, Gradient, Text or Pan tool. A magnifying loupe shows the pixel under the pointer and its RGB values; see the [Canvas guide](/users-guide/canvas/canvas-guide/#tools).
+* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas with the Brush, Eraser, Gradient, Text or Pan tool. A magnifying loupe shows the image color under the pointer and its RGB values, ignoring Inpaint Mask and Regional Guidance overlays. Use **Fill color** in the mask’s Properties to access its own color. See the [Canvas guide](/users-guide/canvas/canvas-guide/#tools).
* When an inpaint mask or regional guidance layer is selected, a third chip, **Mask tint**, edits the color of its overlay.
Picking with **Alt** on the canvas writes to what you are editing: the mask tint while **Mask tint** is chosen, the selected shape layer's fill (foreground chip) or stroke (background chip), the selected text layer's color, and otherwise the active foreground or background color. A pick never turns on a fill or stroke the shape does not have: on such a shape it sets the active foreground or background color instead. A pick that changes a layer is one undoable step. The eyedropper button sets the mask tint while **Mask tint** is chosen, and otherwise the active foreground or background color.
@@ -200,7 +200,9 @@ A control layer made in an earlier version of Invoke keeps its model and works w
### Inpaint mask
-* **Fill color** and **Fill style** (Solid, Grid, Crosshatch, Diagonal, Horizontal or Vertical) — how the mask is drawn on screen.
+A new Canvas starts with a coral inpaint mask (`#e07575`). The first mask you add in the session starts at green (`#83d683`). Added masks cycle through ten colors. The cycle skips colors already used by that mask type on the current Canvas while unused colors remain. Regional Guidance uses the same palette in a separate cycle, also starting at green. You can change any layer’s fill color in Properties.
+
+* **Fill color** and **Fill style** (Solid, Grid, Crosshatch, Diagonal Left, Diagonal Right, Horizontal or Vertical) — how the mask is drawn on screen. The lines keep their spacing as you zoom the canvas.
* **Invert mask** — swap the masked and unmasked areas.
Its child rows, added from the layer menu, set **Noise** (noise added inside the mask before generating, 25% by default) and **Denoise limit** (the most the masked area may change, 80% by default).
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index 01102d9f74..9503d9785f 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -46,7 +46,7 @@ clarity, texture or dehaze adjustment, enabled or not, on any layer or group at
reader would drop the
whole adjustment stack holding it. Schema 6 marks a control layer carrying any derivation field
(`controlType`, `detection`, `original` or `originalTransform`), which an older reader would strip,
-losing the kept original. The live document and each saved canvas snapshot are versioned
+losing the kept original. Schema 7 marks the presence of a vector stack, even when empty. Schema 8 marks a raster regenerate region with a Diagonal Left (`diagonal_left`) fill, which an older reader would silently drop. The live document and each saved canvas snapshot are versioned
this way, and the canvas state takes the newest of them. Adoption is sticky: removing the feature
does not lower the version, as the server floor cannot be lowered either. A canvas with none of
these stays at 3, so older builds keep opening it. A build refuses a canvas that declares a schema above
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index fbb817a260..7a139a1e7b 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -5844,7 +5844,8 @@
"style": "Fill style",
"styles": {
"crosshatch": "Crosshatch",
- "diagonal": "Diagonal",
+ "diagonal": "Diagonal Right",
+ "diagonal_left": "Diagonal Left",
"grid": "Grid",
"horizontal": "Horizontal",
"solid": "Solid",
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
index 0921720475..9c0471468a 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
@@ -12,18 +12,21 @@ const FORMAT_STORAGE_KEY = 'invokeai:v7:webv2:color-format';
const MODE_STORAGE_KEY = 'invokeai:v7:webv2:color-picker-mode';
const MAX_RECENTS = 12;
-/** Keep defaults aligned with REGIONAL_GUIDANCE_FILL_COLORS; owner boundaries forbid importing the canvas constant. */
+/** Neutral swatches followed by the Canvas mask palette. */
export const DEFAULT_COLOR_SWATCHES: readonly string[] = [
'#000000',
'#ffffff',
'#808080',
'#e07575',
- '#dc9065',
- '#fae150',
'#83d683',
- '#799ddb',
- '#a178d6',
- '#d58bca',
+ '#f59e42',
+ '#f4d35e',
+ '#38c9c5',
+ '#62b5f5',
+ '#637be8',
+ '#ad80e8',
+ '#ed79ba',
+ '#b7d65a',
];
const isColorPickerFormat = (value: unknown): value is ColorPickerFormat =>
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 3a8dcd9050..576a05b491 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -141,11 +141,13 @@ Frame's demanded layers form its working set. After drawing, `RasterController.e
1. derived and group artifacts the frame did not read (obsolete parameter variants, inactive groups);
2. least-recently-used base caches outside working set and unprotected.
+The main viewport fills patterned masks and regenerate regions in CSS space through a transformed alpha stencil. Patterned overlays of each style step their phase by one device pixel in compositing order, so consecutive overlays of the same style have different phases. The phase stays fixed during pan, zoom and partial repaint for the same overlay order. The attached RenderController keeps one scratch surface sized to cover the largest patterned areas it has repainted within the current viewport backing bounds, and accounts it as detached working-set memory. A viewport shrink bounds the retained surface again. Detach, document replacement, cache clear and a full frame with no patterned overlay release it. A bounded frame can miss an overlay that is still visible, so it keeps the scratch. The color picker and its loupe omit inpaint and regional guidance stacks from their shared sample composite so they read the image beneath mask overlays.
+
Layer is protected while an operation pins it (`RasterMemoryBudgetController.pin`, held by every read lease, snapshot capture, export and duplicate) or while it is held: its pixels not yet persisted (`BitmapStore.hasPendingWork`) or an edit session (transform, text, float, pixel edit, operation lock) owns them. Whatever working set and protected layers still need stays resident; bytes above budget are reported as overage and leave no room for background reservations. Export and thumbnail callers request and pin their own caches. Deterministic tests assert allocation counts and bytes for pan/reveal, rotated bounds, unflushed paint bounds, isolation, transient transforms, eviction, re-rasterization.
## Raster resource ownership and memory policy
-`RasterController` is the single raster owner. Owns base layer caches, derived and adjusted surfaces, group composites, decoded bitmaps, detached snapshot accounting, reservations and pins. Each store keeps a running byte total, updated at every allocation, resize, transfer and release, and pushes it to `RasterMemoryBudgetController`; nothing resynchronizes totals by rescanning. Cache surfaces change only through `LayerCacheStore` (growth, trim, replacement, `publishRasterized`, `captureState`/`restoreState`), so accounting cannot drift from pixels.
+`RasterController` owns the raster caches and budget: base layer caches, derived and adjusted surfaces, group composites, decoded bitmaps, detached snapshot accounting, reservations and pins. `RenderController` owns the viewport's hatch scratch and tracks its bytes as detached working-set memory through the same budget. Each store keeps a running byte total, updated at every allocation, resize, transfer and release, and pushes it to `RasterMemoryBudgetController`; nothing resynchronizes totals by rescanning. Cache surfaces change only through `LayerCacheStore` (growth, trim, replacement, `publishRasterized`, `captureState`/`restoreState`), so accounting cannot drift from pixels.
Raster soft limit is 512 MiB. Memory snapshot reports:
@@ -153,7 +155,7 @@ Raster soft limit is 512 MiB. Memory snapshot reports:
- `derivedBytes`: derived and adjusted display surfaces;
- `groupBytes`: group composites;
- `decodedBytes`: leased `ImageBitmap` instances;
-- `detachedBytes`: caller-owned raster snapshot surfaces and retained operation pixels;
+- `detachedBytes`: caller-owned raster snapshot surfaces, retained operation pixels and the viewport hatch scratch;
- `reservedBytes`: capacity promised to background work but not yet represented by another class;
- `overageBytes`: amount the protected working set holds above the limit.
@@ -205,7 +207,7 @@ Color picker shows a loupe of pixels under the pointer. Anchors to pipeline's la
## Derived surfaces and invalidation
-Every display-only pixel effect uses `DerivedSurfaceCache`. Slot identified by layer ID and effect kind, guarded by source surface identity, monotonic source version, and a deterministic parameter key. Reuse safe only when every guard matches. So source replacement cannot publish or reuse a surface produced for an older preview. A spatial stack's adjusted surface also records whether its pixels are exact or an interim (see Spatial adjustments).
+Cached display-only pixel effects use `DerivedSurfaceCache`. The viewport hatch instead uses the `RenderController` scratch because the pattern is composited in screen space on each repaint. Each cache slot is identified by layer ID and effect kind, guarded by source surface identity, monotonic source version, and a deterministic parameter key. Reuse safe only when every guard matches. So source replacement cannot publish or reuse a surface produced for an older preview. A spatial stack's adjusted surface also records whether its pixels are exact or an interim (see Spatial adjustments).
Invalidate only affected effect when parameters change. Delete every derived slot when a layer is removed, replaced, or its base cache evicted. Frame-demand culling happens before derived lookup or construction.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
index 385de6c360..90e99ab677 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts
@@ -14,6 +14,15 @@ export {
needsControlDetection,
restoreControlOriginal,
} from './document/controlDerivation';
-export { createControlLayer, type CreateControlLayerInput, nextControlLayerName } from './document/layerFactories';
+export {
+ advanceMaskFillColors,
+ createControlLayer,
+ type CreateControlLayerInput,
+ DEFAULT_INPAINT_MASK_FILL,
+ DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR,
+ nextControlLayerName,
+ nextMaskFillColor,
+ resetMaskFillColors,
+} from './document/layerFactories';
export { createVectorLayer, nextVectorLayerName } from './document/vectorLayerFactories';
export { shapeDrawsOnLayer } from './tools/shapeTarget';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
index 91e9a4470d..84b4135506 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
@@ -266,7 +266,7 @@ export interface CanvasControlAdapterContract {
}
export interface CanvasMaskFillContract {
- style: 'solid' | 'grid' | 'crosshatch' | 'diagonal' | 'horizontal' | 'vertical';
+ style: 'solid' | 'grid' | 'crosshatch' | 'diagonal' | 'diagonal_left' | 'horizontal' | 'vertical';
color: string;
}
@@ -453,12 +453,12 @@ export interface CanvasDocumentContractV3 {
/**
* Schema this document needs: 3 for plain content, 4 for custom-font typography, 5 for noise or spatial
* (clarity, texture, dehaze) adjustments, 6 for control-layer derivation fields, 7 for vector geometry and
- * layer appearance. Each mutation
+ * layer appearance, 8 for a Diagonal Left regenerate region on a raster layer. Each mutation
* raises it to the newer of its content's need and the canvas state's version. A restored snapshot keeps its own,
* possibly lower, version until the next mutation; the state's version and the project's compatibility floor stay
* put meanwhile.
*/
- version: 3 | 4 | 5 | 6 | 7;
+ version: 3 | 4 | 5 | 6 | 7 | 8;
width: number;
height: number;
background: 'transparent' | { color: string };
@@ -489,10 +489,10 @@ export interface CanvasStateContractV3 {
/**
* Newest schema the state needs: the newest of its previous version, the live document's and every snapshot's
* (3 plain, 4 custom-font typography, 5 noise or spatial adjustments, 6 control-layer derivation fields,
- * 7 vector geometry and layer appearance). Sticky:
+ * 7 vector geometry and layer appearance, 8 Diagonal Left raster regenerate regions). Sticky:
* removing that content never lowers it.
*/
- version: 3 | 4 | 5 | 6 | 7;
+ version: 3 | 4 | 5 | 6 | 7 | 8;
document: CanvasDocumentContractV3;
/** Wholesale-replacement counter; the mirror clears pixel history on change, even with reused ids. */
documentRevision: number;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
index b5053e0343..91d6f09fd6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
@@ -2,11 +2,12 @@ import type { CommitMaskImageResult, CommitMaskImageResultOptions } from '@workb
import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import {
+ advanceMaskFillColors,
createInpaintMaskFromImage,
createRegionalGuidanceFromImage,
DEFAULT_INPAINT_MASK_FILL,
nextInpaintMaskName,
- nextRegionalGuidanceFillColor,
+ nextMaskFillColor,
nextRegionalGuidanceName,
} from '@workbench/canvas-engine/document/layerFactories';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
@@ -73,12 +74,13 @@ export class MaskResultController {
if (options.signal?.aborted) {
return Promise.resolve({ status: 'aborted' });
}
- const names = getDocumentLeaves(document).map((layer) => layer.name);
+ const layers = getDocumentLeaves(document);
+ const names = layers.map((layer) => layer.name);
const layerId = o.ctx.createLayerId();
const layer =
options.target === 'inpaint_mask'
? createInpaintMaskFromImage({
- fill: DEFAULT_INPAINT_MASK_FILL,
+ fill: { ...DEFAULT_INPAINT_MASK_FILL, color: nextMaskFillColor('inpaint_mask', 0, layers) },
id: layerId,
image: options.image,
name: nextInpaintMaskName(names),
@@ -86,9 +88,7 @@ export class MaskResultController {
})
: createRegionalGuidanceFromImage({
fill: {
- color: nextRegionalGuidanceFillColor(
- getDocumentLeaves(document).filter((candidate) => candidate.type === 'regional_guidance').length
- ),
+ color: nextMaskFillColor('regional_guidance', 0, layers),
style: 'solid',
},
id: layerId,
@@ -115,9 +115,11 @@ export class MaskResultController {
undo: () => o.ctx.applyStep(removeLayerStep(layerId, selectedLayerId)),
}
);
- return Promise.resolve(
- result.status === 'committed' ? { layerId, status: 'committed' } : { status: guardedResultRefusal(result) }
- );
+ if (result.status === 'committed') {
+ advanceMaskFillColors(layer.type);
+ return Promise.resolve({ layerId, status: 'committed' });
+ }
+ return Promise.resolve({ status: guardedResultRefusal(result) });
} finally {
txn.end();
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts
index 65411b1e30..37b8cd4dce 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts
@@ -2,9 +2,11 @@ import type { ToolContext } from '@workbench/canvas-engine/tools/tool';
import { createPointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelInput } from '@workbench/canvas-engine/input/wheel';
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
import { createViewport } from '@workbench/canvas-engine/viewport';
import { afterEach, describe, expect, it } from 'vitest';
+import { RasterMemoryBudgetController } from './rasterMemoryBudgetController';
import { RenderController } from './renderController';
const cleanups: (() => void)[] = [];
@@ -56,6 +58,8 @@ const createAttachedInput = () => {
});
const controller = new RenderController({
applyCursor: () => undefined,
+ backend: createDomRasterBackend(),
+ rasterMemory: new RasterMemoryBudgetController(),
getInputHandlers: () => ({ ...pipeline, ...wheel }),
isEngineDisposed: () => false,
onPageHide: () => undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
index b603878a61..184da046db 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
@@ -1,53 +1,95 @@
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import { describe, expect, it, vi } from 'vitest';
+import { RasterMemoryBudgetController } from './rasterMemoryBudgetController';
import { RenderController } from './renderController';
+const createHarness = () => {
+ let frame: FrameRequestCallback | null = null;
+ const render = vi.fn();
+ const backend = createTestStubRasterBackend();
+ const rasterMemory = new RasterMemoryBudgetController();
+ const controller = new RenderController({
+ applyCursor: vi.fn(),
+ backend,
+ rasterMemory,
+ cancelFrame: () => {
+ frame = null;
+ },
+ getInputHandlers: () => ({
+ onKeyCapture: vi.fn(),
+ onKeyDown: vi.fn(),
+ onKeyUp: vi.fn(),
+ onFocusIn: vi.fn(),
+ onPinchGestureChange: vi.fn(),
+ onPinchGestureStart: vi.fn(),
+ onPointerCancel: vi.fn(),
+ onPointerDown: vi.fn(),
+ onPointerEnter: vi.fn(),
+ onPointerLeave: vi.fn(),
+ onPointerMove: vi.fn(),
+ onPointerUp: vi.fn(),
+ onWheel: vi.fn(),
+ onWindowFocus: vi.fn(),
+ reset: vi.fn(),
+ }),
+ isEngineDisposed: () => false,
+ onPageHide: vi.fn(),
+ onVisibilityChange: vi.fn(),
+ onWindowBlur: vi.fn(),
+ render,
+ requestFrame: (callback) => {
+ frame = callback;
+ return 1;
+ },
+ setViewportReady: vi.fn(),
+ updateAnimation: vi.fn(),
+ updateCursor: vi.fn(),
+ });
+
+ return {
+ controller,
+ currentFrame: () => frame,
+ rasterMemory,
+ render,
+ runFrame: () => {
+ const scheduled = frame;
+ frame = null;
+ scheduled?.(0);
+ },
+ };
+};
+
describe('RenderController', () => {
it('owns scheduling lifecycle and disposes idempotently', () => {
- let frame: FrameRequestCallback | null = null;
- const render = vi.fn();
- const controller = new RenderController({
- applyCursor: vi.fn(),
- cancelFrame: () => {
- frame = null;
- },
- getInputHandlers: () =>
- ({
- onKeyDown: vi.fn(),
- onKeyUp: vi.fn(),
- onFocusIn: vi.fn(),
- onPointerCancel: vi.fn(),
- onPointerDown: vi.fn(),
- onPointerEnter: vi.fn(),
- onPointerLeave: vi.fn(),
- onPointerMove: vi.fn(),
- onPointerUp: vi.fn(),
- onWheel: vi.fn(),
- reset: vi.fn(),
- }) as never,
- isEngineDisposed: () => false,
- onPageHide: vi.fn(),
- onVisibilityChange: vi.fn(),
- onWindowBlur: vi.fn(),
- render,
- requestFrame: (callback) => {
- frame = callback;
- return 1;
- },
- setViewportReady: vi.fn(),
- updateAnimation: vi.fn(),
- updateCursor: vi.fn(),
- });
-
+ const { controller, currentFrame, render, runFrame } = createHarness();
controller.scheduler.invalidate({ overlay: true });
- expect(frame).not.toBeNull();
- const scheduled = frame as unknown as FrameRequestCallback;
- frame = null;
- scheduled(0);
+ expect(currentFrame()).not.toBeNull();
+ runFrame();
expect(render).toHaveBeenCalledOnce();
controller.dispose();
controller.dispose();
controller.scheduler.invalidate({ all: true });
- expect(frame).toBeNull();
+ expect(currentFrame()).toBeNull();
+ });
+
+ it('reuses the viewport mask scratch, accounts its backing bytes and releases them on detach', () => {
+ const { controller, rasterMemory } = createHarness();
+ const scratch = controller.getMaskScratch(20, 10);
+ const bytes = () => rasterMemory.snapshot().detachedBytes;
+ expect(bytes()).toBe(800);
+ expect(controller.getMaskScratch(30, 5)).toBe(scratch);
+ expect(bytes()).toBe(1200);
+
+ controller.resize(15, 8);
+ expect(scratch).toMatchObject({ height: 8, width: 15 });
+ expect(bytes()).toBe(480);
+
+ controller.detach();
+ expect(scratch).toMatchObject({ height: 0, width: 0 });
+ expect(bytes()).toBe(0);
+ expect(controller.getMaskScratch(20, 10)).not.toBe(scratch);
+ controller.dispose();
+ expect(bytes()).toBe(0);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
index 3265af32a0..bf8a9089e7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
@@ -1,9 +1,11 @@
import type { CanvasKeyOwner, CanvasSurfaceAttachOptions } from '@workbench/canvas-engine/capabilities';
-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { RenderScheduler, RenderSchedulerDeps } from '@workbench/canvas-engine/render/scheduler';
import { createRenderScheduler } from '@workbench/canvas-engine/render/scheduler';
+import type { RasterMemoryBudgetController, RasterMemoryLease } from './rasterMemoryBudgetController';
+
import { PreviewStateController } from './previewStateController';
const wrapCanvasSurface = (canvas: HTMLCanvasElement): RasterSurface => {
@@ -39,6 +41,8 @@ const wrapCanvasSurface = (canvas: HTMLCanvasElement): RasterSurface => {
};
export interface RenderControllerOptions extends RenderSchedulerDeps {
+ readonly backend: Pick<RasterBackend, 'createSurface'>;
+ readonly rasterMemory: Pick<RasterMemoryBudgetController, 'trackDetached'>;
readonly isEngineDisposed: () => boolean;
readonly getInputHandlers: () => {
onPointerDown: (event: PointerEvent) => void;
@@ -72,6 +76,7 @@ export class RenderController {
readonly scheduler: RenderScheduler;
readonly previews = new PreviewStateController();
private screen: RasterSurface | null = null;
+ private maskScratch: { surface: RasterSurface; lease: RasterMemoryLease } | null = null;
private overlay: RasterSurface | null = null;
private input: HTMLCanvasElement | null = null;
private keyboardRoot: HTMLElement | null = null;
@@ -86,6 +91,36 @@ export class RenderController {
return this.screen;
}
+ readonly getMaskScratch = (width: number, height: number): RasterSurface => {
+ const current = this.maskScratch;
+ if (current) {
+ this.resizeMaskScratch(Math.max(current.surface.width, width), Math.max(current.surface.height, height));
+ return current.surface;
+ }
+ const surface = this.options.backend.createSurface(width, height);
+ this.maskScratch = { surface, lease: this.options.rasterMemory.trackDetached(width * height * 4) };
+ return surface;
+ };
+
+ private resizeMaskScratch(width: number, height: number): void {
+ const current = this.maskScratch;
+ if (!current || (current.surface.width === width && current.surface.height === height)) {
+ return;
+ }
+ current.surface.resize(width, height);
+ current.lease.release();
+ current.lease = this.options.rasterMemory.trackDetached(width * height * 4);
+ }
+
+ releaseMaskScratch(): void {
+ const current = this.maskScratch;
+ if (current) {
+ current.surface.resize(0, 0);
+ current.lease.release();
+ this.maskScratch = null;
+ }
+ }
+
getOverlay(): RasterSurface | null {
return this.overlay;
}
@@ -180,6 +215,7 @@ export class RenderController {
handlers.reset();
this.scheduler.pause();
this.options.setViewportReady(false);
+ this.releaseMaskScratch();
this.screen = null;
this.overlay = null;
this.input = null;
@@ -191,6 +227,14 @@ export class RenderController {
resize(width: number, height: number): void {
this.screen?.resize(width, height);
this.overlay?.resize(width, height);
+ if (this.maskScratch) {
+ const { surface } = this.maskScratch;
+ if (width === 0 || height === 0) {
+ this.releaseMaskScratch();
+ } else {
+ this.resizeMaskScratch(Math.min(width, surface.width), Math.min(height, surface.height));
+ }
+ }
}
dispose(): void {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.test.ts
index 8fae7d9311..09762a719f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.test.ts
@@ -1,7 +1,14 @@
+import { layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';
import { describe, expect, it } from 'vitest';
-import { createControlLayer, nextControlLayerName } from './layerFactories';
+import {
+ advanceMaskFillColors,
+ createControlLayer,
+ nextControlLayerName,
+ nextMaskFillColor,
+ resetMaskFillColors,
+} from './layerFactories';
describe('createControlLayer', () => {
it('creates an empty, untyped, model-less layer on the legacy ControlNet defaults with transparency on', () => {
@@ -46,3 +53,63 @@ describe('nextControlLayerName', () => {
expect(nextControlLayerName(['Control Layer 1', 'Control Layer 2'])).toBe('Control Layer 3');
});
});
+
+it('cycles mask colors independently in palette order and restarts at the session defaults', () => {
+ resetMaskFillColors();
+ expect(nextMaskFillColor('inpaint_mask')).toBe('#83d683');
+ expect(nextMaskFillColor('regional_guidance')).toBe('#83d683');
+ expect(Array.from({ length: 10 }, (_, index) => nextMaskFillColor('inpaint_mask', index))).toEqual([
+ '#83d683',
+ '#f59e42',
+ '#f4d35e',
+ '#38c9c5',
+ '#62b5f5',
+ '#637be8',
+ '#ad80e8',
+ '#ed79ba',
+ '#b7d65a',
+ '#e07575',
+ ]);
+ advanceMaskFillColors('inpaint_mask');
+ expect(nextMaskFillColor('inpaint_mask')).toBe('#f59e42');
+ expect(nextMaskFillColor('regional_guidance')).toBe('#83d683');
+ advanceMaskFillColors('regional_guidance');
+ expect(nextMaskFillColor('regional_guidance')).toBe('#f59e42');
+ resetMaskFillColors();
+ expect(nextMaskFillColor('regional_guidance')).toBe('#83d683');
+ expect(nextMaskFillColor('inpaint_mask')).toBe('#83d683');
+});
+
+it.each([
+ { label: 'same type and uppercase hex', used: ['#83D683'], other: [], expected: ['#f59e42'] },
+ { label: 'colors used by the other mask type', used: [], other: ['#83d683'], expected: ['#83d683'] },
+ { label: 'an import batch', used: ['#83d683', '#f4d35e'], other: [], expected: ['#f59e42', '#38c9c5', '#62b5f5'] },
+ {
+ label: 'an exhausted palette',
+ used: [
+ '#e07575',
+ '#83d683',
+ '#f59e42',
+ '#f4d35e',
+ '#38c9c5',
+ '#62b5f5',
+ '#637be8',
+ '#ad80e8',
+ '#ed79ba',
+ '#b7d65a',
+ ],
+ other: [],
+ expected: ['#83d683', '#f59e42'],
+ },
+])('chooses palette colors with $label', ({ used, other, expected }) => {
+ resetMaskFillColors();
+ const layers = [
+ ...used.map((color) =>
+ layerContract(color, 'regional_guidance', { mask: { bitmap: null, fill: { color, style: 'solid' } } })
+ ),
+ ...other.map((color) =>
+ layerContract(color, 'inpaint_mask', { mask: { bitmap: null, fill: { color, style: 'solid' } } })
+ ),
+ ];
+ expect(expected.map((_, offset) => nextMaskFillColor('regional_guidance', offset, layers))).toEqual(expected);
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
index 33e3322c66..4e10ca9fe9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerFactories.ts
@@ -3,6 +3,7 @@ import type {
CanvasImageRef,
CanvasInpaintMaskLayerContract,
CanvasLayerBaseContract,
+ CanvasLayerContract,
CanvasLayerSourceContract,
CanvasMaskFillContract,
CanvasPixelSourceContract,
@@ -13,15 +14,55 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { createDefaultControlAdapter } from '@workbench/controlAdapters';
export const DEFAULT_INPAINT_MASK_FILL = { color: '#e07575', style: 'diagonal' } as const;
-export const REGIONAL_GUIDANCE_FILL_COLORS: readonly string[] = [
- '#799ddb',
- '#83d683',
- '#fae150',
- '#dc9065',
+export const DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR = '#83d683';
+const MASK_FILL_COLORS = [
'#e07575',
- '#d58bca',
- '#a178d6',
-];
+ DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR,
+ '#f59e42',
+ '#f4d35e',
+ '#38c9c5',
+ '#62b5f5',
+ '#637be8',
+ '#ad80e8',
+ '#ed79ba',
+ '#b7d65a',
+] as const;
+
+type MaskLayerKind = 'inpaint_mask' | 'regional_guidance';
+
+// Keep top-level code side-effect free (no spreads, member reads or account registration): the eager editor bundle
+// imports the Canvas API, which would otherwise keep this module. The engine registry registers the account reset.
+// New canvases already contain a coral inpaint mask.
+const nextColorIndex = { inpaint_mask: 1, regional_guidance: 1 };
+
+export const nextMaskFillColor = (
+ kind: MaskLayerKind,
+ offset = 0,
+ layers: readonly CanvasLayerContract[] = []
+): string => {
+ const used = new Set(layers.flatMap((layer) => (layer.type === kind ? [layer.mask.fill.color.toLowerCase()] : [])));
+ const start = nextColorIndex[kind];
+ let available = 0;
+ for (let step = 0; step < MASK_FILL_COLORS.length; step += 1) {
+ const color = MASK_FILL_COLORS[(start + step) % MASK_FILL_COLORS.length]!;
+ if (!used.has(color)) {
+ if (available === offset) {
+ return color;
+ }
+ available += 1;
+ }
+ }
+ return MASK_FILL_COLORS[(start + offset - available) % MASK_FILL_COLORS.length]!;
+};
+
+export const advanceMaskFillColors = (kind: MaskLayerKind, count = 1): void => {
+ nextColorIndex[kind] = (nextColorIndex[kind] + count) % MASK_FILL_COLORS.length;
+};
+
+export const resetMaskFillColors = (): void => {
+ nextColorIndex.inpaint_mask = 1;
+ nextColorIndex.regional_guidance = 1;
+};
export const nextNumberedName = (prefix: string, existingNames: readonly string[]): string => {
const expression = new RegExp(`^${prefix} (\\d+)$`);
@@ -41,10 +82,6 @@ export const nextInpaintMaskName = (names: readonly string[]): string => nextNum
export const nextControlLayerName = (names: readonly string[]): string => nextNumberedName('Control Layer', names);
export const nextRegionalGuidanceName = (names: readonly string[]): string =>
nextNumberedName('Regional Guidance', names);
-export const nextRegionalGuidanceFillColor = (count: number): string =>
- REGIONAL_GUIDANCE_FILL_COLORS[(count + 1) % REGIONAL_GUIDANCE_FILL_COLORS.length] ??
- REGIONAL_GUIDANCE_FILL_COLORS[0]!;
-
export interface CreateMaskLayerFromImageInput {
image: CanvasImageRef;
rect: Rect;
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 2e2b9eb21d..2cde6e3829 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -24,6 +24,7 @@ import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutation
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import type { WorkbenchAction } from '@workbench/workbenchState.testing';
+import { resetMaskFillColors } from '@workbench/canvas-engine/document/layerFactories';
import {
applyCanvasProjectMutation,
isCanvasProjectMutation,
@@ -51,7 +52,7 @@ import {
} from '@workbench/canvas-operations/createCanvasEngine';
import { getCanvasOperationImplementation as getCanvasOperations } from '@workbench/canvas-operations/operationAccess';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
-import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
import type { BitmapStore } from './document/bitmapStore';
import type { StrokeCommittedEvent } from './tools/tool';
@@ -5898,6 +5899,8 @@ describe('replaceSelectionFromImage', () => {
});
describe('commitMaskImageResult', () => {
+ beforeEach(resetMaskFillColors);
+
const resultImage = { height: 12, imageName: 'durable-sam-result.png', width: 16 };
const resultRect = { height: 12, width: 16, x: -5, y: 7 };
@@ -5963,7 +5966,7 @@ describe('commitMaskImageResult', () => {
isLocked: false,
mask: {
bitmap: resultImage,
- fill: { color: '#e07575', style: 'diagonal' },
+ fill: { color: '#83d683', style: 'diagonal' },
offset: { x: -5, y: 7 },
},
name: 'Inpaint Mask 2',
@@ -5981,7 +5984,7 @@ describe('commitMaskImageResult', () => {
isLocked: false,
mask: {
bitmap: resultImage,
- fill: { color: '#fae150', style: 'solid' },
+ fill: { color: '#f59e42', style: 'solid' },
offset: { x: -5, y: 7 },
},
name: 'Regional Guidance 2',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index ef3cb61885..5966ae2a8b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -495,11 +495,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const groupSurfaces = rasterController.groups;
const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, content) =>
groupSurfaces.get(scope, members, matrices, content);
- /** Picking and the picker's loupe see the same adjusted, derived and grouped pixels as the display. */
+ /** Picking and the loupe sample the image underneath the mask overlays. */
const colorSampleProviders: ColorSampleProviders = {
adjustedSurface: getAdjustedSurface,
derivedSurfaces: derivedSurfaceCache,
groupSurface: getGroupSurface,
+ showOverlayStacks: { control: true, inpaint_mask: false, regional_guidance: false, vector: true },
};
const strokeListeners = new Set<(event: StrokeCommittedEvent) => void>();
@@ -1426,6 +1427,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const view = viewport.viewMatrix(dpr);
if (!doc) {
+ renderController.releaseMaskScratch();
clearSurface(screen);
clearSurface(overlay);
return;
@@ -1450,6 +1452,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const renderController = new RenderController({
applyCursor: (value) => applyCursorToInput(value),
+ backend,
+ rasterMemory: rasterController.memory,
getInputHandlers: () => ({ ...pipeline, ...wheelInput, onPointerLeave: onCanvasPointerLeave, reset: resetInput }),
isEngineDisposed: () => disposed,
onPageHide: () => onPageHide(),
@@ -1509,6 +1513,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
isEditingStagingHiddenStack: () => gestureEditsStagingHiddenStack || sessionEditsStagingHiddenStack,
layerCache,
previews: renderController.previews,
+ maskScratch: renderController,
raster: rasterController,
// A failed source waits out its retry backoff instead of failing every frame.
rasterizeLayer: (layer, doc) => {
@@ -1596,6 +1601,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
onBboxChanged: () => scheduler.invalidate({ overlay: true }),
onDocumentReplaced: () => {
const cleanup = createCleanupAccumulator();
+ cleanup.run(() => renderController.releaseMaskScratch());
cleanup.run(() => vectorRuntime.editor.discard());
cleanup.run(() => groupSurfaces.clear());
cleanup.run(() => editingController.invalidateDocument());
@@ -2631,6 +2637,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
checkerboardTile = null;
maskPatternTiles.clear();
+ renderController.releaseMaskScratch();
scheduler.invalidate({ all: true });
};
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.ts
index fa297dacaa..84c1d962a4 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
@@ -50,6 +50,38 @@ describe('color sampling with real browser rasterization', () => {
expect(createColorSampler(backend).sample(doc, caches, { x: 20, y: 0 })).toEqual(EXPECTED_COLOR);
});
+ it('picks the document pixel at the pointer beneath a displayed mask', () => {
+ const backend = createDomRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ const raster = layer(0);
+ const entry = caches.getOrCreate(raster.id, 8, 8);
+ entry.surface.ctx.fillStyle = '#0000ff';
+ entry.surface.ctx.fillRect(0, 0, 8, 8);
+ entry.surface.ctx.fillStyle = '#ef1234';
+ entry.surface.ctx.fillRect(0, 0, 1, 8);
+ caches.publishPixels(raster.id);
+ const coverage = caches.getOrCreate('mask', 8, 8);
+ coverage.surface.ctx.fillRect(0, 0, 8, 8);
+ caches.publishPixels('mask');
+ const doc = {
+ ...documentWith(raster),
+ stacks: stacksFrom([
+ {
+ ...raster,
+ id: 'mask',
+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },
+ type: 'inpaint_mask',
+ },
+ raster,
+ ]),
+ };
+ const sampler = createColorSampler(backend);
+ const providers = { showOverlayStacks: { control: true, inpaint_mask: false, regional_guidance: false } };
+ expect(sampler.sample(doc, caches, { x: 0.5, y: 0.5 }, providers)).toEqual(EXPECTED_COLOR);
+ expect(sampler.sample(doc, caches, { x: 1.5, y: 0.5 }, providers)).toEqual({ a: 255, b: 255, g: 0, r: 0 });
+ expect(sampler.sampleArea(doc, caches, { x: 0.5, y: 0.5 }, 3, providers)?.center).toEqual(EXPECTED_COLOR);
+ });
+
it('samples the square around a pixel with the pick at its center and empty canvas transparent', () => {
const backend = createDomRasterBackend();
const caches = createLayerCacheStore(backend);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
index ba1fa2c22c..4b962c61be 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
@@ -20,7 +20,10 @@ export interface RgbaSample {
a: number;
}
-export type ColorSampleProviders = Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'>;
+export type ColorSampleProviders = Pick<
+ CompositeOptions,
+ 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface' | 'showOverlayStacks'
+>;
const RAW_PIXELS: ColorSampleProviders = {};
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.ts
index 2b6452c135..3151aca456 100644
--- 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.ts
@@ -55,6 +55,7 @@ const scene = (budgetBytes = SURFACE_BYTES * 2) => {
getControlView: () => null,
getGroupSurface: (scope, members, matrices, content) => raster.groups.get(scope, members, matrices, content),
getMaskPatternTile: () => null,
+ maskScratch: { getMaskScratch: backend.createSurface, releaseMaskScratch: () => undefined },
isEditingStagingHiddenStack: () => false,
layerCache: raster.layers,
previews: new PreviewStateController(),
@@ -126,6 +127,7 @@ describe('frame description over 2,000 nodes', () => {
getControlView: () => null,
getGroupSurface: () => null,
getMaskPatternTile: () => null,
+ maskScratch: { getMaskScratch: backend.createSurface, releaseMaskScratch: () => undefined },
isEditingStagingHiddenStack: () => false,
layerCache: raster.layers,
previews: new PreviewStateController(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
index 1682e4dbf0..6a0a8b58a0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
@@ -88,6 +88,7 @@ const makeHarness = (): Harness => {
getCheckerboardTile: () => surface(8, 8),
getControlView: () => harness.controlView,
getMaskPatternTile: () => null,
+ maskScratch: { getMaskScratch: () => surface(8, 8), releaseMaskScratch: vi.fn() },
isEditingStagingHiddenStack: () => harness.editingHiddenStack,
layerCache: {
byteSize: () => 0,
@@ -101,7 +102,7 @@ const makeHarness = (): Harness => {
stores,
transformOverrides: overrides,
viewport: {
- getDpr: () => 1,
+ getDpr: () => 2,
getViewportSize: () => ({ height: 64, width: 64 }),
getZoom: () => 1,
screenToDocument: ({ x, y }: { x: number; y: number }) => ({ x, y }),
@@ -131,6 +132,14 @@ beforeEach(() => {
composite = vi.spyOn(compositor, 'compositeDocument').mockImplementation(() => undefined);
});
+it('passes the viewport DPR and its mask scratch to the screen compositor', () => {
+ draw();
+ expect(lastCompositeOptions().screenMask).toEqual({
+ dpr: 2,
+ getScratch: expect.any(Function),
+ });
+});
+
describe('cache preparation', () => {
it('starts a rasterization for a stale layer the frame demands', () => {
harness.entries.set('a', entryFor(undefined, true));
@@ -332,6 +341,21 @@ describe('the surface budget', () => {
draw();
expect(composite.mock.invocationCallOrder[0]).toBeLessThan(harness.enforce.mock.invocationCallOrder[0]!);
});
+
+ it('releases mask scratch after a full repaint without patterns and retains it across bounded damage', () => {
+ const doc = documentOf([layer('a')]);
+ const frame = createCompositeFrame(harness.deps);
+ const screen = surface();
+ const release = harness.deps.maskScratch.releaseMaskScratch;
+ composite.mockImplementationOnce((...[, , , , options]: Parameters<typeof compositor.compositeDocument>) => {
+ options.screenMask!.getScratch(8, 8);
+ });
+ frame.draw(screen, doc, VIEW, null, null);
+ frame.draw(screen, doc, VIEW, null, null, { kind: 'regions', regions: [{ layerId: 'a', rect: entryFor().rect }] });
+ expect(release).not.toHaveBeenCalled();
+ frame.draw(screen, doc, VIEW, null, null);
+ expect(release).toHaveBeenCalledOnce();
+ });
});
describe('overlay stacks while a result is staged', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
index 41d81b9d90..596be660cb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
@@ -4,6 +4,7 @@ import type {
SamPreviewState,
} from '@workbench/canvas-engine/controllers/previewStateController';
import type { RasterController } from '@workbench/canvas-engine/controllers/rasterController';
+import type { RenderController } from '@workbench/canvas-engine/controllers/renderController';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';
@@ -40,6 +41,7 @@ export interface CreateCompositeFrameDeps {
readonly backend: RasterBackend;
readonly diagnostics: CanvasDiagnostics;
readonly raster: Pick<RasterController, 'beginFrame' | 'enforceBudget'>;
+ readonly maskScratch: Pick<RenderController, 'getMaskScratch' | 'releaseMaskScratch'>;
readonly previews: PreviewStateController;
readonly stores: EngineStores;
readonly viewport: Viewport;
@@ -278,6 +280,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
fullFrameUsage = usage;
}
+ let usedMaskScratch = false;
compositeDocument(screen, doc, layerCache, view, {
damage: frameDamage,
adjustedSurface: deps.getAdjustedSurface,
@@ -296,6 +299,13 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
preparation: frame,
// Screen frames are display-time: the region tint may draw, except over a staged result.
regionOverlays: !staging,
+ screenMask: {
+ dpr: viewport.getDpr(),
+ getScratch: (width, height) => {
+ usedMaskScratch = true;
+ return deps.maskScratch.getMaskScratch(width, height);
+ },
+ },
showOverlayStacks,
// Candidates and progress frames alike land at the rect pinned at submission, never the live bbox.
stagedPreview:
@@ -315,6 +325,10 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
transformOverrides: overrides,
});
+ // A bounded repaint can miss a pattern that is still on screen.
+ if (frameDamage.kind === 'full' && !usedMaskScratch) {
+ deps.maskScratch.releaseMaskScratch();
+ }
enforceBudget(activeFrameLayerIds, fullFrameUsage);
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index dcf594995a..14a58af0c2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -9,7 +9,7 @@ import type {
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';
-import type { FrameDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
+import type { FrameDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import {
@@ -69,6 +69,11 @@ export interface CompositeOptions {
skipLayerId?: string | null;
/** Null means direct solid fill; without a provider only solid fills render. */
maskPatternTile?: ((style: string, color: string) => RasterSurface | null) | null;
+ /** The viewport supplies its backing scale and owns the scratch used to stencil screen-space patterns. */
+ screenMask?: {
+ dpr: number;
+ getScratch: (width: number, height: number) => RasterSurface;
+ };
/** Display-only: pixel-consuming composites must omit them, or the tint becomes generated content. */
regionOverlays?: boolean;
/** Layer-local output bounds, drawn through the layer transform. */
@@ -292,29 +297,13 @@ const isMaskLayer = (
): layer is Extract<CanvasLayerContract, { type: 'regional_guidance' | 'inpaint_mask' }> =>
layer.type === 'regional_guidance' || layer.type === 'inpaint_mask';
-const drawMaskLayer = (
- ctx: Ctx,
- layer: Extract<CanvasLayerContract, { type: 'regional_guidance' | 'inpaint_mask' }>,
- surface: RasterSurface,
- sourceVersion: number,
- origin: Vec2,
- opts: CompositeOptions
-): void => {
- const fill = layer.mask.fill;
- 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);
- // The outer context already applies layer opacity.
- ctx.drawImage(colorized.canvas, origin.x, origin.y);
-};
+type DrawMaskFill = (
+ layerId: string,
+ fill: CanvasMaskFillContract,
+ coverage: { surface: RasterSurface; rect: Rect; version: number },
+ matrix: Mat2d,
+ kind: 'mask-fill' | 'region-fill'
+) => void;
const drawCachedLayer = (
ctx: Ctx,
@@ -323,13 +312,15 @@ const drawCachedLayer = (
entry: LayerCacheEntry,
view: Mat2d,
opts: CompositeOptions,
+ drawMaskFill: DrawMaskFill,
alpha = 1
): void => {
const { layer } = leaf;
ctx.save();
ctx.globalAlpha = layer.opacity * alpha;
ctx.globalCompositeOperation = blendToComposite(layer.blendMode);
- setTransformFromMat(ctx, multiply(view, matrix));
+ const screenMatrix = multiply(view, matrix);
+ setTransformFromMat(ctx, screenMatrix);
const origin = { x: entry.rect.x, y: entry.rect.y };
const preview = isIsolated(opts) ? null : (opts.layerPreviews?.get(layer.id) ?? null);
@@ -356,7 +347,7 @@ const drawCachedLayer = (
: preview.surface;
ctx.drawImage(displayPreview.canvas, preview.rect.x, preview.rect.y);
} else if (isMaskLayer(layer)) {
- drawMaskLayer(ctx, layer, entry.surface, entry.version, origin, opts);
+ drawMaskFill(layer.id, layer.mask.fill, entry, screenMatrix, 'mask-fill');
} else if (layer.type === 'control' && layer.withTransparencyEffect) {
const effect = opts.derivedSurfaces
? opts.derivedSurfaces.get({
@@ -376,44 +367,14 @@ const drawCachedLayer = (
}
if (opts.regionOverlays && layer.type === 'raster' && layer.inpaint?.isEnabled && !preview && !isIsolated(opts)) {
- drawRegionCoverage(ctx, layer.id, layer.inpaint.fill, entry, opts);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = REGION_OVERLAY_ALPHA;
+ drawMaskFill(layer.id, layer.inpaint.fill, entry, screenMatrix, 'region-fill');
}
ctx.restore();
};
-const drawRegionCoverage = (
- ctx: Ctx,
- layerId: string,
- fill: CanvasMaskFillContract,
- coverage: { surface: RasterSurface; rect: Rect; version: number },
- opts: CompositeOptions
-): void => {
- ctx.globalCompositeOperation = 'source-over';
- 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);
-};
-
/** Drawn through the layer matrix then their own, never resampled into document space and back. */
const drawLayerLocalSurface = (
ctx: Ctx,
@@ -485,6 +446,76 @@ export const compositeDocument = (
const ctx = target.ctx;
opts.diagnostics?.increment('compositeFrames');
const repaint = damage.kind === 'rect' ? damage.rect : targetRect;
+ const hatchPhases = new Map<string, number>();
+ if (opts.screenMask && opts.maskPatternTile) {
+ const nextPhase = new Map<CanvasMaskFillContract['style'], number>();
+ // Assign before culling so partial repaints use the same phases as full frames.
+ for (const { layer } of plan.leaves) {
+ const fill = isMaskLayer(layer)
+ ? layer.mask.fill
+ : opts.regionOverlays && !isIsolated(opts) && layer.type === 'raster' && layer.inpaint?.isEnabled
+ ? layer.inpaint.fill
+ : undefined;
+ if (!fill || fill.style === 'solid') {
+ continue;
+ }
+ const phase = nextPhase.get(fill.style) ?? 0;
+ hatchPhases.set(layer.id, phase);
+ nextPhase.set(fill.style, phase + 1);
+ }
+ }
+ const drawMaskFill: DrawMaskFill = (layerId, fill, coverage, matrix, kind) => {
+ const { surface, rect, version } = coverage;
+ const tile = opts.maskPatternTile?.(fill.style, fill.color) ?? null;
+ if (tile && opts.screenMask) {
+ const { dpr, getScratch } = opts.screenMask;
+ const area = intersect(roundOut(transformBounds(matrix, rect)), repaint);
+ if (!area || isEmpty(area) || ![area.x, area.y, area.width, area.height].every(Number.isFinite)) {
+ return;
+ }
+ const scratch = getScratch(area.width, area.height);
+ const stencil = scratch.ctx;
+ stencil.save();
+ identityTransform(stencil);
+ stencil.clearRect(0, 0, area.width, area.height);
+ // The retained scratch can be far larger than a small repaint; drawing the whole mask across it is the cost.
+ stencil.beginPath();
+ stencil.rect(0, 0, area.width, area.height);
+ stencil.clip();
+ stencil.globalCompositeOperation = 'source-over';
+ stencil.imageSmoothingEnabled = ctx.imageSmoothingEnabled;
+ setTransformFromMat(stencil, { ...matrix, e: matrix.e - area.x, f: matrix.f - area.y });
+ stencil.drawImage(surface.canvas, rect.x, rect.y);
+
+ const phase = hatchPhases.get(layerId) ?? 0;
+ const offsetX = fill.style === 'horizontal' ? 0 : phase;
+ const offsetY = fill.style === 'horizontal' || fill.style === 'grid' ? phase : 0;
+ stencil.imageSmoothingEnabled = true;
+ stencil.setTransform(dpr, 0, 0, dpr, offsetX - area.x, offsetY - area.y);
+ stencil.globalCompositeOperation = 'source-in';
+ stencil.fillStyle = stencil.createPattern(tile.canvas, 'repeat') ?? fill.color;
+ stencil.fillRect((area.x - offsetX) / dpr, (area.y - offsetY) / dpr, area.width / dpr, area.height / dpr);
+ stencil.restore();
+
+ ctx.save();
+ identityTransform(ctx);
+ ctx.drawImage(scratch.canvas, 0, 0, area.width, area.height, area.x, area.y, area.width, area.height);
+ ctx.restore();
+ return;
+ }
+
+ const colorized = opts.derivedSurfaces
+ ? opts.derivedSurfaces.get({
+ create: (target) => colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile, target),
+ kind,
+ layerId,
+ paramsKey: `${fill.style}:${fill.color}`,
+ source: surface,
+ sourceVersion: version,
+ })
+ : colorizeMask(opts.backend, surface, surface.width, surface.height, fill, tile);
+ ctx.drawImage(colorized.canvas, rect.x, rect.y);
+ };
ctx.save();
// Nested layer restores preserve it.
@@ -560,7 +591,7 @@ export const compositeDocument = (
}
// A float still draws over an emptied source: its pixels are detached.
if (entry && entry.rect.width > 0 && entry.rect.height > 0 && controlView?.view !== 'original') {
- drawCachedLayer(ctx, leaf, matrix, entry, view, opts, controlView ? CONTROL_OVERLAY_MAP_ALPHA : 1);
+ drawCachedLayer(ctx, leaf, matrix, entry, view, opts, drawMaskFill, controlView ? CONTROL_OVERLAY_MAP_ALPHA : 1);
opts.diagnostics?.increment('layersDrawn');
}
if (float?.layerId === leaf.id) {
@@ -621,8 +652,11 @@ export const compositeDocument = (
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);
+ const matrix = multiply(view, matrices[member]!);
+ setTransformFromMat(ctx, matrix);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = REGION_OVERLAY_ALPHA;
+ drawMaskFill(layer.id, layer.inpaint.fill, memberEntry, matrix, 'region-fill');
ctx.restore();
}
}
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.ts
index 7ed58849da..3189bf9fab 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
@@ -14,6 +14,7 @@ import { identity } from '@workbench/canvas-engine/math/mat2d';
import {
compositeDocument,
createCheckerboardTile,
+ shouldSmoothAtZoom,
type CompositeOptions,
} from '@workbench/canvas-engine/render/compositor';
import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
@@ -189,6 +190,109 @@ describe('compositor goldens', () => {
});
}
+ it.each(['horizontal', 'vertical', 'diagonal'] as const)('keeps %s hatching sharp at DPR 1', (style) => {
+ const mask = inpaintMask('mask', { color: '#e07575', style });
+ const { backend, caches } = scene([mask], {
+ mask: { paint: solid('#000000'), rect: { height: 30, width: 30, x: 4, y: 4 } },
+ });
+ const target = backend.createSurface(WIDTH, HEIGHT);
+ const scratch = backend.createSurface(WIDTH, HEIGHT);
+ const tile = createMaskPatternTile(backend, style, mask.mask.fill.color)!;
+ compositeDocument(target, doc([mask]), caches, identity(), {
+ backend,
+ maskPatternTile: () => tile,
+ screenMask: { dpr: 1, getScratch: () => scratch },
+ });
+ const alpha = (pixels: Uint8ClampedArray) => Array.from(pixels).filter((_, index) => index % 4 === 3);
+ const rendered = alpha(target.ctx.getImageData(12, 12, tile.width, tile.height).data);
+ const original = alpha(tile.ctx.getImageData(0, 0, tile.width, tile.height).data);
+ expect(rendered.sort((a, b) => a - b)).toEqual(original.sort((a, b) => a - b));
+ });
+
+ it.each(['diagonal', 'diagonal_left', 'horizontal', 'vertical'] as const)(
+ 'keeps both colors visible where two opaque %s masks overlap at DPR 1',
+ (style) => {
+ const layers = [
+ inpaintMask('upper', { color: '#ff0000', style }),
+ inpaintMask('lower', { color: '#0000ff', style }),
+ ];
+ const coverage = { paint: solid('#000000'), rect: { height: 30, width: 30, x: 4, y: 4 } };
+ const { backend, caches } = scene(layers, { lower: coverage, upper: coverage });
+ const target = backend.createSurface(WIDTH, HEIGHT);
+ const scratch = backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(
+ target,
+ doc(layers),
+ caches,
+ { a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 },
+ {
+ backend,
+ maskPatternTile: (_, color) => createMaskPatternTile(backend, style, color),
+ screenMask: { dpr: 1, getScratch: () => scratch },
+ }
+ );
+ const { data } = target.ctx.getImageData(24, 24, 12, 12);
+ const red = Array.from(data).filter((_, index) => index % 4 === 0);
+ const blue = Array.from(data).filter((_, index) => index % 4 === 2);
+ expect(red.some((value, index) => value > blue[index]! + 32 && data[index * 4 + 3]! > 32)).toBe(true);
+ expect(blue.some((value, index) => value > red[index]! + 32 && data[index * 4 + 3]! > 32)).toBe(true);
+ }
+ );
+
+ it.each(['diagonal', 'diagonal_left'] as const)('renders the %s mask at a fixed screen scale', (style) => {
+ const layers = [inpaintMask('mask', { color: '#e07575', style })];
+ const { backend, caches } = scene(layers, {
+ mask: { paint: solid('#000000'), rect: { height: 30, width: 30, x: 4, y: 4 } },
+ });
+ const target = backend.createSurface(WIDTH, HEIGHT);
+ const tile = createMaskPatternTile(backend, style, '#e07575');
+ const scratch = backend.createSurface(WIDTH, HEIGHT);
+ const options: CompositeOptions = {
+ backend,
+ maskPatternTile: () => tile,
+ screenMask: { dpr: 2, getScratch: () => scratch },
+ };
+ const document = doc(layers);
+ const read = () => target.ctx.getImageData(0, 0, WIDTH, HEIGHT).data;
+ const stripe = (x = 24, y = 24) =>
+ Array.from(target.ctx.getImageData(x, y, 24, 1).data).filter((_, i) => i % 4 === 3);
+
+ compositeDocument(
+ target,
+ document,
+ caches,
+ { a: 1.5, b: 0, c: 0, d: 1.5, e: 0, f: 0 },
+ {
+ ...options,
+ imageSmoothing: shouldSmoothAtZoom(0.75),
+ }
+ );
+ const baseline = stripe();
+ const nextRow = stripe(24, 26);
+ const peakShift = nextRow.indexOf(Math.max(...nextRow)) - baseline.indexOf(Math.max(...baseline));
+ expect(Math.abs(peakShift - (style === 'diagonal' ? -2 : 2))).toBeLessThanOrEqual(1);
+ expect(Math.max(...baseline)).toBeGreaterThan(0);
+ expect(Math.min(...baseline)).toBe(0);
+ expect(baseline.slice(0, 12)).toEqual(baseline.slice(12, 24));
+ expect(baseline.slice(0, 6)).not.toEqual(baseline.slice(6, 12));
+
+ const zoomedView = { a: 4, b: 0, c: 0, d: 4, e: 3, f: -2 };
+ const zoomedOptions = { ...options, imageSmoothing: shouldSmoothAtZoom(2) };
+ compositeDocument(target, document, caches, zoomedView, zoomedOptions);
+ expect(stripe()).toEqual(baseline);
+ expect(target.ctx.getImageData(16, 24, 1, 1).data[3]).toBe(0);
+
+ const fullFrame = read();
+ solid('#00ff00')(scratch.ctx, { height: HEIGHT, width: WIDTH, x: 0, y: 0 });
+ compositeDocument(target, document, caches, zoomedView, {
+ ...zoomedOptions,
+ damage: { kind: 'regions', regions: [{ layerId: 'mask', rect: { height: 4, width: 4, x: 5, y: 5 } }] },
+ });
+ expect(read()).toEqual(fullFrame);
+ // A small repaint draws only its own corner of the retained scratch.
+ expect(Array.from(scratch.ctx.getImageData(80, 60, 1, 1).data)).toEqual([0, 255, 0, 255]);
+ });
+
it('draws a mask being edited over a staged candidate, which covers the raster beneath', async () => {
const layers = [inpaintMask('mask', { color: '#e07575', style: 'solid' }), raster('base')];
const { backend, caches } = scene(layers, {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts
index 5555231870..9dbd985bd6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.test.ts
@@ -28,15 +28,15 @@ describe('createMaskPatternTile', () => {
}
});
- it('sizes tiles to the legacy specs (diagonal/crosshatch 6px, grid 12px, h/v 9px)', () => {
+ it('sizes repeating tiles for each pattern', () => {
const backend = createTestStubRasterBackend();
const size = (style: CanvasMaskFillContract['style']): number =>
(createMaskPatternTile(backend, style, '#fff') as StubRasterSurface).width;
expect(size('diagonal')).toBe(6);
expect(size('crosshatch')).toBe(6);
expect(size('grid')).toBe(12);
- expect(size('horizontal')).toBe(9);
- expect(size('vertical')).toBe(9);
+ expect(size('horizontal')).toBe(4);
+ expect(size('vertical')).toBe(4);
});
it('draws more lines for crosshatch (both directions) than diagonal (one direction)', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts
index 4b0e63dac8..a61791aa3a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/maskFill.ts
@@ -7,16 +7,15 @@ const PATTERN_SPECS: Record<
Exclude<CanvasMaskFillContract['style'], 'solid'>,
{ size: number; spacing: number; width: number }
> = {
- // 6px tile, two parallel 45° lines 3px apart (legacy `pattern-diagonal.svg`).
- diagonal: { size: 6, spacing: 3, width: 1.3 },
- // 6px tile, 45° lines in BOTH directions (legacy `pattern-crosshatch.svg`).
- crosshatch: { size: 6, spacing: 3, width: 1.2 },
+ // Diagonals repeat every 6px along either axis.
+ diagonal: { size: 6, spacing: 6, width: 1.3 },
+ diagonal_left: { size: 6, spacing: 6, width: 1.3 },
+ // Crosshatch repeats both diagonal families every 6px along either axis.
+ crosshatch: { size: 6, spacing: 6, width: 1.2 },
// 12px tile, 3 vertical + 3 horizontal lines 4px apart (legacy `pattern-grid.svg`).
grid: { size: 12, spacing: 4, width: 1 },
- // 9px tile, 3 horizontal lines 3px apart (legacy `pattern-horizontal.svg`).
- horizontal: { size: 9, spacing: 3, width: 1 },
- // 9px tile, 3 vertical lines 3px apart (legacy `pattern-vertical.svg`).
- vertical: { size: 9, spacing: 3, width: 1 },
+ horizontal: { size: 4, spacing: 4, width: 1 },
+ vertical: { size: 4, spacing: 4, width: 1 },
};
/** Draws the anti-diagonal (`x + y = c`) or main-diagonal (`x - y = c`) line family across the tile. */
@@ -24,11 +23,12 @@ const drawDiagonalLines = (
ctx: RasterSurface['ctx'],
size: number,
spacing: number,
- direction: 'anti' | 'main'
+ direction: 'anti' | 'main',
+ phase: number
): void => {
// Sweep `c` well beyond the tile so every crossing line is drawn; the surface clips to its bounds. `spacing` divides
// `size`, so the family tiles seamlessly.
- for (let c = -size; c <= 2 * size; c += spacing) {
+ for (let c = phase - size; c <= 2 * size; c += spacing) {
ctx.beginPath();
if (direction === 'anti') {
// x + y = c: a long segment crossing the tile.
@@ -62,11 +62,14 @@ export const createMaskPatternTile = (
switch (style) {
case 'diagonal':
- drawDiagonalLines(ctx, spec.size, spec.spacing, 'anti');
+ drawDiagonalLines(ctx, spec.size, spec.spacing, 'anti', 4);
+ break;
+ case 'diagonal_left':
+ drawDiagonalLines(ctx, spec.size, spec.spacing, 'main', 2);
break;
case 'crosshatch':
- drawDiagonalLines(ctx, spec.size, spec.spacing, 'anti');
- drawDiagonalLines(ctx, spec.size, spec.spacing, 'main');
+ drawDiagonalLines(ctx, spec.size, spec.spacing, 'anti', 4);
+ drawDiagonalLines(ctx, spec.size, spec.spacing, 'main', 3);
break;
case 'grid':
case 'horizontal':
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index bfb05eaadc..e5fb1e9a39 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -11,7 +11,7 @@ import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStac
import type { EngineStores } from '@workbench/canvas-engine/engineStores';
import type { CreatePath2D } from '@workbench/canvas-engine/freehand';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
-import type { CompositeOptions } from '@workbench/canvas-engine/render/compositor';
+import type { ColorSampleProviders } from '@workbench/canvas-engine/render/colorSample';
import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
@@ -111,7 +111,7 @@ export interface ToolContext {
/** `commit` fires on pointer up only, so a structural commit in the continuation is not `gesture-active`. */
resolveColorSample?(hex: string, phase: ColorSamplePhase): boolean;
/** Absent samples raw cached pixels. */
- sampleProviders?: Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'>;
+ sampleProviders?: ColorSampleProviders;
/** Layer-local, so moving the layer carries it; the engine forgets entries on replay, replacement and removal. */
paintLineEnds?: PaintLineEnds;
/** Ordinary pointermove does not reevaluate it. */
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
index 37132a1149..6340780bf0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
@@ -8,7 +8,7 @@ import type {
import type { LiveCanvasEngines } from '@workbench/projects/projectAssets';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
-import { getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { getDocumentLeaves, resetMaskFillColors } from '@workbench/canvas-engine/api';
import type { createCanvasEngine, CanvasEngine, CanvasEngineOptions } from './createCanvasEngine';
@@ -217,6 +217,7 @@ registerAccountOwnedResource({
clear: defaultRegistry.disposeAll,
name: 'canvas-engine-registry',
});
+registerAccountOwnedResource({ clear: resetMaskFillColors, name: 'canvas-mask-fill-colors' });
export const getOrCreateEngine = defaultRegistry.getOrCreateEngine;
export const releaseEngine = defaultRegistry.releaseEngine;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index ba517dbbf0..2ec3d0d0e3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -15,7 +15,7 @@ import {
seedArchitectureCapabilities,
} from '@features/models/core/architectureCapabilities.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
-import { createControlLayer, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { createControlLayer, getDocumentLeaves, nextMaskFillColor } from '@workbench/canvas-engine/api';
import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import {
@@ -24,11 +24,10 @@ import {
createRegionalGuidanceFromImage,
createRegionalGuidanceLayerWithRefImage,
DEFAULT_INPAINT_MASK_FILL,
- nextRegionalGuidanceFillColor,
} from '@workbench/widgets/layers/layerOps';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { createInitialWorkbenchState, workbenchReducer, type WorkbenchAction } from '@workbench/workbenchState.testing';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from './importGalleryImages';
@@ -238,7 +237,7 @@ const expectedLayer = (
};
case 'inpaint-mask':
return createInpaintMaskFromImage({
- fill: DEFAULT_INPAINT_MASK_FILL,
+ fill: { ...DEFAULT_INPAINT_MASK_FILL, color: ['#83d683', '#f59e42'][index]! },
id: expect.any(String) as string,
image: ref,
name: `Inpaint Mask ${index + 1}`,
@@ -246,14 +245,18 @@ const expectedLayer = (
});
case 'regional-guidance':
return createRegionalGuidanceFromImage({
- fill: { color: nextRegionalGuidanceFillColor(index), style: 'solid' },
+ fill: { color: ['#83d683', '#f59e42'][index]!, style: 'solid' },
id: expect.any(String) as string,
image: ref,
name: `Regional Guidance ${index + 1}`,
rect: bbox,
});
case 'regional-reference': {
- const layer = createRegionalGuidanceLayerWithRefImage(`Regional Guidance ${index + 1}`, index, base);
+ const layer = createRegionalGuidanceLayerWithRefImage(
+ `Regional Guidance ${index + 1}`,
+ ['#83d683', '#f59e42'][index]!,
+ base
+ );
const reference = layer.referenceImages[0]!;
return {
...layer,
@@ -269,6 +272,10 @@ const expectedLayer = (
seedArchitectureCapabilities();
describe('importGalleryImagesToCanvas', () => {
+ beforeEach(() => {
+ accountLifecycle.invalidate();
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
it.each<Exclude<GalleryCanvasImportDestination, 'control-resized'>>([
'raster',
'control',
@@ -619,6 +626,44 @@ describe('importGalleryImagesToCanvas', () => {
expect(dispatch).not.toHaveBeenCalled();
});
+ it('reports blocked and keeps the mask colors when the project refuses the ingested layers', async () => {
+ const { project, state } = withProject();
+ const applyCanvasMutation = vi.fn(() => false);
+
+ const result = await importGalleryImagesToCanvas({
+ applyCanvasMutation,
+ destination: 'regional-guidance',
+ engine: null,
+ ...queriesFor(() => state),
+ images: [image('a.png'), image('b.png')],
+ project,
+ });
+
+ expect(result).toEqual({ status: 'blocked' });
+ expect(applyCanvasMutation).toHaveBeenCalledOnce();
+ expect(nextMaskFillColor('regional_guidance')).toBe('#83d683');
+ });
+
+ it('advances the palette across accepted imports and skips a refusal between them', async () => {
+ const { project, state } = withProject();
+ const applyCanvasMutation = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false).mockReturnValueOnce(true);
+ const options = {
+ applyCanvasMutation,
+ destination: 'regional-guidance' as const,
+ engine: null,
+ ...queriesFor(() => state),
+ images: [image('a.png')],
+ project,
+ };
+ expect((await importGalleryImagesToCanvas(options)).status).toBe('imported');
+ expect((await importGalleryImagesToCanvas(options)).status).toBe('blocked');
+ expect((await importGalleryImagesToCanvas(options)).status).toBe('imported');
+ const colors = applyCanvasMutation.mock.calls.map(([, mutation]) =>
+ getForwardLayers(mutation).map((layer) => layer.type === 'regional_guidance' && layer.mask.fill.color)
+ );
+ expect(colors).toEqual([['#83d683'], ['#f59e42'], ['#f59e42']]);
+ });
+
it('returns stale-document when the captured target document identity changes', async () => {
const { project, state } = withProject();
let current = state;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
index d31e10a239..1a9642d191 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -30,10 +30,12 @@ import {
type AccountScope,
} from '@platform/state/accountLifecycle';
import {
+ advanceMaskFillColors,
captureInsertionAnchor,
createControlLayer,
getDocumentLeaves,
nextControlLayerName,
+ nextMaskFillColor,
} from '@workbench/canvas-engine/api';
import { hasPendingCanvasResults } from '@workbench/canvasStagingView';
import {
@@ -44,7 +46,6 @@ import {
createRegionalGuidanceLayerWithRefImage,
DEFAULT_INPAINT_MASK_FILL,
nextInpaintMaskName,
- nextRegionalGuidanceFillColor,
nextRegionalGuidanceName,
} from '@workbench/widgets/layers/layerOps';
import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';
@@ -77,6 +78,8 @@ interface BuildLayerContext {
bbox: Project['canvas']['document']['bbox'];
existingLayers: readonly CanvasLayerContract[];
modelBase: string | null;
+ colorOffset: number;
+ paletteLayers: readonly CanvasLayerContract[];
}
type LayerImage = CanvasImageRef | GalleryImage;
@@ -131,16 +134,21 @@ const buildLayer = (
);
case 'inpaint-mask':
return createInpaintMaskFromImage({
- fill: DEFAULT_INPAINT_MASK_FILL,
+ fill: {
+ ...DEFAULT_INPAINT_MASK_FILL,
+ color: nextMaskFillColor('inpaint_mask', context.colorOffset, context.paletteLayers),
+ },
id,
image: ref,
name: nextInpaintMaskName(names),
rect: context.bbox,
});
case 'regional-guidance': {
- const regionalGuidanceCount = context.existingLayers.filter((layer) => layer.type === 'regional_guidance').length;
return createRegionalGuidanceFromImage({
- fill: { color: nextRegionalGuidanceFillColor(regionalGuidanceCount), style: 'solid' },
+ fill: {
+ color: nextMaskFillColor('regional_guidance', context.colorOffset, context.paletteLayers),
+ style: 'solid',
+ },
id,
image: ref,
name: nextRegionalGuidanceName(names),
@@ -148,10 +156,9 @@ const buildLayer = (
});
}
case 'regional-reference': {
- const regionalGuidanceCount = context.existingLayers.filter((layer) => layer.type === 'regional_guidance').length;
const layer = createRegionalGuidanceLayerWithRefImage(
nextRegionalGuidanceName(names),
- regionalGuidanceCount,
+ nextMaskFillColor('regional_guidance', context.colorOffset, context.paletteLayers),
context.modelBase,
id
);
@@ -177,11 +184,14 @@ const buildLayers = (
): CanvasLayerContract[] => {
const layers: CanvasLayerContract[] = [];
const modelBase = getSelectedModelBase(project);
+ const paletteLayers = getDocumentLeaves(project.canvas.document);
for (const image of images) {
layers.push(
buildLayer(image, destination, {
bbox: project.canvas.document.bbox,
- existingLayers: [...getDocumentLeaves(project.canvas.document), ...layers],
+ colorOffset: layers.length,
+ existingLayers: [...paletteLayers, ...layers],
+ paletteLayers,
modelBase,
})
);
@@ -355,9 +365,13 @@ export const importGalleryImagesToCanvas = async (options: {
if (committed.status !== 'committed') {
return { status: 'blocked' };
}
- } else {
- // Without a live canvas session, import through ingestion.
- applyCanvasMutation(project.id, forward);
+ } else if (applyCanvasMutation(project.id, forward) === false) {
+ // Without a live canvas session, import through ingestion; `false` means the project refused the layers.
+ return { status: 'blocked' };
+ }
+ const layerKind = layers[0]?.type;
+ if (layerKind === 'inpaint_mask' || layerKind === 'regional_guidance') {
+ advanceMaskFillColors(layerKind, layers.length);
}
return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };
} finally {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
index e58c0fa2d4..b64234466b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
@@ -247,7 +247,7 @@ describe('loadCanvasState', () => {
control: [groupContract('cg', [createControlLayer({ id: 'control', name: 'Control' })], { isHidden: true })],
inpaint_mask: [createInpaintMaskLayer('Mask', 'mask')],
raster: [groupContract('rg', [createEmptyPaintLayer('Raster', 'raster'), groupContract('inner', [])])],
- regional_guidance: [createRegionalGuidanceLayer('Region', 0, 'region')],
+ regional_guidance: [createRegionalGuidanceLayer('Region', undefined, 'region')],
};
const snapshot = {
createdAt: 'now',
@@ -527,6 +527,25 @@ describe('loadCanvasState', () => {
});
});
+ it('writes version 8 for a Diagonal Left raster regenerate region in the live document or a snapshot', () => {
+ const region = (style: 'diagonal' | 'diagonal_left') => ({
+ ...createEmptyPaintLayer('Layer 1', 'layer-1'),
+ inpaint: { fill: { color: '#e07575', style }, isEnabled: true, name: 'Region' },
+ });
+ const live = load(withNodes([groupContract('group', [region('diagonal_left') as never])]));
+ expect(live.version).toBe(8);
+ expect(live.document.version).toBe(8);
+ expect(load(withNodes([region('diagonal')])).version).toBe(3);
+
+ const snapshotOnly = load({
+ ...createEmptyCanvasState(),
+ snapshots: [{ createdAt: 'now', document: withNodes([region('diagonal_left')]).document, id: 's', name: 'S' }],
+ });
+ expect(snapshotOnly.version).toBe(8);
+ expect(snapshotOnly.document.version).toBe(3);
+ expect(snapshotOnly.snapshots[0]?.document.version).toBe(8);
+ });
+
it('passes a valid state through normalized, keeping every persisted field', () => {
const canvas = {
...withNodes([
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index f6584f5f2e..d5c55f9679 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -171,7 +171,7 @@ const zControlAdapter = z
.refine(({ weight }) => isStorableControlWeight(weight));
const zMaskFill = z.object({
color: z.string(),
- style: z.enum(['solid', 'grid', 'crosshatch', 'diagonal', 'horizontal', 'vertical']),
+ style: z.enum(['solid', 'grid', 'crosshatch', 'diagonal', 'diagonal_left', 'horizontal', 'vertical']),
});
const zMask = z.object({
bitmap: zImageRef.nullable(),
@@ -462,7 +462,17 @@ const CONTROL_DERIVATION_KEYS = ['controlType', 'detection', 'original', 'origin
const controlLayerRequiresV6 = (node: Record<string, unknown>): boolean =>
node.type === 'control' && CONTROL_DERIVATION_KEYS.some((key) => node[key] !== undefined);
+// A v7 reader drops a raster regenerate region whose fill it cannot parse instead of refusing the document.
+const rasterRegionRequiresV8 = (node: Record<string, unknown>): boolean =>
+ node.type === 'raster' &&
+ isRecord(node.inpaint) &&
+ isRecord(node.inpaint.fill) &&
+ node.inpaint.fill.style === 'diagonal_left';
+
const ownSchemaRequirement = (node: Record<string, unknown>): CanvasSchemaVersion => {
+ if (rasterRegionRequiresV8(node)) {
+ return 8;
+ }
if (controlLayerRequiresV6(node)) {
return 6;
}
@@ -474,7 +484,8 @@ const ownSchemaRequirement = (node: Record<string, unknown>): CanvasSchemaVersio
/**
* The newest schema a node or any descendant needs. v4: custom-font typography. v5: a noise or spatial adjustment,
- * enabled or not, which a v4 reader would drop. v6: control derivation fields.
+ * enabled or not, which a v4 reader would drop. v6: control derivation fields. v8: a Diagonal Left raster regenerate
+ * region.
*/
const nodeSchemaRequirement = (node: unknown): CanvasSchemaVersion => {
if (!isRecord(node)) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
index 29a4f59f5c..814e80e661 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
@@ -21,14 +21,15 @@ describe('getProjectCanvasSchemaRequirement', () => {
});
describe('isCanvasSchemaVersionSupported', () => {
- it('opens projects needing schema 3 through 7, including control-layer derivation, and refuses the rest', () => {
- expect([2, 3, 4, 5, 6, 7, 8].map(isCanvasSchemaVersionSupported)).toEqual([
+ it('opens projects needing schema 3 through 8 and refuses the rest', () => {
+ expect([2, 3, 4, 5, 6, 7, 8, 9].map(isCanvasSchemaVersionSupported)).toEqual([
false,
true,
true,
true,
true,
true,
+ true,
false,
]);
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
index 92f9cb37c8..25261b15d4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
@@ -5,9 +5,10 @@ export const MIN_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;
* Newest canvas document schema this build can safely read, edit, and write. A document adopts a newer schema only
* when it carries something older builds would drop on load and then lose on save: 4 for custom-font typography, 5
* for noise, clarity, texture or dehaze adjustments, 6 for control-layer derivation fields (`controlType`,
- * `detection`, `original`, `originalTransform`), 7 for vector layers with their geometry and appearance. Older builds refuse the newer schema instead.
+ * `detection`, `original`, `originalTransform`), 7 for vector layers with their geometry and appearance, 8 for a
+ * Diagonal Left regenerate region on a raster layer. Older builds refuse the newer schema instead.
*/
-export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 7;
+export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 8;
/** Whether a project whose documents need at least `minimumCanvasSchemaVersion` can be opened here. */
export const isCanvasSchemaVersionSupported = (minimumCanvasSchemaVersion: number): boolean =>
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts
index 976763b3e5..6d715c622c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts
@@ -341,6 +341,27 @@ describe('canvas record to recall', () => {
}
});
+ it('recalls a schema 8 raster regenerate region with a Diagonal Left fill', async () => {
+ const inpaint = { fill: { color: '#e07575', style: 'diagonal_left' as const }, isEnabled: true };
+ const canvas = {
+ ...createEmptyCanvasDocument(),
+ version: 8 as const,
+ stacks: {
+ ...createEmptyCanvasDocument().stacks,
+ raster: [{ ...base, type: 'raster' as const, source: { type: 'paint' as const, bitmap: null }, inpaint }],
+ },
+ };
+ const plan = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: recordCanvasMetadata(canvas) },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.problems).toEqual([]);
+ expect(plan.document?.version).toBe(8);
+ expect(plan.document?.stacks.raster[0]).toMatchObject({ inpaint });
+ });
+
it('distinguishes absence, explicit empty, malformed and future records; fences changes and project closure', async () => {
const store = createWorkbenchStore(),
target = targetFor(store),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
index 2fde33bca3..d6ba177d65 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
@@ -18,6 +18,7 @@ import { assertAccountScopeCurrent, isAccountScopeCurrent, type AccountScope } f
import { ApiError } from '@platform/transport/http';
import { prepareLegacyCanvasMetadata, getCanvasEngine } from '@workbench/canvas-operations/api';
import { createEmptyCanvasState, isRecord, loadCanvasState } from '@workbench/canvasMigration';
+import { isCanvasSchemaVersionSupported } from '@workbench/canvasSchemaVersion';
import { deriveControlKind, isStorableControlWeight, isStorableControlStepRange } from '@workbench/controlAdapters';
import {
readCanvasCompositingSettings,
@@ -381,7 +382,12 @@ export const prepareCanvasRecall = async ({
}));
}
const rawDocument = record.document;
- if (!isRecord(rawDocument) || ![3, 4, 5, 6].includes(Number(rawDocument.version))) {
+ if (
+ !isRecord(rawDocument) ||
+ typeof rawDocument.version !== 'number' ||
+ !Number.isInteger(rawDocument.version) ||
+ !isCanvasSchemaVersionSupported(rawDocument.version)
+ ) {
plan.problems.push('invalid-document');
return plan;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.md
index f636358dcf..99a4532717 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/README.md
+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md
@@ -101,6 +101,8 @@ Cold-start offline editing not supported. When backend cannot load, unavailable
The optional `canvas.document.stacks.vector` forest requires Canvas schema 7, even when empty after its last layer is removed. Vector layers retain their Bezier paths and layer-owned appearance in the document and snapshots without image assets. Stroke color and width are required; new layers use black strokes at 50 pixels. A document that has never used vectors omits that forest, preserving its existing compatibility floor. Schema adoption is sticky; older clients refuse schema 7 instead of dropping vector data.
+A raster layer's regenerate region drops on load when its fill does not parse, without refusing the document. A Diagonal Left (`diagonal_left`) fill on a raster regenerate region therefore makes the canvas schema 8 in the live document or any snapshot, so a schema 7 build refuses the canvas instead of autosaving it without the region. Inpaint masks and Regional Guidance refuse an unknown fill style, so `diagonal_left` on them keeps the schema unchanged.
+
New value in a closed canvas set, such as a control layer's adapter kind (`anima_lllite`), is added without raising canvas schema version or project's compatibility floor. Builds that know the value load and save it unchanged; builds that do not refuse the canvas instead of rewriting it, since coercing an unknown kind to a known one would replace the user's adapter on next autosave. In an older build the project is not opened and user sees that it "contains canvas data this version of Invoke cannot read"; saved copy is untouched and exportable, and a build that knows the value opens it as saved. Raise schema version instead when older builds could misread a document without refusing it.
Adjustment stacks are such a case: load drops a stack holding any entry it cannot parse, so an older build would load a document with a new adjustment type minus that layer's whole stack and autosave the loss. A new adjustment type therefore raises the canvas schema for documents that use it. A noise, clarity, texture or dehaze adjustment, enabled or not, on any layer or group at any depth of the live document or a saved snapshot, makes the canvas schema at least 5 (`canvasMigration.ts`, `writableCanvasSchemaVersion`); control-layer derivation fields raise it to 6 (see [Control layer derivation](#control-layer-derivation)). A document with neither keeps its version. Adoption is sticky: removing the last such entry leaves the document at its adopted schema, matching the server's monotonic floor. A build whose maximum is lower refuses the project at the server and the canvas at load as an unsupported version.
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
index ff258a70ab..90b26981bc 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
@@ -47,7 +47,7 @@ describe('getProjectWithinSize', () => {
);
await expect(getProjectWithinSize('p-1', 1000)).resolves.toEqual(record);
expect(transport.apiFetch).toHaveBeenCalledWith(
- '/api/v1/projects/p-1?max_canvas_schema_version=7&max_document_schema_version=4',
+ '/api/v1/projects/p-1?max_canvas_schema_version=8&max_document_schema_version=4',
{ signal: undefined }
);
@@ -95,7 +95,7 @@ describe('createProjectSettled', () => {
const post = () => ({
body: JSON.stringify({
...request,
- max_canvas_schema_version: 7,
+ max_canvas_schema_version: 8,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
@@ -124,7 +124,7 @@ describe('createProjectSettled', () => {
expect(transport.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/projects/', post());
expect(transport.apiFetchJson).toHaveBeenNthCalledWith(
3,
- '/api/v1/projects/project-1?max_canvas_schema_version=7&max_document_schema_version=4',
+ '/api/v1/projects/project-1?max_canvas_schema_version=8&max_document_schema_version=4',
expect.anything()
);
});
@@ -210,7 +210,7 @@ describe('canvas schema compatibility declarations', () => {
await getProject('project/one');
expect(transport.apiFetchJson).toHaveBeenCalledWith(
- '/api/v1/projects/project%2Fone?max_canvas_schema_version=7&max_document_schema_version=4',
+ '/api/v1/projects/project%2Fone?max_canvas_schema_version=8&max_document_schema_version=4',
{ signal: expect.any(AbortSignal) }
);
});
@@ -225,7 +225,7 @@ describe('canvas schema compatibility declarations', () => {
data: {},
minimum_document_schema_version: 4,
name: 'Project',
- max_canvas_schema_version: 7,
+ max_canvas_schema_version: 8,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
@@ -358,7 +358,7 @@ describe('project workspaces', () => {
body: JSON.stringify({
data: { layout: {} },
expected_revision: 1,
- max_canvas_schema_version: 7,
+ max_canvas_schema_version: 8,
max_document_schema_version: 4,
}),
method: 'PUT',
@@ -404,7 +404,7 @@ describe('project workspaces', () => {
minimum_document_schema_version: 4,
name: 'Project',
workspace: { layout: {} },
- max_canvas_schema_version: 7,
+ max_canvas_schema_version: 8,
max_document_schema_version: 4,
minimum_canvas_schema_version: 3,
}),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts
index f282368b84..6607d4cb65 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts
@@ -49,7 +49,7 @@ const galleryItem = (kind: 'image' | 'video', name: string) => ({
});
const regionalWith = (id: string, image: GeneratedImageContract | null): CanvasRegionalGuidanceLayerContract => {
- const layer = createRegionalGuidanceLayerWithRefImage(id, 0, 'sdxl', id);
+ const layer = createRegionalGuidanceLayerWithRefImage(id, undefined, 'sdxl', id);
const [reference] = layer.referenceImages;
return { ...layer, referenceImages: [{ ...reference!, config: { ...reference!.config, image } }] };
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
index d3ddfd6725..f289dca765 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
@@ -143,7 +143,7 @@ const setup = async (layers: readonly Parameters<typeof stacksFrom>[0][number][]
t: (key) => key,
});
- return { doc, engine, layer, loaded, maskBitmap, pixelAt, refusals, runCommand, select, sourceType };
+ return { doc, engine, layer, loaded, maskBitmap, overlay, pixelAt, refusals, runCommand, select, sourceType };
};
const mask = () =>
@@ -159,6 +159,37 @@ const photo = (overrides: Partial<CanvasLayerContract> = {}) =>
...overrides,
} as Partial<CanvasLayerContract>);
+it('picks the raster color beneath a visible inpaint mask through the engine', async () => {
+ const inpaint = mask();
+ if (inpaint.type !== 'inpaint_mask') {
+ throw new Error('Expected an inpaint mask fixture');
+ }
+ inpaint.mask.fill.style = 'solid';
+ const { engine, loaded, overlay } = await setup([inpaint, photo()], 'mask');
+ await loaded('mask');
+ await loaded('photo');
+
+ const point = engine.viewport.getViewport().documentToScreen({ x: 10.5, y: 10.5 });
+ const { left, top } = overlay.getBoundingClientRect();
+ const sampled = engine.tools.requestColorSample();
+ for (const [type, buttons] of [
+ ['pointerdown', 1],
+ ['pointerup', 0],
+ ] as const) {
+ overlay.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ buttons,
+ clientX: left + point.x,
+ clientY: top + point.y,
+ isPrimary: true,
+ pointerId: 1,
+ })
+ );
+ }
+ await expect(sampled).resolves.toBe('#0000ff');
+});
+
describe('selection edits on a real engine', () => {
it('Delete and Cut remove a mask’s selected coverage, one undoable step each', async () => {
const h = await setup([mask()], 'mask');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
index 298be9d527..6ff3691448 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
@@ -13,20 +13,11 @@ import {
reportMaskEdit,
useStructuralPreview,
} from '@workbench/widgets/canvas/useStructuralCommit';
+import { MASK_FILL_STYLES } from '@workbench/widgets/layers/layerOps';
import { PaletteIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */
-const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
- 'solid',
- 'grid',
- 'crosshatch',
- 'diagonal',
- 'horizontal',
- 'vertical',
-];
-
interface InpaintMaskSettingsProps {
engine: (CanvasStructuralEngine & CanvasPreparedEngine & ColorSamplerEngine) | null;
layer: CanvasInpaintMaskLayerContract;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 0a19883a08..78ebac7aee 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -22,6 +22,8 @@ import { canCopyImage } from '@platform/browser/clipboard';
import { IconButton, MenuActionItem, MenuContent, MenuIconItem, RenameDialog, Tooltip } from '@platform/ui';
import { useQueryClient } from '@tanstack/react-query';
import {
+ advanceMaskFillColors,
+ getDocumentLeaves,
canMergeSelectedRasters,
getDocumentIndex,
getDocumentLayer,
@@ -33,6 +35,7 @@ import {
isNodeHidden,
isOverlayStack,
lookupDocumentNodeState,
+ nextMaskFillColor,
renderableSourceOf,
} from '@workbench/canvas-engine/api';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
@@ -466,9 +469,15 @@ const LayerMenu = ({
layer.type === 'raster' && targetType === 'control'
? convertRasterToControl(layer, base)
: layer.type === 'raster' && targetType === 'inpaint_mask'
- ? convertRasterToInpaintMask(layer)
+ ? convertRasterToInpaintMask(
+ layer,
+ nextMaskFillColor('inpaint_mask', 0, getDocumentLeaves(canvas.document))
+ )
: layer.type === 'raster' && targetType === 'regional_guidance'
- ? convertRasterToRegionalGuidance(layer)
+ ? convertRasterToRegionalGuidance(
+ layer,
+ nextMaskFillColor('regional_guidance', 0, getDocumentLeaves(canvas.document))
+ )
: targetType === 'raster'
? convertRasterControlLayer(layer, 'raster')
: null;
@@ -480,8 +489,11 @@ const LayerMenu = ({
if (!engine?.layers.commitLayerConversion(label, layer, converted)) {
throw makeStatusError('not-ready');
}
+ if (converted.type === 'inpaint_mask' || converted.type === 'regional_guidance') {
+ advanceMaskFillColors(converted.type);
+ }
},
- [base, engine, layer, makeStatusError]
+ [base, canvas.document, engine, layer, makeStatusError]
);
const handleToggleVisibility = useCallback(() => {
@@ -762,29 +774,37 @@ const LayerMenu = ({
const handleCopyToInpaintMask = useCallback(() => {
const id = createLayerId();
+ const color = nextMaskFillColor('inpaint_mask', 0, getDocumentLeaves(canvas.document));
const copied =
layer.type === 'raster'
- ? copyRasterToInpaintMask(layer, id)
+ ? copyRasterToInpaintMask(layer, id, color)
: layer.type === 'control'
- ? copyControlToInpaintMask(layer, id)
+ ? copyControlToInpaintMask(layer, id, color)
: layer.type === 'regional_guidance'
? copyRegionalGuidanceToInpaintMask(layer, id)
: null;
addCopy(copied, getActionLabel('copy-to-inpaint-mask'));
- }, [addCopy, getActionLabel, layer]);
+ if (layer.type === 'raster' || layer.type === 'control') {
+ advanceMaskFillColors('inpaint_mask');
+ }
+ }, [addCopy, canvas.document, getActionLabel, layer]);
const handleCopyToRegionalGuidance = useCallback(() => {
const id = createLayerId();
+ const color = nextMaskFillColor('regional_guidance', 0, getDocumentLeaves(canvas.document));
const copied =
layer.type === 'raster'
- ? copyRasterToRegionalGuidance(layer, id)
+ ? copyRasterToRegionalGuidance(layer, id, color)
: layer.type === 'control'
- ? copyControlToRegionalGuidance(layer, id)
+ ? copyControlToRegionalGuidance(layer, id, color)
: layer.type === 'inpaint_mask'
? copyMaskToRegionalGuidance(layer, id)
: null;
addCopy(copied, getActionLabel('copy-to-regional-guidance'));
- }, [addCopy, getActionLabel, layer]);
+ if (layer.type === 'raster' || layer.type === 'control') {
+ advanceMaskFillColors('regional_guidance');
+ }
+ }, [addCopy, canvas.document, getActionLabel, layer]);
const handleCopyTo = useCallback(
(target: LayerType): void | Promise<void> => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx
index bbd31e7c03..0a9887b9e1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx
@@ -10,18 +10,10 @@ import {
type CanvasPreparedEngine,
useStructuralPreview,
} from '@workbench/widgets/canvas/useStructuralCommit';
+import { MASK_FILL_STYLES } from '@workbench/widgets/layers/layerOps';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
- 'solid',
- 'grid',
- 'crosshatch',
- 'diagonal',
- 'horizontal',
- 'vertical',
-];
-
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;
interface LayerRegionSettingsProps {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index f6cdcc3505..06109f228a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -47,6 +47,7 @@ import {
reportMaskEdit,
useStructuralPreview,
} from '@workbench/widgets/canvas/useStructuralCommit';
+import { MASK_FILL_STYLES } from '@workbench/widgets/layers/layerOps';
import { PaletteIcon } from 'lucide-react';
import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -62,16 +63,6 @@ interface RegionalConfigPatch {
layout?: CanvasRegionalLayoutContract | null;
}
-/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */
-const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
- 'solid',
- 'grid',
- 'crosshatch',
- 'diagonal',
- 'horizontal',
- 'vertical',
-];
-
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;
const REGIONAL_PROMPT_HEIGHT_PX = 72;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index f76dc66067..292b6b4e43 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -51,7 +51,7 @@ const makeLayer = (type: CanvasLayerContract['type']): CanvasLayerContract => {
case 'inpaint_mask':
return createInpaintMaskLayer('Mask', 'mask');
case 'regional_guidance':
- return createRegionalGuidanceLayer('Region', 0, 'region');
+ return createRegionalGuidanceLayer('Region', undefined, 'region');
case 'vector':
return createVectorLayer({ id: 'vector', name: 'Vector' });
}
@@ -247,7 +247,7 @@ describe('getLayerContextActions', () => {
},
});
const inpaint = createInpaintMaskLayer('Interaction mask', 'interaction-mask');
- const regional = createRegionalGuidanceLayer('Interaction region', 0, 'interaction-region');
+ const regional = createRegionalGuidanceLayer('Interaction region', undefined, 'interaction-region');
const contexts = [
makeState(raster, { document: rasterDocument, operationLocked: true }),
makeState(raster, {
@@ -604,7 +604,7 @@ describe('remove-from-group', () => {
describe('merge-masks', () => {
const m1 = createInpaintMaskLayer('Mask 1', 'm1');
const m2 = createInpaintMaskLayer('Mask 2', 'm2');
- const region = createRegionalGuidanceLayer('Region', 0, 'region');
+ const region = createRegionalGuidanceLayer('Region', undefined, 'region');
const layers = [m1, groupContract('G', [m2]), region];
it('replaces raster merge for a selection of inpaint masks only', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index 1d13ecbe27..f1e28478b1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -125,7 +125,7 @@ describe('getLayerContextMenuLayout', () => {
it('keeps the primary section lean now the panes own the per-type additions', () => {
const inpaint = createInpaintMaskLayer('Mask', 'mask');
- const regional = createRegionalGuidanceLayer('Region', 0, 'region');
+ const regional = createRegionalGuidanceLayer('Region', undefined, 'region');
expect(summarize(inpaint)[1]).toEqual({
id: 'primary',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
index ecd2ac79f1..4974fd4566 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
@@ -37,8 +37,6 @@ import {
isAutoControlLayerName,
isMergeableRasterLayer,
nextControlTypeLayerName,
- nextRegionalGuidanceFillColor,
- REGIONAL_GUIDANCE_FILL_COLORS,
} from './layerOps';
seedArchitectureCapabilities();
@@ -118,17 +116,6 @@ describe('createAdjustmentEntry', () => {
});
});
-describe('nextRegionalGuidanceFillColor', () => {
- it('derives the colour purely from the existing regional-guidance count (no session state)', () => {
- expect(nextRegionalGuidanceFillColor(0)).toBe(REGIONAL_GUIDANCE_FILL_COLORS[1]);
- expect(nextRegionalGuidanceFillColor(1)).toBe(REGIONAL_GUIDANCE_FILL_COLORS[2]);
- expect(nextRegionalGuidanceFillColor(REGIONAL_GUIDANCE_FILL_COLORS.length - 1)).toBe(
- REGIONAL_GUIDANCE_FILL_COLORS[0]
- );
- expect(nextRegionalGuidanceFillColor(0)).toBe(nextRegionalGuidanceFillColor(0));
- });
-});
-
describe('isMergeableRasterLayer', () => {
it.each<[string, CanvasLayerContract, boolean]>([
['accepts an enabled paint raster layer', paintLayer('p'), true],
@@ -428,13 +415,13 @@ describe('layer copy and conversion parity', () => {
type: 'control',
withTransparencyEffect: true,
});
- expect(copyRasterToInpaintMask(raster, 'm-copy')).toMatchObject({
+ expect(copyRasterToInpaintMask(raster, 'm-copy', '#38C9C5')).toMatchObject({
id: 'm-copy',
- mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
+ mask: { bitmap: raster.source.bitmap, fill: { color: '#38C9C5' }, offset: raster.source.offset },
name: 'Raster copy',
type: 'inpaint_mask',
});
- expect(copyRasterToRegionalGuidance(raster, 'rg-copy')).toMatchObject({
+ expect(copyRasterToRegionalGuidance(raster, 'rg-copy', '#38C9C5')).toMatchObject({
autoNegative: false,
id: 'rg-copy',
mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
@@ -446,14 +433,14 @@ describe('layer copy and conversion parity', () => {
});
expect(convertRasterToControl(raster)).toMatchObject({ id: 'r1', source: raster.source, type: 'control' });
- expect(convertRasterToInpaintMask(raster)).toMatchObject({
+ expect(convertRasterToInpaintMask(raster, '#38C9C5')).toMatchObject({
id: 'r1',
mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
type: 'inpaint_mask',
});
- expect(convertRasterToRegionalGuidance(raster)).toMatchObject({
+ expect(convertRasterToRegionalGuidance(raster, '#38C9C5')).toMatchObject({
id: 'r1',
- mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
+ mask: { bitmap: raster.source.bitmap, fill: { color: '#38C9C5' }, offset: raster.source.offset },
type: 'regional_guidance',
});
});
@@ -468,12 +455,12 @@ describe('layer copy and conversion parity', () => {
transform,
type: 'raster',
});
- expect(copyControlToInpaintMask(control, 'm-copy')).toMatchObject({
+ expect(copyControlToInpaintMask(control, 'm-copy', '#38C9C5')).toMatchObject({
id: 'm-copy',
mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
type: 'inpaint_mask',
});
- expect(copyControlToRegionalGuidance(control, 'rg-copy')).toMatchObject({
+ expect(copyControlToRegionalGuidance(control, 'rg-copy', '#38C9C5')).toMatchObject({
id: 'rg-copy',
mask: { bitmap: raster.source.bitmap, offset: raster.source.offset },
type: 'regional_guidance',
@@ -518,11 +505,11 @@ describe('layer copy and conversion parity', () => {
};
expect(copyRasterToControl(text, 'copy')).toBeNull();
- expect(copyRasterToInpaintMask(text, 'copy')).toBeNull();
- expect(copyRasterToRegionalGuidance(text, 'copy')).toBeNull();
+ expect(copyRasterToInpaintMask(text, 'copy', '#38C9C5')).toBeNull();
+ expect(copyRasterToRegionalGuidance(text, 'copy', '#38C9C5')).toBeNull();
expect(convertRasterToControl(text)).toBeNull();
- expect(convertRasterToInpaintMask(text)).toBeNull();
- expect(convertRasterToRegionalGuidance(text)).toBeNull();
+ expect(convertRasterToInpaintMask(text, '#38C9C5')).toBeNull();
+ expect(convertRasterToRegionalGuidance(text, '#38C9C5')).toBeNull();
});
});
@@ -539,7 +526,7 @@ describe('createRegionalReferenceImage', () => {
describe('createRegionalGuidanceLayerWithRefImage', () => {
it('is a regional guidance layer pre-seeded with exactly one empty reference image', () => {
- const layer = createRegionalGuidanceLayerWithRefImage('Region 1', 0, 'sdxl', 'rg-1');
+ const layer = createRegionalGuidanceLayerWithRefImage('Region 1', undefined, 'sdxl', 'rg-1');
expect(layer.type).toBe('regional_guidance');
expect(layer.id).toBe('rg-1');
expect(layer.referenceImages).toHaveLength(1);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index 184a89b395..742ce64b71 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -22,6 +22,8 @@ import { getRegionalGuidanceSupport } from '@features/generation/graph';
import { createItemId } from '@platform/browser/randomUuid';
import {
createControlLayer,
+ DEFAULT_INPAINT_MASK_FILL,
+ DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR,
getSourceContentRect,
isIdentityAdjustments,
isMergeableRasterLayer,
@@ -62,6 +64,17 @@ export const CANVAS_BLEND_MODES: readonly CanvasBlendMode[] = [
'luminosity',
];
+/** Fill styles in the order every mask and region menu lists them. */
+export const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
+ 'solid',
+ 'grid',
+ 'crosshatch',
+ 'diagonal_left',
+ 'diagonal',
+ 'horizontal',
+ 'vertical',
+];
+
/** Mints a fresh layer id (matches the engine's `createLayerId` shape). */
export const createLayerId = (): string => createItemId('layer');
@@ -79,7 +92,7 @@ export const createEmptyPaintLayer = (name: string, id: string = createLayerId()
});
/** Use the legacy diagonal inpaint hatch and first fill color; multiple masks are allowed. */
-export const DEFAULT_INPAINT_MASK_FILL = { color: '#e07575', style: 'diagonal' } as const;
+export { DEFAULT_INPAINT_MASK_FILL };
/** The next free "Inpaint Mask N" name given the existing layer names (N ≥ 1, first gap). */
export const nextInpaintMaskName = (existingNames: readonly string[]): string => {
@@ -143,33 +156,22 @@ export const isAutoControlLayerName = (name: string, typeLabels: readonly string
['Control Layer', ...typeLabels].some((prefix) => numberedSuffix(prefix, name) !== null);
/** Builds an empty inpaint mask layer with the legacy-default fill (no bitmap yet). */
-export const createInpaintMaskLayer = (name: string, id: string = createLayerId()): CanvasInpaintMaskLayerContract => ({
+export const createInpaintMaskLayer = (
+ name: string,
+ id: string = createLayerId(),
+ color: string = DEFAULT_INPAINT_MASK_FILL.color
+): CanvasInpaintMaskLayerContract => ({
blendMode: 'normal',
id,
isEnabled: true,
isLocked: false,
- mask: { bitmap: null, fill: { ...DEFAULT_INPAINT_MASK_FILL } },
+ mask: { bitmap: null, fill: { ...DEFAULT_INPAINT_MASK_FILL, color } },
name,
opacity: 1,
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'inpaint_mask',
});
-/** Cycle legacy regional fill colors to distinguish overlaps. */
-export const REGIONAL_GUIDANCE_FILL_COLORS: readonly string[] = [
- '#799ddb',
- '#83d683',
- '#fae150',
- '#dc9065',
- '#e07575',
- '#d58bca',
- '#a178d6',
-];
-
-/** Colors from the document's region count, legacy pre-increment: the first region uses palette index 1. */
-export const nextRegionalGuidanceFillColor = (existingRegionalGuidanceCount: number): string =>
- REGIONAL_GUIDANCE_FILL_COLORS[(existingRegionalGuidanceCount + 1) % REGIONAL_GUIDANCE_FILL_COLORS.length];
-
/** The next free "Regional Guidance N" name given the existing layer names (N ≥ 1, first gap). */
export const nextRegionalGuidanceName = (existingNames: readonly string[]): string => {
const used = new Set<number>();
@@ -191,7 +193,7 @@ export const nextRegionalGuidanceName = (existingNames: readonly string[]): stri
export const createRegionalGuidanceLayer = (
name: string,
- existingRegionalGuidanceCount: number,
+ color: string | undefined,
id: string = createLayerId()
): CanvasRegionalGuidanceLayerContract => ({
autoNegative: false,
@@ -201,7 +203,7 @@ export const createRegionalGuidanceLayer = (
isLocked: false,
mask: {
bitmap: null,
- fill: { color: nextRegionalGuidanceFillColor(existingRegionalGuidanceCount), style: 'solid' },
+ fill: { color: color ?? DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR, style: 'solid' },
},
name,
negativePrompt: null,
@@ -232,7 +234,7 @@ export const createInpaintMaskFromImage = (input: CreateMaskLayerFromImageInput)
export const createRegionalGuidanceFromImage = (
input: CreateMaskLayerFromImageInput
): CanvasRegionalGuidanceLayerContract => ({
- ...createRegionalGuidanceLayer(input.name, 0, input.id),
+ ...createRegionalGuidanceLayer(input.name, undefined, input.id),
mask: {
bitmap: { ...input.image },
fill: { ...input.fill },
@@ -332,11 +334,11 @@ export const canAddRegionalReferenceImage = (base: string | null): boolean =>
export const createRegionalGuidanceLayerWithRefImage = (
name: string,
- existingRegionalGuidanceCount: number,
+ color: string | undefined,
base: string | null,
id: string = createLayerId()
): CanvasRegionalGuidanceLayerContract => ({
- ...createRegionalGuidanceLayer(name, existingRegionalGuidanceCount, id),
+ ...createRegionalGuidanceLayer(name, color, id),
referenceImages: [createRegionalReferenceImage(base)],
});
@@ -420,17 +422,17 @@ const clonePixelSource = (layer: PixelLayer): CanvasPixelSourceContract | null =
return null;
};
-const pixelLayerToMask = (layer: PixelLayer): CanvasMaskContract | null => {
+const pixelLayerToMask = (layer: PixelLayer, color: string): CanvasMaskContract | null => {
const source = clonePixelSource(layer);
if (!source) {
return null;
}
if (source.type === 'image') {
- return { bitmap: source.image, fill: { ...DEFAULT_INPAINT_MASK_FILL } };
+ return { bitmap: source.image, fill: { ...DEFAULT_INPAINT_MASK_FILL, color } };
}
return {
bitmap: source.bitmap,
- fill: { ...DEFAULT_INPAINT_MASK_FILL },
+ fill: { ...DEFAULT_INPAINT_MASK_FILL, color },
offset: source.offset,
};
};
@@ -470,18 +472,20 @@ const pixelLayerToControl = (
const pixelLayerToInpaintMask = (
layer: PixelLayer,
id: string,
- isCopy: boolean
+ isCopy: boolean,
+ color: string
): CanvasInpaintMaskLayerContract | null => {
- const mask = pixelLayerToMask(layer);
+ const mask = pixelLayerToMask(layer, color);
return mask ? { ...destinationBase(layer, id, isCopy), mask, type: 'inpaint_mask' } : null;
};
const pixelLayerToRegionalGuidance = (
layer: PixelLayer,
id: string,
- isCopy: boolean
+ isCopy: boolean,
+ color: string
): CanvasRegionalGuidanceLayerContract | null => {
- const mask = pixelLayerToMask(layer);
+ const mask = pixelLayerToMask(layer, color);
return mask
? {
...destinationBase(layer, id, isCopy),
@@ -501,27 +505,33 @@ export const copyRasterToControl = (
base?: string | null
): CanvasControlLayerContract | null => pixelLayerToControl(layer, id, true, base);
+// Pixel layers carry no mask color; callers pass the destination palette's next color.
export const copyRasterToInpaintMask = (
layer: CanvasRasterLayerContractV2,
- id: string
-): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true);
+ id: string,
+ color: string
+): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true, color);
export const copyRasterToRegionalGuidance = (
layer: CanvasRasterLayerContractV2,
- id: string
-): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true);
+ id: string,
+ color: string
+): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true, color);
export const convertRasterToControl = (
layer: CanvasRasterLayerContractV2,
base?: string | null
): CanvasControlLayerContract | null => pixelLayerToControl(layer, layer.id, false, base);
-export const convertRasterToInpaintMask = (layer: CanvasRasterLayerContractV2): CanvasInpaintMaskLayerContract | null =>
- pixelLayerToInpaintMask(layer, layer.id, false);
+export const convertRasterToInpaintMask = (
+ layer: CanvasRasterLayerContractV2,
+ color: string
+): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, layer.id, false, color);
export const convertRasterToRegionalGuidance = (
- layer: CanvasRasterLayerContractV2
-): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, layer.id, false);
+ layer: CanvasRasterLayerContractV2,
+ color: string
+): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, layer.id, false, color);
export const copyControlToRaster = (
layer: CanvasControlLayerContract,
@@ -533,13 +543,15 @@ export const copyControlToRaster = (
export const copyControlToInpaintMask = (
layer: CanvasControlLayerContract,
- id: string
-): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true);
+ id: string,
+ color: string
+): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true, color);
export const copyControlToRegionalGuidance = (
layer: CanvasControlLayerContract,
- id: string
-): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true);
+ id: string,
+ color: string
+): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true, color);
export const copyMaskToRegionalGuidance = (
layer: CanvasInpaintMaskLayerContract,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index d440a1e86a..bcdc261c20 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -996,6 +996,15 @@ describe('Color pane', () => {
await expect.element(foreground).toHaveAttribute('aria-pressed', 'false');
});
+ it('marks a picked default mask swatch as selected', async () => {
+ await mount(SwatchesPane);
+ const swatch = page.getByRole('button', { exact: true, name: '#f59e42' }).first();
+ await act(async () => {
+ await userEvent.click(swatch);
+ });
+ await expect.element(swatch).toHaveAttribute('aria-pressed', 'true');
+ });
+
it('adds the current color to the project palette and removes it by right-click', async () => {
await mount(SwatchesPane);
await act(async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
index 4cbe4ca577..eb380d6d04 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
@@ -1,10 +1,12 @@
import type { CanvasNodeContract } from '@workbench/canvas-engine/api';
import {
+ advanceMaskFillColors,
createControlLayer,
getDocumentIndex,
getDocumentLeaves,
nextControlLayerName,
+ nextMaskFillColor,
} from '@workbench/canvas-engine/api';
import { useCanvasEngine } from '@workbench/canvas-operations/react';
import { setLayerGroupExpanded } from '@workbench/layerPanelState';
@@ -40,19 +42,22 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
(project) => getDocumentIndex(project.canvas.document).nodes.map((entry) => entry.node.name),
(left, right) => left.length === right.length && left.every((name, index) => name === right[index])
);
- const regionalGuidanceCount = useActiveProjectSelector(
- (project) => getDocumentLeaves(project.canvas.document).filter((layer) => layer.type === 'regional_guidance').length
- );
-
return useCallback(
(id: AddLayerItemId) => {
if (!isAddLayerItemAvailable(id, base)) {
return;
}
- const add = (label: string, node: CanvasNodeContract) =>
- commitPrepared(label, (model) =>
+ const add = (label: string, node: CanvasNodeContract) => {
+ const outcome = commitPrepared(label, (model) =>
model.prepare({ aboveId: model.document.selectedLayerId, nodes: [node], type: 'insert' })
);
+ if (outcome.status === 'committed' && (node.type === 'inpaint_mask' || node.type === 'regional_guidance')) {
+ advanceMaskFillColors(node.type);
+ }
+ return outcome;
+ };
+ const document = engine?.document.getDocument();
+ const maskLayers = () => (document ? getDocumentLeaves(document) : []);
switch (id) {
case 'vector': {
if (!engine) {
@@ -104,19 +109,26 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
return;
}
case 'inpaint_mask': {
- const layer = createInpaintMaskLayer(nextInpaintMaskName(layerNames));
+ const layer = createInpaintMaskLayer(
+ nextInpaintMaskName(layerNames),
+ undefined,
+ nextMaskFillColor('inpaint_mask', 0, maskLayers())
+ );
add(t('widgets.layers.actions.addInpaintMask'), layer);
return;
}
case 'regional_guidance': {
- const layer = createRegionalGuidanceLayer(nextRegionalGuidanceName(layerNames), regionalGuidanceCount);
+ const layer = createRegionalGuidanceLayer(
+ nextRegionalGuidanceName(layerNames),
+ nextMaskFillColor('regional_guidance', 0, maskLayers())
+ );
add(t('widgets.layers.actions.addRegionalGuidance'), layer);
return;
}
case 'regional_reference_image': {
const layer = createRegionalGuidanceLayerWithRefImage(
nextRegionalGuidanceName(layerNames),
- regionalGuidanceCount,
+ nextMaskFillColor('regional_guidance', 0, maskLayers()),
base
);
add(t('widgets.layers.actions.addRegionalReferenceImage'), layer);
@@ -124,6 +136,6 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
}
}
},
- [engine, base, commitPrepared, layerNames, projectId, regionalGuidanceCount, t]
+ [engine, base, commitPrepared, layerNames, projectId, t]
);
};