Skip to content

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

23.0 KB
Raw Blame
//! Strongly-typed engine commands, events, input samples, and rendering configs.
//! Completely decoupled from Tauri, wry, or WebView2.

use serde::{Deserialize, Serialize};
use std::ffi::c_void;
use std::sync::Arc;

/// Physical client-pixel bounds of the canvas viewport cutout inside the host window.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewportRect {
    /// Left offset in physical pixels relative to the host window's client origin.
    pub x_px: i32,
    /// Top offset in physical pixels relative to the host window's client origin.
    pub y_px: i32,
    /// Physical pixel width of the swapchain surface.
    pub width_px: u32,
    /// Physical pixel height of the swapchain surface.
    pub height_px: u32,
    /// Effective device pixel ratio (`physical_px / viewport_css_px`), including WebView zoom.
    pub dpr: f32,
}

impl Default for ViewportRect {
    fn default() -> Self {
        Self {
            x_px: 0,
            y_px: 0,
            width_px: 0,
            height_px: 0,
            dpr: 1.0,
        }
    }
}

impl ViewportRect {
    #[inline]
    pub fn safe_dpr(&self) -> f32 {
        if self.dpr.is_finite() && self.dpr > 0.05 {
            self.dpr
        } else {
            1.0
        }
    }

    #[inline]
    pub fn css_width(&self) -> f32 {
        self.width_px as f32 / self.safe_dpr()
    }

    #[inline]
    pub fn css_height(&self) -> f32 {
        self.height_px as f32 / self.safe_dpr()
    }

    #[inline]
    pub fn contains_phys(&self, phys_x: f32, phys_y: f32) -> bool {
        if self.width_px == 0 || self.height_px == 0 {
            return false;
        }
        let x0 = self.x_px as f32;
        let y0 = self.y_px as f32;
        let x1 = x0 + self.width_px as f32;
        let y1 = y0 + self.height_px as f32;
        phys_x >= x0 && phys_x < x1 && phys_y >= y0 && phys_y < y1
    }

    /// Converts window-client physical pixels to viewport-local CSS pixels.
    #[inline]
    pub fn phys_to_local_css(&self, phys_x: f32, phys_y: f32) -> (f32, f32) {
        let dpr = self.safe_dpr();
        (
            (phys_x - self.x_px as f32) / dpr,
            (phys_y - self.y_px as f32) / dpr,
        )
    }

    /// Converts window-client physical pixels to swapchain-local physical pixels.
    #[inline]
    pub fn phys_to_local_phys(&self, phys_x: f32, phys_y: f32) -> (f32, f32) {
        (phys_x - self.x_px as f32, phys_y - self.y_px as f32)
    }
}

/// An occluded UI rectangle in physical window client pixels (modals, popovers,
/// context menus, FloatingBrushPill, floating dock panels, etc.).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UiRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl UiRect {
    #[inline]
    pub fn contains(&self, px: f32, py: f32) -> bool {
        self.width > 0.0
            && self.height > 0.0
            && px >= self.x
            && px <= self.x + self.width
            && py >= self.y
            && py <= self.y + self.height
    }
}

/// 2D affine canvas camera transform matching `CameraTransformState` and
/// `formatArtboardTransform` in `src/components/canvasArea/types.ts` pixel-for-pixel.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraState {
    pub pan_x: f32,
    pub pan_y: f32,
    pub zoom: f32,
    pub rotation: f32,
    pub flip_x: bool,
    pub flip_y: bool,
}

impl Default for CameraState {
    fn default() -> Self {
        Self {
            pan_x: 0.0,
            pan_y: 0.0,
            zoom: 1.0,
            rotation: 0.0,
            flip_x: false,
            flip_y: false,
        }
    }
}

/// Active tool classification used to determine whether native GPU brush capture fires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NativeToolKind {
    #[default]
    Brush,
    Decoration,
    Eraser,
    SelectPen,
    SelectEraser,
    Liquify,
    Retouch,
    Other,
}

