Skip to content

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

9.3 KB
Raw Blame
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  AnimationTimeline as AnimationTimelineType,
  CanvasColorMode,
  CanvasDimensions,
  LayerItem,
  SoftProofSettings,
} from '../../types/editor';
import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { computeTipStampDimensions } from '../../utils/brushMath';
import { getOnionSkinFrames } from '../../utils/animationEngine';
import {
  RuntimePerformanceConfig,
  performanceManager,
} from '../../utils/performanceManager';
import {
  NativeEngineDiagnostics,
  flushNativeGpuPool,
  getNativeDiagnostics,
  parseCssColorToRgba,
  setNativeDisplayConfig,
  subscribeNativeDiagnostics,
} from '../../utils/nativeEngineBridge';
import { useUiStore } from '../../stores';
import {
  computeEffectiveCursorAngleDeg,
  CursorConfig,
  formatArtboardTransform,
  formatCursorRingTransform,
} from './types';

export interface UseCompositorViewportParams {
  viewportRef: React.RefObject<HTMLDivElement | null>;
  onViewportReady?: (viewport: HTMLDivElement) => void;
  artboardRef: React.RefObject<HTMLDivElement | null>;
  cursorRingRef: React.RefObject<HTMLDivElement | null>;
  cursorConfigRef: React.MutableRefObject<CursorConfig>;
  lastPointerPosRef: React.MutableRefObject<{ x: number; y: number } | null>;
  navigation?: CanvasNavigationHandle;
  layers: LayerItem[];
  animationTimeline: AnimationTimelineType | null;
  pan: { x: number; y: number };
  zoom: number;
  rotation: number;
  flipX: boolean;
  flipY: boolean;
  livePan: { x: number; y: number };
  liveZoom: number;
  liveRotation: number;
  liveFlipX: boolean;
  liveFlipY: boolean;
  dimensions: CanvasDimensions;
  showCheckerboard: boolean;
  hasOpenDocument: boolean;
  softProofSettings?: SoftProofSettings;
  valueCheckEnabled?: boolean;
  activeLayerId?: string;
  brushOpacity?: number;
  colorMode: CanvasColorMode;
  nativeCanvasActive?: boolean;
}

function readCanvasMatteRgba(): [number, number, number, number] {
  if (typeof window === 'undefined' || typeof document === 'undefined') {
    return [0.086, 0.086, 0.086, 1.0];
  }
  try {
    const val = getComputedStyle(document.documentElement)
      .getPropertyValue('--ui-canvas-matte')
      .trim();
    return parseCssColorToRgba(val, [0.086, 0.086, 0.086, 1.0]);
  } catch {
    return [0.086, 0.086, 0.086, 1.0];
  }
}

/**
 * Lightweight native `ink-engine` DX12 state-sync & overlay coordination hook.
 *
 * Replaces the legacy WebGL2/Canvas2D `ViewportCompositor`: allocates ZERO WebGL2 contexts,
 * ZERO FBOs, and ZERO viewport `<canvas>` elements inside WebView2. Instead, it pushes
 * animation cel overrides, onion skin frames, soft-proofing, value check, checkerboard,
 * matte theme color, and layer-stack-caching settings directly to the native DX12 WGSL
 * compositor while keeping DOM overlays (rulers, selection marching ants, vector handles)
 * synchronized at 60–240 Hz via `navigation.subscribeCamera`.
 */
