Skip to content

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

36.4 KB
Raw Blame
import React, { useMemo, useRef } from 'react';
import { Upload, Trash2, Plus } from 'lucide-react';
import type {
  BristleProfilePreset,
  BristleSettings,
  BrushRenderMode,
  BrushSettings,
  CspAngleDynamicsMode,
  CspPaperTextureMode,
  CspSubTipOrder,
  CspTaperSettings,
  CspTipFlipMode,
  GrainMappingMode,
  SurfaceTextureId,
} from '../../types/editor';
import {
  DEFAULT_BRISTLE_SETTINGS,
  DEFAULT_NATURAL_PAINT_SETTINGS,
} from '../../types/editor';
import {
  generateNaturalTipByProfile,
  getSurfaceTextureDataUrl,
  SURFACE_TEXTURE_CATALOG,
} from '../../utils/proceduralBrushTips';
import { getPreloadedBuiltinTipImage } from '../../utils/presetBrushes';
import { PressureCurveEditor } from '../PressureCurveEditor';
import { resolveBrushCursorRotationSpec } from '../canvasArea/types';
import {
  readImageFileAsDataUrl,
  StudioSection,
  StudioSegmented,
  StudioSlider,
  StudioToggle,
} from './BrushStudioControls';
import { useI18n } from '../../i18n';

export interface BrushStudioTabProps {
  bs: BrushSettings;
  onPatch: (patch: Partial<BrushSettings>) => void;
}

const DEFAULT_TAPER: CspTaperSettings = {
  useIn: false,
  inLength: 24,
  inRatio: 0.9,
  useOut: false,
  outLength: 32,
  outRatio: 0.9,
  startingSharpness: 0.8,
  endingSharpness: 0.8,
  affectSize: true,
  affectDensity: false,
  affectOpacity: false,
  affectLoad: true,
};

