Skip to content

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

19.6 KB
Raw Blame
import type {
  CanvasAdjustmentEntry,
  CanvasBlendMode,
  CanvasControlLayerContract,
  CanvasDocumentContractV3,
  CanvasImageRef,
  CanvasInpaintMaskLayerContract,
  CanvasLayerBaseContract,
  CanvasLayerContract,
  CanvasMaskContract,
  CanvasMaskFillContract,
  CanvasPixelSourceContract,
  CanvasRasterLayerContractV2,
  CanvasRegionalGuidanceLayerContract,
  RegionalGuidanceReferenceImage,
  Rect,
} from '@workbench/canvas-engine/api';

export type { CanvasStructuralEngine } from '@workbench/canvas-engine/api';

import { getRegionalGuidanceSupport } from '@features/generation/graph';
import { createItemId } from '@platform/browser/randomUuid';
import {
  createControlLayer,
  DEFAULT_INPAINT_MASK_FILL,
  DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR,
  getSourceContentRect,
  isIdentityAdjustments,
  isMergeableRasterLayer,
  mergeDownEligibility,
} from '@workbench/canvas-engine/api';
import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';

type LayerTransform = CanvasLayerBaseContract['transform'];

type ControlConfigPatch = { layerType: 'control'; withTransparencyEffect?: boolean };
type RegionalGuidanceConfigPatch = {
  layerType: 'regional_guidance';
  positivePrompt?: string | null;
  negativePrompt?: string | null;
  autoNegative?: boolean;
  referenceImages?: CanvasRegionalGuidanceLayerContract['referenceImages'];
};
/** Re-export the engine's canonical mergeability predicate so UI and engine exclude unsafe mask merges consistently. */
export { isMergeableRasterLayer };

/** All 16 document blend modes, in the contract's declared order. */
export const CANVAS_BLEND_MODES: readonly CanvasBlendMode[] = [
  'normal',
  'multiply',
  'screen',
  'overlay',
  'darken',
  'lighten',
  'color-dodge',
  'color-burn',
  'hard-light',
  'soft-light',
  'difference',
  'exclusion',
  'hue',
  'saturation',
  'color',
  'luminosity',
];

/** Fill styles in the order every mask and region menu lists them. */
export const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
  'solid',
  'grid',
  'crosshatch',
  'diagonal_left',
  'diagonal',
  'horizontal',
  'vertical',
];

/** Mints a fresh layer id (matches the engine's `createLayerId` shape). */
export const createLayerId = (): string => createItemId('layer');

/** Builds an empty, document-sized paint layer with sensible defaults. */
export const createEmptyPaintLayer = (name: string, id: string = createLayerId()): CanvasRasterLayerContractV2 => ({
  blendMode: 'normal',
  id,
  isEnabled: true,
  isLocked: false,
  name,
  opacity: 1,
  source: { bitmap: null, type: 'paint' },
  transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
  type: 'raster',
});

/** Use the legacy diagonal inpaint hatch and first fill color; multiple masks are allowed. */
export { DEFAULT_INPAINT_MASK_FILL };

/** The next free "Inpaint Mask N" name given the existing layer names (N ≥ 1, first gap). */
export const nextInpaintMaskName = (existingNames: readonly string[]): string => {
  const used = new Set<number>();
  for (const name of existingNames) {
    const match = /^Inpaint Mask (\d+)$/.exec(name.trim());
    if (match) {
      const n = Number(match[1]);
      if (Number.isInteger(n) && n > 0) {
        used.add(n);
      }
    }
  }
  let n = 1;
  while (used.has(n)) {
    n += 1;
  }
  return `Inpaint Mask ${n}`;
};

/** The next free "Group N" name given the existing node names (N ≥ 1, first gap). */
export const nextGroupName = (existingNames: readonly string[]): string => {
  const used = new Set<number>();
  for (const name of existingNames) {
    const match = /^Group (\d+)$/.exec(name.trim());
    if (match) {
      const n = Number(match[1]);
      if (Number.isInteger(n) && n > 0) {
        used.add(n);
      }
    }
  }
  let n = 1;
  while (used.has(n)) {
    n += 1;
  }
  return `Group ${n}`;
};

const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