impl NativeToolKind {
    #[inline]
    pub fn is_native_stroke_tool(self) -> bool {
        matches!(
            self,
            Self::Brush | Self::Decoration | Self::Eraser | Self::SelectPen | Self::SelectEraser
        )
    }

    #[inline]
    pub fn is_selection_brush_tool(self) -> bool {
        matches!(self, Self::SelectPen | Self::SelectEraser)
    }
}

/// GPU brush cursor visual configuration.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CursorConfig {
    /// Active brush diameter in document pixels.
    pub size: f32,
    /// Brush tip thickness ratio (0.05..=1.0).
    pub thickness_ratio: f32,
    /// Whether thickness compresses vertically instead of horizontally.
    pub thickness_vertical: bool,
    /// Brush tip angle in degrees (canvas-space).
    pub tip_angle_deg: f32,
    /// Square brush outline instead of circular/elliptical.
    pub is_square: bool,
    /// Whether the native GPU brush cursor ring should be shown when hovering canvas.
    pub visible: bool,
}

impl Default for CursorConfig {
    fn default() -> Self {
        Self {
            size: 16.0,
            thickness_ratio: 1.0,
            thickness_vertical: false,
            tip_angle_deg: 0.0,
            is_square: false,
            visible: true,
        }
    }
}

/// Minimal Phase 1 PoC GPU dab brush parameters.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BrushParams {
    /// Base brush diameter in document pixels.
    pub size: f32,
    /// Brush opacity (0.01..=1.0).
    pub opacity: f32,
    /// Edge hardness (0.0..=1.0, where 1.0 is crisp and 0.0 is soft airbrush falloff).
    pub hardness: f32,
    /// Dab spacing fraction of diameter (0.03..=1.0).
    pub spacing: f32,
    /// Minimum size ratio under zero pressure (0.0..=1.0).
    pub min_size_ratio: f32,
    /// Whether pressure modulates brush diameter.
    pub use_pressure_size: bool,
    /// Whether pressure modulates dab opacity.
    pub use_pressure_opacity: bool,
    /// Primary sRGB color `[r, g, b, a]` in `0.0..=1.0`.
    pub color: [f32; 4],
    /// True for destination-out erasing, false for normal premultiplied painting.
    pub is_eraser: bool,
}

impl Default for BrushParams {
    fn default() -> Self {
        Self {
            size: 16.0,
            opacity: 1.0,
            hardness: 0.9,
            spacing: 0.10,
            min_size_ratio: 0.15,
            use_pressure_size: true,
            use_pressure_opacity: false,
            color: [0.08, 0.08, 0.10, 1.0],
            is_eraser: false,
        }
    }
}

/// Mouse wheel action configured by user preferences.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WheelNavMode {
    #[default]
    Zoom,
    Scroll,
    BrushSize,
}

/// Native modifier & tool gating flags mirrored from UI/OS state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InteractionPolicy {
    pub active_tool: NativeToolKind,
    pub native_stroke_enabled: bool,
    pub wheel_mode: WheelNavMode,
    pub is_webtoon_mode: bool,
    pub text_input_focused: bool,
    pub workspace_interacting: bool,
    pub modal_open: bool,
}

impl Default for InteractionPolicy {
    fn default() -> Self {
        Self {
            active_tool: NativeToolKind::Brush,
            native_stroke_enabled: true,
            wheel_mode: WheelNavMode::Zoom,
            is_webtoon_mode: false,
            text_input_focused: false,
            workspace_interacting: false,
            modal_open: false,
        }
    }
}

