A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
InkStudio Hybrid Native Rust + wgpu (DX12) Engine Migration
Target Platform: Windows 10/11 Desktop Only (
wgpuDX12 + DirectComposition + transparent WebView2 UI)
Status: Phase 6 of 6 (Complete Canvas Offload, Native Tools/Collab & WebView2 Purge) — Migration Complete
1. Architecture & Crate / Module Layout
InkStudio is structured as a Cargo workspace with a strictly decoupled GPU engine crate (crates/ink-engine) hosted beneath the transparent WebView2 UI in src-tauri:
inkstudio/
├── Cargo.toml # Cargo workspace root (members: crates/ink-engine, src-tauri)
├── crates/
│ └── ink-engine/ # Pure Rust DX12 engine — ZERO tauri/wry/tao/WebView deps
│ ├── Cargo.toml # wgpu 30 (dx12/wgsl), rtrb, crossbeam-channel, pollster, bytemuck, windows-sys (QPC/thread)
│ └── src/
│ ├── lib.rs # Public engine API + headless DX12 vertical-slice integration test
│ ├── clock.rs # Shared Windows QPC monotonic millisecond clock (matches tablet_input.rs)
│ ├── types.rs # ViewportRect, UiRect, CameraState, CursorConfig, BrushParams, InteractionPolicy,
│ │ # NativeInputSample, NativeNavEvent, EngineCommand, EngineEvent, EngineDiagnostics, SurfaceTarget
│ ├── camera.rs # Exact 2D affine camera math matching formatArtboardTransform + NativeCameraNavigator
│ ├── hit_test.rs # Thread-safe physical-pixel viewport & UI occlusion mask (blocking + try_* non-blocking)
│ ├── ring.rs # Dedicated wait-free SPSC rtrb rings (wintab, winink, nav) + WakeSignal
│ ├── shaders.rs # WGSL shaders: artboard compositor, instanced GPU dab rasterizer, analytic SDF GPU cursor
│ ├── stroke.rs # Pressure-sensitive spacing-interpolated dab generator + eraser support
│ ├── gpu.rs # DX12 wgpu renderer (CreateSwapChainForComposition, waitable latency=1, device-lost recovery)
│ └── engine.rs # Dedicated above-normal priority render thread, chronological ring drain, EMA latency telemetry
├── src-tauri/
│ ├── tauri.conf.json # main window: decorations: false, transparent: true
│ └── src/
│ ├── dcomp_host.rs # Windows DirectComposition visual tree host + live DX12 composition swapchain test
│ ├── native_engine.rs # Tauri host lifecycle, WM_SIZE/DPI subclass, WH_MOUSE_LL zero-IPC nav/hover hook, event pump
│ ├── tablet_input.rs # Direct WinTab & Windows Ink SPSC ring push + zero-IPC Channel suppression on native strokes
│ └── lib.rs # WEBVIEW2_DEFAULT_BACKGROUND_COLOR=0, startup init, 11 native_engine_* commands, ordered exit
└── src/
├── index.css # :root[data-native-canvas="true"] RGBA(0,0,0,0) viewport cutout + opaque chrome seam sealing
├── utils/nativeEngineBridge.ts # Typed Tauri IPC + event client (no-op in non-Tauri / Vitest environments)
├── hooks/useNativeEngineViewport.ts # ResizeObserver/DPR/interfaceScale viewport sync, UI occlusion observer, bidirectional camera sync
└── components/
├── CanvasArea.tsx # Mounts native engine hook, hides legacy WebGL2 canvas when native DX12 is active
├── FloatingBrushPill.tsx # Tagged with data-native-occluder="true"
├── AnimationTimeline.tsx # Tagged with data-native-occluder="true"
└── canvasArea/
├── useCompositorViewport.ts # Keeps DOM artboard overlay transform synced; bypasses WebGL2 renders when DX12 is active
├── useCanvasEffects.ts # Suppresses DOM brush outline ring for native-handled tools so GPU SDF cursor is sole cursor
├── useCanvasPointerHandlers.ts # Skips JS brush/eraser stroke dispatch when native DX12 owns strokes
└── CanvasViewportHud.tsx # Native DX12 Perf HUD pill (GPU adapter, FPS, frame time, input-to-present latency, Clear button)
Hard Decoupling Invariant
crates/ink-engine has zero dependencies on tauri, wry, tao, or webview2-com. It accepts only:
SurfaceTarget::CompositionVisual { visual_ptr, on_configured }(orSurfaceTarget::Headless { width, height }for automated GPU testing),- Lock-free SPSC
rtrbinput ring producers (InputProducers { wintab, winink, nav }), and - Typed
EngineCommandcontrol messages.
A future pure-Rust UI shell can host crates/ink-engine directly with no modifications to the engine crate.
2. Windows DirectComposition + WebView2 COM Integration & Lifecycle Invariants
Visual Tree Layering (Single Top-Level HWND, Zero Canvas Child HWND)
On Windows, wry (0.57.x/0.58.x) hosts WebView2 via a child container HWND (WRY_WEBVIEW) inside the top-level main_hwnd using a windowed ICoreWebView2Controller. When "transparent": true is enabled on main in src-tauri/tauri.conf.json:
taoactivates DWM transparency (DwmEnableBlurBehindWindowwith an empty region) onmain_hwnd.src-tauri/src/lib.rssetsWEBVIEW2_DEFAULT_BACKGROUND_COLOR=0before WebView2 boots, andDCompHost::configure_webview2_controllercallsICoreWebView2Controller2::SetDefaultBackgroundColor(COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 })so the transparent cutout never flashes white.DCompHost::new(main_hwnd)creates anIDCompositionDeviceviaDCompositionCreateDevice2(None)and binds anIDCompositionTargetviadevice.CreateTargetForHwnd(main_hwnd, false)(topmost = false):topmost = falseplaces our DirectComposition visual tree (root_visual -> canvas_visual) strictly beneathWRY_WEBVIEWand Chromium's own compositor visual tree in DWM.- No opaque child HWND is created for the canvas. WebView2 dropdown menus, tooltips, floating dock panels, modals,
FloatingBrushPill, andQuickBrushPanelcomposite seamlessly above the DX12 canvas with zero clipping. - Future-proofing:
configure_webview2_controlleralso probescontroller.cast::<ICoreWebView2CompositionController>()and, if a futurewryswitches to visual-hosting mode, attaches a topwebview_visualabovecanvas_visualviaAddVisual(&webview_visual, true, Some(&canvas_visual))+SetRootVisualTarget(&webview_visual).
wgpu DX12 Composition Swapchain Details
Inside crates/ink-engine/src/gpu.rs:
- Backend: Explicitly
wgpu::Backends::DX12,Dx12SwapchainKind::DxgiFromVisual,Dx12UseFrameLatencyWaitableObject::Wait. - Surface Creation:
instance.create_surface_unsafe(SurfaceTargetUnsafe::CompositionVisual { visual }).wgpu-halborrows andAddRefs theIDCompositionVisualpointer (from_raw_borrowed+to_owned) and releases it cleanly whenwgpu::Surfacedrops. - Swapchain Configuration:
- Calls
IDXGIFactory2::CreateSwapChainForCompositionwithDXGI_SWAP_EFFECT_FLIP_DISCARD,DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT, andSetMaximumFrameLatency(1)(desired_maximum_frame_latency: 1). - Present Mode: Prefers
PresentMode::Mailboxwhen advertised by the adapter, falling back toPresentMode::Fifo. - Alpha Mode: Explicitly selects
CompositeAlphaMode::Opaque(DXGI_ALPHA_MODE_IGNORE) orCompositeAlphaMode::PreMultiplied(DXGI_ALPHA_MODE_PREMULTIPLIED) — neverAuto/Inherit(DXGI_ALPHA_MODE_UNSPECIFIED), whichCreateSwapChainForCompositionrejects withDXGI_ERROR_INVALID_CALL. - Mandatory Commit Hook:
wgpu-halcallsIDCompositionVisual::SetContent(&swap_chain1)insidesurface.configure(...)but does not callIDCompositionDevice::Commit().ink-engineinvokes the host'son_configuredcallback immediately after everysurface.configure(...)soDCompHost::commit()commits the swapchain binding to DWM.
- Calls
- Viewport Positioning & Clipping:
DCompHost::set_canvas_viewport(x_px, y_px, width_px, height_px, visible)appliesSetOffsetX2,SetOffsetY2,SetClip2(0..width_px,0..height_px, or0..0when hidden), andCommit().
Lifecycle, Recovery & Ordered Teardown Invariants
WM_SIZE(SIZE_MINIMIZED/ restore):lifecycle_subclass_proconmain_hwndimmediately pauses rendering (SetVisible(false)+ empty DirectComposition clip) when minimized and restores viewport visibility + sendsNotifySurfaceInvalidatedon restore.WM_DPICHANGED/WM_DISPLAYCHANGE: SendsNotifySurfaceInvalidatedto reconfigure the swapchain cleanly; React simultaneously observeswindow.devicePixelRatioviamatchMediaand pushes updated physical bounds.- Device-Lost / Swapchain Outdated Recovery:
GpuRenderer::render_framehandlesSurfaceError::Outdated | Lostby reconfiguring the swapchain, andSurfaceError::Timeout | OutOfMemory | Otherby tracking device-lost recoveries and rebuilding the DX12 device + pipelines + canvas texture cleanly if needed. - Strict Shutdown Order (
native_engine::shutdowninRunEvent::Exit):- Mark engine inactive and detach
tablet_inputring producers (tablet_input::detach_engine_rings()). - Stop
inkstudio-native-mouse(WH_MOUSE_LL) hook thread (PostThreadMessageW(WM_QUIT)+join). - Remove
main_hwndlifecycle subclass (RemoveWindowSubclass). - Call
EngineHandle::shutdown()and join"inkstudio-gpu-engine"— guaranteeswgpu::Surfaceand the DXGI composition swapchain drop strictly before DirectComposition teardown. - Join the event bridge thread, call
DCompHost::clear_content()(SetContent(None)+Commit()), and dropDCompHost.
- Mark engine inactive and detach
- Lock Hierarchy:
RUNTIME->DCompHost::inner.on_configuredonly locksDCompHost::inner, andshutdown()releasesRUNTIMEbefore joining the GPU thread, eliminating AB-BA deadlocks.
3. Zero-IPC Hot Paths & Coordinate System Parity
Lock-Free SPSC Input Routing (Zero JSON, Zero Tauri IPC During Strokes/Nav)
Three dedicated wait-free rtrb SPSC rings feed ink-engine and wake the render thread immediately via WakeSignal:
wintabring (inkstudio-wintabthread ->ink-engine):tablet_input.rsmaps WinTab packets to sub-pixel physical client coordinates(phys_x, phys_y)and pushesNativeInputSamplebatches directly intortrb. When a pen-down lands inside the unoccluded canvas viewport for a native-handled tool (Brush/Eraser),native_stroke_ownedsuppresses Tauri Channel serialization completely for the entire stroke and unoccluded hover.wininkring (UI threadink_subclass_proc->ink-engine): Same directrtrbbatch push + Channel suppression for Windows InkWM_POINTER*history bursts.navring (inkstudio-native-mouseWH_MOUSE_LLthread ->ink-engine): Non-blocking (try_readonSharedHitTest+ wait-freertrbpush) delivery of mouse hover (120–240 Hz GPU cursor), mouse wheel zoom/scroll, middle-mouse pan/rotate/zoom, Space+Left-drag pan/rotate/zoom, and mouse PoC drawing (automatically suppressing pen/touch-synthesized mouse events viaMI_WP_SIGNATUREand recent stylus timestamp).WM_MOUSEMOVEis never swallowed so the OS cursor never stalls.
Physical Pixel Coordinate Invariance (DPI + interfaceScale)
- Native input coordinates (
WinTab,Windows Ink,WH_MOUSE_LL) arrive as physical client pixels relative tomain_hwnd(ScreenToClientwithout dividing by DPI). - React sends viewport cutout bounds and UI occlusion rects as
DOMRect * window.devicePixelRatio. Because WebView2 scaleswindow.devicePixelRatio = os_dpi_scale * native_webview_zoom, physical pixel coordinates remain pixel-exact across all Windows DPI settings (100%–200%+) and InkStudiointerfaceScalelevels (60%–200%). ink-engineconverts physical pixels to zoomed viewport-local CSS pixels via(phys - viewport_origin) / dpr, matchingformatArtboardTransform(src/components/canvasArea/types.ts) andCanvasArtboardOverlayspixel-for-pixel.
4. React <-> Rust IPC Surface (Control & Telemetry Only)
All IPC calls are strictly off the hot stroke/navigation path (fired only on layout changes, tool/setting edits, document opens, or throttled background sync):
Commands (invoke from React -> Rust)
| Command | Purpose |
|---|---|
native_engine_is_active() |
Returns true if Windows DirectComposition + DX12 engine initialized cleanly. |
native_engine_set_viewport(xPx, yPx, widthPx, heightPx, dpr, visible) |
Updates physical cutout bounds, DirectComposition offset/clip, and swapchain size. |
native_engine_set_occluded_rects(rects) |
Replaces physical-pixel UI occlusion rects (modals, popovers, menus, FloatingBrushPill, floating dock windows, QuickBrushPanel, AnimationTimeline, perf HUD). |
native_engine_set_document(width, height, showCheckerboard) |
Resizes/recreates the GPU document canvas surface. |
native_engine_set_appearance(matteRgba, showCheckerboard) |
Syncs --ui-canvas-matte theme color and checkerboard grid toggle. |
native_engine_set_camera(camera) |
Applies programmatic UI camera updates (Fit-to-Screen, Navigator, Flip H/V, Reset Rotation). |
native_engine_set_cursor(config) |
Updates GPU SDF brush outline cursor size, shape, aspect/thickness, tip angle, and visibility. |
native_engine_set_brush(params) |
Updates Phase 1 PoC GPU dab brush size, opacity, hardness, spacing, pressure toggles, color, and eraser mode. |
native_engine_set_policy(policy) |
Syncs active tool classification, wheel mode, Webtoon mode, text-input focus, workspace splitter drag lock, and modal guard. |
native_engine_clear_canvas() |
Clears the Phase 1 PoC GPU canvas texture to transparent. |
native_engine_get_diagnostics() |
Returns latest EngineDiagnostics snapshot on demand. |
Throttled Events (Rust -> React)
| Event | Cadence | Purpose |
|---|---|---|
native-engine://camera |
~60 Hz during native nav + final commit: true |
Keeps useCanvasNavigation.ts & CanvasArtboardOverlays pixel-aligned with native Rust pan/zoom/rotate. |
native-engine://diagnostics |
~4 Hz | Drives the minimal Native DX12 Perf HUD (adapterName, fps, frameTimeMs, inputToPresentMs, presentMode). |
native-engine://pointer-stat |
~30 Hz | Dispatches canvas-pointer-stat so StatusBar coordinates & live pressure readout stay active during zero-IPC strokes. |
5. Phase 1 Completion Checklist
- Cargo workspace root created with strictly decoupled
crates/ink-engine(zero Tauri/wry/WebView deps). - Windows DirectComposition single-HWND visual tree (
CreateTargetForHwnd(main_hwnd, false)) layering DX12CreateSwapChainForComposition(SetMaximumFrameLatency(1),PresentMode::Mailboxpreferred elseFifo) beneath transparent WebView2 (COREWEBVIEW2_COLOR = 0). - Transparent WebView2 viewport cutout across
flat,hairline,islands, and Focus Mode with zero seam leakage and full UI occlusion rect reporting. - Direct lock-free
rtrbSPSC ring routing fromsrc-tauri/src/tablet_input.rs(WinTab + Windows Ink) andWH_MOUSE_LLdirectly intoink-engine(zero IPC during active strokes and camera nav). - Native 120–240 Hz GPU camera navigation (pan/zoom
0.01..32.0/rotate/flip) matchingformatArtboardTransformpixel-for-pixel + throttled sync back to React. - Analytic SDF dual-tone GPU brush outline cursor ring + minimal GPU dab test brush + minimal DX12 Perf HUD with live GPU adapter, FPS, frame time, input-to-present latency, and Clear button.
- Verified live DirectComposition + DX12 swapchain presentation test, workspace Rust tests, Clippy, TypeScript/Vite build, and Vitest suite.
6. Phase 2: Document & Tile Memory Single Source of Truth in Rust
Phase 2 eliminates dual JS/Rust raster storage on Windows desktop. crates/ink-engine is now the single source of truth for all document pixel grids, non-destructive 8-bit layer masks, multi-tab sessions, tiered GPU/RAM/Scratch memory, Copy-on-Write undo/redo history, and binary .ink / .clip / .psd / .psb / WAL crash recovery / timelapse I/O. React receives only compact JSON metadata (DocumentMetaSnapshot, HistoryStateSnapshot, MemoryStats) and small 64×64 PNG data-URL thumbnails — never full-resolution layer buffers.
Phase 2 Crate & File Additions
crates/ink-engine/src/
├── tiles/
│ ├── mod.rs # TILE_SIZE = 256, TileFormat (Monochrome1Bit / Grayscale8Bit / Color32Bit / Rgba16Float),
│ │ # TileCoord, RectI32, TileKind (Raster / Mask), atomic tile version IDs
│ ├── format.rs # Fast SIMD-friendly 1-bit / 8-bit / 32-bit / 16f conversions, U8->F16 LUT,
│ │ # 4×4 Bayer ordered dithering (Rgba16Float -> RGBA8 at I/O boundaries)
│ ├── tile_data.rs # TileStorage (SolidColor zero-alloc / Raw / Lz4Ram / ScratchDisk), CoW Arc<TileData> helpers
│ └── grid.rs # SparseLayerGrid (raster tiles + non-destructive 8-bit mask_tiles + solid fill + auto-pruning)
├── memory/
│ ├── mod.rs # MemoryBudgetConfig, MemoryStats, EvictionReport
│ ├── scratch.rs # Pure-Rust ScratchBackend trait + InMemoryScratchBackend + FileScratchBackend
│ ├── tiered.rs # LRU tiered eviction coordinator (L1 VRAM <-> L2 lz4_flex RAM <-> L3 Scratch Disk)
│ └── gpu_pool.rs # wgpu DX12 GpuTilePool (Rgba16Float + R8Unorm Texture2DArray pools, LRU eviction,
│ # MIPMAP_COMPUTE_WGSL compute shader regenerating dirty LOD 1..3 tiles on GPU)
├── document/
│ ├── mod.rs # Re-exports for DocumentManager, Document, LayerNode, LayerNodeMeta, snapshots
│ ├── types.rs # Full InkStudio layer metadata parity (BlendMode, ExpressionColor, screentone, layer color,
│ │ # mask flags, adjustments, styles, comic frames, text/balloon/vector metadata)
│ ├── doc.rs # Layer CRUD, O(1) CoW duplicate, reorder/reparent, merge down, merge folder, mask CRUD/apply,
│ │ # atomic canvas resize/crop, raw dirty-rect ingestion, CoW undo/redo & selective collab undo
│ └── manager.rs # Multi-tab DocumentManager keyed by DocumentId (instant tab switch + inactive-tab offloading)
├── history/
│ └── mod.rs # CoW HistoryStack (Arc<TileData> deltas, 800ms slider coalesce_key, resize/tree snapshots,
│ # collaborative selective undo/redo tombstones with peer_id / stroke_id / undone)
├── io/
│ ├── mod.rs # I/O re-exports
│ ├── png_codec.rs # Zero-dependency pure-Rust PNG encoder/decoder + 64×64 layer/mask thumbnail generator
│ ├── compositor_cpu.rs # Parallel Rayon multi-layer CPU compositor (blend modes, masks, clipping, folders, downscale)
│ ├── ink_format.rs # Direct parallel Rayon `.ink` v2 ZIP serializer & parser (tile/mask/preview/manifest parity)
│ └── wal.rs # Direct `INKG v1` checkpoint + `TD v1` WAL encoder/replayer (wire-compatible with recovery.rs)
└── phase2_tests.rs # Comprehensive Phase 2 Rust unit + headless DX12 GPU verification suite
src-tauri/src/
├── scratch_disk.rs # Unified in-process sync helpers (init/write/read/clear_sync) sharing SCRATCH_IO_LOCK + registry
├── doc_wire.rs # Factored ParsedDocumentAssembled struct shared by clip_parser, psd_parser, and native_docs
├── clip_parser.rs # Added parse_clip_assembled for zero-copy hydration into ink-engine (skips INKD encode/IPC)
├── psd_parser.rs # Added parse_psd_assembled for zero-copy hydration into ink-engine (skips INKD encode/IPC)
├── native_docs.rs # TauriScratchDiskBackend (zero-IPC), zero-copy .clip/.psd/.psb/.ink open/save,
│ # all layer/mask/history/memory/thumbnail/timelapse/recovery handlers + integration tests
└── native_engine.rs # Injects TauriScratchDiskBackend, exposes shared DocumentManager, pumps Phase 2 events
src/utils/nativeEngineBridge.ts # Full typed Phase 2 TS facade (documents, layers, masks, binary dirty-rect ingest,
# CoW history, memory budgets, thumbnails, timelapse, recovery, event listeners)
Key Architectural Guarantees
- Sparse Virtual Tiles & Zero-Allocation Fast Paths:
- Every layer stores both
tiles: HashMap<TileCoord, Arc<TileData>>andmask_tiles: HashMap<TileCoord, Arc<TileData>>atTILE_SIZE = 256. - Supported formats:
Monochrome1Bit(8 KB),Grayscale8Bit(64 KB),Color32Bit(256 KB), and internalRgba16Float(512 KB GPU working format with exact losslessu8 <-> f16round-trip plus 4×4 Bayer ordered dithering at 8-bit I/O boundaries). - Uniform tiles (e.g., white Paper fill on a 6071×8598 manga canvas, or newly added opaque masks) stay
TileStorage::SolidColor(0 bytes heap allocated), promoting toRawonly on mutated tiles and auto-pruning fully transparent tiles.
- Every layer stores both
- Tiered L1 ↔ L2 ↔ L3 Memory Pipeline + GPU Compute Mipmaps:
- L1 (DX12 GPU VRAM):
GpuTilePoolmaintainsRgba16Floatraster andR8Unormmaskwgpu::Texture2DArrayslot pools bounded by the VRAM budget preset (low=128 MB,medium=256 MB,high=512 MB,ultra=1024 MB) with LRU eviction. Dirty LOD 1..3 tiles regenerate asynchronously on the GPU viaMIPMAP_COMPUTE_WGSL. - L2 (CPU RAM): Cold tiles compress in-memory with
lz4_flex(TileStorage::Lz4Ram). - L3 (Scratch Disk): When RAM exceeds budget (or tabs go inactive),
TauriScratchDiskBackendpages cold compressed tiles directly in-process intosrc-tauri/src/scratch_disk.rs(zero Tauri IPC). - Device-Lost Resilience: After DX12 TDR recovery,
GpuRenderer::sync_documentre-hydrates GPU VRAM directly from Rust's CPU/LZ4/Scratch source of truth with zero data loss.
- L1 (DX12 GPU VRAM):
- Copy-on-Write (
Arc<TileData>) Undo/Redo & Collaborative Selective Undo:- Layer duplication (
duplicate_layer), history tile deltas (CowTileDelta), and full-document resize/crop snapshots clone onlyArcpointers (O(1)for untouched tiles); mutations copy only dirty tiles viaArc::make_mut. - Slider drags (e.g., opacity) coalesce within an 800 ms window via
coalesce_key. - Collaborative selective undo/redo marks individual
(peer_id, stroke_id)entries with tombstones (undone = true) and protects tiles later modified by other peers (conflict_protected). - Native DX12 strokes stamp at 240 Hz straight into the live display texture and commit dabs onto the active
SparseLayerGrid+ CoWHistoryStackon pen-up, emittingnative-engine://stroke-committed,native-engine://history, andnative-engine://thumbnails.
- Layer duplication (
- Zero-Copy Open, Save, Recovery, Thumbnails & Timelapse:
- Opening
.clip,.csp,.lip,.psd,.psb, or.inkparses directly in Rust (parse_clip_assembled/parse_psd_assembled/parse_ink_document), hydrates tiles intoDocumentManager, generates 64×64 PNG thumbnails in parallel with Rayon, syncs the DX12 GPU renderer, and returns only compact metadata to React. - Saving
.inkreads straight from Rust tiles with Rayon parallel deflate compression and atomic file writes (viasave_dialog::write_file_atomic). - Crash recovery checkpoints (
native_engine_recovery_checkpoint) and restores (native_engine_recovery_restore) callrecovery.rsin-process using the exactINKG v1/TD v1wire format. - Artwork timelapse captures (
native_engine_capture_timelapse_frame) downscale-composite directly in Rust and write PNG frames in-process viatimelapse.rs.
- Opening
Phase 2 Tauri Commands & Events
| Group | Commands (invoke from React → Rust) |
|---|---|
| Documents & Zero-Copy I/O | native_engine_create_document, native_engine_open_file, native_engine_open_file_bytes, native_engine_save_ink, native_engine_save_ink_with_dialog, native_engine_switch_document, native_engine_close_document, native_engine_get_document_state, native_engine_resize_canvas |
| Layer Tree, Masks & Dirty-Rect Ingest | native_engine_add_layer, native_engine_delete_layer, native_engine_duplicate_layer, native_engine_reorder_layers, native_engine_update_layer, native_engine_sync_layers, native_engine_clear_layer, native_engine_merge_down, native_engine_merge_folder, native_engine_add_mask, native_engine_remove_mask, native_engine_ingest_dirty_rect (raw binary body + x-doc-id / x-layer-id / x-rect-* headers) |
| CoW Undo/Redo & Collab Selective Undo | native_engine_undo, native_engine_redo, native_engine_jump_history, native_engine_selective_undo, native_engine_selective_redo, native_engine_push_history_meta, native_engine_get_history, native_engine_reset_history |
| Memory, Thumbnails, Timelapse & Recovery | native_engine_get_memory_stats, native_engine_set_memory_budget, native_engine_purge_memory, native_engine_request_thumbnails, native_engine_capture_timelapse_frame, native_engine_recovery_checkpoint, native_engine_recovery_restore |
| New Phase 2 Events (Rust → React) | Purpose |
|---|---|
native-engine://history |
Pushes compact HistoryStateSnapshot (items: HistoryItemMeta[], currentIndex, canUndo, canRedo) after native strokes or history commands. |
native-engine://thumbnails |
Streams async 64×64 PNG data-URL layer & mask thumbnail updates to useLayerManager.ts. |
native-engine://stroke-committed |
Notifies React on pen-up commit with dirty tile count, document ID, and layer ID (triggers timelapse & recovery hooks). |
Deleted / Retired Legacy JS & IPC Plumbing
- Deleted Tauri commands in
src-tauri/src/lib.rs: removedsave_undo_tile_cache,load_undo_tile_cache,clear_undo_tile_cache, andMAX_UNDO_CACHE_BYTES. - Removed JS undo-cache disk IPC in
src/utils/undoCache.ts: eliminated allinvoke('save_undo_tile_cache' / 'load_undo_tile_cache' / 'clear_undo_tile_cache')round-trips. - Bypassed JS pixel hydration & history duplication on Windows desktop (
isNativeCanvasActive()):DocumentLifecycleManager.tsx: opens.ink/.clip/.csp/.lip/.psd/.psb, saves.ink, switches/closes tabs, resizes canvases, restores crash recovery, and syncs memory budgets/purges directly vianativeEngineBridge.tswithout allocating JSSparseTileGridpixel buffers.useLayerDocumentOps.ts,useLayerCrud.ts,useLayerPropertiesAndMasks.ts,useLayerManager.ts: deterministic blank layer IDs (layer-1-{docId},layer-bg-{docId}), zero JS white-tile fill on new canvas, zero JS mask canvas allocation on native mask creation, and full Rust layer/mask/merge/duplicate synchronization.useDrawingHistory.ts: delegates undo, redo, jump-to-index, selective collab undo/redo, clear, and reset directly to Rust CoW history; skips JSTileDeltacapture and JSUndoCacheManagerwrites when native is active.vectorLayerRenderer.ts,recoveryService.ts,timelapseEngine.ts: text/balloon commits push tight RGBA8 dirty-rects via binarynative_engine_ingest_dirty_rect; recovery checkpoints and artwork timelapse frames run directly in-process in Rust.
Phase 2 Verification Summary
cargo test --workspace: 97 passed, 0 failed (ink-engine: 16 passed including sparse solid tiles, 1/8/32/16f conversions + 4×4 Bayer dithering, non-destructive masks, CoWArcsharing + coalescing + resize undo, collab selective undo tombstones, LRU → L2 LZ4 → L3 scratch disk round-trip, headless DX12GpuTilePoolLRU +MIPMAP_COMPUTE_WGSLGPU readback,.ink+ WAL + PNG timelapse;src-tauri: 81 passed includingTauriScratchDiskBackendin-process round-trip and zero-copy.psd&.clip→ink-engine→.inkround-trips).cargo clippy -p ink-engine --all-targets -- -D warnings: 0 errors, 0 warnings (cargo clippy --workspace --all-targetspasses with 0 warnings in all Phase 2 files).npm run build(tsc && vite build): 0 errors.npm run test(Vitest): 126 test files / 1,074 tests passing.
7. Phase 3: Feature-Complete WGSL Layer Compositor & Legacy WebGL2 Removal
Phase 3 replaces InkStudio's entire legacy WebGL2/Canvas2D ViewportCompositor with a native DX12 wgpu + WGSL multi-layer compositor inside crates/ink-engine/src/compositor/, eliminates Phase 2's CPU full-canvas flattening on sync_document, and deletes src/utils/compositor/ and <canvas ref={viewportCanvasRef} /> so WebView2 allocates zero viewport GPU FBOs or canvas textures.
Phase 3 Crate & Module Layout
crates/ink-engine/src/
├── compositor/
│ ├── mod.rs # CmykStandard, SoftProofConfig, OnionSkinFrame, CompositorDisplayConfig,
│ │ # FlattenOptions, ParsedLayerStyles, hex_to_rgb_f32
│ ├── layer_tree.rs # LayerTreeNode, clipping-chain grouping, nested folder/frame-folder partitioning,
│ │ # AboveSliceStrategy (Empty / NormalStack / BakedSingleBlend / Dynamic)
│ ├── stack_cache.rs # DocBounds, ScissorRect, LOD 0..3 zoom selection, frustum culling, Fnv1a64 signatures,
│ │ # LayerStackCacheTracker (3-slice invalidation + cache hit/rebuild telemetry)
│ ├── lut.rs # Fritsch-Carlson cubic spline Curves, Levels, Gradient Map, Color Balance + GPU LUT cache
│ ├── frame_geometry.rs # Ear-clipping polygon triangulation & mitered border geometry for comic frame-folders
│ ├── targets.rs # Rgba16Float SurfaceRgba16F (scissored copy_region_to), DocMaskCache (R8Unorm),
│ │ # StyledLayerCache (8-entry LRU), growable folder/clip/frame surface stacks
│ ├── renderer.rs # WgpuCompositor: FrameArenas (dynamic-offset uniform/instance staging, zero per-pass allocs),
│ │ # 3-slice stack caching + dirty-rect scissor WYSIWYG live stroke compositing,
│ │ # chunked (>2048px) headless render_document_flattened, render_layer_thumbnail_gpu
│ └── shaders/
│ ├── mod.rs # Shared WGSL shader re-exports
│ ├── blend_modes.rs # All 28 BlendModes (0..27: Normal..Luminosity) ported accurately from blendModesGlsl.ts
│ ├── screentone.rs # CSP screentone halftones (circle/euclidean/line/diamond, specified vs image density, DPI)
│ ├── layer_tile.rs # Instanced Rgba16Float tile + R8Unorm mask shader with expressionColor, layerColor tint & tone
│ ├── blit.rs # Fullscreen & scissored clear, straight-over, custom-blend (28 modes) & clip-masked blit
│ ├── adjustment.rs # GPU Curves / Levels / Gradient Map (256×1 LUT) + Color Balance (preserveLuminosity)
│ ├── layer_styles.rs # 2-pass separable Gaussian alpha blur + Stroke (outside/inside/center), Drop Shadow, Outer Glow
│ ├── frame_poly.rs # Comic frame-folder polygon mask, opaque fill, and mitered border rasterization
│ ├── viewport_present.rs # Matte, artboard shadow/border, checkerboard, CMYK Soft Proof (3 standards + gamut warning),
│ │ # perceptual Rec.709 Value Check, high-zoom pixel grid, 4×4 Bayer dithering
│ └── live_dab.rs # In-stack WYSIWYG live brush/eraser dab stamping + active-layer base/live merge shader
├── compositor_tests.rs # Pure unit + headless DX12 GPU pixel-readback test suite (all 28 blend modes, masks,
│ # clipping chains, pass-through vs isolated folders, comic frames, expression/tint/tones,
│ # all 4 adjustments, layer styles + LRU cache hits, 3-slice cache + live strokes + display passes)
├── gpu.rs # Hosts WgpuCompositor, pure-VRAM sync_document (no CPU flatten), render_document_frame,
│ # render_document_flattened, render_layer_thumbnail_gpu, headless readback
└── engine.rs # Manages CompositorDisplayConfig, handles Phase 3 EngineCommands, clears live stroke on commit
Key Architectural Guarantees
- Complete Feature Parity in
Rgba16FloatWGSL:- All 28 blend modes (
0..=27), CSPexpressionColor(color/gray/monochromewith threshold & black/white visibility), two-tonelayerColor/layerSubColortint, screentone halftones (circle,euclidean,line,diamond,specifiedvsimagedensity at document DPI), all 4 non-destructive adjustments (curves,levels,gradient-map,color-balance), and cached non-destructive layer styles (strokeoutside/inside/center,dropShadow,outerGlow). - Full hierarchical compositing: base + clipped sibling chains (
clipped: true), nestedfolderandframe-folder(comic polygon clipping + fill + mitered borders) in bothpass-throughand isolated modes, and per-layer non-destructive 8-bitmask_tiles. - Viewport display passes: animation onion skin tinted ghosts (rendered over paper/below layers and underneath the active cel), CMYK soft proofing (
japan-color-2001,us-web-coated-swop,iso-coated-v2) with out-of-gamut warning, linear Rec.709 perceptualvalueCheck, high-zoom pixel grid, and artboard checkerboard + border + drop shadow.
- All 28 blend modes (
- 3-Slice Baked Stack Cache, Frustum Culling, Auto-LOD & Dirty-Rect Scissor Live Strokes:
- Partitioned
Rgba16FloatGPU caches (below_active_cache,active_unit_surface,above_active_cachewithAboveSliceStrategy) keep painting on any layer of a 150-layer stack to a tight dirty-rect scissor re-composite of 3 surfaces without rebuilding below/above caches. - Live native brush/eraser dabs merge in-stack at WYSIWYG fidelity (clipped siblings, layer masks, expression color, screentones, and upper blend modes all apply live during the stroke).
- Dynamic-offset
FrameArenasstaging buffers eliminate per-pass GPU buffer allocations and queue write hazards; scissoredBackdropScratchcopies prevent stale-pixel artifacts outside the dirty scissor.
- Partitioned
- Isolated Headless GPU Flattening, Timelapse, Navigator & Thumbnails:
render_document_flattenedrenders full-resolution or scaled previews using dedicated export targets (never disturbing live viewport stack caches), automatically chunking canvases >2048px with layer-style margin overlap for seamless 600 DPI manga & Webtoon exports.native_docs.rsroutesflatten_document_rgba,capture_timelapse_frame, and effect-bearing async layer thumbnails through the DX12 GPU compositor first (with CPU fallback when headless/non-Windows).
New Phase 3 Tauri Commands & Diagnostics
| Command / Field | Purpose |
|---|---|
native_engine_set_display_config(config) |
Pushes CompositorDisplayConfig (onion skins, cel visibility overrides, soft proof, value check, pixel grid, checkerboard, matte color, stack caching toggle). |
native_engine_invalidate_compositor_cache() |
Forces full 3-slice stack, styled-layer, mask, and LUT cache invalidation. |
native_engine_flush_gpu_pool() |
Evicts cold VRAM tile slots on memory-pressure purge (performanceManager). |
native_engine_flatten_document(docId, options) |
Headless DX12 GPU document flatten returning binary [w: u32 LE, h: u32 LE, rgba8...] for PNG/JPEG/WebP/PSD export. |
native_engine_render_navigator_preview(docId, maxDim, options) |
Fast DX12 GPU downscaled preview for NavigatorPanel.tsx. |
EngineDiagnostics::{stack_cache_hits, stack_cache_rebuilds} |
Exposes 3-slice stack cache hit/rebuild counters to performanceManager & diagnostics subscribers. |
Deleted Legacy WebGL2 Compositor & Frontend Migration
- Deleted completely:
src/utils/compositor/(all 21 legacy WebGL2/Canvas2D compositor, FBO, GLSL shader, and tile-draw modules)src/utils/compositor.tssrc/utils/__tests__/compositor.test.ts<canvas ref={viewportCanvasRef} />element insrc/components/CanvasArea.tsx
- Replaced with lightweight pure-TS / native-bridge modules:
src/components/canvasArea/useCompositorViewport.ts: zero-<canvas>, zero-WebGL2 state-sync hook pushingNativeCompositorDisplayConfigtoink-engine, syncing DOM overlay transforms vianavigation.subscribeCamera, and registering DX12 telemetry (backend: 'dx12') &flushNativeGpuPool()withperformanceManager.src/utils/saveManager/gpuComposite.ts&src/components/NavigatorPanel.tsx: useflattenNativeDocument/renderNativeNavigatorPreviewon DX12 desktop (with pure Canvas2D/CPU fallback only for headless Vitest).src/utils/layerTree.ts&src/utils/previewRenderer.ts: zero-WebGL pure-TS tree helpers and non-Tauri preview fallback.
Phase 3 Verification Summary
cargo test --workspace: 109 passed, 0 failed (ink-engine: 28 passed including headless DX12 GPU pixel-readback verification of all 28 blend modes, clipping chains, 8-bit masks, pass-through vs isolated folders, comic frame folders, expression color/tint/screentones, all 4 adjustments, layer styles + LRU cache hits, 3-slice stack caching + dirty-rect WYSIWYG live strokes + onion skin + CMYK soft proof & gamut warning + value check + chunked >2048px flatten;src-tauri: 81 passed including live DirectComposition + DX12 swapchain presentation).cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 3 files (crates/ink-engine/src/compositor/*,compositor_tests.rs,gpu.rs,src-tauri/src/native_docs.rs,native_engine.rs,lib.rs).npm run build(tsc && vite build): 0 errors (built in 5.17s).- Vitest (
vitest run): 125 test files / 1,024 tests passing, 0 failures. - Hard decoupling invariant preserved:
crates/ink-engine/Cargo.tomlstill has zero dependencies ontauri,wry,tao, orwebview2-com.
8. Phase 4: Core Native Stroke & GPU Brush Engine
Phase 4 moves InkStudio's entire stroke geometry pipeline (curves, CSP stabilizer, sharp corners, post-correction, Catmull–Rom/Hermite spline & arc-length resampler, taper + ballistic flick, straight & 1/2/3-point perspective ruler snapping, and ephemeral speculative stroke head prediction) plus the full CSP-compatible GPU instanced stamp, multi-subTip, paper-grain, dual-brush, and watercolor wet-edge engine directly into crates/ink-engine/src/stroke/ and crates/ink-engine/src/brush/. Active strokes run end-to-end on the Rust engine thread directly from tablet_input.rs SPSC ring samples to sparse 256×256 Rgba16Float GPU stroke tiles with zero JS involvement during strokes, and delete #ink-predicted-canvas, the hidden draft <canvas>, WebGlBrushEngine.ts, and DualBrushEngine.ts.
Phase 4 Crate & Module Layout
crates/ink-engine/src/
├── stroke/ # Replaced flat Phase 1-3 stroke.rs
│ ├── mod.rs # StrokePoint, CommittedStrokePoint, StrokePipelineConfig, NativeStrokePipeline
│ ├── curves.rs # CompiledCurveLut (256-entry Fritsch-Carlson PCHIP + CSP stub protection),
│ │ # GlobalPressureCurve, calculate_stroke_width (light-pressure anti-collapse floor)
│ ├── stabilizer.rs # OneEuroAxis pressure filter, CSP 0..50 sample-rate-invariant 3-stage isotropic
│ │ # cascade, Frenet lateral twitch damping, backtrack spike guard, sharp-corner
│ │ # CornerConvergencePlan, full-tail catch-up, apply_csp_post_correction (0..5)
│ ├── spline.rs # Centripetal Catmull-Rom (0.48*d12 clamp, C0 corner breaks), provisional Hermite
│ │ # stitching, ArcLengthTable, ArcLengthResampler (exact carry-over)
│ ├── taper.rs # Full CspTaperSettings (inOutType 0..3, inOutBySpeed, sharpness, per-channel targets),
│ │ # TaperEngine (G-Pen 3-stage Hermite S-curve, ballistic flick + 32ms dwell/zoom gates)
│ ├── rulers.rs # StraightRulerSnapSession (26/zoom edge vs parallel + Alt override),
│ │ # PerspectiveSnapSession (1/2/3-point, 4 doc px lock, |dot| axis + Alt override)
│ └── prediction.rs # Strictly ephemeral build_predicted_segments rendered natively in wgpu
├── brush/
│ ├── mod.rs # Public GPU brush exports
│ ├── prng.rs # Deterministic per-stroke Xoshiro256** (SplitMix64 seeded) + dab_hash_float
│ ├── config.rs # NativeBrushConfig mirroring BrushSettings, CspSensorConfig, BrushDynamics,
│ │ # CspSpraySettings, CspDualBrushConfig, all 9 paper modes, 4 grain mapping modes,
│ │ # 3 tip blend modes, 32 combine modes (0..31), 7 angle dynamics, 6 sub-tip orders,
│ │ # 3 tip flip modes, and all 12 DualBrushCompositeModes
│ ├── dynamics.rs # GpuBrushDab (80B Pod), spherical tilt, multi-sensor evaluator, elliptical stepping,
│ │ # gap-adjusted density, multi-axis jitter (count 1..10, scatter, HSV/temp/FG-BG color),
│ │ # spray particle emitter, StrokeDabEmitter (primary + independent dual secondary)
│ ├── procedural_tips.rs # Native Sfc32, periodic bilinear grids, Worley cellular domes, all 7 seamless
│ │ # 512×512 SurfaceTextureId heightfields + built-in 256×256 procedural brush tips
│ ├── tip_cache.rs # Content-hashed TipTextureCache (PNG/RGBA8 upload-once, D2Array multi-subTip sets,
│ │ # seamless repeat paper textures)
│ ├── shaders.rs # WGSL shaders: PAPER_GRAIN_WGSL (9 modes × 4 mappings), BRUSH_DAB_TILE_WGSL
│ │ # (tile + viewport prediction, SDF + D2Array, AA 0..3 / 1-bit binary, dual-tone),
│ │ # STROKE_DARKEN_MERGE_WGSL, STROKE_POST_TILE_WGSL (12 Dual Brush modes + per-stroke grain),
│ │ # WET_EDGE_TILE_WGSL (2-pass separable Gaussian on 288×288 3×3-neighbor padded window),
│ │ # TILE_COMMIT_COMPUTE_WGSL (all 32 combine modes, alphaLocked, mono 1-bit, selection hook)
│ └── sparse_stroke.rs # GpuBrushEngine: dynamically growing sparse 256×256 Rgba16Float stroke tile pools
│ # (never full-canvas FBO), batched tile binning, live resolved cache, single-submit
│ # GPU-to-GPU layer pool commit + batched RGBA8 readback
├── io/png_codec.rs # Added pure-Rust decode_png_rgba8 (8/16-bit Gray/RGB/Palette/GrayAlpha/RGBA)
├── compositor/ # Added SPARSE_STROKE_PROJECT_WGSL, 32-mode live_stroke_merge, LiveGpuStrokeOverlay,
│ # transient predicted-head rendering + prev/cur predicted scissor unioning
├── phase4_tests.rs # 12 Phase 4 parity tests + 4096×4096 300px textured dual-brush benchmark
├── gpu.rs # Hosts GpuBrushEngine, texture upload, sparse stamp/commit, GPU mipmap regeneration
└── engine.rs # End-to-end native stroke session: lazy per-tile Arc<TileData> CoW capture,
# ephemeral prediction, finalize re-raster (postCorrection/useOut), locked/non-raster
# guards, compact StrokeCommitted event (dirtyRect, history, committed points)
src-tauri/src/
├── tablet_input.rs # Added VK_SHIFT (0x0100) & VK_MENU (0x0200) modifier bits to NativeInputSample::buttons
├── native_engine.rs # Added native_engine_set_full_brush, native_engine_set_pressure_curve,
└── lib.rs # native_engine_set_rulers, native_engine_upload_brush_texture (raw binary upload)
Key Architectural Guarantees
- Sparse
256×256Rgba16FloatGPU Stroke Tiles (Never a Full-Canvas FBO):GpuBrushEngineallocates stroke tiles lazily strictly for(tx, ty)coordinates touched by incoming dabs, projecting only visible stroke tiles intoWgpuCompositor'slive_stroke_surfacein-stack atactiveLayerId(so clipping chains, masks, expression color, screentones, and upper blend modes preview WYSIWYG live).- Speculative stroke head dabs (
prediction.rs) are rendered strictly ephemerally into the viewport live stroke pass and unioned with the previous frame's predicted scissor so predicted tips never leave ghosts or mutate committed geometry.
- Seamless 2-Pass GPU Watercolor Wet Edge & Exact Alpha Conventions:
WET_EDGE_TILE_WGSLsamples a3×3neighborhood of sparse stroke tiles into a288×288(256 + 2×16padding) compute scratch texture for separable horizontal + vertical Gaussian blur, guaranteeing zero tile seams across tile boundaries and zero outer halo outside the stroke silhouette.GpuTilePoolmaintains straightRgba16FloatwhileGpuBrushEngine&WgpuCompositoractive surfaces use premultipliedRgba16Float;TILE_COMMIT_COMPUTE_WGSLmerges straight base + premultiplied stroke across all 32CspBrushCombineModes (plusalphaLocked,isEraser/isBgEraser, 1-bit monochrome, and Phase 6 selection mask hook) and writes both the updatedRgba16FloatVRAM slot and packedRGBA8readback bytes in a single compute dispatch.
- Zero-IPC Hot Strokes & Compact Commit Telemetry:
- React syncs
NativeBrushConfig, FG/BG colors, globalPressureCurveSettings, andStraightRuler/PerspectiveRuleronly when changed (memoized signatures), uploading custom tips/sub-tips/dual-tips/paper textures once by FNV-1a content hash. - Before the first dab touches tile
(tx, ty),engine.rsrecords its lazyArc<TileData>CoW reference; on pen-up, GPU-to-GPU tile commit + LOD 1..3 compute mipmaps + CoW undo commit emit only a compactStrokeCommittedpayload (dirtyRect,history,points) for Shift+Click anchor continuity and collaboration broadcast.
- React syncs
Deleted Legacy Files & DOM Canvases
- Deleted completely:
src/engine/WebGlBrushEngine.ts(3,504 lines of legacy WebGL2 brush/dual/ribbon/paper GLSL engine)src/engine/DualBrushEngine.ts(pure-TS config/CPU helpers extracted intosrc/utils/dualBrushConfig.ts)<canvas id="ink-predicted-canvas" ... />and<canvas ref={effectiveDraftCanvasRef} ... />fromsrc/components/CanvasArea.tsx(zero mounted stroke<canvas>elements remain in the DOM; a detached unmounted canvas is lazily created only for Phase-5-deferred Natural Paint / Ribbon / Bristle brushes and headless Vitest)
- Temporary Phase 5 Capability Gate (
canNativeEngineHandleBrushinsrc/utils/nativeEngineBridge.ts):- Routes all stamp, dual-brush, textured, multi-subTip, spray, wet-edge, binary manga (
antiAlias == 0), decoration, and eraser strokes on raster layers directly through Rustink-engine. - Defers ONLY
colorMixing/NaturalPaintRenderer/RibbonBrushEngine/BristleRibbonEngineand non-raster/mask layers until Phase 5 deletes the remaining JS stroke engines completely.
- Routes all stamp, dual-brush, textured, multi-subTip, spray, wet-edge, binary manga (
4096×4096 300px Textured Dual-Brush Benchmark (--release, DX12)
Measured on NVIDIA GeForce GTX 1650 (DX12, 1920×1080 viewport, 4096×4096 canvas, 60-frame curved sweep with a 300px textured Dual Brush [pro:watercolor-wash-256 + pro:sumi-fude-brush-256], 512×512 cold-press-watercolor paper grain, 2-pass watercolor wetEdge, stabilizer + ephemeral head prediction):
| Metric | Measured Result |
|---|---|
| Sparse GPU Stroke Tiles Allocated | 31 / 256 tiles (12.1% of a full 4K FBO — zero 4K/8K FBO allocation) |
| Input → Present Frame Time (stamp + dual + wet edge + 1080p WYSIWYG composite + predicted head) | avg 5.78 ms (~173 FPS) · p50 6.83 ms · p95 10.00 ms (includes synchronous headless GPU fence wait) |
| Pen-Up GPU Tile Commit (all 31 tiles = 2.0M px) | 5.75 ms GPU commit (0.185 ms/tile, <1 ms for typical 1–5 tile strokes) · 9.09 ms total including CoW Undo + LOD 1..3 compute mipmaps |
Phase 4 Verification Summary
cargo test --workspace: 120 passed, 0 failed (ink-engine: 39 passed including all 12 new Phase 4 parity & DX12 GPU tests covering PCHIP curves + anti-collapse floor, CSP stabilizer lag/isotropy/Frenet twitch damping/full-tail catch-up, sharp corners + post-correction + ephemeral prediction, spline arc-length carry-over + G-Pen/ballistic flick +CspTaperSettings, straight & perspective ruler snapping, multi-sensor dynamics + spray +Xoshiro256**, all 7 seamless 512×512 surface heightfields + PNG encode/decode round-trip, 1-bit binary manga inkingantiAlias == 0, dual-tone tips,blendTipsMode::Compare, all 9 paper modes per-dab & per-stroke, all 12 Dual Brush modes, seamless 2-pass watercolorwetEdgeacross thex = 256tile boundary,alphaLocked/Behind/Clear, end-to-endEngineHandleCoW Undo/Redo, and the 4K 300px dual-brush benchmark;src-tauri: 81 passed).cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 4 modules (crates/ink-engine/src/stroke/*,crates/ink-engine/src/brush/*,src-tauri/src/native_engine.rs).npm run build(tsc && vite build): 0 errors (built in 2.67s).- Vitest (
vitest run): 125 test files / 1,021 tests passing, 0 failures. - Hard decoupling invariant preserved:
crates/ink-engine/Cargo.tomlremains 100% free oftauri,wry,tao, andwebview2-com.
9. Phase 5: Full Physical Media & Painterly GPU Compute Engine + Legacy JS Brush Engine Deletion
Phase 5 completes the brush migration: 100% of InkStudio brush presets (Pen, Sketch, Brush, Blend, Natural Paint, Texture & FX, Decoration, Ribbon, Bristle-Ribbon, Bristle-Hybrid, Eraser, .sut, .inkb, and Layer Mask painting) now execute exclusively inside crates/ink-engine on Windows DX12 with zero CPU readPixels stalls, persistent R16Float impasto 3D heightfield tiles + live relief lighting, and all legacy JS brush engine files deleted.
Phase 5 Crate & Module Layout
crates/ink-engine/src/
├── natural_paint/ # New Phase 5 Physical Media & Painterly Engine
│ ├── mod.rs # Public module exports
│ ├── pigment.rs # Exact 1:1 8-band cube-root Kubelka-Munk + 6-basis reflectance decomposition +
│ │ # Saunderson (k1=0.0052, k2=0.38) + Linear sRGB <-> OKLab (Rust + PIGMENT_WGSL),
│ │ # DirtyBrushGpuBank (persistent 64-bristle BrushLoadBuffer + 16×16 SpatialTipMixer,
│ │ # honoring autoClean: true/false across strokes + CleanDirtyBrush)
│ ├── bristle_ribbon.rs # BristleRibbonSimulator: 4..64 physical strands, spring lag & stiffness,
│ │ # all 7 profiles (Round, Flat, Filbert, Fan, Rake, Knife, Custom), clumping,
│ │ # pressure/tilt splay + bristleSplaySensor, lift-off, 5-band under-bed,
│ │ # BristleRibbon & BristleHybrid capsule generation (GpuBristleCapsule)
│ ├── ribbon.rs # RibbonMeshBuilder & GpuRibbonRenderer: continuous UV-mapped ribbon triangle
│ │ # strips, miter clamping + bevel corners + anti-bowtie guard, integer tile splitting,
│ │ # repeat/reverse/once modes, subTips, flipH/flipV, Dual Brush ribbon,
│ │ # isColorTip/isDualToneTip, paper grain, AA 0..3
│ ├── impasto.rs # NaturalPaintTilePools: sparse 256×256 Rgba16Float color + R16Float impasto
│ │ # heightfield + lazy GPU-composited mixGroundColor ground_pool (zero readPixels!)
│ └── natural_paint.rs # GpuNaturalPaintEngine: 4 WGSL compute pipelines:
│ # - cs_update_bristle_load (zero-readback canvas/ground pickup + belly feed + depletion)
│ # - cs_raster_natural_paint (multi-bristle KM/OKLab mixing, all 4 NaturalMixingModes,
│ # dryBrush valley skipping + penetrationCurve, watercolor granulation, CSP useBlur,
│ # and arched 3D R16Float impasto accumulation in the same compute dispatch!)
│ # - cs_color_mix_pickup + cs_color_mix_stamp (standard CSP colorMixing 16×16 SpatialTipMixer)
├── tiles/ # Sparse R16Float impasto heightfield tiles (TileFormat::Height16Float)
│ ├── format.rs / tile_data.rs / grid.rs # TileGrid::impasto_tiles + f16/f32 helpers + CoW apply_gpu_committed_impasto_tiles
├── document/ # ImpastoLayerLight metadata + UndoEntry::ImpastoTileDelta / MaskTileDelta
├── memory/ # ImpastoGpuAtlas (256×256 R16Float texture array in GpuTilePool) + LZ4/scratch tiering
├── io/ # WAL impasto deltas + .ink v2 ZIP `impasto/<layer_id>/<tx>_<ty>.r16f` round-trip
├── compositor/
│ ├── shaders/impasto_lighting.rs # IMPASTO_HEIGHT_PROJECT_WGSL + IMPASTO_LIGHTING_WGSL (3×3 Sobel normals,
│ │ # directional diffuse, 5-tap cast shadow march, concavity micro-AO, chromatic
│ │ # trough deepening, 2-lobe Blinn-Phong satin oil gloss & glint)
│ ├── shaders/live_dab.rs # Added combine_mode == 32u straight Rgba16Float direct-replace live stroke merge
│ └── renderer.rs / targets.rs / stack_cache.rs # Live Impasto height projection & relief lighting pass integrated per layer
├── brush/
│ ├── config.rs # Added NaturalPaintSettings, BristleSettings, ImpastoSettings, NaturalMixingMode,
│ │ # BrushRenderMode, CspRibbonRepeatMode, dryBrush, granulation, autoClean, mixGroundColor
│ └── sparse_stroke.rs # Hosts GpuRibbonRenderer + GpuNaturalPaintEngine + direct layer mask commit
├── phase5_tests.rs # 8 Phase 5 unit & headless DX12 GPU tests + 4096×4096 250px GPU benchmark
├── gpu.rs / engine.rs / types.rs # Native Mask Mode strokes, CleanDirtyBrush, RenderBrushPreview (native GPU PNG/RGBA8)
src-tauri/src/
├── native_engine.rs / native_docs.rs / lib.rs # Added native_engine_clean_dirty_brush, native_engine_set_mask_mode,
# native_engine_render_brush_preview; TileFormat::Height16Float support
Key Architectural Guarantees
- Zero-Readback GPU Pigment Physics (
natural_paint/pigment.rs&natural_paint.rs):- Active layer tiles are copied GPU-to-GPU into
NaturalPaintTilePools::color_pool; whenmixGroundColoris true, layers belowactiveLayerIdare lazily composited intoground_pooldirectly on the GPU — zeroreadPixelscalls occur during active strokes. DirtyBrushGpuBankkeeps persistent VRAMBrushLoadBuffers (64 × GpuBristleSlot) and16×16SpatialTipMixerbuffers keyed by preset ID, honoringautoClean: falseacross consecutive strokes until explicitly reset viaCleanDirtyBrush(native_engine_clean_dirty_brush).- Supports all 4
NaturalMixingModes (blend,running_color,smear,impasto_mix), exact 8-band cube-root Kubelka–Munk subtractive mixing (perceptualMixing,pigmentMixingStrength), OKLab interpolation, CSPamountOfPaint/densityOfPaint/colorStretch/useBlur/blurStrength, 512×512 seamless surface heightfielddryBrushvalley skipping (penetrationCurve), and watercolorgranulationvalley settling.
- Active layer tiles are copied GPU-to-GPU into
- Persistent Sparse
R16FloatImpasto Heightfield + Live Relief Lighting:- Impasto heightfields are stored per layer as lazily-allocated sparse
256×256R16Floattiles (TileGrid::impasto_tiles), participating atomically in Copy-on-Write Undo/Redo, tiered LZ4/scratch memory, WAL crash recovery, and.inkv2 ZIP serialization. cs_raster_natural_paintupdates color andR16Floatheight in the exact same GPU compute pass (sculpting an arched macro oil cross-section + bristle grooves + outeredgeRidgewithout mesa clipping).WgpuCompositorprojects committed + live impasto tiles into a viewportR16Floatsurface and executesIMPASTO_LIGHTING_WGSLlive at interactive frame rates.
- Impasto heightfields are stored per layer as lazily-allocated sparse
- 100% Native Brush Coverage (Zero JS Brush Fallback):
canNativeEngineHandleBrushinsrc/utils/nativeEngineBridge.tsnow returnstruefor every brush preset on both raster layers and Layer Mask mode (SetMaskModeroutes strokes directly intolayer.grid.mask_tileswith CoW mask undo).- Brush library thumbnails and Brush Studio previews use native DX12 GPU stroke rendering (
renderNativeBrushPreview).
Deleted Legacy JS Brush Engines & Files
- Deleted completely (10 engine/pigment files +
brushStrokeSession/+ 16 obsolete JS-only brush engine tests):src/engine/BrushEngine.tssrc/engine/NaturalPaintRenderer.tssrc/engine/RibbonBrushEngine.tssrc/engine/BristleRibbonEngine.tssrc/engine/InputStabilizer.tssrc/engine/SplineGenerator.tssrc/engine/TaperEngine.tssrc/engine/StrokePipeline.tssrc/utils/colorMixingEngine.tssrc/utils/spectralPigmentEngine.tssrc/hooks/drawing/brushStrokeSession/(entire directory)- 16 obsolete JS-only brush engine test files in
src/utils/__tests__/(whose parity coverage now lives in Rustphase4_tests.rs&phase5_tests.rs)
- Minimal pure non-engine helpers retained for UI/gradients/retouch/collab:
src/utils/brushMath.ts(lightweight PCHIP/curve preset constants & tip dimension helpers for UI controls & vector/collab paths)src/utils/pigmentMath.ts(pure stateless 8-band KM color math forPigmentBlendControl.tsx,gradientEngine.ts,retouchEngine.ts, andtileEngine/strokeComposite.ts— no brush engine, reservoir, or pixel sampler)src/hooks/drawing/useBrushStrokeSession.ts(slimmed to native Rust stroke-commit bridging + Vector layer drawing only)
4096×4096 250px Physical Media GPU Benchmark (--release, DX12)
Measured on NVIDIA GeForce GTX 1650 (DX12, 1920×1080 viewport, 4096×4096 canvas, 31-step curved sweep with 250px full physical media brushes):
| Brush Preset & Workload | Capsules / Sparse Tiles | Interactive Stroke Time | Pen-Up GPU Commit | CPU readPixels Stalls |
|---|---|---|---|---|
impasto-bristle-oil (250px, 32 bristles, R16Float impasto + live Sobel/shadow/specular relief lighting) |
4,620 capsules · 20 color + 20 R16F tiles |
avg 9.90 ms/step (101.1 FPS) | 16.7 ms (all 20 color + 20 R16F tiles) |
0 |
wet-mixing-filbert (250px, 28 bristles, mixGroundColor lazy ground composite + 8-band KM compute) |
4,120 capsules · 17 color tiles | avg 4.96 ms/step (201.4 FPS) | 13.5 ms (all 17 color tiles) | 0 |
Phase 5 Verification Summary
cargo test --workspace: 128 passed, 0 failed (ink-engine: 47 passed, including all 8 new Phase 5 Rust & headless DX12 GPU tests covering 8-band cube-root KM + OKLab pigment mixing, zero-readback GPU canvas/ground pickup + all 4NaturalMixingModes + CSPcolorMixing, multi-bristle spatial mixing + depletion +autoClean: false/true+ all 7BristleProfilePresets +BristleHybrid, dry-brush 512×512 heightfield valley skipping + watercolor granulation, continuous ribbon UV continuity + miter/bevel + anti-bowtie + Dual Brush ribbon GPU rasterization, persistentR16Floatimpasto + CoW Undo/Redo +.inkv2 round-trip + live 180° azimuth relief lighting shift, native mask-mode painting + native DX12 brush preview PNG rendering, and the 4K 250px GPU benchmark;src-tauri: 81 passed).cargo clippy --workspace --all-targets: 0 errors, 0 warnings across all Phase 5 modules (crates/ink-engine/src/natural_paint/*,engine.rs,gpu.rs,brush/sparse_stroke.rs,compositor/shaders/impasto_lighting.rs,phase5_tests.rs,src-tauri/src/native_engine.rs,native_docs.rs).npm run build(tsc && vite build): 0 errors (built in 4.45s).- Vitest (
vitest run): 110 test files / 820 tests passing, 0 failures. - Hard decoupling invariant preserved:
crates/ink-engine/Cargo.tomlcontinues to have zero dependencies ontauri,wry,tao, orwebview2-com.
10. Phase 6 Complete — Complete Canvas Offload, WebView2 Purge & Final Before/After Metrics
Phase 6 completes the InkStudio Native Rust + wgpu (DX12 / DirectComposition) migration. Every remaining interactive raster, selection, liquify, fill, transform/warp, retouch, gradient, shape, vector rasterization, filter/tonal, and multiplayer remote-draft pipeline now executes natively inside crates/ink-engine. WebView2 is strictly an ultra-lightweight, transparent React UI shell holding zero full-resolution HTMLCanvasElement or OffscreenCanvas backing stores and zero JS pixel-processing loops.
Added & Completed Phase 6 Rust / Tauri Modules
crates/ink-engine/src/
├── selection/
│ ├── mod.rs / mask.rs # Sparse R8Unorm 256×256 selection mask tiles bound directly into
│ │ # Phase 4/5 brush, ribbon, natural-paint, fill, filter & clear paths;
│ │ # exact O(n) Felzenszwalb–Huttenlocher EDT expand/contract + Gaussian feather
│ ├── ops.rs # Rect, 4×4 AA Lasso, Magic Wand (tolerance, contiguous, antiAlias,
│ │ # referMode: active/all/reference), Select Pen/Eraser, invert, clear,
│ │ # delete-outside, fill, cut/copy/paste, move-to-new-layer, floating selection
│ └── marching_ants.rs # Viewport-resolution animated GPU Marching Ants overlay shader
│ # (MARCHING_ANTS_WGSL edge detection on R8Unorm mask — zero DOM SVG ants!)
├── tools/
│ ├── mod.rs # Shared native tool types & hex/color helpers
│ ├── liquify.rs # Interactive GPU Rg16Float displacement field (core-spec render pass)
│ │ # for all 8 LiquifyModes (push, expand, pinch, push-left, push-right,
│ │ # twirl-cw, twirl-ccw, reconstruct), size/strength/hardness/usePressure/
│ │ # multiLayer; live in-stack Phase 3 warp + CoW tile bake on commit
│ ├── fill.rs # Direct Rust sparse-tile Flood Fill (refer-all/active/reference, closeGap
│ │ # with V-tip recovery, centerline-guarded areaScale, antiAlias, opacity),
│ │ # 4×4 AA Lasso Fill, Smart Line Fill (enclose-and-fill, paint-unfilled),
│ │ # and instant native Eyedropper/Pipette (<0.03 ms)
│ ├── transform.rs # Live GPU in-stack preview + Anti-Ringing Lanczos-3 / Bicubic CoW bake
│ │ # for all 5 TransformModes (affine, perspective, Catmull-Rom mesh,
│ │ # ARAP puppet warp w/ pin depths, Hormann–Floater MVC cage) across
│ │ # single layers, selections, and multi-layer groups + seamless switch_mode
│ ├── retouch.rs # 7-mode native tile Retouch (Clone Stamp, Heal, Dodge, Burn, Sponge,
│ │ # Smudge w/ 8-band KM pigment mixing, Blur) with CoW undo
│ ├── gradient.rs # Linear/Radial/Conical/Diamond/Mesh gradients (live GPU preview + commit)
│ ├── shape.rs # Analytic SDF Shapes, Pen path strokes & QuickShape auto-snapping
│ ├── vector.rs # Fast native vector stroke tessellation & rasterization into layer tiles
│ └── filters.rs # Live GPU preview + CoW tile commit for Gaussian blur, motion blur,
│ # unsharp mask, film grain, PCHIP curves, levels, HSL, color balance,
│ # brightness/contrast, gradient map, and RGBA luminance histogram
├── collab/
│ ├── mod.rs # Zero-JS-canvas binary TILE wire codec (EMPTY/SOLID/LZ4/RAW) streaming
│ │ # directly between ink-engine sparse tiles and server.rs / WebRTC
│ └── draft_renderer.rs # Per-peer live GPU draft layers (PeerDraftSurface) composited natively
│ # inside Phase 3 WgpuCompositor with zero-flicker handoff on commit
├── io/image_codec.rs # Pure-Rust lossless WebP (VP8L) + PNG/JPEG export directly from tiles
└── phase6_tests.rs # 10 comprehensive Phase 6 unit, DX12 GPU & 4K/8K benchmark tests
src-tauri/src/
├── native_tools.rs # Typed Tauri IPC commands for selection, liquify, fill, eyedropper,
│ # transform, retouch, gradient, shape, vector, filters & collab fast-path
└── wic_codec.rs # Hardware-accelerated Windows Imaging Component (WIC) JPEG/PNG encoder
Purged Legacy JS Raster Engines & Dead Pixel-IPC Commands
- 25 Legacy JS Raster Modules / Directories Deleted (verified absent by
src/utils/__tests__/phase6WebviewPurgeAudit.test.ts):src/utils/tileEngine/(entire directory) &src/utils/tileEngine.tssrc/utils/liquifyEngine.ts,src/utils/floodFill.ts,src/utils/smartLineFill.tssrc/utils/transformEngine.ts,src/utils/transformResampler.ts,src/utils/puppetWarpEngine.ts,src/utils/cageWarpEngine.tssrc/utils/retouchEngine.ts,src/utils/gradientEngine.ts,src/utils/filterEngine.ts,src/utils/tonalEngine.tssrc/utils/selectionUtils.ts,src/utils/shapeEngine.ts,src/utils/quickShapeEngine.ts,src/utils/vectorStrokeRenderer.tssrc/utils/canvasWebglCompositor.ts,src/utils/canvasBlit.ts,src/utils/pixelSampler.ts,src/utils/layerMaskUtils.tssrc/engine/RemoteStrokeRenderer.ts,src/engine/RemoteDraftCanvasManager.tssrc/components/canvasArea/SelectionMarchingAnts.tsx(replaced byMARCHING_ANTS_WGSLinwgpu)src/utils/webtoonExporter.tslegacy canvas overload removed (100% native Rust tile slice export)
- 13 Dead Pixel-IPC Tauri Commands Deleted from
src-tauri/src/lib.rs:native_apply_filter,native_flood_fill,native_liquify_step,native_compress_tiles_lz4,native_decompress_tiles_lz4,save_undo_tile_cache,load_undo_tile_cache,parse_psd_file,parse_clip_file,export_psd_file,compose_layer_stack,rasterize_text_layer_legacy,encode_canvas_rgba_png
- Zero-Canvas WebView2 Memory Audit:
src/utils/__tests__/phase6WebviewPurgeAudit.test.tsstatically audits all 25 core open, draw, undo, zoom, transform, liquify, collab, webtoon export, and save modules to guarantee zerodocument.createElement('canvas'),new OffscreenCanvas(...), or full-document<canvas>backing stores exist anywhere in the active WebView2 pipeline.
Final Before / After Architecture & Performance Metrics
Measured in --release on NVIDIA GeForce GTX 1650 (DirectX 12, Windows Desktop, 1920×1080 viewport) via cargo test -p ink-engine phase6_4k_8k --release -- --nocapture and Phase 3–5 DX12 benchmarks:
| Metric | Legacy WebView2 / WebGL2 + JS Tile Engine (Before) | Native Rust + wgpu DX12 Engine (After — Phase 6) |
Improvement |
|---|---|---|---|
| WebView2 Full-Document Canvas RAM (4K/8K artwork) | ~450–900 MB (dense <canvas> + WebGL2 FBOs + JS tile heap) |
0 MB (pure transparent React UI shell; zero full-res <canvas>) |
100% eliminated |
Rust Process Artwork RAM — 4K (3840×2160, 12 layers) (380 MB dense eq.) |
N/A (duplicated across JS heap & IPC byte copies) | 22.75 MB L1 active sparse raw · 0.09 MB L2 LZ4 compressed | 16.7× – 4,200× smaller |
Rust Process Artwork RAM — 8K (7680×4320, 8 layers) (1,012 MB dense eq.) |
>1.2 GB / frequent V8 GC pauses & WebGL2 OOM risk | 25.00 MB L1 active sparse raw · 0.10 MB L2 LZ4 compressed | 40.5× – 10,100× smaller |
| Stroke Input-to-Photon Frame Time (4K 12-layer, 1080p WYSIWYG DX12) | ~18–35 ms (Chromium input -> IPC -> JS brush -> WebGL2 -> DWM) | 3.96–5.11 ms (~195–252 FPS; lock-free SPSC Wintab/WinInk -> DX12 waitable swapchain) | 4× – 7× lower latency |
| Pan / Zoom / Rotate Compositor FPS (4K 12-layer, 1080p) | 25–55 FPS (JS main-thread + WebGL2 texture uploads) | 78–81 FPS worst-case sync headless continuous rotation · 160–240+ FPS live DX12 swapchain w/ 3-slice stack cache | 3× – 5× higher FPS |
| 4K Interactive Liquify FPS (160px brush + live 1080p composite) | ~8–15 FPS (per-step native_liquify_step CPU/IPC round-trips) |
51.5–57.1 FPS sync headless DX12 (120+ FPS pipelined live swapchain; Rg16Float GPU field, 0 IPC) |
6× – 10× higher FPS |
| Undo / Redo Latency (4K 12-layer document, 100-op avg) | 15–80 ms (JS ImageData / tile decompress + canvas redraw) |
0.039 ms (39.4 µs) (Arc<TileData> O(1) CoW pointer swap) |
~400× – 2,000× faster |
| Eyedropper / Pipette Sample Latency (4K 12-layer composited) | 3–12 ms (WebGL2 readPixels GPU pipeline stall) |
0.019–0.029 ms (19–29 µs) (direct Rust tile/framebuffer sample) |
>100× faster (<0.1 ms) |
Phase 6 Final Verification Summary
cargo test --workspace: 135 passed, 0 failed (ink-engine: 57 passed, including all 10 new Phase 6 unit, DX12 GPU & 4K/8K benchmark tests;src-tauri: 78 passed).cargo clippy --workspace --all-targets: 0 errors across the entire workspace and 0 warnings across all Phase 6 modules (crates/ink-engine/src/selection/*,tools/*,collab/*,io/image_codec.rs,phase6_tests.rs,src-tauri/src/native_tools.rs,wic_codec.rs).npm run build(tsc && vite build): 0 errors (clean production bundle).npm run test(vitest run): 85 test files / 568 tests passing, 0 failures (includingphase6WebviewPurgeAudit.test.tsenforcing zero legacy JS raster engines, zero dead pixel-IPC commands, zero full-res<canvas>backing stores, and strictink-enginedecoupling).- Hard Decoupling Invariant Preserved:
crates/ink-engine/Cargo.tomlhas zero dependencies ontauri,wry,tao, orwebview2-com.