/** The number in a "<prefix> N" name (N ≥ 1), or null. */
const numberedSuffix = (prefix: string, name: string): number | null => {
  const match = new RegExp(`^${escapeRegExp(prefix)} (\\d+)$`).exec(name.trim());
  const number = Number(match?.[1]);
  return Number.isInteger(number) && number > 0 ? number : null;
};

/** The next free "<Type> N" name for a control layer that just got a type, given the other layers' names. */
export const nextControlTypeLayerName = (typeLabel: string, existingNames: readonly string[]): string => {
  const used = new Set(existingNames.map((name) => numberedSuffix(typeLabel, name)));
  let n = 1;
  while (used.has(n)) {
    n += 1;
  }
  return `${typeLabel} ${n}`;
};

/** Whether a control layer still has an app-given name, so a type change may rename it; typed names stay. */
export const isAutoControlLayerName = (name: string, typeLabels: readonly string[]): boolean =>
  ['Control Layer', ...typeLabels].some((prefix) => numberedSuffix(prefix, name) !== null);

/** Builds an empty inpaint mask layer with the legacy-default fill (no bitmap yet). */
export const createInpaintMaskLayer = (
  name: string,
  id: string = createLayerId(),
  color: string = DEFAULT_INPAINT_MASK_FILL.color
): CanvasInpaintMaskLayerContract => ({
  blendMode: 'normal',
  id,
  isEnabled: true,
  isLocked: false,
  mask: { bitmap: null, fill: { ...DEFAULT_INPAINT_MASK_FILL, color } },
  name,
  opacity: 1,
  transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
  type: 'inpaint_mask',
});

/** The next free "Regional Guidance N" name given the existing layer names (N ≥ 1, first gap). */
export const nextRegionalGuidanceName = (existingNames: readonly string[]): string => {
  const used = new Set<number>();
  for (const name of existingNames) {
    const match = /^Regional Guidance (\d+)$/.exec(name.trim());
    if (match) {
      const n = Number(match[1]);
      if (Number.isInteger(n) && n > 0) {
        used.add(n);
      }
    }
  }
  let n = 1;
  while (used.has(n)) {
    n += 1;
  }
  return `Regional Guidance ${n}`;
};

export const createRegionalGuidanceLayer = (
  name: string,
  color: string | undefined,
  id: string = createLayerId()
): CanvasRegionalGuidanceLayerContract => ({
  autoNegative: false,
  blendMode: 'normal',
  id,
  isEnabled: true,
  isLocked: false,
  mask: {
    bitmap: null,
    fill: { color: color ?? DEFAULT_REGIONAL_GUIDANCE_FILL_COLOR, style: 'solid' },
  },
  name,
  negativePrompt: null,
  opacity: 0.5,
  positivePrompt: null,
  referenceImages: [],
  transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
  type: 'regional_guidance',
});

export interface CreateMaskLayerFromImageInput {
  image: CanvasImageRef;
  rect: Rect;
  id: string;
  name: string;
  fill: CanvasMaskFillContract;
}

export const createInpaintMaskFromImage = (input: CreateMaskLayerFromImageInput): CanvasInpaintMaskLayerContract => ({
  ...createInpaintMaskLayer(input.name, input.id),
  mask: {
    bitmap: { ...input.image },
    fill: { ...input.fill },
    offset: { x: input.rect.x, y: input.rect.y },
  },
});

export const createRegionalGuidanceFromImage = (
  input: CreateMaskLayerFromImageInput
): CanvasRegionalGuidanceLayerContract => ({
  ...createRegionalGuidanceLayer(input.name, undefined, input.id),
  mask: {
    bitmap: { ...input.image },
    fill: { ...input.fill },
    offset: { x: input.rect.x, y: input.rect.y },
  },
});

export const createReferenceImageId = (): string => createItemId('rgref');

export const createAdjustmentId = (): string => createItemId('adj');

/** A new noise entry's amount: σ ≈ 13 of 255, grain clearly visible at 100% zoom without swamping detail. */
export const DEFAULT_NOISE_AMOUNT = 0.1;

/** A new noise entry's grain size: one independent sample per pixel, the finest grain. */
export const DEFAULT_NOISE_SIZE = 1;

/** Clarity's and Texture's default feature sizes in owner pixels, matching the backend nodes' defaults. */
export const DEFAULT_CLARITY_SIZE = 40;
export const DEFAULT_TEXTURE_SIZE = 8;