export const ShapeBristlesTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {
  const { t, tc } = useI18n();
  const tipInputRef = useRef<HTMLInputElement>(null);
  const subTipInputRef = useRef<HTMLInputElement>(null);
  const bristle: BristleSettings = { ...DEFAULT_BRISTLE_SETTINGS, ...(bs.bristle || {}) };
  const renderMode: BrushRenderMode = bs.renderMode ?? 'stamp';

  const patchBristle = (p: Partial<BristleSettings>) => {
    onPatch({ bristle: { ...bristle, ...p } });
  };

  const applyProfilePreset = (profile: BristleProfilePreset) => {
    if (profile === 'custom') {
      patchBristle({ profile: 'custom' });
      return;
    }
    const url = generateNaturalTipByProfile(profile);
    const img = url ? getPreloadedBuiltinTipImage(url) : undefined;
    onPatch({
      bristle: { ...bristle, profile },
      customTipDataUrl: url || bs.customTipDataUrl,
      customTipImage: img || bs.customTipImage,
    });
  };

  const handleUploadTip = async (file: File) => {
    try {
      const res = await readImageFileAsDataUrl(file);
      onPatch({
        customTipDataUrl: res.dataUrl,
        customTipImage: res.image,
        bristle: { ...bristle, profile: 'custom' },
      });
    } catch {
      // ignore invalid image
    }
  };

  const handleAddSubTip = async (file: File) => {
    try {
      const res = await readImageFileAsDataUrl(file);
      const nextSubs = [
        ...(bs.subTips || []),
        { dataUrl: res.dataUrl, width: res.width, height: res.height, isColor: false },
      ].slice(0, 16);
      const nextImgs = [...(bs.subTipImages || []), res.image].slice(0, 16);
      onPatch({
        subTips: nextSubs,
        subTipImages: nextImgs,
        customTipDataUrl: bs.customTipDataUrl || res.dataUrl,
        customTipImage: bs.customTipImage || res.image,
      });
    } catch {
      // ignore
    }
  };

  const removeSubTip = (idx: number) => {
    const nextSubs = (bs.subTips || []).filter((_, i) => i !== idx);
    const nextImgs = (bs.subTipImages || []).filter((_, i) => i !== idx);
    onPatch({
      subTips: nextSubs.length > 0 ? nextSubs : undefined,
      subTipImages: nextImgs.length > 0 ? nextImgs : undefined,
    });
  };

  const subTipCount = bs.subTips?.length ?? 0;

  return (
    <div className="divide-y divide-ui-subtle">
      <StudioSection
        title={t('Engine & Tip Profile')}
        summary={tc('bristleProfile', bristle.profile)}
        divider={false}
        defaultOpen
      >
        <StudioSegmented<BrushRenderMode>
          label={t('Render Mode')}
          value={renderMode}
          options={[
            { id: 'stamp', label: t('Stamp') },
            { id: 'bristle-ribbon', label: t('Bristle Ribbon') },
            { id: 'bristle-hybrid', label: t('Bristle Hybrid') },
          ]}
          onChange={(mode) =>
            onPatch({
              renderMode: mode,
              rotateCursor: undefined,
              naturalPaint:
                mode !== 'stamp'
                  ? { ...DEFAULT_NATURAL_PAINT_SETTINGS, ...(bs.naturalPaint || {}), enabled: true }
                  : bs.naturalPaint,
            })
          }
        />

        <StudioSegmented<BristleProfilePreset>
          label={t('Brush Tip Profile')}
          value={bristle.profile}
          options={[
            { id: 'round', label: t('Round') },
            { id: 'flat', label: tc('bristleTip', 'Flat') },
            { id: 'filbert', label: t('Filbert') },
            { id: 'fan', label: t('Fan') },
            { id: 'rake', label: t('Rake') },
            { id: 'knife', label: t('Knife') },
            { id: 'custom', label: t('Custom') },
          ]}
          onChange={applyProfilePreset}
        />

        {/* Primary Tip Preview & Upload */}
        <div className="p-2 rounded-ui-sm bg-ui-input border border-ui-subtle flex items-center gap-2.5">
          <div className="w-11 h-11 rounded-ui-xs bg-neutral-950 border border-ui-default flex items-center justify-center overflow-hidden shrink-0">
            {bs.customTipDataUrl ? (
              <img src={bs.customTipDataUrl} alt={t('Tip')} className="w-9 h-9 object-contain" />
            ) : (
              <div className="w-6 h-6 rounded-full bg-white/85" />
            )}
          </div>
          <div className="flex-1 min-w-0 space-y-1.5">
            <div className="text-[11px] text-ui-primary font-medium truncate">
              {t('Primary Tip Shape')}
            </div>
            <div className="flex items-center gap-1.5">
              <button
                type="button"
                onClick={() => tipInputRef.current?.click()}
                className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer transition-colors"
              >
                <Upload className="w-3 h-3" />
                <span>{t('Upload PNG')}</span>
              </button>
              {bs.customTipDataUrl && (
                <button
                  type="button"
                  onClick={() => onPatch({ customTipDataUrl: undefined, customTipImage: undefined })}
                  className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle hover:border-ui-danger/40 text-[10px] text-ui-secondary hover:text-ui-danger cursor-pointer transition-colors"
                >
                  {t('Clear')}
                </button>
              )}
            </div>
          </div>
          <input
            ref={tipInputRef}
            type="file"
            accept="image/png,image/webp,image/jpeg"
            className="hidden"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) handleUploadTip(f);
              e.target.value = '';
            }}
          />
        </div>
      </StudioSection>

      <StudioSection
        title={t('Multi-Tip Atlas')}
        summary={subTipCount > 0 ? t('{count} tips', { count: subTipCount }) : t('Single')}
        summaryTone={subTipCount > 0 ? 'accent' : 'muted'}
        defaultOpen={subTipCount > 0}
        divider={false}
      >
        <div className="flex items-center justify-between gap-2">
          <span className="text-[10.5px] text-ui-muted">
            {t('Combine up to 16 sequential or random tip shapes')}
          </span>
          <button
            type="button"
            onClick={() => subTipInputRef.current?.click()}
            className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer transition-colors shrink-0"
          >
            <Plus className="w-3 h-3" />
            <span>{t('Add Tip')}</span>
          </button>
          <input
            ref={subTipInputRef}
            type="file"
            accept="image/png,image/webp,image/jpeg"
            className="hidden"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) handleAddSubTip(f);
              e.target.value = '';
            }}
          />
        </div>
        {bs.subTips && bs.subTips.length > 0 && (
          <>
            <div className="flex flex-wrap gap-1.5">
              {bs.subTips.map((st, idx) => (
                <div
                  key={idx}
                  className="relative group w-9 h-9 rounded-ui-xs bg-neutral-950 border border-ui-default flex items-center justify-center overflow-hidden"
                >
                  <img src={st.dataUrl} alt="" className="w-7 h-7 object-contain" />
                  <button
                    type="button"
                    onClick={() => removeSubTip(idx)}
                    aria-label={t('Remove sub-tip {n}', { n: idx + 1 })}
                    className="absolute inset-0 bg-ui-overlay opacity-0 group-hover:opacity-100 flex items-center justify-center text-ui-danger cursor-pointer"
                  >
                    <Trash2 className="w-3 h-3" />
                  </button>
                </div>
              ))}
            </div>
            <StudioSegmented<CspSubTipOrder>
              label={t('Sub-Tip Order')}
              value={bs.subTipOrder ?? 'sequential'}
              options={[
                { id: 'sequential', label: t('Sequential') },
                { id: 'random', label: t('Random') },
                { id: 'direction', label: t('Direction') },
                { id: 'reverse', label: t('Reverse') },
              ]}
              onChange={(order) => onPatch({ subTipOrder: order })}
            />
          </>
        )}
      </StudioSection>

      <StudioSection
        title={t('Bristle Architecture')}
        summary={t('{count} strands', { count: bristle.count })}
        defaultOpen
        divider={false}
      >
        <StudioSlider
          label={t('Bristle Count')}
          value={bristle.count}
          min={4}
          max={64}
          defaultValue={DEFAULT_BRISTLE_SETTINGS.count}
          valueLabel={t('{count} strands', { count: bristle.count })}
          onChange={(v) => patchBristle({ count: v })}
        />
        <StudioSlider
          label={t('Bristle Clumping')}
          value={Math.round(bristle.clumping * 100)}
          min={0}
          max={100}
          defaultValue={Math.round(DEFAULT_BRISTLE_SETTINGS.clumping * 100)}
          valueLabel={`${Math.round(bristle.clumping * 100)}%`}
          onChange={(v) => patchBristle({ clumping: v / 100 })}
        />
        <StudioSlider
          label={t('Stiffness')}
          value={Math.round(bristle.stiffness * 100)}
          min={0}
          max={100}
          defaultValue={Math.round(DEFAULT_BRISTLE_SETTINGS.stiffness * 100)}
          valueLabel={`${Math.round(bristle.stiffness * 100)}%`}
          onChange={(v) => patchBristle({ stiffness: v / 100 })}
        />
        <StudioSlider
          label={t('Pressure / Tilt Splay')}
          value={Math.round(bristle.splay * 100)}
          min={0}
          max={100}
          defaultValue={Math.round(DEFAULT_BRISTLE_SETTINGS.splay * 100)}
          valueLabel={`${Math.round(bristle.splay * 100)}%`}
          onChange={(v) => patchBristle({ splay: v / 100 })}
        />
        <StudioSlider
          label={t('Strand Irregularity')}
          value={Math.round(bristle.irregularity * 100)}
          min={0}
          max={100}
          defaultValue={Math.round(DEFAULT_BRISTLE_SETTINGS.irregularity * 100)}
          valueLabel={`${Math.round(bristle.irregularity * 100)}%`}
          onChange={(v) => patchBristle({ irregularity: v / 100 })}
        />
        <StudioSlider
          label={t('Edge Ridge Buildup')}
          value={Math.round((bristle.edgeRidge ?? 0.2) * 100)}
          min={0}
          max={100}
          defaultValue={20}
          valueLabel={`${Math.round((bristle.edgeRidge ?? 0.2) * 100)}%`}
          onChange={(v) => patchBristle({ edgeRidge: v / 100 })}
        />
      </StudioSection>

      <StudioSection
        title={t('Tip Geometry & Orientation')}
        summary={`${Math.round((bs.hardness ?? 0.9) * 100)}%`}
        defaultOpen
        divider={false}
      >
        <StudioSlider
          label={t('Hardness')}
          value={Math.round((bs.hardness ?? 0.9) * 100)}
          min={0}
          max={100}
          defaultValue={90}
          valueLabel={`${Math.round((bs.hardness ?? 0.9) * 100)}%`}
          onChange={(v) => onPatch({ hardness: v / 100 })}
        />
        <StudioSlider
          label={t('Thickness (Aspect)')}
          value={Math.round((bs.thickness ?? 1.0) * 100)}
          min={5}
          max={100}
          defaultValue={100}
          valueLabel={`${Math.round((bs.thickness ?? 1.0) * 100)}%`}
          onChange={(v) => onPatch({ thickness: v / 100 })}
        />
        <StudioSlider
          label={t('Tip Angle')}
          value={Math.round(bs.customTipAngle ?? 0)}
          min={-180}
          max={180}
          defaultValue={0}
          valueLabel={`${Math.round(bs.customTipAngle ?? 0)}°`}
          onChange={(v) => onPatch({ customTipAngle: v })}
        />
        <StudioSegmented<CspAngleDynamicsMode>
          label={t('Angle Dynamics')}
          value={bs.customTipAngleDynamics ?? 'none'}
          options={[
            { id: 'none', label: t('Fixed') },
            { id: 'direction', label: tc('angleDynamics', 'Stroke') },
            { id: 'tilt', label: t('Tilt') },
            { id: 'twist', label: t('Twist') },
            { id: 'random', label: t('Random') },
          ]}
          onChange={(v) => onPatch({ customTipAngleDynamics: v, rotateCursor: undefined })}
        />
        <StudioToggle
          label={t('This brush rotates')}
          description={t('Rotate the brush cursor preview to track brush direction')}
          checked={resolveBrushCursorRotationSpec(bs, 'brush').enabled}
          onChange={(v) => onPatch({ rotateCursor: v })}
        />
        <div className="grid grid-cols-2 gap-2">
          <StudioSegmented<CspTipFlipMode>
            label={t('Flip Horizontal')}
            value={bs.flipH ?? 'none'}
            options={[
              { id: 'none', label: t('Off') },
              { id: 'alternate', label: tc('flip', 'Alt') },
              { id: 'random', label: tc('flip', 'Rand') },
            ]}
            onChange={(v) => onPatch({ flipH: v })}
          />
          <StudioSegmented<CspTipFlipMode>
            label={t('Flip Vertical')}
            value={bs.flipV ?? 'none'}
            options={[
              { id: 'none', label: t('Off') },
              { id: 'alternate', label: tc('flip', 'Alt') },
              { id: 'random', label: tc('flip', 'Rand') },
            ]}
            onChange={(v) => onPatch({ flipV: v })}
          />
        </div>
      </StudioSection>
    </div>
  );
};

