Skip to content

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

8.0 KB
Raw Blame
//! `ink-engine`: Decoupled native Windows `wgpu` (DX12) digital painting engine.
//!
//! Strictly free of `tauri`, `wry`, `tao`, or WebView2 dependencies. Accepts raw GPU
//! surface targets (`IDCompositionVisual` or headless), lock-free SPSC `rtrb` input rings,
//! and typed [`EngineCommand`]s.

pub mod brush;
pub mod camera;
pub mod clock;
pub mod collab;
pub mod compositor;
pub mod document;
pub mod engine;
pub mod gpu;
pub mod history;
pub mod hit_test;
pub mod io;
pub mod memory;
pub mod natural_paint;
pub mod ring;
pub mod selection;
pub mod shaders;
pub mod stroke;
pub mod tiles;
pub mod tools;
pub mod types;

#[cfg(test)]
mod compositor_tests;
#[cfg(test)]
mod phase2_tests;
#[cfg(test)]
mod phase4_tests;
#[cfg(test)]
mod phase5_tests;
#[cfg(test)]
mod phase6_tests;
#[cfg(test)]
mod regression_dx12_tests;
#[cfg(test)]
mod brush_parity_dx12_tests;
#[cfg(test)]
mod audit_regression_tests;
#[cfg(test)]
mod brush_feel_tests;

pub use camera::{
    clamp_zoom, compute_smooth_rotation_delta, doc_to_viewport_css, viewport_css_to_doc,
    NativeCameraNavigator, MAX_ZOOM, MIN_ZOOM,
};
pub use compositor::{
    CmykStandard, CompositorDisplayConfig, DocBounds, FlattenOptions, OnionSkinFrame, ScissorRect,
    SoftProofConfig, StackCacheStats, WgpuCompositor,
};
pub use document::{
    BlendMode, CanvasColorMode, CanvasDimensions, ComicFrame, Document, DocumentId,
    DocumentManager, DocumentMetaSnapshot, ExpressionColor, LayerColorLabel, LayerId, LayerNode,
    LayerNodeMeta, LayerPropsPatch, LayerType, ToneDensityType, ToneDotShape,
};
pub use engine::{EngineConfig, EngineHandle, EnginePerfSnapshot};
pub use history::{
    AppliedHistoryChange, CanvasResizeDelta, HistoryEntry, HistoryItemMeta, HistoryStack,
    HistoryStateSnapshot, LayerTreeMutation, SelectiveUndoOutcome,
};
pub use hit_test::{HitTestState, SharedHitTest};
pub use memory::{
    EvictionContext, FileScratchBackend, GpuPoolStats, GpuTilePool, InMemoryScratchBackend,
    MemoryBudgetConfig, MemoryStats, ScratchBackend, ScratchTileWrite, TieredMemoryManager,
    ViewportFrustum,
};
pub use ring::{InputProducers, NavRingProducer, TabletRingProducer, WakeSignal};
pub use selection::{
    FloatingSelection, GpuSelectionOverlay, SelectionClipboard, SelectionCombineMode,
    SelectionFillResult, SelectionMetaSnapshot, SelectionOpResult, SparseSelectionMask,
    WandReferMode,
};
pub use brush::{
    BristleProfilePreset, BristleSettings, BrushDynamics, BrushRenderMode, BrushTextureKind,
    CspAngleDynamicsMode, CspBlendTipsMode, CspBrushCombineMode, CspDualBrushConfig,
    CspPaperTextureMode, CspSensorConfig, CspSpraySettings, CspSubTipOrder, CspTipFlipMode,
    DualBrushCompositeMode, GpuBrushDab, GpuBrushEngine, GrainMappingMode, ImpastoSettings,
    NativeBrushConfig, NaturalMixingMode, NaturalPaintSettings, RibbonRepeatMode, StrokeDabEmitter,
};
pub use stroke::{
    CommittedStrokePoint, CompiledCurveLut, CspTaperSettings, DabInstance, GlobalPressureCurve,
    InputStabilizer, NativeStrokePipeline, PerspectiveMode, PerspectiveRulerConfig,
    SplineGenerator, StraightRulerConfig, StrokeDabGenerator, StrokePoint, TaperEngine,
};
pub use tiles::{
    CowTileDelta, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKey, TileKind,
    TileStorage, TILE_PIXELS, TILE_SIZE,
};
pub use types::{
    BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, EngineEvent,
    InteractionPolicy, NativeInputSample, NativeNavEvent, NativeNavGesture, NativeToolKind,
    ScratchpadStrokeInput, ScratchpadStrokePoint, SurfaceTarget, ThumbnailUpdate, UiRect,
    ViewportRect, WheelNavMode,
};