/// High-frequency tablet/pen sample pushed directly into the lock-free `rtrb` ring buffer
/// from `src-tauri/src/tablet_input.rs` (zero JSON, zero IPC).
#[derive(Debug, Clone, Copy)]
pub struct NativeInputSample {
    /// Sub-pixel physical X coordinate relative to the top-level window client origin.
    pub phys_x: f32,
    /// Sub-pixel physical Y coordinate relative to the top-level window client origin.
    pub phys_y: f32,
    /// Normalized pen pressure in `0.0..=1.0`.
    pub pressure: f32,
    /// Pen tilt X in degrees (`-90..=90`).
    pub tilt_x: f32,
    /// Pen tilt Y in degrees (`-90..=90`).
    pub tilt_y: f32,
    /// Barrel twist in degrees (`0..=360`).
    pub twist: f32,
    /// QPC monotonic timestamp in milliseconds (same domain as `clock::now_ms()`).
    pub timestamp_ms: f64,
    /// Button bitmask: bit 0=tip, 1=barrel1, 2=barrel2, 3=eraser/inverted.
    pub buttons: u16,
    /// Phase: 0=hover, 1=down, 2=move/drag, 3=up, 4=leave.
    pub phase: u8,
    /// Backend: 1=wintab, 2=windows-ink, 3=mouse.
    pub backend: u8,
}

/// Active native camera navigation gesture kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeNavGesture {
    Pan,
    Rotate,
    ZoomDrag,
}

/// High-frequency native mouse/wheel navigation and hover events pushed into a lock-free
/// SPSC ring buffer directly from the Win32 subclass proc.
#[derive(Debug, Clone, Copy)]
pub enum NativeNavEvent {
    Hover {
        phys_x: f32,
        phys_y: f32,
        timestamp_ms: f64,
    },
    HoverLeave,
    GestureStart {
        gesture: NativeNavGesture,
        phys_x: f32,
        phys_y: f32,
        timestamp_ms: f64,
    },
    GestureMove {
        phys_x: f32,
        phys_y: f32,
        snap_15_deg: bool,
        timestamp_ms: f64,
    },
    GestureEnd {
        timestamp_ms: f64,
    },
    Wheel {
        phys_x: f32,
        phys_y: f32,
        delta_x: f32,
        delta_y: f32,
        ctrl_held: bool,
        shift_held: bool,
        timestamp_ms: f64,
    },
    MouseDraw {
        phys_x: f32,
        phys_y: f32,
        phase: u8, // 1=down, 2=move, 3=up
        shift_held: bool,
        timestamp_ms: f64,
    },
}

/// Recorded stylus sample point for Brush Studio live scratchpad replay.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScratchpadStrokePoint {
    pub x: f32,
    pub y: f32,
    pub pressure: f32,
    #[serde(default)]
    pub tilt_x: f32,
    #[serde(default)]
    pub tilt_y: f32,
    #[serde(default)]
    pub twist: f32,
    #[serde(default)]
    pub timestamp_ms: f64,
}

/// Recorded Brush Studio scratchpad stroke re-rendered live when brush parameters change.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScratchpadStrokeInput {
    pub points: Vec<ScratchpadStrokePoint>,
    pub color: [f32; 3],
    #[serde(default)]
    pub seed: u64,
}

/// Reply channel for offscreen GPU RGBA8 image renders (`(width, height, rgba8)`).
pub type Rgba8ImageReply = crossbeam_channel::Sender<Result<(u32, u32, Vec<u8>), String>>;

