Skip to content

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

17.3 KB
Raw Blame
import { zipSync } from 'fflate';
import { AnimationTimeline, OnionSkinSettings, LayerItem } from '../types/editor';
import { saveFileWithDialog, SaveFileDialogResult } from './fileSaveDialog';
import {
  exportNativeDocumentImage,
  flattenNativeDocument,
} from './nativeEngineBridge';

export interface OnionSkinFrameInfo {
  frame: number;
  layerId: string;
  tint: string;
  opacity: number;
  direction: 'prev' | 'next';
}

/**
 * Creates default animation timeline settings.
 */
export function createDefaultAnimationTimeline(initialLayers: LayerItem[] = []): AnimationTimeline {
  const cels: Record<number, string> = {};

  const firstRaster = initialLayers.find((l) => l.type === 'raster');
  if (firstRaster) {
    cels[0] = firstRaster.id;
  }

  const defaultOnionSkin: OnionSkinSettings = {
    enabled: true,
    prevFrames: 2,
    nextFrames: 2,
    prevTint: '#00bcd4',
    nextTint: '#ec4899',
    opacity: 0.35,
  };

  return {
    fps: 12,
    totalFrames: 24,
    currentFrame: 0,
    cels,
    onionSkin: defaultOnionSkin,
    isPlaying: false,
    loop: true,
  };
}

export function getFrameCelLayerId(timeline: AnimationTimeline, frame: number): string | null {
  return timeline.cels[frame] ?? null;
}

export function setFrameCel(
  timeline: AnimationTimeline,
  frame: number,
  layerId: string
): AnimationTimeline {
  return {
    ...timeline,
    cels: {
      ...timeline.cels,
      [frame]: layerId,
    },
  };
}

export function removeFrameCel(
  timeline: AnimationTimeline,
  frame: number
): AnimationTimeline {
  const newCels = { ...timeline.cels };
  delete newCels[frame];
  return {
    ...timeline,
    cels: newCels,
  };
}

/**
 * Calculates prior and upcoming onion skin frames with progressive opacity falloff.
 */
export function getOnionSkinFrames(timeline: AnimationTimeline): OnionSkinFrameInfo[] {
  const { onionSkin, currentFrame, cels } = timeline;
  if (!onionSkin || !onionSkin.enabled) return [];

  const frames: OnionSkinFrameInfo[] = [];

  const prevCount = Math.max(1, onionSkin.prevFrames || 2);
  for (let step = 1; step <= prevCount; step++) {
    const f = currentFrame - step;
    if (f >= 0 && cels[f]) {
      const falloff = 1 - (step - 1) / prevCount;
      frames.push({
        frame: f,
        layerId: cels[f],
        tint: onionSkin.prevTint || '#00bcd4',
        opacity: Math.max(0.05, onionSkin.opacity * falloff),
        direction: 'prev',
      });
    }
  }

  const nextCount = Math.max(1, onionSkin.nextFrames || 2);
  for (let step = 1; step <= nextCount; step++) {
    const f = currentFrame + step;
    if (f < timeline.totalFrames && cels[f]) {
      const falloff = 1 - (step - 1) / nextCount;
      frames.push({
        frame: f,
        layerId: cels[f],
        tint: onionSkin.nextTint || '#ec4899',
        opacity: Math.max(0.05, onionSkin.opacity * falloff),
        direction: 'next',
      });
    }
  }

  return frames;
}

/**
 * Builds per-layer visibility overrides so only the active frame's cel is visible during export.
 */
export function buildCelVisibilityOverrides(
  timeline: AnimationTimeline,
  frameIndex: number
): Record<string, boolean> {
  const overrides: Record<string, boolean> = {};
  const activeCelId = timeline.cels[frameIndex];
  for (const celLayerId of Object.values(timeline.cels)) {
    if (celLayerId) {
      overrides[celLayerId] = celLayerId === activeCelId;
    }
  }
  return overrides;
}