export const StrokeTaperTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {
  const { t } = useI18n();
  const taper: CspTaperSettings = { ...DEFAULT_TAPER, ...(bs.taper || {}) };
  const patchTaper = (p: Partial<CspTaperSettings>) => onPatch({ taper: { ...taper, ...p } });

  const taperSummary =
    taper.useIn && taper.useOut
      ? t('In & Out')
      : taper.useIn
        ? t('In')
        : taper.useOut
          ? t('Out')
          : t('Off');

  return (
    <div className="divide-y divide-ui-subtle">
      <StudioSection
        title={t('Stroke Path & Smoothing')}
        summary={`${Math.round((bs.spacing ?? 0.06) * 100)}%`}
        divider={false}
        defaultOpen
      >
        <StudioSlider
          label={t('Spacing')}
          value={Math.round((bs.spacing ?? 0.06) * 100)}
          min={2}
          max={100}
          defaultValue={6}
          valueLabel={`${Math.round((bs.spacing ?? 0.06) * 100)}%`}
          onChange={(v) => onPatch({ spacing: v / 100 })}
        />
        <StudioSlider
          label={t('Streamline / Stabilization')}
          value={Math.round(bs.stabilization ?? 10)}
          min={0}
          max={50}
          defaultValue={10}
          valueLabel={`${Math.round(bs.stabilization ?? 10)}`}
          onChange={(v) => onPatch({ stabilization: v })}
        />
        <StudioSlider
          label={t('Post-Correction')}
          value={Math.round(bs.postCorrection ?? 0)}
          min={0}
          max={5}
          defaultValue={0}
          valueLabel={`${Math.round(bs.postCorrection ?? 0)}`}
          onChange={(v) => onPatch({ postCorrection: v })}
        />
        <StudioToggle
          label={t('Sharp Angles')}
          description={t('Preserve crisp corners instead of rounding')}
          checked={bs.sharpCorners !== false}
          onChange={(v) => onPatch({ sharpCorners: v })}
        />
      </StudioSection>

      <StudioSection
        title={t('Taper In & Taper Out')}
        summary={taperSummary}
        summaryTone={taper.useIn || taper.useOut ? 'accent' : 'muted'}
        defaultOpen
        divider={false}
      >
        <StudioToggle
          label={t('Enable Taper In')}
          checked={Boolean(taper.useIn)}
          onChange={(v) => patchTaper({ useIn: v })}
        />
        {taper.useIn && (
          <>
            <StudioSlider
              label={t('Taper In Length')}
              value={Math.round(taper.inLength)}
              min={4}
              max={200}
              defaultValue={24}
              valueLabel={`${Math.round(taper.inLength)}px`}
              onChange={(v) => patchTaper({ inLength: v })}
            />
            <StudioSlider
              label={t('Start Sharpness')}
              value={Math.round((taper.startingSharpness ?? 0.8) * 100)}
              min={0}
              max={100}
              defaultValue={80}
              valueLabel={`${Math.round((taper.startingSharpness ?? 0.8) * 100)}%`}
              onChange={(v) => patchTaper({ startingSharpness: v / 100 })}
            />
          </>
        )}

        <StudioToggle
          label={t('Enable Taper Out')}
          checked={Boolean(taper.useOut)}
          onChange={(v) => patchTaper({ useOut: v })}
        />
        {taper.useOut && (
          <>
            <StudioSlider
              label={t('Taper Out Length')}
              value={Math.round(taper.outLength)}
              min={4}
              max={250}
              defaultValue={32}
              valueLabel={`${Math.round(taper.outLength)}px`}
              onChange={(v) => patchTaper({ outLength: v })}
            />
            <StudioSlider
              label={t('End Sharpness')}
              value={Math.round((taper.endingSharpness ?? 0.8) * 100)}
              min={0}
              max={100}
              defaultValue={80}
              valueLabel={`${Math.round((taper.endingSharpness ?? 0.8) * 100)}%`}
              onChange={(v) => patchTaper({ endingSharpness: v / 100 })}
            />
          </>
        )}

        <div className="pt-2 border-t border-ui-subtle space-y-1">
          <StudioToggle
            label={t('Affect Size')}
            checked={taper.affectSize !== false}
            onChange={(v) => patchTaper({ affectSize: v })}
          />
          <StudioToggle
            label={t('Affect Density / Opacity')}
            checked={Boolean(taper.affectDensity || taper.affectOpacity)}
            onChange={(v) => patchTaper({ affectDensity: v, affectOpacity: v })}
          />
          <StudioToggle
            label={t('Affect Paint Load (Dry Tail)')}
            checked={taper.affectLoad !== false}
            onChange={(v) => patchTaper({ affectLoad: v })}
          />
        </div>
      </StudioSection>
    </div>
  );
};

