Skip to content

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

11.2 KB
Raw Blame
import { Point, CanvasDimensions, BlendMode } from '../types/editor';
import { evaluateFastSpline } from './brushMath';
import { getActiveCssZoom } from './interfaceScale';

export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {
  alpha: true,
  desynchronized: false,
  willReadFrequently: true,
};

export const CANVAS_2D_GPU_OPTIONS: CanvasRenderingContext2DSettings = {
  alpha: true,
  desynchronized: false,
  willReadFrequently: false,
};

export function get2DContext(
  canvas: HTMLCanvasElement,
  options: CanvasRenderingContext2DSettings = CANVAS_2D_CONTEXT_OPTIONS
): CanvasRenderingContext2D | null {
  return canvas.getContext('2d', options);
}

export function getGpu2DContext(
  canvas: HTMLCanvasElement
): CanvasRenderingContext2D | null {
  return canvas.getContext('2d', CANVAS_2D_GPU_OPTIONS);
}

/**
 * Calculates stroke width based on base brush size, pressure, pressure curve, and minimum size ratio.
 * Follows Clip Studio Paint's exact dynamics calculation using O(1) LUT splines.
 */
export function calculateStrokeWidth(
  baseSize: number,
  pressure: number,
  minSizeFactor: number,
  usePressure: boolean,
  pointerType: string,
  pressureCurveGamma: number = 1.0,
  velocityScale: number = 1.0,
  pressureCurve?: [number, number][]
): number {
  if (!usePressure) {
    return Math.max(0.2, baseSize * velocityScale);
  }

  let effectivePressure = pressure;
  if (pointerType === 'mouse') {
    effectivePressure = 0.5;
  } else {
    if (Number.isNaN(effectivePressure) || effectivePressure === undefined) {
      effectivePressure = 0;
    }
    effectivePressure = Math.max(0, Math.min(1.0, effectivePressure));
  }

  let curvePressure = effectivePressure;
  if (pressureCurve && pressureCurve.length > 0) {
    curvePressure = evaluateFastSpline(effectivePressure, pressureCurve);
  } else if (pressureCurveGamma !== 1.0) {
    curvePressure = Math.pow(Math.max(0, effectivePressure), pressureCurveGamma);
  }

  const minRatio = Math.max(0, Math.min(1.0, minSizeFactor ?? 0));
  const dynamicWidth = baseSize * (minRatio + (1.0 - minRatio) * curvePressure) * velocityScale;
  const contactFloor =
    effectivePressure > 0.005 ? Math.min(baseSize, Math.max(0.35, baseSize * minRatio)) : 0.1;
  return Math.max(contactFloor, dynamicWidth);
}

/**
 * Computes midpoint between two points.
 */
export function getMidPoint(p1: Point, p2: Point): Point {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2,
    pressure: (p1.pressure + p2.pressure) / 2,
    width: (p1.width + p2.width) / 2,
  };
}

export const BLEND_MODES: { value: BlendMode; label: string }[] = [
  { value: 'pass-through', label: 'Pass Through' },
  { value: 'normal', label: 'Normal' },
  { value: 'darken', label: 'Darken' },
  { value: 'multiply', label: 'Multiply' },
  { value: 'color-burn', label: 'Color Burn' },
  { value: 'linear-burn', label: 'Linear Burn' },
  { value: 'darker-color', label: 'Darker Color' },
  { value: 'lighten', label: 'Lighten' },
  { value: 'screen', label: 'Screen' },
  { value: 'color-dodge', label: 'Color Dodge' },
  { value: 'color-dodge-glow', label: 'Glow Dodge' },
  { value: 'add-glow', label: 'Add (Glow)' },
  { value: 'lighter-color', label: 'Lighter Color' },
  { value: 'overlay', label: 'Overlay' },
  { value: 'soft-light', label: 'Soft Light' },
  { value: 'hard-light', label: 'Hard Light' },
  { value: 'vivid-light', label: 'Vivid Light' },
  { value: 'linear-light', label: 'Linear Light' },
  { value: 'pin-light', label: 'Pin Light' },
  { value: 'hard-mix', label: 'Hard Mix' },
  { value: 'difference', label: 'Difference' },
  { value: 'exclusion', label: 'Exclusion' },
  { value: 'subtract', label: 'Subtract' },
  { value: 'divide', label: 'Divide' },
  { value: 'hue', label: 'Hue' },
  { value: 'saturation', label: 'Saturation' },
  { value: 'color', label: 'Color' },
  { value: 'luminosity', label: 'Luminosity' },
];

