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
refactor(webv2): extract the floating-selection frame
joshistoastacfc5fb9e5ce
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 6bc3b31011..e082779526 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -102,7 +102,7 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';import type { RenderScheduler } from '@workbench/canvas-engine/render/scheduler';import type { SamVisualInput } from '@workbench/canvas-engine/samInteraction';-import type { Mat2d, Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';+import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import { ControlPixelController } from '@workbench/canvas-engine/controllers/controlPixelController';@@ -146,7 +146,6 @@ import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, union } from '@workbench/canvas-engine/math/rect';import {- type CompositeOptions,compositeDocument,createCheckerboardTile,shouldSmoothAtZoom,@@ -159,11 +158,7 @@ import { createDomRasterBackend, type RasterBackend, type RasterSurface } from 'import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';import { enforceSurfaceBudget } from '@workbench/canvas-engine/render/surfaceBudget';import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';-import {- documentDeltaToLocal,- floatDocumentMatrix,- liftSelectedPixels,-} from '@workbench/canvas-engine/selection/floatingSelection';+import { documentDeltaToLocal, liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';import { ANTS_STEP_PX, createAntsAnimator, type AntsAnimator } from '@workbench/canvas-engine/selection/marchingAnts';import { createBboxTool } from '@workbench/canvas-engine/tools/bboxTool';import { createBrushTool } from '@workbench/canvas-engine/tools/brushTool';@@ -179,11 +174,7 @@ import { createSamTool } from '@workbench/canvas-engine/tools/samTool';import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';import { createTextTool } from '@workbench/canvas-engine/tools/textTool';import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';-import {- bakeMatrix,- type LayerTransform,- transformOverlayGeometry,-} from '@workbench/canvas-engine/transform/transformMath';+import { type LayerTransform, transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';import type { ImagePatchApply } from './history/imagePatch';@@ -197,6 +188,7 @@ import { createLayerExportGuards, isDeeplyEqual, isSupportedExportSource } fromimport { createLayerRasterizer } from './layerRasterizer';import { createPreviewPublisher } from './previewPublisher';import { createRasterSnapshotCapture } from './rasterSnapshotCapture';+import { floatingSelectionFrame } from './render/floatingSelectionFrame';import { createSelectObjectBridge } from './selectObjectBridge';import { createStrokeCommit } from './strokeCommit';import { createViewTool } from './tools/viewTool';@@ -845,30 +837,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC* layer-local placement, and the document-space matrix the ants ride through* so the outline tracks the pixels in flight.*/- const floatingSelectionRender = (- doc: CanvasDocumentContractV2 | null- ): { composite: NonNullable<CompositeOptions['floatingSelection']>; ants: Mat2d } | null => {- const float = floatingSelection.get();- const layer = float && doc ? doc.layers.find((candidate) => candidate.id === float.layerId) : undefined;- if (!float || !layer) {- return null;- }- const matrix = bakeMatrix(float.transform);- const ants = floatDocumentMatrix(layerMatrix(layer.transform), matrix);- return ants- ? {- ants,- composite: {- layerId: float.layerId,- matrix,- rect: float.pixels.rect,- // The display copy when the layer has an effect; the raw pixels- // otherwise. Only the bake ever touches `pixels`.- surface: float.display ?? float.pixels.surface,- },- }- : null;- };const antsAnimator: AntsAnimator = createAntsAnimator({cancelFrame: (handle) => globalThis.cancelAnimationFrame(handle),@@ -1292,7 +1260,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst filterPreviews = renderController.previews.filterSnapshot();// Resolved once: the composite draws the float's pixels, the overlay rides// the ants through the matching document-space transform.- const floatRender = floatingSelectionRender(doc);+ const floatRender = floatingSelectionFrame(floatingSelection.get(), doc);if (needsComposite) {const stagedPlacement = stagedPreview?.placement;const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.tsnew file mode 100644index 0000000000..798da29fb8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.ts@@ -0,0 +1,70 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';++import { describe, expect, it } from 'vitest';++import { floatingSelectionFrame } from './floatingSelectionFrame';++const pixels = { surface: { id: 'raw' } as unknown as RasterSurface };++const float = (overrides: Partial<FloatingSelection> = {}): FloatingSelection =>+ ({+ display: null,+ layerId: 'layer-1',+ pixels: { rect: { height: 4, width: 4, x: 1, y: 2 }, surface: pixels.surface },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ ...overrides,+ }) as unknown as FloatingSelection;++const documentOf = (layerIds: readonly string[]): CanvasDocumentContractV2 =>+ ({+ layers: layerIds.map((id) => ({+ id,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },+ })),+ }) as unknown as CanvasDocumentContractV2;++describe('floatingSelectionFrame', () => {+ it('describes the composite and the ants together', () => {+ const frame = floatingSelectionFrame(float(), documentOf(['layer-1']));+ expect(frame).toMatchObject({+ composite: { layerId: 'layer-1', rect: { height: 4, width: 4, x: 1, y: 2 } },+ });+ expect(frame?.ants).toBeTruthy();+ });++ it('hands the compositor the same matrix the ants ride through', () => {+ const frame = floatingSelectionFrame(float(), documentOf(['layer-1']));+ // The ants matrix is the composite matrix projected into document space, so+ // a divergence here means the outline would drift off the drawn pixels.+ expect(frame?.composite.matrix).toBeTruthy();+ expect(frame?.ants).not.toBe(frame?.composite.matrix);+ });++ it.each([+ ['there is nothing floating', null, documentOf(['layer-1'])],+ ['there is no document', float(), null],+ ['the layer it was cut from is gone', float(), documentOf(['other'])],+ ])('reports nothing when %s', (_label, floating, doc) => {+ expect(floatingSelectionFrame(floating, doc)).toBeNull();+ });++ it('prefers the display copy so an effect layer draws what the user sees', () => {+ const display = { id: 'display' } as unknown as RasterSurface;+ const frame = floatingSelectionFrame(float({ display }), documentOf(['layer-1']));+ expect(frame?.composite.surface).toBe(display);+ });++ it('falls back to the raw pixels when the layer has no effect', () => {+ const frame = floatingSelectionFrame(float(), documentOf(['layer-1']));+ expect(frame?.composite.surface).toBe(pixels.surface);+ });++ it('reports nothing when the layer transform cannot be inverted', () => {+ const collapsed = {+ layers: [{ id: 'layer-1', transform: { rotation: 0, scaleX: 0, scaleY: 0, x: 0, y: 0 } }],+ } as unknown as CanvasDocumentContractV2;+ expect(floatingSelectionFrame(float(), collapsed)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.tsnew file mode 100644index 0000000000..d04b9560d3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts@@ -0,0 +1,50 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';+import type { Mat2d } from '@workbench/canvas-engine/types';++import { floatDocumentMatrix } from '@workbench/canvas-engine/selection/floatingSelection';+import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';+import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';++import type { CompositeOptions } from './compositor';++export interface FloatingSelectionFrame {+ /** What the compositor draws above the layer the pixels were cut from. */+ readonly composite: NonNullable<CompositeOptions['floatingSelection']>;+ /** The layer-local → document matrix the overlay rides its marching ants through. */+ readonly ants: Mat2d;+}++/**+ * How a floating selection appears this frame, or `null` when there is nothing+ * floating (or its layer has gone).+ *+ * The composite and the overlay must agree exactly — the ants outline the same+ * pixels the compositor drew — so both are resolved from one call rather than+ * each deriving the transform for itself. `display` is preferred over `pixels`+ * for drawing because a layer with a display-only effect shows its adjusted+ * copy; only the bake ever touches the raw pixels.+ */+export const floatingSelectionFrame = (+ float: FloatingSelection | null,+ doc: CanvasDocumentContractV2 | null+): FloatingSelectionFrame | null => {+ const layer = float && doc ? doc.layers.find((candidate) => candidate.id === float.layerId) : undefined;+ if (!float || !layer) {+ return null;+ }+ const matrix = bakeMatrix(float.transform);+ const ants = floatDocumentMatrix(layerMatrix(layer.transform), matrix);+ if (!ants) {+ return null;+ }+ return {+ ants,+ composite: {+ layerId: float.layerId,+ matrix,+ rect: float.pixels.rect,+ surface: float.display ?? float.pixels.surface,+ },+ };+};