export const TextureGrainTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {
  const { t, tc, td } = useI18n();
  const texInputRef = useRef<HTMLInputElement>(null);
  const natural = { ...DEFAULT_NATURAL_PAINT_SETTINGS, ...(bs.naturalPaint || {}) };

  const thumbnails = useMemo(
    () =>
      SURFACE_TEXTURE_CATALOG.map((meta) => ({
        ...meta,
        url: getSurfaceTextureDataUrl(meta.id),
      })),
    []
  );

  const activeTexEntry = SURFACE_TEXTURE_CATALOG.find((tex) => tex.id === bs.surfaceTextureId);
  const hasActiveTexture = Boolean(activeTexEntry || bs.paperTexture);
  const activeTexLabel = activeTexEntry
    ? td(activeTexEntry.label)
    : bs.paperTexture
      ? t('Custom')
      : t('None');
  const dualTexEntry = SURFACE_TEXTURE_CATALOG.find((tex) => tex.id === bs.dualSurfaceTextureId);
  const dualTexLabel = dualTexEntry ? td(dualTexEntry.label) : t('Off');
  const grainPct = Math.round((bs.grain ?? bs.textureDensity ?? 0) * 100);

  const selectBuiltinTexture = (id: SurfaceTextureId) => {
    const url = getSurfaceTextureDataUrl(id);
    const img = url ? getPreloadedBuiltinTipImage(url) : undefined;
    onPatch({
      surfaceTextureId: id,
      paperTexture: url || undefined,
      paperTextureImage: img,
      grain: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.35),
      textureDensity: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.35),
    });
  };

  const handleUploadTexture = async (file: File) => {
    try {
      const res = await readImageFileAsDataUrl(file);
      onPatch({
        paperTexture: res.dataUrl,
        paperTextureImage: res.image,
        grain: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.45),
        textureDensity: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.45),
      });
    } catch {
      // ignore
    }
  };

  return (
    <div className="divide-y divide-ui-subtle">
      {/* Built-in 512x512 Seamless Surface Texture Gallery */}
      <StudioSection
        title={t('Surface Texture Library')}
        summary={activeTexLabel}
        summaryTone={hasActiveTexture ? 'accent' : 'muted'}
        divider={false}
        defaultOpen
      >
        <div className="flex items-center justify-between gap-2">
          <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
            {t('512 × 512 seamless grain')}
          </span>
          <button
            type="button"
            onClick={() => texInputRef.current?.click()}
            className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer transition-colors"
          >
            <Upload className="w-3 h-3" />
            <span>{t('Import PNG/WebP')}</span>
          </button>
          <input
            ref={texInputRef}
            type="file"
            accept="image/png,image/webp,image/jpeg"
            className="hidden"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) handleUploadTexture(f);
              e.target.value = '';
            }}
          />
        </div>

        <div className="grid grid-cols-4 gap-1.5">
          {thumbnails.map((tex) => {
            const active = bs.surfaceTextureId === tex.id;
            const texLabel = td(tex.label);
            return (
              <button
                key={tex.id}
                type="button"
                onClick={() => selectBuiltinTexture(tex.id)}
                title={td(tex.desc)}
                className={`p-1 rounded-ui-xs border text-left transition-colors cursor-pointer ${
                  active
                    ? 'border-ui-accent bg-ui-accent-subtle'
                    : 'border-ui-subtle bg-ui-input hover:border-ui-strong'
                }`}
              >
                <div className="w-full aspect-square rounded-ui-xs overflow-hidden bg-ui-void mb-1">
                  {tex.url && (
                    <img src={tex.url} alt={texLabel} className="w-full h-full object-cover" />
                  )}
                </div>
                <div className="text-[9px] text-ui-primary truncate leading-tight">{texLabel}</div>
              </button>
            );
          })}
        </div>

        <StudioSegmented<GrainMappingMode>
          label={t('Spatial Grain Mapping')}
          value={bs.grainMappingMode ?? 'canvas-locked'}
          options={[
            { id: 'canvas-locked', label: t('Canvas') },
            { id: 'brush-aligned', label: t('Brush') },
            { id: 'stroke-flow', label: tc('grainMap', 'Flow') },
            { id: 'random-per-stroke', label: t('Random') },
          ]}
          onChange={(m) => onPatch({ grainMappingMode: m })}
        />
      </StudioSection>

      <StudioSection
        title={t('Grain & Paper Physics')}
        summary={`${grainPct}%`}
        summaryTone={grainPct > 0 ? 'accent' : 'muted'}
        defaultOpen
        divider={false}
      >
        <StudioSlider
          label={t('Grain Depth / Intensity')}
          value={grainPct}
          min={0}
          max={100}
          defaultValue={0}
          valueLabel={`${grainPct}%`}
          onChange={(v) => onPatch({ grain: v / 100, textureDensity: v / 100 })}
        />
        <StudioSlider
          label={t('Dry-Brush Valley Cutoff')}
          value={Math.round(natural.dryBrush * 100)}
          min={0}
          max={100}
          defaultValue={0}
          valueLabel={`${Math.round(natural.dryBrush * 100)}%`}
          onChange={(v) => onPatch({ naturalPaint: { ...natural, dryBrush: v / 100 } })}
        />
        <StudioSlider
          label={t('Scale')}
          value={Math.round((bs.paperTextureScale ?? 1.0) * 100)}
          min={20}
          max={300}
          defaultValue={100}
          valueLabel={`${Math.round((bs.paperTextureScale ?? 1.0) * 100)}%`}
          onChange={(v) => onPatch({ paperTextureScale: v / 100 })}
        />
        <StudioSlider
          label={t('Rotation')}
          value={Math.round(bs.paperTextureRotate ?? 0)}
          min={-180}
          max={180}
          defaultValue={0}
          valueLabel={`${Math.round(bs.paperTextureRotate ?? 0)}°`}
          onChange={(v) => onPatch({ paperTextureRotate: v })}
        />
        <StudioSlider
          label={t('Contrast')}
          value={Math.round(bs.paperTextureContrast ?? 0)}
          min={-80}
          max={80}
          defaultValue={0}
          valueLabel={`${Math.round(bs.paperTextureContrast ?? 0)}`}
          onChange={(v) => onPatch({ paperTextureContrast: v })}
        />
        <StudioSlider
          label={t('Brightness')}
          value={Math.round(bs.paperTextureBrightness ?? 0)}
          min={-50}
          max={50}
          defaultValue={0}
          valueLabel={`${Math.round(bs.paperTextureBrightness ?? 0)}`}
          onChange={(v) => onPatch({ paperTextureBrightness: v })}
        />
        <StudioSegmented<CspPaperTextureMode>
          label={t('Texture Blend Mode')}
          value={bs.paperTextureMode ?? 'compare'}
          options={[
            { id: 'compare', label: tc('textureMode', 'Compare') },
            { id: 'multiply', label: tc('blendMode', 'Multiply') },
            { id: 'subtract', label: tc('blendMode', 'Subtract') },
            { id: 'overlay', label: tc('blendMode', 'Overlay') },
            { id: 'outline', label: tc('textureMode', 'Outline') },
          ]}
          onChange={(v) => onPatch({ paperTextureMode: v })}
        />
        <StudioToggle
          label={t('Invert Texture')}
          checked={Boolean(bs.paperTextureInverted)}
          onChange={(v) => onPatch({ paperTextureInverted: v })}
        />
      </StudioSection>

      {/* Dual Grain Secondary Surface */}
      <StudioSection
        title={t('Secondary Dual Grain')}
        summary={dualTexLabel}
        summaryTone={bs.dualSurfaceTextureId ? 'accent' : 'muted'}
        defaultOpen={Boolean(bs.dualSurfaceTextureId)}
        divider={false}
      >
        <select
          value={bs.dualSurfaceTextureId || ''}
          onChange={(e) =>
            onPatch({
              dualSurfaceTextureId: (e.target.value || undefined) as SurfaceTextureId | undefined,
            })
          }
          className="w-full h-[var(--ui-control-height)] px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:border-ui-default text-[11px] text-ui-primary"
        >
          <option value="">{t('None')}</option>
          {SURFACE_TEXTURE_CATALOG.map((tex) => (
            <option key={tex.id} value={tex.id}>
              {td(tex.label)}
            </option>
          ))}
        </select>
        {bs.dualSurfaceTextureId && (
          <StudioSlider
            label={t('Dual Grain Depth')}
            value={Math.round((bs.dualGrainDepth ?? 0.35) * 100)}
            min={0}
            max={100}
            defaultValue={35}
            valueLabel={`${Math.round((bs.dualGrainDepth ?? 0.35) * 100)}%`}
            onChange={(v) => onPatch({ dualGrainDepth: v / 100 })}
          />
        )}
      </StudioSection>

      {/* Pressure-to-Penetration Curve */}
      <StudioSection
        title={t('Valley Penetration Curve')}
        summary={t('Curve')}
        defaultOpen={false}
        divider={false}
      >
        <PressureCurveEditor
          value={{
            enabled: true,
            preset: 'custom',
            points: natural.penetrationCurve ?? [
              [0, 0],
              [1, 1],
            ],
          }}
          onChange={(next) =>
            onPatch({
              naturalPaint: {
                ...natural,
                penetrationCurve: next.points,
              },
            })
          }
        />
      </StudioSection>
    </div>
  );
};

