Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

29.2 KB
Raw Blame
import { computePerceptualLuminanceByte, clampNavigatorSplitRatio } from './valueCheck';

export const SUB_VIEW_MIN_ZOOM = 0.05;
export const SUB_VIEW_MAX_ZOOM = 16.0;
export const BOARD_MIN_CARD_SCALE = 0.04;
export const BOARD_MAX_CARD_SCALE = 12.0;
export const DEFAULT_BOARD_CARD_TARGET_DIM = 220;

export type SubViewMode = 'board' | 'single';
export type SubViewBoardTool = 'eyedrop' | 'select' | 'pan';
export type SubViewValueSteps = 0 | 2 | 3 | 5;
export type SubViewGridMode = 'none' | 'thirds' | 'grid4' | 'grid8' | 'crosshair' | 'golden';
export type SubViewBoardLayoutMode = 'grid' | 'row' | 'column';

export interface SubViewTransform {
  zoom: number;
  pan: { x: number; y: number };
  rotation: number; // degrees
  flipX: boolean;
}

export interface SubViewStudyFilter {
  grayscale: boolean;
  valueSteps: SubViewValueSteps;
  notanThreshold: number; // 0..255
  squintBlur: boolean;
  brightness: number; // -100..100
  contrast: number; // -100..100
  gridMode: SubViewGridMode;
  splitBw: boolean;
  splitRatio: number; // 0.05..0.95
}

export const DEFAULT_SUB_VIEW_TRANSFORM: SubViewTransform = {
  zoom: 1,
  pan: { x: 0, y: 0 },
  rotation: 0,
  flipX: false,
};

export const DEFAULT_SUB_VIEW_STUDY_FILTER: SubViewStudyFilter = {
  grayscale: false,
  valueSteps: 0,
  notanThreshold: 128,
  squintBlur: false,
  brightness: 0,
  contrast: 0,
  gridMode: 'none',
  splitBw: false,
  splitRatio: 0.5,
};

export interface PixelCoord {
  x: number;
  y: number;
}

export interface BoardPoint {
  x: number;
  y: number;
}

export interface BoardCardGeometry {
  id: string;
  width: number;
  height: number;
  boardX: number;
  boardY: number;
  boardScale: number;
  boardRotation: number;
  boardFlipX: boolean;
  boardFlipY: boolean;
  zIndex: number;
  locked?: boolean;
}

export type CardHandleKind = 'tl' | 'tr' | 'br' | 'bl' | 'rotate';

export interface CardStageOverlay {
  tl: BoardPoint;
  tr: BoardPoint;
  br: BoardPoint;
  bl: BoardPoint;
  center: BoardPoint;
  topMid: BoardPoint;
  rotHandle: BoardPoint;
}

export interface BoardHitResult<T extends BoardCardGeometry> {
  card: T;
  pixel: PixelCoord;
  local: BoardPoint;
}

export interface ExtractedSwatch {
  hex: string;
  luminance: number; // 0..100 perceptual value %
  ratio: number; // 0..1 pixel share
}

export function clampSubViewZoom(z: number): number {
  if (!Number.isFinite(z)) return 1;
  return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, z));
}

export function clampBoardCardScale(scale: number): number {
  if (!Number.isFinite(scale)) return 1;
  return Math.max(BOARD_MIN_CARD_SCALE, Math.min(BOARD_MAX_CARD_SCALE, scale));
}

export function clampNotanThreshold(val: number): number {
  if (!Number.isFinite(val)) return 128;
  return Math.max(10, Math.min(245, Math.round(val)));
}

export function clampBrightnessContrast(val: number): number {
  if (!Number.isFinite(val)) return 0;
  return Math.max(-100, Math.min(100, Math.round(val)));
}

