Skip to content

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

39.4 KB
Raw Blame
//! GPU `Rgba16Float` render target pool, scissored region copies, per-layer `R8Unorm`
//! document-level mask cache, and per-layer styled-surface LRU cache.

use super::stack_cache::ScissorRect;
use crate::document::LayerNode;
use std::collections::{HashMap, HashSet};

/// Single `Rgba16Float` offscreen GPU render target.
pub struct SurfaceRgba16F {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub width: u32,
    pub height: u32,
}

impl SurfaceRgba16F {
    pub fn new(device: &wgpu::Device, label: &str, width: u32, height: u32) -> Self {
        let w = width.max(1);
        let h = height.max(1);
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        Self {
            texture,
            view,
            width: w,
            height: h,
        }
    }

    /// Resizes the texture only when dimensions actually differ. Returns `true` if recreated.
    pub fn ensure_size(
        &mut self,
        device: &wgpu::Device,
        label: &str,
        width: u32,
        height: u32,
    ) -> bool {
        let w = width.max(1);
        let h = height.max(1);
        if self.width == w && self.height == h {
            return false;
        }
        *self = Self::new(device, label, w, h);
        true
    }

    /// Copies a top-left physical-pixel [`ScissorRect`] region from `self` into `dst` on the GPU.
    pub fn copy_region_to(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        dst: &SurfaceRgba16F,
        scissor: ScissorRect,
    ) {
        let max_w = self.width.min(dst.width);
        let max_h = self.height.min(dst.height);
        if scissor.x >= max_w || scissor.y >= max_h || scissor.width == 0 || scissor.height == 0 {
            return;
        }
        let copy_w = scissor.width.min(max_w - scissor.x);
        let copy_h = scissor.height.min(max_h - scissor.y);
        if copy_w == 0 || copy_h == 0 {
            return;
        }
        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &self.texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: scissor.x,
                    y: scissor.y,
                    z: 0,
                },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: &dst.texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: scissor.x,
                    y: scissor.y,
                    z: 0,
                },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: copy_w,
                height: copy_h,
                depth_or_array_layers: 1,
            },
        );
    }
}

/// Single `Rgba8Unorm` offscreen GPU render target for 4 B/px export/thumbnail readback.
pub struct SurfaceRgba8 {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub width: u32,
    pub height: u32,
}

impl SurfaceRgba8 {
    pub fn new(device: &wgpu::Device, label: &str, width: u32, height: u32) -> Self {
        let w = width.max(1);
        let h = height.max(1);
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        Self {
            texture,
            view,
            width: w,
            height: h,
        }
    }

    /// Resizes the texture only when dimensions actually differ. Returns `true` if recreated.
    pub fn ensure_size(
        &mut self,
        device: &wgpu::Device,
        label: &str,
        width: u32,
        height: u32,
    ) -> bool {
        let w = width.max(1);
        let h = height.max(1);
        if self.width == w && self.height == h {
            return false;
        }
        *self = Self::new(device, label, w, h);
        true
    }
}

/// Single `R16Float` offscreen GPU render target for live impasto 3D heightfield projection.
pub struct SurfaceR16F {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub width: u32,
    pub height: u32,
}

impl SurfaceR16F {
    pub fn new(device: &wgpu::Device, label: &str, width: u32, height: u32) -> Self {
        let w = width.max(1);
        let h = height.max(1);
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R16Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        Self {
            texture,
            view,
            width: w,
            height: h,
        }
    }

    pub fn ensure_size(
        &mut self,
        device: &wgpu::Device,
        label: &str,
        width: u32,
        height: u32,
    ) -> bool {
        let w = width.max(1);
        let h = height.max(1);
        if self.width == w && self.height == h {
            return false;
        }
        *self = Self::new(device, label, w, h);
        true
    }
}

