A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
improved 3d. added 2d animation and manga stuff
sora3f72d790de9a
diff --git a/src/App.tsx b/src/App.tsxindex 4a77516..0f5fcdf 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -18,7 +18,16 @@ import {WandSettings,AdjustmentLayerData,FilterType,+ BalloonSettings,+ VectorEditSettings,+ SpeechBalloon,+ AnimationTimeline,} from './types/editor';+import {+ createDefaultAnimationTimeline,+ setFrameCel,+ removeFrameCel,+} from './utils/animationEngine';import { applyLiquifyStep, createLiquifySelectionMask, DirtyRect } from './utils/liquifyEngine';import { PerspectiveRuler, ConstraintAxis } from './types/perspective';import { createDefaultPerspectiveRuler, applyWormsEyePreset } from './utils/perspectiveMath';@@ -97,7 +106,23 @@ import {StrokeFinishMessage,MultiplayerMessage,} from './types/multiplayer';-import { renderVectorStroke } from './utils/vectorEngine';+import {+ renderVectorStroke,+ renderVectorLayer,+ pinchVectorStroke,+ modifyStrokeWidth,+ simplifyVectorStroke,+} from './utils/vectorEngine';+import { renderMangaTextToCanvas } from './utils/mangaTextEngine';+import { createDefaultSpeechBalloon, renderSpeechBalloon } from './utils/balloonEngine';+import {+ renderSaturatedLines,+ renderStreamLines,+ SaturatedLinesOptions,+ StreamLinesOptions,+} from './utils/mangaEffectsEngine';+import { MangaEffectsModal } from './components/MangaEffectsModal';+import { WebtoonExportModal } from './components/WebtoonExportModal';import {AppSettings,@@ -113,6 +138,8 @@ import {Save,Download,Trash2,+ Film,+ Layers,Undo2,Redo2,ZoomIn,@@ -142,6 +169,11 @@ import {Feather,BoxSelect,X,+ Smartphone,+ Archive,+ Sparkles,+ MessageSquare,+ Spline,} from 'lucide-react';import { parseSutFile } from './utils/sutParser';import {@@ -236,6 +268,35 @@ export function App() {fillColor: '#ffffff',});+ // Speech Balloon tool settings & active placement session+ const [balloonSettings, setBalloonSettings] = useState<BalloonSettings>({+ shape: 'ellipse',+ fillColor: '#ffffff',+ strokeColor: '#000000',+ strokeWidth: 3,+ text: '',+ fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",+ fontSize: 22,+ vertical: false,+ });+ const [activeBalloon, setActiveBalloon] = useState<SpeechBalloon | null>(null);++ // Vector "Correct Line" tool settings+ const [vectorEditSettings, setVectorEditSettings] = useState<VectorEditSettings>({+ mode: 'pinch',+ radius: 35,+ pinchStrength: 1.0,+ widthFactor: 1.5,+ simplifyTolerance: 2.0,+ });++ // Webtoon Studio Mode state+ const [isWebtoonMode, setIsWebtoonMode] = useState<boolean>(false);+ const [isWebtoonExportModalOpen, setIsWebtoonExportModalOpen] = useState<boolean>(false);++ // Manga Effect Lines Modal state+ const [isMangaEffectsModalOpen, setIsMangaEffectsModalOpen] = useState<boolean>(false);+// Liquify tool settingsconst [liquifySettings, setLiquifySettings] = useState<LiquifySettings>(() => {try {@@ -269,6 +330,10 @@ export function App() {const prevLiquifyPointRef = useRef<{ x: number; y: number } | null>(null);const liquifyBeforeImageDataRef = useRef<ImageData | null>(null);const liquifyInitialImageDataRef = useRef<ImageData | null>(null);++ const isVectorEditingRef = useRef<boolean>(false);+ const lastVectorEditPtRef = useRef<{ x: number; y: number } | null>(null);+ const vectorEditBeforeStrokesRef = useRef<any[] | null>(null);const liquifyDirtyRectRef = useRef<DirtyRect | null>(null);const liquifyRafIdRef = useRef<number | null>(null);const liquifyLastPointerPosRef = useRef<{ pt: { x: number; y: number }; pressure: number } | null>(null);@@ -514,6 +579,65 @@ export function App() {// Active edit target for painting/erasing ('layer' content vs 'mask')const [activeEditTarget, setActiveEditTarget] = useState<'layer' | 'mask'>('layer');+ // 2D Frame-by-Frame Animation Timeline State+ const [animationTimeline, setAnimationTimeline] = useState<AnimationTimeline | null>(null);++ const activeDoc = documents.find((d) => d.id === activeDocumentId);+ const activeAnimationTimeline = activeDoc?.animation !== undefined ? activeDoc.animation : animationTimeline;++ const handleUpdateAnimationTimeline = useCallback(+ (timeline: AnimationTimeline | null) => {+ setAnimationTimeline(timeline);+ if (activeDocumentId) {+ setDocuments((docs) =>+ docs.map((d) => (d.id === activeDocumentId ? { ...d, animation: timeline } : d))+ );+ }+ },+ [activeDocumentId]+ );++ const handleAddAnimationCel = useCallback(+ (frameIndex: number) => {+ const newLayerId = `layer-cel-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ const newCelLayer: LayerItem = {+ id: newLayerId,+ name: `Cel Frame ${frameIndex + 1}`,+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ };++ const canvas = document.createElement('canvas');+ canvas.width = dimensions.width;+ canvas.height = dimensions.height;+ registerLayerCanvas(newLayerId, canvas);++ setLayers((prev) => [newCelLayer, ...prev]);+ setActiveLayerId(newLayerId);++ const currentTl = activeAnimationTimeline || createDefaultAnimationTimeline(layers);+ const updatedTl = setFrameCel(currentTl, frameIndex, newLayerId);+ handleUpdateAnimationTimeline(updatedTl);+ showToast(`Cel added for frame ${frameIndex + 1}`);+ },+ [activeAnimationTimeline, dimensions, handleUpdateAnimationTimeline, layers, registerLayerCanvas, setActiveLayerId, setLayers, showToast]+ );++ const handleDeleteAnimationCel = useCallback(+ (frameIndex: number) => {+ if (!activeAnimationTimeline) return;+ const updatedTl = removeFrameCel(activeAnimationTimeline, frameIndex);+ handleUpdateAnimationTimeline(updatedTl);+ showToast(`Cel removed from frame ${frameIndex + 1}`);+ },+ [activeAnimationTimeline, handleUpdateAnimationTimeline, showToast]+ );+// Adjustment Layer Modal stateconst [adjustmentModalState, setAdjustmentModalState] = useState<{isOpen: boolean;@@ -591,6 +715,7 @@ export function App() {resetRotation,} = useCanvasNavigation({dimensions,+ isWebtoonMode,});// Remote multiplayer draft overlays and stroke states@@ -2266,32 +2391,18 @@ export function App() {const c = get2DContext(target);if (!c) return;const s = textSession.settings;- const lines = s.text.split('\n');- const fontSize = s.fontSize;- const fontStyle = `${s.italic ? 'italic ' : ''}${s.bold ? 'bold ' : ''}${fontSize}px ${s.fontFamily}`;-- c.save();- c.font = fontStyle;- c.textAlign = s.align;- c.textBaseline = 'middle';-- const lineHeight = fontSize * 1.25;- const totalH = lines.length * lineHeight;- const startY = textSession.y - totalH / 2 + lineHeight / 2;-- lines.forEach((line, i) => {- const lineY = startY + i * lineHeight;- if (s.outline && s.outlineWidth > 0) {- c.strokeStyle = s.outlineColor;- c.lineWidth = s.outlineWidth * 2;- c.lineJoin = 'round';- c.miterLimit = 2;- c.strokeText(line, textSession.x, lineY);- }- c.fillStyle = s.color;- c.fillText(line, textSession.x, lineY);+ renderMangaTextToCanvas(c, s.text, textSession.x, textSession.y, {+ fontSize: s.fontSize,+ fontFamily: s.fontFamily,+ writingMode: s.writingMode || 'horizontal-tb',+ bold: s.bold,+ italic: s.italic,+ align: s.align,+ color: s.color,+ outline: s.outline,+ outlineColor: s.outlineColor,+ outlineWidth: s.outlineWidth,});- c.restore();};renderTextOn(canvas);@@ -2314,6 +2425,73 @@ export function App() {setTextSession(null);}, []);+ const handleConfirmBalloon = useCallback(() => {+ if (!activeBalloon) return;+ const canvas = getActiveCanvas();+ if (!canvas) return;+ const ctx = get2DContext(canvas);+ if (!ctx) return;++ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);++ const drawOn = (target: HTMLCanvasElement) => {+ const c = get2DContext(target);+ if (!c) return;+ renderSpeechBalloon(c, activeBalloon);+ };++ drawOn(canvas);+ if (sourceCanvas) drawOn(sourceCanvas);++ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);+ updateLayerThumbnail(activeLayerId, true);+ pushHistoryStep(+ 'frame',+ 'Speech Balloon',+ beforeImageData,+ afterImageData,+ activeLayerId+ );++ setActiveBalloon(null);+ }, [activeBalloon, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);++ const handleDeleteBalloon = useCallback(() => {+ setActiveBalloon(null);+ }, []);++ const handleApplyMangaEffects = useCallback(+ (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {+ const canvas = getActiveCanvas();+ if (!canvas) return;+ const ctx = get2DContext(canvas);+ if (!ctx) return;++ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);++ const renderOn = (target: HTMLCanvasElement) => {+ const c = get2DContext(target);+ if (!c) return;+ if (type === 'saturated') {+ renderSaturatedLines(c, canvas.width, canvas.height, options as SaturatedLinesOptions);+ } else {+ renderStreamLines(c, canvas.width, canvas.height, options as StreamLinesOptions);+ }+ };++ renderOn(canvas);+ if (sourceCanvas) renderOn(sourceCanvas);++ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);+ updateLayerThumbnail(activeLayerId, true);+ pushHistoryStep('brush', `Manga Effect (${type})`, beforeImageData, afterImageData, activeLayerId);+ showToast(`Applied manga ${type} lines`);+ },+ [getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep, showToast]+ );+const handleInsert3DRasterLayer = useCallback((layer: LayerItem, canvas: HTMLCanvasElement) => {pasteLayerFromCanvas(canvas, layer.name, layer.blendMode, layer.opacity, layer.id);@@ -2795,6 +2973,35 @@ export function App() {});return;}++ if (tool === 'balloon') {+ e.preventDefault();+ const newBalloon = createDefaultSpeechBalloon(+ Math.round(pt.x - 100),+ Math.round(pt.y - 70),+ 200,+ 140,+ balloonSettings.shape+ );+ newBalloon.strokeWidth = balloonSettings.strokeWidth;+ newBalloon.strokeColor = primaryColor || '#000000';+ newBalloon.fillColor = balloonSettings.fillColor || '#ffffff';+ newBalloon.vertical = balloonSettings.vertical;+ setActiveBalloon(newBalloon);+ return;+ }++ if (tool === 'vector-edit') {+ e.preventDefault();+ if (!activeLayer || activeLayer.type !== 'vector' || !activeLayer.vectorStrokes) {+ showToast('Select a Vector Layer to use Correct Line tools');+ return;+ }+ isVectorEditingRef.current = true;+ lastVectorEditPtRef.current = pt;+ vectorEditBeforeStrokesRef.current = JSON.parse(JSON.stringify(activeLayer.vectorStrokes));+ return;+ }},[hasOpenDocument,@@ -2839,6 +3046,57 @@ export function App() {return;}+ if (tool === 'vector-edit') {+ if (!isVectorEditingRef.current || !activeLayer?.vectorStrokes) return;+ const pt = getCanvasCoords(e);+ const lastPt = lastVectorEditPtRef.current || pt;+ const delta = { x: pt.x - lastPt.x, y: pt.y - lastPt.y };+ lastVectorEditPtRef.current = pt;++ const radius = vectorEditSettings.radius || 35;+ let updated = false;++ const newStrokes = activeLayer.vectorStrokes.map((stroke) => {+ if (stroke.deleted) return stroke;+ if (+ pt.x < stroke.bounds.minX - radius ||+ pt.x > stroke.bounds.maxX + radius ||+ pt.y < stroke.bounds.minY - radius ||+ pt.y > stroke.bounds.maxY + radius+ ) {+ return stroke;+ }++ if (vectorEditSettings.mode === 'pinch') {+ if (Math.hypot(delta.x, delta.y) > 0.05) {+ updated = true;+ return pinchVectorStroke(stroke, pt, radius, delta);+ }+ } else if (vectorEditSettings.mode === 'width') {+ updated = true;+ return modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);+ } else if (vectorEditSettings.mode === 'simplify') {+ updated = true;+ return simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);+ }+ return stroke;+ });++ if (updated) {+ activeLayer.vectorStrokes = newStrokes;+ const canvas = getActiveCanvas();+ if (canvas) {+ const ctx = get2DContext(canvas);+ if (ctx) {+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ renderVectorLayer(ctx, newStrokes);+ updateLayerThumbnail(activeLayerId, true);+ }+ }+ }+ return;+ }+if (tool === 'liquify') {if (!isLiquifyingRef.current) return;const pt = getCanvasCoords(e);@@ -3227,6 +3485,23 @@ export function App() {}return;}++ if (tool === 'vector-edit' && isVectorEditingRef.current) {+ isVectorEditingRef.current = false;+ if (activeLayer?.vectorStrokes && vectorEditBeforeStrokesRef.current) {+ pushHistoryStep(+ 'brush',+ `Correct Line (${vectorEditSettings.mode})`,+ null,+ null,+ activeLayerId,+ undefined,+ undefined,+ { before: vectorEditBeforeStrokesRef.current, after: [...activeLayer.vectorStrokes] }+ );+ }+ return;+ }},[tool,@@ -4259,6 +4534,13 @@ export function App() {disabled: !hasOpenDocument,onClick: handleExportImage,},+ {+ id: 'file-export-webtoon',+ label: 'Export Webtoon Chapter Slices (.zip)...',+ icon: <Archive className="w-3.5 h-3.5 text-cyan-400" />,+ disabled: !hasOpenDocument,+ onClick: () => setIsWebtoonExportModalOpen(true),+ },{id: 'file-div-2',label: '',@@ -5008,6 +5290,116 @@ export function App() {prev ? { ...prev, snapEnabled: !prev.snapEnabled } : null),},+ {+ id: 'view-div-webtoon',+ label: '',+ divider: true,+ },+ {+ id: 'view-webtoon-mode',+ label: isWebtoonMode ? 'Exit Webtoon Studio Mode' : 'Webtoon Studio Mode (9:16 Mockup)',+ icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,+ disabled: !hasOpenDocument,+ onClick: () => setIsWebtoonMode((prev) => !prev),+ },+ ],+ },+ {+ id: 'manga',+ label: 'Manga',+ items: [+ {+ id: 'manga-effects-generator',+ label: 'Manga Effect Lines Generator...',+ icon: <Sparkles className="w-3.5 h-3.5 text-amber-400" />,+ disabled: !hasOpenDocument,+ onClick: () => setIsMangaEffectsModalOpen(true),+ },+ {+ id: 'manga-balloon-tool',+ label: 'Parametric Speech Balloon Tool',+ icon: <MessageSquare className="w-3.5 h-3.5 text-cyan-400" />,+ disabled: !hasOpenDocument,+ onClick: () => handleSelectTool('balloon'),+ },+ {+ id: 'manga-correct-line',+ label: 'Correct Line (Vector Pinch/Width/Simplify)',+ icon: <Spline className="w-3.5 h-3.5 text-indigo-400" />,+ disabled: !hasOpenDocument,+ onClick: () => handleSelectTool('vector-edit'),+ },+ {+ id: 'manga-div-webtoon',+ label: '',+ divider: true,+ },+ {+ id: 'manga-webtoon-toggle',+ label: isWebtoonMode ? 'Exit Webtoon Studio Mode' : 'Webtoon Studio Mode (9:16 Simulator)',+ icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,+ disabled: !hasOpenDocument,+ onClick: () => setIsWebtoonMode((prev) => !prev),+ },+ {+ id: 'manga-webtoon-export',+ label: 'Export Webtoon Chapter Slices (.zip)...',+ icon: <Archive className="w-3.5 h-3.5 text-sky-400" />,+ disabled: !hasOpenDocument,+ onClick: () => setIsWebtoonExportModalOpen(true),+ },+ ],+ },+ {+ id: 'animation',+ label: 'Animation',+ items: [+ {+ id: 'anim-toggle-timeline',+ label: activeAnimationTimeline ? 'Hide Animation Timeline' : 'Show Animation Timeline',+ shortcut: 'Ctrl+Alt+A',+ icon: <Film className="w-3.5 h-3.5 text-emerald-400" />,+ disabled: !hasOpenDocument,+ onClick: () => {+ if (activeAnimationTimeline) {+ handleUpdateAnimationTimeline(null);+ } else {+ const tl = createDefaultAnimationTimeline(layers);+ handleUpdateAnimationTimeline(tl);+ }+ },+ },+ {+ id: 'anim-new-cel',+ label: 'Add Cel to Current Frame',+ shortcut: 'Alt+C',+ icon: <Plus className="w-3.5 h-3.5" />,+ disabled: !hasOpenDocument || !activeAnimationTimeline,+ onClick: () => {+ if (activeAnimationTimeline) {+ handleAddAnimationCel(activeAnimationTimeline.currentFrame);+ }+ },+ },+ {+ id: 'anim-toggle-onion',+ label: activeAnimationTimeline?.onionSkin.enabled+ ? 'Disable Onion Skinning'+ : 'Enable Onion Skinning',+ icon: <Layers className="w-3.5 h-3.5 text-purple-400" />,+ disabled: !hasOpenDocument || !activeAnimationTimeline,+ onClick: () => {+ if (activeAnimationTimeline) {+ handleUpdateAnimationTimeline({+ ...activeAnimationTimeline,+ onionSkin: {+ ...activeAnimationTimeline.onionSkin,+ enabled: !activeAnimationTimeline.onionSkin.enabled,+ },+ });+ }+ },+ },],},{@@ -5213,6 +5605,11 @@ export function App() {onFillScreentone={handleFillScreentone}liquifySettings={liquifySettings}onUpdateLiquifySettings={handleUpdateLiquifySettings}+ balloonSettings={balloonSettings}+ onUpdateBalloonSettings={(newSettings) => setBalloonSettings((prev) => ({ ...prev, ...newSettings }))}+ vectorEditSettings={vectorEditSettings}+ onUpdateVectorEditSettings={(newSettings) => setVectorEditSettings((prev) => ({ ...prev, ...newSettings }))}+ onOpenMangaEffects={() => setIsMangaEffectsModalOpen(true)}wandSettings={wandSettings}onUpdateWandSettings={(newSettings) => setWandSettings((prev) => ({ ...prev, ...newSettings }))}onExpandSelection={handleExpandSelection}@@ -5305,6 +5702,18 @@ export function App() {setInitial3DFile(null);}}onInsertRasterLayer={handleInsert3DRasterLayer}+ isWebtoonMode={isWebtoonMode}+ onToggleWebtoonMode={() => setIsWebtoonMode((prev) => !prev)}+ onOpenWebtoonExport={() => setIsWebtoonExportModalOpen(true)}+ activeBalloon={activeBalloon}+ onUpdateBalloon={(updater) => setActiveBalloon((prev) => (prev ? updater(prev) : null))}+ onConfirmBalloon={handleConfirmBalloon}+ onDeleteBalloon={handleDeleteBalloon}+ animationTimeline={activeAnimationTimeline}+ onUpdateAnimationTimeline={handleUpdateAnimationTimeline}+ onAddAnimationCel={handleAddAnimationCel}+ onDeleteAnimationCel={handleDeleteAnimationCel}+ onSelectCelLayer={setActiveLayerId}/></div>@@ -5513,6 +5922,25 @@ export function App() {isOpen={!appSettings.hasPromptedName && !appSettings.userName}onSaveName={handleSaveFirstTimeName}/>++ {/* Manga Effect Lines Generator Modal */}+ <MangaEffectsModal+ isOpen={isMangaEffectsModalOpen}+ onClose={() => setIsMangaEffectsModalOpen(false)}+ canvasWidth={dimensions.width}+ canvasHeight={dimensions.height}+ onApply={handleApplyMangaEffects}+ />++ {/* Webtoon Chapter Slicer & Zip Exporter Modal */}+ <WebtoonExportModal+ isOpen={isWebtoonExportModalOpen}+ onClose={() => setIsWebtoonExportModalOpen(false)}+ getActiveCanvas={getActiveCanvas}+ canvasWidth={dimensions.width}+ canvasHeight={dimensions.height}+ documentTitle={documents.find((d) => d.id === activeDocumentId)?.name || 'webtoon_chapter'}+ /></div>);}diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsxnew file mode 100644index 0000000..71b39a6--- /dev/null+++ b/src/components/AnimationTimeline.tsx@@ -0,0 +1,668 @@+import React, { useState, useEffect, useRef, useCallback } from 'react';+import {+ Play,+ Pause,+ RotateCcw,+ Plus,+ Trash2,+ Download,+ ChevronLeft,+ ChevronRight,+ Repeat,+ Layers,+ Sparkles,+ X,+ Film,+} from 'lucide-react';+import { AnimationTimeline as TimelineData, LayerItem, AnimationExportFormat } from '../types/editor';+import {+ exportAnimationToGif,+ exportAnimationToApng,+ exportAnimationToVideo,+ exportAnimationToPngZip,+ downloadBlob,+} from '../utils/animationEngine';++export interface AnimationTimelineProps {+ timeline: TimelineData;+ onChangeTimeline: (timeline: TimelineData) => void;+ layers: LayerItem[];+ layerCanvasesMap?: Map<string, HTMLCanvasElement>;+ dimensions: { width: number; height: number };+ onAddCel: (frameIndex: number) => void;+ onDeleteCel: (frameIndex: number) => void;+ onSelectCelLayer?: (layerId: string) => void;+ onClose?: () => void;+}++export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({+ timeline,+ onChangeTimeline,+ layers,+ layerCanvasesMap = new Map(),+ dimensions,+ onAddCel,+ onDeleteCel,+ onSelectCelLayer,+ onClose,+}) => {+ const [isPlaying, setIsPlaying] = useState<boolean>(false);+ const [showOnionSettings, setShowOnionSettings] = useState<boolean>(false);+ const [showExportModal, setShowExportModal] = useState<boolean>(false);+ const [exportFormat, setExportFormat] = useState<AnimationExportFormat>('gif');+ const [isExporting, setIsExporting] = useState<boolean>(false);+ const [exportProgress, setExportProgress] = useState<string>('');++ const scrubberRef = useRef<HTMLDivElement | null>(null);+ const playTimerRef = useRef<number | null>(null);++ // Playback timer loop+ useEffect(() => {+ if (!isPlaying) {+ if (playTimerRef.current !== null) {+ clearInterval(playTimerRef.current);+ playTimerRef.current = null;+ }+ return;+ }++ const intervalMs = Math.max(10, Math.round(1000 / timeline.fps));+ playTimerRef.current = window.setInterval(() => {+ onChangeTimeline({+ ...timeline,+ currentFrame:+ timeline.currentFrame + 1 >= timeline.totalFrames+ ? timeline.loop+ ? 0+ : timeline.totalFrames - 1+ : timeline.currentFrame + 1,+ });++ if (!timeline.loop && timeline.currentFrame + 1 >= timeline.totalFrames) {+ setIsPlaying(false);+ }+ }, intervalMs);++ return () => {+ if (playTimerRef.current !== null) {+ clearInterval(playTimerRef.current);+ playTimerRef.current = null;+ }+ };+ }, [isPlaying, timeline, onChangeTimeline]);++ // Synchronize active cel layer when frame changes+ useEffect(() => {+ const celId = timeline.cels[timeline.currentFrame];+ if (celId && onSelectCelLayer) {+ onSelectCelLayer(celId);+ }+ }, [timeline.currentFrame, timeline.cels, onSelectCelLayer]);++ // Handle Scrub Click/Drag+ const handleScrub = useCallback(+ (clientX: number) => {+ if (!scrubberRef.current) return;+ const rect = scrubberRef.current.getBoundingClientRect();+ const clickX = Math.max(0, Math.min(rect.width, clientX - rect.left));+ const frameRatio = clickX / rect.width;+ const newFrame = Math.max(0, Math.min(timeline.totalFrames - 1, Math.floor(frameRatio * timeline.totalFrames)));++ onChangeTimeline({+ ...timeline,+ currentFrame: newFrame,+ });+ },+ [timeline, onChangeTimeline]+ );++ const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {+ e.preventDefault();+ handleScrub(e.clientX);++ const onPointerMove = (ev: PointerEvent) => handleScrub(ev.clientX);+ const onPointerUp = () => {+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ };++ window.addEventListener('pointermove', onPointerMove);+ window.addEventListener('pointerup', onPointerUp);+ };++ // Keyboard navigation shortcuts+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;++ if (e.code === 'Space') {+ e.preventDefault();+ setIsPlaying((p) => !p);+ } else if (e.code === 'ArrowLeft') {+ e.preventDefault();+ onChangeTimeline({+ ...timeline,+ currentFrame: Math.max(0, timeline.currentFrame - 1),+ });+ } else if (e.code === 'ArrowRight') {+ e.preventDefault();+ onChangeTimeline({+ ...timeline,+ currentFrame: Math.min(timeline.totalFrames - 1, timeline.currentFrame + 1),+ });+ }+ };++ window.addEventListener('keydown', handleKeyDown);+ return () => window.removeEventListener('keydown', handleKeyDown);+ }, [timeline, onChangeTimeline]);++ // Export Action+ const handleExport = async () => {+ setIsExporting(true);+ setExportProgress('Encoding frames...');++ try {+ const onProgress = (current: number, total: number) => {+ setExportProgress(`Rendering ${current}/${total}...`);+ };++ let blob: Blob;+ let filename = `animation_${Date.now()}`;++ if (exportFormat === 'gif') {+ blob = await exportAnimationToGif(timeline, layers, layerCanvasesMap, dimensions, onProgress);+ filename += '.gif';+ } else if (exportFormat === 'apng') {+ blob = await exportAnimationToApng(timeline, layers, layerCanvasesMap, dimensions, onProgress);+ filename += '.png';+ } else if (exportFormat === 'webm' || exportFormat === 'mp4') {+ blob = await exportAnimationToVideo(timeline, layers, layerCanvasesMap, dimensions, onProgress);+ filename += exportFormat === 'mp4' ? '.mp4' : '.webm';+ } else {+ blob = await exportAnimationToPngZip(timeline, layers, layerCanvasesMap, dimensions, onProgress);+ filename += '.zip';+ }++ downloadBlob(blob, filename);+ setShowExportModal(false);+ } catch (err) {+ console.error('[Animation Export Failed]:', err);+ } finally {+ setIsExporting(false);+ setExportProgress('');+ }+ };++ const currentCelId = timeline.cels[timeline.currentFrame];+ const currentCelLayer = currentCelId ? layers.find((l) => l.id === currentCelId) : null;++ return (+ <div className="absolute inset-x-0 bottom-0 z-40 bg-[#17191e]/95 backdrop-blur-md border-t border-[#2e323b] shadow-2xl flex flex-col select-none text-xs text-gray-300">+ {/* 1. Header & Transport Controls Dock */}+ <div className="flex items-center justify-between px-3 py-1.5 border-b border-[#242730] bg-[#1a1d24]">+ {/* Playback Transport */}+ <div className="flex items-center space-x-1.5">+ <button+ type="button"+ onClick={() => onChangeTimeline({ ...timeline, currentFrame: 0 })}+ className="p-1 hover:bg-white/10 rounded text-gray-400 hover:text-white"+ title="First Frame (Home)"+ >+ <RotateCcw className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={() =>+ onChangeTimeline({+ ...timeline,+ currentFrame: Math.max(0, timeline.currentFrame - 1),+ })+ }+ className="p-1 hover:bg-white/10 rounded text-gray-400 hover:text-white"+ title="Previous Frame (Left Arrow)"+ >+ <ChevronLeft className="w-4 h-4" />+ </button>+ <button+ type="button"+ onClick={() => setIsPlaying(!isPlaying)}+ className={`p-1.5 px-3 rounded font-medium flex items-center space-x-1.5 shadow-md transition-colors ${+ isPlaying+ ? 'bg-amber-600 hover:bg-amber-500 text-white'+ : 'bg-emerald-600 hover:bg-emerald-500 text-white'+ }`}+ title="Play / Pause (Space)"+ >+ {isPlaying ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}+ <span className="text-[11px] font-semibold">{isPlaying ? 'Pause' : 'Play'}</span>+ </button>+ <button+ type="button"+ onClick={() =>+ onChangeTimeline({+ ...timeline,+ currentFrame: Math.min(timeline.totalFrames - 1, timeline.currentFrame + 1),+ })+ }+ className="p-1 hover:bg-white/10 rounded text-gray-400 hover:text-white"+ title="Next Frame (Right Arrow)"+ >+ <ChevronRight className="w-4 h-4" />+ </button>++ {/* Loop Toggle */}+ <button+ type="button"+ onClick={() => onChangeTimeline({ ...timeline, loop: !timeline.loop })}+ className={`p-1 px-2 rounded border border-white/5 flex items-center space-x-1 ${+ timeline.loop ? 'bg-sky-600/30 text-sky-300 ring-1 ring-sky-400' : 'text-gray-400 hover:bg-white/10'+ }`}+ title="Loop Playback"+ >+ <Repeat className="w-3 h-3" />+ <span className="text-[10px]">Loop</span>+ </button>++ {/* Frame Rate FPS Selector */}+ <div className="flex items-center space-x-1 bg-[#22252c] rounded px-2 py-0.5 border border-white/5">+ <span className="text-[10px] text-gray-400 font-mono">FPS:</span>+ <select+ value={timeline.fps}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ fps: parseInt(e.target.value, 10),+ })+ }+ className="bg-transparent text-white font-mono text-[11px] outline-none cursor-pointer"+ >+ {[6, 8, 12, 16, 24, 30, 60].map((rate) => (+ <option key={rate} value={rate} className="bg-[#1e2129]">+ {rate} fps+ </option>+ ))}+ </select>+ </div>++ {/* Frame Ticker Counter */}+ <div className="font-mono text-cyan-400 bg-[#14161b] px-2.5 py-0.5 rounded border border-[#2a2d36] text-[11px] tracking-wider">+ {String(timeline.currentFrame + 1).padStart(3, '0')} / {String(timeline.totalFrames).padStart(3, '0')}+ </div>+ </div>++ {/* Cel & Onion Skin Tools */}+ <div className="flex items-center space-x-2">+ {/* Add Cel Button */}+ <button+ type="button"+ onClick={() => onAddCel(timeline.currentFrame)}+ className="flex items-center space-x-1 px-2.5 py-1 bg-blue-600 hover:bg-blue-500 text-white rounded font-medium shadow-sm"+ title="Add Cel for Current Frame"+ >+ <Plus className="w-3.5 h-3.5" />+ <span className="text-[11px]">Add Cel</span>+ </button>++ {/* Delete Cel Button */}+ {currentCelId && (+ <button+ type="button"+ onClick={() => onDeleteCel(timeline.currentFrame)}+ className="p-1 hover:bg-red-500/20 text-gray-400 hover:text-red-400 rounded transition-colors"+ title="Delete Cel from Current Frame"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ )}++ {/* Onion Skin Quick Settings Popover */}+ <div className="relative">+ <button+ type="button"+ onClick={() => setShowOnionSettings(!showOnionSettings)}+ className={`flex items-center space-x-1 px-2 py-1 rounded border border-white/5 transition-colors ${+ timeline.onionSkin.enabled+ ? 'bg-purple-600/30 text-purple-300 ring-1 ring-purple-400'+ : 'text-gray-400 hover:bg-white/10'+ }`}+ title="Configure Colored Onion Skinning"+ >+ <Layers className="w-3.5 h-3.5" />+ <span className="text-[11px]">Onion Skin</span>+ </button>++ {showOnionSettings && (+ <div className="absolute bottom-full mb-2 right-0 bg-[#1b1e24] border border-purple-500/40 rounded-xl p-3 shadow-2xl z-50 flex flex-col space-y-2.5 w-64">+ <div className="flex items-center justify-between">+ <span className="font-semibold text-purple-300 text-xs flex items-center space-x-1">+ <Sparkles className="w-3.5 h-3.5" />+ <span>Colored Onion Skin</span>+ </span>+ <label className="flex items-center space-x-1.5 cursor-pointer">+ <input+ type="checkbox"+ checked={timeline.onionSkin.enabled}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ enabled: e.target.checked,+ },+ })+ }+ className="accent-purple-500"+ />+ <span className="text-[10px] text-gray-300">Enabled</span>+ </label>+ </div>++ {/* Prior Frames Settings (Cyan/Red) */}+ <div className="flex items-center justify-between text-[11px] text-gray-300">+ <span>Prior Frames ({timeline.onionSkin.prevFrames}):</span>+ <div className="flex items-center space-x-2">+ <input+ type="color"+ value={timeline.onionSkin.prevTint}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ prevTint: e.target.value,+ },+ })+ }+ className="w-5 h-5 rounded cursor-pointer border-0 bg-transparent"+ />+ <input+ type="range"+ min="1"+ max="5"+ value={timeline.onionSkin.prevFrames}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ prevFrames: parseInt(e.target.value, 10),+ },+ })+ }+ className="w-16 accent-cyan-400 h-1"+ />+ </div>+ </div>++ {/* Next Frames Settings (Magenta/Blue) */}+ <div className="flex items-center justify-between text-[11px] text-gray-300">+ <span>Next Frames ({timeline.onionSkin.nextFrames}):</span>+ <div className="flex items-center space-x-2">+ <input+ type="color"+ value={timeline.onionSkin.nextTint}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ nextTint: e.target.value,+ },+ })+ }+ className="w-5 h-5 rounded cursor-pointer border-0 bg-transparent"+ />+ <input+ type="range"+ min="1"+ max="5"+ value={timeline.onionSkin.nextFrames}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ nextFrames: parseInt(e.target.value, 10),+ },+ })+ }+ className="w-16 accent-pink-500 h-1"+ />+ </div>+ </div>++ {/* Base Opacity */}+ <div className="flex items-center justify-between text-[11px] text-gray-300">+ <span>Base Opacity:</span>+ <div className="flex items-center space-x-2">+ <input+ type="range"+ min="0.1"+ max="0.8"+ step="0.05"+ value={timeline.onionSkin.opacity}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ onionSkin: {+ ...timeline.onionSkin,+ opacity: parseFloat(e.target.value),+ },+ })+ }+ className="w-24 accent-purple-500 h-1"+ />+ <span className="font-mono text-[10px] w-6 text-right">+ {Math.round(timeline.onionSkin.opacity * 100)}%+ </span>+ </div>+ </div>+ </div>+ )}+ </div>++ {/* Total Frames Adjuster */}+ <div className="flex items-center space-x-1 bg-[#22252c] rounded px-1.5 py-0.5 border border-white/5">+ <span className="text-[10px] text-gray-400">Total:</span>+ <input+ type="number"+ min="2"+ max="240"+ value={timeline.totalFrames}+ onChange={(e) =>+ onChangeTimeline({+ ...timeline,+ totalFrames: Math.max(2, Math.min(240, parseInt(e.target.value, 10) || 24)),+ })+ }+ className="w-10 bg-transparent font-mono text-white text-center text-[11px] outline-none"+ />+ </div>++ {/* Export Video Modal Button */}+ <button+ type="button"+ onClick={() => setShowExportModal(true)}+ className="flex items-center space-x-1 px-2.5 py-1 bg-emerald-600 hover:bg-emerald-500 text-white rounded font-medium shadow-sm"+ title="Export Animation"+ >+ <Download className="w-3.5 h-3.5" />+ <span className="text-[11px]">Export</span>+ </button>++ {/* Close Timeline */}+ {onClose && (+ <button+ type="button"+ onClick={onClose}+ className="p-1 text-gray-400 hover:text-white hover:bg-white/10 rounded transition-colors"+ title="Close Timeline Dock"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ </div>++ {/* 2. Interactive Scrubber Timeline Track */}+ <div className="px-3 py-2 flex flex-col space-y-1 bg-[#14161b]">+ {/* Frame Ruler Numbers */}+ <div+ ref={scrubberRef}+ onPointerDown={handlePointerDown}+ className="relative h-14 bg-[#1b1e25] rounded border border-[#2d313b] cursor-pointer overflow-hidden flex flex-col justify-between"+ >+ {/* Top Frame Tick Ruler */}+ <div className="relative h-5 border-b border-[#292c36] bg-[#20242d] flex items-center">+ {Array.from({ length: timeline.totalFrames }).map((_, f) => (+ <div+ key={f}+ style={{+ width: `${100 / timeline.totalFrames}%`,+ }}+ className={`h-full border-r border-[#2d313b] flex items-center justify-center text-[9px] font-mono select-none ${+ f % 5 === 0 ? 'text-gray-300 font-bold' : 'text-gray-500 text-[8px]'+ }`}+ >+ {f % 2 === 0 || timeline.totalFrames <= 24 ? f + 1 : ''}+ </div>+ ))}+ </div>++ {/* Cel Slots Track */}+ <div className="relative h-9 flex items-center">+ {Array.from({ length: timeline.totalFrames }).map((_, f) => {+ const hasCel = !!timeline.cels[f];+ const isCurrent = timeline.currentFrame === f;++ return (+ <div+ key={f}+ style={{+ width: `${100 / timeline.totalFrames}%`,+ }}+ className={`h-full border-r border-[#262933] flex items-center justify-center p-0.5 transition-colors ${+ isCurrent ? 'bg-sky-500/10' : ''+ }`}+ >+ {hasCel ? (+ <div+ className={`w-full h-5 rounded-[2px] flex items-center justify-center text-[9px] font-mono font-medium shadow-sm truncate ${+ isCurrent+ ? 'bg-sky-500 text-white font-bold ring-1 ring-white'+ : 'bg-[#3b4252] text-gray-200 hover:bg-[#434c5e]'+ }`}+ title={`Frame ${f + 1}: Cel Assigned`}+ >+ ●+ </div>+ ) : (+ <div className="w-1 h-1 rounded-full bg-gray-600/40" />+ )}+ </div>+ );+ })}+ </div>++ {/* Scrub Playhead Red Line */}+ <div+ className="absolute top-0 bottom-0 pointer-events-none z-20 transition-all duration-75 flex flex-col items-center"+ style={{+ left: `${((timeline.currentFrame + 0.5) / timeline.totalFrames) * 100}%`,+ transform: 'translateX(-50%)',+ }}+ >+ <div className="w-3 h-2 bg-red-500 rounded-b shadow-[0_0_8px_rgba(239,68,68,0.8)]" />+ <div className="w-[2px] h-full bg-red-500" />+ </div>+ </div>++ {/* Cel Info Bar */}+ <div className="flex items-center justify-between text-[10px] text-gray-400 px-1">+ <div className="flex items-center space-x-2">+ <span>+ Active Cel:{' '}+ {currentCelLayer ? (+ <span className="text-cyan-400 font-medium font-mono">{currentCelLayer.name}</span>+ ) : (+ <span className="text-gray-500 italic">None (Drawing creates new frame cel)</span>+ )}+ </span>+ </div>+ <div className="flex items-center space-x-3 text-gray-500">+ <span>Click/drag scrubber to navigate</span>+ <span>•</span>+ <span>Space: Play/Pause</span>+ <span>•</span>+ <span>← / →: Prev/Next frame</span>+ </div>+ </div>+ </div>++ {/* 3. Export Modal */}+ {showExportModal && (+ <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center">+ <div className="bg-[#1b1e25] border border-white/10 rounded-xl p-5 shadow-2xl w-84 flex flex-col space-y-4">+ <div className="flex items-center justify-between">+ <span className="text-sm font-semibold text-white flex items-center space-x-1.5">+ <Film className="w-4 h-4 text-emerald-400" />+ <span>Export Animation</span>+ </span>+ <button+ type="button"+ onClick={() => setShowExportModal(false)}+ className="text-gray-400 hover:text-white"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ <div className="flex flex-col space-y-2">+ <label className="text-xs text-gray-300">Format</label>+ <div className="grid grid-cols-2 gap-2 text-xs">+ {(+ [+ ['gif', 'Animated GIF'],+ ['apng', 'Animated PNG (APNG)'],+ ['webm', 'WebM Video'],+ ['png-zip', 'Numbered PNGs (.zip)'],+ ] as Array<[AnimationExportFormat, string]>+ ).map(([fmt, label]) => (+ <button+ key={fmt}+ type="button"+ onClick={() => setExportFormat(fmt)}+ className={`py-2 px-2.5 rounded text-left border transition-colors ${+ exportFormat === fmt+ ? 'bg-emerald-600/30 border-emerald-500 text-white font-medium ring-1 ring-emerald-500'+ : 'bg-[#252831] border-white/5 text-gray-400 hover:bg-white/5'+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ </div>++ <div className="text-[11px] text-gray-400 space-y-1 bg-[#14161b] p-2.5 rounded border border-white/5 font-mono">+ <div>Resolution: {dimensions.width} × {dimensions.height} px</div>+ <div>Frame Rate: {timeline.fps} FPS</div>+ <div>Total Frames: {timeline.totalFrames} frames</div>+ </div>++ <button+ type="button"+ onClick={handleExport}+ disabled={isExporting}+ className="w-full py-2 bg-emerald-600 hover:bg-emerald-500 text-white font-medium rounded text-xs transition-colors shadow-lg flex items-center justify-center space-x-1.5 disabled:opacity-50"+ >+ <Download className="w-4 h-4" />+ <span>{isExporting ? exportProgress || 'Exporting...' : 'Start Export'}</span>+ </button>+ </div>+ </div>+ )}+ </div>+ );+};diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsxindex c2e6895..fe4c854 100644--- a/src/components/CanvasArea.tsx+++ b/src/components/CanvasArea.tsx@@ -1,4 +1,4 @@-import React, { useState, useEffect, useRef } from 'react';+import React, { useState, useEffect, useRef, useMemo } from 'react';import {CanvasDimensions,BrushSettings,@@ -8,11 +8,14 @@ import {TextSettings,ToolType,LiquifySettings,+ SpeechBalloon,} from '../types/editor';import { ROTATE_CURSOR_CSS } from '../hooks/useCanvasNavigation';import { SelectionOverlay } from './SelectionOverlay';import { TransformOverlay } from './TransformOverlay';import { TextEditorOverlay } from './TextEditorOverlay';+import { SpeechBalloonOverlay } from './SpeechBalloonOverlay';+import { SmartphoneViewportSimulator } from './SmartphoneViewportSimulator';import { PerspectiveRulerOverlay } from './PerspectiveRulerOverlay';import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';import { Local3DContainer } from './Local3DContainer';@@ -20,6 +23,10 @@ import { ViewportCompositor } from '../utils/compositor';import { globalTileGrid } from '../utils/tileEngine';import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../utils/brushOutline';import { preloadTipImage } from '../utils/brushStorage';+import { Smartphone, Archive } from 'lucide-react';+import { AnimationTimeline } from './AnimationTimeline';+import { AnimationTimeline as AnimationTimelineType } from '../types/editor';+import { getOnionSkinFrames } from '../utils/animationEngine';const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;@@ -88,6 +95,18 @@ interface CanvasAreaProps {onInsertRasterLayer?: (layer: LayerItem, canvas: HTMLCanvasElement) => void;onBake3DSuccess?: (layer: LayerItem) => void;liquifySettings?: LiquifySettings;+ isWebtoonMode?: boolean;+ onToggleWebtoonMode?: () => void;+ onOpenWebtoonExport?: () => void;+ activeBalloon?: SpeechBalloon | null;+ onUpdateBalloon?: (updater: (prev: SpeechBalloon) => SpeechBalloon) => void;+ onConfirmBalloon?: () => void;+ onDeleteBalloon?: () => void;+ animationTimeline?: AnimationTimelineType | null;+ onUpdateAnimationTimeline?: (timeline: AnimationTimelineType) => void;+ onAddAnimationCel?: (frameIndex: number) => void;+ onDeleteAnimationCel?: (frameIndex: number) => void;+ onSelectCelLayer?: (layerId: string) => void;}export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({@@ -104,6 +123,13 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({isRotating,onStartPan,onStartRotate,+ isWebtoonMode = false,+ onToggleWebtoonMode,+ onOpenWebtoonExport,+ activeBalloon = null,+ onUpdateBalloon,+ onConfirmBalloon,+ onDeleteBalloon,isHovering: _isHovering,cursorPos: _cursorPos,onPointerDown,@@ -154,6 +180,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({onInsertRasterLayer,onBake3DSuccess,liquifySettings,+ animationTimeline = null,+ onUpdateAnimationTimeline,+ onAddAnimationCel,+ onDeleteAnimationCel,+ onSelectCelLayer,}) => {const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;@@ -309,6 +340,27 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({};}, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef, tool]);+ // Compute colored onion skin frames and active cel isolation for animation+ const onionSkinFrames = useMemo(() => {+ if (!animationTimeline || !animationTimeline.onionSkin?.enabled) return [];+ return getOnionSkinFrames(animationTimeline);+ }, [animationTimeline]);++ const effectiveLayers = useMemo(() => {+ if (!animationTimeline) return layers;+ const currentCelId = animationTimeline.cels[animationTimeline.currentFrame];+ const allCelIds = new Set(Object.values(animationTimeline.cels));+ return layers.map((layer) => {+ if (allCelIds.has(layer.id)) {+ return {+ ...layer,+ visible: layer.id === currentCelId && layer.visible,+ };+ }+ return layer;+ });+ }, [layers, animationTimeline]);+// Unified GPU Viewport Compositorconst viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);const compositorRef = useRef<ViewportCompositor | null>(null);@@ -332,11 +384,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({}compositorRef.current.resize(w, h);compositorRef.current.render(- layers,+ effectiveLayers,{ pan, zoom, rotation },dimensions,globalTileGrid,- { dimensions, showCheckerboard, devicePixelRatio: dpr }+ { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames });}@@ -350,7 +402,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({updateCanvasSizes();window.addEventListener('resize', updateCanvasSizes);return () => window.removeEventListener('resize', updateCanvasSizes);- }, [viewportRef, effectiveDraftCanvasRef, layers, pan, zoom, rotation, dimensions, showCheckerboard]);+ }, [viewportRef, effectiveDraftCanvasRef, effectiveLayers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames]);// Render scene using Unified GPU Viewport CompositoruseEffect(() => {@@ -380,13 +432,13 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({const dpr = window.devicePixelRatio || 1;compositorRef.current.render(- layers,+ effectiveLayers,{ pan, zoom, rotation },dimensions,globalTileGrid,- { dimensions, showCheckerboard, devicePixelRatio: dpr }+ { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames });- }, [layers, pan, zoom, rotation, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas]);+ }, [effectiveLayers, layers, pan, zoom, rotation, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas, onionSkinFrames]);// Event-Driven Compositor Invalidation via SparseTileGrid subscriptionuseEffect(() => {@@ -395,11 +447,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({if (compositorRef.current) {const dpr = window.devicePixelRatio || 1;compositorRef.current.render(- layers,+ effectiveLayers,{ pan, zoom, rotation },dimensions,globalTileGrid,- { dimensions, showCheckerboard, devicePixelRatio: dpr }+ { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames });}};@@ -425,7 +477,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({unsubscribe();if (rafId !== null) cancelAnimationFrame(rafId);};- }, [layers, pan, zoom, rotation, dimensions, showCheckerboard]);+ }, [effectiveLayers, layers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames]);useEffect(() => {return () => {@@ -773,6 +825,17 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({/>)}+ {/* Parametric Speech Balloon Overlay */}+ {activeBalloon && (+ <SpeechBalloonOverlay+ balloon={activeBalloon}+ zoom={zoom}+ onUpdateBalloon={onUpdateBalloon || (() => {})}+ onConfirmBalloon={onConfirmBalloon || (() => {})}+ onDeleteBalloon={onDeleteBalloon || (() => {})}+ />+ )}+{/* Local-Only 3D Viewport Ghost Layer (Strictly Client-Side Isolated State) */}{is3DLayerOpen && onClose3DLayer && onInsertRasterLayer && (<Local3DContainer@@ -785,6 +848,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({onClose={onClose3DLayer}onInsertRasterLayer={onInsertRasterLayer}onBakeSuccess={onBake3DSuccess}+ perspectiveRuler={perspectiveRuler}+ onUpdatePerspectiveRuler={onUpdatePerspectiveRuler}/>)}@@ -1002,6 +1067,56 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({</div></div>)}++ {/* Floating Webtoon Mode Quick-Access Bar */}+ <div className="absolute top-3 right-4 z-40 flex items-center space-x-2 select-none">+ <button+ onClick={onToggleWebtoonMode}+ className={`px-3 py-1.5 rounded-full text-xs font-medium flex items-center space-x-1.5 shadow-lg border transition-colors cursor-pointer ${+ isWebtoonMode+ ? 'bg-[#1e382d] text-[#55eaab] border-[#2a7a5c]'+ : 'bg-[#222326]/90 text-[#aaaaaa] hover:text-white border-[#3b3d45]'+ }`}+ title="Toggle Webtoon Studio Mode (Smartphone Simulator & Vertical Scrolling)"+ >+ <Smartphone className="w-3.5 h-3.5" />+ <span>Webtoon Mode</span>+ {isWebtoonMode && <span className="w-1.5 h-1.5 rounded-full bg-[#55eaab] animate-pulse" />}+ </button>++ {isWebtoonMode && onOpenWebtoonExport && (+ <button+ onClick={onOpenWebtoonExport}+ className="px-3 py-1.5 rounded-full text-xs font-medium bg-[#1a2d3e] hover:bg-[#234059] text-cyan-300 border border-[#2d5573] flex items-center space-x-1.5 shadow-lg transition-colors cursor-pointer"+ title="Export Chapter Slices (.zip)"+ >+ <Archive className="w-3.5 h-3.5" />+ <span>Export Slices</span>+ </button>+ )}+ </div>++ {/* Smartphone Viewport Simulator in Webtoon Mode */}+ {isWebtoonMode && (+ <SmartphoneViewportSimulator+ visible={true}+ onToggleVisible={onToggleWebtoonMode || (() => {})}+ />+ )}++ {/* 2D Frame-by-Frame Animation Timeline Scrubber Dock */}+ {animationTimeline && onUpdateAnimationTimeline && (+ <AnimationTimeline+ timeline={animationTimeline}+ onChangeTimeline={onUpdateAnimationTimeline}+ layers={layers}+ layerCanvasesMap={layerCanvasesRef?.current || new Map()}+ dimensions={dimensions}+ onAddCel={onAddAnimationCel || (() => {})}+ onDeleteCel={onDeleteAnimationCel || (() => {})}+ onSelectCelLayer={onSelectCelLayer}+ />+ )}</main>);});diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsxindex a88fb1b..cd77755 100644--- a/src/components/LeftPanel.tsx+++ b/src/components/LeftPanel.tsx@@ -38,6 +38,8 @@ import {Wand2,PenTool,Feather,+ MessageSquare,+ Spline,} from 'lucide-react';import {ToolType,@@ -50,6 +52,8 @@ import {LiquifySettings,LiquifyMode,WandSettings,+ BalloonSettings,+ VectorEditSettings,} from '../types/editor';import { LiquifyIcon } from './LiquifyIcon';import { PENCIL_CONFIGS, PencilGrade } from '../utils/pencilEngine';@@ -106,6 +110,11 @@ interface LeftPanelProps {onFillScreentone?: () => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;+ balloonSettings?: BalloonSettings;+ onUpdateBalloonSettings?: (newSettings: Partial<BalloonSettings>) => void;+ vectorEditSettings?: VectorEditSettings;+ onUpdateVectorEditSettings?: (newSettings: Partial<VectorEditSettings>) => void;+ onOpenMangaEffects?: () => void;wandSettings?: WandSettings;onUpdateWandSettings?: (newSettings: Partial<WandSettings>) => void;onExpandSelection?: (pixels: number) => void;@@ -140,6 +149,11 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({onFillScreentone: _onFillScreentone,liquifySettings,onUpdateLiquifySettings,+ balloonSettings,+ onUpdateBalloonSettings,+ vectorEditSettings,+ onUpdateVectorEditSettings,+ onOpenMangaEffects,wandSettings,onUpdateWandSettings,onExpandSelection,@@ -555,6 +569,226 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({);}+ if (currentTool === 'balloon') {+ return (+ <div className="flex-1 flex flex-col overflow-y-auto">+ <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">+ <div className="flex items-center space-x-2">+ <MessageSquare className="w-4 h-4 text-cyan-400" />+ <span className="text-xs font-semibold text-white">Speech Balloon Tool</span>+ </div>+ <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="p-3 space-y-4">+ <div className="space-y-1.5">+ <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Balloon Shape:</label>+ <div className="grid grid-cols-2 gap-1.5">+ {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (+ <button+ key={shape}+ type="button"+ onClick={() => onUpdateBalloonSettings?.({ shape })}+ className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer capitalize font-medium ${+ balloonSettings?.shape === shape+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'+ }`}+ >+ {shape.replace('-', ' ')}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1.5">+ <label className="text-[11px] font-medium text-[#aaaaaa] block">Writing Direction:</label>+ <div className="grid grid-cols-2 gap-1.5">+ <button+ type="button"+ onClick={() => onUpdateBalloonSettings?.({ vertical: false })}+ className={`py-1 px-2 rounded text-xs text-center transition-colors cursor-pointer font-medium ${+ !balloonSettings?.vertical+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'+ : 'bg-[#202226] text-[#aaaaaa] hover:text-white border border-transparent'+ }`}+ >+ Horizontal (横)+ </button>+ <button+ type="button"+ onClick={() => onUpdateBalloonSettings?.({ vertical: true })}+ className={`py-1 px-2 rounded text-xs text-center transition-colors cursor-pointer font-medium ${+ balloonSettings?.vertical+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'+ : 'bg-[#202226] text-[#aaaaaa] hover:text-white border border-transparent'+ }`}+ >+ Vertical (縦書き)+ </button>+ </div>+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label className="text-[11px] font-medium text-[#aaaaaa]">Border Width:</label>+ <span className="text-xs font-mono text-cyan-400">{balloonSettings?.strokeWidth ?? 3}px</span>+ </div>+ <input+ type="range"+ min={1}+ max={15}+ value={balloonSettings?.strokeWidth ?? 3}+ onChange={(e) => onUpdateBalloonSettings?.({ strokeWidth: Number(e.target.value) })}+ className="w-full accent-cyan-400"+ />+ </div>++ <div className="pt-2 border-t border-[#26282c] space-y-1 text-[11px] text-[#888888]">+ <p>• Click on canvas to place parametric speech balloon.</p>+ <p>• Drag handles to resize body or re-orient bezier tail.</p>+ </div>+ </div>+ </div>+ );+ }++ if (currentTool === 'vector-edit') {+ const activeMode = vectorEditSettings?.mode || 'pinch';++ return (+ <div className="flex-1 flex flex-col overflow-y-auto">+ <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">+ <div className="flex items-center space-x-2">+ <Spline className="w-4 h-4 text-cyan-400" />+ <span className="text-xs font-semibold text-white">Correct Line (Vector)</span>+ </div>+ <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="p-3 space-y-4">+ <div className="space-y-1.5">+ <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Operation Mode:</label>+ <div className="space-y-1">+ <button+ type="button"+ onClick={() => onUpdateVectorEditSettings?.({ mode: 'pinch' })}+ className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${+ activeMode === 'pinch'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'+ }`}+ >+ <span>Pinch / Reshape Line</span>+ <span className="text-[10px] text-[#777777]">Bell-curve</span>+ </button>++ <button+ type="button"+ onClick={() => onUpdateVectorEditSettings?.({ mode: 'width' })}+ className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${+ activeMode === 'width'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'+ }`}+ >+ <span>Modify Line Width</span>+ <span className="text-[10px] text-[#777777]">Local scale</span>+ </button>++ <button+ type="button"+ onClick={() => onUpdateVectorEditSettings?.({ mode: 'simplify' })}+ className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${+ activeMode === 'simplify'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'+ }`}+ >+ <span>Simplify Vector Line</span>+ <span className="text-[10px] text-[#777777]">Ramer-Douglas</span>+ </button>+ </div>+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label className="text-[11px] font-medium text-[#aaaaaa]">Influence Radius:</label>+ <span className="text-xs font-mono text-cyan-400">{vectorEditSettings?.radius ?? 30}px</span>+ </div>+ <input+ type="range"+ min={5}+ max={150}+ value={vectorEditSettings?.radius ?? 30}+ onChange={(e) => onUpdateVectorEditSettings?.({ radius: Number(e.target.value) })}+ className="w-full accent-cyan-400"+ />+ </div>++ {activeMode === 'width' && (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label className="text-[11px] font-medium text-[#aaaaaa]">Width Factor:</label>+ <span className="text-xs font-mono text-cyan-400">+ {(vectorEditSettings?.widthFactor ?? 1.5).toFixed(1)}x+ </span>+ </div>+ <input+ type="range"+ min={2}+ max={30}+ value={Math.round((vectorEditSettings?.widthFactor ?? 1.5) * 10)}+ onChange={(e) =>+ onUpdateVectorEditSettings?.({ widthFactor: Number(e.target.value) / 10 })+ }+ className="w-full accent-cyan-400"+ />+ </div>+ )}++ {activeMode === 'simplify' && (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label className="text-[11px] font-medium text-[#aaaaaa]">Reduction Tolerance:</label>+ <span className="text-xs font-mono text-cyan-400">+ {(vectorEditSettings?.simplifyTolerance ?? 2.0).toFixed(1)}px+ </span>+ </div>+ <input+ type="range"+ min={5}+ max={80}+ value={Math.round((vectorEditSettings?.simplifyTolerance ?? 2.0) * 10)}+ onChange={(e) =>+ onUpdateVectorEditSettings?.({ simplifyTolerance: Number(e.target.value) / 10 })+ }+ className="w-full accent-cyan-400"+ />+ </div>+ )}++ {onOpenMangaEffects && (+ <div className="pt-2 border-t border-[#26282c]">+ <button+ type="button"+ onClick={onOpenMangaEffects}+ className="w-full py-2 px-3 rounded bg-[#18191c] hover:bg-[#25272b] border border-[#383a40] text-cyan-300 text-xs font-medium flex items-center justify-center space-x-2 transition-colors cursor-pointer"+ >+ <Sparkles className="w-3.5 h-3.5 text-amber-400" />+ <span>Manga Effect Lines...</span>+ </button>+ </div>+ )}+ </div>+ </div>+ );+ }+if (currentTool === 'text') {return (<div className="flex-1 flex flex-col overflow-y-auto">@@ -586,6 +820,34 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({</select></div>+ <div className="space-y-1.5">+ <label className="text-[11px] font-medium text-[#aaaaaa]">Writing Direction:</label>+ <div className="grid grid-cols-2 gap-1.5">+ <button+ type="button"+ onClick={() => onUpdateTextSettings?.({ writingMode: 'horizontal-tb' })}+ className={`px-2 py-1 rounded text-xs transition-colors cursor-pointer text-center font-medium ${+ textSettings?.writingMode !== 'vertical-rl'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'+ : 'bg-[#202226] text-[#888888] hover:text-white border border-transparent'+ }`}+ >+ Horizontal (横)+ </button>+ <button+ type="button"+ onClick={() => onUpdateTextSettings?.({ writingMode: 'vertical-rl' })}+ className={`px-2 py-1 rounded text-xs transition-colors cursor-pointer text-center font-medium ${+ textSettings?.writingMode === 'vertical-rl'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'+ : 'bg-[#202226] text-[#888888] hover:text-white border border-transparent'+ }`}+ >+ Vertical (縦書き)+ </button>+ </div>+ </div>+<div className="space-y-1.5"><div className="flex items-center justify-between"><label className="text-[11px] font-medium text-[#aaaaaa]">Default Font Size:</label>@@ -1351,6 +1613,38 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({Frame Border (F)</div></button>++ {/* Speech Balloon Tool (B) */}+ <button+ onClick={() => onSelectTool('balloon')}+ title="Speech Balloon Tool"+ className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${+ currentTool === 'balloon'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'+ : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'+ }`}+ >+ <MessageSquare className="w-4 h-4" />+ <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">+ Speech Balloon+ </div>+ </button>++ {/* Correct Line (Vector Edit) Tool (Y) */}+ <button+ onClick={() => onSelectTool('vector-edit')}+ title="Correct Line (Vector Pinch/Width/Simplify)"+ className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${+ currentTool === 'vector-edit'+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'+ : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'+ }`}+ >+ <Spline className="w-4 h-4" />+ <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">+ Correct Line (Vector)+ </div>+ </button></div>{/* Bottom Swatches, Swap Button, and Hide/Show Button */}diff --git a/src/components/Local3DContainer.tsx b/src/components/Local3DContainer.tsxindex 8cfdbbb..b32ea5f 100644--- a/src/components/Local3DContainer.tsx+++ b/src/components/Local3DContainer.tsx@@ -7,7 +7,18 @@ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';import { LayerItem } from '../types/editor';-import { bake3DToRasterLayer, disposeThreeResources } from '../services/bake3DService';+import { PerspectiveRuler } from '../types/perspective';+import { calculatePerspectiveFromCamera } from '../utils/perspectiveMath';+import { bake3DToRasterLayer, bake3DToLineAndTone, disposeThreeResources } from '../services/bake3DService';+import {+ createProceduralMannequin,+ findHumanoidBones,+ solveTwoBoneIK,+ createIKHandles,+ applyPosePreset,+ HumanoidBones,+ PosePresetName,+} from '../utils/mannequin3D';import { Csp3DToolbar, Csp3DToolMode } from './Csp3DToolbar';import { LightSourceWidget, LightSettings } from './LightSourceWidget';import {@@ -22,6 +33,10 @@ import {Compass,Move,Rotate3d,+ User,+ Sliders,+ Sparkles,+ Link,} from 'lucide-react';export type ShadingMode = 'shaded' | 'smooth' | 'silhouette';@@ -37,6 +52,8 @@ export interface Local3DContainerProps {onClose: () => void;onInsertRasterLayer: (layer: LayerItem, canvas: HTMLCanvasElement) => void;onBakeSuccess?: (layer: LayerItem) => void;+ perspectiveRuler?: PerspectiveRuler | null;+ onUpdatePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;}export const Local3DContainer: React.FC<Local3DContainerProps> = ({@@ -49,6 +66,8 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({onClose,onInsertRasterLayer,onBakeSuccess,+ perspectiveRuler,+ onUpdatePerspectiveRuler,}) => {const mountRef = useRef<HTMLDivElement | null>(null);const canvasRef = useRef<HTMLCanvasElement | null>(null);@@ -68,6 +87,9 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({const ambientLightRef = useRef<THREE.AmbientLight | null>(null);const hemiLightRef = useRef<THREE.HemisphereLight | null>(null);const gridHelperRef = useRef<THREE.GridHelper | null>(null);+ const mannequinBonesRef = useRef<HumanoidBones | null>(null);+ const ikHandlesRef = useRef<Record<string, THREE.Mesh> | null>(null);+ const ikHandlesContainerRef = useRef<THREE.Group | null>(null);// Interaction Stateconst [activeToolMode, setActiveToolMode] = useState<Csp3DToolMode>('camera-orbit');@@ -75,6 +97,13 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({const [showGrid, setShowGrid] = useState<boolean>(true);const [showLightPanel, setShowLightPanel] = useState<boolean>(false);const [showCameraPresets, setShowCameraPresets] = useState<boolean>(false);+ const [isMannequinActive, setIsMannequinActive] = useState<boolean>(false);+ const [showPoseDrawer, setShowPoseDrawer] = useState<boolean>(false);+ const [showLTModal, setShowLTModal] = useState<boolean>(false);+ const [syncCameraPerspective, setSyncCameraPerspective] = useState<boolean>(true);+ const [activeIKHandle, setActiveIKHandle] = useState<string | null>(null);+ const [ltLineThreshold, setLtLineThreshold] = useState<number>(0.28);+ const [ltToneBands, setLtToneBands] = useState<2 | 3>(2);// Viewport Settingsconst [opacity, setOpacity] = useState<number>(0.85);@@ -305,7 +334,17 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({controls.enableDamping = true;controls.dampingFactor = 0.08;controls.target.set(0, 0.3, 0);- controls.update();+ controls.addEventListener('change', () => {+ if (onUpdatePerspectiveRuler && cameraRef.current) {+ const ruler = calculatePerspectiveFromCamera(+ cameraRef.current,+ dimensions.width,+ dimensions.height,+ perspectiveRuler+ );+ onUpdatePerspectiveRuler(ruler);+ }+ });controlsRef.current = controls;// 7. TransformControls for 3D In-Scene Gizmo Rings@@ -322,6 +361,27 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({}});+ transformControls.addEventListener('objectChange', () => {+ const targetObj = transformControls.object;+ if (targetObj && targetObj.name.startsWith('IKHandle_') && mannequinBonesRef.current) {+ const handleName = targetObj.name.replace('IKHandle_', '');+ const bones = mannequinBonesRef.current;+ const targetPos = targetObj.position;+ if (handleName === 'leftHand' && bones.leftUpperArm && bones.leftLowerArm && bones.leftHand) {+ solveTwoBoneIK(bones.leftUpperArm, bones.leftLowerArm, bones.leftHand, targetPos, new THREE.Vector3(0.6, 1.2, -0.4));+ } else if (handleName === 'rightHand' && bones.rightUpperArm && bones.rightLowerArm && bones.rightHand) {+ solveTwoBoneIK(bones.rightUpperArm, bones.rightLowerArm, bones.rightHand, targetPos, new THREE.Vector3(-0.6, 1.2, -0.4));+ } else if (handleName === 'leftFoot' && bones.leftUpperLeg && bones.leftLowerLeg && bones.leftFoot) {+ solveTwoBoneIK(bones.leftUpperLeg, bones.leftLowerLeg, bones.leftFoot, targetPos, new THREE.Vector3(0.12, 0.48, 0.5));+ } else if (handleName === 'rightFoot' && bones.rightUpperLeg && bones.rightLowerLeg && bones.rightFoot) {+ solveTwoBoneIK(bones.rightUpperLeg, bones.rightLowerLeg, bones.rightFoot, targetPos, new THREE.Vector3(-0.12, 0.48, 0.5));+ } else if (handleName === 'head' && bones.neck && bones.head) {+ bones.head.lookAt(targetPos);+ bones.head.updateMatrixWorld(true);+ }+ }+ });+transformControlsRef.current = transformControls;transformHelperRef.current = transformHelper;@@ -746,6 +806,20 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({applyShading(shadingMode);updateGizmoTarget();+ // Detect humanoid skinned mesh hierarchy+ const detectedBones = findHumanoidBones(model);+ if (detectedBones.hips || detectedBones.leftHand || detectedBones.rightHand || detectedBones.head) {+ mannequinBonesRef.current = detectedBones;+ setIsMannequinActive(true);+ const { container: handlesContainer, handles } = createIKHandles();+ ikHandlesRef.current = handles;+ ikHandlesContainerRef.current = handlesContainer;+ sceneRef.current?.add(handlesContainer);+ } else {+ mannequinBonesRef.current = null;+ setIsMannequinActive(false);+ }+if (cameraRef.current && controlsRef.current) {cameraRef.current.position.set(0, 0.5, 3.8);controlsRef.current.target.set(0, 0.3, 0);@@ -820,6 +894,119 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({setPerspective(1.0);};+ // Load procedural humanoid drawing mannequin+ const loadProceduralMannequin = useCallback(() => {+ if (!sceneRef.current) return;+ if (modelRootRef.current) {+ if (transformControlsRef.current) transformControlsRef.current.detach();+ disposeMeshUserData(modelRootRef.current);+ disposeThreeResources(modelRootRef.current, null);+ sceneRef.current.remove(modelRootRef.current);+ modelRootRef.current = null;+ }+ if (ikHandlesContainerRef.current) {+ sceneRef.current.remove(ikHandlesContainerRef.current);+ ikHandlesContainerRef.current = null;+ }++ const { group, bones } = createProceduralMannequin();+ const { container: handlesContainer, handles } = createIKHandles();++ mannequinBonesRef.current = bones;+ ikHandlesRef.current = handles;+ ikHandlesContainerRef.current = handlesContainer;++ group.position.set(0, 0, 0);+ modelRootRef.current = group;+ sceneRef.current.add(group);+ sceneRef.current.add(handlesContainer);++ setLoadedFileName('Mannequin (Rigged)');+ setIsMannequinActive(true);+ applyShading(shadingMode);++ if (cameraRef.current && controlsRef.current) {+ cameraRef.current.position.set(0, 1.1, 3.2);+ controlsRef.current.target.set(0, 0.9, 0);+ controlsRef.current.update();+ }+ }, [applyShading, disposeMeshUserData, shadingMode]);++ // Select an IK Target limb to manipulate+ const selectIKTarget = useCallback((targetName: string | null) => {+ setActiveIKHandle(targetName);+ if (!transformControlsRef.current || !ikHandlesRef.current) return;+ if (targetName && ikHandlesRef.current[targetName]) {+ const handleMesh = ikHandlesRef.current[targetName];+ transformControlsRef.current.setMode('translate');+ transformControlsRef.current.attach(handleMesh);+ if (transformHelperRef.current) transformHelperRef.current.visible = true;+ } else {+ transformControlsRef.current.detach();+ if (transformHelperRef.current) transformHelperRef.current.visible = false;+ }+ }, []);++ // Apply Pose Presets (Standing, Action, Sitting, Fists, Relaxed Palm)+ const handleApplyPreset = useCallback((preset: PosePresetName) => {+ if (!mannequinBonesRef.current) return;+ applyPosePreset(mannequinBonesRef.current, preset);+ if (ikHandlesRef.current) {+ const updateHandle = (name: string, bone?: THREE.Bone) => {+ if (bone && ikHandlesRef.current![name]) {+ const wp = new THREE.Vector3();+ bone.getWorldPosition(wp);+ ikHandlesRef.current![name].position.copy(wp);+ }+ };+ updateHandle('head', mannequinBonesRef.current.head);+ updateHandle('leftHand', mannequinBonesRef.current.leftHand);+ updateHandle('rightHand', mannequinBonesRef.current.rightHand);+ updateHandle('leftFoot', mannequinBonesRef.current.leftFoot);+ updateHandle('rightFoot', mannequinBonesRef.current.rightFoot);+ }+ }, []);++ // 3D LT Lineart & Screentone Extraction (3D-to-2D Line Extraction)+ const handleExtractLineAndTone = async () => {+ if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || isBaking) return;+ setIsBaking(true);+ setShowLTModal(false);++ try {+ if (transformHelperRef.current) transformHelperRef.current.visible = false;+ if (gridHelperRef.current) gridHelperRef.current.visible = false;+ if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = false;++ await bake3DToLineAndTone({+ scene: sceneRef.current,+ camera: cameraRef.current,+ dimensions,+ activeRenderer: rendererRef.current,+ baseLayerName: loadedFileName ? loadedFileName.replace(/\.[^/.]+$/, '') : '3D Model',+ lineThreshold: ltLineThreshold,+ toneBands: ltToneBands,+ toneFrequencies: [55, 60],+ toneAngles: [45, 60],+ toneDensities: [0.45, 0.2],+ disposeOnComplete: true,+ onInsertLayers: (layers, canvases) => {+ for (let i = 0; i < layers.length; i++) {+ onInsertRasterLayer(layers[i], canvases[i]);+ }+ },+ });++ onClose();+ } catch (err) {+ console.error('[3D] Failed to extract line & tone:', err);+ setIsBaking(false);+ if (gridHelperRef.current) gridHelperRef.current.visible = showGrid;+ if (transformHelperRef.current && gizmoMode !== 'none') transformHelperRef.current.visible = true;+ if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = true;+ }+ };+// Bake 3D to 2D Layer (Ensuring Gizmos & Grids are NOT baked into layer)const handleBakeTo2D = async () => {if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || isBaking) return;@@ -913,13 +1100,23 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({<p className="text-sm font-medium text-white">Import 3D Model</p><p className="text-xs text-gray-400 mt-1">Drag and drop .glb, .gltf, or .obj file, or click upload</p></div>- <button- type="button"- onClick={() => fileInputRef.current?.click()}- className="px-4 py-1.5 bg-purple-600 hover:bg-purple-500 text-white rounded text-xs font-medium transition-colors shadow-lg shadow-purple-900/30"- >- Upload Model- </button>+ <div className="flex items-center space-x-2">+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ className="px-4 py-1.5 bg-purple-600 hover:bg-purple-500 text-white rounded text-xs font-medium transition-colors shadow-lg shadow-purple-900/30"+ >+ Upload Model+ </button>+ <button+ type="button"+ onClick={loadProceduralMannequin}+ className="px-4 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs font-medium transition-colors shadow-lg shadow-blue-900/30 flex items-center space-x-1.5"+ >+ <User className="w-3.5 h-3.5" />+ <span>Insert 3D Mannequin</span>+ </button>+ </div></div></div>)}@@ -972,7 +1169,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({className="pointer-events-auto bg-[#181b20]/95 backdrop-blur-md border border-[#3b82f6]/40 shadow-2xl rounded-lg px-3 py-1.5 flex items-center space-x-2.5 text-xs text-[#cccccc]"onPointerDown={(e) => e.stopPropagation()}>- {/* Model Upload Button */}+ {/* Model & Mannequin Upload / Preset Button */}<div className="flex items-center space-x-1.5 bg-[#252830] rounded px-2 py-1 border border-white/10"><span className="text-[10px] uppercase font-semibold text-gray-400">Model</span><button@@ -980,16 +1177,29 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({onClick={() => fileInputRef.current?.click()}title="Upload 3D Model (.glb, .gltf, .obj)"className={`p-1 px-2 rounded transition-colors flex items-center space-x-1.5 ${- loadedFileName+ loadedFileName && !isMannequinActive? 'bg-purple-600 text-white hover:bg-purple-500': 'bg-purple-600/30 text-purple-300 hover:bg-purple-600 hover:text-white'}`}><Upload className="w-3.5 h-3.5" />- <span className="text-[10px] font-medium max-w-[120px] truncate">+ <span className="text-[10px] font-medium max-w-[100px] truncate">{loadedFileName || 'Upload'}</span></button>+ <button+ type="button"+ onClick={loadProceduralMannequin}+ title="Load Rigged Humanoid Drawing Mannequin"+ className={`p-1 px-2 rounded transition-colors flex items-center space-x-1.5 ${+ isMannequinActive+ ? 'bg-blue-600 text-white hover:bg-blue-500'+ : 'bg-blue-600/30 text-blue-300 hover:bg-blue-600 hover:text-white'+ }`}+ >+ <User className="w-3.5 h-3.5" />+ <span className="text-[10px] font-medium">Mannequin</span>+ </button><inputref={fileInputRef}type="file"@@ -999,6 +1209,115 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({/></div>+ {/* Poses Drawer Trigger (Standing, Action, Sitting, Fists, Relaxed Palm) */}+ {isMannequinActive && (+ <div className="relative">+ <button+ type="button"+ onClick={() => setShowPoseDrawer(!showPoseDrawer)}+ className={`flex items-center space-x-1 px-2 py-1 rounded border border-white/10 text-[10px] transition-colors ${+ showPoseDrawer ? 'bg-amber-600 text-white' : 'bg-[#252830] text-amber-300 hover:bg-white/10'+ }`}+ title="Humanoid Pose Presets"+ >+ <Sliders className="w-3.5 h-3.5" />+ <span>Poses</span>+ </button>++ {showPoseDrawer && (+ <div className="absolute top-full mt-1.5 left-0 bg-[#1b1e24] border border-[#f59e0b]/40 rounded-lg p-2 shadow-2xl z-50 flex flex-col space-y-1.5 w-44">+ <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider px-1">+ Pose Presets+ </span>+ <button+ type="button"+ onClick={() => {+ handleApplyPreset('standing');+ setShowPoseDrawer(false);+ }}+ className="text-left px-2 py-1 rounded text-[11px] hover:bg-white/10 text-gray-200 flex items-center justify-between"+ >+ <span>Heroic Standing</span>+ <span className="text-[9px] text-gray-500 font-mono">Neutral</span>+ </button>+ <button+ type="button"+ onClick={() => {+ handleApplyPreset('action');+ setShowPoseDrawer(false);+ }}+ className="text-left px-2 py-1 rounded text-[11px] hover:bg-white/10 text-gray-200 flex items-center justify-between"+ >+ <span>Manga Action</span>+ <span className="text-[9px] text-orange-400 font-mono">Combat</span>+ </button>+ <button+ type="button"+ onClick={() => {+ handleApplyPreset('sitting');+ setShowPoseDrawer(false);+ }}+ className="text-left px-2 py-1 rounded text-[11px] hover:bg-white/10 text-gray-200 flex items-center justify-between"+ >+ <span>Seated Pose</span>+ <span className="text-[9px] text-sky-400 font-mono">Rest</span>+ </button>+ <div className="border-t border-white/10 my-0.5" />+ <button+ type="button"+ onClick={() => {+ handleApplyPreset('fists');+ setShowPoseDrawer(false);+ }}+ className="text-left px-2 py-1 rounded text-[11px] hover:bg-white/10 text-gray-200 flex items-center justify-between"+ >+ <span>Hand Fists</span>+ <span className="text-[9px] text-gray-400 font-mono">Clenched</span>+ </button>+ <button+ type="button"+ onClick={() => {+ handleApplyPreset('relaxed_palm');+ setShowPoseDrawer(false);+ }}+ className="text-left px-2 py-1 rounded text-[11px] hover:bg-white/10 text-gray-200 flex items-center justify-between"+ >+ <span>Relaxed Palm</span>+ <span className="text-[9px] text-gray-400 font-mono">Open</span>+ </button>+ </div>+ )}+ </div>+ )}++ {/* IK Limbs Selector */}+ {isMannequinActive && (+ <div className="flex items-center space-x-1 bg-[#252830] rounded px-1.5 py-1 border border-white/10">+ <span className="text-[10px] uppercase font-semibold text-gray-400 mr-1">IK</span>+ {(['head', 'leftHand', 'rightHand', 'leftFoot', 'rightFoot'] as const).map((limb) => (+ <button+ key={limb}+ type="button"+ onClick={() => selectIKTarget(activeIKHandle === limb ? null : limb)}+ title={`Manipulate ${limb} IK handle`}+ className={`px-1.5 py-0.5 rounded text-[10px] capitalize transition-colors ${+ activeIKHandle === limb ? 'bg-cyan-600 text-white font-medium' : 'text-gray-400 hover:bg-white/10'+ }`}+ >+ {limb === 'leftHand'+ ? 'L-Hand'+ : limb === 'rightHand'+ ? 'R-Hand'+ : limb === 'leftFoot'+ ? 'L-Foot'+ : limb === 'rightFoot'+ ? 'R-Foot'+ : 'Head'}+ </button>+ ))}+ </div>+ )}+{/* 3D Gizmo Rings Mode (Rotate / Translate / Off) */}<div className="flex items-center space-x-1 bg-[#252830] rounded px-1.5 py-1 border border-white/10"><span className="text-[10px] uppercase font-semibold text-gray-400 mr-1">Gizmo</span>@@ -1190,6 +1509,119 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({<RotateCcw className="w-3.5 h-3.5" /></button>+ {/* Perspective Ruler Camera Sync Toggle */}+ <button+ type="button"+ onClick={() => {+ const nextSync = !syncCameraPerspective;+ setSyncCameraPerspective(nextSync);+ if (nextSync && cameraRef.current && onUpdatePerspectiveRuler) {+ const ruler = calculatePerspectiveFromCamera(+ cameraRef.current,+ dimensions.width,+ dimensions.height,+ perspectiveRuler+ );+ onUpdatePerspectiveRuler(ruler);+ }+ }}+ title="Synchronize 3D camera with document Perspective Ruler"+ className={`p-1.5 px-2 rounded transition-colors flex items-center space-x-1 ${+ syncCameraPerspective+ ? 'bg-cyan-600/30 text-cyan-300 ring-1 ring-cyan-400'+ : 'text-gray-400 hover:bg-white/10'+ }`}+ >+ <Link className="w-3.5 h-3.5" />+ <span className="text-[10px]">Ruler Sync</span>+ </button>++ {/* 3D LT Line & Screentone Extraction */}+ <div className="relative">+ <button+ type="button"+ onClick={() => setShowLTModal(!showLTModal)}+ disabled={isBaking || !modelRootRef.current}+ title="Extract Lineart and Screentones from 3D Model (LT Conversion)"+ className="flex items-center space-x-1 bg-purple-600 hover:bg-purple-500 text-white font-medium px-2.5 py-1 rounded shadow-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <Sparkles className="w-3.5 h-3.5 text-amber-300" />+ <span className="text-xs">LT Convert</span>+ </button>++ {showLTModal && (+ <div className="absolute top-full mt-2 right-0 bg-[#1b1e24] border border-purple-500/40 rounded-xl p-3 shadow-2xl z-50 flex flex-col space-y-2.5 w-60">+ <div className="flex items-center justify-between">+ <span className="text-xs font-semibold text-purple-300 flex items-center space-x-1">+ <Sparkles className="w-3.5 h-3.5" />+ <span>LT Line & Tone Extraction</span>+ </span>+ <button+ type="button"+ onClick={() => setShowLTModal(false)}+ className="text-gray-400 hover:text-white"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="flex flex-col space-y-1">+ <div className="flex items-center justify-between text-[11px] text-gray-300">+ <span>Line Sensitivity</span>+ <span className="font-mono text-cyan-400">{Math.round((1 - ltLineThreshold) * 100)}%</span>+ </div>+ <input+ type="range"+ min="0.1"+ max="0.6"+ step="0.02"+ value={ltLineThreshold}+ onChange={(e) => setLtLineThreshold(parseFloat(e.target.value))}+ className="w-full accent-purple-500 cursor-pointer h-1.5"+ />+ </div>++ <div className="flex flex-col space-y-1">+ <span className="text-[11px] text-gray-300">Screentone Quantization</span>+ <div className="flex space-x-2">+ <button+ type="button"+ onClick={() => setLtToneBands(2)}+ className={`flex-1 py-1 rounded text-[10px] font-medium transition-colors ${+ ltToneBands === 2+ ? 'bg-purple-600 text-white'+ : 'bg-white/5 text-gray-400 hover:bg-white/10'+ }`}+ >+ 2 Bands (Shadow)+ </button>+ <button+ type="button"+ onClick={() => setLtToneBands(3)}+ className={`flex-1 py-1 rounded text-[10px] font-medium transition-colors ${+ ltToneBands === 3+ ? 'bg-purple-600 text-white'+ : 'bg-white/5 text-gray-400 hover:bg-white/10'+ }`}+ >+ 3 Bands (Deep/Mid)+ </button>+ </div>+ </div>++ <button+ type="button"+ onClick={handleExtractLineAndTone}+ disabled={isBaking}+ className="w-full py-1.5 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-medium rounded text-xs transition-colors shadow-lg flex items-center justify-center space-x-1.5"+ >+ <CheckCircle2 className="w-3.5 h-3.5" />+ <span>Extract Line & Tone</span>+ </button>+ </div>+ )}+ </div>+{/* Bake to 2D Layer */}<buttontype="button"diff --git a/src/components/MangaEffectsModal.tsx b/src/components/MangaEffectsModal.tsxnew file mode 100644index 0000000..1ebf52c--- /dev/null+++ b/src/components/MangaEffectsModal.tsx@@ -0,0 +1,465 @@+import React, { useState, useRef, useEffect, useCallback } from 'react';+import { X, Sparkles, Check, RefreshCw } from 'lucide-react';+import {+ renderSaturatedLines,+ renderStreamLines,+ SaturatedLinesOptions,+ StreamLinesOptions,+} from '../utils/mangaEffectsEngine';++interface MangaEffectsModalProps {+ isOpen: boolean;+ onClose: () => void;+ canvasWidth: number;+ canvasHeight: number;+ onApply: (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => void;+}++export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({+ isOpen,+ onClose,+ canvasWidth,+ canvasHeight,+ onApply,+}) => {+ const [activeTab, setActiveTab] = useState<'saturated' | 'stream'>('saturated');++ // Saturated Lines State+ const [satOptions, setSatOptions] = useState<SaturatedLinesOptions>({+ centerX: Math.round(canvasWidth * 0.5),+ centerY: Math.round(canvasHeight * 0.5),+ innerRadius: Math.round(Math.min(canvasWidth, canvasHeight) * 0.2),+ density: 120,+ spacingJitter: 0.5,+ lengthJitter: 0.35,+ lineWidth: 4,+ taper: 'in',+ color: '#000000',+ });++ // Stream Lines State+ const [streamOptions, setStreamOptions] = useState<StreamLinesOptions>({+ angle: 0,+ density: 80,+ lineLength: Math.round(Math.min(canvasWidth, canvasHeight) * 0.5),+ lengthNoise: 0.4,+ thickness: 3,+ thicknessNoise: 0.5,+ gapNoise: 0.3,+ color: '#000000',+ });++ const previewCanvasRef = useRef<HTMLCanvasElement>(null);++ // Re-draw preview canvas whenever parameters change+ const updatePreview = useCallback(() => {+ const canvas = previewCanvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;++ ctx.clearRect(0, 0, canvas.width, canvas.height);+ // Draw white background+ ctx.fillStyle = '#ffffff';+ ctx.fillRect(0, 0, canvas.width, canvas.height);++ // Scaling ratio to fit canvas inside preview box+ const scale = canvas.width / canvasWidth;++ ctx.save();+ ctx.scale(scale, scale);++ if (activeTab === 'saturated') {+ renderSaturatedLines(ctx, canvasWidth, canvasHeight, satOptions);++ // Draw faint indicator circle for center cutout+ ctx.strokeStyle = '#38bdf8';+ ctx.lineWidth = 1.5 / scale;+ ctx.setLineDash([4 / scale, 4 / scale]);+ ctx.beginPath();+ ctx.arc(satOptions.centerX, satOptions.centerY, satOptions.innerRadius, 0, Math.PI * 2);+ ctx.stroke();++ // Crosshair at center+ ctx.beginPath();+ ctx.arc(satOptions.centerX, satOptions.centerY, 3 / scale, 0, Math.PI * 2);+ ctx.fillStyle = '#38bdf8';+ ctx.fill();+ } else {+ renderStreamLines(ctx, canvasWidth, canvasHeight, streamOptions);+ }++ ctx.restore();+ }, [activeTab, canvasWidth, canvasHeight, satOptions, streamOptions]);++ useEffect(() => {+ if (isOpen) {+ updatePreview();+ }+ }, [isOpen, updatePreview]);++ if (!isOpen) return null;++ // Handle clicking on preview canvas to set focal point for saturated lines+ const handlePreviewClick = (e: React.MouseEvent<HTMLCanvasElement>) => {+ if (activeTab !== 'saturated') return;+ const canvas = previewCanvasRef.current;+ if (!canvas) return;+ const rect = canvas.getBoundingClientRect();+ const clickX = e.clientX - rect.left;+ const clickY = e.clientY - rect.top;+ const scale = canvasWidth / canvas.width;++ setSatOptions((prev) => ({+ ...prev,+ centerX: Math.round(clickX * scale),+ centerY: Math.round(clickY * scale),+ }));+ };++ const handleApplyClick = () => {+ if (activeTab === 'saturated') {+ onApply('saturated', satOptions);+ } else {+ onApply('stream', streamOptions);+ }+ onClose();+ };++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs select-none">+ <div className="w-[680px] bg-[#222327] border border-[#3b3d45] rounded-lg shadow-2xl overflow-hidden flex flex-col text-[#cccccc] font-sans">+ {/* Header */}+ <div className="px-4 py-3 bg-[#1a1b1e] border-b border-[#2e3036] flex items-center justify-between">+ <div className="flex items-center space-x-2">+ <Sparkles className="w-4 h-4 text-amber-400" />+ <h2 className="text-sm font-semibold text-white">Manga Effect Lines Generator</h2>+ </div>+ <button+ onClick={onClose}+ className="p-1 rounded text-[#888888] hover:text-white hover:bg-[#2b2d31] transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ {/* Tab Switcher */}+ <div className="flex border-b border-[#2e3036] bg-[#1d1e21] px-4 pt-2">+ <button+ onClick={() => setActiveTab('saturated')}+ className={`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors cursor-pointer ${+ activeTab === 'saturated'+ ? 'border-cyan-400 text-cyan-300'+ : 'border-transparent text-[#888888] hover:text-[#cccccc]'+ }`}+ >+ Saturated Lines (Focus / Burst)+ </button>+ <button+ onClick={() => setActiveTab('stream')}+ className={`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors cursor-pointer ${+ activeTab === 'stream'+ ? 'border-cyan-400 text-cyan-300'+ : 'border-transparent text-[#888888] hover:text-[#cccccc]'+ }`}+ >+ Stream Lines (Parallel Speed)+ </button>+ </div>++ {/* Body: Left Preview, Right Controls */}+ <div className="p-4 flex space-x-4 max-h-[480px]">+ {/* Interactive Preview Canvas */}+ <div className="flex flex-col items-center">+ <div className="relative border border-[#3b3d45] rounded overflow-hidden bg-white shadow-inner">+ <canvas+ ref={previewCanvasRef}+ width={300}+ height={Math.round((300 * canvasHeight) / canvasWidth)}+ onClick={handlePreviewClick}+ className="cursor-crosshair block"+ title={activeTab === 'saturated' ? 'Click on preview to move focus center' : undefined}+ />+ </div>+ {activeTab === 'saturated' && (+ <span className="text-[10px] text-[#777777] mt-1.5">+ Click preview to reposition focus point+ </span>+ )}+ </div>++ {/* Right Parameters Panel */}+ <div className="flex-1 space-y-3 overflow-y-auto pr-1 text-xs">+ {activeTab === 'saturated' ? (+ <>+ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Center Cutout Radius:</span>+ <span className="font-mono text-cyan-400">{satOptions.innerRadius}px</span>+ </div>+ <input+ type="range"+ min={10}+ max={Math.round(Math.min(canvasWidth, canvasHeight) * 0.45)}+ value={satOptions.innerRadius}+ onChange={(e) =>+ setSatOptions((p) => ({ ...p, innerRadius: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Line Density:</span>+ <span className="font-mono text-cyan-400">{satOptions.density} lines</span>+ </div>+ <input+ type="range"+ min={20}+ max={400}+ value={satOptions.density}+ onChange={(e) =>+ setSatOptions((p) => ({ ...p, density: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Stroke Width:</span>+ <span className="font-mono text-cyan-400">{satOptions.lineWidth}px</span>+ </div>+ <input+ type="range"+ min={1}+ max={12}+ value={satOptions.lineWidth}+ onChange={(e) =>+ setSatOptions((p) => ({ ...p, lineWidth: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Spacing & Depth Jitter:</span>+ <span className="font-mono text-cyan-400">{Math.round(satOptions.spacingJitter * 100)}%</span>+ </div>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(satOptions.spacingJitter * 100)}+ onChange={(e) =>+ setSatOptions((p) => ({+ ...p,+ spacingJitter: Number(e.target.value) / 100,+ lengthJitter: Number(e.target.value) / 100,+ }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div className="flex items-center space-x-2 pt-1">+ <span className="text-[11px] text-[#aaaaaa]">Taper Direction:</span>+ <button+ onClick={() => setSatOptions((p) => ({ ...p, taper: 'in' }))}+ className={`px-2 py-0.5 rounded text-[11px] border ${+ satOptions.taper === 'in'+ ? 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40'+ : 'border-[#3b3d45] text-[#888888]'+ }`}+ >+ Point to Center+ </button>+ <button+ onClick={() => setSatOptions((p) => ({ ...p, taper: 'none' }))}+ className={`px-2 py-0.5 rounded text-[11px] border ${+ satOptions.taper === 'none'+ ? 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40'+ : 'border-[#3b3d45] text-[#888888]'+ }`}+ >+ Uniform+ </button>+ </div>+ </>+ ) : (+ <>+ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Angle:</span>+ <span className="font-mono text-cyan-400">{streamOptions.angle}°</span>+ </div>+ <div className="flex items-center space-x-2">+ <input+ type="range"+ min={0}+ max={360}+ value={streamOptions.angle}+ onChange={(e) =>+ setStreamOptions((p) => ({ ...p, angle: Number(e.target.value) }))+ }+ className="flex-1 accent-cyan-400"+ />+ <div className="flex space-x-1">+ <button+ onClick={() => setStreamOptions((p) => ({ ...p, angle: 0 }))}+ className="px-1.5 py-0.5 rounded bg-[#18191c] border border-[#3b3d45] text-[10px]"+ >+ 0°+ </button>+ <button+ onClick={() => setStreamOptions((p) => ({ ...p, angle: 90 }))}+ className="px-1.5 py-0.5 rounded bg-[#18191c] border border-[#3b3d45] text-[10px]"+ >+ 90°+ </button>+ <button+ onClick={() => setStreamOptions((p) => ({ ...p, angle: 45 }))}+ className="px-1.5 py-0.5 rounded bg-[#18191c] border border-[#3b3d45] text-[10px]"+ >+ 45°+ </button>+ </div>+ </div>+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Density:</span>+ <span className="font-mono text-cyan-400">{streamOptions.density} lines</span>+ </div>+ <input+ type="range"+ min={15}+ max={300}+ value={streamOptions.density}+ onChange={(e) =>+ setStreamOptions((p) => ({ ...p, density: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Streak Length:</span>+ <span className="font-mono text-cyan-400">{streamOptions.lineLength}px</span>+ </div>+ <input+ type="range"+ min={50}+ max={1200}+ value={streamOptions.lineLength}+ onChange={(e) =>+ setStreamOptions((p) => ({ ...p, lineLength: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Thickness:</span>+ <span className="font-mono text-cyan-400">{streamOptions.thickness}px</span>+ </div>+ <input+ type="range"+ min={1}+ max={10}+ value={streamOptions.thickness}+ onChange={(e) =>+ setStreamOptions((p) => ({ ...p, thickness: Number(e.target.value) }))+ }+ className="w-full accent-cyan-400"+ />+ </div>++ <div>+ <div className="flex justify-between text-[11px] mb-1">+ <span className="text-[#aaaaaa]">Thickness & Length Noise:</span>+ <span className="font-mono text-cyan-400">+ {Math.round(streamOptions.thicknessNoise * 100)}%+ </span>+ </div>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(streamOptions.thicknessNoise * 100)}+ onChange={(e) =>+ setStreamOptions((p) => ({+ ...p,+ thicknessNoise: Number(e.target.value) / 100,+ lengthNoise: Number(e.target.value) / 100,+ }))+ }+ className="w-full accent-cyan-400"+ />+ </div>+ </>+ )}+ </div>+ </div>++ {/* Footer */}+ <div className="px-4 py-3 bg-[#1a1b1e] border-t border-[#2e3036] flex items-center justify-between">+ <button+ onClick={() => {+ // Quick reset to defaults+ if (activeTab === 'saturated') {+ setSatOptions({+ centerX: Math.round(canvasWidth * 0.5),+ centerY: Math.round(canvasHeight * 0.5),+ innerRadius: Math.round(Math.min(canvasWidth, canvasHeight) * 0.2),+ density: 120,+ spacingJitter: 0.5,+ lengthJitter: 0.35,+ lineWidth: 4,+ taper: 'in',+ color: '#000000',+ });+ } else {+ setStreamOptions({+ angle: 0,+ density: 80,+ lineLength: Math.round(Math.min(canvasWidth, canvasHeight) * 0.5),+ lengthNoise: 0.4,+ thickness: 3,+ thicknessNoise: 0.5,+ gapNoise: 0.3,+ color: '#000000',+ });+ }+ }}+ className="flex items-center space-x-1 text-xs text-[#888888] hover:text-[#cccccc] transition-colors cursor-pointer"+ >+ <RefreshCw className="w-3 h-3" />+ <span>Reset Defaults</span>+ </button>++ <div className="flex items-center space-x-2">+ <button+ onClick={onClose}+ className="px-3 py-1.5 bg-[#2b2d31] hover:bg-[#383a40] text-[#cccccc] rounded text-xs transition-colors cursor-pointer"+ >+ Cancel+ </button>+ <button+ onClick={handleApplyClick}+ className="px-3.5 py-1.5 bg-[#234b3e] hover:bg-[#2b604f] text-[#55eaab] border border-[#2e6e58] rounded text-xs font-semibold flex items-center space-x-1.5 transition-colors cursor-pointer"+ >+ <Check className="w-3.5 h-3.5" />+ <span>Apply Effect to Layer</span>+ </button>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/MenuBar.tsx b/src/components/MenuBar.tsxindex 0d76be9..cf627f6 100644--- a/src/components/MenuBar.tsx+++ b/src/components/MenuBar.tsx@@ -9,6 +9,7 @@ export const DEFAULT_MENU_SECTIONS: MenuSection[] = [{ id: 'layer', label: 'Layer', items: [] },{ id: 'ruler', label: 'Ruler', items: [] },{ id: 'view', label: 'View', items: [] },+ { id: 'manga', label: 'Manga', items: [] },{ id: 'help', label: 'Help', items: [] },];diff --git a/src/components/SmartphoneViewportSimulator.tsx b/src/components/SmartphoneViewportSimulator.tsxnew file mode 100644index 0000000..5e6d9f5--- /dev/null+++ b/src/components/SmartphoneViewportSimulator.tsx@@ -0,0 +1,131 @@+import React, { useState, useRef } from 'react';+import { Smartphone, X, GripHorizontal } from 'lucide-react';++interface SmartphoneViewportSimulatorProps {+ visible: boolean;+ onToggleVisible: () => void;+ viewportWidth?: number;+ viewportHeight?: number;+}++export const SmartphoneViewportSimulator: React.FC<SmartphoneViewportSimulatorProps> = ({+ visible,+ onToggleVisible,+}) => {+ // Mobile phone mockup dimensions (standard 9:16 smartphone viewport)+ const phoneWidth = 360;+ const phoneHeight = 640;++ // Floating position (defaults to bottom-right or center)+ const [position, setPosition] = useState<{ x: number; y: number }>(() => ({+ x: Math.max(20, (window.innerWidth - phoneWidth) / 2),+ y: Math.max(20, (window.innerHeight - phoneHeight) / 2),+ }));++ const isDraggingRef = useRef(false);+ const dragStartRef = useRef<{ clientX: number; clientY: number; initX: number; initY: number }>({+ clientX: 0,+ clientY: 0,+ initX: 0,+ initY: 0,+ });++ if (!visible) return null;++ const handlePointerDown = (e: React.PointerEvent) => {+ e.stopPropagation();+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ isDraggingRef.current = true;+ dragStartRef.current = {+ clientX: e.clientX,+ clientY: e.clientY,+ initX: position.x,+ initY: position.y,+ };+ };++ const handlePointerMove = (e: React.PointerEvent) => {+ if (!isDraggingRef.current) return;+ const dx = e.clientX - dragStartRef.current.clientX;+ const dy = e.clientY - dragStartRef.current.clientY;+ setPosition({+ x: Math.round(dragStartRef.current.initX + dx),+ y: Math.round(dragStartRef.current.initY + dy),+ });+ };++ const handlePointerUp = (e: React.PointerEvent) => {+ if (isDraggingRef.current) {+ try {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ } catch {+ // ignore+ }+ isDraggingRef.current = false;+ }+ };++ return (+ <div+ className="fixed z-40 select-none pointer-events-none"+ style={{+ left: `${position.x}px`,+ top: `${position.y}px`,+ width: `${phoneWidth}px`,+ height: `${phoneHeight}px`,+ }}+ >+ {/* Smartphone Outer Chassis & Bezel */}+ <div className="relative w-full h-full rounded-[42px] border-[5px] border-[#383a42]/80 ring-1 ring-white/20 shadow-[0_25px_60px_-15px_rgba(0,0,0,0.7)] flex flex-col overflow-hidden pointer-events-auto">+ {/* Dynamic Island / Camera Notch */}+ <div+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ className="absolute top-2.5 left-1/2 -translate-x-1/2 w-28 h-6 bg-black/90 rounded-full flex items-center justify-between px-3 cursor-move z-30 shadow-md group"+ title="Drag to reposition smartphone preview frame"+ >+ <div className="w-2.5 h-2.5 rounded-full bg-[#111111] border border-[#222222] ring-1 ring-cyan-500/20" />+ <GripHorizontal className="w-3.5 h-3.5 text-[#555555] group-hover:text-white transition-colors" />+ <div className="w-2 h-2 rounded-full bg-[#16202c]" />+ </div>++ {/* Top Status Bar Mockup */}+ <div className="w-full h-8 pt-1.5 px-6 flex items-center justify-between text-[11px] font-semibold text-white/90 z-20 pointer-events-none bg-gradient-to-b from-black/40 to-transparent">+ <span>9:41</span>+ <div className="flex items-center space-x-1.5 text-[10px]">+ <span>5G</span>+ <div className="w-5 h-2.5 rounded-xs border border-white/80 p-0.5 flex items-center">+ <div className="h-full w-full bg-white/90 rounded-xs" />+ </div>+ <button+ type="button"+ onClick={onToggleVisible}+ className="text-white/60 hover:text-white transition-colors pointer-events-auto ml-1 p-0.5"+ title="Hide Viewport Simulator"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ </div>++ {/* Translucent Cutout Viewport showing Canvas through */}+ <div className="flex-1 w-full relative pointer-events-none">+ {/* Subtle 9:16 guide overlay */}+ <div className="absolute inset-0 border border-cyan-400/30 rounded-lg pointer-events-none" />++ {/* Webtoon Reader Badge */}+ <div className="absolute bottom-6 left-1/2 -translate-x-1/2 px-3 py-1 bg-black/60 backdrop-blur-md rounded-full border border-white/10 text-[10px] text-cyan-300 font-medium flex items-center space-x-1.5 shadow-lg">+ <Smartphone className="w-3 h-3 text-cyan-400" />+ <span>9:16 Webtoon Simulator</span>+ </div>+ </div>++ {/* Bottom Home Indicator Bar */}+ <div className="w-full h-5 flex items-center justify-center pb-1.5 z-20 pointer-events-none bg-gradient-to-t from-black/40 to-transparent">+ <div className="w-32 h-1 bg-white/70 rounded-full" />+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/SpeechBalloonOverlay.tsx b/src/components/SpeechBalloonOverlay.tsxnew file mode 100644index 0000000..fd32d44--- /dev/null+++ b/src/components/SpeechBalloonOverlay.tsx@@ -0,0 +1,428 @@+import React, { useRef, useState } from 'react';+import { SpeechBalloon } from '../types/editor';+import {+ MessageSquare,+ Sparkles,+ Cloud,+ Square,+ Check,+ Trash2,+} from 'lucide-react';+import { getBalloonHandles, BalloonHandle } from '../utils/balloonEngine';++interface SpeechBalloonOverlayProps {+ balloon: SpeechBalloon | null;+ zoom: number;+ onUpdateBalloon: (updater: (prev: SpeechBalloon) => SpeechBalloon) => void;+ onConfirmBalloon: () => void;+ onDeleteBalloon: () => void;+}++export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({+ balloon,+ zoom,+ onUpdateBalloon,+ onConfirmBalloon,+ onDeleteBalloon,+}) => {+ if (!balloon) return null;++ const dragRef = useRef<{+ activeHandle: string | null;+ startX: number;+ startY: number;+ initialBounds: { x: number; y: number; width: number; height: number };+ initialTail: SpeechBalloon['tail'];+ }>({+ activeHandle: null,+ startX: 0,+ startY: 0,+ initialBounds: { ...balloon.bounds },+ initialTail: { ...balloon.tail },+ });++ const [activeTab, setActiveTab] = useState<'shape' | 'text'>('shape');++ const handles: BalloonHandle[] = getBalloonHandles(balloon);++ const handlePointerDown = (handleId: string, e: React.PointerEvent) => {+ e.stopPropagation();+ (e.target as HTMLElement).setPointerCapture(e.pointerId);++ dragRef.current = {+ activeHandle: handleId,+ startX: e.clientX,+ startY: e.clientY,+ initialBounds: { ...balloon.bounds },+ initialTail: {+ start: { ...balloon.tail.start },+ control1: { ...balloon.tail.control1 },+ control2: { ...balloon.tail.control2 },+ tip: { ...balloon.tail.tip },+ },+ };+ };++ const handlePointerMove = (e: React.PointerEvent) => {+ const { activeHandle, startX, startY, initialBounds, initialTail } = dragRef.current;+ if (!activeHandle) return;++ const dx = (e.clientX - startX) / zoom;+ const dy = (e.clientY - startY) / zoom;++ onUpdateBalloon((prev) => {+ if (activeHandle === 'tail-tip') {+ return {+ ...prev,+ tail: {+ ...prev.tail,+ tip: {+ ...prev.tail.tip,+ x: Math.round(initialTail.tip.x + dx),+ y: Math.round(initialTail.tip.y + dy),+ },+ },+ };+ }++ if (activeHandle === 'tail-ctrl1') {+ return {+ ...prev,+ tail: {+ ...prev.tail,+ control1: {+ ...prev.tail.control1,+ x: Math.round(initialTail.control1.x + dx),+ y: Math.round(initialTail.control1.y + dy),+ },+ },+ };+ }++ if (activeHandle === 'tail-ctrl2') {+ return {+ ...prev,+ tail: {+ ...prev.tail,+ control2: {+ ...prev.tail.control2,+ x: Math.round(initialTail.control2.x + dx),+ y: Math.round(initialTail.control2.y + dy),+ },+ },+ };+ }++ if (activeHandle === 'tail-start') {+ return {+ ...prev,+ tail: {+ ...prev.tail,+ start: {+ ...prev.tail.start,+ x: Math.round(initialTail.start.x + dx),+ y: Math.round(initialTail.start.y + dy),+ },+ },+ };+ }++ // Body bounding box resize handles+ let { x, y, width, height } = initialBounds;++ if (activeHandle.includes('e')) width = Math.max(40, width + dx);+ if (activeHandle.includes('s')) height = Math.max(40, height + dy);+ if (activeHandle.includes('w')) {+ const newW = Math.max(40, width - dx);+ x = initialBounds.x + (width - newW);+ width = newW;+ }+ if (activeHandle.includes('n')) {+ const newH = Math.max(40, height - dy);+ y = initialBounds.y + (height - newH);+ height = newH;+ }++ return {+ ...prev,+ bounds: {+ x: Math.round(x),+ y: Math.round(y),+ width: Math.round(width),+ height: Math.round(height),+ },+ };+ });+ };++ const handlePointerUp = (e: React.PointerEvent) => {+ if (dragRef.current.activeHandle) {+ try {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ } catch {+ // ignore+ }+ dragRef.current.activeHandle = null;+ }+ };++ const { bounds, tail } = balloon;++ return (+ <div className="absolute inset-0 pointer-events-none z-35">+ {/* SVG overlay rendering handles and tail control skeleton */}+ <svg className="w-full h-full overflow-visible pointer-events-none">+ {/* Bounding box guide */}+ <rect+ x={bounds.x}+ y={bounds.y}+ width={bounds.width}+ height={bounds.height}+ fill="none"+ stroke="#00bcd4"+ strokeWidth={1.5 / zoom}+ strokeDasharray={`${4 / zoom},${4 / zoom}`}+ />++ {/* Tail control arm lines */}+ <line+ x1={tail.start.x}+ y1={tail.start.y}+ x2={tail.control1.x}+ y2={tail.control1.y}+ stroke="#00bcd4"+ strokeWidth={1 / zoom}+ strokeDasharray={`${3 / zoom},${3 / zoom}`}+ />+ <line+ x1={tail.tip.x}+ y1={tail.tip.y}+ x2={tail.control2.x}+ y2={tail.control2.y}+ stroke="#00bcd4"+ strokeWidth={1 / zoom}+ strokeDasharray={`${3 / zoom},${3 / zoom}`}+ />+ </svg>++ {/* Interactive Handles */}+ {handles.map((h) => {+ const isTail = h.type.startsWith('tail');+ const size = isTail ? 10 / zoom : 8 / zoom;++ return (+ <div+ key={h.id}+ onPointerDown={(e) => handlePointerDown(h.id, e)}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ className={`absolute pointer-events-auto rounded-full border shadow-sm transition-transform hover:scale-125 ${+ h.id === 'tail-tip'+ ? 'bg-amber-400 border-white ring-2 ring-amber-500/50'+ : isTail+ ? 'bg-cyan-400 border-white'+ : 'bg-white border-[#00bcd4]'+ }`}+ style={{+ left: `${h.x}px`,+ top: `${h.y}px`,+ width: `${size}px`,+ height: `${size}px`,+ transform: 'translate(-50%, -50%)',+ cursor: h.cursor,+ }}+ title={h.id === 'tail-tip' ? 'Drag Tail Tip' : `Handle: ${h.id}`}+ />+ );+ })}++ {/* Floating Balloon Inspector Panel */}+ <div+ className="absolute pointer-events-auto bg-[#1e1f22] border border-[#383a40] rounded-md shadow-2xl p-2.5 w-72 text-xs text-[#cccccc] flex flex-col space-y-2 select-none"+ style={{+ left: `${bounds.x + bounds.width + 15}px`,+ top: `${bounds.y}px`,+ transform: `scale(${zoom > 0 ? 1 / zoom : 1})`,+ transformOrigin: 'top left',+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between border-b border-[#2b2d31] pb-1.5">+ <div className="flex items-center space-x-1.5 text-white font-medium">+ <MessageSquare className="w-3.5 h-3.5 text-cyan-400" />+ <span>Speech Balloon</span>+ </div>+ <div className="flex items-center space-x-1">+ <button+ onClick={() => setActiveTab('shape')}+ className={`px-1.5 py-0.5 rounded text-[10px] ${+ activeTab === 'shape' ? 'bg-[#2b2d31] text-white' : 'text-[#888888]'+ }`}+ >+ Shape+ </button>+ <button+ onClick={() => setActiveTab('text')}+ className={`px-1.5 py-0.5 rounded text-[10px] ${+ activeTab === 'text' ? 'bg-[#2b2d31] text-white' : 'text-[#888888]'+ }`}+ >+ Text+ </button>+ </div>+ </div>++ {activeTab === 'shape' ? (+ <div className="space-y-2">+ <div>+ <label className="text-[10px] text-[#888888] block mb-1">Shape Preset:</label>+ <div className="grid grid-cols-4 gap-1">+ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, shape: 'ellipse' }))}+ className={`p-1 rounded flex flex-col items-center border ${+ balloon.shape === 'ellipse'+ ? 'border-cyan-400 bg-cyan-500/10 text-cyan-300'+ : 'border-[#2e3036] text-[#888888] hover:text-white'+ }`}+ title="Ellipse (Standard)"+ >+ <div className="w-4 h-3 rounded-full border border-current my-0.5" />+ <span className="text-[9px]">Ellipse</span>+ </button>++ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, shape: 'rounded-rect' }))}+ className={`p-1 rounded flex flex-col items-center border ${+ balloon.shape === 'rounded-rect'+ ? 'border-cyan-400 bg-cyan-500/10 text-cyan-300'+ : 'border-[#2e3036] text-[#888888] hover:text-white'+ }`}+ title="Rounded Rectangle"+ >+ <Square className="w-3.5 h-3.5 my-0.5" />+ <span className="text-[9px]">Box</span>+ </button>++ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, shape: 'jagged-flash' }))}+ className={`p-1 rounded flex flex-col items-center border ${+ balloon.shape === 'jagged-flash'+ ? 'border-cyan-400 bg-cyan-500/10 text-cyan-300'+ : 'border-[#2e3036] text-[#888888] hover:text-white'+ }`}+ title="Jagged Flash (Shout / Action)"+ >+ <Sparkles className="w-3.5 h-3.5 my-0.5 text-amber-400" />+ <span className="text-[9px]">Flash</span>+ </button>++ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, shape: 'thought' }))}+ className={`p-1 rounded flex flex-col items-center border ${+ balloon.shape === 'thought'+ ? 'border-cyan-400 bg-cyan-500/10 text-cyan-300'+ : 'border-[#2e3036] text-[#888888] hover:text-white'+ }`}+ title="Thought Bubble (Cloud)"+ >+ <Cloud className="w-3.5 h-3.5 my-0.5 text-sky-400" />+ <span className="text-[9px]">Thought</span>+ </button>+ </div>+ </div>++ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#888888]">Border Width:</span>+ <div className="flex items-center space-x-1">+ <input+ type="range"+ min={1}+ max={12}+ value={balloon.strokeWidth}+ onChange={(e) =>+ onUpdateBalloon((p) => ({ ...p, strokeWidth: Number(e.target.value) }))+ }+ className="w-24 accent-cyan-400"+ />+ <span className="font-mono text-cyan-400 w-6 text-right">+ {balloon.strokeWidth}px+ </span>+ </div>+ </div>+ </div>+ ) : (+ <div className="space-y-2">+ <textarea+ value={balloon.text}+ onChange={(e) => onUpdateBalloon((p) => ({ ...p, text: e.target.value }))}+ placeholder="Balloon dialogue text..."+ rows={2}+ className="w-full bg-[#141517] text-white text-xs border border-[#383a40] rounded p-1.5 focus:border-cyan-500 focus:outline-none resize-none"+ />++ <div className="flex items-center justify-between">+ <span className="text-[11px] text-[#888888]">Direction:</span>+ <div className="flex space-x-1">+ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, vertical: false }))}+ className={`px-2 py-0.5 rounded text-[10px] ${+ !balloon.vertical+ ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40'+ : 'bg-[#141517] text-[#888888]'+ }`}+ >+ Horizontal+ </button>+ <button+ onClick={() => onUpdateBalloon((p) => ({ ...p, vertical: true }))}+ className={`px-2 py-0.5 rounded text-[10px] ${+ balloon.vertical+ ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40'+ : 'bg-[#141517] text-[#888888]'+ }`}+ >+ Vertical 縦+ </button>+ </div>+ </div>++ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#888888]">Font Size:</span>+ <div className="flex items-center space-x-1">+ <input+ type="range"+ min={12}+ max={72}+ value={balloon.fontSize}+ onChange={(e) =>+ onUpdateBalloon((p) => ({ ...p, fontSize: Number(e.target.value) }))+ }+ className="w-24 accent-cyan-400"+ />+ <span className="font-mono text-cyan-400 w-6 text-right">{balloon.fontSize}px</span>+ </div>+ </div>+ </div>+ )}++ <div className="flex items-center justify-between pt-1.5 border-t border-[#2b2d31]">+ <button+ onClick={onDeleteBalloon}+ className="p-1 text-rose-400 hover:bg-rose-500/20 rounded transition-colors"+ title="Delete Balloon"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>++ <button+ onClick={onConfirmBalloon}+ className="px-2.5 py-1 bg-[#234b3e] hover:bg-[#2b604f] text-[#55eaab] border border-[#2e6e58] rounded text-xs font-semibold flex items-center space-x-1"+ >+ <Check className="w-3.5 h-3.5" />+ <span>Apply Balloon</span>+ </button>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/TextEditorOverlay.tsx b/src/components/TextEditorOverlay.tsxindex a337068..4c9c76c 100644--- a/src/components/TextEditorOverlay.tsx+++ b/src/components/TextEditorOverlay.tsx@@ -101,6 +101,8 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({textAlign: settings.align,color: settings.color,lineHeight: 1.25,+ writingMode: settings.writingMode === 'vertical-rl' ? 'vertical-rl' : 'horizontal-tb',+ textOrientation: 'mixed',textShadow: settings.outline? `-${settings.outlineWidth}px -${settings.outlineWidth}px 0 ${settings.outlineColor},@@ -231,6 +233,28 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({</button></div>+ {/* Writing Direction (Horizontal vs Vertical Manga Tate-gaki) */}+ <div className="flex items-center space-x-1 bg-[#141517] p-0.5 rounded border border-[#2b2d31]">+ <button+ onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'horizontal-tb' }))}+ title="Horizontal Layout (Left-to-Right)"+ className={`px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${+ settings.writingMode !== 'vertical-rl' ? 'bg-[#2b2d31] text-cyan-300' : 'text-[#888888] hover:text-white'+ }`}+ >+ Horiz+ </button>+ <button+ onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'vertical-rl' }))}+ title="Vertical Layout (Manga Tate-gaki: Right-to-Left columns)"+ className={`px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${+ settings.writingMode === 'vertical-rl' ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'text-[#888888] hover:text-white'+ }`}+ >+ Vert 縦+ </button>+ </div>+{/* Alignments */}<div className="flex items-center space-x-1 bg-[#141517] p-0.5 rounded border border-[#2b2d31]"><buttondiff --git a/src/components/WebtoonExportModal.tsx b/src/components/WebtoonExportModal.tsxnew file mode 100644index 0000000..51fff6f--- /dev/null+++ b/src/components/WebtoonExportModal.tsx@@ -0,0 +1,208 @@+import React, { useState } from 'react';+import { X, Archive, Download, Loader2 } from 'lucide-react';+import { exportWebtoonChapterZip, downloadWebtoonZip } from '../utils/webtoonExporter';++interface WebtoonExportModalProps {+ isOpen: boolean;+ onClose: () => void;+ getActiveCanvas: () => HTMLCanvasElement | null;+ canvasWidth: number;+ canvasHeight: number;+ documentTitle?: string;+}++export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({+ isOpen,+ onClose,+ getActiveCanvas,+ canvasWidth,+ canvasHeight,+ documentTitle = 'webtoon_chapter',+}) => {+ const [sliceHeight, setSliceHeight] = useState(1280);+ const [format, setFormat] = useState<'jpg' | 'png'>('jpg');+ const [quality, setQuality] = useState(92);+ const [isExporting, setIsExporting] = useState(false);+ const [progress, setProgress] = useState<{ current: number; total: number; percent: number } | null>(null);++ if (!isOpen) return null;++ const totalSlices = Math.max(1, Math.ceil(canvasHeight / sliceHeight));++ const handleStartExport = async () => {+ const canvas = getActiveCanvas();+ if (!canvas) return;++ try {+ setIsExporting(true);+ setProgress({ current: 0, total: totalSlices, percent: 0 });++ const zipBytes = await exportWebtoonChapterZip(canvas, {+ sliceWidth: canvasWidth,+ sliceHeight,+ format,+ quality: quality / 100,+ filePrefix: `${documentTitle.replace(/\s+/g, '_')}_slice_`,+ onProgress: (p) => setProgress(p),+ });++ const zipName = `${documentTitle.replace(/\s+/g, '_')}_slices.zip`;+ downloadWebtoonZip(zipBytes, zipName);+ setIsExporting(false);+ setProgress(null);+ onClose();+ } catch (err) {+ console.error('Webtoon export error:', err);+ setIsExporting(false);+ setProgress(null);+ alert('Failed to export webtoon slices.');+ }+ };++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs select-none">+ <div className="w-[460px] bg-[#222327] border border-[#3b3d45] rounded-lg shadow-2xl overflow-hidden flex flex-col text-[#cccccc] font-sans">+ {/* Header */}+ <div className="px-4 py-3 bg-[#1a1b1e] border-b border-[#2e3036] flex items-center justify-between">+ <div className="flex items-center space-x-2">+ <Archive className="w-4 h-4 text-emerald-400" />+ <h2 className="text-sm font-semibold text-white">Webtoon Chapter Slicer Exporter</h2>+ </div>+ {!isExporting && (+ <button+ onClick={onClose}+ className="p-1 rounded text-[#888888] hover:text-white hover:bg-[#2b2d31] transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>++ {/* Content */}+ <div className="p-4 space-y-4 text-xs">+ <div className="bg-[#18191c] p-3 rounded border border-[#2e3036] space-y-1">+ <div className="flex justify-between">+ <span className="text-[#888888]">Canvas Dimensions:</span>+ <span className="font-mono text-white">{canvasWidth} × {canvasHeight} px</span>+ </div>+ <div className="flex justify-between">+ <span className="text-[#888888]">Total Slices:</span>+ <span className="font-mono text-emerald-400 font-semibold">{totalSlices} sequential tiles</span>+ </div>+ <div className="flex justify-between">+ <span className="text-[#888888]">Tile Dimensions:</span>+ <span className="font-mono text-white">{canvasWidth} × {sliceHeight} px</span>+ </div>+ </div>++ <div className="space-y-1.5">+ <div className="flex justify-between">+ <label className="text-[11px] text-[#aaaaaa] font-medium">Slice Tile Height:</label>+ <span className="font-mono text-cyan-400">{sliceHeight}px</span>+ </div>+ <div className="flex space-x-2">+ {[800, 1024, 1280, 1920].map((h) => (+ <button+ key={h}+ onClick={() => setSliceHeight(h)}+ className={`flex-1 py-1 rounded text-xs border cursor-pointer font-medium transition-colors ${+ sliceHeight === h+ ? 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40'+ : 'bg-[#18191c] border-[#33353b] text-[#888888] hover:text-white'+ }`}+ >+ {h}px+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1.5">+ <label className="text-[11px] text-[#aaaaaa] font-medium">Output Format:</label>+ <div className="grid grid-cols-2 gap-2">+ <button+ onClick={() => setFormat('jpg')}+ className={`py-1.5 rounded text-xs border cursor-pointer font-medium transition-colors ${+ format === 'jpg'+ ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40'+ : 'bg-[#18191c] border-[#33353b] text-[#888888] hover:text-white'+ }`}+ >+ JPEG (Standard Webtoon)+ </button>+ <button+ onClick={() => setFormat('png')}+ className={`py-1.5 rounded text-xs border cursor-pointer font-medium transition-colors ${+ format === 'png'+ ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40'+ : 'bg-[#18191c] border-[#33353b] text-[#888888] hover:text-white'+ }`}+ >+ PNG (Lossless)+ </button>+ </div>+ </div>++ {format === 'jpg' && (+ <div className="space-y-1.5">+ <div className="flex justify-between text-[11px]">+ <span className="text-[#aaaaaa]">JPEG Compression Quality:</span>+ <span className="font-mono text-cyan-400">{quality}%</span>+ </div>+ <input+ type="range"+ min={50}+ max={100}+ value={quality}+ onChange={(e) => setQuality(Number(e.target.value))}+ className="w-full accent-cyan-400"+ />+ </div>+ )}++ {isExporting && progress && (+ <div className="space-y-2 pt-2 border-t border-[#2e3036]">+ <div className="flex justify-between text-[11px]">+ <span className="text-white flex items-center space-x-1.5">+ <Loader2 className="w-3.5 h-3.5 animate-spin text-emerald-400" />+ <span>Slicing tile {progress.current} of {progress.total}...</span>+ </span>+ <span className="font-mono text-emerald-400">{progress.percent}%</span>+ </div>+ <div className="w-full bg-[#18191c] h-2 rounded-full overflow-hidden border border-[#33353b]">+ <div+ className="bg-emerald-500 h-full transition-all duration-150"+ style={{ width: `${progress.percent}%` }}+ />+ </div>+ </div>+ )}+ </div>++ {/* Footer */}+ <div className="px-4 py-3 bg-[#1a1b1e] border-t border-[#2e3036] flex items-center justify-end space-x-2">+ {!isExporting && (+ <button+ onClick={onClose}+ className="px-3 py-1.5 bg-[#2b2d31] hover:bg-[#383a40] text-[#cccccc] rounded text-xs transition-colors cursor-pointer"+ >+ Cancel+ </button>+ )}+ <button+ onClick={handleStartExport}+ disabled={isExporting}+ className={`px-3.5 py-1.5 rounded text-xs font-semibold flex items-center space-x-1.5 transition-colors cursor-pointer ${+ isExporting+ ? 'bg-[#1e382d] text-[#777777] cursor-not-allowed'+ : 'bg-[#1b4e3b] hover:bg-[#23634b] text-[#55eaab] border border-[#2a7a5c]'+ }`}+ >+ <Download className="w-3.5 h-3.5" />+ <span>{isExporting ? 'Packaging ZIP...' : `Export ${totalSlices} Tiles (.ZIP)`}</span>+ </button>+ </div>+ </div>+ </div>+ );+};diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.tsindex abf3422..482179a 100644--- a/src/hooks/useCanvasNavigation.ts+++ b/src/hooks/useCanvasNavigation.ts@@ -43,9 +43,10 @@ export function formatZoomPercent(zoom: number): string {interface UseCanvasNavigationProps {dimensions?: CanvasDimensions;+ isWebtoonMode?: boolean;}-export function useCanvasNavigation({ dimensions: _dimensions }: UseCanvasNavigationProps = {}) {+export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = false }: UseCanvasNavigationProps = {}) {const viewportRef = useRef<HTMLDivElement | null>(null);const [zoom, setZoomState] = useState<number>(1.0);@@ -332,6 +333,14 @@ export function useCanvasNavigation({ dimensions: _dimensions }: UseCanvasNavigadelta *= 500; // Pages to pixels}+ // In Webtoon mode, standard wheel scrolls canvas vertically+ if (isWebtoonMode && !e.ctrlKey && !e.metaKey) {+ const nextPanY = panRef.current.y - delta;+ panRef.current = { x: panRef.current.x, y: nextPanY };+ setPanState({ x: panRef.current.x, y: nextPanY });+ return;+ }+// Smooth exponential zoom factorconst zoomFactor = Math.exp(-delta * 0.0018);const currentZoom = zoomRef.current;@@ -467,7 +476,7 @@ export function useCanvasNavigation({ dimensions: _dimensions }: UseCanvasNavigaconst dy = e.clientY - panStartRef.current.clientY;const newPan = {- x: panStartRef.current.panX + dx,+ x: isWebtoonMode ? panStartRef.current.panX : panStartRef.current.panX + dx,y: panStartRef.current.panY + dy,};diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.tsindex 810fb5e..59996e2 100644--- a/src/services/bake3DService.ts+++ b/src/services/bake3DService.ts@@ -1,6 +1,7 @@import * as THREE from 'three';import { LayerItem, BlendMode } from '../types/editor';import { multiplayerService } from './multiplayerService';+import { applyScreentoneCPU } from '../utils/screentoneEngine';export interface Bake3DOptions {scene: THREE.Scene;@@ -186,3 +187,426 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3return { layer, canvas: rasterCanvas, dataUrl };}++export interface Bake3DLTOptions {+ scene: THREE.Scene;+ camera: THREE.Camera;+ dimensions: { width: number; height: number };+ activeRenderer?: THREE.WebGLRenderer | null;+ baseLayerName?: string;+ lineThreshold?: number; // 0.15 to 0.6 (default: 0.28)+ toneBands?: 2 | 3; // 2 or 3 bands (default: 2)+ toneFrequencies?: [number, number]; // Lines per inch [shadow, midtone]+ toneAngles?: [number, number]; // Halftone grid angles [shadow, midtone]+ toneDensities?: [number, number]; // Density percentage [shadow, midtone]+ disposeOnComplete?: boolean;+ onInsertLayers?: (layers: LayerItem[], canvases: HTMLCanvasElement[]) => void;+ onBroadcastLayer?: (layer: LayerItem, dataUrl: string) => void;+}++export interface Bake3DLTResult {+ lineLayer: LayerItem;+ lineCanvas: HTMLCanvasElement;+ toneLayers: LayerItem[];+ toneCanvases: HTMLCanvasElement[];+}++const isLittleEndian = (() => {+ const buf = new ArrayBuffer(4);+ new Uint32Array(buf)[0] = 0x11223344;+ return new Uint8Array(buf)[0] === 0x44;+})();+const SOLID_BLACK_U32 = isLittleEndian ? 0xff000000 : 0x000000ff;++/**+ * 3D LT Line & Screentone Extraction (3D-to-2D line extraction).+ *+ * Renders custom depth, normal, and diffuse passes from the 3D scene, runs a Sobel+ * edge-detection filter for crisp black lineart, and quantizes diffuse lighting into+ * 2 or 3 luminance bands converted to manga screentone layers via screentoneEngine.+ */+export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bake3DLTResult> {+ const {+ scene,+ camera,+ dimensions,+ activeRenderer,+ baseLayerName = '3D',+ lineThreshold = 0.28,+ toneBands = 2,+ toneFrequencies = [55, 60],+ toneAngles = [45, 60],+ toneDensities = [0.45, 0.2],+ disposeOnComplete = true,+ onInsertLayers,+ onBroadcastLayer,+ } = options;++ const targetWidth = Math.max(1, Math.round(dimensions.width));+ const targetHeight = Math.max(1, Math.round(dimensions.height));++ const offscreenRenderer = new THREE.WebGLRenderer({+ alpha: true,+ antialias: false,+ preserveDrawingBuffer: true,+ powerPreference: 'high-performance',+ });++ const maxGlSize = offscreenRenderer.capabilities.maxTextureSize || 4096;+ let renderWidth = targetWidth;+ let renderHeight = targetHeight;+ if (renderWidth > maxGlSize || renderHeight > maxGlSize) {+ const scale = maxGlSize / Math.max(renderWidth, renderHeight);+ renderWidth = Math.max(1, Math.round(renderWidth * scale));+ renderHeight = Math.max(1, Math.round(renderHeight * scale));+ }++ offscreenRenderer.setSize(renderWidth, renderHeight, false);+ offscreenRenderer.setPixelRatio(1);+ offscreenRenderer.setClearColor(0x000000, 0);++ const renderCamera = camera.clone();+ if ('aspect' in renderCamera) {+ (renderCamera as THREE.PerspectiveCamera).aspect = targetWidth / targetHeight;+ (renderCamera as THREE.PerspectiveCamera).updateProjectionMatrix();+ } else if ('left' in renderCamera) {+ (renderCamera as THREE.OrthographicCamera).updateProjectionMatrix();+ }++ // Preserve original mesh materials for safe restoration+ const savedMaterials = new Map<THREE.Mesh, THREE.Material | THREE.Material[]>();+ scene.traverse((obj) => {+ const mesh = obj as THREE.Mesh;+ if (mesh.isMesh) {+ savedMaterials.set(mesh, mesh.material);+ }+ });++ // Helper to capture offscreen WebGL buffer to 2D canvas imageData+ const captureRenderPass = (): Uint8ClampedArray => {+ const canvas = document.createElement('canvas');+ canvas.width = renderWidth;+ canvas.height = renderHeight;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ if (!ctx) throw new Error('Failed to acquire 2D context for pass extraction');+ ctx.drawImage(offscreenRenderer.domElement, 0, 0, renderWidth, renderHeight);+ return ctx.getImageData(0, 0, renderWidth, renderHeight).data;+ };++ // 1. Normal Pass+ const normalMat = new THREE.MeshNormalMaterial();+ scene.traverse((obj) => {+ const mesh = obj as THREE.Mesh;+ if (mesh.isMesh) {+ mesh.material = normalMat;+ }+ });+ offscreenRenderer.render(scene, renderCamera);+ const normalData = captureRenderPass();++ // 2. Depth Pass+ const depthMat = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });+ scene.traverse((obj) => {+ const mesh = obj as THREE.Mesh;+ if (mesh.isMesh) {+ mesh.material = depthMat;+ }+ });+ offscreenRenderer.render(scene, renderCamera);+ const depthData = captureRenderPass();++ // 3. Diffuse Lighting Pass (restore original materials)+ scene.traverse((obj) => {+ const mesh = obj as THREE.Mesh;+ if (mesh.isMesh && savedMaterials.has(mesh)) {+ mesh.material = savedMaterials.get(mesh)!;+ }+ });+ offscreenRenderer.render(scene, renderCamera);+ const diffuseData = captureRenderPass();++ // 4. Sobel Edge Detection Filter+ const lineCanvas = document.createElement('canvas');+ lineCanvas.width = targetWidth;+ lineCanvas.height = targetHeight;++ const tempLineCanvas = document.createElement('canvas');+ tempLineCanvas.width = renderWidth;+ tempLineCanvas.height = renderHeight;+ const tempLineCtx = tempLineCanvas.getContext('2d')!;+ const lineImageData = tempLineCtx.createImageData(renderWidth, renderHeight);+ const lineData32 = new Uint32Array(lineImageData.data.buffer);++ const w = renderWidth;+ const h = renderHeight;++ for (let y = 1; y < h - 1; y++) {+ const rowOffset = y * w;+ for (let x = 1; x < w - 1; x++) {+ const idx = (rowOffset + x) * 4;+ const alpha = normalData[idx + 3];++ if (alpha === 0) continue; // background++ // Check outer silhouette against 4-neighborhood+ const leftA = normalData[(rowOffset + x - 1) * 4 + 3];+ const rightA = normalData[(rowOffset + x + 1) * 4 + 3];+ const topA = normalData[((y - 1) * w + x) * 4 + 3];+ const bottomA = normalData[((y + 1) * w + x) * 4 + 3];++ if (leftA === 0 || rightA === 0 || topA === 0 || bottomA === 0) {+ lineData32[rowOffset + x] = SOLID_BLACK_U32;+ continue;+ }++ // Sobel operator on Normal components+ // Row -1+ const n00_r = normalData[((y - 1) * w + (x - 1)) * 4];+ const n00_g = normalData[((y - 1) * w + (x - 1)) * 4 + 1];+ const n00_b = normalData[((y - 1) * w + (x - 1)) * 4 + 2];+ const n10_r = normalData[((y - 1) * w + x) * 4];+ const n10_g = normalData[((y - 1) * w + x) * 4 + 1];+ const n10_b = normalData[((y - 1) * w + x) * 4 + 2];+ const n20_r = normalData[((y - 1) * w + (x + 1)) * 4];+ const n20_g = normalData[((y - 1) * w + (x + 1)) * 4 + 1];+ const n20_b = normalData[((y - 1) * w + (x + 1)) * 4 + 2];++ // Row 0+ const n01_r = normalData[(rowOffset + (x - 1)) * 4];+ const n01_g = normalData[(rowOffset + (x - 1)) * 4 + 1];+ const n01_b = normalData[(rowOffset + (x - 1)) * 4 + 2];+ const n21_r = normalData[(rowOffset + (x + 1)) * 4];+ const n21_g = normalData[(rowOffset + (x + 1)) * 4 + 1];+ const n21_b = normalData[(rowOffset + (x + 1)) * 4 + 2];++ // Row +1+ const n02_r = normalData[((y + 1) * w + (x - 1)) * 4];+ const n02_g = normalData[((y + 1) * w + (x - 1)) * 4 + 1];+ const n02_b = normalData[((y + 1) * w + (x - 1)) * 4 + 2];+ const n12_r = normalData[((y + 1) * w + x) * 4];+ const n12_g = normalData[((y + 1) * w + x) * 4 + 1];+ const n12_b = normalData[((y + 1) * w + x) * 4 + 2];+ const n22_r = normalData[((y + 1) * w + (x + 1)) * 4];+ const n22_g = normalData[((y + 1) * w + (x + 1)) * 4 + 1];+ const n22_b = normalData[((y + 1) * w + (x + 1)) * 4 + 2];++ const gx_r = -n00_r + n20_r - 2 * n01_r + 2 * n21_r - n02_r + n22_r;+ const gy_r = -n00_r - 2 * n10_r - n20_r + n02_r + 2 * n12_r + n22_r;++ const gx_g = -n00_g + n20_g - 2 * n01_g + 2 * n21_g - n02_g + n22_g;+ const gy_g = -n00_g - 2 * n10_g - n20_g + n02_g + 2 * n12_g + n22_g;++ const gx_b = -n00_b + n20_b - 2 * n01_b + 2 * n21_b - n02_b + n22_b;+ const gy_b = -n00_b - 2 * n10_b - n20_b + n02_b + 2 * n12_b + n22_b;++ const normEdge = Math.hypot(gx_r, gy_r) + Math.hypot(gx_g, gy_g) + Math.hypot(gx_b, gy_b);++ // Sobel operator on Depth+ const d00 = depthData[((y - 1) * w + (x - 1)) * 4];+ const d10 = depthData[((y - 1) * w + x) * 4];+ const d20 = depthData[((y - 1) * w + (x + 1)) * 4];+ const d01 = depthData[(rowOffset + (x - 1)) * 4];+ const d21 = depthData[(rowOffset + (x + 1)) * 4];+ const d02 = depthData[((y + 1) * w + (x - 1)) * 4];+ const d12 = depthData[((y + 1) * w + x) * 4];+ const d22 = depthData[((y + 1) * w + (x + 1)) * 4];++ const gx_d = -d00 + d20 - 2 * d01 + 2 * d21 - d02 + d22;+ const gy_d = -d00 - 2 * d10 - d20 + d02 + 2 * d12 + d22;+ const depthEdge = Math.hypot(gx_d, gy_d);++ const totalEdge = (normEdge / 255.0) * 0.45 + (depthEdge / 255.0) * 2.2;++ if (totalEdge > lineThreshold) {+ lineData32[rowOffset + x] = SOLID_BLACK_U32;+ }+ }+ }++ tempLineCtx.putImageData(lineImageData, 0, 0);+ const lineCtx = lineCanvas.getContext('2d')!;+ lineCtx.drawImage(tempLineCanvas, 0, 0, targetWidth, targetHeight);++ // 5. Diffuse Lighting Quantization into 2 or 3 luminance bands+ const maskCanvasShadow = document.createElement('canvas');+ maskCanvasShadow.width = renderWidth;+ maskCanvasShadow.height = renderHeight;+ const shadowCtx = maskCanvasShadow.getContext('2d')!;+ const shadowImageData = shadowCtx.createImageData(renderWidth, renderHeight);+ const shadowData32 = new Uint32Array(shadowImageData.data.buffer);++ let maskCanvasMidtone: HTMLCanvasElement | null = null;+ let midtoneCtx: CanvasRenderingContext2D | null = null;+ let midtoneImageData: ImageData | null = null;+ let midtoneData32: Uint32Array | null = null;++ if (toneBands === 3) {+ maskCanvasMidtone = document.createElement('canvas');+ maskCanvasMidtone.width = renderWidth;+ maskCanvasMidtone.height = renderHeight;+ midtoneCtx = maskCanvasMidtone.getContext('2d')!;+ midtoneImageData = midtoneCtx.createImageData(renderWidth, renderHeight);+ midtoneData32 = new Uint32Array(midtoneImageData.data.buffer);+ }++ for (let i = 0; i < renderWidth * renderHeight; i++) {+ const pIdx = i * 4;+ const a = diffuseData[pIdx + 3];+ if (a === 0 || lineData32[i] !== 0) continue; // skip background and lineart++ const r = diffuseData[pIdx];+ const g = diffuseData[pIdx + 1];+ const b = diffuseData[pIdx + 2];+ const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255.0;++ if (toneBands === 2) {+ if (lum < 0.54) {+ shadowData32[i] = SOLID_BLACK_U32;+ }+ } else {+ if (lum < 0.35) {+ shadowData32[i] = SOLID_BLACK_U32;+ } else if (lum < 0.72 && midtoneData32) {+ midtoneData32[i] = SOLID_BLACK_U32;+ }+ }+ }++ shadowCtx.putImageData(shadowImageData, 0, 0);+ if (midtoneCtx && midtoneImageData) {+ midtoneCtx.putImageData(midtoneImageData, 0, 0);+ }++ // 6. Convert diffuse bands to manga screentone layers using screentoneEngine+ const toneCanvases: HTMLCanvasElement[] = [];+ const toneLayers: LayerItem[] = [];++ // Shadow Screentone Layer+ const shadowToneRenderCanvas = document.createElement('canvas');+ shadowToneRenderCanvas.width = renderWidth;+ shadowToneRenderCanvas.height = renderHeight;+ applyScreentoneCPU(maskCanvasShadow, shadowToneRenderCanvas, {+ frequency: toneFrequencies[0],+ angle: toneAngles[0],+ specifiedDensity: toneDensities[0],+ densityType: 'specified',+ dpi: 600,+ antiAliasing: true,+ });++ const finalShadowCanvas = document.createElement('canvas');+ finalShadowCanvas.width = targetWidth;+ finalShadowCanvas.height = targetHeight;+ const fShadowCtx = finalShadowCanvas.getContext('2d')!;+ fShadowCtx.drawImage(shadowToneRenderCanvas, 0, 0, targetWidth, targetHeight);+ toneCanvases.push(finalShadowCanvas);++ const shadowDataUrl = finalShadowCanvas.toDataURL('image/png');+ const shadowLayer: LayerItem = {+ id: `raster-lt-shadow-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,+ name: `${baseLayerName} Shadow Tone (LT)`,+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'multiply',+ locked: false,+ collapsed: false,+ parentId: null,+ thumbnailUrl: shadowDataUrl,+ toneEnabled: true,+ toneFrequency: toneFrequencies[0],+ toneAngle: toneAngles[0],+ toneDensity: Math.round(toneDensities[0] * 100),+ toneDensityType: 'specified',+ };+ toneLayers.push(shadowLayer);++ // Optional Midtone Screentone Layer (for 3 bands)+ if (toneBands === 3 && maskCanvasMidtone) {+ const midToneRenderCanvas = document.createElement('canvas');+ midToneRenderCanvas.width = renderWidth;+ midToneRenderCanvas.height = renderHeight;+ applyScreentoneCPU(maskCanvasMidtone, midToneRenderCanvas, {+ frequency: toneFrequencies[1],+ angle: toneAngles[1],+ specifiedDensity: toneDensities[1],+ densityType: 'specified',+ dpi: 600,+ antiAliasing: true,+ });++ const finalMidtoneCanvas = document.createElement('canvas');+ finalMidtoneCanvas.width = targetWidth;+ finalMidtoneCanvas.height = targetHeight;+ const fMidtoneCtx = finalMidtoneCanvas.getContext('2d')!;+ fMidtoneCtx.drawImage(midToneRenderCanvas, 0, 0, targetWidth, targetHeight);+ toneCanvases.push(finalMidtoneCanvas);++ const midtoneDataUrl = finalMidtoneCanvas.toDataURL('image/png');+ const midtoneLayer: LayerItem = {+ id: `raster-lt-midtone-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,+ name: `${baseLayerName} Midtone Tone (LT)`,+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'multiply',+ locked: false,+ collapsed: false,+ parentId: null,+ thumbnailUrl: midtoneDataUrl,+ toneEnabled: true,+ toneFrequency: toneFrequencies[1],+ toneAngle: toneAngles[1],+ toneDensity: Math.round(toneDensities[1] * 100),+ toneDensityType: 'specified',+ };+ toneLayers.push(midtoneLayer);+ }++ // 7. Lineart Layer+ const lineDataUrl = lineCanvas.toDataURL('image/png');+ const lineLayer: LayerItem = {+ id: `raster-lt-line-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,+ name: `${baseLayerName} Lineart (LT)`,+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ thumbnailUrl: lineDataUrl,+ };++ // Clean up WebGL resources+ if (disposeOnComplete) {+ disposeThreeResources(scene, offscreenRenderer);+ if (activeRenderer) {+ disposeThreeResources(null, activeRenderer);+ }+ } else {+ offscreenRenderer.dispose();+ }++ const allLayers = [...toneLayers, lineLayer];+ const allCanvases = [...toneCanvases, lineCanvas];++ if (onInsertLayers) {+ onInsertLayers(allLayers, allCanvases);+ }++ if (onBroadcastLayer) {+ onBroadcastLayer(lineLayer, lineDataUrl);+ toneLayers.forEach((l, i) => onBroadcastLayer(l, toneCanvases[i].toDataURL('image/png')));+ } else if (multiplayerService.isConnected()) {+ multiplayerService.sendLayerAdd(lineLayer, lineDataUrl);+ toneLayers.forEach((l, i) => multiplayerService.sendLayerAdd(l, toneCanvases[i].toDataURL('image/png')));+ }++ return {+ lineLayer,+ lineCanvas,+ toneLayers,+ toneCanvases,+ };+}diff --git a/src/types/editor.ts b/src/types/editor.tsindex 2509161..09fb8c6 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -13,6 +13,8 @@ export type ToolType =| 'fill'| 'text'| 'frame'+ | 'balloon'+ | 'vector-edit'| 'liquify';export interface Point {@@ -180,6 +182,27 @@ export interface BrushSettings {isTransparentInk?: boolean; // Transparent Ink mode (CSP 'C' key toggle)}+export interface OnionSkinSettings {+ enabled: boolean;+ prevFrames: number;+ nextFrames: number;+ prevTint: string;+ nextTint: string;+ opacity: number;+}++export interface AnimationTimeline {+ fps: number;+ totalFrames: number;+ currentFrame: number;+ cels: Record<number, string>; // Mapping frame index to layer ID+ onionSkin: OnionSkinSettings;+ isPlaying?: boolean;+ loop?: boolean;+}++export type AnimationExportFormat = 'gif' | 'apng' | 'webm' | 'mp4' | 'png-zip';+export interface DocumentTab {id: string;name: string;@@ -197,6 +220,7 @@ export interface DocumentTab {historyIndex?: number;perspectiveRuler?: PerspectiveRuler | null;defaultFrequency?: number;+ animation?: AnimationTimeline | null;}export type HistoryActionType =@@ -253,6 +277,57 @@ export interface TextSettings {outlineColor: string;outlineWidth: number;color: string;+ writingMode?: 'horizontal-tb' | 'vertical-rl';+}++export interface SpeechBalloonTail {+ start: Point;+ control1: Point;+ control2: Point;+ tip: Point;+}++export interface SpeechBalloon {+ id: string;+ shape: 'ellipse' | 'rounded-rect' | 'jagged-flash' | 'thought';+ bounds: { x: number; y: number; width: number; height: number };+ tail: SpeechBalloonTail;+ fillColor: string;+ strokeColor: string;+ strokeWidth: number;+ text: string;+ fontFamily: string;+ fontSize: number;+ vertical: boolean;+}++export interface BalloonSettings {+ shape: 'ellipse' | 'rounded-rect' | 'jagged-flash' | 'thought';+ fillColor: string;+ strokeColor: string;+ strokeWidth: number;+ text: string;+ fontFamily: string;+ fontSize: number;+ vertical: boolean;+}++export interface WebtoonSettings {+ enabled: boolean;+ viewportAspect: '9:16';+ smartphoneMockup: boolean;+ sliceHeight: number;+ sliceFormat: 'jpg' | 'png';+}++export type VectorEditMode = 'pinch' | 'width' | 'simplify';++export interface VectorEditSettings {+ mode: VectorEditMode;+ radius: number;+ pinchStrength: number;+ widthFactor: number;+ simplifyTolerance: number;}export interface FrameSettings {@@ -492,6 +567,8 @@ export interface LayerItem {vectorStrokes?: VectorStroke[];// Comic Frame DatacomicFrames?: ComicFrame[];+ // Speech Balloon Data+ balloons?: SpeechBalloon[];// Collaborative Layer Soft-LockingreservedByPeerId?: string | number;reservedByPeerName?: string;diff --git a/src/utils/__tests__/animationEngine.test.ts b/src/utils/__tests__/animationEngine.test.tsnew file mode 100644index 0000000..3d1b664--- /dev/null+++ b/src/utils/__tests__/animationEngine.test.ts@@ -0,0 +1,183 @@+import { describe, it, expect } from 'vitest';+import {+ createDefaultAnimationTimeline,+ setFrameCel,+ removeFrameCel,+ getOnionSkinFrames,+ renderAnimationFrame,+ exportAnimationToPngZip,+ exportAnimationToGif,+ exportAnimationToApng,+} from '../animationEngine';+import { LayerItem } from '../../types/editor';++const DUMMY_PNG_DATA_URL =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';++class MockCanvas {+ width = 100;+ height = 100;+ getContext(_type: string) {+ return {+ clearRect: () => {},+ drawImage: () => {},+ fillRect: () => {},+ getImageData: (_x: number, _y: number, w: number, h: number) => ({+ data: new Uint8ClampedArray(w * h * 4),+ width: w,+ height: h,+ }),+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ fillStyle: '#000000',+ };+ }+ toDataURL(_type = 'image/png') {+ return DUMMY_PNG_DATA_URL;+ }+}++if (typeof (globalThis as any).HTMLCanvasElement === 'undefined') {+ (globalThis as any).HTMLCanvasElement = MockCanvas;+}++if (typeof (globalThis as any).document === 'undefined') {+ (globalThis as any).document = {+ createElement: (tag: string) => {+ if (tag === 'canvas') return new MockCanvas();+ return {};+ },+ body: {+ appendChild: () => {},+ removeChild: () => {},+ },+ };+}++describe('2D Animation Engine & Export Pipeline', () => {+ const dummyLayer: LayerItem = {+ id: 'layer-1',+ name: 'Cel 1',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ };++ it('initializes default timeline with proper onion skin settings', () => {+ const tl = createDefaultAnimationTimeline([dummyLayer]);+ expect(tl.fps).toBe(12);+ expect(tl.totalFrames).toBe(24);+ expect(tl.currentFrame).toBe(0);+ expect(tl.cels[0]).toBe('layer-1');+ expect(tl.onionSkin.enabled).toBe(true);+ expect(tl.onionSkin.prevTint).toBe('#00bcd4'); // Cyan+ expect(tl.onionSkin.nextTint).toBe('#ec4899'); // Magenta+ });++ it('maps and removes frame cels cleanly', () => {+ let tl = createDefaultAnimationTimeline();+ tl = setFrameCel(tl, 5, 'layer-cel-5');+ expect(tl.cels[5]).toBe('layer-cel-5');++ tl = removeFrameCel(tl, 5);+ expect(tl.cels[5]).toBeUndefined();+ });++ it('calculates progressive opacity falloff for colored onion skinning', () => {+ let tl = createDefaultAnimationTimeline();+ tl = setFrameCel(tl, 0, 'cel-0');+ tl = setFrameCel(tl, 1, 'cel-1');+ tl = setFrameCel(tl, 2, 'cel-2');+ tl = setFrameCel(tl, 3, 'cel-3');+ tl = setFrameCel(tl, 4, 'cel-4');++ // At frame 2, prev frames are 1 and 0, next frames are 3 and 4+ tl.currentFrame = 2;+ tl.onionSkin.prevFrames = 2;+ tl.onionSkin.nextFrames = 2;+ tl.onionSkin.opacity = 0.4;++ const onionFrames = getOnionSkinFrames(tl);+ expect(onionFrames.length).toBe(4);++ const prev1 = onionFrames.find((f) => f.frame === 1);+ const prev0 = onionFrames.find((f) => f.frame === 0);+ expect(prev1).toBeDefined();+ expect(prev0).toBeDefined();++ // Prior frame closest to current has higher opacity than furthest+ expect(prev1!.opacity).toBeGreaterThan(prev0!.opacity);+ expect(prev1!.tint).toBe('#00bcd4');++ const next3 = onionFrames.find((f) => f.frame === 3);+ const next4 = onionFrames.find((f) => f.frame === 4);+ expect(next3).toBeDefined();+ expect(next4).toBeDefined();+ expect(next3!.opacity).toBeGreaterThan(next4!.opacity);+ expect(next3!.tint).toBe('#ec4899');+ });++ it('renders a frame onto offscreen canvas', () => {+ const tl = createDefaultAnimationTimeline([dummyLayer]);+ const canvases = new Map<string, HTMLCanvasElement>();++ const c = document.createElement('canvas');+ c.width = 100;+ c.height = 100;+ canvases.set('layer-1', c);++ const rendered = renderAnimationFrame(0, tl, [dummyLayer], canvases, { width: 100, height: 100 }, false);+ expect(rendered).toBeInstanceOf(HTMLCanvasElement);+ expect(rendered.width).toBe(100);+ expect(rendered.height).toBe(100);+ });++ it('exports animation as a valid zipped numbered PNG sequence', async () => {+ const tl = createDefaultAnimationTimeline([dummyLayer]);+ tl.totalFrames = 3; // test 3 frames+ const canvases = new Map<string, HTMLCanvasElement>();+ const c = document.createElement('canvas');+ c.width = 32;+ c.height = 32;+ canvases.set('layer-1', c);++ const zipBlob = await exportAnimationToPngZip(tl, [dummyLayer], canvases, { width: 32, height: 32 });+ expect(zipBlob).toBeInstanceOf(Blob);+ expect(zipBlob.type).toBe('application/zip');+ expect(zipBlob.size).toBeGreaterThan(0);+ });++ it('exports animation as a valid animated GIF Blob', async () => {+ const tl = createDefaultAnimationTimeline([dummyLayer]);+ tl.totalFrames = 2;+ const canvases = new Map<string, HTMLCanvasElement>();+ const c = document.createElement('canvas');+ c.width = 16;+ c.height = 16;+ canvases.set('layer-1', c);++ const gifBlob = await exportAnimationToGif(tl, [dummyLayer], canvases, { width: 16, height: 16 });+ expect(gifBlob).toBeInstanceOf(Blob);+ expect(gifBlob.type).toBe('image/gif');+ expect(gifBlob.size).toBeGreaterThan(0);+ });++ it('exports animation as a valid Animated PNG (APNG) Blob', async () => {+ const tl = createDefaultAnimationTimeline([dummyLayer]);+ tl.totalFrames = 2;+ const canvases = new Map<string, HTMLCanvasElement>();+ const c = document.createElement('canvas');+ c.width = 16;+ c.height = 16;+ canvases.set('layer-1', c);++ const apngBlob = await exportAnimationToApng(tl, [dummyLayer], canvases, { width: 16, height: 16 });+ expect(apngBlob).toBeInstanceOf(Blob);+ expect(apngBlob.type).toBe('image/png');+ expect(apngBlob.size).toBeGreaterThan(0);+ });+});diff --git a/src/utils/__tests__/balloonEngine.test.ts b/src/utils/__tests__/balloonEngine.test.tsnew file mode 100644index 0000000..d2330ce--- /dev/null+++ b/src/utils/__tests__/balloonEngine.test.ts@@ -0,0 +1,41 @@+import { describe, it, expect } from 'vitest';+import {+ createDefaultSpeechBalloon,+ getBalloonHandles,+ hitTestBalloon,+} from '../balloonEngine';++describe('Speech Balloon Engine', () => {+ it('creates a default speech balloon with vector tail', () => {+ const balloon = createDefaultSpeechBalloon(100, 150, 200, 120, 'ellipse');++ expect(balloon.shape).toBe('ellipse');+ expect(balloon.bounds.x).toBe(100);+ expect(balloon.bounds.y).toBe(150);+ expect(balloon.bounds.width).toBe(200);+ expect(balloon.bounds.height).toBe(120);++ expect(balloon.tail).toBeDefined();+ expect(balloon.tail.start.x).toBe(200);+ expect(balloon.tail.tip.y).toBeGreaterThan(balloon.bounds.y + balloon.bounds.height);+ });++ it('generates interactive resize and tail handles', () => {+ const balloon = createDefaultSpeechBalloon(50, 50, 100, 100, 'rounded-rect');+ const handles = getBalloonHandles(balloon);++ expect(handles.length).toBeGreaterThanOrEqual(12);+ const tipHandle = handles.find((h) => h.id === 'tail-tip');+ expect(tipHandle).toBeDefined();+ expect(tipHandle?.x).toBe(balloon.tail.tip.x);+ expect(tipHandle?.y).toBe(balloon.tail.tip.y);+ });++ it('correctly hit tests balloon bounds', () => {+ const balloon = createDefaultSpeechBalloon(100, 100, 200, 200, 'thought');++ expect(hitTestBalloon(balloon, { x: 150, y: 150 })).toBe(true);+ expect(hitTestBalloon(balloon, { x: 50, y: 50 })).toBe(false);+ expect(hitTestBalloon(balloon, { x: 400, y: 400 })).toBe(false);+ });+});diff --git a/src/utils/__tests__/mangaEffectsEngine.test.ts b/src/utils/__tests__/mangaEffectsEngine.test.tsnew file mode 100644index 0000000..5f59ca2--- /dev/null+++ b/src/utils/__tests__/mangaEffectsEngine.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from 'vitest';+import {+ renderSaturatedLines,+ renderStreamLines,+ SaturatedLinesOptions,+ StreamLinesOptions,+} from '../mangaEffectsEngine';++describe('Manga Effect Lines Generator Engine', () => {+ it('renders saturated focus lines without throwing errors', () => {+ // Mock minimal Canvas 2D context+ const calls: string[] = [];+ const ctx = {+ save: () => calls.push('save'),+ restore: () => calls.push('restore'),+ beginPath: () => calls.push('beginPath'),+ moveTo: () => calls.push('moveTo'),+ lineTo: () => calls.push('lineTo'),+ closePath: () => calls.push('closePath'),+ fill: () => calls.push('fill'),+ fillStyle: '',+ strokeStyle: '',+ } as unknown as CanvasRenderingContext2D;++ const options: SaturatedLinesOptions = {+ centerX: 400,+ centerY: 400,+ innerRadius: 100,+ density: 20,+ spacingJitter: 0.3,+ lengthJitter: 0.2,+ lineWidth: 3,+ color: '#000000',+ };++ renderSaturatedLines(ctx, 800, 800, options);+ expect(calls).toContain('save');+ expect(calls).toContain('restore');+ expect(calls).toContain('fill');+ expect(calls.filter((c) => c === 'fill').length).toBe(20);+ });++ it('renders directional stream lines without throwing errors', () => {+ const calls: string[] = [];+ const ctx = {+ save: () => calls.push('save'),+ restore: () => calls.push('restore'),+ beginPath: () => calls.push('beginPath'),+ moveTo: () => calls.push('moveTo'),+ lineTo: () => calls.push('lineTo'),+ closePath: () => calls.push('closePath'),+ fill: () => calls.push('fill'),+ fillStyle: '',+ } as unknown as CanvasRenderingContext2D;++ const options: StreamLinesOptions = {+ angle: 45,+ density: 15,+ lineLength: 300,+ lengthNoise: 0.3,+ thickness: 4,+ thicknessNoise: 0.3,+ gapNoise: 0.2,+ color: '#000000',+ };++ renderStreamLines(ctx, 800, 800, options);+ expect(calls).toContain('save');+ expect(calls).toContain('restore');+ expect(calls.filter((c) => c === 'fill').length).toBe(15);+ });+});diff --git a/src/utils/__tests__/mangaTextEngine.test.ts b/src/utils/__tests__/mangaTextEngine.test.tsnew file mode 100644index 0000000..a57b11c--- /dev/null+++ b/src/utils/__tests__/mangaTextEngine.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect } from 'vitest';+import { computeMangaTextLayout, isLatinChar } from '../mangaTextEngine';++describe('Manga Text Engine (Tate-gaki & Yokogaki)', () => {+ it('correctly identifies Latin characters', () => {+ expect(isLatinChar('A')).toBe(true);+ expect(isLatinChar('z')).toBe(true);+ expect(isLatinChar('9')).toBe(true);+ expect(isLatinChar('あ')).toBe(false);+ expect(isLatinChar('漢')).toBe(false);+ });++ it('computes horizontal layout with glyph positions', () => {+ const layout = computeMangaTextLayout('HELLO\nWORLD', {+ fontSize: 20,+ fontFamily: 'Arial',+ writingMode: 'horizontal-tb',+ });++ expect(layout.glyphs.length).toBe(10);+ expect(layout.width).toBeGreaterThan(0);+ expect(layout.height).toBeGreaterThan(0);+ expect(layout.glyphs[0].rotateDeg).toBe(0);+ });++ it('computes vertical-rl layout with right-to-left columns and top-to-bottom glyphs', () => {+ // Two lines: col 0 should be on the right, col 1 on the left+ const layout = computeMangaTextLayout('あいう\nえおか', {+ fontSize: 20,+ fontFamily: 'sans-serif',+ writingMode: 'vertical-rl',+ });++ expect(layout.glyphs.length).toBe(6);+ // Find glyph for 'あ' (col 0, row 0) and 'え' (col 1, row 0)+ const glyphA = layout.glyphs.find((g) => g.char === 'あ');+ const glyphE = layout.glyphs.find((g) => g.char === 'え');+ expect(glyphA).toBeDefined();+ expect(glyphE).toBeDefined();+ // Col 0 ('あ') should have a higher X coordinate than Col 1 ('え') in vertical-rl+ expect(glyphA!.x).toBeGreaterThan(glyphE!.x);+ // Within column: 'い' should have higher Y than 'あ'+ const glyphI = layout.glyphs.find((g) => g.char === 'い');+ expect(glyphI!.y).toBeGreaterThan(glyphA!.y);+ });++ it('rotates em-dashes and brackets 90 degrees in vertical mode', () => {+ const layout = computeMangaTextLayout('「愛」—', {+ fontSize: 20,+ fontFamily: 'sans-serif',+ writingMode: 'vertical-rl',+ });++ const openBracket = layout.glyphs.find((g) => g.char === '「');+ const closeBracket = layout.glyphs.find((g) => g.char === '」');+ const dash = layout.glyphs.find((g) => g.char === '—');+ const kanji = layout.glyphs.find((g) => g.char === '愛');++ expect(openBracket!.rotateDeg).toBe(90);+ expect(closeBracket!.rotateDeg).toBe(90);+ expect(dash!.rotateDeg).toBe(90);+ expect(kanji!.rotateDeg).toBe(0);+ });+});diff --git a/src/utils/__tests__/mannequin3D.test.ts b/src/utils/__tests__/mannequin3D.test.tsnew file mode 100644index 0000000..7443552--- /dev/null+++ b/src/utils/__tests__/mannequin3D.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect } from 'vitest';+import * as THREE from 'three';+import {+ createProceduralMannequin,+ findHumanoidBones,+ solveTwoBoneIK,+ createIKHandles,+ applyPosePreset,+} from '../mannequin3D';++describe('3D Humanoid Mannequin & IK System', () => {+ it('generates a rigged procedural humanoid mannequin with bones', () => {+ const { group, skinnedMesh, skeleton, bones } = createProceduralMannequin();+ expect(group).toBeDefined();+ expect(skinnedMesh).toBeInstanceOf(THREE.SkinnedMesh);+ expect(skeleton.bones.length).toBeGreaterThanOrEqual(15);+ expect(bones.hips).toBeDefined();+ expect(bones.head).toBeDefined();+ expect(bones.leftHand).toBeDefined();+ expect(bones.rightHand).toBeDefined();+ expect(bones.leftFoot).toBeDefined();+ expect(bones.rightFoot).toBeDefined();+ });++ it('discovers humanoid bones using standard pattern matching', () => {+ const root = new THREE.Group();+ const hip = new THREE.Bone();+ hip.name = 'mixamorig:Hips';+ const lHand = new THREE.Bone();+ lHand.name = 'mixamorig:LeftHand';+ const rHand = new THREE.Bone();+ rHand.name = 'mixamorig:RightHand';+ root.add(hip);+ root.add(lHand);+ root.add(rHand);++ const found = findHumanoidBones(root);+ expect(found.hips).toBe(hip);+ expect(found.leftHand).toBe(lHand);+ expect(found.rightHand).toBe(rHand);+ });++ it('solves two-bone IK for limb stretching towards target', () => {+ const rootBone = new THREE.Bone();+ rootBone.position.set(0, 1.0, 0);++ const midBone = new THREE.Bone();+ midBone.position.set(0, 0.5, 0);+ rootBone.add(midBone);++ const endBone = new THREE.Bone();+ endBone.position.set(0, 0.5, 0);+ midBone.add(endBone);++ rootBone.updateMatrixWorld(true);++ const target = new THREE.Vector3(0.5, 1.2, 0.2);+ const pole = new THREE.Vector3(0, 1.5, 1);++ solveTwoBoneIK(rootBone, midBone, endBone, target, pole);++ const finalPos = new THREE.Vector3();+ endBone.getWorldPosition(finalPos);++ // End bone should move towards target+ expect(Number.isFinite(finalPos.x)).toBe(true);+ expect(Number.isFinite(finalPos.y)).toBe(true);+ expect(Number.isFinite(finalPos.z)).toBe(true);+ });++ it('creates interactive IK target handles for extremities', () => {+ const { container, handles } = createIKHandles();+ expect(container).toBeInstanceOf(THREE.Group);+ expect(handles.head).toBeDefined();+ expect(handles.leftHand).toBeDefined();+ expect(handles.rightHand).toBeDefined();+ expect(handles.leftFoot).toBeDefined();+ expect(handles.rightFoot).toBeDefined();+ });++ it('applies pose presets without throwing and updates rotations', () => {+ const { bones } = createProceduralMannequin();++ applyPosePreset(bones, 'standing');+ expect(bones.leftUpperArm?.rotation.x).not.toBe(0);++ applyPosePreset(bones, 'action');+ expect(bones.leftUpperArm?.rotation.x).not.toBe(0);++ applyPosePreset(bones, 'sitting');+ expect(bones.leftUpperLeg?.rotation.x).not.toBe(0);++ applyPosePreset(bones, 'fists');+ expect(bones.leftHand?.rotation.x).not.toBe(0);++ applyPosePreset(bones, 'relaxed_palm');+ expect(bones.leftHand?.rotation.x).not.toBe(0);+ });+});diff --git a/src/utils/__tests__/perspectiveSync.test.ts b/src/utils/__tests__/perspectiveSync.test.tsnew file mode 100644index 0000000..53657a1--- /dev/null+++ b/src/utils/__tests__/perspectiveSync.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect } from 'vitest';+import * as THREE from 'three';+import { calculatePerspectiveFromCamera } from '../perspectiveMath';++describe('Perspective Ruler Camera Sync', () => {+ it('calculates 2-point perspective when camera is level', () => {+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+ camera.position.set(0, 0, 5);+ camera.lookAt(0, 0, 0);+ camera.updateMatrixWorld();+ camera.updateProjectionMatrix();++ const ruler = calculatePerspectiveFromCamera(camera, 1000, 1000);+ expect(ruler).toBeDefined();+ expect(ruler.vps.length).toBeGreaterThanOrEqual(2);++ const vp1 = ruler.vps.find((v) => v.id === 'vp1');+ const vp2 = ruler.vps.find((v) => v.id === 'vp2');+ expect(vp1).toBeDefined();+ expect(vp2).toBeDefined();+ });++ it('detects 3-point perspective when camera is tilted up or down', () => {+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+ camera.position.set(0, 5, 5);+ camera.lookAt(0, 0, 0); // Looking down (high-angle bird's eye view)+ camera.updateMatrixWorld();+ camera.updateProjectionMatrix();++ const ruler = calculatePerspectiveFromCamera(camera, 1920, 1080);+ expect(ruler.type).toBe('3-point');+ const vp3 = ruler.vps.find((v) => v.id === 'vp3');+ expect(vp3).toBeDefined();+ expect(typeof vp3!.x).toBe('number');+ expect(typeof vp3!.y).toBe('number');+ });++ it('computes correct horizon angle across camera roll/tilt', () => {+ const camera = new THREE.PerspectiveCamera(45, 1.5, 0.1, 100);+ camera.position.set(2, 2, 4);+ camera.lookAt(0, 0, 0);+ camera.updateMatrixWorld();+ camera.updateProjectionMatrix();++ const ruler = calculatePerspectiveFromCamera(camera, 1200, 800);+ expect(Number.isFinite(ruler.horizonAngle)).toBe(true);+ });+});diff --git a/src/utils/__tests__/vectorEngine.test.ts b/src/utils/__tests__/vectorEngine.test.tsindex 8a0be04..a2addd9 100644--- a/src/utils/__tests__/vectorEngine.test.ts+++ b/src/utils/__tests__/vectorEngine.test.ts@@ -8,6 +8,9 @@ import {simplifyPathPoints,adjustVectorStrokeWidth,reshapeVectorLine,+ pinchVectorStroke,+ modifyStrokeWidth,+ simplifyVectorStroke,} from '../vectorEngine';import { VectorKnot, VectorStroke } from '../../types/editor';@@ -232,4 +235,75 @@ describe('Vector Inking Engine & Vector Eraser', () => {expect(reshaped.knots[2].x).toBe(100);expect(reshaped.knots[2].y).toBe(50);});++ it('pinchVectorStroke displaces knots within bell-curve radius', () => {+ const stroke: VectorStroke = {+ id: 'stroke-pinch',+ layerId: 'v1',+ tool: 'brush',+ knots: [+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },+ { x: 100, y: 50, pressure: 0.5, width: 4, timestamp: 20 },+ ],+ color: '#000000',+ baseWidth: 4,+ opacity: 1,+ bounds: { minX: 0, minY: 48, maxX: 100, maxY: 52 },+ };++ const pinched = pinchVectorStroke(stroke, { x: 50, y: 50 }, 30, { x: 10, y: 20 });+ expect(pinched.knots[1].x).toBeCloseTo(60);+ expect(pinched.knots[1].y).toBeCloseTo(70);+ expect(pinched.knots[0].x).toBe(0);+ expect(pinched.knots[2].x).toBe(100);+ });++ it('modifyStrokeWidth scales knot widths locally within radius', () => {+ const stroke: VectorStroke = {+ id: 'stroke-width',+ layerId: 'v1',+ tool: 'brush',+ knots: [+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },+ { x: 100, y: 50, pressure: 0.5, width: 4, timestamp: 20 },+ ],+ color: '#000000',+ baseWidth: 4,+ opacity: 1,+ bounds: { minX: 0, minY: 48, maxX: 100, maxY: 52 },+ };++ const modified = modifyStrokeWidth(stroke, { x: 50, y: 50 }, 30, 2.0);+ // Center knot should be doubled from width 4 to 8+ expect(modified.knots[1].width).toBeCloseTo(8);+ // Knots outside radius stay 4+ expect(modified.knots[0].width).toBe(4);+ expect(modified.knots[2].width).toBe(4);+ });++ it('simplifyVectorStroke prunes redundant collinear knots', () => {+ const stroke: VectorStroke = {+ id: 'stroke-simplify',+ layerId: 'v1',+ tool: 'brush',+ knots: [+ { x: 0, y: 0, pressure: 0.5, width: 4, timestamp: 0 },+ { x: 25, y: 0.1, pressure: 0.5, width: 4, timestamp: 5 },+ { x: 50, y: 0, pressure: 0.5, width: 4, timestamp: 10 },+ { x: 75, y: 0.1, pressure: 0.5, width: 4, timestamp: 15 },+ { x: 100, y: 0, pressure: 0.5, width: 4, timestamp: 20 },+ ],+ color: '#000000',+ baseWidth: 4,+ opacity: 1,+ bounds: { minX: 0, minY: 0, maxX: 100, maxY: 0.1 },+ };++ const simplified = simplifyVectorStroke(stroke, 1.0);+ expect(simplified.knots.length).toBeLessThan(stroke.knots.length);+ expect(simplified.knots[0].x).toBe(0);+ expect(simplified.knots[simplified.knots.length - 1].x).toBe(100);+ });});diff --git a/src/utils/__tests__/webtoonExporter.test.ts b/src/utils/__tests__/webtoonExporter.test.tsnew file mode 100644index 0000000..03da743--- /dev/null+++ b/src/utils/__tests__/webtoonExporter.test.ts@@ -0,0 +1,26 @@+import { describe, it, expect } from 'vitest';+import { zipSync, unzipSync } from 'fflate';++describe('Webtoon Chapter Slicer & Exporter', () => {+ it('correctly calculates vertical chapter slice counts', () => {+ const totalHeight = 30000;+ const sliceHeight = 1280;+ const expectedSlices = Math.ceil(totalHeight / sliceHeight);++ expect(expectedSlices).toBe(24);+ });++ it('compresses sequential tiles into valid zip archive', () => {+ const mockFiles: Record<string, Uint8Array> = {+ 'slice_001.jpg': new Uint8Array([255, 216, 255, 224, 0, 16]),+ 'slice_002.jpg': new Uint8Array([255, 216, 255, 224, 0, 16]),+ };++ const zipData = zipSync(mockFiles);+ expect(zipData.length).toBeGreaterThan(0);++ const unzipped = unzipSync(zipData);+ expect(Object.keys(unzipped)).toContain('slice_001.jpg');+ expect(Object.keys(unzipped)).toContain('slice_002.jpg');+ });+});diff --git a/src/utils/animationEngine.ts b/src/utils/animationEngine.tsnew file mode 100644index 0000000..a10421a--- /dev/null+++ b/src/utils/animationEngine.ts@@ -0,0 +1,601 @@+import { zipSync } from 'fflate';+import { AnimationTimeline, OnionSkinSettings, LayerItem } from '../types/editor';++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> = {};++ // If there are initial raster layers, assign the first to frame 0+ 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', // Cyan+ nextTint: '#ec4899', // Magenta+ opacity: 0.35,+ };++ return {+ fps: 12,+ totalFrames: 24,+ currentFrame: 0,+ cels,+ onionSkin: defaultOnionSkin,+ isPlaying: false,+ loop: true,+ };+}++/**+ * Resolves active cel layer ID for a specific frame index.+ */+export function getFrameCelLayerId(timeline: AnimationTimeline, frame: number): string | null {+ return timeline.cels[frame] ?? null;+}++/**+ * Maps a cel layer ID to a specific frame.+ */+export function setFrameCel(+ timeline: AnimationTimeline,+ frame: number,+ layerId: string+): AnimationTimeline {+ return {+ ...timeline,+ cels: {+ ...timeline.cels,+ [frame]: layerId,+ },+ };+}++/**+ * Removes a cel mapping from a specific frame.+ */+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[] = [];++ // Previous frames (Cyan / Red tint)+ const prevCount = Math.max(1, onionSkin.prevFrames || 2);+ for (let step = 1; step <= prevCount; step++) {+ const f = currentFrame - step;+ if (f >= 0 && cels[f]) {+ // Linear falloff: 1st prior frame gets 100% of base opacity, furthest gets lower+ 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',+ });+ }+ }++ // Next frames (Magenta / Blue tint)+ 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;+}++/**+ * Renders an offscreen canvas tinted with a given hex color.+ */+export function renderTintedCanvas(+ sourceCanvas: HTMLCanvasElement,+ tintColorHex: string,+ opacity: number+): HTMLCanvasElement {+ const canvas = document.createElement('canvas');+ canvas.width = sourceCanvas.width;+ canvas.height = sourceCanvas.height;+ const ctx = canvas.getContext('2d');+ if (!ctx) return canvas;++ ctx.globalAlpha = opacity;+ ctx.drawImage(sourceCanvas, 0, 0);++ // Tint using source-in compositing+ ctx.globalCompositeOperation = 'source-in';+ ctx.fillStyle = tintColorHex;+ ctx.fillRect(0, 0, canvas.width, canvas.height);++ return canvas;+}++/**+ * Composites a single animation frame onto an offscreen canvas.+ * Renders background layers, optional colored onion skinning, active cel, and foreground layers.+ */+export function renderAnimationFrame(+ frameIndex: number,+ timeline: AnimationTimeline,+ layers: LayerItem[],+ layerCanvases: Map<string, HTMLCanvasElement>,+ dimensions: { width: number; height: number },+ includeOnionSkin: boolean = false+): HTMLCanvasElement {+ const canvas = document.createElement('canvas');+ canvas.width = dimensions.width;+ canvas.height = dimensions.height;+ const ctx = canvas.getContext('2d');+ if (!ctx) return canvas;++ // Clear canvas+ ctx.clearRect(0, 0, dimensions.width, dimensions.height);++ const activeCelLayerId = timeline.cels[frameIndex];+ const allCelLayerIds = new Set(Object.values(timeline.cels));++ // 1. Render static background non-cel layers+ for (let i = layers.length - 1; i >= 0; i--) {+ const layer = layers[i];+ if (allCelLayerIds.has(layer.id)) continue;+ if (!layer.visible) continue;++ const c = layerCanvases.get(layer.id);+ if (c) {+ ctx.globalAlpha = layer.opacity;+ ctx.drawImage(c, 0, 0);+ }+ }++ // 2. Render colored onion skin cels if requested+ if (includeOnionSkin && timeline.onionSkin.enabled) {+ const onionFrames = getOnionSkinFrames({+ ...timeline,+ currentFrame: frameIndex,+ });++ for (const info of onionFrames) {+ const c = layerCanvases.get(info.layerId);+ if (c) {+ const tinted = renderTintedCanvas(c, info.tint, info.opacity);+ ctx.drawImage(tinted, 0, 0);+ }+ }+ }++ // 3. Render active frame cel+ if (activeCelLayerId) {+ const celLayer = layers.find((l) => l.id === activeCelLayerId);+ const celCanvas = layerCanvases.get(activeCelLayerId);+ if (celLayer && celCanvas && celLayer.visible) {+ ctx.globalAlpha = celLayer.opacity;+ ctx.drawImage(celCanvas, 0, 0);+ }+ }++ return canvas;+}++/**+ * Downloads a Blob directly to the client's filesystem.+ */+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);+ URL.revokeObjectURL(url);+}++/**+ * Export Pipeline: Exports animation as a zipped numbered PNG sequence.+ */+export async function exportAnimationToPngZip(+ timeline: AnimationTimeline,+ layers: LayerItem[],+ layerCanvases: Map<string, HTMLCanvasElement>,+ dimensions: { width: number; height: number },+ onProgress?: (current: number, total: number) => void+): Promise<Blob> {+ const files: Record<string, Uint8Array> = {};+ const total = timeline.totalFrames;++ for (let f = 0; f < total; f++) {+ onProgress?.(f + 1, total);+ const frameCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);++ // Convert canvas to PNG bytes via DataURL+ const dataUrl = frameCanvas.toDataURL('image/png');+ const base64Data = dataUrl.split(',')[1];+ const binaryStr = atob(base64Data);+ const bytes = new Uint8Array(binaryStr.length);+ for (let i = 0; i < binaryStr.length; i++) {+ bytes[i] = binaryStr.charCodeAt(i);+ }++ const pad = String(f + 1).padStart(4, '0');+ files[`frame_${pad}.png`] = bytes;+ }++ const zipped = zipSync(files, { level: 6 });+ return new Blob([zipped as any], { type: 'application/zip' });+}++/**+ * Export Pipeline: Exports animation to WebM or MP4 video using canvas.captureStream and MediaRecorder.+ */+export async function exportAnimationToVideo(+ timeline: AnimationTimeline,+ layers: LayerItem[],+ layerCanvases: Map<string, HTMLCanvasElement>,+ dimensions: { width: number; height: number },+ onProgress?: (current: number, total: number) => void+): Promise<Blob> {+ const { fps, totalFrames } = timeline;++ const canvas = document.createElement('canvas');+ canvas.width = dimensions.width;+ canvas.height = dimensions.height;+ const ctx = canvas.getContext('2d')!;++ const stream = canvas.captureStream(fps);++ 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 / fps;++ return new Promise<Blob>((resolve, reject) => {+ recorder.onstop = () => {+ const blob = new Blob(chunks, { type: mimeType });+ resolve(blob);+ };+ recorder.onerror = (e) => reject(e);++ recorder.start();++ let frame = 0;+ const renderNext = () => {+ if (frame >= totalFrames) {+ recorder.stop();+ return;+ }++ onProgress?.(frame + 1, totalFrames);+ const frameCanvas = renderAnimationFrame(frame, timeline, layers, layerCanvases, dimensions, false);+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(frameCanvas, 0, 0);++ frame++;+ setTimeout(renderNext, delayMs);+ };++ renderNext();+ });+}++/**+ * Fast Client-Side Animated GIF89a Encoder with LZW compression and Netscape loop block.+ */+export async function exportAnimationToGif(+ timeline: AnimationTimeline,+ layers: LayerItem[],+ layerCanvases: Map<string, HTMLCanvasElement>,+ dimensions: { width: number; height: number },+ onProgress?: (current: number, total: number) => void+): Promise<Blob> {+ const { fps, totalFrames } = timeline;+ const width = Math.min(1280, dimensions.width);+ const height = Math.round((width / dimensions.width) * dimensions.height);++ const delayCentisecs = Math.max(2, Math.round(100 / fps));+ const buffer: number[] = [];++ // GIF Header+ for (const c of 'GIF89a') buffer.push(c.charCodeAt(0));++ // Logical Screen Descriptor+ buffer.push(width & 0xff, (width >> 8) & 0xff);+ buffer.push(height & 0xff, (height >> 8) & 0xff);+ buffer.push(0x70, 0x00, 0x00); // 128 colors, no global color table++ // Netscape 2.0 Loop Block+ buffer.push(0x21, 0xff, 0x0b);+ for (const c of 'NETSCAPE2.0') buffer.push(c.charCodeAt(0));+ buffer.push(0x03, 0x01, 0x00, 0x00, 0x00);++ const renderCanvas = document.createElement('canvas');+ renderCanvas.width = width;+ renderCanvas.height = height;+ const rCtx = renderCanvas.getContext('2d')!;++ for (let f = 0; f < totalFrames; f++) {+ onProgress?.(f + 1, totalFrames);+ const fullCanvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);++ rCtx.clearRect(0, 0, width, height);+ rCtx.drawImage(fullCanvas, 0, 0, width, height);+ const imgData = rCtx.getImageData(0, 0, width, height);+ const pixels = imgData.data;++ // Build adaptive 64-color palette for fast encoding+ 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; // Transparent+ 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; // Fallback+ }+ }+ indexedPixels[i] = colorIdx;+ }++ // Graphic Control Extension (delay and transparent index 0)+ buffer.push(0x21, 0xf9, 0x04, 0x09);+ buffer.push(delayCentisecs & 0xff, (delayCentisecs >> 8) & 0xff);+ buffer.push(0x00, 0x00); // Transparent color index 0++ // Image Descriptor+ buffer.push(0x2c, 0x00, 0x00, 0x00, 0x00);+ buffer.push(width & 0xff, (width >> 8) & 0xff);+ buffer.push(height & 0xff, (height >> 8) & 0xff);+ buffer.push(0x86); // Local color table, 128 entries (7-bit)++ // Local Color Table+ buffer.push(0, 0, 0); // Transparent+ 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);+ }+ }++ // Uncompressed LZW raster data+ const minCodeSize = 7;+ buffer.push(minCodeSize);++ let offset = 0;+ while (offset < indexedPixels.length) {+ const blockSize = Math.min(254, indexedPixels.length - offset);+ buffer.push(blockSize + 1);+ buffer.push(1 << minCodeSize); // Clear code+ for (let j = 0; j < blockSize; j++) {+ buffer.push(indexedPixels[offset + j]);+ }+ offset += blockSize;+ }+ buffer.push(0x01, (1 << minCodeSize) + 1); // End of information code+ buffer.push(0x00); // Block terminator+ }++ // GIF Trailer+ buffer.push(0x3b);++ return new Blob([new Uint8Array(buffer)], { type: 'image/gif' });+}++/**+ * Exports animation as an Animated PNG (APNG).+ */+export async function exportAnimationToApng(+ timeline: AnimationTimeline,+ layers: LayerItem[],+ layerCanvases: Map<string, HTMLCanvasElement>,+ dimensions: { width: number; height: number },+ onProgress?: (current: number, total: number) => void+): Promise<Blob> {+ const { fps, totalFrames } = timeline;+ const numFrames = totalFrames;++ // Render all frames to PNG array buffers+ const framePngBuffers: ArrayBuffer[] = [];+ for (let f = 0; f < numFrames; f++) {+ onProgress?.(f + 1, numFrames);+ const canvas = renderAnimationFrame(f, timeline, layers, layerCanvases, dimensions, false);+ const dataUrl = canvas.toDataURL('image/png');+ const base64 = dataUrl.split(',')[1];+ const binStr = atob(base64);+ const buf = new Uint8Array(binStr.length);+ for (let i = 0; i < binStr.length; i++) buf[i] = binStr.charCodeAt(i);+ framePngBuffers.push(buf.buffer);+ }++ // Helper CRC32 table+ 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;+ };++ // Parse chunks from first frame+ const f0 = new Uint8Array(framePngBuffers[0]);+ let offset = 8; // skip 8-byte signature+ let ihdrChunk: Uint8Array | null = null;+ const idatChunks: Uint8Array[] = [];++ while (offset < f0.length) {+ const len = new DataView(f0.buffer, 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[] = [];+ // PNG Signature+ outChunks.push(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));+ if (ihdrChunk) outChunks.push(ihdrChunk);++ // acTL chunk (num_frames: 4 bytes, num_plays: 4 bytes: 0 for infinite loop)+ const actlData = new Uint8Array(8);+ const actlDv = new DataView(actlData.buffer);+ actlDv.setUint32(0, numFrames);+ actlDv.setUint32(4, 0);+ outChunks.push(createChunk('acTL', actlData));++ let seq = 0;++ // Frame 0: fcTL + IDATs+ 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); // x offset+ fctl0Dv.setUint32(16, 0); // y offset+ fctl0Dv.setUint16(20, 1); // delay num+ fctl0Dv.setUint16(22, fps); // delay den+ fctl0Dv.setUint8(24, 0); // dispose op (none)+ fctl0Dv.setUint8(25, 0); // blend op (source)+ outChunks.push(createChunk('fcTL', fctl0));++ for (const idat of idatChunks) {+ outChunks.push(createChunk('IDAT', idat));+ }++ // Frames 1..N-1: fcTL + fdATs+ for (let f = 1; f < numFrames; f++) {+ const fnBytes = new Uint8Array(framePngBuffers[f]);+ let fOffset = 8;+ const fnIdats: Uint8Array[] = [];++ while (fOffset < fnBytes.length) {+ const len = new DataView(fnBytes.buffer, 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, fps);+ 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));+ }+ }++ // IEND chunk+ 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' });+}diff --git a/src/utils/balloonEngine.ts b/src/utils/balloonEngine.tsnew file mode 100644index 0000000..adfe700--- /dev/null+++ b/src/utils/balloonEngine.ts@@ -0,0 +1,300 @@+/**+ * Parametric Vector Speech Balloon Engine+ *+ * Implements Clip Studio Paint EX-style manga speech balloons with:+ * - Parametric body shapes: Ellipse, Rounded-Rect, Jagged-Flash, and Thought bubble+ * - Draggable vector bezier tails (start, control1, control2, tip)+ * - Automatic centered text wrapping (horizontal-tb or vertical-rl manga lettering)+ * - Interactive bounding box and tail handle manipulation+ */++import { SpeechBalloon, SpeechBalloonTail, Point } from '../types/editor';+import { renderMangaTextToCanvas } from './mangaTextEngine';++export interface BalloonHandle {+ id: string;+ type: 'resize' | 'tail-tip' | 'tail-ctrl1' | 'tail-ctrl2' | 'tail-start';+ x: number;+ y: number;+ cursor: string;+}++/**+ * Creates a default parametric speech balloon at the given location.+ */+export function createDefaultSpeechBalloon(+ x: number,+ y: number,+ width = 200,+ height = 140,+ shape: SpeechBalloon['shape'] = 'ellipse'+): SpeechBalloon {+ const startX = x + width * 0.5;+ const startY = y + height - 2;+ const tipX = x + width * 0.3;+ const tipY = y + height + 50;++ const tail: SpeechBalloonTail = {+ start: { x: startX, y: startY, pressure: 1, width: 20 },+ control1: { x: startX - 10, y: startY + 25, pressure: 1, width: 15 },+ control2: { x: tipX + 15, y: tipY - 20, pressure: 1, width: 10 },+ tip: { x: tipX, y: tipY, pressure: 1, width: 4 },+ };++ return {+ id: `balloon-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,+ shape,+ bounds: { x, y, width, height },+ tail,+ fillColor: '#ffffff',+ strokeColor: '#000000',+ strokeWidth: 3,+ text: '',+ fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",+ fontSize: 22,+ vertical: false,+ };+}++/**+ * Builds the geometric path of the speech balloon body.+ */+export function traceBalloonBodyPath(+ ctx: CanvasRenderingContext2D,+ balloon: SpeechBalloon+): void {+ const { x, y, width: w, height: h } = balloon.bounds;+ const cx = x + w * 0.5;+ const cy = y + h * 0.5;+ const rx = Math.max(10, w * 0.5);+ const ry = Math.max(10, h * 0.5);++ ctx.beginPath();++ switch (balloon.shape) {+ case 'ellipse': {+ ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);+ break;+ }++ case 'rounded-rect': {+ const radius = Math.min(24, w * 0.2, h * 0.2);+ ctx.roundRect(x, y, w, h, radius);+ break;+ }++ case 'jagged-flash': {+ // Dynamic manga explosive/shout flash balloon+ const teeth = 20;+ const angleStep = (Math.PI * 2) / teeth;+ for (let i = 0; i < teeth; i++) {+ const theta1 = i * angleStep;+ const theta2 = (i + 0.5) * angleStep;++ const outerFactor = 1.05 + 0.15 * Math.sin(i * 3.7);+ const innerFactor = 0.78 + 0.08 * Math.cos(i * 2.3);++ const xOuter = cx + Math.cos(theta1) * rx * outerFactor;+ const yOuter = cy + Math.sin(theta1) * ry * outerFactor;+ const xInner = cx + Math.cos(theta2) * rx * innerFactor;+ const yInner = cy + Math.sin(theta2) * ry * innerFactor;++ if (i === 0) {+ ctx.moveTo(xOuter, yOuter);+ } else {+ ctx.lineTo(xOuter, yOuter);+ }+ ctx.lineTo(xInner, yInner);+ }+ ctx.closePath();+ break;+ }++ case 'thought': {+ // Cloud thought bubble composed of circular puffs+ const puffs = 12;+ const angleStep = (Math.PI * 2) / puffs;+ const puffRadius = Math.min(rx, ry) * 0.35;++ for (let i = 0; i < puffs; i++) {+ const theta = i * angleStep;+ const px = cx + Math.cos(theta) * (rx - puffRadius * 0.5);+ const py = cy + Math.sin(theta) * (ry - puffRadius * 0.5);++ ctx.moveTo(px + puffRadius, py);+ ctx.arc(px, py, puffRadius, 0, Math.PI * 2);+ }+ break;+ }+ }+}++/**+ * Builds the geometric path of the draggable vector tail.+ */+export function traceBalloonTailPath(+ ctx: CanvasRenderingContext2D,+ tail: SpeechBalloonTail,+ baseWidth = 24+): void {+ const { start, control1, control2, tip } = tail;++ // Compute normal vector at base+ const dx = tip.x - start.x;+ const dy = tip.y - start.y;+ const len = Math.hypot(dx, dy) || 1;+ const nx = -dy / len;+ const ny = dx / len;++ const halfW = baseWidth * 0.5;+ const b1x = start.x - nx * halfW;+ const b1y = start.y - ny * halfW;+ const b2x = start.x + nx * halfW;+ const b2y = start.y + ny * halfW;++ ctx.beginPath();+ ctx.moveTo(b1x, b1y);+ // Curve 1 down to tip+ ctx.bezierCurveTo(+ control1.x - nx * (halfW * 0.4),+ control1.y - ny * (halfW * 0.4),+ control2.x,+ control2.y,+ tip.x,+ tip.y+ );+ // Curve 2 back to b2+ ctx.bezierCurveTo(+ control2.x + nx * (halfW * 0.2),+ control2.y + ny * (halfW * 0.2),+ control1.x + nx * (halfW * 0.4),+ control1.y + ny * (halfW * 0.4),+ b2x,+ b2y+ );+ ctx.closePath();+}++/**+ * Renders a full SpeechBalloon onto a Canvas2D context.+ */+export function renderSpeechBalloon(+ ctx: CanvasRenderingContext2D,+ balloon: SpeechBalloon+): void {+ const { bounds, tail, fillColor, strokeColor, strokeWidth, text } = balloon;++ ctx.save();+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';++ // 1. Fill Tail+ traceBalloonTailPath(ctx, tail, 26);+ ctx.fillStyle = fillColor;+ ctx.fill();++ // 2. Stroke Tail+ if (strokeWidth > 0) {+ ctx.strokeStyle = strokeColor;+ ctx.lineWidth = strokeWidth;+ ctx.stroke();+ }++ // 3. Fill Body over tail attachment+ traceBalloonBodyPath(ctx, balloon);+ ctx.fillStyle = fillColor;+ ctx.fill();++ // 4. Stroke Body+ if (strokeWidth > 0) {+ ctx.strokeStyle = strokeColor;+ ctx.lineWidth = strokeWidth;+ ctx.stroke();+ }++ // 5. If thought bubble, draw little thought trailing bubbles+ if (balloon.shape === 'thought') {+ const tip = tail.tip;+ const dot1x = tip.x - 8;+ const dot1y = tip.y + 14;+ const dot2x = tip.x - 16;+ const dot2y = tip.y + 28;++ ctx.fillStyle = fillColor;+ ctx.strokeStyle = strokeColor;+ ctx.lineWidth = strokeWidth;++ ctx.beginPath();+ ctx.arc(dot1x, dot1y, 7, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();++ ctx.beginPath();+ ctx.arc(dot2x, dot2y, 4, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();+ }++ // 6. Centered Manga Text+ if (text && text.trim()) {+ const centerX = bounds.x + bounds.width * 0.5;+ const centerY = bounds.y + bounds.height * 0.5;++ renderMangaTextToCanvas(ctx, text, centerX, centerY, {+ fontSize: balloon.fontSize || 20,+ fontFamily: balloon.fontFamily || 'sans-serif',+ writingMode: balloon.vertical ? 'vertical-rl' : 'horizontal-tb',+ align: 'center',+ color: strokeColor,+ bold: true,+ lineHeightRatio: 1.3,+ });+ }++ ctx.restore();+}++/**+ * Returns interactive handles for manipulating the speech balloon on the canvas overlay.+ */+export function getBalloonHandles(balloon: SpeechBalloon): BalloonHandle[] {+ const { x, y, width: w, height: h } = balloon.bounds;+ const { tail } = balloon;++ return [+ // 8 Bounding Box Resize Handles+ { id: 'nw', type: 'resize', x, y, cursor: 'nwse-resize' },+ { id: 'n', type: 'resize', x: x + w * 0.5, y, cursor: 'ns-resize' },+ { id: 'ne', type: 'resize', x: x + w, y, cursor: 'nesw-resize' },+ { id: 'e', type: 'resize', x: x + w, y: y + h * 0.5, cursor: 'ew-resize' },+ { id: 'se', type: 'resize', x: x + w, y: y + h, cursor: 'nwse-resize' },+ { id: 's', type: 'resize', x: x + w * 0.5, y: y + h, cursor: 'ns-resize' },+ { id: 'sw', type: 'resize', x, y: y + h, cursor: 'nesw-resize' },+ { id: 'w', type: 'resize', x, y: y + h * 0.5, cursor: 'ew-resize' },++ // Tail tip handle+ { id: 'tail-tip', type: 'tail-tip', x: tail.tip.x, y: tail.tip.y, cursor: 'grab' },+ // Tail control points+ { id: 'tail-ctrl1', type: 'tail-ctrl1', x: tail.control1.x, y: tail.control1.y, cursor: 'crosshair' },+ { id: 'tail-ctrl2', type: 'tail-ctrl2', x: tail.control2.x, y: tail.control2.y, cursor: 'crosshair' },+ // Tail start anchor+ { id: 'tail-start', type: 'tail-start', x: tail.start.x, y: tail.start.y, cursor: 'move' },+ ];+}++/**+ * Hit test a point against speech balloon bounds or body.+ */+export function hitTestBalloon(+ balloon: SpeechBalloon,+ point: Point | { x: number; y: number }+): boolean {+ const { x, y, width: w, height: h } = balloon.bounds;+ // Bounding box hit test with small margin+ return (+ point.x >= x - 5 &&+ point.x <= x + w + 5 &&+ point.y >= y - 5 &&+ point.y <= y + h + 5+ );+}diff --git a/src/utils/compositor.ts b/src/utils/compositor.tsindex 8aff3ff..b915c78 100644--- a/src/utils/compositor.ts+++ b/src/utils/compositor.ts@@ -322,11 +322,18 @@ void main() {}`;+export interface OnionSkinCompositorFrame {+ layerId: string;+ tint: string;+ opacity: number;+}+export interface CompositorOptions {dimensions: CanvasDimensions;colorMode?: CanvasColorMode;showCheckerboard?: boolean;devicePixelRatio?: number;+ onionSkinFrames?: OnionSkinCompositorFrame[];}/**@@ -791,7 +798,25 @@ export class ViewportCompositor {gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);- // Render layers in bottom-to-top order grouped by clipping masks+ // 2. Render colored onion skin cels if active in animation mode+ if (_options.onionSkinFrames && _options.onionSkinFrames.length > 0) {+ for (const onion of _options.onionSkinFrames) {+ const targetLayer = layers.find((l) => l.id === onion.layerId);+ if (targetLayer && targetLayer.visible) {+ const virtualOnionLayer: LayerItem = {+ ...targetLayer,+ opacity: onion.opacity,+ layerColorEnabled: true,+ layerColor: onion.tint,+ layerSubColor: '#ffffff',+ blendMode: 'normal',+ };+ this.renderSingleLayer(gl, virtualOnionLayer, dimensions, grid, frustum);+ }+ }+ }++ // 3. Render layers in bottom-to-top order grouped by clipping masksconst renderOrder = layers.slice().reverse();const groups = groupLayersForCompositing(renderOrder);diff --git a/src/utils/mangaEffectsEngine.ts b/src/utils/mangaEffectsEngine.tsnew file mode 100644index 0000000..5cd0f9d--- /dev/null+++ b/src/utils/mangaEffectsEngine.ts@@ -0,0 +1,201 @@+/**+ * Manga Effect Lines Generator Engine+ *+ * Implements Clip Studio Paint EX-grade parametric manga action effects:+ * - Saturated Lines (Focus / Burst / Shonen Impact lines): Radiating toward a center target+ * with configurable center cutout radius, density, spacing jitter, and needle taper.+ * - Stream Lines (Directional Speed / Motion lines): Directional parallel speed lines+ * with angle, length, density, thickness noise, and tapered tails.+ */++export interface SaturatedLinesOptions {+ centerX: number;+ centerY: number;+ innerRadius: number; // Cutout radius around center target (e.g. face / action point)+ outerRadius?: number; // Outer boundary radius+ density: number; // Number of radiating lines (30 - 600)+ spacingJitter: number; // Angular jitter (0.0 to 1.0)+ lengthJitter: number; // Variation in starting & ending depth (0.0 to 1.0)+ lineWidth: number; // Outer stroke thickness (1 to 15)+ taper?: 'in' | 'out' | 'none'; // 'in' = thick at border, sharp needle tip towards center+ color: string;+}++export interface StreamLinesOptions {+ angle: number; // In degrees (0° to 360°)+ density: number; // Number of parallel speed streaks (10 to 400)+ lineLength: number; // Mean streak length (50 to 1500)+ lengthNoise: number; // Length jitter ratio (0.0 to 1.0)+ thickness: number; // Mean stroke thickness (1 to 12)+ thicknessNoise: number; // Thickness variation (0.0 to 1.0)+ gapNoise: number; // Spacing jitter along perpendicular axis (0.0 to 1.0)+ color: string;+}++// Pseudo-random number generator for reproducible procedural effects+function pseudoRandom(seed: number): () => number {+ let s = seed % 2147483647;+ if (s <= 0) s += 2147483646;+ return () => {+ s = (s * 16807) % 2147483647;+ return (s - 1) / 2147483646;+ };+}++/**+ * Renders Saturated / Focus / Burst lines radiating towards a center focal point.+ */+export function renderSaturatedLines(+ ctx: CanvasRenderingContext2D,+ canvasWidth: number,+ canvasHeight: number,+ options: SaturatedLinesOptions+): void {+ const {+ centerX,+ centerY,+ innerRadius,+ density = 120,+ spacingJitter = 0.5,+ lengthJitter = 0.3,+ lineWidth = 4,+ taper = 'in',+ color = '#000000',+ } = options;++ const maxCanvasRadius = Math.hypot(+ Math.max(centerX, canvasWidth - centerX),+ Math.max(centerY, canvasHeight - centerY)+ ) * 1.2;++ const outerRadius = options.outerRadius || maxCanvasRadius;+ const count = Math.max(8, Math.min(1000, density));+ const rng = pseudoRandom(1337 + count);++ ctx.save();+ ctx.fillStyle = color;+ ctx.strokeStyle = color;++ const baseAngleStep = (Math.PI * 2) / count;++ for (let i = 0; i < count; i++) {+ // Angular spacing with jitter+ const jitter = (rng() - 0.5) * spacingJitter * baseAngleStep * 1.5;+ const angle = i * baseAngleStep + jitter;++ // Radius start and end with jitter+ const inJitter = (rng() - 0.5) * lengthJitter * innerRadius * 0.5;+ const rStart = Math.max(2, innerRadius + inJitter);++ const outJitter = (rng() - 0.5) * lengthJitter * 60;+ const rEnd = outerRadius + outJitter;++ if (rStart >= rEnd) continue;++ const cosA = Math.cos(angle);+ const sinA = Math.sin(angle);+ // Perpendicular unit vector+ const perpX = -sinA;+ const perpY = cosA;++ // Line taper calculation+ const wOuter = (lineWidth * (0.6 + rng() * 0.8));+ const wInner = taper === 'in' ? 0.2 : (taper === 'none' ? wOuter : 0.2);+ const effectiveWOuter = taper === 'out' ? 0.2 : wOuter;++ // Coordinates of outer corners and inner corners (drawn as tapered polygon)+ const xOuter1 = centerX + cosA * rEnd - perpX * (effectiveWOuter * 0.5);+ const yOuter1 = centerY + sinA * rEnd - perpY * (effectiveWOuter * 0.5);+ const xOuter2 = centerX + cosA * rEnd + perpX * (effectiveWOuter * 0.5);+ const yOuter2 = centerY + sinA * rEnd + perpY * (effectiveWOuter * 0.5);++ const xInner1 = centerX + cosA * rStart + perpX * (wInner * 0.5);+ const yInner1 = centerY + sinA * rStart + perpY * (wInner * 0.5);+ const xInner2 = centerX + cosA * rStart - perpX * (wInner * 0.5);+ const yInner2 = centerY + sinA * rStart - perpY * (wInner * 0.5);++ ctx.beginPath();+ ctx.moveTo(xOuter1, yOuter1);+ ctx.lineTo(xOuter2, yOuter2);+ ctx.lineTo(xInner1, yInner1);+ ctx.lineTo(xInner2, yInner2);+ ctx.closePath();+ ctx.fill();+ }++ ctx.restore();+}++/**+ * Renders directional Stream / Speed / Motion lines.+ */+export function renderStreamLines(+ ctx: CanvasRenderingContext2D,+ canvasWidth: number,+ canvasHeight: number,+ options: StreamLinesOptions+): void {+ const {+ angle = 0,+ density = 80,+ lineLength = 400,+ lengthNoise = 0.4,+ thickness = 3,+ thicknessNoise = 0.5,+ gapNoise = 0.4,+ color = '#000000',+ } = options;++ const rad = (angle * Math.PI) / 180;+ const dirX = Math.cos(rad);+ const dirY = Math.sin(rad);+ const perpX = -dirY;+ const perpY = dirX;++ // Diagonal span to cover entire rotated canvas+ const diag = Math.hypot(canvasWidth, canvasHeight);+ const count = Math.max(5, Math.min(800, density));+ const rng = pseudoRandom(42 + count + Math.round(angle));++ ctx.save();+ ctx.fillStyle = color;++ const centerX = canvasWidth * 0.5;+ const centerY = canvasHeight * 0.5;++ const bandStep = (diag * 1.4) / count;++ for (let i = 0; i < count; i++) {+ const bandOffset = (i - count * 0.5) * bandStep + (rng() - 0.5) * gapNoise * bandStep;+ // Longitudinal shift along speed line direction+ const longShift = (rng() - 0.5) * diag * 0.9;++ const streakLen = Math.max(20, lineLength * (1 + (rng() - 0.5) * lengthNoise * 1.5));+ const streakThick = Math.max(0.6, thickness * (1 + (rng() - 0.5) * thicknessNoise * 1.2));++ // Base origin point on the perpendicular swath+ const px = centerX + perpX * bandOffset + dirX * longShift;+ const py = centerY + perpY * bandOffset + dirY * longShift;++ // Start, mid, and end points of speed needle+ const startX = px - dirX * (streakLen * 0.5);+ const startY = py - dirY * (streakLen * 0.5);+ const endX = px + dirX * (streakLen * 0.5);+ const endY = py + dirY * (streakLen * 0.5);++ // Tapered diamond / speed blade+ const midX = px;+ const midY = py;+ const halfW = streakThick * 0.5;++ ctx.beginPath();+ ctx.moveTo(startX, startY);+ ctx.lineTo(midX + perpX * halfW, midY + perpY * halfW);+ ctx.lineTo(endX, endY);+ ctx.lineTo(midX - perpX * halfW, midY - perpY * halfW);+ ctx.closePath();+ ctx.fill();+ }++ ctx.restore();+}diff --git a/src/utils/mangaTextEngine.ts b/src/utils/mangaTextEngine.tsnew file mode 100644index 0000000..9e23fe1--- /dev/null+++ b/src/utils/mangaTextEngine.ts@@ -0,0 +1,212 @@+/**+ * Manga Lettering & Text Layout Engine+ *+ * Implements Clip Studio Paint EX-grade text formatting with support for:+ * - Traditional Japanese / East Asian vertical lettering (tate-gaki: vertical-rl, right-to-left columns)+ * - Punctuation shifting (e.g. Japanese full stops and commas positioned top-right)+ * - Glyphs and Latin/dash rotation (90° clockwise rotation for em-dashes, brackets, tildes)+ * - Automatic centering and boundary containment for speech balloons+ */++export interface MangaTextOptions {+ fontSize: number;+ fontFamily: string;+ writingMode?: 'horizontal-tb' | 'vertical-rl';+ bold?: boolean;+ italic?: boolean;+ align?: 'left' | 'center' | 'right';+ color?: string;+ outline?: boolean;+ outlineColor?: string;+ outlineWidth?: number;+ lineHeightRatio?: number;+ maxWidth?: number;+ maxHeight?: number;+}++export interface PositionedGlyph {+ char: string;+ x: number;+ y: number;+ rotateDeg: number;+ scaleX?: number;+ scaleY?: number;+}++export interface TextLayoutResult {+ glyphs: PositionedGlyph[];+ width: number;+ height: number;+}++// Characters that should be rotated 90 degrees clockwise in vertical writing mode+const ROTATED_PUNCTUATION = new Set([+ '—', '―', '–', '-', '―', '…', '‥', '~', '~', ':', ';',+ '「', '」', '『', '』', '(', ')', '(', ')', '【', '】',+ '[', ']', '[', ']', '{', '}', '{', '}', '〈', '〉',+ '《', '》', '<', '>', '<', '>', '〔', '〕', '|', '|',+ '=' , '=', '_', '_'+]);++// Japanese punctuation that needs shifting to the upper right corner in vertical mode+const SHIFTED_PUNCTUATION = new Set([+ '。', '、', ',', '.', '・'+]);++/**+ * Checks if a character is an ASCII Latin letter or digit+ */+export function isLatinChar(char: string): boolean {+ const code = char.charCodeAt(0);+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57);+}++/**+ * Computes glyph positions for horizontal or vertical manga lettering.+ */+export function computeMangaTextLayout(+ text: string,+ options: MangaTextOptions+): TextLayoutResult {+ const isVertical = options.writingMode === 'vertical-rl';+ const fontSize = options.fontSize || 20;+ const lineHeightRatio = options.lineHeightRatio || (isVertical ? 1.4 : 1.25);+ const lineSpacing = fontSize * lineHeightRatio;+ const rawLines = text.split('\n');++ if (!isVertical) {+ // Standard horizontal-tb layout+ const glyphs: PositionedGlyph[] = [];+ const charWidth = fontSize * 0.6; // estimated fallback+ let maxLineWidth = 0;++ rawLines.forEach((line, lineIdx) => {+ const lineY = lineIdx * lineSpacing + fontSize * 0.5;+ const lineWidth = line.length * charWidth;+ if (lineWidth > maxLineWidth) maxLineWidth = lineWidth;++ for (let cIdx = 0; cIdx < line.length; cIdx++) {+ glyphs.push({+ char: line[cIdx],+ x: cIdx * charWidth + charWidth * 0.5,+ y: lineY,+ rotateDeg: 0,+ });+ }+ });++ const totalHeight = rawLines.length * lineSpacing;+ return {+ glyphs,+ width: Math.max(fontSize, maxLineWidth),+ height: Math.max(fontSize, totalHeight),+ };+ }++ // Vertical-rl layout: Columns proceed Right to Left, characters Top to Bottom+ const numColumns = rawLines.length;+ const totalWidth = numColumns * lineSpacing;+ let maxColHeight = 0;+ const glyphs: PositionedGlyph[] = [];++ rawLines.forEach((line, colIndex) => {+ // In vertical-rl, col 0 is at rightmost position (x = (numColumns - 1 - colIndex) * lineSpacing)+ const colX = (numColumns - 1 - colIndex) * lineSpacing + lineSpacing * 0.5;+ let currentY = fontSize * 0.6;++ for (let cIdx = 0; cIdx < line.length; cIdx++) {+ const char = line[cIdx];+ let rotateDeg = 0;+ let dx = 0;+ let dy = 0;+ const stepY = fontSize;++ if (ROTATED_PUNCTUATION.has(char)) {+ rotateDeg = 90;+ } else if (SHIFTED_PUNCTUATION.has(char)) {+ // Shift to top-right quadrant+ dx = fontSize * 0.28;+ dy = -fontSize * 0.28;+ }++ glyphs.push({+ char,+ x: colX + dx,+ y: currentY + dy,+ rotateDeg,+ });++ currentY += stepY;+ }++ if (currentY > maxColHeight) {+ maxColHeight = currentY;+ }+ });++ return {+ glyphs,+ width: Math.max(fontSize, totalWidth),+ height: Math.max(fontSize, maxColHeight),+ };+}++/**+ * Renders manga text onto a 2D Canvas context.+ * Automatically aligns to (originX, originY) according to options.+ */+export function renderMangaTextToCanvas(+ ctx: CanvasRenderingContext2D,+ text: string,+ originX: number,+ originY: number,+ options: MangaTextOptions+): void {+ if (!text || !text.trim()) return;++ const fontSize = options.fontSize || 20;+ const fontStyle = `${options.italic ? 'italic ' : ''}${options.bold ? 'bold ' : ''}${fontSize}px ${options.fontFamily || 'sans-serif'}`;+ const layout = computeMangaTextLayout(text, options);++ ctx.save();+ ctx.font = fontStyle;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';++ // Compute bounding offset so text is centered or aligned around (originX, originY)+ let offsetX = originX - layout.width * 0.5;+ let offsetY = originY - layout.height * 0.5;++ if (options.align === 'left') {+ offsetX = originX;+ } else if (options.align === 'right') {+ offsetX = originX - layout.width;+ }++ for (const g of layout.glyphs) {+ const gx = offsetX + g.x;+ const gy = offsetY + g.y;++ ctx.save();+ ctx.translate(gx, gy);+ if (g.rotateDeg !== 0) {+ ctx.rotate((g.rotateDeg * Math.PI) / 180);+ }++ // Outline stroke+ if (options.outline && (options.outlineWidth || 0) > 0) {+ ctx.strokeStyle = options.outlineColor || '#ffffff';+ ctx.lineWidth = (options.outlineWidth || 2) * 2;+ ctx.lineJoin = 'round';+ ctx.miterLimit = 2;+ ctx.strokeText(g.char, 0, 0);+ }++ // Main fill+ ctx.fillStyle = options.color || '#000000';+ ctx.fillText(g.char, 0, 0);+ ctx.restore();+ }++ ctx.restore();+}diff --git a/src/utils/mannequin3D.ts b/src/utils/mannequin3D.tsnew file mode 100644index 0000000..2fdb836--- /dev/null+++ b/src/utils/mannequin3D.ts@@ -0,0 +1,562 @@+import * as THREE from 'three';+import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';++export type PosePresetName = 'standing' | 'action' | 'sitting' | 'fists' | 'relaxed_palm';++export interface HumanoidBones {+ root?: THREE.Bone;+ hips?: THREE.Bone;+ spine?: THREE.Bone;+ chest?: THREE.Bone;+ neck?: THREE.Bone;+ head?: THREE.Bone;+ leftShoulder?: THREE.Bone;+ leftUpperArm?: THREE.Bone;+ leftLowerArm?: THREE.Bone;+ leftHand?: THREE.Bone;+ rightShoulder?: THREE.Bone;+ rightUpperArm?: THREE.Bone;+ rightLowerArm?: THREE.Bone;+ rightHand?: THREE.Bone;+ leftUpperLeg?: THREE.Bone;+ leftLowerLeg?: THREE.Bone;+ leftFoot?: THREE.Bone;+ rightUpperLeg?: THREE.Bone;+ rightLowerLeg?: THREE.Bone;+ rightFoot?: THREE.Bone;+ [key: string]: THREE.Bone | undefined;+}++export interface IKTarget {+ name: 'head' | 'leftHand' | 'rightHand' | 'leftFoot' | 'rightFoot';+ object: THREE.Mesh;+ pole: THREE.Vector3;+}++/**+ * Creates a stylized humanoid drawing mannequin as a THREE.SkinnedMesh.+ * Rigged with standard hierarchy and anime/manga drawing doll proportions.+ */+export function createProceduralMannequin(): {+ group: THREE.Group;+ skinnedMesh: THREE.SkinnedMesh;+ skeleton: THREE.Skeleton;+ bones: HumanoidBones;+} {+ const group = new THREE.Group();+ group.name = 'HumanoidMannequin';++ // 1. Build Bone Hierarchy+ const hips = new THREE.Bone();+ hips.name = 'Hips';+ hips.position.set(0, 0.95, 0);++ const spine = new THREE.Bone();+ spine.name = 'Spine';+ spine.position.set(0, 0.2, 0);+ hips.add(spine);++ const chest = new THREE.Bone();+ chest.name = 'Chest';+ chest.position.set(0, 0.22, 0);+ spine.add(chest);++ const neck = new THREE.Bone();+ neck.name = 'Neck';+ neck.position.set(0, 0.18, 0);+ chest.add(neck);++ const head = new THREE.Bone();+ head.name = 'Head';+ head.position.set(0, 0.15, 0);+ neck.add(head);++ // Left Arm+ const leftShoulder = new THREE.Bone();+ leftShoulder.name = 'LeftShoulder';+ leftShoulder.position.set(0.18, 0.14, 0);+ chest.add(leftShoulder);++ const leftUpperArm = new THREE.Bone();+ leftUpperArm.name = 'LeftUpperArm';+ leftUpperArm.position.set(0.12, 0, 0);+ leftShoulder.add(leftUpperArm);++ const leftLowerArm = new THREE.Bone();+ leftLowerArm.name = 'LeftLowerArm';+ leftLowerArm.position.set(0, -0.28, 0);+ leftUpperArm.add(leftLowerArm);++ const leftHand = new THREE.Bone();+ leftHand.name = 'LeftHand';+ leftHand.position.set(0, -0.26, 0);+ leftLowerArm.add(leftHand);++ // Right Arm+ const rightShoulder = new THREE.Bone();+ rightShoulder.name = 'RightShoulder';+ rightShoulder.position.set(-0.18, 0.14, 0);+ chest.add(rightShoulder);++ const rightUpperArm = new THREE.Bone();+ rightUpperArm.name = 'RightUpperArm';+ rightUpperArm.position.set(-0.12, 0, 0);+ rightShoulder.add(rightUpperArm);++ const rightLowerArm = new THREE.Bone();+ rightLowerArm.name = 'RightLowerArm';+ rightLowerArm.position.set(0, -0.28, 0);+ rightUpperArm.add(rightLowerArm);++ const rightHand = new THREE.Bone();+ rightHand.name = 'RightHand';+ rightHand.position.set(0, -0.26, 0);+ rightLowerArm.add(rightHand);++ // Left Leg+ const leftUpperLeg = new THREE.Bone();+ leftUpperLeg.name = 'LeftUpperLeg';+ leftUpperLeg.position.set(0.12, -0.05, 0);+ hips.add(leftUpperLeg);++ const leftLowerLeg = new THREE.Bone();+ leftLowerLeg.name = 'LeftLowerLeg';+ leftLowerLeg.position.set(0, -0.42, 0);+ leftUpperLeg.add(leftLowerLeg);++ const leftFoot = new THREE.Bone();+ leftFoot.name = 'LeftFoot';+ leftFoot.position.set(0, -0.42, 0.04);+ leftLowerLeg.add(leftFoot);++ // Right Leg+ const rightUpperLeg = new THREE.Bone();+ rightUpperLeg.name = 'RightUpperLeg';+ rightUpperLeg.position.set(-0.12, -0.05, 0);+ hips.add(rightUpperLeg);++ const rightLowerLeg = new THREE.Bone();+ rightLowerLeg.name = 'RightLowerLeg';+ rightLowerLeg.position.set(0, -0.42, 0);+ rightUpperLeg.add(rightLowerLeg);++ const rightFoot = new THREE.Bone();+ rightFoot.name = 'RightFoot';+ rightFoot.position.set(0, -0.42, 0.04);+ rightLowerLeg.add(rightFoot);++ const boneList = [+ hips, // 0+ spine, // 1+ chest, // 2+ neck, // 3+ head, // 4+ leftShoulder, // 5+ leftUpperArm, // 6+ leftLowerArm, // 7+ leftHand, // 8+ rightShoulder, // 9+ rightUpperArm, // 10+ rightLowerArm, // 11+ rightHand, // 12+ leftUpperLeg, // 13+ leftLowerLeg, // 14+ leftFoot, // 15+ rightUpperLeg, // 16+ rightLowerLeg, // 17+ rightFoot, // 18+ ];++ const bonesMap: HumanoidBones = {+ hips,+ spine,+ chest,+ neck,+ head,+ leftShoulder,+ leftUpperArm,+ leftLowerArm,+ leftHand,+ rightShoulder,+ rightUpperArm,+ rightLowerArm,+ rightHand,+ leftUpperLeg,+ leftLowerLeg,+ leftFoot,+ rightUpperLeg,+ rightLowerLeg,+ rightFoot,+ };++ // 2. Build segmented mannequin meshes bound to bones+ const geometries: THREE.BufferGeometry[] = [];++ const addPart = (+ geom: THREE.BufferGeometry,+ boneIndex: number,+ offset: THREE.Vector3,+ rot?: THREE.Euler,+ scale?: THREE.Vector3+ ) => {+ geom = geom.clone();+ if (scale) geom.scale(scale.x, scale.y, scale.z);+ if (rot) geom.applyQuaternion(new THREE.Quaternion().setFromEuler(rot));+ geom.translate(offset.x, offset.y, offset.z);++ const count = geom.attributes.position.count;+ const skinIndices = new Float32Array(count * 4);+ const skinWeights = new Float32Array(count * 4);++ for (let i = 0; i < count; i++) {+ skinIndices[i * 4] = boneIndex;+ skinIndices[i * 4 + 1] = 0;+ skinIndices[i * 4 + 2] = 0;+ skinIndices[i * 4 + 3] = 0;++ skinWeights[i * 4] = 1.0;+ skinWeights[i * 4 + 1] = 0.0;+ skinWeights[i * 4 + 2] = 0.0;+ skinWeights[i * 4 + 3] = 0.0;+ }++ geom.setAttribute('skinIndex', new THREE.BufferAttribute(skinIndices, 4));+ geom.setAttribute('skinWeight', new THREE.BufferAttribute(skinWeights, 4));+ geometries.push(geom);+ };++ // World bone base positions for geometry placement+ // Pelvis / Hips+ addPart(new THREE.CylinderGeometry(0.14, 0.11, 0.16, 16), 0, new THREE.Vector3(0, 0.95, 0));+ // Spine (Mid Torso)+ addPart(new THREE.CylinderGeometry(0.13, 0.12, 0.18, 16), 1, new THREE.Vector3(0, 1.15, 0));+ // Chest+ addPart(new THREE.CylinderGeometry(0.16, 0.13, 0.22, 16), 2, new THREE.Vector3(0, 1.35, 0));+ // Neck+ addPart(new THREE.CylinderGeometry(0.06, 0.07, 0.12, 12), 3, new THREE.Vector3(0, 1.55, 0));+ // Head (Egg/Stylized drawing doll head with face plane)+ addPart(+ new THREE.SphereGeometry(0.12, 16, 16),+ 4,+ new THREE.Vector3(0, 1.72, 0),+ undefined,+ new THREE.Vector3(0.9, 1.15, 1.05)+ );++ // Limbs+ // Left Arm+ addPart(new THREE.SphereGeometry(0.07, 12, 12), 5, new THREE.Vector3(0.24, 1.45, 0)); // Shoulder joint+ addPart(new THREE.CylinderGeometry(0.05, 0.045, 0.26, 12), 6, new THREE.Vector3(0.3, 1.28, 0)); // Upper Arm+ addPart(new THREE.SphereGeometry(0.05, 12, 12), 6, new THREE.Vector3(0.3, 1.14, 0)); // Elbow joint+ addPart(new THREE.CylinderGeometry(0.045, 0.04, 0.24, 12), 7, new THREE.Vector3(0.3, 1.0, 0)); // Forearm+ addPart(new THREE.BoxGeometry(0.04, 0.1, 0.08), 8, new THREE.Vector3(0.3, 0.82, 0)); // Hand++ // Right Arm+ addPart(new THREE.SphereGeometry(0.07, 12, 12), 9, new THREE.Vector3(-0.24, 1.45, 0));+ addPart(new THREE.CylinderGeometry(0.05, 0.045, 0.26, 12), 10, new THREE.Vector3(-0.3, 1.28, 0));+ addPart(new THREE.SphereGeometry(0.05, 12, 12), 10, new THREE.Vector3(-0.3, 1.14, 0));+ addPart(new THREE.CylinderGeometry(0.045, 0.04, 0.24, 12), 11, new THREE.Vector3(-0.3, 1.0, 0));+ addPart(new THREE.BoxGeometry(0.04, 0.1, 0.08), 12, new THREE.Vector3(-0.3, 0.82, 0));++ // Left Leg+ addPart(new THREE.SphereGeometry(0.075, 12, 12), 0, new THREE.Vector3(0.12, 0.9, 0)); // Hip joint+ addPart(new THREE.CylinderGeometry(0.07, 0.06, 0.38, 14), 13, new THREE.Vector3(0.12, 0.68, 0)); // Thigh+ addPart(new THREE.SphereGeometry(0.06, 12, 12), 13, new THREE.Vector3(0.12, 0.48, 0)); // Knee joint+ addPart(new THREE.CylinderGeometry(0.058, 0.045, 0.38, 14), 14, new THREE.Vector3(0.12, 0.28, 0)); // Calf+ addPart(new THREE.BoxGeometry(0.08, 0.06, 0.18), 15, new THREE.Vector3(0.12, 0.05, 0.04)); // Foot++ // Right Leg+ addPart(new THREE.SphereGeometry(0.075, 12, 12), 0, new THREE.Vector3(-0.12, 0.9, 0));+ addPart(new THREE.CylinderGeometry(0.07, 0.06, 0.38, 14), 16, new THREE.Vector3(-0.12, 0.68, 0));+ addPart(new THREE.SphereGeometry(0.06, 12, 12), 16, new THREE.Vector3(-0.12, 0.48, 0));+ addPart(new THREE.CylinderGeometry(0.058, 0.045, 0.38, 14), 17, new THREE.Vector3(-0.12, 0.28, 0));+ addPart(new THREE.BoxGeometry(0.08, 0.06, 0.18), 18, new THREE.Vector3(-0.12, 0.05, 0.04));++ const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries);+ mergedGeometry.computeVertexNormals();++ // CSP Mannequin Clay Material+ const material = new THREE.MeshStandardMaterial({+ color: 0xd8dde3,+ roughness: 0.38,+ metalness: 0.08,+ });++ const skinnedMesh = new THREE.SkinnedMesh(mergedGeometry, material);+ const skeleton = new THREE.Skeleton(boneList);++ skinnedMesh.add(hips);+ skinnedMesh.bind(skeleton);+ skinnedMesh.castShadow = true;+ skinnedMesh.receiveShadow = true;++ group.add(skinnedMesh);++ return {+ group,+ skinnedMesh,+ skeleton,+ bones: bonesMap,+ };+}++/**+ * Discovers and maps humanoid bones from any loaded 3D GLTF/FBX model+ * based on standard naming conventions (Mixamo, Blender, Three.js, etc.).+ */+export function findHumanoidBones(root: THREE.Object3D): HumanoidBones {+ const bones: HumanoidBones = {};++ const nameMatchPatterns: Array<[keyof HumanoidBones, RegExp]> = [+ ['head', /head|kubi_atama/i],+ ['neck', /neck|kubi/i],+ ['chest', /chest|upper_chest|spine1|spine01/i],+ ['spine', /spine|spine00/i],+ ['hips', /hip|hips|pelvis|waist/i],++ ['leftHand', /left.*hand|hand.*l|l_hand|wrist.*l|leftwrist/i],+ ['leftLowerArm', /left.*fore.*arm|forearm.*l|l_forearm|elbow.*l|leftlowerarm/i],+ ['leftUpperArm', /left.*arm|arm.*l|l_arm|leftupperarm/i],+ ['leftShoulder', /left.*shoulder|shoulder.*l|l_shoulder|clavicle.*l/i],++ ['rightHand', /right.*hand|hand.*r|r_hand|wrist.*r|rightwrist/i],+ ['rightLowerArm', /right.*fore.*arm|forearm.*r|r_forearm|elbow.*r|rightlowerarm/i],+ ['rightUpperArm', /right.*arm|arm.*r|r_arm|rightupperarm/i],+ ['rightShoulder', /right.*shoulder|shoulder.*r|r_shoulder|clavicle.*r/i],++ ['leftFoot', /left.*foot|foot.*l|l_foot|ankle.*l|leftankle/i],+ ['leftLowerLeg', /left.*leg|leg.*l|l_leg|shin.*l|knee.*l|leftlowerleg/i],+ ['leftUpperLeg', /left.*up.*leg|upleg.*l|l_upleg|thigh.*l|leftupperleg/i],++ ['rightFoot', /right.*foot|foot.*r|r_foot|ankle.*r|rightankle/i],+ ['rightLowerLeg', /right.*leg|leg.*r|r_leg|shin.*r|knee.*r|rightlowerleg/i],+ ['rightUpperLeg', /right.*up.*leg|upleg.*r|r_upleg|thigh.*r|rightupperleg/i],+ ];++ root.traverse((obj) => {+ if ((obj as THREE.Bone).isBone) {+ const bone = obj as THREE.Bone;+ const lower = bone.name.toLowerCase();++ for (const [key, pattern] of nameMatchPatterns) {+ if (!bones[key] && pattern.test(lower)) {+ bones[key] = bone;+ }+ }+ }+ });++ return bones;+}++/**+ * Closed-form analytic 2-bone Inverse Kinematics (IK) with pole target constraint.+ * Solves root (shoulder/hip) and mid (elbow/knee) joint rotations in real time.+ */+export function solveTwoBoneIK(+ rootBone: THREE.Bone,+ midBone: THREE.Bone,+ endBone: THREE.Bone,+ targetWorldPos: THREE.Vector3,+ poleWorldPos: THREE.Vector3+): void {+ const rootWorldPos = new THREE.Vector3();+ const midWorldPos = new THREE.Vector3();+ const endWorldPos = new THREE.Vector3();++ rootBone.getWorldPosition(rootWorldPos);+ midBone.getWorldPosition(midWorldPos);+ endBone.getWorldPosition(endWorldPos);++ const l1 = rootWorldPos.distanceTo(midWorldPos);+ const l2 = midWorldPos.distanceTo(endWorldPos);+ const totalLength = l1 + l2;++ if (l1 <= 1e-4 || l2 <= 1e-4) return;++ const toTarget = new THREE.Vector3().subVectors(targetWorldPos, rootWorldPos);+ const targetDist = Math.max(0.001, Math.min(totalLength - 1e-4, toTarget.length()));+ const targetDir = toTarget.clone().normalize();++ // Law of Cosines for limb angles+ // cos(alpha): angle at root joint+ const cosAlpha = Math.max(+ -1.0,+ Math.min(1.0, (l1 * l1 + targetDist * targetDist - l2 * l2) / (2.0 * l1 * targetDist))+ );+ const alpha = Math.acos(cosAlpha);++ // Compute bend plane normal from pole vector+ const toPole = new THREE.Vector3().subVectors(poleWorldPos, rootWorldPos).normalize();+ let bendNormal = new THREE.Vector3().crossVectors(targetDir, toPole);+ if (bendNormal.lengthSq() < 1e-4) {+ bendNormal = new THREE.Vector3(0, 0, 1).applyQuaternion(rootBone.quaternion);+ } else {+ bendNormal.normalize();+ }++ // Mid joint direction vector in world coordinates+ const midDir = targetDir+ .clone()+ .applyAxisAngle(bendNormal, alpha)+ .normalize();+ const solvedMidWorldPos = rootWorldPos.clone().addScaledVector(midDir, l1);++ // Orient Root Bone towards solved mid position+ const rootParent = rootBone.parent;+ if (rootParent) {+ const currentLimbDir = new THREE.Vector3().subVectors(midWorldPos, rootWorldPos).normalize();+ const targetLimbDir = new THREE.Vector3().subVectors(solvedMidWorldPos, rootWorldPos).normalize();+ const rotDelta = new THREE.Quaternion().setFromUnitVectors(currentLimbDir, targetLimbDir);+ rootBone.quaternion.premultiply(rotDelta);+ rootBone.updateMatrixWorld(true);+ }++ // Orient Mid Bone towards target position+ const midParent = midBone.parent;+ if (midParent) {+ const currentEndDir = new THREE.Vector3().subVectors(endWorldPos, midWorldPos).normalize();+ const targetEndDir = new THREE.Vector3().subVectors(targetWorldPos, solvedMidWorldPos).normalize();+ const rotDelta = new THREE.Quaternion().setFromUnitVectors(currentEndDir, targetEndDir);+ midBone.quaternion.premultiply(rotDelta);+ midBone.updateMatrixWorld(true);+ }+}++/**+ * Creates visual interactive handles for IK target endpoints (hands, feet, head).+ */+export function createIKHandles(): {+ container: THREE.Group;+ handles: Record<string, THREE.Mesh>;+} {+ const container = new THREE.Group();+ container.name = 'IKHandles';++ const handles: Record<string, THREE.Mesh> = {};++ const handleDefs: Array<{+ name: string;+ color: number;+ size: number;+ initialPos: [number, number, number];+ }> = [+ { name: 'head', color: 0xf59e0b, size: 0.08, initialPos: [0, 1.72, 0] },+ { name: 'leftHand', color: 0x06b6d4, size: 0.07, initialPos: [0.3, 0.82, 0] },+ { name: 'rightHand', color: 0xa855f7, size: 0.07, initialPos: [-0.3, 0.82, 0] },+ { name: 'leftFoot', color: 0x10b981, size: 0.07, initialPos: [0.12, 0.05, 0.04] },+ { name: 'rightFoot', color: 0xec4899, size: 0.07, initialPos: [-0.12, 0.05, 0.04] },+ ];++ for (const def of handleDefs) {+ const geom = new THREE.SphereGeometry(def.size, 16, 16);+ const mat = new THREE.MeshBasicMaterial({+ color: def.color,+ wireframe: true,+ depthTest: false,+ });+ const mesh = new THREE.Mesh(geom, mat);+ mesh.name = `IKHandle_${def.name}`;+ mesh.position.set(...def.initialPos);+ mesh.renderOrder = 999;+ container.add(mesh);+ handles[def.name] = mesh;+ }++ return { container, handles };+}++/**+ * Applies studio pose presets to humanoid mannequin bones.+ */+export function applyPosePreset(bones: HumanoidBones, preset: PosePresetName): void {+ // Reset all bones to identity rotation first+ for (const key of Object.keys(bones)) {+ const b = bones[key];+ if (b) {+ b.quaternion.identity();+ }+ }++ const rad = (deg: number) => (deg * Math.PI) / 180;++ switch (preset) {+ case 'standing': {+ // Natural upright hero pose: slightly relaxed arms and shoulders+ if (bones.leftUpperArm) bones.leftUpperArm.rotation.set(rad(8), 0, rad(12));+ if (bones.rightUpperArm) bones.rightUpperArm.rotation.set(rad(8), 0, rad(-12));+ if (bones.leftLowerArm) bones.leftLowerArm.rotation.set(rad(-14), 0, 0);+ if (bones.rightLowerArm) bones.rightLowerArm.rotation.set(rad(-14), 0, 0);+ if (bones.leftUpperLeg) bones.leftUpperLeg.rotation.set(0, 0, rad(4));+ if (bones.rightUpperLeg) bones.rightUpperLeg.rotation.set(0, 0, rad(-4));+ break;+ }++ case 'action': {+ // Dynamic manga action battle pose+ if (bones.hips) bones.hips.rotation.set(rad(12), rad(-20), 0);+ if (bones.chest) bones.chest.rotation.set(rad(-8), rad(25), 0);+ if (bones.head) bones.head.rotation.set(rad(-10), rad(-15), 0);++ // Guard arm (Left)+ if (bones.leftUpperArm) bones.leftUpperArm.rotation.set(rad(-45), rad(20), rad(30));+ if (bones.leftLowerArm) bones.leftLowerArm.rotation.set(rad(-85), 0, 0);++ // Cocked punch arm (Right)+ if (bones.rightUpperArm) bones.rightUpperArm.rotation.set(rad(25), rad(-30), rad(-40));+ if (bones.rightLowerArm) bones.rightLowerArm.rotation.set(rad(-110), 0, 0);++ // Deep battle stance legs+ if (bones.leftUpperLeg) bones.leftUpperLeg.rotation.set(rad(-35), rad(-15), rad(10));+ if (bones.leftLowerLeg) bones.leftLowerLeg.rotation.set(rad(60), 0, 0);++ if (bones.rightUpperLeg) bones.rightUpperLeg.rotation.set(rad(25), rad(20), rad(-15));+ if (bones.rightLowerLeg) bones.rightLowerLeg.rotation.set(rad(35), 0, 0);+ break;+ }++ case 'sitting': {+ // Seated pose (90 degree hips, 90 degree knees)+ if (bones.hips) bones.hips.position.y = 0.55;+ if (bones.spine) bones.spine.rotation.set(rad(6), 0, 0);++ if (bones.leftUpperLeg) bones.leftUpperLeg.rotation.set(rad(-85), rad(10), 0);+ if (bones.leftLowerLeg) bones.leftLowerLeg.rotation.set(rad(90), 0, 0);++ if (bones.rightUpperLeg) bones.rightUpperLeg.rotation.set(rad(-85), rad(-10), 0);+ if (bones.rightLowerLeg) bones.rightLowerLeg.rotation.set(rad(90), 0, 0);++ // Hands resting on knees+ if (bones.leftUpperArm) bones.leftUpperArm.rotation.set(rad(-15), 0, rad(12));+ if (bones.leftLowerArm) bones.leftLowerArm.rotation.set(rad(-55), 0, 0);++ if (bones.rightUpperArm) bones.rightUpperArm.rotation.set(rad(-15), 0, rad(-12));+ if (bones.rightLowerArm) bones.rightLowerArm.rotation.set(rad(-55), 0, 0);+ break;+ }++ case 'fists': {+ // Clenched fist rotations on wrists and arm readiness+ if (bones.leftHand) bones.leftHand.rotation.set(rad(-20), rad(10), rad(15));+ if (bones.rightHand) bones.rightHand.rotation.set(rad(-20), rad(-10), rad(-15));+ if (bones.leftLowerArm) bones.leftLowerArm.rotation.set(rad(-35), 0, 0);+ if (bones.rightLowerArm) bones.rightLowerArm.rotation.set(rad(-35), 0, 0);+ break;+ }++ case 'relaxed_palm': {+ // Natural open resting palms+ if (bones.leftHand) bones.leftHand.rotation.set(rad(5), rad(-8), 0);+ if (bones.rightHand) bones.rightHand.rotation.set(rad(5), rad(8), 0);+ if (bones.leftLowerArm) bones.leftLowerArm.rotation.set(rad(-10), 0, 0);+ if (bones.rightLowerArm) bones.rightLowerArm.rotation.set(rad(-10), 0, 0);+ break;+ }+ }++ // Update matrix world for all bones+ for (const key of Object.keys(bones)) {+ const b = bones[key];+ if (b) b.updateMatrixWorld(true);+ }+}diff --git a/src/utils/perspectiveMath.ts b/src/utils/perspectiveMath.tsindex 87ddb00..d268786 100644--- a/src/utils/perspectiveMath.ts+++ b/src/utils/perspectiveMath.ts@@ -449,3 +449,117 @@ export function applyWormsEyePreset(vps: newVps,};}++/**+ * Calculates real-time vanishing points from a Three.js PerspectiveCamera+ * in document canvas coordinates and returns an updated PerspectiveRuler.+ */+export function calculatePerspectiveFromCamera(+ camera: {+ matrixWorldInverse: { elements: ArrayLike<number> };+ projectionMatrix: { elements: ArrayLike<number> };+ },+ docWidth: number,+ docHeight: number,+ existingRuler?: PerspectiveRuler | null+): PerspectiveRuler {+ const V = camera.matrixWorldInverse.elements;+ const P = camera.projectionMatrix.elements;++ // Multiply M = P * V (column-major 4x4 matrix multiplication)+ const M = new Float64Array(16);+ for (let col = 0; col < 4; col++) {+ for (let row = 0; row < 4; row++) {+ let sum = 0;+ for (let k = 0; k < 4; k++) {+ sum += P[k * 4 + row] * V[col * 4 + k];+ }+ M[col * 4 + row] = sum;+ }+ }++ // Project a 3D world direction vector (dx, dy, dz, 0) to document screen space+ const projectDirection = (dx: number, dy: number, dz: number) => {+ const cx = M[0] * dx + M[4] * dy + M[8] * dz;+ const cy = M[1] * dx + M[5] * dy + M[9] * dz;+ const cw = M[3] * dx + M[7] * dy + M[11] * dz;++ if (Math.abs(cw) < 1e-4) {+ return null;+ }++ const ndcX = cx / cw;+ const ndcY = cy / cw;++ const docX = (ndcX + 1.0) * 0.5 * docWidth;+ const docY = (1.0 - ndcY) * 0.5 * docHeight;++ const MAX_COORD = 50000;+ return {+ x: Math.max(-MAX_COORD, Math.min(MAX_COORD, Math.round(docX))),+ y: Math.max(-MAX_COORD, Math.min(MAX_COORD, Math.round(docY))),+ cw,+ };+ };++ // VP1: World X direction (1, 0, 0)+ const p1 = projectDirection(1, 0, 0);+ // VP2: World Z direction (0, 0, 1)+ const p2 = projectDirection(0, 0, 1);+ // VP3: World Y direction (0, 1, 0)+ const p3 = projectDirection(0, 1, 0);++ const fallbackW = Math.max(1, docWidth);+ const fallbackH = Math.max(1, docHeight);++ const vp1: VanishingPoint = {+ id: 'vp1',+ x: p1 ? p1.x : -fallbackW * 0.8,+ y: p1 ? p1.y : fallbackH * 0.5,+ label: 'VP1 (X-Axis)',+ color: '#06b6d4',+ };++ const vp2: VanishingPoint = {+ id: 'vp2',+ x: p2 ? p2.x : fallbackW * 1.8,+ y: p2 ? p2.y : fallbackH * 0.5,+ label: 'VP2 (Z-Axis)',+ color: '#a855f7',+ };++ const is3Point = p3 !== null && Math.abs(p3.cw) > 0.02;+ const vps: VanishingPoint[] = [vp1, vp2];++ if (is3Point && p3) {+ const vp3: VanishingPoint = {+ id: 'vp3',+ x: p3.x,+ y: p3.y,+ label: 'VP3 (Y-Axis)',+ color: '#f97316',+ };+ vps.push(vp3);+ }++ const dx = vp2.x - vp1.x;+ const dy = vp2.y - vp1.y;+ const horizonAngle = (Math.atan2(dy, dx) * 180) / Math.PI;++ return {+ id: existingRuler?.id || `ruler-cam-sync-${Date.now()}`,+ type: is3Point ? '3-point' : '2-point',+ enabled: true,+ locked: existingRuler?.locked ?? false,+ snapEnabled: existingRuler?.snapEnabled ?? true,+ vps,+ horizonAngle,+ guideRayCount: existingRuler?.guideRayCount ?? 8,+ grid: existingRuler?.grid ?? {+ enabled: false,+ density: 16,+ plane: 'ground',+ opacity: 0.25,+ },+ };+}diff --git a/src/utils/vectorEngine.ts b/src/utils/vectorEngine.tsindex d4376a4..958ec0a 100644--- a/src/utils/vectorEngine.ts+++ b/src/utils/vectorEngine.ts@@ -702,3 +702,175 @@ export function reshapeVectorLine(bounds: computeStrokeBounds(knots),};}++/**+ * Displaces neighboring Catmull-Rom knots within a bell-curve radius.+ * Supports passing a VectorStroke directly or (strokeId, point, radius, delta, strokes).+ */+export function pinchVectorStroke(+ stroke: VectorStroke,+ point: Point2D,+ radius: number,+ delta: Point2D+): VectorStroke;+export function pinchVectorStroke(+ strokeId: string,+ point: Point2D,+ radius: number,+ delta: Point2D,+ strokes: VectorStroke[]+): VectorStroke[];+export function pinchVectorStroke(+ target: VectorStroke | string,+ point: Point2D,+ radius: number,+ delta: Point2D,+ strokes?: VectorStroke[]+): VectorStroke | VectorStroke[] {+ if (typeof target === 'string') {+ const list = strokes || [];+ return list.map((s) => (s.id === target ? pinchVectorStroke(s, point, radius, delta) : s));+ }+ const stroke = target;+ if (!stroke.knots || stroke.knots.length === 0 || radius <= 0) return stroke;++ const invRadius = 1 / radius;+ const updatedKnots = stroke.knots.map((k) => {+ const dist = Math.hypot(k.x - point.x, k.y - point.y);+ if (dist >= radius) return k;+ const factor = 0.5 * (1 + Math.cos(Math.PI * dist * invRadius));+ return {+ ...k,+ x: k.x + delta.x * factor,+ y: k.y + delta.y * factor,+ };+ });++ return {+ ...stroke,+ knots: updatedKnots,+ bounds: computeStrokeBounds(updatedKnots),+ };+}++/**+ * Scales knot.width locally within a bell-curve radius.+ * Supports passing a VectorStroke directly or (strokeId, point, radius, widthFactor, strokes).+ */+export function modifyStrokeWidth(+ stroke: VectorStroke,+ point: Point2D,+ radius: number,+ widthFactor: number+): VectorStroke;+export function modifyStrokeWidth(+ strokeId: string,+ point: Point2D,+ radius: number,+ widthFactor: number,+ strokes: VectorStroke[]+): VectorStroke[];+export function modifyStrokeWidth(+ target: VectorStroke | string,+ point: Point2D,+ radius: number,+ widthFactor: number,+ strokes?: VectorStroke[]+): VectorStroke | VectorStroke[] {+ if (typeof target === 'string') {+ const list = strokes || [];+ return list.map((s) => (s.id === target ? modifyStrokeWidth(s, point, radius, widthFactor) : s));+ }+ const stroke = target;+ if (!stroke.knots || stroke.knots.length === 0 || radius <= 0) return stroke;++ const invRadius = 1 / radius;+ const updatedKnots = stroke.knots.map((k) => {+ const dist = Math.hypot(k.x - point.x, k.y - point.y);+ if (dist >= radius) return k;+ const factor = 0.5 * (1 + Math.cos(Math.PI * dist * invRadius));+ const effectiveFactor = 1 + (widthFactor - 1) * factor;+ return {+ ...k,+ width: Math.max(0.5, k.width * effectiveFactor),+ };+ });++ return {+ ...stroke,+ knots: updatedKnots,+ bounds: computeStrokeBounds(updatedKnots),+ };+}++/**+ * Applies Ramer-Douglas-Peucker reduction to prune redundant knots while preserving shape.+ * Supports passing a VectorStroke directly or (strokeId, tolerance, strokes).+ */+export function simplifyVectorStroke(+ stroke: VectorStroke,+ tolerance: number+): VectorStroke;+export function simplifyVectorStroke(+ strokeId: string,+ tolerance: number,+ strokes: VectorStroke[]+): VectorStroke[];+export function simplifyVectorStroke(+ target: VectorStroke | string,+ tolerance: number,+ strokes?: VectorStroke[]+): VectorStroke | VectorStroke[] {+ if (typeof target === 'string') {+ const list = strokes || [];+ return list.map((s) => (s.id === target ? simplifyVectorStroke(s, tolerance) : s));+ }+ const stroke = target;+ if (!stroke.knots || stroke.knots.length <= 2 || tolerance <= 0) return stroke;++ const simplified = simplifyPathPoints(stroke.knots, tolerance);+ const finalKnots = simplified.length >= 2 ? simplified : stroke.knots;++ return {+ ...stroke,+ knots: finalKnots,+ bounds: computeStrokeBounds(finalKnots),+ };+}++/**+ * Finds the nearest vector stroke and knot index within a maximum distance.+ */+export function findNearestVectorStroke(+ strokes: VectorStroke[],+ point: Point2D,+ maxDist = 30+): { stroke: VectorStroke; knotIndex: number; distance: number } | null {+ let closest: { stroke: VectorStroke; knotIndex: number; distance: number } | null = null;+ let minDist = maxDist;++ for (const stroke of strokes) {+ if (stroke.deleted) continue;+ // Bounding box pre-check+ if (+ point.x < stroke.bounds.minX - minDist ||+ point.x > stroke.bounds.maxX + minDist ||+ point.y < stroke.bounds.minY - minDist ||+ point.y > stroke.bounds.maxY + minDist+ ) {+ continue;+ }++ for (let i = 0; i < stroke.knots.length; i++) {+ const k = stroke.knots[i];+ const d = Math.hypot(k.x - point.x, k.y - point.y);+ if (d < minDist) {+ minDist = d;+ closest = { stroke, knotIndex: i, distance: d };+ }+ }+ }++ return closest;+}+diff --git a/src/utils/webtoonExporter.ts b/src/utils/webtoonExporter.tsnew file mode 100644index 0000000..a1988fc--- /dev/null+++ b/src/utils/webtoonExporter.ts@@ -0,0 +1,135 @@+/**+ * Webtoon Chapter Slicer & ZIP Exporter Engine+ *+ * Implements Clip Studio Paint EX-grade Webtoon export:+ * - Cuts tall Webtoon canvases (e.g. 800×30000px) into sequential vertical tiles (e.g. 800×1280px)+ * - Automatically pads / handles fractional end tiles+ * - Compresses tiles to JPEG or PNG+ * - Packages sequential files into a standardized .ZIP archive ready for Line Webtoon, Tapas, Kakao+ */++import { zipSync } from 'fflate';++export interface WebtoonSliceOptions {+ sliceWidth?: number;+ sliceHeight?: number; // Default: 1280px+ format?: 'jpg' | 'png'; // Default: 'jpg'+ quality?: number; // Default: 0.92 for JPEG+ filePrefix?: string; // Default: 'episode_'+ onProgress?: (progress: { current: number; total: number; percent: number }) => void;+}++/**+ * Extracts a Uint8Array from a canvas slice+ */+async function canvasSliceToBytes(+ canvas: HTMLCanvasElement,+ format: 'jpg' | 'png',+ quality: number+): Promise<Uint8Array> {+ const mimeType = format === 'jpg' ? 'image/jpeg' : 'image/png';+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ async (blob) => {+ if (!blob) {+ reject(new Error('Failed to create slice blob'));+ return;+ }+ const buffer = await blob.arrayBuffer();+ resolve(new Uint8Array(buffer));+ },+ mimeType,+ quality+ );+ });+}++/**+ * Slices tall Webtoon canvas into sequential 800×1280px tiles and compiles them into a ZIP archive.+ */+export async function exportWebtoonChapterZip(+ sourceCanvas: HTMLCanvasElement,+ options: WebtoonSliceOptions = {}+): Promise<Uint8Array> {+ const sliceHeight = options.sliceHeight || 1280;+ const format = options.format || 'jpg';+ const quality = options.quality ?? 0.92;+ const filePrefix = options.filePrefix || 'slice_';+ const ext = format === 'jpg' ? 'jpg' : 'png';++ const totalHeight = sourceCanvas.height;+ const sliceWidth = options.sliceWidth || sourceCanvas.width;+ const totalSlices = Math.max(1, Math.ceil(totalHeight / sliceHeight));++ const zipFiles: Record<string, Uint8Array> = {};++ const sliceCanvas = document.createElement('canvas');+ sliceCanvas.width = sliceWidth;++ for (let i = 0; i < totalSlices; i++) {+ const srcY = i * sliceHeight;+ const currentSliceH = Math.min(sliceHeight, totalHeight - srcY);++ sliceCanvas.height = currentSliceH;+ const ctx = sliceCanvas.getContext('2d');+ if (!ctx) continue;++ // Fill white background for JPEGs+ if (format === 'jpg') {+ ctx.fillStyle = '#ffffff';+ ctx.fillRect(0, 0, sliceWidth, currentSliceH);+ } else {+ ctx.clearRect(0, 0, sliceWidth, currentSliceH);+ }++ // Draw segment+ ctx.drawImage(+ sourceCanvas,+ 0,+ srcY,+ sliceWidth,+ currentSliceH,+ 0,+ 0,+ sliceWidth,+ currentSliceH+ );++ const bytes = await canvasSliceToBytes(sliceCanvas, format, quality);+ const fileName = `${filePrefix}${String(i + 1).padStart(3, '0')}.${ext}`;+ zipFiles[fileName] = bytes;++ if (options.onProgress) {+ options.onProgress({+ current: i + 1,+ total: totalSlices,+ percent: Math.round(((i + 1) / totalSlices) * 100),+ });+ }++ // Yield thread to keep UI responsive+ await new Promise((r) => setTimeout(r, 4));+ }++ // Synchronously pack into ZIP archive+ const zipBytes = zipSync(zipFiles, { level: 6 });+ return zipBytes;+}++/**+ * Triggers a browser download of the generated Webtoon ZIP package.+ */+export function downloadWebtoonZip(+ zipBytes: Uint8Array,+ filename = 'webtoon_chapter.zip'+): void {+ const blob = new Blob([zipBytes as BlobPart], { type: 'application/zip' });+ 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);+}