export function useCompositorViewport({
  viewportRef,
  onViewportReady,
  artboardRef,
  cursorRingRef,
  cursorConfigRef,
  lastPointerPosRef,
  navigation,
  animationTimeline,
  livePan,
  liveZoom,
  liveRotation,
  liveFlipX,
  liveFlipY,
  dimensions,
  showCheckerboard,
  softProofSettings,
  valueCheckEnabled = false,
  nativeCanvasActive = false,
}: UseCompositorViewportParams): void {
  const [perfConfig, setPerfConfig] = useState<RuntimePerformanceConfig>(() =>
    performanceManager.getConfig()
  );

  useEffect(() => {
    return performanceManager.subscribe((next) => {
      setPerfConfig(next);
    });
  }, []);

  const appearance = useUiStore((s) => s.appSettings.appearance);

  // Track latest native DX12 diagnostics for PerformanceSettingsTab & InfoPanel telemetry
  const latestDiagRef = useRef<NativeEngineDiagnostics | null>(null);
  useEffect(() => {
    let active = true;
    void getNativeDiagnostics().then((diag) => {
      if (active && diag) latestDiagRef.current = diag;
    });
    const unsub = subscribeNativeDiagnostics((diag) => {
      if (active) latestDiagRef.current = diag;
    });
    return () => {
      active = false;
      unsub();
    };
  }, [nativeCanvasActive]);

  // Register DX12 GPU telemetry & VRAM pool flush hooks with performanceManager
  useEffect(() => {
    performanceManager.registerCompositorHooks({
      getTelemetry: () => {
        const d = latestDiagRef.current;
        return {
          backend: 'dx12',
          rendererName: d?.adapterName || 'DirectX 12 (wgpu)',
          arrayPoolUsed: d?.gpuTilesResident ?? 0,
          arrayPoolCapacity: d?.gpuTilesCapacity ?? 0,
          texture2DPoolUsed: 0,
          estimatedVramMb: d?.gpuVramUsedBytes
            ? Math.round((d.gpuVramUsedBytes / (1024 * 1024)) * 10) / 10
            : 0,
          stackCacheHits: d?.stackCacheHits ?? 0,
          stackCacheRebuilds: d?.stackCacheRebuilds ?? 0,
        };
      },
      flushGpuCaches: () => {
        void flushNativeGpuPool();
      },
    });
    return () => {
      performanceManager.registerCompositorHooks(null);
    };
  }, []);

  // Compute native onion skin frames & animation cel visibility overrides
  const nativeOnionSkinFrames = useMemo(() => {
    if (!animationTimeline || !animationTimeline.onionSkin?.enabled) return [];
    return getOnionSkinFrames(animationTimeline).map((f) => {
      const [r, g, b] = parseCssColorToRgba(f.tint, [0.0, 0.74, 0.83, 1.0]);
      return {
        layerId: f.layerId,
        tint: [r, g, b] as [number, number, number],
        opacity: f.opacity,
      };
    });
  }, [animationTimeline]);

  const celVisibilityOverrides = useMemo<Record<string, boolean>>(() => {
    if (!animationTimeline) return {};
    const currentCelId = animationTimeline.cels[animationTimeline.currentFrame];
    const overrides: Record<string, boolean> = {};
    for (const celId of Object.values(animationTimeline.cels)) {
      overrides[celId] = celId === currentCelId;
    }
    return overrides;
  }, [animationTimeline]);

  // Push complete display configuration to Rust DX12 WGSL compositor whenever display state changes
  useEffect(() => {
    if (!nativeCanvasActive) return;
    const matteColor = readCanvasMatteRgba();
    void setNativeDisplayConfig({
      showCheckerboard,
      matteColor,
      softProof: {
        enabled: Boolean(softProofSettings?.enabled),
        standard: softProofSettings?.standard ?? 'japan-color-2001',
        gamutWarning: Boolean(softProofSettings?.gamutWarning),
        gamutWarningColor: softProofSettings?.gamutWarningColor ?? '#808080',
      },
      valueCheckEnabled: Boolean(valueCheckEnabled),
      showPixelGrid: true,
      onionSkinFrames: nativeOnionSkinFrames,
      celVisibilityOverrides,
      layerStackCaching: perfConfig.layerStackCaching,
    });
  }, [
    nativeCanvasActive,
    showCheckerboard,
    softProofSettings,
    valueCheckEnabled,
    nativeOnionSkinFrames,
    celVisibilityOverrides,
    perfConfig.layerStackCaching,
    appearance,
    dimensions.width,
    dimensions.height,
  ]);

  const renderParamsRef = useRef({
    pan: livePan,
    zoom: liveZoom,
    rotation: liveRotation,
    flipX: liveFlipX,
    flipY: liveFlipY,
    dimensions,
  });
  renderParamsRef.current = {
    pan: livePan,
    zoom: liveZoom,
    rotation: liveRotation,
    flipX: liveFlipX,
    flipY: liveFlipY,
    dimensions,
  };

  // Direct zero-React-rerender camera subscription for DOM overlays (artboard guides, rulers, selection, cursor ring)
  useEffect(() => {
    if (!navigation) return;
    return navigation.subscribeCamera((cam) => {
      const rp = renderParamsRef.current;
      rp.pan = cam.pan;
      rp.zoom = cam.zoom;
      rp.rotation = cam.rotation;
      rp.flipX = cam.flipX;
      rp.flipY = cam.flipY;

      const cfg = cursorConfigRef.current;
      cfg.rotation = cam.rotation;
      cfg.flipX = cam.flipX;
      cfg.flipY = cam.flipY;

      const artboard = artboardRef.current;
      if (artboard) {
        artboard.style.transform = formatArtboardTransform(
          cam.pan,
          cam.zoom,
          cam.rotation,
          cam.flipX,
          cam.flipY,
          rp.dimensions
        );
      }

      const ring = cursorRingRef.current;
      if (ring) {
        const baseW = Math.max(4, cfg.activeToolSize * cam.zoom);
        const dims = computeTipStampDimensions(
          baseW,
          cfg.thicknessRatio,
          cfg.thicknessVertical,
          1,
          cfg.tipAspect
        );
        const cW = Math.max(2, dims.width);
        const cH = Math.max(2, dims.height);
        ring.style.width = `${cW}px`;
        ring.style.height = `${cH}px`;
        const pos = lastPointerPosRef.current;
        if (pos && ring.style.display !== 'none') {
          ring.style.transform = formatCursorRingTransform(
            pos.x,
            pos.y,
            cam.rotation,
            cam.flipX,
            cam.flipY,
            computeEffectiveCursorAngleDeg(cfg)
          );
        }
      }
    });
  }, [navigation, artboardRef, cursorRingRef, cursorConfigRef, lastPointerPosRef]);

  useEffect(() => {
    if (viewportRef.current) {
      onViewportReady?.(viewportRef.current);
      const raf = requestAnimationFrame(() => {
        if (viewportRef.current) {
          onViewportReady?.(viewportRef.current);
        }
      });
      return () => cancelAnimationFrame(raf);
    }
  }, [onViewportReady, viewportRef]);
}