/// Viewport-resolution GPU-projected `R8Unorm` mask texture cache (zero CPU pixel loops,
/// razor-sharp at 4K–8K!).
///
/// Keyed strictly on `grid.mask_version` (NEVER `grid.layer_version`) so raster strokes on a
/// masked layer trigger ZERO mask rebuilds. Used by:
/// - Masked folders & frame-folders (`blit.rs`)
/// - Masked adjustment layers (`adjustment.rs`)
/// - Masked active layer during live stroke merge (`live_dab.rs`)
/// - Masked raster layers at zoomed-out LOD 1..3 (`layer_tile.rs`)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DocMaskSig {
    pub doc_w: u32,
    pub doc_h: u32,
    pub vp_w: u32,
    pub vp_h: u32,
    pub camera_sig: u64,
    pub mask_version: u64,
    pub mask_default: u8,
    pub mask_tile_count: usize,
    pub force_nearest: bool,
}

impl DocMaskSig {
    #[inline]
    #[allow(clippy::too_many_arguments)]
    pub fn for_layer(
        layer: &LayerNode,
        doc_w: u32,
        doc_h: u32,
        vp_w: u32,
        vp_h: u32,
        camera_sig: u64,
        force_nearest: bool,
    ) -> Self {
        Self {
            doc_w,
            doc_h,
            vp_w: vp_w.max(1),
            vp_h: vp_h.max(1),
            camera_sig,
            mask_version: layer.grid.mask_version,
            mask_default: layer.grid.mask_default_value,
            mask_tile_count: layer.grid.mask_tiles.len(),
            force_nearest,
        }
    }
}

static NEXT_VIEW_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

struct CachedDocMask {
    _texture: wgpu::Texture,
    view: wgpu::TextureView,
    view_id: u64,
    width: u32,
    height: u32,
    sig: DocMaskSig,
}

#[derive(Default)]
pub struct DocMaskCache {
    entries: HashMap<String, CachedDocMask>,
    pub rebuilds: u64,
}

impl DocMaskCache {
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn needs_update(&self, layer_id: &str, sig: DocMaskSig) -> bool {
        self.entries
            .get(layer_id)
            .map(|e| e.sig != sig || e.width != sig.vp_w || e.height != sig.vp_h)
            .unwrap_or(true)
    }

    /// Allocates or resizes the viewport-resolution `R8Unorm` render target for `layer_id`,
    /// records `sig`, increments `self.rebuilds`, and returns its `TextureView` ready for
    /// GPU sparse-tile projection.
    pub fn prepare_render_target(
        &mut self,
        device: &wgpu::Device,
        layer_id: &str,
        sig: DocMaskSig,
    ) -> &wgpu::TextureView {
        let tex_w = sig.vp_w.max(1);
        let tex_h = sig.vp_h.max(1);
        let recreate = self
            .entries
            .get(layer_id)
            .map(|e| e.width != tex_w || e.height != tex_h)
            .unwrap_or(true);

        if recreate {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("ink-vp-doc-mask-r8"),
                size: wgpu::Extent3d {
                    width: tex_w,
                    height: tex_h,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::R8Unorm,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.entries.insert(
                layer_id.to_string(),
                CachedDocMask {
                    _texture: texture,
                    view,
                    view_id: NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
                    width: tex_w,
                    height: tex_h,
                    sig,
                },
            );
        } else if let Some(entry) = self.entries.get_mut(layer_id) {
            entry.sig = sig;
        }
        self.rebuilds = self.rebuilds.saturating_add(1);
        &self.entries.get(layer_id).expect("mask target prepared").view
    }

    pub fn get_cached_view(&self, layer_id: &str) -> Option<&wgpu::TextureView> {
        self.entries.get(layer_id).map(|e| &e.view)
    }

    pub fn get_cached_view_with_id(&self, layer_id: &str) -> Option<(&wgpu::TextureView, u64)> {
        self.entries.get(layer_id).map(|e| (&e.view, e.view_id))
    }

    pub fn retain_layers(&mut self, valid_ids: &HashSet<&str>) {
        self.entries.retain(|k, _| valid_ids.contains(k.as_str()));
    }

    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

/// Per-layer cached GPU styled output (`stroke`, `dropShadow`, `outerGlow`) with LRU eviction.
pub struct StyledLayerEntry {
    pub surface: SurfaceRgba16F,
    pub view_id: u64,
    pub sig: u64,
    pub last_used_frame: u64,
}

pub struct StyledLayerCache {
    entries: HashMap<String, StyledLayerEntry>,
    max_entries: usize,
    frame: u64,
    pub hits: u64,
    pub rebuilds: u64,
}

impl Default for StyledLayerCache {
    fn default() -> Self {
        Self::new(8)
    }
}

impl StyledLayerCache {
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: HashMap::new(),
            max_entries: max_entries.max(2),
            frame: 1,
            hits: 0,
            rebuilds: 0,
        }
    }

