Skip to content

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

6.3 KB
Raw Blame
/**
 * Lightweight Tauri v2 IPC bridge for `.sut` SQLite brush extraction and raw flate helpers.
 *
 * All raster operations (filters, tonal corrections, flood/smart fill, liquify, transform,
 * retouch, gradients, shapes, and tile LZ4 sync) execute directly in-process inside
 * `crates/ink-engine` via `nativeEngineBridge.ts` — zero legacy pixel-IPC commands remain!
 */

import { isTauriEnvironment } from './tauriEnv';
import { performanceManager } from './performanceManager';

type TauriInvoke = typeof import('@tauri-apps/api/core').invoke;

let cachedInvokePromise: Promise<TauriInvoke> | null = null;
const utf8Decoder = new TextDecoder('utf-8');

export function isNativeRustAvailable(): boolean {
  return isTauriEnvironment() && performanceManager.getConfig().useNativeRustAcceleration;
}

function getInvoke(): Promise<TauriInvoke> {
  if (!cachedInvokePromise) {
    cachedInvokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
  }
  return cachedInvokePromise;
}

function toUint8Array(raw: ArrayBuffer | Uint8Array | number[]): Uint8Array {
  if (raw instanceof Uint8Array) return raw;
  if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
  return new Uint8Array(raw);
}

export type CspExpressionColor = 'color' | 'gray' | 'monochrome';

export interface NativeSutMaterial {
  pwId: string;
  originalPath: string;
  catalogPath: string;
  fileData: Uint8Array;
  decodedPng?: Uint8Array;
  width?: number;
  height?: number;
  expressionColor?: CspExpressionColor;
  isPaperTexture?: boolean;
  hasSubColor?: boolean;
  decodedFromLayer?: boolean;
}

export interface NativeSutExtract {
  nodeName: string | null;
  nodeUuid?: string | null;
  variantId: number | null;
  nodeInitVariantId?: number | null;
  variantValues: Map<string, unknown>;
  dualVariantValues?: Map<string, unknown>;
  materials: NativeSutMaterial[];
}

function normalizeExpressionColor(val: unknown): CspExpressionColor | undefined {
  if (val === 'color' || val === 'gray' || val === 'monochrome') {
    return val;
  }
  return undefined;
}

export async function parseSutSqliteNative(bytes: Uint8Array): Promise<NativeSutExtract> {
  const invoke = await getInvoke();
  const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('parse_sut_sqlite', bytes);
  const wire = toUint8Array(raw);
  if (
    wire.byteLength < 8 ||
    wire[0] !== 0x53 ||
    wire[1] !== 0x55 ||
    wire[2] !== 0x54 ||
    wire[3] !== 0x44
  ) {
    throw new Error('Invalid SUTD binary response from Rust backend');
  }
  const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
  const metaLen = view.getUint32(4, true);
  if (8 + metaLen > wire.byteLength) {
    throw new Error('Truncated SUTD metadata header');
  }
  const meta = JSON.parse(utf8Decoder.decode(wire.subarray(8, 8 + metaLen))) as {
    nodeName: string | null;
    nodeUuid?: string | null;
    variantId: number | null;
    nodeInitVariantId?: number | null;
    variantScalars: Record<string, unknown>;
    variantBlobs: Record<string, { offset: number; len: number }>;
    dualVariantScalars?: Record<string, unknown>;
    dualVariantBlobs?: Record<string, { offset: number; len: number }>;
    materials: Array<{
      pwId: string;
      originalPath: string;
      catalogPath: string;
      fileDataOffset: number;
      fileDataLen: number;
      decodedPngOffset?: number;
      decodedPngLen?: number;
      width?: number;
      height?: number;
      expressionColor?: string;
      isPaperTexture?: boolean;
      hasSubColor?: boolean;
      decodedFromLayer?: boolean;
    }>;
  };
  const blobs = wire.subarray(8 + metaLen);
  const variantValues = new Map<string, unknown>();
  for (const [k, v] of Object.entries(meta.variantScalars)) {
    variantValues.set(k.toLowerCase(), v);
  }
  for (const [k, ref] of Object.entries(meta.variantBlobs)) {
    variantValues.set(k.toLowerCase(), blobs.subarray(ref.offset, ref.offset + ref.len));
  }

  let dualVariantValues: Map<string, unknown> | undefined = undefined;
  if (meta.dualVariantScalars || meta.dualVariantBlobs) {
    const dualMap = new Map<string, unknown>();
    if (meta.dualVariantScalars) {
      for (const [k, v] of Object.entries(meta.dualVariantScalars)) {
        dualMap.set(k.toLowerCase(), v);
      }
    }
    if (meta.dualVariantBlobs) {
      for (const [k, ref] of Object.entries(meta.dualVariantBlobs)) {
        dualMap.set(k.toLowerCase(), blobs.subarray(ref.offset, ref.offset + ref.len));
      }
    }
    if (dualMap.size > 0) {
      dualVariantValues = dualMap;
    }
  }

  const materials: NativeSutMaterial[] = meta.materials.map((m) => ({
    pwId: m.pwId,
    originalPath: m.originalPath,
    catalogPath: m.catalogPath,
    fileData: blobs.subarray(m.fileDataOffset, m.fileDataOffset + m.fileDataLen),
    decodedPng:
      typeof m.decodedPngOffset === 'number' &&
      typeof m.decodedPngLen === 'number' &&
      m.decodedPngLen > 0
        ? blobs.subarray(m.decodedPngOffset, m.decodedPngOffset + m.decodedPngLen)
        : undefined,
    width: m.width,
    height: m.height,
    expressionColor: normalizeExpressionColor(m.expressionColor),
    isPaperTexture: m.isPaperTexture,
    hasSubColor: m.hasSubColor,
    decodedFromLayer: m.decodedFromLayer,
  }));
  return {
    nodeName: meta.nodeName,
    nodeUuid: meta.nodeUuid ?? null,
    variantId: meta.variantId,
    nodeInitVariantId: meta.nodeInitVariantId ?? null,
    variantValues,
    dualVariantValues,
    materials,
  };
}

export async function flateCompressNative(
  op: 'deflate' | 'zlib',
  data: Uint8Array,
  level: number = 1
): Promise<Uint8Array> {
  const invoke = await getInvoke();
  const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_flate_compress', data, {
    headers: {
      'x-op': op,
      'x-level': String(level),
    },
  });
  return toUint8Array(raw);
}

export async function flateDecompressNative(
  op: 'inflate' | 'unzlib',
  data: Uint8Array,
  maxOutputBytes?: number
): Promise<Uint8Array> {
  const invoke = await getInvoke();
  const headers: Record<string, string> = { 'x-op': op };
  if (typeof maxOutputBytes === 'number' && maxOutputBytes > 0) {
    headers['x-max-output-bytes'] = String(Math.floor(maxOutputBytes));
  }
  const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('native_flate_decompress', data, {
    headers,
  });
  return toUint8Array(raw);
}