/** A fresh uint32 pattern seed for a noise entry. */
export const createNoiseSeed = (): number => crypto.getRandomValues(new Uint32Array(1))[0]!;

/** Parametric types start at identity; invert and noise (fresh seed, visible grain) apply at once. */
export const createAdjustmentEntry = (type: CanvasAdjustmentEntry['type']): CanvasAdjustmentEntry => {
  const id = createAdjustmentId();
  switch (type) {
    case 'brightness-contrast':
      return { brightness: 0, contrast: 0, id, isEnabled: true, type };
    case 'exposure':
      return { id, isEnabled: true, stops: 0, type };
    case 'levels':
      return { gamma: 1, id, inBlack: 0, inWhite: 255, isEnabled: true, outBlack: 0, outWhite: 255, type };
    case 'curves':
      return { curves: {}, id, isEnabled: true, type };
    case 'hsl':
      return { id, isEnabled: true, saturation: 0, type };
    case 'hue':
      return { id, isEnabled: true, rotation: 0, type };
    case 'invert':
      return { id, isEnabled: true, type };
    case 'noise':
      return {
        amount: DEFAULT_NOISE_AMOUNT,
        distribution: 'gaussian',
        grain: 'monochrome',
        id,
        isEnabled: true,
        // Grain that fades out in shadows and highlights reads as film rather than as a noise overlay.
        response: 'midtones',
        seed: createNoiseSeed(),
        size: DEFAULT_NOISE_SIZE,
        type,
      };
    case 'clarity':
      return { amount: 0, id, isEnabled: true, size: DEFAULT_CLARITY_SIZE, type };
    case 'texture':
      return { amount: 0, id, isEnabled: true, size: DEFAULT_TEXTURE_SIZE, type };
    case 'dehaze':
      return { amount: 0, id, isEnabled: true, type };
  }
};

export const DEFAULT_REGIONAL_REFERENCE_WEIGHT = 1;

/** Regional-reference defaults: FLUX uses Redux, other bases IP-Adapter. */
export const createRegionalReferenceImage = (
  base: string | null,
  id: string = createReferenceImageId()
): RegionalGuidanceReferenceImage => {
  if (getRegionalGuidanceSupport(base)?.referenceImages === 'flux_redux') {
    return {
      config: { image: null, imageInfluence: 'highest', model: null, type: 'flux_redux' },
      id,
      isEnabled: true,
    };
  }
  return {
    config: {
      beginEndStepPct: [0, 1],
      clipVisionModel: 'ViT-H',
      image: null,
      method: 'full',
      model: null,
      type: 'ip_adapter',
      weight: DEFAULT_REGIONAL_REFERENCE_WEIGHT,
    },
    id,
    isEnabled: true,
  };
};

/** Whether a regional reference image can be added; with no model selected every option stays open. */
export const canAddRegionalReferenceImage = (base: string | null): boolean =>
  base === null || Boolean(getRegionalGuidanceSupport(base)?.referenceImages);

export const createRegionalGuidanceLayerWithRefImage = (
  name: string,
  color: string | undefined,
  base: string | null,
  id: string = createLayerId()
): CanvasRegionalGuidanceLayerContract => ({
  ...createRegionalGuidanceLayer(name, color, id),
  referenceImages: [createRegionalReferenceImage(base)],
});

export { CONTROL_ADAPTER_DEFAULTS };

export const CONTROL_WEIGHT_BOUNDS = {
  inputMax: 2,
  inputMin: -1,
  sliderMax: 2,
  sliderMin: 0,
  step: 0.05,
} as const;

export const DEFAULT_CONTROL_ADAPTER = CONTROL_ADAPTER_DEFAULTS.controlnet;

/** A new mask modifier's magnitude (legacy defaults): noise level and denoise limit. */
export const MASK_MODIFIER_DEFAULTS = { denoise: 0.8, noise: 0.25 } as const;