export function sanitizeStudyFilter(raw?: Partial<SubViewStudyFilter> | null): SubViewStudyFilter {
  if (!raw || typeof raw !== 'object') {
    return { ...DEFAULT_SUB_VIEW_STUDY_FILTER };
  }
  const valueSteps: SubViewValueSteps =
    raw.valueSteps === 2 || raw.valueSteps === 3 || raw.valueSteps === 5 ? raw.valueSteps : 0;
  const gridMode: SubViewGridMode =
    raw.gridMode === 'thirds' ||
    raw.gridMode === 'grid4' ||
    raw.gridMode === 'grid8' ||
    raw.gridMode === 'crosshair' ||
    raw.gridMode === 'golden'
      ? raw.gridMode
      : 'none';
  return {
    grayscale: Boolean(raw.grayscale),
    valueSteps,
    notanThreshold: clampNotanThreshold(
      typeof raw.notanThreshold === 'number' ? raw.notanThreshold : 128
    ),
    squintBlur: Boolean(raw.squintBlur),
    brightness: clampBrightnessContrast(typeof raw.brightness === 'number' ? raw.brightness : 0),
    contrast: clampBrightnessContrast(typeof raw.contrast === 'number' ? raw.contrast : 0),
    gridMode,
    splitBw: Boolean(raw.splitBw),
    splitRatio: clampNavigatorSplitRatio(
      typeof raw.splitRatio === 'number' ? raw.splitRatio : 0.5
    ),
  };
}

/**
 * Inverse-maps a point `(localX, localY)` inside the Single-mode stage into
 * integer source image pixel coordinates `(x, y)` accounting for pan, zoom, rotation, and flipX.
 * Returns `null` if the point lies outside the image bounds.
 */
export function subViewPointToImagePixel(
  localX: number,
  localY: number,
  stageW: number,
  stageH: number,
  imgW: number,
  imgH: number,
  transform: SubViewTransform
): PixelCoord | null {
  if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return null;
  const safeZoom = Math.max(1e-4, transform.zoom);
  const dx = localX - (stageW / 2 + transform.pan.x);
  const dy = localY - (stageH / 2 + transform.pan.y);

  const rad = (transform.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);

  const unrotX = dx * cos + dy * sin;
  const unrotY = -dx * sin + dy * cos;
  const fx = transform.flipX ? -1 : 1;

  const px = Math.floor(imgW / 2 + (fx * unrotX) / safeZoom);
  const py = Math.floor(imgH / 2 + unrotY / safeZoom);

  if (px < 0 || py < 0 || px >= imgW || py >= imgH) return null;
  return { x: px, y: py };
}

export function computeSubViewFitZoom(
  stageW: number,
  stageH: number,
  imgW: number,
  imgH: number,
  padding = 12
): number {
  if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return 1;
  const availW = Math.max(16, stageW - padding * 2);
  const availH = Math.max(16, stageH - padding * 2);
  const fit = Math.min(availW / imgW, availH / imgH);
  return clampSubViewZoom(fit);
}

/**
 * Maps a point in PureRef board space into stage pixel coordinates.
 */