    pub fn begin_frame(&mut self) {
        self.frame = self.frame.saturating_add(1);
    }

    /// Checks whether a cached styled texture exists with exact matching signature and dimensions.
    pub fn get_hit(
        &mut self,
        layer_id: &str,
        sig: u64,
        w: u32,
        h: u32,
    ) -> Option<(&SurfaceRgba16F, u64)> {
        let entry = self.entries.get_mut(layer_id)?;
        if entry.sig == sig && entry.surface.width == w && entry.surface.height == h {
            entry.last_used_frame = self.frame;
            self.hits = self.hits.saturating_add(1);
            Some((&entry.surface, entry.view_id))
        } else {
            None
        }
    }

    /// Allocates or resizes a cache slot for `layer_id`, evicting the LRU entry if over budget.
    pub fn allocate_slot(
        &mut self,
        device: &wgpu::Device,
        layer_id: &str,
        sig: u64,
        w: u32,
        h: u32,
    ) -> (&SurfaceRgba16F, u64) {
        if !self.entries.contains_key(layer_id) && self.entries.len() >= self.max_entries {
            if let Some(lru_key) = self
                .entries
                .iter()
                .min_by_key(|(_, e)| e.last_used_frame)
                .map(|(k, _)| k.clone())
            {
                self.entries.remove(&lru_key);
            }
        }

        let frame = self.frame;
        self.rebuilds = self.rebuilds.saturating_add(1);
        let entry = self
            .entries
            .entry(layer_id.to_string())
            .or_insert_with(|| StyledLayerEntry {
                surface: SurfaceRgba16F::new(device, "ink-styled-layer-cache", w, h),
                view_id: NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
                sig,
                last_used_frame: frame,
            });
        if entry
            .surface
            .ensure_size(device, "ink-styled-layer-cache", w, h)
        {
            entry.view_id = NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        entry.sig = sig;
        entry.last_used_frame = frame;
        (&entry.surface, entry.view_id)
    }

    pub fn clear(&mut self) {
        self.entries.clear();
    }

    pub fn retain_layers(&mut self, valid_ids: &HashSet<&str>) {
        self.entries.retain(|k, _| valid_ids.contains(k.as_str()));
    }
}

/// Step granularity (in physical pixels) used to cushion drag-resize viewport target allocations
/// so dragging a window edge does not destroy/recreate full-viewport textures on every pixel.
const RESIZE_SLACK_STEP: u32 = 128;

#[inline]
fn round_up_slack(dim: u32, max_dim: u32) -> u32 {
    let clamped = dim.max(1).min(max_dim);
    let rounded = clamped.div_ceil(RESIZE_SLACK_STEP) * RESIZE_SLACK_STEP;
    rounded.min(max_dim)
}

/// Complete pool of viewport-sized `Rgba16Float` targets and 1×1 fallback dummy textures.
///
/// Only `final_scene` and the 1×1 dummy textures are allocated eagerly; all optional scratch,
/// 3-slice cache, live-stroke, folder/clip/frame stack, layer-style, and impasto surfaces are
/// allocated strictly on first use so a 1-layer blank canvas uses minimal VRAM.
pub struct CompositorTargets {
    /// Logical viewport dimensions (in physical pixels).
    pub width: u32,
    pub height: u32,
    /// Backing GPU texture dimensions (`>= width, height` when `use_slack` is true).
    pub alloc_width: u32,
    pub alloc_height: u32,
    use_slack: bool,