/// Typed control commands sent from the host UI/window layer into `ink-engine`.
#[derive(Debug, Clone)]
pub enum EngineCommand {
    /// Updates the physical pixel cutout rect and effective DPI of the canvas viewport.
    SetViewport(ViewportRect),
    /// Replaces the list of occluded UI rects in physical client pixels.
    SetOccludedRects(Vec<UiRect>),
    /// Updates document pixel dimensions and allocates/clears the GPU canvas surface if changed.
    SetDocumentSize {
        width: u32,
        height: u32,
        show_checkerboard: bool,
    },
    /// Sets whether the artboard checkerboard transparency grid is shown (vs solid white paper).
    SetShowCheckerboard(bool),
    /// Sets the canvas matte background sRGB color `[r, g, b, a]` synced from the active UI theme.
    SetMatteColor([f32; 4]),
    /// Updates the camera transform from programmatic UI actions (Navigator, buttons, resize, reset).
    SetCamera(CameraState),
    /// Updates the native GPU brush cursor configuration.
    SetCursorConfig(CursorConfig),
    /// Updates the Phase 1 PoC GPU dab brush parameters.
    SetBrushParams(BrushParams),
    /// Updates the full Phase 4/5 CSP-compatible native GPU brush configuration (only sent on change).
    SetFullBrushConfig(Box<crate::brush::NativeBrushConfig>),
    /// Cleans the persistent dirty GPU brush pigment reservoir (`None` = clean all presets).
    CleanDirtyBrush(Option<String>),
    /// Toggles whether native brush strokes paint onto the active layer's 8-bit mask plane.
    SetMaskMode(bool),
    /// Renders an authentic GPU S-curve brush preview card on the DX12 render thread.
    RenderBrushPreview {
        brush: Box<crate::brush::NativeBrushConfig>,
        width: u32,
        height: u32,
        reply: Rgba8ImageReply,
    },
    /// Renders Brush Studio live scratchpad strokes on DX12 with the live-edited brush config.
    RenderScratchpadPreview {
        brush: Box<crate::brush::NativeBrushConfig>,
        strokes: Vec<ScratchpadStrokeInput>,
        width: u32,
        height: u32,
        reply: Rgba8ImageReply,
    },
    /// Updates global stylus pressure curve (`AppSettings.pressureCurve`).
    SetGlobalPressureCurve(crate::stroke::GlobalPressureCurve),
    /// Updates active straight ruler & perspective ruler snapping configurations.
    SetRulers {
        straight: Option<crate::stroke::StraightRulerConfig>,
        perspective: Option<crate::stroke::PerspectiveRulerConfig>,
    },
    /// Content-hashed one-time binary upload for `.sut` / `.inkb` / custom brush tips & paper textures.
    UploadBrushTexture {
        hash: String,
        kind: crate::brush::BrushTextureKind,
        is_png: bool,
        width: u32,
        height: u32,
        data: Vec<u8>,
    },
    /// Updates tool & interaction policy flags.
    SetInteractionPolicy(InteractionPolicy),
    /// Shows or hides rendering (e.g. hidden on Welcome Home screen or minimized window).
    SetVisible(bool),
    /// Clears the active layer or GPU canvas texture to transparent.
    ClearCanvas,
    /// Updates full viewport display configuration (soft-proof, value check, onion skins,
    /// animation cel visibility overrides, layer stack caching, matte color, checkerboard).
    SetDisplayConfig(crate::compositor::CompositorDisplayConfig),
    /// Explicitly invalidates the 3-slice baked layer stack cache & styled-layer cache.
    InvalidateCompositorCache,
    /// Executes a headless GPU document flatten (`render_document_flattened`) on the DX12
    /// render thread using the already-warm `GpuTilePool`, returning `(w, h, rgba8)` via `reply`.
    RenderDocumentFlattened {
        doc_id: Option<String>,
        options: crate::compositor::FlattenOptions,
        reply: Rgba8ImageReply,
    },
    /// Executes a GPU-accurate single-layer thumbnail render on the DX12 render thread.
    RenderLayerThumbnail {
        doc_id: Option<String>,
        layer_id: String,
        max_dim: u32,
        reply: Rgba8ImageReply,
    },
    /// Synchronizes the active Rust `Document` (dirty tiles, GPU mipmaps, and composited texture)
    /// into the DX12 `GpuRenderer`.
    SyncActiveDocument,
    /// Updates the L1 GPU VRAM tile atlas budget in bytes.
    SetVramBudget(u64),
    /// Flushes all resident tiles from the L1 GPU VRAM tile atlas pool.
    FlushGpuPool,
    /// Notifies the engine that the host window was resized, DPI changed, or restored.
    NotifySurfaceInvalidated,
    // --- Phase 6: GPU Liquify, 5-Mode Transform/Warp, Live Tool/Filter Previews & Collab Drafts ---
    LiquifyBegin {
        multi_layer: bool,
        layer_ids: Option<Vec<String>>,
        reply: crossbeam_channel::Sender<Result<Vec<String>, String>>,
    },
    LiquifyStep {
        step: crate::tools::LiquifyStepParams,
        reply: crossbeam_channel::Sender<Result<crate::tiles::RectI32, String>>,
    },
    LiquifyCommit {
        reply: crossbeam_channel::Sender<Result<(Vec<String>, crate::tiles::RectI32), String>>,
    },
    LiquifyCancel,
    TransformBegin {
        mode: crate::tools::TransformMode,
        layer_ids: Option<Vec<String>>,
        reply: crossbeam_channel::Sender<Result<crate::tools::TransformSessionSnapshot, String>>,
    },
    TransformUpdate {
        payload: crate::tools::TransformUpdatePayload,
        reply: crossbeam_channel::Sender<Result<crate::tools::TransformSessionSnapshot, String>>,
    },
    TransformSwitchMode {
        next_mode: crate::tools::TransformMode,
        reply: crossbeam_channel::Sender<Result<crate::tools::TransformSessionSnapshot, String>>,
    },
    TransformCommit {
        reply: crossbeam_channel::Sender<Result<crate::tools::TransformCommitResult, String>>,
    },
    TransformCancel,
    SetToolPreviewRgba8 {
        rect: crate::tiles::RectI32,
        rgba: Vec<u8>,
        opacity: f32,
        replaced_layer_id: Option<String>,
    },
    ClearToolPreview,
    RemoteStrokeStart(crate::collab::RemoteStrokeStartParams),
    RemoteStrokeChunk {
        peer_id: String,
        stroke_id: String,
        points: Vec<crate::collab::RemoteStrokePoint>,
    },
    RemoteStrokeFinish {
        peer_id: String,
        stroke_id: String,
        expected_tiles: u32,
    },
    RemoteStrokeDispose {
        peer_id: String,
        stroke_id: String,
    },
    RemotePeerDispose {
        peer_id: String,
    },
    RemoteNotifyTileDelta {
        layer_id: String,
    },
    /// Toggles whether `EngineEvent::StrokeCommitted` includes the full `points` array
    /// (enabled only when multiplayer collaboration is connected, avoiding per-stroke cloning &
    /// JSON serialization overhead during solo sketching).
    SetCollabPointsEnabled(bool),
    /// Requests a graceful shutdown of the engine thread.
    Shutdown,
}