export async function saveAnimationBlob(
  blob: Blob,
  filename: string
): Promise<SaveFileDialogResult> {
  const dotIdx = filename.lastIndexOf('.');
  const ext = dotIdx >= 0 ? filename.slice(dotIdx).toLowerCase() : '.gif';
  const description =
    ext === '.gif'
      ? 'GIF Animation'
      : ext === '.png'
        ? 'Animated PNG (APNG)'
        : ext === '.mp4'
          ? 'MP4 Video'
          : ext === '.webm'
            ? 'WebM Video'
            : ext === '.zip'
              ? 'PNG Sequence Archive'
              : 'Animation File';

  return saveFileWithDialog({
    data: blob,
    suggestedName: filename,
    mimeType: blob.type || 'application/octet-stream',
    description,
    extensions: [ext],
    category: 'animation',
    title: 'Save Animation As',
  });
}

export function downloadBlob(blob: Blob, filename: string): void {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

/**
 * Zero-canvas Export Pipeline: renders each frame directly via Rust DX12 compositor into PNG bytes and zips them.
 */
export async function exportAnimationToPngZip(
  timeline: AnimationTimeline,
  _layers: LayerItem[],
  _dimensions: { width: number; height: number },
  onProgress?: (current: number, total: number) => void,
  docId?: string | null
): Promise<Blob> {
  const files: Record<string, Uint8Array> = {};
  const total = timeline.totalFrames;

  for (let f = 0; f < total; f++) {
    onProgress?.(f + 1, total);
    const pngBytes = await exportNativeDocumentImage({
      docId: docId ?? null,
      format: 'png',
      options: {
        celVisibilityOverrides: buildCelVisibilityOverrides(timeline, f),
      },
    });
    if (!pngBytes) {
      throw new Error('Native animation export requires the Windows desktop Rust engine.');
    }
    const pad = String(f + 1).padStart(4, '0');
    files[`frame_${pad}.png`] = pngBytes;
  }

  const zipped = zipSync(files, { level: 6 });
  return new Blob([zipped as BlobPart], { type: 'application/zip' });
}

/**
 * Export Pipeline: renders downscaled animation frames on Rust DX12 and encodes WebM/MP4 via MediaRecorder.
 */
export async function exportAnimationToVideo(
  timeline: AnimationTimeline,
  _layers: LayerItem[],
  dimensions: { width: number; height: number },
  onProgress?: (current: number, total: number) => void,
  docId?: string | null
): Promise<Blob> {
  const { fps, totalFrames } = timeline;
  const safeFps = Math.max(1, Number.isFinite(fps) ? fps : 12);
  const safeTotalFrames = Math.max(0, Number.isFinite(totalFrames) ? Math.floor(totalFrames) : 0);
  const maxDim = Math.min(1920, Math.max(1, dimensions.width, dimensions.height));
  const scale = Math.min(1, maxDim / Math.max(1, dimensions.width, dimensions.height));
  const targetW = Math.max(2, Math.round(dimensions.width * scale));
  const targetH = Math.max(2, Math.round(dimensions.height * scale));

  const canvas = document.createElement('canvas');
  canvas.width = targetW;
  canvas.height = targetH;
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('Failed to create 2D context for animation video export.');
  }
  const stream = canvas.captureStream(safeFps);

  const preferredTypes = [
    'video/webm;codecs=vp9',
    'video/webm;codecs=vp8',
    'video/webm',
    'video/mp4',
  ];
  const mimeType = preferredTypes.find((t) => MediaRecorder.isTypeSupported(t)) || 'video/webm';

  const recorder = new MediaRecorder(stream, {
    mimeType,
    videoBitsPerSecond: 8000000,
  });

  const chunks: Blob[] = [];
  recorder.ondataavailable = (e) => {
    if (e.data && e.data.size > 0) chunks.push(e.data);
  };

  const delayMs = 1000 / safeFps;

  return new Promise<Blob>((resolve, reject) => {
    let settled = false;
    const cleanupResources = () => {
      stream.getTracks().forEach((t) => {
        try {
          t.stop();
        } catch {
          // Ignore track stop errors
        }
      });
      canvas.width = 0;
      canvas.height = 0;
    };

    recorder.onstop = () => {
      cleanupResources();
      if (!settled) {
        settled = true;
        resolve(new Blob(chunks, { type: mimeType }));
      }
    };
    recorder.onerror = (e) => {
      cleanupResources();
      if (!settled) {
        settled = true;
        reject(e);
      }
    };

    recorder.start();

    let frame = 0;
    const renderNext = async () => {
      try {
        if (frame >= safeTotalFrames) {
          if (recorder.state !== 'inactive') {
            recorder.stop();
          }
          return;
        }

        onProgress?.(frame + 1, safeTotalFrames);
        const flat = await flattenNativeDocument(docId ?? null, {
          maxDim,
          celVisibilityOverrides: buildCelVisibilityOverrides(timeline, frame),
        });
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        if (flat) {
          if (canvas.width !== flat.width) canvas.width = flat.width;
          if (canvas.height !== flat.height) canvas.height = flat.height;
          ctx.putImageData(new ImageData(flat.rgba, flat.width, flat.height), 0, 0);
        }

        frame++;
        setTimeout(() => void renderNext(), delayMs);
      } catch (err) {
        try {
          if (recorder.state !== 'inactive') {
            recorder.stop();
          }
        } catch {
          // Ignore stop errors after failure
        }
        cleanupResources();
        if (!settled) {
          settled = true;
          reject(err);
        }
      }
    };

    void renderNext();
  });
}