    // Final composited scene (read by viewport_present) & lazily-allocated reusable backdrop copy
    pub final_scene: SurfaceRgba16F,
    pub backdrop_scratch: Option<SurfaceRgba16F>,

    // Lazily-allocated 3-Slice Baked Layer Stack Cache targets
    pub below_active_cache: Option<SurfaceRgba16F>,
    pub above_active_cache: Option<SurfaceRgba16F>,
    pub active_unit_surface: Option<SurfaceRgba16F>,

    // Lazily-allocated Live WYSIWYG Stroke targets
    pub active_layer_base_surface: Option<SurfaceRgba16F>,
    pub live_stroke_surface: Option<SurfaceRgba16F>,

    // Nested stack targets (start empty, grown on demand by folder/clipping/frame nesting depth)
    pub folder_stack: Vec<SurfaceRgba16F>,
    pub clip_mask_stack: Vec<SurfaceRgba16F>,
    pub frame_mask_stack: Vec<SurfaceRgba16F>,

    // Lazily-allocated Layer Styles intermediate passes
    pub style_src: Option<SurfaceRgba16F>,
    pub style_blur_tmp: Option<SurfaceRgba16F>,
    pub style_shadow_blur: Option<SurfaceRgba16F>,
    pub style_glow_blur: Option<SurfaceRgba16F>,
    pub style_stroke_dilate_tmp: Option<SurfaceRgba16F>,
    pub style_stroke_dilate: Option<SurfaceRgba16F>,
    pub style_composite_out: Option<SurfaceRgba16F>,

    // Lazily-allocated Impasto Relief Lighting passes (0 VRAM cost on non-impasto documents!)
    pub impasto_height: Option<SurfaceR16F>,
    pub impasto_color_scratch: Option<SurfaceRgba16F>,
    pub impasto_lit_scratch: Option<SurfaceRgba16F>,

    // 1×1 immutable dummy fallback textures so unused bind-group slots always bind validly
    pub dummy_transparent_rgba16f: wgpu::Texture,
    pub dummy_transparent_rgba16f_view: wgpu::TextureView,
    pub dummy_white_rgba16f: wgpu::Texture,
    pub dummy_white_rgba16f_view: wgpu::TextureView,
    pub dummy_white_r8: wgpu::Texture,
    pub dummy_white_r8_view: wgpu::TextureView,
    pub dummy_lut_rgba8: wgpu::Texture,
    pub dummy_lut_rgba8_view: wgpu::TextureView,
}

impl CompositorTargets {
    /// Creates a viewport target pool with 128 px resize slack to prevent drag-resize reallocation storms.
    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32) -> Self {
        Self::new_with_slack(device, queue, width, height, true)
    }

    /// Creates an exact-sized target pool (used for temporary export/thumbnail chunks).
    pub fn new_exact(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32) -> Self {
        Self::new_with_slack(device, queue, width, height, false)
    }

    fn new_with_slack(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        use_slack: bool,
    ) -> Self {
        let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
        let w = width.clamp(1, max_dim);
        let h = height.clamp(1, max_dim);
        let (alloc_w, alloc_h) = if use_slack {
            (round_up_slack(w, max_dim), round_up_slack(h, max_dim))
        } else {
            (w, h)
        };

        let (dummy_transparent_rgba16f, dummy_transparent_rgba16f_view) =
            create_1x1_rgba16f(device, queue, "ink-dummy-transparent-16f", [0.0, 0.0, 0.0, 0.0]);
        let (dummy_white_rgba16f, dummy_white_rgba16f_view) =
            create_1x1_rgba16f(device, queue, "ink-dummy-white-16f", [1.0, 1.0, 1.0, 1.0]);
        let (dummy_white_r8, dummy_white_r8_view) =
            create_1x1_r8(device, queue, "ink-dummy-white-r8", 255);
        let (dummy_lut_rgba8, dummy_lut_rgba8_view) =
            create_identity_lut_rgba8(device, queue);

        Self {
            width: w,
            height: h,
            alloc_width: alloc_w,
            alloc_height: alloc_h,
            use_slack,
            final_scene: SurfaceRgba16F::new(device, "ink-comp-final-scene", alloc_w, alloc_h),
            backdrop_scratch: None,
            below_active_cache: None,
            above_active_cache: None,
            active_unit_surface: None,
            active_layer_base_surface: None,
            live_stroke_surface: None,
            folder_stack: Vec::new(),
            clip_mask_stack: Vec::new(),
            frame_mask_stack: Vec::new(),
            style_src: None,
            style_blur_tmp: None,
            style_shadow_blur: None,
            style_glow_blur: None,
            style_stroke_dilate_tmp: None,
            style_stroke_dilate: None,
            style_composite_out: None,
            impasto_height: None,
            impasto_color_scratch: None,
            impasto_lit_scratch: None,
            dummy_transparent_rgba16f,
            dummy_transparent_rgba16f_view,
            dummy_white_rgba16f,
            dummy_white_rgba16f_view,
            dummy_white_r8,
            dummy_white_r8_view,
            dummy_lut_rgba8,
            dummy_lut_rgba8_view,
        }
    }