export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalCompositeOperation {
  switch (blendMode) {
    case 'pass-through':
    case 'normal':
      return 'source-over';
    case 'multiply':
      return 'multiply';
    case 'screen':
      return 'screen';
    case 'overlay':
      return 'overlay';
    case 'darken':
    case 'darker-color':
      return 'darken';
    case 'lighten':
    case 'lighter-color':
      return 'lighten';
    case 'color-dodge':
    case 'color-dodge-glow':
      return 'color-dodge';
    case 'color-burn':
    case 'linear-burn':
      return 'color-burn';
    case 'add-glow':
      return 'lighter';
    case 'hard-light':
    case 'vivid-light':
    case 'linear-light':
    case 'pin-light':
    case 'hard-mix':
      return 'hard-light';
    case 'soft-light':
      return 'soft-light';
    case 'difference':
    case 'subtract':
    case 'divide':
      return 'difference';
    case 'exclusion':
      return 'exclusion';
    case 'hue':
      return 'hue';
    case 'saturation':
      return 'saturation';
    case 'color':
      return 'color';
    case 'luminosity':
      return 'luminosity';
    default:
      return 'source-over';
  }
}

export function formatTime(timestamp: number | Date = Date.now()): string {
  const d = typeof timestamp === 'number' ? new Date(timestamp) : timestamp;
  const pad = (n: number) => n.toString().padStart(2, '0');
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

export function screenToCanvasInto(
  clientX: number,
  clientY: number,
  viewportRect: DOMRect,
  pan: { x: number; y: number },
  zoom: number,
  rotation: number,
  dimensions: CanvasDimensions,
  out: { x: number; y: number },
  flipX: boolean = false,
  flipY: boolean = false
): void {
  const cssZoom = getActiveCssZoom();
  const vx = (clientX - viewportRect.left) / cssZoom;
  const vy = (clientY - viewportRect.top) / cssZoom;

  const rx = vx - pan.x;
  const ry = vy - pan.y;

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

  const unrotX = rx * cos + ry * sin;
  const unrotY = -rx * sin + ry * cos;

  const fx = flipX ? -1 : 1;
  const fy = flipY ? -1 : 1;

  out.x = dimensions.width / 2 + (fx * unrotX) / zoom;
  out.y = dimensions.height / 2 + (fy * unrotY) / zoom;
}

export function screenToCanvas(
  clientX: number,
  clientY: number,
  viewportRect: DOMRect,
  pan: { x: number; y: number },
  zoom: number,
  rotation: number,
  dimensions: CanvasDimensions,
  flipX: boolean = false,
  flipY: boolean = false
): { x: number; y: number } {
  const out = { x: 0, y: 0 };
  screenToCanvasInto(clientX, clientY, viewportRect, pan, zoom, rotation, dimensions, out, flipX, flipY);
  return out;
}

export const clientToDocument = screenToCanvas;

export function canvasToScreen(
  canvasX: number,
  canvasY: number,
  pan: { x: number; y: number },
  zoom: number,
  rotation: number,
  dimensions: CanvasDimensions,
  flipX: boolean = false,
  flipY: boolean = false
): { x: number; y: number } {
  const fx = flipX ? -1 : 1;
  const fy = flipY ? -1 : 1;

  const dx = (canvasX - dimensions.width / 2) * fx;
  const dy = (canvasY - dimensions.height / 2) * fy;

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

  const rx = zoom * (dx * cos - dy * sin);
  const ry = zoom * (dx * sin + dy * cos);

  return {
    x: pan.x + rx,
    y: pan.y + ry,
  };
}

export function formatRotationDegrees(degrees: number): string {
  let normalized = degrees % 360;
  if (normalized > 180) normalized -= 360;
  if (normalized <= -180) normalized += 360;

  const rounded = Math.round(normalized * 10) / 10;
  const finalVal = Math.abs(rounded) < 0.05 ? 0 : rounded;
  return `${finalVal % 1 === 0 ? finalVal.toFixed(0) : finalVal.toFixed(1)}°`;
}

export interface CanvasTransformMatrix {
  a: number;
  b: number;
  c: number;
  d: number;
  e: number;
  f: number;
}

export function getCanvasToViewportMatrix(
  pan: { x: number; y: number },
  zoom: number,
  rotation: number,
  dimensions: CanvasDimensions,
  scaleX: number = 1,
  scaleY: number = scaleX,
  flipX: boolean = false,
  flipY: boolean = false
): CanvasTransformMatrix {
  const rad = (rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);

  const cx = dimensions.width / 2;
  const cy = dimensions.height / 2;
  const sx = (flipX ? -1 : 1) * zoom;
  const sy = (flipY ? -1 : 1) * zoom;

  const a = scaleX * sx * cos;
  const b = scaleY * sx * sin;
  const c = -scaleX * sy * sin;
  const d = scaleY * sy * cos;
  const e = scaleX * (pan.x - sx * cx * cos + sy * cy * sin);
  const f = scaleY * (pan.y - sx * cx * sin - sy * cy * cos);

  return { a, b, c, d, e, f };
}

export function getVisibleCanvasBounds(
  viewportRect: DOMRect,
  pan: { x: number; y: number },
  zoom: number,
  rotation: number,
  dimensions: CanvasDimensions,
  margin: number = 64,
  flipX: boolean = false,
  flipY: boolean = false
): { minX: number; minY: number; maxX: number; maxY: number } {
  const c1 = screenToCanvas(viewportRect.left, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
  const c2 = screenToCanvas(viewportRect.right, viewportRect.top, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
  const c3 = screenToCanvas(viewportRect.right, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);
  const c4 = screenToCanvas(viewportRect.left, viewportRect.bottom, viewportRect, pan, zoom, rotation, dimensions, flipX, flipY);

  const rawMinX = Math.min(c1.x, c2.x, c3.x, c4.x) - margin;
  const rawMinY = Math.min(c1.y, c2.y, c3.y, c4.y) - margin;
  const rawMaxX = Math.max(c1.x, c2.x, c3.x, c4.x) + margin;
  const rawMaxY = Math.max(c1.y, c2.y, c3.y, c4.y) + margin;

  return {
    minX: Math.max(0, Math.floor(rawMinX)),
    minY: Math.max(0, Math.floor(rawMinY)),
    maxX: Math.min(dimensions.width, Math.ceil(rawMaxX)),
    maxY: Math.min(dimensions.height, Math.ceil(rawMaxY)),
  };
}

export function applyParametricTaper(
  points: Point[],
  options?: {
    useIn?: boolean;
    useOut?: boolean;
    inCount?: number;
    outCount?: number;
    minSizeFactor?: number;
    exitSpeed?: number;
  }
): Point[] {
  if (points.length < 2) return points;

  const minRatio = Math.max(0.01, Math.min(1.0, options?.minSizeFactor ?? 0.05));
  const n = points.length;

  if (options?.useIn) {
    const inCount = Math.min(Math.floor(n / 2), options.inCount ?? Math.min(8, n));
    for (let i = 0; i < inCount; i++) {
      const u = (i + 1) / (inCount + 1);
      const taper = Math.sin((u * Math.PI) / 2);
      const factor = minRatio + (1.0 - minRatio) * taper;
      points[i].width *= factor;
      points[i].pressure *= factor;
    }
  }

  const useOut = options?.useOut ?? true;
  if (useOut) {
    let outCount = options?.outCount ?? 6;
    if (options?.exitSpeed && options.exitSpeed > 0.8) {
      outCount = Math.min(Math.floor(n / 2), Math.round(outCount * Math.min(2.5, options.exitSpeed)));
    }
    outCount = Math.min(Math.floor(n / 2), Math.max(2, outCount));
    const startIdx = n - outCount;
    for (let i = startIdx; i < n; i++) {
      const step = n - 1 - i;
      const u = (step + 1) / (outCount + 1);
      const taper = Math.sin((u * Math.PI) / 2);
      const factor = minRatio + (1.0 - minRatio) * taper;
      points[i].width *= factor;
      points[i].pressure *= factor;
    }
  }

  return points;
}