/** Returns the transform that fits the layer's unrotated local content into the bbox. */
export const fitLayerTransformToBbox = (
  layer: CanvasLayerContract,
  bbox: Rect,
  documentRect: Rect = bbox,
  mode: 'contain' | 'cover' | 'fill' = 'contain'
): LayerTransform | null => {
  const doc = { height: documentRect.height, width: documentRect.width } as CanvasDocumentContractV3;
  const contentRect = getSourceContentRect(layer, doc);
  if (contentRect.width <= 0 || contentRect.height <= 0) {
    return null;
  }
  const widthScale = bbox.width / contentRect.width;
  const heightScale = bbox.height / contentRect.height;
  const scale = mode === 'cover' ? Math.max(widthScale, heightScale) : Math.min(widthScale, heightScale);
  const scaleX = mode === 'fill' ? widthScale : scale;
  const scaleY = mode === 'fill' ? heightScale : scale;
  return {
    rotation: 0,
    scaleX,
    scaleY,
    x: bbox.x + (bbox.width - contentRect.width * scaleX) / 2 - contentRect.x * scaleX,
    y: bbox.y + (bbox.height - contentRect.height * scaleY) / 2 - contentRect.y * scaleY,
  };
};

export const getControlTransparencyEffectPatch = (layer: CanvasControlLayerContract): ControlConfigPatch => ({
  layerType: 'control',
  withTransparencyEffect: !layer.withTransparencyEffect,
});

export const getRegionalGuidanceAutoNegativePatch = (
  layer: CanvasRegionalGuidanceLayerContract
): RegionalGuidanceConfigPatch => ({ autoNegative: !layer.autoNegative, layerType: 'regional_guidance' });

/** Allow raster/control conversion only for pixel-backed image/paint sources, excluding parametric and mask layers. */
export const canConvertRasterControl = (layer: CanvasLayerContract): boolean => {
  if (layer.type === 'control') {
    return true;
  }
  return layer.type === 'raster' && (layer.source.type === 'image' || layer.source.type === 'paint');
};

type PixelLayer = CanvasRasterLayerContractV2 | CanvasControlLayerContract;

/** Whether adjustments change the pixels, so moving to the control stack must bake them. */
export const needsBakedControlPixels = (layer: CanvasLayerContract): boolean =>
  layer.type === 'raster' && !isIdentityAdjustments(layer.adjustments);

const cloneTransform = (layer: CanvasLayerContract): LayerTransform => ({ ...layer.transform });

const clonePixelSource = (layer: PixelLayer): CanvasPixelSourceContract | null => {
  if (layer.source.type === 'image') {
    return { image: { ...layer.source.image }, type: 'image' };
  }
  if (layer.source.type === 'paint') {
    return {
      bitmap: layer.source.bitmap ? { ...layer.source.bitmap } : null,
      offset: layer.source.offset ? { ...layer.source.offset } : undefined,
      type: 'paint',
    };
  }
  return null;
};

const pixelLayerToMask = (layer: PixelLayer, color: string): CanvasMaskContract | null => {
  const source = clonePixelSource(layer);
  if (!source) {
    return null;
  }
  if (source.type === 'image') {
    return { bitmap: source.image, fill: { ...DEFAULT_INPAINT_MASK_FILL, color } };
  }
  return {
    bitmap: source.bitmap,
    fill: { ...DEFAULT_INPAINT_MASK_FILL, color },
    offset: source.offset,
  };
};

const cloneMask = (mask: CanvasMaskContract): CanvasMaskContract => ({
  bitmap: mask.bitmap ? { ...mask.bitmap } : null,
  fill: { ...mask.fill },
  offset: mask.offset ? { ...mask.offset } : undefined,
});

const destinationBase = (layer: CanvasLayerContract, id: string, isCopy: boolean): CanvasLayerBaseContract => ({
  blendMode: layer.blendMode,
  ...(layer.colorLabel ? { colorLabel: layer.colorLabel } : {}),
  id,
  isEnabled: layer.isEnabled,
  isLocked: layer.isLocked,
  name: isCopy ? `${layer.name} copy` : layer.name,
  opacity: layer.opacity,
  transform: cloneTransform(layer),
});

/** An untyped, model-less control layer over the same pixels; generation resolves its model. */
const pixelLayerToControl = (
  layer: PixelLayer,
  id: string,
  isCopy: boolean,
  base?: string | null
): CanvasControlLayerContract | null => {
  const source = needsBakedControlPixels(layer) ? null : clonePixelSource(layer);
  if (!source) {
    return null;
  }
  const destination = destinationBase(layer, id, isCopy);
  return { ...createControlLayer({ base, id, name: destination.name, source }), ...destination };
};