    /// Updates logical viewport size and grows backing GPU textures with 128 px slack when needed.
    /// Returns `(logical_changed, textures_reallocated)`.
    pub fn ensure_size_detailed(
        &mut self,
        device: &wgpu::Device,
        width: u32,
        height: u32,
    ) -> (bool, bool) {
        let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
        let w = width.clamp(1, max_dim);
        let h = height.clamp(1, max_dim);
        let logical_changed = self.width != w || self.height != h;
        self.width = w;
        self.height = h;

        let (need_realloc, next_aw, next_ah) = if self.use_slack {
            if w > self.alloc_width || h > self.alloc_height {
                (
                    true,
                    round_up_slack(w, max_dim).max(self.alloc_width),
                    round_up_slack(h, max_dim).max(self.alloc_height),
                )
            } else {
                (false, self.alloc_width, self.alloc_height)
            }
        } else if self.alloc_width != w || self.alloc_height != h {
            (true, w, h)
        } else {
            (false, self.alloc_width, self.alloc_height)
        };

        if !need_realloc {
            return (logical_changed, false);
        }

        self.reallocate_all(device, next_aw, next_ah);
        (logical_changed, true)
    }

    /// Resizes viewport targets. Returns `true` if either logical dimensions or backing textures changed.
    pub fn ensure_size(&mut self, device: &wgpu::Device, width: u32, height: u32) -> bool {
        let (logical_changed, reallocated) = self.ensure_size_detailed(device, width, height);
        logical_changed || reallocated
    }

    /// Shrinks oversized slack-allocated textures down to `round_up_slack(width, height)` after idle.
    /// Returns `true` if backing textures were reallocated.
    pub fn trim_to_logical_size(&mut self, device: &wgpu::Device) -> bool {
        if !self.use_slack {
            return false;
        }
        let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
        let target_w = round_up_slack(self.width, max_dim);
        let target_h = round_up_slack(self.height, max_dim);
        if self.alloc_width > target_w + RESIZE_SLACK_STEP
            || self.alloc_height > target_h + RESIZE_SLACK_STEP
        {
            self.reallocate_all(device, target_w, target_h);
            return true;
        }
        false
    }

