Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): polygon and freehand shapes drawn onto the selected layer
Josh Corbett89c9927a6fa4
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4549eb60dc..993c218c76 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2718,9 +2718,16 @@"shapeEdit": "Edit shape","shapeEllipse": "Ellipse","shapeFill": "Fill",+ "shapeFreehand": "Freehand",+ "shapeFreehandHint": "Drag to draw a freeform shape.","shapeHint": "Drag to draw a shape.",+ "shapePolygon": "Polygon",+ "shapePolygonHint": "Click to place points. Double-click, Enter, or click the first point to close.","shapeRect": "Rectangle","shapeStar": "Star",+ "shapeTarget": "Place on",+ "shapeTargetNew": "New layer",+ "shapeTargetSelected": "Selected layer","shapeTriangle": "Triangle","shapeStroke": "Stroke","shapeStrokeWidth": "Stroke width",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex cc7e808659..b18ae007d3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -593,7 +593,9 @@ export type {LassoToolOptions,LayerThumbnailStatus,MarqueeToolOptions,+ ShapeToolKind,ShapeToolOptions,+ ShapeToolTarget,TextEditSession,TextToolOptions,TransformSession,@@ -619,7 +621,13 @@ export {type CompositeEntry,type CompositeLayerRef,} from './render/rasterComposite';-export { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';+export {+ getSourceBounds,+ getSourceContentRect,+ isEmptyPolygonShape,+ isRenderableLayer,+ renderableSourceOf,+} from './document/sources';export {areSelectedRasterLayersContiguous,canMergeSelectedRasters,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex e4827c50ef..faf87d4d53 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -100,7 +100,7 @@ export interface CanvasImageRef {contentHash?: string;}-/** The drag-drawable shape kinds; `polygon` (point lists) stays a non-tool source. */+/** The box-parametric shape kinds; `polygon` carries its own point list instead. */export type ParametricShapeKind = 'rect' | 'ellipse' | 'triangle' | 'star';export type CanvasLayerSourceContract =@@ -131,6 +131,7 @@ export type CanvasLayerSourceContract =| {type: 'shape';kind: ParametricShapeKind | 'polygon';+ /** Polygon vertices in layer-local px across the `width`×`height` box, closed implicitly. */points?: { x: number; y: number }[];width: number;height: number;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 76278d9280..143df22211 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -27,6 +27,7 @@ import {import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { createLayerSnapshotEntry } from '@workbench/canvas-engine/history/layerSnapshot';import { isEmpty } from '@workbench/canvas-engine/math/rect';+import { strokeCommitLabel } from '@workbench/canvas-engine/strokeCommit';export interface PixelEditControllerOptions {readonly applyImagePatch: ImagePatchApply;@@ -274,7 +275,7 @@ export class PixelEditController {return;}if (- commitPatch(event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke', {+ commitPatch(strokeCommitLabel(event.tool), {after: event.afterImageData,before: event.beforeImageData,rect: event.dirtyRect,@@ -456,7 +457,7 @@ export class PixelEditController {commitStroke: (event) =>isImageDataEqual(event.beforeImageData, event.afterImageData)? cancel()- : commit(event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke', event),+ : commit(strokeCommitLabel(event.tool), event),layerId,};owner = { cancel, layerId };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex 2d9a1c4374..797b003dd9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -6,7 +6,7 @@ import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';-import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';+import { getSourceContentRect, isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { rasterizeSource } from '@workbench/canvas-engine/render/rasterizers';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';@@ -44,7 +44,7 @@ export class RasterizeLayerController {const source = layer.source;if ((source.type !== 'shape' && source.type !== 'gradient' && source.type !== 'text') ||- (source.type === 'shape' && source.kind === 'polygon')+ (source.type === 'shape' && isEmptyPolygonShape(source))) {return false;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.tsindex 8c31d44d1f..6384ff1afa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts@@ -16,6 +16,7 @@ import type {CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,+ ParametricShapeKind,} from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';@@ -65,10 +66,13 @@ export const renderableSourceOf = (layer: CanvasLayerContract): CanvasLayerSourcreturn maskAsPaintSource(layer);};+/** A polygon shape needs three points to fill; anything less has no raster. */+export const isEmptyPolygonShape = (source: { kind: ParametricShapeKind | 'polygon'; points?: unknown[] }): boolean =>+ source.kind === 'polygon' && (source.points?.length ?? 0) < 3;+/**- * True when a layer's source is one the engine can rasterize today: image,- * paint, gradient, text, or a parametric (non-polygon) shape. A `polygon` shape has no- * rasterizer yet (deferred), so it is not renderable.+ * True when a layer's source is one the engine can rasterize: image, paint,+ * gradient, text, or a shape — a polygon only once it has three points.*/export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {if (!isLayerContributing(layer)) {@@ -90,7 +94,7 @@ export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {case 'text':return true;case 'shape':- return source.kind !== 'polygon';+ return !isEmptyPolygonShape(source);default:return false;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.tsindex b5285a9aaa..d826b436e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts@@ -6,6 +6,7 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { Rect } from '@workbench/canvas-engine/types';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { bakeMatrix, IDENTITY_TRANSFORM, type LayerTransform } from '@workbench/canvas-engine/transform/transformMath';@@ -36,7 +37,7 @@ const isIdentity = (transform: LayerTransform): boolean =>const isRasterizable = (layer: PixelEditableLayer): boolean =>layer.type === 'raster'? layer.source.type === 'image' || layer.source.type === 'paint'- : layer.source.type !== 'shape' || layer.source.kind !== 'polygon';+ : layer.source.type !== 'shape' || !isEmptyPolygonShape(layer.source);/** Whether the leaf, with its ancestors applied, can take a direct pixel edit. */export const isLeafPixelEditEligible = (leaf: SemanticLeaf | null | undefined): boolean =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 3ad51e3b61..acf5c103a5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -2147,15 +2147,12 @@ describe('createCanvasEngine', () => {});it('cropLayerToBbox reports missing, locked, unsupported, and not-ready layers explicitly', async () => {+ // A polygon without enough points to fill has no raster to crop.const polygon: CanvasLayerSourceContract = {fill: '#000',height: 10,kind: 'polygon',- points: [- { x: 0, y: 0 },- { x: 10, y: 0 },- { x: 5, y: 10 },- ],+ points: [],stroke: null,strokeWidth: 0,type: 'shape',@@ -14273,16 +14270,13 @@ describe('hasExportableLayerContent', () => {engine.lifecycle.dispose();});- it('returns false for empty paint, unsupported polygon, and missing ids', () => {+ it('returns false for empty paint, pointless polygon, and missing ids', () => {+ // A polygon without enough points to fill has no raster to export.const polygon: CanvasLayerSourceContract = {fill: '#000',height: 20,kind: 'polygon',- points: [- { x: 0, y: 0 },- { x: 20, y: 0 },- { x: 10, y: 20 },- ],+ points: [],stroke: null,strokeWidth: 0,type: 'shape',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 8e785c7b97..e53bedd7a5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -97,19 +97,28 @@ export interface GradientStop {* foreground/background pair at gesture start — there is no second global* shape color; a selected shape's explicit fill/stroke is document state.*/+export type ShapeToolKind = ParametricShapeKind | 'polygon' | 'freehand';++/** Where a drawn shape lands: pixels on the selected paint layer, or its own shape layer. */+export type ShapeToolTarget = 'selected' | 'new';+export interface ShapeToolOptions {- kind: ParametricShapeKind;+ /** The box-parametric kinds drag out a rect; `polygon` places vertices, `freehand` traces a drag. */+ kind: ShapeToolKind;+ /** Falls back to a new shape layer whenever the selected layer cannot take pixels. */+ target: ShapeToolTarget;fillEnabled: boolean;strokeEnabled: boolean;strokeWidth: number;}-/** Sensible starting shape options: a filled rect, no stroke. */+/** Sensible starting shape options: a filled rect, no stroke, drawn onto the selected paint layer. */export const DEFAULT_SHAPE_OPTIONS: ShapeToolOptions = {fillEnabled: true,kind: 'rect',strokeEnabled: false,strokeWidth: 8,+ target: 'selected',};/** Largest shape stroke width (document px) the options bar clamps to. */@@ -632,6 +641,7 @@ const marqueeOptionsEqual = (a: MarqueeToolOptions, b: MarqueeToolOptions): boolconst shapeOptionsEqual = (a: ShapeToolOptions, b: ShapeToolOptions): boolean =>a.kind === b.kind &&+ a.target === b.target &&a.fillEnabled === b.fillEnabled &&a.strokeEnabled === b.strokeEnabled &&a.strokeWidth === b.strokeWidth;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.tsindex 6059659517..05fc06044d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts@@ -9,16 +9,16 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/import { areJsonValuesStructurallyEqual } from '@platform/core/json';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';-import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';+import {+ getSourceContentRect,+ isEmptyPolygonShape,+ renderableSourceOf,+} from '@workbench/canvas-engine/document/sources';import { isEmpty } from '@workbench/canvas-engine/math/rect';-/** Polygon shapes have no raster path, so they can never back an export. */-export const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {- if (source.type === 'shape') {- return source.kind !== 'polygon';- }- return true;-};+/** A pointless polygon shape has no raster, so it can never back an export. */+export const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean =>+ source.type !== 'shape' || !isEmptyPolygonShape(source);/** A raster layer a PSD or raster export can contain; an empty layer is still counted and handled at export time. */export const isExportableRasterLayer = (layer: CanvasLayerContract): boolean =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.tsindex fc446c6d0b..0f0334b945 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts@@ -12,6 +12,8 @@import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import { isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';+import type { RasterizeDeps, RasterizeResult } from './types';import { rasterizeGradientSource } from './gradientRasterizer';@@ -42,8 +44,8 @@ export const rasterizeSource = (case 'paint':return rasterizePaintSource(source, deps, target);case 'shape':- if (source.kind === 'polygon') {- throw new Error("rasterizeSource: 'polygon' shapes are not implemented yet (deferred)");+ if (isEmptyPolygonShape(source)) {+ throw new Error('rasterizeSource: a polygon shape needs at least three points');}return rasterizeShapeSource(source, deps, target);case 'gradient':diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.tsindex 02127b6ea3..5f401f14b6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts@@ -180,7 +180,7 @@ describe('rasterizeSource — paint', () => {});describe('rasterizeSource — unimplemented sources', () => {- it('throws for the deferred polygon shape kind', () => {+ it('throws for a polygon shape without enough points to fill', () => {const { backend } = createSpyBackend();const resolver = vi.fn<ImageResolver>(() => Promise.resolve(new Blob()));const deps = makeDeps(resolver, backend);@@ -193,7 +193,29 @@ describe('rasterizeSource — unimplemented sources', () => {type: 'shape',width: 10,} as unknown as CanvasLayerSourceContract;- expect(() => rasterizeSource(source, deps)).toThrow(/not implemented/i);+ expect(() => rasterizeSource(source, deps)).toThrow(/three points/i);+ });++ it('rasterizes a polygon shape once it has points', async () => {+ const { backend } = createSpyBackend();+ const resolver = vi.fn<ImageResolver>(() => Promise.resolve(new Blob()));+ const deps = makeDeps(resolver, backend);+ const source = {+ fill: '#000000',+ height: 10,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 5, y: 10 },+ ],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ } as unknown as CanvasLayerSourceContract;+ const { rect } = await rasterizeSource(source, deps);+ expect(rect).toEqual({ height: 10, width: 10, x: 0, y: 0 });});it('rasterizes shape, gradient, and text sources (no longer throwing)', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.tsindex 7e03e4103a..7f9651fa69 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts@@ -49,6 +49,38 @@ describe('rasterizeShapeSource — extent + sizing', () => {});});+describe('rasterizeShapeSource — polygon', () => {+ it('traces the stored vertices, rescaled into the stroke inset box', async () => {+ const deps = makeDeps();+ const surface = (+ await rasterizeShapeSource(+ rect({+ fill: null,+ height: 40,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 60, y: 0 },+ { x: 30, y: 40 },+ ],+ stroke: '#0000ff',+ strokeWidth: 8,+ width: 60,+ }),+ deps+ )+ ).surface as StubRasterSurface;+ // Inset 4px per side: the 60×40 box becomes 52×32 at (4, 4).+ expect(surface.callLog.find((e) => e.op === 'moveTo')?.args).toEqual([4, 4]);+ expect(surface.callLog.filter((e) => e.op === 'lineTo').map((e) => e.args)).toEqual([+ [56, 4],+ [30, 36],+ ]);+ expect(ops(surface)).toContain('closePath');+ expect(ops(surface)).toContain('stroke');+ });+});+describe('rasterizeShapeSource — rect', () => {it('fills a rect covering the full extent when fill is set and no stroke', async () => {const deps = makeDeps();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.tsindex a013a2e9dd..0c93fd5850 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts@@ -1,7 +1,6 @@/**- * Rasterizes a `shape` layer source (rect / ellipse / triangle / star). Shape- * layers are- * PARAMETRIC: their pixels are derived from the source params (`width`,+ * Rasterizes a `shape` layer source (rect / ellipse / triangle / star /+ * polygon). Shape layers are PARAMETRIC: their pixels are derived from the source params (`width`,* `height`, `fill`, `stroke`, `strokeWidth`, `kind`) rather than a persisted* bitmap, so they re-render for free whenever a param changes.*@@ -12,9 +11,8 @@* thick outline stays entirely within the extent rather than clipping at the* surface edge.*- * `polygon` is intentionally NOT handled here (deferred until a points-editing- * UX exists); the dispatch never routes a polygon source to this rasterizer in- * this phase.+ * `polygon` sources carry their vertices across the extent; a polygon with+ * fewer than three points has nothing to draw and is refused by the dispatch.** Zero React, zero import-time side effects.*/@@ -48,13 +46,31 @@ export const buildParametricShapePath = (y: number,width: number,height: number,- inset: number+ inset: number,+ points?: readonly { x: number; y: number }[]): void => {const w = Math.max(0, width - inset * 2);const h = Math.max(0, height - inset * 2);const cx = x + width / 2;const cy = y + height / 2;ctx.beginPath();+ if (kind === 'polygon') {+ // Vertices are stored across the un-inset box; rescale them into the+ // inset one (the same box rescale the other kinds get).+ const sx = width > 0 ? w / width : 1;+ const sy = height > 0 ? h / height : 1;+ (points ?? []).forEach((point, index) => {+ const px = x + inset + point.x * sx;+ const py = y + inset + point.y * sy;+ if (index === 0) {+ ctx.moveTo(px, py);+ } else {+ ctx.lineTo(px, py);+ }+ });+ ctx.closePath();+ return;+ }if (kind === 'ellipse') {ctx.ellipse(cx, cy, w / 2, h / 2, 0, 0, Math.PI * 2);return;@@ -83,12 +99,39 @@ export const buildParametricShapePath = (ctx.closePath();return;}- // `rect` (and, defensively, `polygon` which the dispatch never sends here).ctx.rect(x + inset, y + inset, w, h);};-const buildShapePath = (ctx: Ctx, kind: ShapeSource['kind'], width: number, height: number, inset: number): void =>- buildParametricShapePath(ctx, kind, 0, 0, width, height, inset);+/**+ * Draws a shape source's fill then stroke into an `x/y + width×height` box on+ * the current transform. Shared by the layer rasterizer and the shape tool's+ * pixel placement so both stroke a shape the same way.+ */+export const drawShapeSource = (+ ctx: Ctx,+ source: ShapeSource,+ x: number,+ y: number,+ width: number,+ height: number+): void => {+ if (source.fill) {+ ctx.fillStyle = source.fill;+ buildParametricShapePath(ctx, source.kind, x, y, width, height, 0, source.points);+ ctx.fill();+ }+ if (source.stroke && source.strokeWidth > 0) {+ ctx.strokeStyle = source.stroke;+ ctx.lineWidth = source.strokeWidth;+ // Round joins keep sharp vertices within the half-stroke inset (a miter+ // would spike past it); a rect keeps its miter — the 90° tip lands exactly+ // on the extent corner, and rounding it would re-render every stored rect.+ ctx.lineJoin = source.kind === 'rect' || source.kind === 'ellipse' ? 'miter' : 'round';+ // Inset by half the stroke width so the (centered) stroke stays inside the extent.+ buildParametricShapePath(ctx, source.kind, x, y, width, height, source.strokeWidth / 2, source.points);+ ctx.stroke();+ }+};/*** Draws a shape source onto a surface sized to the source extent. Reuses@@ -112,23 +155,7 @@ export const rasterizeShapeSource = (ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, width, height);- if (source.fill) {- ctx.fillStyle = source.fill;- buildShapePath(ctx, source.kind, width, height, 0);- ctx.fill();- }-- if (source.stroke && source.strokeWidth > 0) {- ctx.strokeStyle = source.stroke;- ctx.lineWidth = source.strokeWidth;- // Round joins keep sharp vertices within the half-stroke inset (a miter- // would spike past it); a rect keeps its miter — the 90° tip lands exactly- // on the extent corner, and rounding it would re-render every stored rect.- ctx.lineJoin = source.kind === 'triangle' || source.kind === 'star' ? 'round' : 'miter';- // Inset by half the stroke width so the (centered) stroke stays inside the extent.- buildShapePath(ctx, source.kind, width, height, source.strokeWidth / 2);- ctx.stroke();- }+ drawShapeSource(ctx, source, 0, 0, width, height);return Promise.resolve({ rect: { height, width, x: 0, y: 0 }, surface });};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex ed80c0312a..2b98665a67 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -21,6 +21,10 @@ export interface CreateStrokeCommitDeps {readonly strokeListeners: ReadonlySet<(event: StrokeCommittedEvent) => void>;}+/** The history label for a committed pixel stroke. */+export const strokeCommitLabel = (tool: StrokeCommittedEvent['tool']): string =>+ tool === 'eraser' ? 'Eraser stroke' : tool === 'shape' ? 'Draw shape' : 'Brush stroke';+export interface StrokeCommit {/** Records one committed tool stroke: persistence, history, then subscriber fanout. */commitOrdinaryStroke(event: StrokeCommittedEvent): void;@@ -76,7 +80,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =// stroke, so this never fires during apply — the guard is belt-and-braces.if (!history.isApplying()) {deps.commitPaintEdit();- const label = event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke';+ const label = strokeCommitLabel(event.tool);history.push(event.createdLayer? createComposedPaintEntry(event.createdLayer, event, label)diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.tsindex 6c7aaf9788..f2f44b4721 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts@@ -231,7 +231,7 @@ describe('lassoTool: polygon mode', () => {click(tool, ctx, 0, 0, 0);click(tool, ctx, 40, 0, 1000);click(tool, ctx, 40, 40, 2000);- // Within POLYGON_CLOSE_HIT_PX of the first vertex (identity viewport).+ // Within the polyline close radius of the first vertex (identity viewport).click(tool, ctx, 3, 2, 3000);expect(commits).toHaveLength(1);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.tsindex eacbec7593..525632962a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts@@ -13,7 +13,7 @@* - **polygon** (`shape: 'polygon'`) — a click-to-place-vertex SESSION spanning* many clicks. Each press appends a vertex; a rubber-band segment tracks the* cursor. The session closes and commits on a double-click, on Enter, or on a- * click landing within {@link POLYGON_CLOSE_HIT_PX} screen pixels of the first+ * click landing within the shared polyline close radius of the first* vertex. Escape drops it.** A live dashed preview of the in-progress path is published to the engine's@@ -34,24 +34,21 @@ import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMoimport type { Tool, ToolContext } from './tool';+import {+ MIN_POLYLINE_POINTS,+ movePolyline,+ polylinePreview,+ pressPolyline,+ startPolyline,+ type PolylineSession,+} from './polylineSession';+/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;/** Minimum document-space gap between stored polygon points (input decimation). */export const LASSO_MIN_POINT_DISTANCE = 2;-/** Fewest distinct points that make a fillable selection polygon. */-const MIN_POLYGON_POINTS = 3;--/** Screen-pixel radius around the first vertex where a click closes the polygon. */-export const POLYGON_CLOSE_HIT_PX = 8;--/** Longest gap (ms) between two presses that still reads as a double-click. */-export const POLYGON_DOUBLE_CLICK_MS = 350;--/** Screen-pixel radius within which two presses count as the same spot. */-const POLYGON_DOUBLE_CLICK_PX = 4;-const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);/** A freehand drag in progress. */@@ -61,16 +58,8 @@ interface FreehandSession {}/** A polygon vertex-placing session spanning multiple clicks. */-interface PolygonSession {+interface PolygonSession extends PolylineSession {kind: 'polygon';- points: Vec2[];- /** The rubber-band endpoint (the last cursor position), or `null` before any move. */- cursor: Vec2 | null;- /** Whether the cursor sits on the first vertex, where a click closes the polygon. */- closeArmed: boolean;- /** Screen position and time of the previous press, for double-click detection. */- lastPressScreen: Vec2;- lastPressAt: number;}type Session = FreehandSession | PolygonSession;@@ -96,13 +85,7 @@ export const createLassoTool = (): Tool => {if (!session || session.points.length === 0) {ctx.stores.lassoPreview.set(null);} else if (session.kind === 'polygon') {- ctx.stores.lassoPreview.set({- closeArmed: session.closeArmed,- closeRadiusPx: session.points.length >= MIN_POLYGON_POINTS ? POLYGON_CLOSE_HIT_PX : null,- cursor: session.cursor,- kind: 'polygon',- points: session.points.slice(),- });+ ctx.stores.lassoPreview.set(polylinePreview(session));} else {ctx.stores.lassoPreview.set({ kind: 'freehand', points: session.points.slice() });}@@ -120,7 +103,7 @@ export const createLassoTool = (): Tool => {// A double-click's second press lands on the previous vertex, so count// distinct points; and a flat polygon would select a line of nothing.const distinct = polygon.filter((point, index) => index === 0 || distance(point, polygon[index - 1]!) >= 1);- if (distinct.length < MIN_POLYGON_POINTS || bounds.width < 1 || bounds.height < 1 || !ctx.commitSelection) {+ if (distinct.length < MIN_POLYLINE_POINTS || bounds.width < 1 || bounds.height < 1 || !ctx.commitSelection) {return;}ctx.commitSelection({@@ -130,17 +113,6 @@ export const createLassoTool = (): Tool => {});};- /** True when a press at `screenPoint` lands on the polygon's first vertex. */- const isOnFirstVertex = (ctx: ToolContext, polygon: PolygonSession, screenPoint: Vec2): boolean => {- const first = polygon.points[0];- if (!first || polygon.points.length < MIN_POLYGON_POINTS) {- return false;- }- // Project through the viewport rather than caching the vertex's screen- // position: the user may pan (space-hold) between vertices.- return distance(ctx.viewport.documentToScreen(first), screenPoint) <= POLYGON_CLOSE_HIT_PX;- };-const closePolygon = (ctx: ToolContext,polygon: PolygonSession,@@ -201,14 +173,7 @@ export const createLassoTool = (): Tool => {}if (!session) {- session = {- closeArmed: false,- cursor: null,- kind: 'polygon',- lastPressAt: input.timeStamp,- lastPressScreen: input.screenPoint,- points: [{ x: input.documentPoint.x, y: input.documentPoint.y }],- };+ session = { ...startPolyline(input), kind: 'polygon' };publishPreview(ctx);return;}@@ -217,17 +182,10 @@ export const createLassoTool = (): Tool => {return;}- const isDoubleClick =- input.timeStamp - session.lastPressAt <= POLYGON_DOUBLE_CLICK_MS &&- distance(session.lastPressScreen, input.screenPoint) <= POLYGON_DOUBLE_CLICK_PX;- if (isDoubleClick || isOnFirstVertex(ctx, session, input.screenPoint)) {+ if (pressPolyline(ctx, session, input) === 'close') {closePolygon(ctx, session, input.modifiers);return;}-- session.points.push({ x: input.documentPoint.x, y: input.documentPoint.y });- session.lastPressAt = input.timeStamp;- session.lastPressScreen = input.screenPoint;publishPreview(ctx);},onPointerMove: (ctx, input, batch) => {@@ -235,10 +193,7 @@ export const createLassoTool = (): Tool => {return;}if (session.kind === 'polygon') {- session.cursor = { x: input.documentPoint.x, y: input.documentPoint.y };- const closeArmed = isOnFirstVertex(ctx, session, input.screenPoint);- if (closeArmed !== session.closeArmed) {- session.closeArmed = closeArmed;+ if (movePolyline(ctx, session, input)) {ctx.updateCursor();}} else {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.test.tsnew file mode 100644index 0000000000..0825889c0b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.test.ts@@ -0,0 +1,68 @@+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { PointerInput } from '@workbench/canvas-engine/types';++import { describe, expect, it } from 'vitest';++import { isOnFirstVertex, movePolyline, polylinePreview, pressPolyline, startPolyline } from './polylineSession';++const pointer = (x: number, y: number, timeStamp = 0): PointerInput => ({+ buttons: 1,+ documentPoint: { x, y },+ modifiers: { alt: false, ctrl: false, meta: false, shift: false },+ pointerType: 'mouse',+ pressure: 0.5,+ screenPoint: { x, y },+ timeStamp,+});++// Identity viewport: document and screen coordinates coincide.+const ctx = { viewport: { documentToScreen: (p: { x: number; y: number }) => p } } as unknown as ToolContext;++describe('polylineSession', () => {+ it('places vertices on separate presses and closes on a press at the first vertex', () => {+ const session = startPolyline(pointer(0, 0, 0));+ expect(pressPolyline(ctx, session, pointer(40, 0, 1000))).toBe('place');+ expect(pressPolyline(ctx, session, pointer(40, 40, 2000))).toBe('place');+ expect(pressPolyline(ctx, session, pointer(3, 2, 3000))).toBe('close');+ expect(session.points).toHaveLength(3);+ });++ it('does not treat the first vertex as a close target before the polygon is fillable', () => {+ const session = startPolyline(pointer(0, 0, 0));+ pressPolyline(ctx, session, pointer(40, 0, 1000));+ expect(isOnFirstVertex(ctx, session, { x: 1, y: 1 })).toBe(false);+ expect(pressPolyline(ctx, session, pointer(1, 1, 2000))).toBe('place');+ });++ it('closes on a quick double-click but places a slow second click at the same spot', () => {+ const quick = startPolyline(pointer(0, 0, 0));+ pressPolyline(ctx, quick, pointer(40, 0, 1000));+ expect(pressPolyline(ctx, quick, pointer(40, 1, 1200))).toBe('close');++ const slow = startPolyline(pointer(0, 0, 0));+ pressPolyline(ctx, slow, pointer(40, 0, 1000));+ expect(pressPolyline(ctx, slow, pointer(40, 1, 5000))).toBe('place');+ });++ it('arms the close cue only while hovering the first vertex and reports each flip', () => {+ const session = startPolyline(pointer(0, 0, 0));+ pressPolyline(ctx, session, pointer(40, 0, 1000));+ pressPolyline(ctx, session, pointer(40, 40, 2000));++ expect(movePolyline(ctx, session, pointer(30, 30))).toBe(false);+ expect(movePolyline(ctx, session, pointer(3, 2))).toBe(true);+ expect(movePolyline(ctx, session, pointer(4, 2))).toBe(false);+ expect(polylinePreview(session)).toEqual({+ closeArmed: true,+ closeRadiusPx: 8,+ cursor: { x: 4, y: 2 },+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 40, y: 0 },+ { x: 40, y: 40 },+ ],+ });+ expect(movePolyline(ctx, session, pointer(20, 20))).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.tsnew file mode 100644index 0000000000..8e6d40dcea--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts@@ -0,0 +1,96 @@+/**+ * A click-to-place polyline shared by the lasso's polygon mode and the shape+ * tool's polygon kind: vertices accumulate across presses, a rubber band+ * follows the cursor, and the shape closes on a double-click, on Enter, or on+ * a press within a screen radius of the first vertex — which the overlay+ * previews as an armed ring while the cursor hovers there.+ *+ * Zero React, zero import-time side effects.+ */++import type { LassoPreview } from '@workbench/canvas-engine/engineStores';+import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';++import type { ToolContext } from './tool';++/** Fewest distinct points that make a fillable polygon. */+export const MIN_POLYLINE_POINTS = 3;++/** Screen-pixel radius around the first vertex where a click closes the polygon. */+export const POLYLINE_CLOSE_HIT_PX = 8;++/** Longest gap (ms) between two presses that still reads as a double-click. */+export const POLYLINE_DOUBLE_CLICK_MS = 350;++/** Screen-pixel radius within which two presses count as the same spot. */+const DOUBLE_CLICK_PX = 4;++const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);++export interface PolylineSession {+ points: Vec2[];+ /** The rubber-band endpoint (the last cursor position), or `null` before any move. */+ cursor: Vec2 | null;+ /** Whether the cursor sits on the first vertex, where a click closes the polygon. */+ closeArmed: boolean;+ /** Screen position and time of the previous press, for double-click detection. */+ lastPressScreen: Vec2;+ lastPressAt: number;+}++/** Starts a session with its first vertex at the press. */+export const startPolyline = (input: PointerInput): PolylineSession => ({+ closeArmed: false,+ cursor: null,+ lastPressAt: input.timeStamp,+ lastPressScreen: input.screenPoint,+ points: [{ x: input.documentPoint.x, y: input.documentPoint.y }],+});++/** True when a press at `screenPoint` lands on the polygon's first vertex (once it is fillable). */+export const isOnFirstVertex = (ctx: ToolContext, session: PolylineSession, screenPoint: Vec2): boolean => {+ const first = session.points[0];+ if (!first || session.points.length < MIN_POLYLINE_POINTS) {+ return false;+ }+ // Project through the viewport rather than caching the vertex's screen+ // position: the user may pan (space-hold) between vertices.+ return distance(ctx.viewport.documentToScreen(first), screenPoint) <= POLYLINE_CLOSE_HIT_PX;+};++/**+ * Handles a press after the first: closes when it double-clicks or lands on+ * the first vertex, else places a vertex. Returns what happened.+ */+export const pressPolyline = (ctx: ToolContext, session: PolylineSession, input: PointerInput): 'close' | 'place' => {+ const isDoubleClick =+ input.timeStamp - session.lastPressAt <= POLYLINE_DOUBLE_CLICK_MS &&+ distance(session.lastPressScreen, input.screenPoint) <= DOUBLE_CLICK_PX;+ if (isDoubleClick || isOnFirstVertex(ctx, session, input.screenPoint)) {+ return 'close';+ }+ session.points.push({ x: input.documentPoint.x, y: input.documentPoint.y });+ session.lastPressAt = input.timeStamp;+ session.lastPressScreen = input.screenPoint;+ return 'place';+};++/** Tracks the rubber band and the close cue; true when the cue flipped (the cursor should refresh). */+export const movePolyline = (ctx: ToolContext, session: PolylineSession, input: PointerInput): boolean => {+ session.cursor = { x: input.documentPoint.x, y: input.documentPoint.y };+ const closeArmed = isOnFirstVertex(ctx, session, input.screenPoint);+ if (closeArmed === session.closeArmed) {+ return false;+ }+ session.closeArmed = closeArmed;+ return true;+};++/** The overlay's view of the session. */+export const polylinePreview = (session: PolylineSession): LassoPreview => ({+ closeArmed: session.closeArmed,+ closeRadiusPx: session.points.length >= MIN_POLYLINE_POINTS ? POLYLINE_CLOSE_HIT_PX : null,+ cursor: session.cursor,+ kind: 'polygon',+ points: session.points.slice(),+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex e7f5a98f03..8aba0be0ec 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';@@ -7,11 +7,27 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';-import { createShapeTool, rectFromDrag } from './shapeTool';+import { createShapeTool, polygonShapeFrom, rectFromDrag } from './shapeTool';-const makeDoc = (): CanvasDocumentContractV3 => ({+const paintLayer = (over: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>+ ({+ blendMode: 'normal',+ id: 'paint-1',+ isEnabled: true,+ isLocked: false,+ name: 'Paint',+ opacity: 1,+ source: { bitmap: null, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ ...over,+ }) as CanvasLayerContract;++const makeDoc = (over: Partial<CanvasDocumentContractV3> = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 96, width: 96, x: 0, y: 0 },height: 512,@@ -19,20 +35,25 @@ const makeDoc = (): CanvasDocumentContractV3 => ({selectedLayerId: null,version: 3,width: 512,+ ...over,});const identityViewport = {documentToScreen: (p: Vec2): Vec2 => ({ x: p.x, y: p.y }),} as unknown as Viewport;-const pointer = (x: number, y: number, opts: { shift?: boolean; buttons?: number } = {}): PointerInput => ({+const pointer = (+ x: number,+ y: number,+ opts: { shift?: boolean; buttons?: number; timeStamp?: number } = {}+): PointerInput => ({buttons: opts.buttons ?? 1,documentPoint: { x, y },modifiers: { alt: false, ctrl: false, meta: false, shift: opts.shift ?? false },pointerType: 'mouse',pressure: 0.5,screenPoint: { x, y },- timeStamp: 0,+ timeStamp: opts.timeStamp ?? 0,});interface StructuralCommit {@@ -45,9 +66,11 @@ const createHarness = (doc: CanvasDocumentContractV3) => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const stores = createEngineStores();+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);let idCounter = 0;const ctx: ToolContext = {- backend: null as never,+ backend,commitStructural: (label, forward, inverse) => {commits.push({ forward, inverse, label });return { status: 'committed' as const };@@ -59,7 +82,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {emitStrokeCommitted: vi.fn(),getDocument: () => doc,invalidate: vi.fn(),- layers: null as never,+ layers,notifyLayerPainted: vi.fn(),setLayerTransformOverride: vi.fn(),setOverlayCursor: vi.fn(),@@ -67,7 +90,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {updateCursor: vi.fn(),viewport: identityViewport,};- return { commits, ctx, dispatched, previewOf: () => stores.shapePreview.get(), stores };+ return { commits, ctx, dispatched, layers, previewOf: () => stores.shapePreview.get(), stores };};const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);@@ -131,7 +154,13 @@ describe('shape tool: creation', () => {it('resolves the pair at gesture start for the enabled fill and stroke', () => {const h = createHarness(makeDoc());- h.stores.shapeOptions.set({ fillEnabled: true, kind: 'ellipse', strokeEnabled: true, strokeWidth: 4 });+ h.stores.shapeOptions.set({+ fillEnabled: true,+ kind: 'ellipse',+ strokeEnabled: true,+ strokeWidth: 4,+ target: 'new',+ });h.stores.colorPair.set({ background: '#0000ff', foreground: '#ff0000' });const tool = createShapeTool();@@ -196,3 +225,248 @@ describe('shape tool: creation', () => {expect(h.commits).toHaveLength(0);});});++describe('shape tool: polygon and freehand kinds', () => {+ const click = (tool: Tool, ctx: ToolContext, x: number, y: number, timeStamp: number): void => {+ down(tool, ctx, pointer(x, y, { timeStamp }));+ up(tool, ctx, pointer(x, y, { timeStamp }));+ };++ it('places polygon vertices click by click and commits one layer on close, points relative to its box', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();++ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ move(tool, h.ctx, pointer(50, 40));+ expect(h.stores.lassoPreview.get()).toMatchObject({+ kind: 'polygon',+ points: [+ { x: 10, y: 10 },+ { x: 50, y: 10 },+ ],+ });+ click(tool, h.ctx, 50, 40, 2000);+ expect(h.commits).toHaveLength(0);+ tool.onKeyCommand?.(h.ctx, 'apply');++ expect(h.commits).toHaveLength(1);+ const forward = h.commits[0]?.forward;+ if (forward?.type === 'addCanvasLayer' && forward.layer.type === 'raster') {+ expect(forward.layer.source).toMatchObject({+ height: 30,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 40, y: 0 },+ { x: 40, y: 30 },+ ],+ width: 40,+ });+ expect(forward.layer.transform).toMatchObject({ x: 10, y: 10 });+ } else {+ throw new Error('expected a polygon layer');+ }+ expect(h.stores.lassoPreview.get()).toBeNull();+ });++ it('traces a freehand drag into a closed polygon', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'freehand' });+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(0, 0));+ move(tool, h.ctx, pointer(30, 0));+ move(tool, h.ctx, pointer(30, 30));+ expect(h.stores.lassoPreview.get()).toMatchObject({ kind: 'freehand' });+ up(tool, h.ctx, pointer(0, 30));++ const forward = h.commits[0]?.forward;+ if (forward?.type === 'addCanvasLayer' && forward.layer.type === 'raster') {+ expect(forward.layer.source).toMatchObject({ height: 30, kind: 'polygon', width: 30 });+ expect((forward.layer.source as { points?: unknown[] }).points).toHaveLength(4);+ } else {+ throw new Error('expected a polygon layer');+ }+ });++ it('commits nothing for a flat polygon', () => {+ // The third point survives the 1px dedupe; only the sub-pixel bounds reject it.+ expect(+ polygonShapeFrom(+ [+ { x: 0, y: 0 },+ { x: 40, y: 0 },+ { x: 20, y: 0.5 },+ ],+ { fill: '#000', stroke: null, strokeWidth: 0 }+ )+ ).toBeNull();+ });++ it('closes the polygon with a click on the first vertex', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();++ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ click(tool, h.ctx, 50, 40, 2000);+ move(tool, h.ctx, pointer(13, 12));+ expect(h.stores.lassoPreview.get()).toMatchObject({ closeArmed: true, kind: 'polygon' });+ expect(tool.cursor?.(h.ctx)).toBe('pointer');+ click(tool, h.ctx, 13, 12, 3000);++ expect(h.commits).toHaveLength(1);+ expect(h.stores.lassoPreview.get()).toBeNull();+ });++ it('drops an open polygon when the kind changes mid-session', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();++ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'rect' });+ move(tool, h.ctx, pointer(50, 40));+ expect(h.stores.lassoPreview.get()).toBeNull();++ // The next press starts a fresh rect drag rather than extending the polygon.+ down(tool, h.ctx, pointer(0, 0));+ move(tool, h.ctx, pointer(20, 20));+ up(tool, h.ctx, pointer(20, 20));+ expect(h.commits).toHaveLength(1);+ const forward = h.commits[0]?.forward;+ if (forward?.type === 'addCanvasLayer' && forward.layer.type === 'raster') {+ expect(forward.layer.source).toMatchObject({ kind: 'rect', width: 20 });+ } else {+ throw new Error('expected a rect layer');+ }+ });+});++describe('shape tool: placement', () => {+ it('draws onto the selected paint layer as one stroke event, growing its cache to the shape', () => {+ const layer = paintLayer({ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 50 } });+ const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'paint-1' }));+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(110, 60));+ move(tool, h.ctx, pointer(170, 100));+ up(tool, h.ctx, pointer(170, 100));++ expect(h.commits).toHaveLength(0);+ expect(h.ctx.emitStrokeCommitted).toHaveBeenCalledOnce();+ const event = vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0];+ // Layer-local: the document rect minus the layer's offset.+ expect(event.dirtyRect).toEqual({ height: 40, width: 60, x: 10, y: 10 });+ expect(event.tool).toBe('shape');+ expect(event.layerId).toBe('paint-1');+ expect(h.layers.get('paint-1')?.rect).toEqual({ height: 40, width: 60, x: 10, y: 10 });+ const surface = h.layers.get('paint-1')?.surface as StubRasterSurface;+ expect(surface.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);+ });++ it('maps the shape through a scaled layer and clamps the cache growth to the selection', () => {+ const layer = paintLayer({ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 100, y: 50 } });+ const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'paint-1' }));+ const mask = h.ctx.backend.createSurface(40, 40);+ h.ctx.getSelectionMask = () => ({ rect: { height: 40, width: 40, x: 100, y: 50 }, surface: mask });+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(110, 60));+ move(tool, h.ctx, pointer(170, 100));+ up(tool, h.ctx, pointer(170, 100));++ const event = vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0];+ // Document 110..140 × 60..90 (the selection's extent) → local (5..20, 5..20) at half scale.+ expect(event.dirtyRect).toEqual({ height: 15, width: 15, x: 5, y: 5 });+ expect(h.layers.get('paint-1')?.rect).toEqual(event.dirtyRect);+ });++ it('clips to the bbox and skips a shape that lands entirely outside the selection', () => {+ const h = createHarness(makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' }));+ const mask = h.ctx.backend.createSurface(10, 10);+ h.ctx.getSelectionMask = () => ({ rect: { height: 10, width: 10, x: 0, y: 0 }, surface: mask });+ h.ctx.getStrokeClipRect = () => ({ height: 8, width: 8, x: 0, y: 0 });+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(4, 4));+ move(tool, h.ctx, pointer(60, 60));+ up(tool, h.ctx, pointer(60, 60));+ expect(vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0].dirtyRect).toEqual({+ height: 4,+ width: 4,+ x: 4,+ y: 4,+ });++ down(tool, h.ctx, pointer(20, 20));+ move(tool, h.ctx, pointer(60, 60));+ up(tool, h.ctx, pointer(60, 60));+ // Nothing to draw: no stroke event, no history, no new layer.+ expect(h.ctx.emitStrokeCommitted).toHaveBeenCalledOnce();+ expect(h.commits).toHaveLength(0);+ expect(h.layers.get('paint-1')?.rect).toEqual({ height: 4, width: 4, x: 4, y: 4 });+ });++ it('refuses a locked paint layer instead of spawning a layer over it', () => {+ const h = createHarness(+ makeDoc({ stacks: stacksFrom([paintLayer({ isLocked: true })]), selectedLayerId: 'paint-1' })+ );+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));++ expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.commits).toHaveLength(0);+ });++ it('waits for a durable paint layer whose pixels are not cached yet', () => {+ const durable = paintLayer({ source: { bitmap: { height: 8, imageName: 'b', width: 8 }, type: 'paint' } });+ const h = createHarness(makeDoc({ stacks: stacksFrom([durable]), selectedLayerId: 'paint-1' }));+ h.ctx.requestLayerRasterization = vi.fn();+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));++ expect(h.ctx.requestLayerRasterization).toHaveBeenCalledWith('paint-1');+ expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.commits).toHaveLength(0);+ });++ it('falls back to a new shape layer when the selection is not a paint layer', () => {+ const image = paintLayer({+ id: 'image-1',+ source: { image: { height: 8, imageName: 'i', width: 8 }, type: 'image' },+ });+ const h = createHarness(makeDoc({ stacks: stacksFrom([image]), selectedLayerId: 'image-1' }));+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));++ expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');+ });++ it('creates a shape layer over a paint layer when the target is a new layer', () => {+ const h = createHarness(makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' }));+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), target: 'new' });+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));++ expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex 0abf052338..06f07d785e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -1,44 +1,67 @@/**- * The shape tool: drag on the canvas to CREATE a new shape layer sized by the- * drag rect. Scope is creation-only — dragging never edits an existing shape- * (param edits happen through the options bar and the transform tool).+ * The shape tool. The box kinds (rect / ellipse / triangle / star) drag out a+ * rect; `polygon` places vertices click by click through the shared polyline+ * session; `freehand` traces a drag and closes it. A finished shape lands+ * either as pixels on the selected paint layer (one undoable stroke, clipped+ * to the selection and the bbox like a brush stroke) or, when the target is+ * `new` or the selection is not a paint layer, as its own parametric shape+ * layer. A locked, disabled or not-yet-rasterized paint layer refuses the+ * shape (a no-op, like the brush) rather than spawning a layer over it.*- * Interaction contract (CANVAS_PLAN Phase 6.1):- * - **Pointer-down** (primary button) starts a gesture at the press point.- * - **Pointer-move** (past a small threshold) updates a transient overlay- * preview rect (`stores.shapePreview`) — it never dispatches. Hold **shift**- * to constrain to a square/circle.- * - **Commit** (pointer-up after a real drag): exactly one `commitStructural`- * whose forward is `addCanvasLayer` (a shape source sized to the rect, placed- * at the rect origin) and whose inverse is `removeCanvasLayers` — so undo- * removes the created layer. A zero-area drag commits nothing.+ * Interaction contract:+ * - **Pointer-move** updates a transient overlay preview (the drag rect, or the+ * polyline through `stores.lassoPreview`) — it never dispatches. Hold+ * **shift** to constrain a drag to a square/circle.+ * - **Commit**: exactly one `commitStructural` (`addCanvasLayer`, undone by+ * `removeCanvasLayers`) or one stroke event. A zero-area shape commits nothing.* - **Cancel** (Esc / pointercancel): drops the preview, no dispatch.*- * The selection mask does NOT constrain shape creation — a shape layer is a- * parametric object, not a pixel edit into an existing layer.- ** Zero React, zero import-time side effects.*/-import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { PlacedSurface, Rect, Vec2 } from '@workbench/canvas-engine/types';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafPaintable } from '@workbench/canvas-engine/document/layerEligibility';+import { polygonBounds } from '@workbench/canvas-engine/freehand';+import { identity, invert, multiply, translate } from '@workbench/canvas-engine/math/mat2d';+import { intersect, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';+import { drawShapeSource } from '@workbench/canvas-engine/render/rasterizers/shapeRasterizer';import type { Tool, ToolContext } from './tool';+import { layerMatrix } from './moveHitTest';+import {+ MIN_POLYLINE_POINTS,+ movePolyline,+ polylinePreview,+ pressPolyline,+ startPolyline,+ type PolylineSession,+} from './polylineSession';++type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;+/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */export const SHAPE_DRAG_THRESHOLD_PX = 3;-interface GestureState {- startDoc: Vec2;- startScreen: Vec2;- moved: boolean;-}+/** Minimum document-space gap between stored freehand points (input decimation). */+const FREEHAND_MIN_POINT_DISTANCE = 2;++type Session =+ | { kind: 'drag'; startDoc: Vec2; startScreen: Vec2; moved: boolean }+ | { kind: 'polyline'; session: PolylineSession }+ | { kind: 'freehand'; points: Vec2[] };++const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);/** The integer, normalized document rect for a drag from `start` to `end`, optionally square-constrained. */export const rectFromDrag = (start: Vec2, end: Vec2, square: boolean): Rect => {@@ -54,115 +77,311 @@ export const rectFromDrag = (start: Vec2, end: Vec2, square: boolean): Rect => {return { height: Math.round(Math.abs(dy)), width: Math.round(Math.abs(dx)), x, y };};+/** A shape to place: its source plus the document rect it covers. */+interface PlacedShape {+ source: ShapeSource;+ rect: Rect;+}++/**+ * A polygon source for document-space vertices: the extent is the vertex+ * bounds, and the stored points are relative to that box's origin.+ */+export const polygonShapeFrom = (+ vertices: readonly Vec2[],+ style: Pick<ShapeSource, 'fill' | 'stroke' | 'strokeWidth'>+): PlacedShape | null => {+ const distinct = vertices.filter((point, index) => index === 0 || distance(point, vertices[index - 1]!) >= 1);+ const bounds = polygonBounds(distinct);+ if (distinct.length < MIN_POLYLINE_POINTS || bounds.width < 1 || bounds.height < 1) {+ return null;+ }+ const rect = roundOut(bounds);+ return {+ rect,+ source: {+ ...style,+ height: rect.height,+ kind: 'polygon',+ points: distinct.map((point) => ({ x: point.x - rect.x, y: point.y - rect.y })),+ type: 'shape',+ width: rect.width,+ },+ };+};++/** Where a finished shape went: pixels, refused by the paint layer, or not a paint layer at all. */+type PixelPlacement = 'placed' | 'refused' | 'unsupported';++/** Whether a session was started for the current kind option; a kind change mid-session drops it. */+const sessionFitsKind = (session: Session, kind: ShapeToolOptions['kind']): boolean =>+ kind === 'polygon'+ ? session.kind === 'polyline'+ : kind === 'freehand'+ ? session.kind === 'freehand'+ : session.kind === 'drag';+/** Creates a fresh shape tool with its own gesture state. */export const createShapeTool = (): Tool => {- let state: GestureState | null = null;+ let session: Session | null = null;const clearPreview = (ctx: ToolContext): void => {ctx.stores.shapePreview.set(null);+ ctx.stores.lassoPreview.set(null);ctx.invalidate({ overlay: true });};+ const reset = (ctx: ToolContext): void => {+ session = null;+ clearPreview(ctx);+ };++ /** The fill/stroke the next shape gets, resolved from the active pair now. */+ const styleFromOptions = (ctx: ToolContext): Pick<ShapeSource, 'fill' | 'stroke' | 'strokeWidth'> => {+ const options = ctx.stores.shapeOptions.get();+ const pair = ctx.stores.colorPair.get();+ return {+ fill: options.fillEnabled ? pair.foreground : null,+ stroke: options.strokeEnabled ? pair.background : null,+ strokeWidth: options.strokeWidth,+ };+ };++ /**+ * Draws the shape as pixels onto the selected paint layer, as one stroke+ * event: the layer cache grows to the shape's layer-local bounds (clamped to+ * the selection and bbox clips, so growth never escapes them), the shape is+ * drawn through the layer's inverse transform, then clipped to the selection+ * mask and the bbox exactly as a brush stroke is.+ */+ const commitPixels = (ctx: ToolContext, leaf: SemanticLeaf, placed: PlacedShape): PixelPlacement => {+ const layer = leaf.layer;+ if (layer.type !== 'raster' || layer.source.type !== 'paint') {+ return 'unsupported';+ }+ if (!isLeafPaintable(leaf)) {+ return 'refused';+ }+ if (layer.source.bitmap) {+ const existing = ctx.layers.get(layer.id);+ if (!existing || existing.stale) {+ // The durable pixels are not in the cache yet: drawing now would lose them.+ ctx.requestLayerRasterization?.(layer.id);+ return 'refused';+ }+ }+ const toLocal = invert(layerMatrix(layer.transform));+ if (!toLocal) {+ return 'refused';+ }+ const clipMask: PlacedSurface | null = ctx.getSelectionMask?.() ?? null;+ const clipRect: Rect | null = ctx.getStrokeClipRect?.() ?? null;+ let docRect: Rect | null = placed.rect;+ if (clipMask) {+ docRect = intersect(docRect, clipMask.rect);+ }+ if (docRect && clipRect) {+ docRect = intersect(docRect, clipRect);+ }+ const dirtyRect = docRect ? roundOut(transformBounds(toLocal, docRect)) : null;+ if (!dirtyRect || dirtyRect.width < 1 || dirtyRect.height < 1) {+ return 'refused';+ }+ const entry = ctx.layers.growToRect(layer.id, dirtyRect);+ const surfaceCtx = entry.surface.ctx;+ const sx = dirtyRect.x - entry.rect.x;+ const sy = dirtyRect.y - entry.rect.y;+ const beforeImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);++ // Draw into a scratch the size of the dirty rect (scratch origin = dirtyRect+ // origin in layer space) so the clips and the transparency lock apply in+ // one composite. Document → layer-local → scratch: the layer's inverse,+ // then the scratch offset.+ const scratch = ctx.backend.createSurface(dirtyRect.width, dirtyRect.height);+ const draw = scratch.ctx;+ const { rect, source } = placed;+ const toScratch = multiply(translate(identity(), { x: -dirtyRect.x, y: -dirtyRect.y }), toLocal);+ draw.setTransform(toScratch.a, toScratch.b, toScratch.c, toScratch.d, toScratch.e, toScratch.f);+ drawShapeSource(draw, source, rect.x, rect.y, rect.width, rect.height);+ draw.globalCompositeOperation = 'destination-in';+ if (clipMask) {+ // The mask sits in document space, so it goes through the same mapping.+ draw.drawImage(clipMask.surface.canvas, clipMask.rect.x, clipMask.rect.y);+ }+ if (clipRect && (toLocal.b !== 0 || toLocal.c !== 0)) {+ // The dirty-rect clamp only bounds the AABB on a rotated/sheared layer;+ // keep exactly the pixels inside the document-space rect.+ draw.fillStyle = '#000';+ draw.beginPath();+ draw.rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);+ draw.fill();+ }+ surfaceCtx.save();+ surfaceCtx.setTransform(1, 0, 0, 1, 0, 0);+ surfaceCtx.globalCompositeOperation = layer.isTransparencyLocked ? 'source-atop' : 'source-over';+ surfaceCtx.drawImage(scratch.canvas, sx, sy);+ surfaceCtx.restore();+ const afterImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);+ ctx.emitStrokeCommitted({ afterImageData, beforeImageData, dirtyRect, layerId: layer.id, tool: 'shape' });+ return 'placed';+ };++ const commitLayer = (ctx: ToolContext, placed: PlacedShape): void => {+ const doc = ctx.getDocument();+ if (!doc) {+ return;+ }+ const layerId = ctx.createLayerId();+ const layer: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: layerId,+ isEnabled: true,+ isLocked: false,+ name: `Shape ${getDocumentLeaves(doc).length + 1}`,+ opacity: 1,+ source: placed.source,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: placed.rect.x, y: placed.rect.y },+ type: 'raster',+ };+ const forward: CanvasProjectMutation = {+ anchor: ctx.captureInsertionAnchor('raster', doc.selectedLayerId),+ layer,+ type: 'addCanvasLayer',+ };+ const inverse: CanvasProjectMutation = { ids: [layerId], type: 'removeCanvasLayers' };+ ctx.commitStructural('Add shape', forward, inverse);+ };++ /** Places a finished shape on the selected paint layer when asked, else on a new layer. */+ const commit = (ctx: ToolContext, placed: PlacedShape | null): void => {+ reset(ctx);+ const doc = ctx.getDocument();+ if (!placed || !doc) {+ return;+ }+ if (ctx.stores.shapeOptions.get().target === 'selected') {+ const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;+ if (leaf && commitPixels(ctx, leaf, placed) !== 'unsupported') {+ return;+ }+ }+ commitLayer(ctx, placed);+ };++ const boxShape = (ctx: ToolContext, rect: Rect): PlacedShape | null => {+ const kind = ctx.stores.shapeOptions.get().kind;+ if (rect.width < 1 || rect.height < 1 || kind === 'polygon' || kind === 'freehand') {+ return null;+ }+ return { rect, source: { ...styleFromOptions(ctx), height: rect.height, kind, type: 'shape', width: rect.width } };+ };++ const closePolyline = (ctx: ToolContext, polyline: PolylineSession): void => {+ commit(ctx, polygonShapeFrom(polyline.points, styleFromOptions(ctx)));+ };+return {- cursor: () => 'crosshair',+ cursor: () => (session?.kind === 'polyline' && session.session.closeArmed ? 'pointer' : 'crosshair'),id: 'shape',- onDeactivate: (ctx) => {- state = null;- clearPreview(ctx);+ onDeactivate: (ctx, opts) => {+ // A modifier-hold switch (space → view to pan mid-polygon) keeps the session.+ if (!opts?.temporary) {+ reset(ctx);+ }},onKeyCommand: (ctx, command) => {- if (command === 'cancel' && state) {- state = null;- clearPreview(ctx);+ if (!session) {+ return;+ }+ if (command === 'cancel') {+ reset(ctx);+ } else if (session.kind === 'polyline') {+ closePolyline(ctx, session.session);}},- onPointerCancel: (ctx) => {- state = null;- clearPreview(ctx);- },+ onPointerCancel: (ctx) => reset(ctx),onPointerDown: (ctx, input) => {- if (state || (input.buttons & PRIMARY_BUTTON) === 0) {+ if ((input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {+ return;+ }+ const kind = ctx.stores.shapeOptions.get().kind;+ if (session && !sessionFitsKind(session, kind)) {+ reset(ctx);+ }+ if (kind === 'polygon') {+ if (session?.kind !== 'polyline') {+ session = { kind: 'polyline', session: startPolyline(input) };+ } else if (pressPolyline(ctx, session.session, input) === 'close') {+ closePolyline(ctx, session.session);+ return;+ }+ ctx.stores.lassoPreview.set(polylinePreview(session.session));+ ctx.invalidate({ overlay: true });return;}- if (!ctx.getDocument()) {+ if (session) {return;}- state = { moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };+ session =+ kind === 'freehand'+ ? { kind: 'freehand', points: [{ x: input.documentPoint.x, y: input.documentPoint.y }] }+ : { kind: 'drag', moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };},- onPointerMove: (ctx, input) => {- if (!state) {+ onPointerMove: (ctx, input, batch) => {+ if (!session) {return;}- if (!state.moved) {- const dxs = input.screenPoint.x - state.startScreen.x;- const dys = input.screenPoint.y - state.startScreen.y;+ const kind = ctx.stores.shapeOptions.get().kind;+ if (!sessionFitsKind(session, kind)) {+ reset(ctx);+ return;+ }+ if (session.kind === 'polyline') {+ if (movePolyline(ctx, session.session, input)) {+ ctx.updateCursor();+ }+ ctx.stores.lassoPreview.set(polylinePreview(session.session));+ ctx.invalidate({ overlay: true });+ return;+ }+ if (session.kind === 'freehand') {+ for (const sample of batch) {+ const last = session.points[session.points.length - 1];+ if (!last || distance(last, sample.documentPoint) >= FREEHAND_MIN_POINT_DISTANCE) {+ session.points.push({ x: sample.documentPoint.x, y: sample.documentPoint.y });+ }+ }+ ctx.stores.lassoPreview.set({ kind: 'freehand', points: session.points.slice() });+ ctx.invalidate({ overlay: true });+ return;+ }+ if (!session.moved) {+ const dxs = input.screenPoint.x - session.startScreen.x;+ const dys = input.screenPoint.y - session.startScreen.y;if (Math.hypot(dxs, dys) < SHAPE_DRAG_THRESHOLD_PX) {return;}- state.moved = true;+ session.moved = true;+ }+ if (kind !== 'polygon' && kind !== 'freehand') {+ const rect = rectFromDrag(session.startDoc, input.documentPoint, input.modifiers.shift);+ ctx.stores.shapePreview.set({ kind, rect });+ ctx.invalidate({ overlay: true });}- const rect = rectFromDrag(state.startDoc, input.documentPoint, input.modifiers.shift);- ctx.stores.shapePreview.set({ kind: ctx.stores.shapeOptions.get().kind, rect });- ctx.invalidate({ overlay: true });},onPointerUp: (ctx, input) => {- if (!state) {+ if (!session || session.kind === 'polyline') {return;}- const current = state;- state = null;-- if (!current.moved) {- clearPreview(ctx);+ if (session.kind === 'freehand') {+ commit(ctx, polygonShapeFrom([...session.points, input.documentPoint], styleFromOptions(ctx)));return;}-- const rect = rectFromDrag(current.startDoc, input.documentPoint, input.modifiers.shift);- if (rect.width < 1 || rect.height < 1) {- // Degenerate drag: nothing to create.- clearPreview(ctx);+ if (!session.moved) {+ reset(ctx);return;}-- const doc = ctx.getDocument();- if (!doc) {- clearPreview(ctx);- return;- }-- const options = ctx.stores.shapeOptions.get();- // The active pair, resolved now: the new shape gets explicit document- // colors; later pair edits never rewrite them.- const pair = ctx.stores.colorPair.get();- const layerId = ctx.createLayerId();- const layer: CanvasRasterLayerContractV2 = {- blendMode: 'normal',- id: layerId,- isEnabled: true,- isLocked: false,- name: `Shape ${getDocumentLeaves(doc).length + 1}`,- opacity: 1,- source: {- fill: options.fillEnabled ? pair.foreground : null,- height: rect.height,- kind: options.kind,- stroke: options.strokeEnabled ? pair.background : null,- strokeWidth: options.strokeWidth,- type: 'shape',- width: rect.width,- },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: rect.x, y: rect.y },- type: 'raster',- };-- const forward: CanvasProjectMutation = {- anchor: ctx.captureInsertionAnchor('raster', doc.selectedLayerId),- layer,- type: 'addCanvasLayer',- };- const inverse: CanvasProjectMutation = { ids: [layerId], type: 'removeCanvasLayers' };- ctx.commitStructural('Add shape', forward, inverse);- clearPreview(ctx);+ commit(ctx, boxShape(ctx, rectFromDrag(session.startDoc, input.documentPoint, input.modifiers.shift)));},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 1f8a6b41ad..1930e630b3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -76,7 +76,7 @@ export interface StrokeSessionConfig {* already opaque, alpha never grows).*/composite: 'source-over' | 'destination-out' | 'source-atop';- tool: 'brush' | 'eraser';+ tool: 'brush' | 'eraser' | 'shape';/** Set only when this gesture auto-created its paint layer (for the composed history entry). */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor } | null;/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 4012923bf8..47dcd9bcd5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -47,8 +47,8 @@ export interface StrokeCommittedEvent {beforeImageData: ImageData;/** Cache pixels within `dirtyRect` after the stroke. */afterImageData: ImageData;- /** Which tool produced the stroke. */- tool: 'brush' | 'eraser';+ /** Which tool produced the stroke; a `shape` is one drawn as pixels onto a paint layer. */+ tool: 'brush' | 'eraser' | 'shape';/*** When the gesture auto-created its paint layer on pointer-down, the created* layer contract (and where it was inserted). The engine composes this intodiff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tsindex 19b5e3be82..be1dd38e08 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts@@ -12,6 +12,7 @@ import {adjustmentsKey,getBaseRasterContentBounds,getCompositeLayerBounds,+ isEmptyPolygonShape,planBaseRasterComposite,} from '@workbench/canvas-engine/api';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';@@ -81,13 +82,13 @@ const isInpaintMaskWithContent = (layer: CanvasLayerContract): layer is CanvasIn* A raster layer whose regenerate region is enabled and whose source can both* hold pixels and rasterize: the layer's OWN content alpha joins the inpaint* mask. Invoke flushes paint uploads before planning, so a stroked layer always- * carries its bitmap; polygon shapes have no rasterizer and would fail the- * snapshot capture, so they never enter the plan.+ * carries its bitmap; a pointless polygon shape has no raster and would fail+ * the snapshot capture, so it never enters the plan.*/const isRegionRasterWithContent = (layer: CanvasLayerContract): layer is CanvasRasterLayerContractV2 =>layer.type === 'raster' &&layer.inpaint?.isEnabled === true &&- !(layer.source.type === 'shape' && layer.source.kind === 'polygon') &&+ !(layer.source.type === 'shape' && isEmptyPolygonShape(layer.source)) &&(layer.source.type !== 'paint' || layer.source.bitmap !== null);/** JSON with recursively sorted object keys, so equal sources always serialize identically. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsxindex 8d05fe3f7a..c53e79886c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx@@ -1,7 +1,7 @@import type {CanvasCoreStoreCapability,CanvasToolCapability,- ParametricShapeKind,+ ShapeToolKind,ToolId,} from '@workbench/canvas-engine/api';@@ -16,6 +16,8 @@ import {HandIcon,LassoIcon,MoveIcon,+ PenLineIcon,+ PentagonIcon,Rotate3dIcon,SquareDashedIcon,SquareIcon,@@ -52,15 +54,19 @@ const ToolStripButton = ({ engine, icon, isInteractionLocked, label, toolId }: T);};-const SHAPE_KIND_ICONS: Record<ParametricShapeKind, React.ElementType> = {+const SHAPE_KIND_ICONS: Record<ShapeToolKind, React.ElementType> = {ellipse: CircleIcon,+ freehand: PenLineIcon,+ polygon: PentagonIcon,rect: SquareIcon,star: StarIcon,triangle: TriangleIcon,};-const SHAPE_KIND_ORDER: readonly ParametricShapeKind[] = ['rect', 'ellipse', 'triangle', 'star'];-const SHAPE_KIND_LABEL_KEYS: Record<ParametricShapeKind, string> = {+const SHAPE_KIND_ORDER: readonly ShapeToolKind[] = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'];+const SHAPE_KIND_LABEL_KEYS: Record<ShapeToolKind, string> = {ellipse: 'widgets.canvas.toolOptions.shapeEllipse',+ freehand: 'widgets.canvas.toolOptions.shapeFreehand',+ polygon: 'widgets.canvas.toolOptions.shapePolygon',rect: 'widgets.canvas.toolOptions.shapeRect',star: 'widgets.canvas.toolOptions.shapeStar',triangle: 'widgets.canvas.toolOptions.shapeTriangle',@@ -89,7 +95,7 @@ const ShapeFamilyButton = ({const onActivate = useCallback(() => engine.tools.setTool('shape'), [engine]);const onSelectSubtool = useCallback((id: string) => {- engine.interaction.set('shapeOptions', { ...options, kind: id as ParametricShapeKind });+ engine.interaction.set('shapeOptions', { ...options, kind: id as ShapeToolKind });engine.tools.setTool('shape');},[engine, options]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex e770c443f8..422e4f9229 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -434,11 +434,15 @@ describe('tool selection', () => {expect(engine.interaction.set).toHaveBeenCalledWith('shapeOptions', { fillEnabled: true, kind: 'ellipse' });});- it('shape cycles star back around to rect', () => {- const engine = run('canvas.tool.shape', {+ it('shape cycles star on to polygon, and freehand back around to rect', () => {+ const fromStar = run('canvas.tool.shape', {engine: createEngine({ activeTool: 'shape', shapeOptions: { kind: 'star' } as never }),});- expect(engine.interaction.set).toHaveBeenCalledWith('shapeOptions', { kind: 'rect' });+ expect(fromStar.interaction.set).toHaveBeenCalledWith('shapeOptions', { kind: 'polygon' });+ const fromFreehand = run('canvas.tool.shape', {+ engine: createEngine({ activeTool: 'shape', shapeOptions: { kind: 'freehand' } as never }),+ });+ expect(fromFreehand.interaction.set).toHaveBeenCalledWith('shapeOptions', { kind: 'rect' });});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 5d4b1b5fa2..a958df8e2e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -239,7 +239,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCif (engine.interaction.get('activeTool') === 'shape') {// Repeat presses cycle the kind, like the marquee hotkey.const shape = engine.interaction.get('shapeOptions');- const order = ['rect', 'ellipse', 'triangle', 'star'] as const;+ const order = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'] as const;const next = order[(order.indexOf(shape.kind) + 1) % order.length]!;engine.interaction.set('shapeOptions', { ...shape, kind: next });} else {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex f7f85feb48..de18085b3e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -60,12 +60,7 @@ const useShapeEditor = (engine: ToolFormProps['engine']) => {},(a, b) => a?.id === b?.id && a?.name === b?.name && a?.source === b?.source);- // Polygon shapes (no tool kind) display as rect; every parametric kind passes through.- const kind: ShapeKind = selected- ? selected.source.kind === 'polygon'- ? 'rect'- : selected.source.kind- : options.kind;+ const kind: ShapeKind = selected ? selected.source.kind : options.kind;const fill = selected ? selected.source.fill : options.fillEnabled ? pair.foreground : null;const stroke = selected ? selected.source.stroke : options.strokeEnabled ? pair.background : null;const strokeWidth = selected ? selected.source.strokeWidth : options.strokeWidth;@@ -75,7 +70,9 @@ const useShapeEditor = (engine: ToolFormProps['engine']) => {if (!selected) {return;}- const after: ShapeSource = { ...selected.source, ...patch };+ // Vertices belong to polygons only; a box kind never carries stale ones.+ const { points, ...merged } = { ...selected.source, ...patch };+ const after: ShapeSource = merged.kind === 'polygon' ? { ...merged, points } : merged;commitPrepared(t('widgets.canvas.toolOptions.shapeEdit'), (model) =>model.prepare({ id: selected.id, source: after, type: 'patch-source' }));@@ -91,10 +88,14 @@ const useShapeEditor = (engine: ToolFormProps['engine']) => {const setKind = useCallback((next: ShapeKind) => {setOptions({ kind: next });- commitSource({ kind: next });+ // Creation-only kinds never rewrite a selected layer; a box kind drops a polygon's points.+ if (next !== 'freehand' && next !== 'polygon') {+ commitSource({ kind: next });+ }},[commitSource, setOptions]);+ const setTarget = useCallback((next: ShapeToolOptions['target']) => setOptions({ target: next }), [setOptions]);const previewStrokeWidth = useCallback((value: number) => setOptions({ strokeWidth: value }), [setOptions]);const setStrokeWidth = useCallback((value: number) => {@@ -144,7 +145,10 @@ const useShapeEditor = (engine: ToolFormProps['engine']) => {return {fill,kind,+ selectedIsPolygon: selected?.source.kind === 'polygon',selectedName: selected?.name ?? null,+ setTarget,+ target: options.target,setFillColor,setFillEnabled,setKind,@@ -154,6 +158,7 @@ const useShapeEditor = (engine: ToolFormProps['engine']) => {setStrokeWidth,stroke,strokeWidth,+ toolKind: options.kind,};};@@ -161,12 +166,29 @@ const ShapeSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const editor = useShapeEditor(engine);const sampleColor = useColorSampler(engine);+ // A selected layer shows its own kind and can only switch among the box+ // kinds (a box has no vertices to become a polygon; a polygon switched to a+ // box drops its points). Polygon and freehand are creation gestures, offered+ // while nothing is selected.const kindOptions = useMemo(() => [{ label: t('widgets.canvas.toolOptions.shapeRect'), value: 'rect' as const },{ label: t('widgets.canvas.toolOptions.shapeEllipse'), value: 'ellipse' as const },{ label: t('widgets.canvas.toolOptions.shapeTriangle'), value: 'triangle' as const },{ label: t('widgets.canvas.toolOptions.shapeStar'), value: 'star' as const },+ ...(editor.selectedName === null || editor.selectedIsPolygon+ ? [{ label: t('widgets.canvas.toolOptions.shapePolygon'), value: 'polygon' as const }]+ : []),+ ...(editor.selectedName === null+ ? [{ label: t('widgets.canvas.toolOptions.shapeFreehand'), value: 'freehand' as const }]+ : []),+ ],+ [editor.selectedIsPolygon, editor.selectedName, t]+ );+ const targetOptions = useMemo(+ () => [+ { label: t('widgets.canvas.toolOptions.shapeTargetSelected'), value: 'selected' as const },+ { label: t('widgets.canvas.toolOptions.shapeTargetNew'), value: 'new' as const },],[t]);@@ -191,6 +213,14 @@ const ShapeSettings = ({ engine }: ToolFormProps) => {value={editor.kind}onValueChange={editor.setKind}/>+ {editor.selectedName === null ? (+ <PropertySegmentedRow+ label={t('widgets.canvas.toolOptions.shapeTarget')}+ options={targetOptions}+ value={editor.target}+ onValueChange={editor.setTarget}+ />+ ) : null}{/* The chip stays enabled-looking but inert when the slot is off; the toggle owns enablement. */}<PropertyControlRow label={t('widgets.canvas.toolOptions.shapeFill')}><ColorPicker@@ -245,7 +275,13 @@ const ShapeSettings = ({ engine }: ToolFormProps) => {/></PropertyControlRow><Text color="fg.muted" fontSize="2xs">- {t('widgets.canvas.toolOptions.shapeHint')}+ {t(+ editor.toolKind === 'polygon'+ ? 'widgets.canvas.toolOptions.shapePolygonHint'+ : editor.toolKind === 'freehand'+ ? 'widgets.canvas.toolOptions.shapeFreehandHint'+ : 'widgets.canvas.toolOptions.shapeHint'+ )}</Text></>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex a7367a6668..c90fcb8902 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -794,27 +794,30 @@ describe('getLayerContextActions', () => {}});- it('hides filter for empty paint and polygon raster sources', () => {+ it('hides filter for empty paint and pointless polygon sources, but offers it for a drawn polygon', () => {const empty = createEmptyPaintLayer('Empty', 'filter-empty');+ const polygonSource = (points: { x: number; y: number }[]) => ({+ fill: '#fff',+ height: 20,+ kind: 'polygon' as const,+ points,+ stroke: null,+ strokeWidth: 0,+ type: 'shape' as const,+ width: 20,+ });+ const pointless = paintLayer('filter-pointless', { source: polygonSource([]) });const polygon = paintLayer('filter-polygon', {- source: {- fill: '#fff',- height: 20,- kind: 'polygon',- points: [- { x: 0, y: 0 },- { x: 20, y: 0 },- { x: 10, y: 20 },- ],- stroke: null,- strokeWidth: 0,- type: 'shape',- width: 20,- },+ source: polygonSource([+ { x: 0, y: 0 },+ { x: 20, y: 0 },+ { x: 10, y: 20 },+ ]),});expect(idsFor(empty, [empty], { hasSupportedContent: false })).not.toContain('filter');- expect(idsFor(polygon, [polygon], { hasSupportedContent: true })).not.toContain('filter');+ expect(idsFor(pointless, [pointless], { hasSupportedContent: true })).not.toContain('filter');+ expect(idsFor(polygon, [polygon], { hasSupportedContent: true })).toContain('filter');});it('enables raster filter only with an engine, unlocked layer, and unlocked interaction', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex b0eb26e3c2..a57398e327 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -11,6 +11,7 @@ import type { LucideIcon } from 'lucide-react';import {getDocumentIndex,getSourceContentRect,+ isEmptyPolygonShape,isHideableLayer,isNodeHidden,isPixelBackedLayer,@@ -276,7 +277,7 @@ const isParametricRasterizable = (layer: CanvasLayerContract): boolean =>layer.type === 'raster' &&(layer.source.type === 'gradient' ||layer.source.type === 'text' ||- (layer.source.type === 'shape' && layer.source.kind !== 'polygon'));+ (layer.source.type === 'shape' && !isEmptyPolygonShape(layer.source)));const hasFilterableLayerContent = (context: LayerContextActionState): boolean => {if (!context.hasSupportedContent || (context.layer.type !== 'raster' && context.layer.type !== 'control')) {@@ -291,7 +292,9 @@ const hasFilterableLayerContent = (context: LayerContextActionState): boolean =>if (context.layer.type !== 'raster') {return false;}- return source.type === 'text' || source.type === 'gradient' || (source.type === 'shape' && source.kind !== 'polygon');+ return (+ source.type === 'text' || source.type === 'gradient' || (source.type === 'shape' && !isEmptyPolygonShape(source))+ );};/** Where the layer sits among its siblings (index 0 = top), or null when absent. */