/// Serializes DX12 GPU test device allocations across all test modules so default parallel
/// `cargo test --workspace` never oversubscribes integrated GPU VRAM (e.g. Intel Iris Xe).
#[cfg(test)]
pub(crate) fn lock_dx12_test() -> std::sync::MutexGuard<'static, ()> {
    static DX12_TEST_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
        std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
    DX12_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_headless_dx12_engine_vertical_slice_stroke_and_camera() {
        let _dx12_guard = crate::lock_dx12_test();
        let (handle, mut producers) = match EngineHandle::spawn(
            SurfaceTarget::Headless {
                width: 320,
                height: 240,
            },
            EngineConfig {
                doc_width: 512,
                doc_height: 512,
                show_checkerboard: true,
                matte_color: [0.086, 0.086, 0.086, 1.0],
                ..Default::default()
            },
        ) {
            Ok(pair) => pair,
            Err(err) => {
                // Allow headless CI environments without a DX12 adapter to report gracefully
                eprintln!("Skipping DX12 headless test (no adapter available): {err}");
                return;
            }
        };

        handle.send_command(EngineCommand::SetVisible(true));
        handle.send_command(EngineCommand::SetViewport(ViewportRect {
            x_px: 0,
            y_px: 0,
            width_px: 320,
            height_px: 240,
            dpr: 1.0,
        }));
        handle.send_command(EngineCommand::SetCamera(CameraState {
            pan_x: 160.0,
            pan_y: 120.0,
            zoom: 0.5,
            rotation: 0.0,
            flip_x: false,
            flip_y: false,
        }));

        let now = clock::now_ms();
        // Push a complete stylus stroke through the lock-free SPSC WinTab ring
        assert_eq!(
            producers.wintab.push_batch(&[
                NativeInputSample {
                    phys_x: 120.0,
                    phys_y: 100.0,
                    pressure: 0.4,
                    tilt_x: 0.0,
                    tilt_y: 0.0,
                    twist: 0.0,
                    timestamp_ms: now,
                    buttons: 1,
                    phase: 1,
                    backend: 1,
                },
                NativeInputSample {
                    phys_x: 200.0,
                    phys_y: 140.0,
                    pressure: 0.9,
                    tilt_x: 0.0,
                    tilt_y: 0.0,
                    twist: 0.0,
                    timestamp_ms: now + 4.0,
                    buttons: 1,
                    phase: 2,
                    backend: 1,
                },
                NativeInputSample {
                    phys_x: 200.0,
                    phys_y: 140.0,
                    pressure: 0.0,
                    tilt_x: 0.0,
                    tilt_y: 0.0,
                    twist: 0.0,
                    timestamp_ms: now + 8.0,
                    buttons: 0,
                    phase: 3,
                    backend: 1,
                },
            ]),
            3
        );

        // Push a native wheel zoom event through the SPSC nav ring
        assert!(producers.nav.push(NativeNavEvent::Wheel {
            phys_x: 160.0,
            phys_y: 120.0,
            delta_x: 0.0,
            delta_y: -120.0,
            ctrl_held: false,
            shift_held: false,
            timestamp_ms: now + 10.0,
        }));

        // Wait for at least one rendered frame and camera sync event
        let mut saw_camera_zoom = false;
        let deadline = std::time::Instant::now() + Duration::from_secs(3);
        while std::time::Instant::now() < deadline {
            if let Ok(EngineEvent::CameraChanged { camera, .. }) =
                handle.events().recv_timeout(Duration::from_millis(50))
            {
                if camera.zoom > 0.55 {
                    saw_camera_zoom = true;
                }
            }
            let d = handle.diagnostics();
            if d.total_frames_rendered >= 1 && saw_camera_zoom {
                break;
            }
        }

        let diag = handle.diagnostics();
        assert!(diag.ready);
        assert_eq!(diag.backend, "DX12");
        assert!(saw_camera_zoom, "native wheel zoom should emit CameraChanged");
        handle.shutdown();
        assert!(!handle.is_running());
    }
}