    fn reallocate_all(&mut self, device: &wgpu::Device, aw: u32, ah: u32) {
        self.alloc_width = aw;
        self.alloc_height = ah;
        self.final_scene
            .ensure_size(device, "ink-comp-final-scene", aw, ah);
        if let Some(ref mut surf) = self.backdrop_scratch {
            surf.ensure_size(device, "ink-comp-backdrop-scratch", aw, ah);
        }
        if let Some(ref mut surf) = self.below_active_cache {
            surf.ensure_size(device, "ink-comp-below-cache", aw, ah);
        }
        if let Some(ref mut surf) = self.above_active_cache {
            surf.ensure_size(device, "ink-comp-above-cache", aw, ah);
        }
        if let Some(ref mut surf) = self.active_unit_surface {
            surf.ensure_size(device, "ink-comp-active-unit", aw, ah);
        }
        if let Some(ref mut surf) = self.active_layer_base_surface {
            surf.ensure_size(device, "ink-comp-active-base", aw, ah);
        }
        if let Some(ref mut surf) = self.live_stroke_surface {
            surf.ensure_size(device, "ink-comp-live-stroke", aw, ah);
        }
        for (i, surf) in self.folder_stack.iter_mut().enumerate() {
            surf.ensure_size(device, &format!("ink-comp-folder-{i}"), aw, ah);
        }
        for (i, surf) in self.clip_mask_stack.iter_mut().enumerate() {
            surf.ensure_size(device, &format!("ink-comp-clip-{i}"), aw, ah);
        }
        for (i, surf) in self.frame_mask_stack.iter_mut().enumerate() {
            surf.ensure_size(device, &format!("ink-comp-frame-{i}"), aw, ah);
        }
        if let Some(ref mut surf) = self.style_src {
            surf.ensure_size(device, "ink-comp-style-src", aw, ah);
        }
        if let Some(ref mut surf) = self.style_blur_tmp {
            surf.ensure_size(device, "ink-comp-style-blur-tmp", aw, ah);
        }
        if let Some(ref mut surf) = self.style_shadow_blur {
            surf.ensure_size(device, "ink-comp-style-shadow-blur", aw, ah);
        }
        if let Some(ref mut surf) = self.style_glow_blur {
            surf.ensure_size(device, "ink-comp-style-glow-blur", aw, ah);
        }
        if let Some(ref mut surf) = self.style_stroke_dilate_tmp {
            surf.ensure_size(device, "ink-comp-style-stroke-dilate-tmp", aw, ah);
        }
        if let Some(ref mut surf) = self.style_stroke_dilate {
            surf.ensure_size(device, "ink-comp-style-stroke-dilate", aw, ah);
        }
        if let Some(ref mut surf) = self.style_composite_out {
            surf.ensure_size(device, "ink-comp-style-composite-out", aw, ah);
        }
        if let Some(ref mut surf) = self.impasto_height {
            surf.ensure_size(device, "ink-comp-impasto-height", aw, ah);
        }
        if let Some(ref mut surf) = self.impasto_color_scratch {
            surf.ensure_size(device, "ink-comp-impasto-color-scratch", aw, ah);
        }
        if let Some(ref mut surf) = self.impasto_lit_scratch {
            surf.ensure_size(device, "ink-comp-impasto-lit-scratch", aw, ah);
        }
    }

    pub fn ensure_backdrop_scratch(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.backdrop_scratch
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-backdrop-scratch", w, h))
    }

    pub fn ensure_below_cache(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.below_active_cache
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-below-cache", w, h))
    }

    pub fn ensure_above_cache(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.above_active_cache
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-above-cache", w, h))
    }

    pub fn ensure_active_unit(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.active_unit_surface
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-active-unit", w, h))
    }

    pub fn ensure_active_base(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.active_layer_base_surface
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-active-base", w, h))
    }

    pub fn ensure_live_stroke(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.live_stroke_surface
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-live-stroke", w, h))
    }

    pub fn ensure_style_src(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_src
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-src", w, h))
    }

    pub fn ensure_style_blur_tmp(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_blur_tmp
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-blur-tmp", w, h))
    }

    pub fn ensure_style_shadow_blur(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_shadow_blur
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-shadow-blur", w, h))
    }

    pub fn ensure_style_glow_blur(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_glow_blur
            .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-glow-blur", w, h))
    }

    pub fn ensure_style_stroke_surfaces(&mut self, device: &wgpu::Device) {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_stroke_dilate_tmp.get_or_insert_with(|| {
            SurfaceRgba16F::new(device, "ink-comp-style-stroke-dilate-tmp", w, h)
        });
        self.style_stroke_dilate.get_or_insert_with(|| {
            SurfaceRgba16F::new(device, "ink-comp-style-stroke-dilate", w, h)
        });
    }