/// Live GPU and latency telemetry emitted periodically to the host UI.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EngineDiagnostics {
    pub ready: bool,
    pub adapter_name: String,
    pub backend: String,
    pub present_mode: String,
    pub fps: f32,
    pub frame_time_ms: f32,
    pub input_to_present_ms: f32,
    pub swapchain_width: u32,
    pub swapchain_height: u32,
    pub doc_width: u32,
    pub doc_height: u32,
    pub active_stroke_dabs: u64,
    pub total_frames_rendered: u64,
    pub device_lost_recoveries: u32,
    pub max_frame_latency: u32,
    pub composition_mode: String,
    #[serde(default)]
    pub gpu_vram_used_bytes: u64,
    #[serde(default)]
    pub gpu_vram_budget_bytes: u64,
    #[serde(default)]
    pub gpu_tiles_resident: u32,
    #[serde(default)]
    pub gpu_tiles_capacity: u32,
    #[serde(default)]
    pub stack_cache_hits: u64,
    #[serde(default)]
    pub stack_cache_rebuilds: u64,
    #[serde(default)]
    pub is_idle: bool,
}

impl Default for EngineDiagnostics {
    fn default() -> Self {
        Self {
            ready: false,
            adapter_name: "Initializing...".to_string(),
            backend: "DX12".to_string(),
            present_mode: "Fifo".to_string(),
            fps: 0.0,
            frame_time_ms: 0.0,
            input_to_present_ms: 0.0,
            swapchain_width: 0,
            swapchain_height: 0,
            doc_width: 1920,
            doc_height: 1080,
            active_stroke_dabs: 0,
            total_frames_rendered: 0,
            device_lost_recoveries: 0,
            max_frame_latency: 1,
            composition_mode: "DirectComposition".to_string(),
            gpu_vram_used_bytes: 0,
            gpu_vram_budget_bytes: 0,
            gpu_tiles_resident: 0,
            gpu_tiles_capacity: 0,
            stack_cache_hits: 0,
            stack_cache_rebuilds: 0,
            is_idle: true,
        }
    }
}