const pixelLayerToInpaintMask = (
  layer: PixelLayer,
  id: string,
  isCopy: boolean,
  color: string
): CanvasInpaintMaskLayerContract | null => {
  const mask = pixelLayerToMask(layer, color);
  return mask ? { ...destinationBase(layer, id, isCopy), mask, type: 'inpaint_mask' } : null;
};

const pixelLayerToRegionalGuidance = (
  layer: PixelLayer,
  id: string,
  isCopy: boolean,
  color: string
): CanvasRegionalGuidanceLayerContract | null => {
  const mask = pixelLayerToMask(layer, color);
  return mask
    ? {
        ...destinationBase(layer, id, isCopy),
        autoNegative: false,
        mask,
        negativePrompt: null,
        positivePrompt: null,
        referenceImages: [],
        type: 'regional_guidance',
      }
    : null;
};

export const copyRasterToControl = (
  layer: CanvasRasterLayerContractV2,
  id: string,
  base?: string | null
): CanvasControlLayerContract | null => pixelLayerToControl(layer, id, true, base);

// Pixel layers carry no mask color; callers pass the destination palette's next color.
export const copyRasterToInpaintMask = (
  layer: CanvasRasterLayerContractV2,
  id: string,
  color: string
): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true, color);

export const copyRasterToRegionalGuidance = (
  layer: CanvasRasterLayerContractV2,
  id: string,
  color: string
): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true, color);

export const convertRasterToControl = (
  layer: CanvasRasterLayerContractV2,
  base?: string | null
): CanvasControlLayerContract | null => pixelLayerToControl(layer, layer.id, false, base);

export const convertRasterToInpaintMask = (
  layer: CanvasRasterLayerContractV2,
  color: string
): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, layer.id, false, color);

export const convertRasterToRegionalGuidance = (
  layer: CanvasRasterLayerContractV2,
  color: string
): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, layer.id, false, color);

export const copyControlToRaster = (
  layer: CanvasControlLayerContract,
  id: string
): CanvasRasterLayerContractV2 | null => {
  const source = clonePixelSource(layer);
  return source ? { ...destinationBase(layer, id, true), source, type: 'raster' } : null;
};

export const copyControlToInpaintMask = (
  layer: CanvasControlLayerContract,
  id: string,
  color: string
): CanvasInpaintMaskLayerContract | null => pixelLayerToInpaintMask(layer, id, true, color);

export const copyControlToRegionalGuidance = (
  layer: CanvasControlLayerContract,
  id: string,
  color: string
): CanvasRegionalGuidanceLayerContract | null => pixelLayerToRegionalGuidance(layer, id, true, color);

export const copyMaskToRegionalGuidance = (
  layer: CanvasInpaintMaskLayerContract,
  id: string
): CanvasRegionalGuidanceLayerContract => ({
  ...destinationBase(layer, id, true),
  autoNegative: false,
  mask: cloneMask(layer.mask),
  negativePrompt: null,
  positivePrompt: null,
  referenceImages: [],
  type: 'regional_guidance',
});

export const copyRegionalGuidanceToInpaintMask = (
  layer: CanvasRegionalGuidanceLayerContract,
  id: string
): CanvasInpaintMaskLayerContract => ({
  ...destinationBase(layer, id, true),
  mask: cloneMask(layer.mask),
  type: 'inpaint_mask',
});

/** Converts raster/control types keeping source, identity, transform and base; rejects unsupported targets. */
export const convertRasterControlLayer = (
  layer: CanvasLayerContract,
  targetType: 'raster' | 'control',
  base?: string | null
): CanvasLayerContract | null => {
  if (layer.type === targetType || !canConvertRasterControl(layer)) {
    return null;
  }
  if (layer.type === 'raster' && targetType === 'control') {
    return convertRasterToControl(layer, base);
  }
  if (layer.type === 'control' && targetType === 'raster') {
    const source = clonePixelSource(layer);
    return source ? { ...destinationBase(layer, layer.id, false), source, type: 'raster' } : null;
  }
  return null;
};

/** Whether the layers panel may offer merge-down for `layerId`; merging is pixel work, so it needs an engine. */
export const canMergeLayerDown = (document: CanvasDocumentContractV3, layerId: string, hasEngine: boolean): boolean =>
  hasEngine && mergeDownEligibility(document, layerId).status === 'eligible';