/**
 * Zero-canvas Animated GIF89a Encoder consuming downscaled RGBA8 frames straight from Rust DX12.
 */
export async function exportAnimationToGif(
  timeline: AnimationTimeline,
  _layers: LayerItem[],
  dimensions: { width: number; height: number },
  onProgress?: (current: number, total: number) => void,
  docId?: string | null
): Promise<Blob> {
  const { fps, totalFrames } = timeline;
  const maxDim = Math.min(1280, Math.max(dimensions.width, dimensions.height));
  const delayCentisecs = Math.max(2, Math.round(100 / fps));

  const renderedFrames: Array<{ width: number; height: number; rgba: Uint8ClampedArray }> = [];
  for (let f = 0; f < totalFrames; f++) {
    onProgress?.(f + 1, totalFrames);
    const flat = await flattenNativeDocument(docId ?? null, {
      maxDim,
      celVisibilityOverrides: buildCelVisibilityOverrides(timeline, f),
    });
    if (!flat) {
      throw new Error('Native GIF export requires the Windows desktop Rust engine.');
    }
    renderedFrames.push(flat);
  }

  const width = renderedFrames[0]?.width ?? Math.min(1280, dimensions.width);
  const height = renderedFrames[0]?.height ?? Math.round((width / Math.max(1, dimensions.width)) * dimensions.height);
  const buffer: number[] = [];

  for (const c of 'GIF89a') buffer.push(c.charCodeAt(0));
  buffer.push(width & 0xff, (width >> 8) & 0xff);
  buffer.push(height & 0xff, (height >> 8) & 0xff);
  buffer.push(0x70, 0x00, 0x00);

  buffer.push(0x21, 0xff, 0x0b);
  for (const c of 'NETSCAPE2.0') buffer.push(c.charCodeAt(0));
  buffer.push(0x03, 0x01, 0x00, 0x00, 0x00);

  for (const frame of renderedFrames) {
    const pixels = frame.rgba;
    const palette: number[][] = [];
    const colorMap = new Map<number, number>();
    const indexedPixels = new Uint8Array(width * height);

    for (let i = 0; i < width * height; i++) {
      const r = pixels[i * 4] & 0xe0;
      const g = pixels[i * 4 + 1] & 0xe0;
      const b = pixels[i * 4 + 2] & 0xc0;
      const a = pixels[i * 4 + 3];

      if (a < 128) {
        indexedPixels[i] = 0;
        continue;
      }

      const key = (r << 16) | (g << 8) | b;
      let colorIdx = colorMap.get(key);
      if (colorIdx === undefined) {
        if (palette.length < 127) {
          colorIdx = palette.length + 1;
          palette.push([r, g, b]);
          colorMap.set(key, colorIdx);
        } else {
          colorIdx = 1;
        }
      }
      indexedPixels[i] = colorIdx;
    }

    buffer.push(0x21, 0xf9, 0x04, 0x09);
    buffer.push(delayCentisecs & 0xff, (delayCentisecs >> 8) & 0xff);
    buffer.push(0x00, 0x00);

    buffer.push(0x2c, 0x00, 0x00, 0x00, 0x00);
    buffer.push(width & 0xff, (width >> 8) & 0xff);
    buffer.push(height & 0xff, (height >> 8) & 0xff);
    buffer.push(0x86);

    buffer.push(0, 0, 0);
    for (let i = 0; i < 127; i++) {
      if (i < palette.length) {
        buffer.push(palette[i][0], palette[i][1], palette[i][2]);
      } else {
        buffer.push(0, 0, 0);
      }
    }

    const minCodeSize = 7;
    buffer.push(minCodeSize);

    let offset = 0;
    while (offset < indexedPixels.length) {
      const blockSize = Math.min(125, indexedPixels.length - offset);
      buffer.push(blockSize + 1);
      buffer.push(1 << minCodeSize);
      for (let j = 0; j < blockSize; j++) {
        buffer.push(indexedPixels[offset + j]);
      }
      offset += blockSize;
    }
    buffer.push(0x01, (1 << minCodeSize) + 1);
    buffer.push(0x00);
  }

  buffer.push(0x3b);
  return new Blob([new Uint8Array(buffer)], { type: 'image/gif' });
}