/// Compact 64x64 PNG data URL update for a single layer and/or its non-destructive mask.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThumbnailUpdate {
    pub layer_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mask_thumbnail_url: Option<String>,
}

/// Lightweight events emitted from `ink-engine` back to the host (throttled outside hot strokes).
#[derive(Debug, Clone)]
pub enum EngineEvent {
    /// Emitted when native Rust pan/zoom/rotate updates the camera.
    /// `commit` is true when a drag/wheel gesture completes so React can commit UI state.
    CameraChanged {
        camera: CameraState,
        commit: bool,
    },
    /// Periodic (~4 Hz) GPU & latency diagnostics snapshot.
    Diagnostics(EngineDiagnostics),
    /// Throttled (~30 Hz) pointer coordinate & pressure telemetry for StatusBar.
    PointerStat {
        doc_x: Option<i32>,
        doc_y: Option<i32>,
        pressure: f32,
    },
    /// Emitted whenever Rust-side undo/redo history mutates (e.g. native stroke commit).
    HistoryChanged {
        doc_id: String,
        history: crate::history::HistoryStateSnapshot,
    },
    /// Emitted asynchronously when 64x64 layer/mask thumbnails finish rendering.
    ThumbnailsUpdated {
        doc_id: String,
        updates: Vec<ThumbnailUpdate>,
    },
    /// Emitted when a native DX12 brush stroke commits its CoW tile deltas to the active layer.
    StrokeCommitted {
        doc_id: String,
        layer_id: String,
        entry_id: String,
        dirty_rect: crate::tiles::RectI32,
        history: crate::history::HistoryStateSnapshot,
        points: Vec<crate::stroke::CommittedStrokePoint>,
    },
    /// Emitted whenever a native selection mask changes (e.g. Select Pen / Select Eraser commit).
    SelectionChanged {
        doc_id: String,
        selection: crate::selection::SelectionMetaSnapshot,
    },
    /// Emitted after OS DPI/display changes or window restore from minimize so the host UI
    /// re-measures physical viewport cutout bounds and occlusion rects even if CSS size is unchanged.
    ViewportInvalidated,
}

/// Raw GPU surface target accepted by `ink-engine` without depending on Tauri/wry/WinUI.
#[derive(Clone)]
pub enum SurfaceTarget {
    /// Windows DirectComposition `IDCompositionVisual` raw COM pointer (`*mut c_void`).
    ///
    /// # Safety Contract
    /// - `visual_ptr` must be a valid, AddRef'd or host-kept `IDCompositionVisual` pointer
    ///   that outlives the engine thread (i.e. remains valid until `EngineHandle::shutdown()` joins).
    /// - `on_configured` is invoked immediately after `surface.configure(...)` so the host
    ///   commits `IDCompositionDevice::Commit()` after `wgpu-hal` calls `visual.SetContent(swapchain)`.
    CompositionVisual {
        visual_ptr: usize,
        on_configured: Arc<dyn Fn() + Send + Sync>,
    },
    /// Headless offscreen target for automated GPU/unit tests without a window.
    Headless { width: u32, height: u32 },
}

impl SurfaceTarget {
    /// Helper to construct a `CompositionVisual` target from a raw `*mut c_void`.
    ///
    /// # Safety
    /// Caller must ensure `visual` is a valid non-null `IDCompositionVisual` COM pointer
    /// that outlives the engine handle.
    pub unsafe fn from_composition_visual(
        visual: *mut c_void,
        on_configured: Arc<dyn Fn() + Send + Sync>,
    ) -> Self {
        debug_assert!(!visual.is_null(), "IDCompositionVisual pointer cannot be null");
        Self::CompositionVisual {
            visual_ptr: visual as usize,
            on_configured,
        }
    }
}