export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {
  const { t, tc } = useI18n();
  const dualInputRef = useRef<HTMLInputElement>(null);

  const patchDual = (patch: Partial<typeof bs>) => {
    const baseCfg = bs.dualBrushConfig;
    const nextEnabled =
      patch.dualBrush !== undefined ? patch.dualBrush : (baseCfg?.enabled ?? Boolean(bs.dualBrush));
    const nextCfg = baseCfg
      ? {
          ...baseCfg,
          enabled: nextEnabled,
          ...(patch.dualBrushCompositeMode !== undefined
            ? {
                compositeMode: patch.dualBrushCompositeMode as NonNullable<
                  typeof bs.dualBrushConfig
                >['compositeMode'],
              }
            : {}),
          ...(patch.dualScale !== undefined ? { sizeRatio: patch.dualScale } : {}),
          ...(patch.dualAngle !== undefined ? { angle: patch.dualAngle } : {}),
          ...(patch.dualScatter !== undefined ? { scatter: patch.dualScatter } : {}),
          ...(patch.dualSpacing !== undefined ? { spacing: patch.dualSpacing } : {}),
          ...(patch.dualTipDataUrl !== undefined ? { tipDataUrl: patch.dualTipDataUrl } : {}),
          ...(patch.dualTipImage !== undefined ? { tipImage: patch.dualTipImage } : {}),
        }
      : undefined;
    onPatch(nextCfg ? { ...patch, dualBrushConfig: nextCfg } : patch);
  };

  const handleUploadDualTip = async (file: File) => {
    try {
      const res = await readImageFileAsDataUrl(file);
      patchDual({
        dualBrush: true,
        dualTipDataUrl: res.dataUrl,
        dualTipImage: res.image,
      });
    } catch {
      // ignore
    }
  };

  return (
    <div className="divide-y divide-ui-subtle">
      <StudioSection
        title={t('Dual Brush Compositing')}
        summary={bs.dualBrush ? t('Active') : t('Off')}
        summaryTone={bs.dualBrush ? 'accent' : 'muted'}
        divider={false}
        defaultOpen
      >
        <StudioToggle
          label={t('Enable Dual Brush')}
          description={t('Modulate primary tip with a secondary tip shape')}
          checked={Boolean(bs.dualBrush)}
          onChange={(v) => patchDual({ dualBrush: v })}
        />

        {bs.dualBrush && (
          <>
            <div className="p-2 rounded-ui-sm bg-ui-input border border-ui-subtle flex items-center gap-2.5">
              <div className="w-11 h-11 rounded-ui-xs bg-neutral-950 border border-ui-default flex items-center justify-center overflow-hidden shrink-0">
                {bs.dualTipDataUrl ? (
                  <img src={bs.dualTipDataUrl} alt={t('Dual Tip')} className="w-9 h-9 object-contain" />
                ) : (
                  <span className="text-[9px] text-ui-muted">{t('None')}</span>
                )}
              </div>
              <div className="flex flex-wrap items-center gap-1.5 min-w-0">
                <button
                  type="button"
                  onClick={() => dualInputRef.current?.click()}
                  className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer transition-colors"
                >
                  <Upload className="w-3 h-3" />
                  <span>{t('Upload Tip')}</span>
                </button>
                <button
                  type="button"
                  onClick={() => {
                    const url = generateNaturalTipByProfile('rake');
                    const img = url ? getPreloadedBuiltinTipImage(url) : undefined;
                    patchDual({ dualTipDataUrl: url, dualTipImage: img });
                  }}
                  className="h-6 px-2 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors"
                >
                  {t('Use Rake Tip')}
                </button>
              </div>
              <input
                ref={dualInputRef}
                type="file"
                accept="image/png,image/webp,image/jpeg"
                className="hidden"
                onChange={(e) => {
                  const f = e.target.files?.[0];
                  if (f) handleUploadDualTip(f);
                  e.target.value = '';
                }}
              />
            </div>

            <StudioSegmented<
              | 'multiply'
              | 'subtract'
              | 'darken'
              | 'height'
              | 'linear-burn'
              | 'color-burn'
              | 'compare-density'
              | 'overlay'
              | 'screen'
            >
              label={t('Composite Blend Mode')}
              value={
                (bs.dualBrushCompositeMode as
                  | 'multiply'
                  | 'subtract'
                  | 'darken'
                  | 'height'
                  | 'linear-burn'
                  | 'color-burn'
                  | 'compare-density'
                  | 'overlay'
                  | 'screen') || 'multiply'
              }
              options={[
                { id: 'multiply', label: tc('blendMode', 'Multiply') },
                { id: 'subtract', label: tc('blendMode', 'Subtract') },
                { id: 'darken', label: tc('blendMode', 'Darken') },
                { id: 'height', label: tc('textureMode', 'Height') },
                { id: 'linear-burn', label: tc('dualBlend', 'Lin Burn') },
                { id: 'color-burn', label: tc('dualBlend', 'Col Burn') },
                { id: 'compare-density', label: tc('textureMode', 'Compare') },
                { id: 'overlay', label: tc('blendMode', 'Overlay') },
                { id: 'screen', label: tc('blendMode', 'Screen') },
              ]}
              onChange={(v) => patchDual({ dualBrushCompositeMode: v })}
            />

            <StudioSlider
              label={t('Dual Scale')}
              value={Math.round((bs.dualScale ?? 1.0) * 100)}
              min={20}
              max={300}
              defaultValue={100}
              valueLabel={`${Math.round((bs.dualScale ?? 1.0) * 100)}%`}
              onChange={(v) => patchDual({ dualScale: v / 100 })}
            />
            <StudioSlider
              label={t('Dual Angle')}
              value={Math.round(bs.dualAngle ?? 0)}
              min={-180}
              max={180}
              defaultValue={0}
              valueLabel={`${Math.round(bs.dualAngle ?? 0)}°`}
              onChange={(v) => patchDual({ dualAngle: v })}
            />
            <StudioSlider
              label={t('Dual Scatter')}
              value={Math.round((bs.dualScatter ?? 0) * 100)}
              min={0}
              max={200}
              defaultValue={0}
              valueLabel={`${Math.round((bs.dualScatter ?? 0) * 100)}%`}
              onChange={(v) => patchDual({ dualScatter: v / 100 })}
            />
            <StudioSlider
              label={t('Dual Spacing')}
              value={Math.round((bs.dualSpacing ?? 0.1) * 100)}
              min={2}
              max={100}
              defaultValue={10}
              valueLabel={`${Math.round((bs.dualSpacing ?? 0.1) * 100)}%`}
              onChange={(v) => patchDual({ dualSpacing: v / 100 })}
            />
          </>
        )}
      </StudioSection>
    </div>
  );
};