    pub fn ensure_style_composite_out(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
        let (w, h) = (self.alloc_width, self.alloc_height);
        self.style_composite_out.get_or_insert_with(|| {
            SurfaceRgba16F::new(device, "ink-comp-style-composite-out", w, h)
        })
    }

    /// Lazily allocates the viewport `R16Float` heightfield and `Rgba16Float` relief scratch surfaces.
    pub fn ensure_impasto_surfaces(&mut self, device: &wgpu::Device) {
        let w = self.alloc_width;
        let h = self.alloc_height;
        self.impasto_height
            .get_or_insert_with(|| SurfaceR16F::new(device, "ink-comp-impasto-height", w, h));
        self.impasto_color_scratch.get_or_insert_with(|| {
            SurfaceRgba16F::new(device, "ink-comp-impasto-color-scratch", w, h)
        });
        self.impasto_lit_scratch.get_or_insert_with(|| {
            SurfaceRgba16F::new(device, "ink-comp-impasto-lit-scratch", w, h)
        });
    }

    pub fn ensure_folder_depth(&mut self, device: &wgpu::Device, depth: usize) {
        while self.folder_stack.len() <= depth {
            let i = self.folder_stack.len();
            self.folder_stack.push(SurfaceRgba16F::new(
                device,
                &format!("ink-comp-folder-{i}"),
                self.alloc_width,
                self.alloc_height,
            ));
        }
    }

    pub fn ensure_clip_depth(&mut self, device: &wgpu::Device, depth: usize) {
        while self.clip_mask_stack.len() <= depth {
            let i = self.clip_mask_stack.len();
            self.clip_mask_stack.push(SurfaceRgba16F::new(
                device,
                &format!("ink-comp-clip-{i}"),
                self.alloc_width,
                self.alloc_height,
            ));
        }
    }

    pub fn ensure_frame_depth(&mut self, device: &wgpu::Device, depth: usize) {
        while self.frame_mask_stack.len() <= depth {
            let i = self.frame_mask_stack.len();
            self.frame_mask_stack.push(SurfaceRgba16F::new(
                device,
                &format!("ink-comp-frame-{i}"),
                self.alloc_width,
                self.alloc_height,
            ));
        }
    }

    /// Trims unused nested folder/clip/frame stack surfaces and optional transient surfaces.
    /// Returns `true` if any GPU texture was dropped (caller should clear `bg_cache`).
    pub fn trim_unused_stacks(
        &mut self,
        keep_folder: usize,
        keep_clip: usize,
        keep_frame: usize,
        release_live_stroke: bool,
        release_styles: bool,
        release_impasto: bool,
    ) -> bool {
        let mut dropped = false;
        if self.folder_stack.len() > keep_folder {
            self.folder_stack.truncate(keep_folder);
            self.folder_stack.shrink_to_fit();
            dropped = true;
        }
        if self.clip_mask_stack.len() > keep_clip {
            self.clip_mask_stack.truncate(keep_clip);
            self.clip_mask_stack.shrink_to_fit();
            dropped = true;
        }
        if self.frame_mask_stack.len() > keep_frame {
            self.frame_mask_stack.truncate(keep_frame);
            self.frame_mask_stack.shrink_to_fit();
            dropped = true;
        }
        if release_live_stroke {
            if self.active_layer_base_surface.take().is_some() {
                dropped = true;
            }
            if self.live_stroke_surface.take().is_some() {
                dropped = true;
            }
            if self.active_unit_surface.take().is_some() {
                dropped = true;
            }
        }
        if release_styles {
            for slot in [
                &mut self.style_src,
                &mut self.style_blur_tmp,
                &mut self.style_shadow_blur,
                &mut self.style_glow_blur,
                &mut self.style_stroke_dilate_tmp,
                &mut self.style_stroke_dilate,
                &mut self.style_composite_out,
            ] {
                if slot.take().is_some() {
                    dropped = true;
                }
            }
        }
        if release_impasto {
            if self.impasto_height.take().is_some() {
                dropped = true;
            }
            if self.impasto_color_scratch.take().is_some() {
                dropped = true;
            }
            if self.impasto_lit_scratch.take().is_some() {
                dropped = true;
            }
        }
        dropped
    }