/**
 * Zero-canvas Animated PNG (APNG) exporter consuming PNG frames straight from Rust DX12.
 */
export async function exportAnimationToApng(
  timeline: AnimationTimeline,
  _layers: LayerItem[],
  dimensions: { width: number; height: number },
  onProgress?: (current: number, total: number) => void,
  docId?: string | null
): Promise<Blob> {
  const { fps, totalFrames } = timeline;
  const safeFps = Math.max(1, Number.isFinite(fps) ? fps : 12);
  const numFrames = Math.max(0, Number.isFinite(totalFrames) ? Math.floor(totalFrames) : 0);
  if (numFrames === 0) {
    throw new Error('Cannot export an APNG with 0 frames.');
  }

  const framePngBuffers: Uint8Array[] = [];
  for (let f = 0; f < numFrames; f++) {
    onProgress?.(f + 1, numFrames);
    const pngBytes = await exportNativeDocumentImage({
      docId: docId ?? null,
      format: 'png',
      options: {
        celVisibilityOverrides: buildCelVisibilityOverrides(timeline, f),
      },
    });
    if (!pngBytes) {
      throw new Error('Native APNG export requires the Windows desktop Rust engine.');
    }
    framePngBuffers.push(pngBytes);
  }

  const crcTable = new Uint32Array(256);
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    crcTable[n] = c;
  }
  const computeCrc = (type: string, data: Uint8Array): number => {
    let crc = 0xffffffff;
    for (let i = 0; i < 4; i++) crc = crcTable[(crc ^ type.charCodeAt(i)) & 0xff] ^ (crc >>> 8);
    for (let i = 0; i < data.length; i++) crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
    return (crc ^ 0xffffffff) >>> 0;
  };

  const createChunk = (type: string, data: Uint8Array): Uint8Array => {
    const chunk = new Uint8Array(4 + 4 + data.length + 4);
    const dv = new DataView(chunk.buffer);
    dv.setUint32(0, data.length);
    for (let i = 0; i < 4; i++) chunk[4 + i] = type.charCodeAt(i);
    chunk.set(data, 8);
    dv.setUint32(8 + data.length, computeCrc(type, data));
    return chunk;
  };

  const f0 = framePngBuffers[0];
  let offset = 8;
  let ihdrChunk: Uint8Array | null = null;
  const idatChunks: Uint8Array[] = [];

  while (offset < f0.length) {
    const len = new DataView(f0.buffer, f0.byteOffset + offset, 4).getUint32(0);
    const type = String.fromCharCode(...f0.slice(offset + 4, offset + 8));
    const fullLen = 8 + len + 4;
    const chunkData = f0.slice(offset, offset + fullLen);

    if (type === 'IHDR') ihdrChunk = chunkData;
    else if (type === 'IDAT') idatChunks.push(f0.slice(offset + 8, offset + 8 + len));
    offset += fullLen;
  }

  const outChunks: Uint8Array[] = [];
  outChunks.push(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
  if (ihdrChunk) outChunks.push(ihdrChunk);

  const actlData = new Uint8Array(8);
  const actlDv = new DataView(actlData.buffer);
  actlDv.setUint32(0, numFrames);
  actlDv.setUint32(4, timeline.loop === false ? 1 : 0);
  outChunks.push(createChunk('acTL', actlData));

  let seq = 0;

  const fctl0 = new Uint8Array(26);
  const fctl0Dv = new DataView(fctl0.buffer);
  fctl0Dv.setUint32(0, seq++);
  fctl0Dv.setUint32(4, dimensions.width);
  fctl0Dv.setUint32(8, dimensions.height);
  fctl0Dv.setUint32(12, 0);
  fctl0Dv.setUint32(16, 0);
  fctl0Dv.setUint16(20, 1);
  fctl0Dv.setUint16(22, safeFps);
  fctl0Dv.setUint8(24, 0);
  fctl0Dv.setUint8(25, 0);
  outChunks.push(createChunk('fcTL', fctl0));

  for (const idat of idatChunks) {
    outChunks.push(createChunk('IDAT', idat));
  }

  for (let f = 1; f < numFrames; f++) {
    const fnBytes = framePngBuffers[f];
    let fOffset = 8;
    const fnIdats: Uint8Array[] = [];

    while (fOffset < fnBytes.length) {
      const len = new DataView(fnBytes.buffer, fnBytes.byteOffset + fOffset, 4).getUint32(0);
      const type = String.fromCharCode(...fnBytes.slice(fOffset + 4, fOffset + 8));
      if (type === 'IDAT') {
        fnIdats.push(fnBytes.slice(fOffset + 8, fOffset + 8 + len));
      }
      fOffset += 8 + len + 4;
    }

    const fctl = new Uint8Array(26);
    const fctlDv = new DataView(fctl.buffer);
    fctlDv.setUint32(0, seq++);
    fctlDv.setUint32(4, dimensions.width);
    fctlDv.setUint32(8, dimensions.height);
    fctlDv.setUint32(12, 0);
    fctlDv.setUint32(16, 0);
    fctlDv.setUint16(20, 1);
    fctlDv.setUint16(22, safeFps);
    fctlDv.setUint8(24, 0);
    fctlDv.setUint8(25, 0);
    outChunks.push(createChunk('fcTL', fctl));

    for (const idat of fnIdats) {
      const fdat = new Uint8Array(4 + idat.length);
      new DataView(fdat.buffer).setUint32(0, seq++);
      fdat.set(idat, 4);
      outChunks.push(createChunk('fdAT', fdat));
    }
  }

  outChunks.push(createChunk('IEND', new Uint8Array(0)));

  const totalLen = outChunks.reduce((acc, c) => acc + c.length, 0);
  const apngBytes = new Uint8Array(totalLen);
  let p = 0;
  for (const c of outChunks) {
    apngBytes.set(c, p);
    p += c.length;
  }

  return new Blob([apngBytes], { type: 'image/png' });
}