export function boardPointToStagePoint(
  bx: number,
  by: number,
  stageW: number,
  stageH: number,
  boardTransform: SubViewTransform
): BoardPoint {
  const fx = boardTransform.flipX ? -1 : 1;
  const sx = fx * boardTransform.zoom * bx;
  const sy = boardTransform.zoom * by;
  const rad = (boardTransform.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  return {
    x: stageW / 2 + boardTransform.pan.x + (sx * cos - sy * sin),
    y: stageH / 2 + boardTransform.pan.y + (sx * sin + sy * cos),
  };
}

/**
 * Inverse-maps a stage pixel coordinate into PureRef board space.
 */
export function stagePointToBoardPoint(
  localX: number,
  localY: number,
  stageW: number,
  stageH: number,
  boardTransform: SubViewTransform
): BoardPoint {
  const safeZoom = Math.max(1e-4, boardTransform.zoom);
  const dx = localX - (stageW / 2 + boardTransform.pan.x);
  const dy = localY - (stageH / 2 + boardTransform.pan.y);
  const rad = (boardTransform.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const unrotX = dx * cos + dy * sin;
  const unrotY = -dx * sin + dy * cos;
  const fx = boardTransform.flipX ? -1 : 1;
  return {
    x: (fx * unrotX) / safeZoom,
    y: unrotY / safeZoom,
  };
}

/**
 * Converts a delta in stage pixels into a delta in board space (accounting for zoom, rotation, flipX).
 */
export function stageDeltaToBoardDelta(
  dx: number,
  dy: number,
  boardTransform: SubViewTransform
): BoardPoint {
  const safeZoom = Math.max(1e-4, boardTransform.zoom);
  const rad = (boardTransform.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const unrotX = dx * cos + dy * sin;
  const unrotY = -dx * sin + dy * cos;
  const fx = boardTransform.flipX ? -1 : 1;
  return {
    x: (fx * unrotX) / safeZoom,
    y: unrotY / safeZoom,
  };
}

/**
 * Maps a point in card-local space (center = 0,0) into board space.
 */
export function cardLocalToBoardPoint(
  lx: number,
  ly: number,
  card: Pick<BoardCardGeometry, 'boardX' | 'boardY' | 'boardScale' | 'boardRotation' | 'boardFlipX' | 'boardFlipY'>
): BoardPoint {
  const sx = (card.boardFlipX ? -1 : 1) * card.boardScale * lx;
  const sy = (card.boardFlipY ? -1 : 1) * card.boardScale * ly;
  const rad = (card.boardRotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  return {
    x: card.boardX + (sx * cos - sy * sin),
    y: card.boardY + (sx * sin + sy * cos),
  };
}

/**
 * Inverse-maps a board point into card-local pixel-offset coordinates (center = 0,0).
 */
export function boardPointToCardLocal(
  bx: number,
  by: number,
  card: Pick<BoardCardGeometry, 'boardX' | 'boardY' | 'boardScale' | 'boardRotation' | 'boardFlipX' | 'boardFlipY'>
): BoardPoint {
  const safeScale = Math.max(1e-4, card.boardScale);
  const dx = bx - card.boardX;
  const dy = by - card.boardY;
  const rad = (card.boardRotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const unrotX = dx * cos + dy * sin;
  const unrotY = -dx * sin + dy * cos;
  return {
    x: ((card.boardFlipX ? -1 : 1) * unrotX) / safeScale,
    y: ((card.boardFlipY ? -1 : 1) * unrotY) / safeScale,
  };
}

/**
 * Computes screen-space corner and rotation handle positions for a card on the PureRef board.
 */
export function getCardStageOverlay(
  card: BoardCardGeometry,
  stageW: number,
  stageH: number,
  boardTransform: SubViewTransform,
  rotHandleOffsetPx = 18
): CardStageOverlay {
  const hw = card.width / 2;
  const hh = card.height / 2;
  // Use unflipped corner geometry so handles stay attached visually to TL/TR/BR/BL
  const baseCard = { ...card, boardFlipX: false, boardFlipY: false };
  const tlB = cardLocalToBoardPoint(-hw, -hh, baseCard);
  const trB = cardLocalToBoardPoint(hw, -hh, baseCard);
  const brB = cardLocalToBoardPoint(hw, hh, baseCard);
  const blB = cardLocalToBoardPoint(-hw, hh, baseCard);
  const topMidB = cardLocalToBoardPoint(0, -hh, baseCard);

  const tl = boardPointToStagePoint(tlB.x, tlB.y, stageW, stageH, boardTransform);
  const tr = boardPointToStagePoint(trB.x, trB.y, stageW, stageH, boardTransform);
  const br = boardPointToStagePoint(brB.x, brB.y, stageW, stageH, boardTransform);
  const bl = boardPointToStagePoint(blB.x, blB.y, stageW, stageH, boardTransform);
  const center = boardPointToStagePoint(card.boardX, card.boardY, stageW, stageH, boardTransform);
  const topMid = boardPointToStagePoint(topMidB.x, topMidB.y, stageW, stageH, boardTransform);

  // Compute outward normal along (topMid - center) in stage pixels so handle offset is crisp at all zooms
  const nx = topMid.x - center.x;
  const ny = topMid.y - center.y;
  const nLen = Math.hypot(nx, ny);
  const rotHandle: BoardPoint =
    nLen > 1e-4
      ? {
          x: topMid.x + (nx / nLen) * rotHandleOffsetPx,
          y: topMid.y + (ny / nLen) * rotHandleOffsetPx,
        }
      : { x: topMid.x, y: topMid.y - rotHandleOffsetPx };

  return { tl, tr, br, bl, center, topMid, rotHandle };
}

export function hitTestCardHandle(
  localX: number,
  localY: number,
  card: BoardCardGeometry,
  stageW: number,
  stageH: number,
  boardTransform: SubViewTransform,
  hitRadius = 9
): CardHandleKind | null {
  if (card.locked) return null;
  const overlay = getCardStageOverlay(card, stageW, stageH, boardTransform);
  const r2 = hitRadius * hitRadius;
  const check = (p: BoardPoint) => {
    const dx = localX - p.x;
    const dy = localY - p.y;
    return dx * dx + dy * dy <= r2;
  };
  if (check(overlay.rotHandle)) return 'rotate';
  if (check(overlay.tl)) return 'tl';
  if (check(overlay.tr)) return 'tr';
  if (check(overlay.br)) return 'br';
  if (check(overlay.bl)) return 'bl';
  return null;
}

/**
 * Hit-tests cards on the PureRef board from top zIndex to bottom, returning the topmost card
 * and exact source image pixel coordinates under `(localX, localY)`.
 */
export function hitTestBoardCards<T extends BoardCardGeometry>(
  localX: number,
  localY: number,
  cards: readonly T[],
  stageW: number,
  stageH: number,
  boardTransform: SubViewTransform
): BoardHitResult<T> | null {
  if (cards.length === 0 || stageW <= 0 || stageH <= 0) return null;
  const bp = stagePointToBoardPoint(localX, localY, stageW, stageH, boardTransform);

  const sorted = cards
    .map((card, idx) => ({ card, idx }))
    .sort((a, b) => b.card.zIndex - a.card.zIndex || b.idx - a.idx);

  for (const { card } of sorted) {
    if (card.width <= 0 || card.height <= 0) continue;
    const lp = boardPointToCardLocal(bp.x, bp.y, card);
    const px = Math.floor(card.width / 2 + lp.x);
    const py = Math.floor(card.height / 2 + lp.y);
    if (px >= 0 && py >= 0 && px < card.width && py < card.height) {
      return { card, pixel: { x: px, y: py }, local: lp };
    }
  }
  return null;
}

/**
 * Computes the world-space axis-aligned bounding box of one or more board cards.
 */
export function computeBoardBounds(
  cards: readonly BoardCardGeometry[]
): { minX: number; minY: number; maxX: number; maxY: number; width: number; height: number; cx: number; cy: number } | null {
  if (cards.length === 0) return null;
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;

  for (const card of cards) {
    const hw = Math.max(1, card.width) / 2;
    const hh = Math.max(1, card.height) / 2;
    const corners = [
      cardLocalToBoardPoint(-hw, -hh, card),
      cardLocalToBoardPoint(hw, -hh, card),
      cardLocalToBoardPoint(hw, hh, card),
      cardLocalToBoardPoint(-hw, hh, card),
    ];
    for (const c of corners) {
      if (c.x < minX) minX = c.x;
      if (c.y < minY) minY = c.y;
      if (c.x > maxX) maxX = c.x;
      if (c.y > maxY) maxY = c.y;
    }
  }

  if (!Number.isFinite(minX)) return null;
  const width = Math.max(1, maxX - minX);
  const height = Math.max(1, maxY - minY);
  return {
    minX,
    minY,
    maxX,
    maxY,
    width,
    height,
    cx: (minX + maxX) / 2,
    cy: (minY + maxY) / 2,
  };
}

/**
 * Computes a board camera transform that fits all given cards cleanly inside the stage.
 */
export function computeBoardFitTransform(
  cards: readonly BoardCardGeometry[],
  stageW: number,
  stageH: number,
  padding = 18
): SubViewTransform {
  const bounds = computeBoardBounds(cards);
  if (!bounds || stageW <= 0 || stageH <= 0) {
    return { ...DEFAULT_SUB_VIEW_TRANSFORM, pan: { x: 0, y: 0 } };
  }
  const availW = Math.max(20, stageW - padding * 2);
  const availH = Math.max(20, stageH - padding * 2);
  const zoom = clampSubViewZoom(Math.min(availW / bounds.width, availH / bounds.height));
  return {
    zoom,
    pan: {
      x: -bounds.cx * zoom,
      y: -bounds.cy * zoom,
    },
    rotation: 0,
    flipX: false,
  };
}

export function computeNormalizedBoardScale(
  width: number,
  height: number,
  targetDim = DEFAULT_BOARD_CARD_TARGET_DIM
): number {
  const longEdge = Math.max(1, width, height);
  return clampBoardCardScale(targetDim / longEdge);
}

/**
 * Computes clean, non-overlapping PureRef board placements for all items in a given layout.
 */
export function computeBoardAutoLayout(
  items: ReadonlyArray<{ id: string; width: number; height: number }>,
  mode: SubViewBoardLayoutMode = 'grid',
  gap = 14,
  targetDim = DEFAULT_BOARD_CARD_TARGET_DIM
): Map<string, { boardX: number; boardY: number; boardScale: number; boardRotation: number }> {
  const result = new Map<
    string,
    { boardX: number; boardY: number; boardScale: number; boardRotation: number }
  >();
  if (items.length === 0) return result;

  const sized = items.map((it) => {
    const w = Math.max(1, it.width);
    const h = Math.max(1, it.height);
    const scale = computeNormalizedBoardScale(w, h, targetDim);
    return {
      id: it.id,
      scale,
      dw: w * scale,
      dh: h * scale,
    };
  });

  if (mode === 'row') {
    const totalW = sized.reduce((acc, s) => acc + s.dw, 0) + gap * Math.max(0, sized.length - 1);
    let cursorX = -totalW / 2;
    for (const s of sized) {
      result.set(s.id, {
        boardX: cursorX + s.dw / 2,
        boardY: 0,
        boardScale: s.scale,
        boardRotation: 0,
      });
      cursorX += s.dw + gap;
    }
    return result;
  }

  if (mode === 'column') {
    const totalH = sized.reduce((acc, s) => acc + s.dh, 0) + gap * Math.max(0, sized.length - 1);
    let cursorY = -totalH / 2;
    for (const s of sized) {
      result.set(s.id, {
        boardX: 0,
        boardY: cursorY + s.dh / 2,
        boardScale: s.scale,
        boardRotation: 0,
      });
      cursorY += s.dh + gap;
    }
    return result;
  }

  // 'grid' — neat balanced row-packed grid (PureRef style)
  const cols = Math.max(1, Math.ceil(Math.sqrt(sized.length)));
  const rows: Array<typeof sized> = [];
  for (let i = 0; i < sized.length; i += cols) {
    rows.push(sized.slice(i, i + cols));
  }

  const rowHeights = rows.map((r) => Math.max(...r.map((s) => s.dh)));
  const rowWidths = rows.map(
    (r) => r.reduce((acc, s) => acc + s.dw, 0) + gap * Math.max(0, r.length - 1)
  );
  const totalH = rowHeights.reduce((a, b) => a + b, 0) + gap * Math.max(0, rows.length - 1);

  let cursorY = -totalH / 2;
  rows.forEach((row, rIdx) => {
    const rh = rowHeights[rIdx];
    const rw = rowWidths[rIdx];
    let cursorX = -rw / 2;
    for (const s of row) {
      result.set(s.id, {
        boardX: cursorX + s.dw / 2,
        boardY: cursorY + rh / 2,
        boardScale: s.scale,
        boardRotation: 0,
      });
      cursorX += s.dw + gap;
    }
    cursorY += rh + gap;
  });

  return result;
}

/**
 * Computes initial board positions for newly added images without overlapping existing cards.
 */
export function computePlacementForNewBoardItems(
  existingCards: readonly BoardCardGeometry[],
  incoming: ReadonlyArray<{ width: number; height: number }>,
  dropBoardPoint?: BoardPoint | null,
  gap = 14
): Array<{ boardX: number; boardY: number; boardScale: number }> {
  if (incoming.length === 0) return [];

  if (existingCards.length === 0 && !dropBoardPoint) {
    const tempItems = incoming.map((it, idx) => ({ id: String(idx), width: it.width, height: it.height }));
    const layout = computeBoardAutoLayout(tempItems, 'grid', gap);
    return tempItems.map((it) => {
      const p = layout.get(it.id)!;
      return { boardX: p.boardX, boardY: p.boardY, boardScale: p.boardScale };
    });
  }

  const existingBounds = computeBoardBounds(existingCards);
  let cursorX = dropBoardPoint
    ? dropBoardPoint.x
    : existingBounds
      ? existingBounds.maxX + gap
      : 0;
  const anchorY = dropBoardPoint ? dropBoardPoint.y : existingBounds ? existingBounds.cy : 0;

  return incoming.map((it, idx) => {
    const w = Math.max(1, it.width);
    const h = Math.max(1, it.height);
    const scale = computeNormalizedBoardScale(w, h);
    const dw = w * scale;
    const bx = dropBoardPoint && idx === 0 ? cursorX : cursorX + dw / 2;
    cursorX = bx + dw / 2 + gap;
    return {
      boardX: bx,
      boardY: anchorY,
      boardScale: scale,
    };
  });
}

/**
 * Applies artist light & shape study filters in-place on an ImageData buffer:
 * - Brightness & Contrast adjustment
 * - True linear-light Rec.709 perceptual B/W luminance
 * - Value grouping / Notan posterization (2-value Notan, 3-value, 5-value)
 */
export function applyStudyFilterToImageData(
  imageData: Pick<ImageData, 'data' | 'width' | 'height'>,
  filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'brightness' | 'contrast'>,
  forceGrayscale = false
): void {
  const { data } = imageData;
  const useGray = forceGrayscale || filter.grayscale || filter.valueSteps > 0;
  const brightness = clampBrightnessContrast(filter.brightness);
  const contrast = clampBrightnessContrast(filter.contrast);
  const hasToneAdjust = brightness !== 0 || contrast !== 0;

  if (!useGray && !hasToneAdjust) return;

  // Standard contrast factor mapping [-100..100] -> [0..~4]
  const cVal = contrast * 2.55;
  const contrastFactor = contrast === 0 ? 1 : (259 * (cVal + 255)) / (255 * Math.max(1, 259 - cVal));
  const brightOffset = brightness * 1.28;
  const threshold = clampNotanThreshold(filter.notanThreshold);
  const thresholdShift = (threshold - 128) * 0.6;
  const steps = filter.valueSteps;

  for (let i = 0; i < data.length; i += 4) {
    if (data[i + 3] === 0) continue;

    let r = data[i];
    let g = data[i + 1];
    let b = data[i + 2];

    if (hasToneAdjust) {
      r = Math.max(0, Math.min(255, Math.round(contrastFactor * (r - 128) + 128 + brightOffset)));
      g = Math.max(0, Math.min(255, Math.round(contrastFactor * (g - 128) + 128 + brightOffset)));
      b = Math.max(0, Math.min(255, Math.round(contrastFactor * (b - 128) + 128 + brightOffset)));
    }

    if (useGray) {
      let lum = computePerceptualLuminanceByte(r, g, b);
      if (steps === 2) {
        // 2-Value Notan (pure shadow / light mass study)
        lum = lum >= threshold ? 248 : 16;
      } else if (steps === 3) {
        // 3-Value study (Shadow / Midtone / Light)
        const t1 = Math.max(20, Math.min(200, 85 + thresholdShift));
        const t2 = Math.max(t1 + 20, Math.min(240, 170 + thresholdShift));
        lum = lum < t1 ? 24 : lum < t2 ? 132 : 242;
      } else if (steps === 5) {
        // 5-Value study (0%, 25%, 50%, 75%, 100%)
        const shifted = Math.max(0, Math.min(255, lum - thresholdShift * 0.5));
        const bucket = Math.min(4, Math.floor((shifted / 256) * 5));
        lum = Math.round((bucket / 4) * 236 + 12);
      }
      data[i] = lum;
      data[i + 1] = lum;
      data[i + 2] = lum;
    } else {
      data[i] = r;
      data[i + 1] = g;
      data[i + 2] = b;
    }
  }
}

export function getStudyFilterSignature(
  filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'squintBlur' | 'brightness' | 'contrast'>,
  itemGrayscale = false
): string {
  const effGray = filter.grayscale || itemGrayscale;
  return `${effGray ? 1 : 0}:${filter.valueSteps}:${filter.notanThreshold}:${filter.squintBlur ? 1 : 0}:${filter.brightness}:${filter.contrast}`;
}

export function isStudyFilterVisualActive(
  filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'squintBlur' | 'brightness' | 'contrast'>,
  itemGrayscale = false
): boolean {
  return (
    filter.grayscale ||
    itemGrayscale ||
    filter.valueSteps > 0 ||
    filter.squintBlur ||
    filter.brightness !== 0 ||
    filter.contrast !== 0
  );
}

/**
 * Produces a filtered offscreen canvas from a source canvas (used for cached 60fps rendering
 * of perceptual B/W, Notan, value grouping, brightness/contrast, and squint blur).
 */
export function buildFilteredReferenceCanvas(
  sourceCanvas: HTMLCanvasElement,
  filter: Pick<SubViewStudyFilter, 'grayscale' | 'valueSteps' | 'notanThreshold' | 'squintBlur' | 'brightness' | 'contrast'>,
  itemGrayscale = false
): HTMLCanvasElement {
  if (!isStudyFilterVisualActive(filter, itemGrayscale)) {
    return sourceCanvas;
  }

  const w = Math.max(1, sourceCanvas.width);
  const h = Math.max(1, sourceCanvas.height);

  // Cap processing resolution for very large photos while preserving crisp reference detail
  const maxWorkDim = 1024;
  const downScale = Math.min(1, maxWorkDim / Math.max(w, h));
  const workW = Math.max(1, Math.round(w * downScale));
  const workH = Math.max(1, Math.round(h * downScale));

  const out = document.createElement('canvas');
  out.width = workW;
  out.height = workH;
  const ctx = out.getContext('2d', { willReadFrequently: true });
  if (!ctx) return sourceCanvas;

  if (filter.squintBlur) {
    // Fast squint-blur via multi-step downscale/upscale (works consistently across all Canvas2D engines)
    const blurScale = Math.max(0.06, Math.min(0.18, 42 / Math.max(workW, workH)));
    const smallW = Math.max(2, Math.round(workW * blurScale));
    const smallH = Math.max(2, Math.round(workH * blurScale));
    const tiny = document.createElement('canvas');
    tiny.width = smallW;
    tiny.height = smallH;
    const tCtx = tiny.getContext('2d');
    if (tCtx) {
      tCtx.imageSmoothingEnabled = true;
      tCtx.drawImage(sourceCanvas, 0, 0, smallW, smallH);
      ctx.imageSmoothingEnabled = true;
      ctx.drawImage(tiny, 0, 0, workW, workH);
    } else {
      ctx.drawImage(sourceCanvas, 0, 0, workW, workH);
    }
  } else {
    ctx.drawImage(sourceCanvas, 0, 0, workW, workH);
  }

  const needsPixelPass =
    filter.grayscale ||
    itemGrayscale ||
    filter.valueSteps > 0 ||
    filter.brightness !== 0 ||
    filter.contrast !== 0;

  if (needsPixelPass && typeof ctx.getImageData === 'function' && typeof ctx.putImageData === 'function') {
    try {
      const imgData = ctx.getImageData(0, 0, workW, workH);
      applyStudyFilterToImageData(imgData, filter, itemGrayscale);
      ctx.putImageData(imgData, 0, 0);
    } catch {
      // Guard against tainted canvas in unusual browser contexts
    }
  }

  return out;
}

/**
 * Extracts a curated dominant color palette (up to `maxColors` distinct colors) from a reference canvas.
 * Useful for instant color-key and light-study swatch extraction.
 */
export function extractDominantColorsFromCanvas(
  canvas: HTMLCanvasElement | null,
  maxColors = 7
): ExtractedSwatch[] {
  if (!canvas || canvas.width <= 0 || canvas.height <= 0) return [];
  try {
    const sampleSize = 48;
    const scale = Math.min(1, sampleSize / Math.max(canvas.width, canvas.height));
    const sw = Math.max(1, Math.round(canvas.width * scale));
    const sh = Math.max(1, Math.round(canvas.height * scale));

    const tmp = document.createElement('canvas');
    tmp.width = sw;
    tmp.height = sh;
    const tCtx = tmp.getContext('2d', { willReadFrequently: true });
    if (!tCtx) return [];
    tCtx.drawImage(canvas, 0, 0, sw, sh);
    const data = tCtx.getImageData(0, 0, sw, sh).data;

    // 4-bit-per-channel quantized bins (16x16x16 = 4096 max bins)
    const buckets = new Map<number, { rSum: number; gSum: number; bSum: number; count: number }>();
    let totalOpaque = 0;

    for (let i = 0; i < data.length; i += 4) {
      if (data[i + 3] < 128) continue;
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4);
      const existing = buckets.get(key);
      if (existing) {
        existing.rSum += r;
        existing.gSum += g;
        existing.bSum += b;
        existing.count += 1;
      } else {
        buckets.set(key, { rSum: r, gSum: g, bSum: b, count: 1 });
      }
      totalOpaque += 1;
    }

    if (totalOpaque === 0) return [];

    const sortedBuckets = Array.from(buckets.values())
      .map((b) => ({
        r: Math.round(b.rSum / b.count),
        g: Math.round(b.gSum / b.count),
        b: Math.round(b.bSum / b.count),
        count: b.count,
      }))
      .sort((a, b) => b.count - a.count);

    // Greedy perceptual-distance selection so extracted palette has distinct, useful hues & values
    const chosen: Array<{ r: number; g: number; b: number; count: number }> = [];
    const minDistSq = 38 * 38;

    for (const cand of sortedBuckets) {
      if (chosen.length >= maxColors) break;
      const tooClose = chosen.some((c) => {
        const dr = cand.r - c.r;
        const dg = cand.g - c.g;
        const db = cand.b - c.b;
        return dr * dr * 0.3 + dg * dg * 0.59 + db * db * 0.11 < minDistSq * 0.34;
      });
      if (!tooClose) {
        chosen.push(cand);
      }
    }

    // Fallback if image is nearly monochrome / flat color so we still return at least 1 swatch
    if (chosen.length === 0 && sortedBuckets.length > 0) {
      chosen.push(sortedBuckets[0]);
    }

    return chosen
      .map((c) => {
        const hex = `#${c.r.toString(16).padStart(2, '0')}${c.g.toString(16).padStart(2, '0')}${c.b.toString(16).padStart(2, '0')}`;
        const lumByte = computePerceptualLuminanceByte(c.r, c.g, c.b);
        return {
          hex,
          luminance: Math.round((lumByte / 255) * 100),
          ratio: c.count / totalOpaque,
        };
      })
      .sort((a, b) => a.luminance - b.luminance);
  } catch {
    return [];
  }
}

/**
 * Draws a crisp proportional study grid overlay inside a centered rectangle `[-w/2, -h/2, w, h]`
 * in the current transformed canvas context.
 */
export function drawProportionalGrid(
  ctx: CanvasRenderingContext2D,
  w: number,
  h: number,
  gridMode: SubViewGridMode,
  screenScale: number
): void {
  if (gridMode === 'none' || w <= 0 || h <= 0) return;

  const x0 = -w / 2;
  const y0 = -h / 2;
  const invScale = 1 / Math.max(0.05, Math.abs(screenScale));

  ctx.save();
  ctx.beginPath();

  const addLine = (ax: number, ay: number, bx: number, by: number) => {
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
  };

  if (gridMode === 'thirds') {
    for (let i = 1; i <= 2; i++) {
      addLine(x0 + (w * i) / 3, y0, x0 + (w * i) / 3, y0 + h);
      addLine(x0, y0 + (h * i) / 3, x0 + w, y0 + (h * i) / 3);
    }
  } else if (gridMode === 'grid4' || gridMode === 'grid8') {
    const div = gridMode === 'grid4' ? 4 : 8;
    for (let i = 1; i < div; i++) {
      addLine(x0 + (w * i) / div, y0, x0 + (w * i) / div, y0 + h);
      addLine(x0, y0 + (h * i) / div, x0 + w, y0 + (h * i) / div);
    }
  } else if (gridMode === 'crosshair') {
    addLine(0, y0, 0, y0 + h);
    addLine(x0, 0, x0 + w, 0);
    // Subtle diagonals for angle & center checking
    addLine(x0, y0, x0 + w, y0 + h);
    addLine(x0 + w, y0, x0, y0 + h);
  } else if (gridMode === 'golden') {
    const phiA = 0.381966;
    const phiB = 1 - phiA;
    addLine(x0 + w * phiA, y0, x0 + w * phiA, y0 + h);
    addLine(x0 + w * phiB, y0, x0 + w * phiB, y0 + h);
    addLine(x0, y0 + h * phiA, x0 + w, y0 + h * phiA);
    addLine(x0, y0 + h * phiB, x0 + w, y0 + h * phiB);
  }

  // Dual-contrast hairline (subtle dark shadow + crisp light line) so grid stays readable on both bright & dark refs
  ctx.strokeStyle = 'rgba(0, 0, 0, 0.45)';
  ctx.lineWidth = 2 * invScale;
  ctx.stroke();

  ctx.strokeStyle = 'rgba(255, 255, 255, 0.72)';
  ctx.lineWidth = 1 * invScale;
  ctx.stroke();

  ctx.restore();
}