    /// Number of currently allocated full-viewport GPU textures (excluding 1×1 dummies).
    pub fn allocated_surface_count(&self) -> usize {
        let mut n = 1usize; // final_scene
        for opt in [
            &self.backdrop_scratch,
            &self.below_active_cache,
            &self.above_active_cache,
            &self.active_unit_surface,
            &self.active_layer_base_surface,
            &self.live_stroke_surface,
            &self.style_src,
            &self.style_blur_tmp,
            &self.style_shadow_blur,
            &self.style_glow_blur,
            &self.style_stroke_dilate_tmp,
            &self.style_stroke_dilate,
            &self.style_composite_out,
            &self.impasto_color_scratch,
            &self.impasto_lit_scratch,
        ] {
            if opt.is_some() {
                n += 1;
            }
        }
        if self.impasto_height.is_some() {
            n += 1;
        }
        n + self.folder_stack.len() + self.clip_mask_stack.len() + self.frame_mask_stack.len()
    }

    /// Estimated VRAM bytes currently occupied by all allocated viewport surfaces.
    pub fn allocated_vram_bytes(&self) -> u64 {
        let mut bytes = (self.final_scene.width as u64) * (self.final_scene.height as u64) * 8;
        let mut add_rgba16f = |s: &SurfaceRgba16F| {
            bytes += (s.width as u64) * (s.height as u64) * 8;
        };
        for opt in [
            &self.backdrop_scratch,
            &self.below_active_cache,
            &self.above_active_cache,
            &self.active_unit_surface,
            &self.active_layer_base_surface,
            &self.live_stroke_surface,
            &self.style_src,
            &self.style_blur_tmp,
            &self.style_shadow_blur,
            &self.style_glow_blur,
            &self.style_stroke_dilate_tmp,
            &self.style_stroke_dilate,
            &self.style_composite_out,
            &self.impasto_color_scratch,
            &self.impasto_lit_scratch,
        ] {
            if let Some(s) = opt {
                add_rgba16f(s);
            }
        }
        for s in &self.folder_stack {
            add_rgba16f(s);
        }
        for s in &self.clip_mask_stack {
            add_rgba16f(s);
        }
        for s in &self.frame_mask_stack {
            add_rgba16f(s);
        }
        if let Some(ref s) = self.impasto_height {
            bytes += (s.width as u64) * (s.height as u64) * 2;
        }
        bytes
    }
}

fn create_1x1_rgba16f(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    label: &str,
    rgba: [f32; 4],
) -> (wgpu::Texture, wgpu::TextureView) {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba16Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    let mut bytes = [0u8; 8];
    for (i, &c) in rgba.iter().enumerate() {
        let bits = half::f16::from_f32(c).to_bits().to_le_bytes();
        bytes[i * 2] = bits[0];
        bytes[i * 2 + 1] = bits[1];
    }
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &bytes,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(8),
            rows_per_image: Some(1),
        },
        wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    (texture, view)
}

fn create_1x1_r8(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    label: &str,
    val: u8,
) -> (wgpu::Texture, wgpu::TextureView) {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::R8Unorm,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &[val],
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(1),
            rows_per_image: Some(1),
        },
        wgpu::Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    (texture, view)
}

fn create_identity_lut_rgba8(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
) -> (wgpu::Texture, wgpu::TextureView) {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("ink-dummy-identity-lut"),
        size: wgpu::Extent3d {
            width: 256,
            height: 1,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    let mut data = vec![0u8; 256 * 4];
    for i in 0..256usize {
        let v = i as u8;
        data[i * 4] = v;
        data[i * 4 + 1] = v;
        data[i * 4 + 2] = v;
        data[i * 4 + 3] = 255;
    }
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &data,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(256 * 4),
            rows_per_image: Some(1),
        },
        wgpu::Extent3d {
            width: 256,
            height: 1,
            depth_or_array_layers: 1,
        },
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    (texture, view)
}