Skip to content

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

88.2 KB
Raw Blame
//! L1 GPU VRAM Tile Atlas Pool (`Rgba16Float` `Texture2DArray`) with LRU Eviction
//! and WGSL Compute Mipmap Pyramid Generator (LOD 0 -> 1 -> 2 -> 3).
//!
//! All GPU working tiles are stored in `wgpu::TextureFormat::Rgba16Float` (`256×256`, 512 KB/slot)
//! so blending, filtering, and zoomed-out mipmaps execute with zero 8-bit banding.

use crate::memory::ScratchBackend;
use crate::tiles::{
    SparseLayerGrid, TileCoord, TileData, TileFormat, BYTES_16F, BYTES_R16F, TILE_SIZE,
};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};

const MIPMAP_UNIFORM_STRIDE: u64 = 256;
static NEXT_POOL_ID: AtomicU64 = AtomicU64::new(1);

/// WGSL Compute Shader for 2×2 premultiplied-alpha box-filtered mipmap downsampling
/// (`4 child Rgba16Float tiles at LOD k-1 -> 1 parent Rgba16Float tile at LOD k`).
///
/// Writes into a dedicated `256×256` `rgba16float` storage scratch texture (avoiding
/// simultaneous read+write hazards on the atlas array), followed by an L2-speed VRAM copy
/// into the target atlas slice.
pub const MIPMAP_COMPUTE_WGSL: &str = r#"
struct MipmapParams {
    // Atlas slice indices for the 4 child quadrants (TL, TR, BL, BR).
    // Negative value (< 0) indicates an unallocated/transparent quadrant.
    child_slots: vec4<i32>,
    _pad: vec4<u32>,
};

@group(0) @binding(0) var<uniform> params: MipmapParams;
@group(0) @binding(1) var atlas_src: texture_2d_array<f32>;
@group(0) @binding(2) var dst_tile: texture_storage_2d<rgba16float, write>;

@compute @workgroup_size(16, 16, 1)
fn cs_downsample(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (gid.x >= 256u || gid.y >= 256u) {
        return;
    }

    let qx = gid.x >> 7u; // 0 (left) or 1 (right)
    let qy = gid.y >> 7u; // 0 (top)  or 1 (bottom)
    let q_idx = qy * 2u + qx;

    var child_slot: i32 = -1;
    switch (q_idx) {
        case 0u: { child_slot = params.child_slots.x; }
        case 1u: { child_slot = params.child_slots.y; }
        case 2u: { child_slot = params.child_slots.z; }
        default: { child_slot = params.child_slots.w; }
    }

    if (child_slot < 0) {
        textureStore(dst_tile, vec2<i32>(i32(gid.x), i32(gid.y)), vec4<f32>(0.0));
        return;
    }

    let local_x = i32((gid.x & 127u) << 1u);
    let local_y = i32((gid.y & 127u) << 1u);

    let p00 = textureLoad(atlas_src, vec2<i32>(local_x,     local_y),     child_slot, 0);
    let p10 = textureLoad(atlas_src, vec2<i32>(local_x + 1, local_y),     child_slot, 0);
    let p01 = textureLoad(atlas_src, vec2<i32>(local_x,     local_y + 1), child_slot, 0);
    let p11 = textureLoad(atlas_src, vec2<i32>(local_x + 1, local_y + 1), child_slot, 0);

    // Alpha-weighted (premultiplied) box filter prevents dark halos around anti-aliased ink
    let a0 = p00.a;
    let a1 = p10.a;
    let a2 = p01.a;
    let a3 = p11.a;
    let sum_a = a0 + a1 + a2 + a3;

    var out_px: vec4<f32>;
    if (sum_a <= 1e-5) {
        out_px = vec4<f32>(0.0);
    } else {
        let rgb = (p00.rgb * a0 + p10.rgb * a1 + p01.rgb * a2 + p11.rgb * a3) / sum_a;
        out_px = vec4<f32>(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), clamp(sum_a * 0.25, 0.0, 1.0));
    }

    textureStore(dst_tile, vec2<i32>(i32(gid.x), i32(gid.y)), out_px);
}
"#;

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct MipmapUniforms {
    child_slots: [i32; 4],
    _pad: [u32; 4],
}

/// Compact `Copy` key identifying a single GPU-resident tile slice inside the L1 VRAM atlas.
/// Uses interned `u32` IDs for `doc_id` and `layer_id` (zero per-tile heap `String` allocations).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpuTileKey {
    pub doc_id: u32,
    pub layer_id: u32,
    pub lod: u8,
    pub coord: TileCoord,
}

#[derive(Debug, Clone)]
struct SlotRecord {
    key: Option<GpuTileKey>,
    solid_color: Option<[u16; 4]>,
    version: u64,
    last_access_seq: u64,
    pin_count: u32,
    ref_bit: bool,
}

impl SlotRecord {
    #[inline]
    fn empty() -> Self {
        Self {
            key: None,
            solid_color: None,
            version: 0,
            last_access_seq: 0,
            pin_count: 0,
            ref_bit: false,
        }
    }

    #[inline]
    fn is_free(&self) -> bool {
        self.key.is_none() && self.solid_color.is_none() && self.pin_count == 0
    }
}

/// O(1) amortized Clock (Second-Chance LRU) victim selector that strictly skips pinned slots.
/// Returns `None` if every single slot in `slots` currently has `pin_count > 0`.
fn select_clock_victim(slots: &mut [SlotRecord], hand: &mut usize) -> Option<usize> {
    let n = slots.len();
    if n == 0 {
        return None;
    }
    let mut idx = *hand % n;
    // Two full revolutions guarantee finding any unpinned slot (first pass clears ref_bit, second evicts).
    for _ in 0..(n * 2) {
        let rec = &mut slots[idx];
        if rec.pin_count == 0 {
            if !rec.ref_bit {
                *hand = (idx + 1) % n;
                return Some(idx);
            }
            rec.ref_bit = false;
        }
        idx += 1;
        if idx == n {
            idx = 0;
        }
    }
    None
}

/// Extreme fallback only if every slot in the atlas is simultaneously pinned and cannot grow.
/// Picks the oldest slot WITHOUT resetting its `pin_count` (preserving caller ref-counting).
fn select_oldest_pinned_fallback(slots: &[SlotRecord]) -> usize {
    let mut fallback_idx = 0usize;
    let mut oldest = u64::MAX;
    for (i, rec) in slots.iter().enumerate() {
        if rec.last_access_seq < oldest {
            oldest = rec.last_access_seq;
            fallback_idx = i;
        }
    }
    fallback_idx
}

fn pop_free_slot(slots: &[SlotRecord], free_list: &mut Vec<u32>) -> Option<usize> {
    while let Some(s) = free_list.pop() {
        let idx = s as usize;
        if idx < slots.len() && slots[idx].is_free() {
            return Some(idx);
        }
    }
    None
}

/// Live L1 GPU VRAM tile atlas telemetry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GpuPoolStats {
    pub slots_used: u32,
    pub slots_capacity: u32,
    pub used_bytes: u64,
    pub capacity_bytes: u64,
    pub evictions: u64,
    pub mipmaps_generated: u64,
}

/// Lazily-allocated `R16Float` `Texture2DArray` storing sparse `256×256` impasto heightfield tiles
/// (128 KB/slot). Allocated only when a document actually paints or loads impasto height tiles.
struct ImpastoGpuAtlas {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    capacity: u32,
    slots: Vec<SlotRecord>,
    free_slots: Vec<u32>,
    clock_hand: usize,
    key_to_slot: HashMap<GpuTileKey, u32>,
}

/// Job descriptor for batched GPU compute mipmap generation (`generate_mipmap_batch`).
#[derive(Debug, Clone)]
pub struct MipmapBatchJob {
    pub parent_key: GpuTileKey,
    pub child_slots: [Option<u32>; 4],
    pub version: u64,
}

/// L1 GPU VRAM tiled atlas (`256×256×N` `Rgba16Float`) + LRU allocator + compute mipmap generator.
pub struct GpuTilePool {
    atlas_id: u64,
    atlas_texture: wgpu::Texture,
    atlas_array_view: wgpu::TextureView,
    capacity: u32,

    // Dedicated 256×256 Rgba16Float storage target for compute mipmap output (512 KB)
    mipmap_scratch_tex: wgpu::Texture,
    mipmap_scratch_view: wgpu::TextureView,
    mipmap_bgl: wgpu::BindGroupLayout,
    mipmap_uniform_buf: wgpu::Buffer,
    mipmap_uniform_cap: usize,
    mipmap_uniform_staging: Vec<u8>,
    mipmap_bind_group: wgpu::BindGroup,
    mipmap_pipeline: wgpu::ComputePipeline,

    // Compact R8Unorm 2D array pool for non-destructive 8-bit layer mask tiles (64 KB/slot)
    mask_atlas_texture: wgpu::Texture,
    mask_atlas_view: wgpu::TextureView,
    mask_capacity: u32,
    mask_slots: Vec<SlotRecord>,
    mask_free_slots: Vec<u32>,
    mask_clock_hand: usize,
    mask_key_to_slot: HashMap<GpuTileKey, u32>,

    // Lazily-allocated R16Float 2D array pool for persistent 3D impasto heightfield tiles (128 KB/slot)
    impasto_atlas: Option<ImpastoGpuAtlas>,
    impasto_atlas_id: u64,
    impasto_desired_capacity: u32,
    _dummy_impasto_tex: wgpu::Texture,
    dummy_impasto_view: wgpu::TextureView,

    // Reusable CPU upload scratch buffers (eliminates per-tile 512 KB heap allocations!)
    upload_rgba16f_scratch: Vec<u8>,
    upload_rgba8_scratch: Vec<u8>,
    upload_r16f_scratch: Vec<u8>,
    upload_mask8_scratch: Vec<u8>,

    // Compact string interners so tile lookups on the render thread perform ZERO heap allocations
    doc_intern: HashMap<String, u32>,
    next_doc_id: u32,
    layer_intern: HashMap<String, u32>,
    next_layer_id: u32,

    slots: Vec<SlotRecord>,
    free_slots: Vec<u32>,
    clock_hand: usize,
    key_to_slot: HashMap<GpuTileKey, u32>,
    solid_color_to_slot: HashMap<[u16; 4], u32>,
    pinned_slots_count: u32,
    access_seq: u64,
    frame_counter: u64,
    evictions: u64,
    mipmaps_generated: u64,
    mipmap_submits: u64,
}

impl GpuTilePool {
    /// Creates a new L1 GPU VRAM tile atlas sized for `vram_budget_bytes` (clamped safely to
    /// hardware `max_texture_array_layers`, minimum 16 slots so small test pools always work).
    pub fn new(device: &wgpu::Device, vram_budget_bytes: u64) -> Self {
        let max_layers = device.limits().max_texture_array_layers.max(16);
        let desired_slots = (vram_budget_bytes / BYTES_16F as u64).clamp(16, max_layers as u64) as u32;
        let capacity = desired_slots.min(max_layers);
        let mask_capacity = (capacity / 4).clamp(16, max_layers);

        let (atlas_texture, atlas_array_view) = Self::create_atlas_texture(device, capacity);
        let (mask_atlas_texture, mask_atlas_view) = Self::create_mask_atlas(device, mask_capacity);

        let mipmap_scratch_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-mipmap-scratch-rgba16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::STORAGE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let mipmap_scratch_view =
            mipmap_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());

        let mipmap_uniform_cap = 64usize;
        let mipmap_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-mipmap-uniforms-dyn"),
            size: mipmap_uniform_cap as u64 * MIPMAP_UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let mipmap_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-mipmap-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: NonZeroU64::new(
                            std::mem::size_of::<MipmapUniforms>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format: wgpu::TextureFormat::Rgba16Float,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
            ],
        });

        let mipmap_bind_group = Self::create_mipmap_bind_group(
            device,
            &mipmap_bgl,
            &mipmap_uniform_buf,
            &atlas_array_view,
            &mipmap_scratch_view,
        );

        let mipmap_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-mipmap-compute-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(MIPMAP_COMPUTE_WGSL)),
        });
        let mipmap_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-mipmap-pl"),
            bind_group_layouts: &[Some(&mipmap_bgl)],
            immediate_size: 0,
        });
        let mipmap_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-mipmap-compute-pipeline"),
            layout: Some(&mipmap_pl),
            module: &mipmap_shader,
            entry_point: Some("cs_downsample"),
            compilation_options: Default::default(),
            cache: None,
        });

        let slots = (0..capacity).map(|_| SlotRecord::empty()).collect();
        let free_slots: Vec<u32> = (0..capacity).rev().collect();
        let mask_slots = (0..mask_capacity).map(|_| SlotRecord::empty()).collect();
        let mask_free_slots: Vec<u32> = (0..mask_capacity).rev().collect();

        let (_dummy_impasto_tex, dummy_impasto_view) = Self::create_dummy_impasto_atlas(device);
        let impasto_desired_capacity = (capacity / 2).clamp(32, max_layers);

        Self {
            atlas_id: NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed),
            atlas_texture,
            atlas_array_view,
            capacity,
            mipmap_scratch_tex,
            mipmap_scratch_view,
            mipmap_bgl,
            mipmap_uniform_buf,
            mipmap_uniform_cap,
            mipmap_uniform_staging: Vec::with_capacity(64 * MIPMAP_UNIFORM_STRIDE as usize),
            mipmap_bind_group,
            mipmap_pipeline,
            mask_atlas_texture,
            mask_atlas_view,
            mask_capacity,
            mask_slots,
            mask_free_slots,
            mask_clock_hand: 0,
            mask_key_to_slot: HashMap::with_capacity(mask_capacity as usize),
            impasto_atlas: None,
            impasto_atlas_id: 0,
            impasto_desired_capacity,
            _dummy_impasto_tex,
            dummy_impasto_view,
            upload_rgba16f_scratch: Vec::new(),
            upload_rgba8_scratch: Vec::new(),
            upload_r16f_scratch: Vec::new(),
            upload_mask8_scratch: Vec::new(),
            doc_intern: HashMap::with_capacity(8),
            next_doc_id: 1,
            layer_intern: HashMap::with_capacity(64),
            next_layer_id: 1,
            slots,
            free_slots,
            clock_hand: 0,
            key_to_slot: HashMap::with_capacity(capacity as usize),
            solid_color_to_slot: HashMap::with_capacity(8),
            pinned_slots_count: 0,
            access_seq: 1,
            frame_counter: 1,
            evictions: 0,
            mipmaps_generated: 0,
            mipmap_submits: 0,
        }
    }

    fn create_mipmap_bind_group(
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        uniform_buf: &wgpu::Buffer,
        atlas_view: &wgpu::TextureView,
        scratch_view: &wgpu::TextureView,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ink-mipmap-bg"),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: uniform_buf,
                        offset: 0,
                        size: NonZeroU64::new(std::mem::size_of::<MipmapUniforms>() as u64),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(scratch_view),
                },
            ],
        })
    }

    fn ensure_mipmap_uniform_capacity(&mut self, device: &wgpu::Device, needed: usize) {
        if needed <= self.mipmap_uniform_cap {
            return;
        }
        let new_cap = needed.next_power_of_two().max(64);
        self.mipmap_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-mipmap-uniforms-dyn"),
            size: new_cap as u64 * MIPMAP_UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        self.mipmap_uniform_cap = new_cap;
        self.mipmap_bind_group = Self::create_mipmap_bind_group(
            device,
            &self.mipmap_bgl,
            &self.mipmap_uniform_buf,
            &self.atlas_array_view,
            &self.mipmap_scratch_view,
        );
    }

    /// Unique monotonic ID for this pool's color+mask atlas texture views (for compositor BG caching).
    #[inline]
    pub fn atlas_id(&self) -> u64 {
        self.atlas_id
    }

    /// Unique monotonic ID for the lazily-allocated impasto height atlas (`0` while dummy 1×1 is bound).
    #[inline]
    pub fn impasto_atlas_id(&self) -> u64 {
        self.impasto_atlas_id
    }

    /// Interns a document ID string into a compact `u32` (zero heap allocations on cache hit).
    #[inline]
    pub fn intern_doc(&mut self, doc_id: &str) -> u32 {
        if let Some(&id) = self.doc_intern.get(doc_id) {
            return id;
        }
        let id = self.next_doc_id;
        self.next_doc_id = self.next_doc_id.saturating_add(1);
        self.doc_intern.insert(doc_id.to_string(), id);
        id
    }

    /// Interns a layer ID string into a compact `u32` (zero heap allocations on cache hit).
    #[inline]
    pub fn intern_layer(&mut self, layer_id: &str) -> u32 {
        if let Some(&id) = self.layer_intern.get(layer_id) {
            return id;
        }
        let id = self.next_layer_id;
        self.next_layer_id = self.next_layer_id.saturating_add(1);
        self.layer_intern.insert(layer_id.to_string(), id);
        id
    }

    #[inline]
    pub fn lookup_doc_id(&self, doc_id: &str) -> Option<u32> {
        self.doc_intern.get(doc_id).copied()
    }

    #[inline]
    pub fn lookup_layer_id(&self, layer_id: &str) -> Option<u32> {
        self.layer_intern.get(layer_id).copied()
    }

    /// Convenience helper building a compact `GpuTileKey` using the pool's string interner.
    #[inline]
    pub fn make_key(&mut self, doc_id: &str, layer_id: &str, lod: u8, coord: TileCoord) -> GpuTileKey {
        let doc_id = self.intern_doc(doc_id);
        let layer_id = self.intern_layer(layer_id);
        GpuTileKey {
            doc_id,
            layer_id,
            lod,
            coord,
        }
    }

    /// Read-only key builder that returns `None` if `doc_id` or `layer_id` has never been interned.
    #[inline]
    pub fn try_make_key(
        &self,
        doc_id: &str,
        layer_id: &str,
        lod: u8,
        coord: TileCoord,
    ) -> Option<GpuTileKey> {
        Some(GpuTileKey {
            doc_id: self.lookup_doc_id(doc_id)?,
            layer_id: self.lookup_layer_id(layer_id)?,
            lod,
            coord,
        })
    }

    /// Total GPU queue submissions issued for mipmap generation (for perf telemetry/tests).
    #[inline]
    pub fn mipmap_submits(&self) -> u64 {
        self.mipmap_submits
    }

    fn create_dummy_impasto_atlas(device: &wgpu::Device) -> (wgpu::Texture, wgpu::TextureView) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-dummy-impasto-r16f"),
            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::R16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-dummy-impasto-r16f-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });
        (texture, view)
    }

    fn create_impasto_atlas(device: &wgpu::Device, capacity: u32) -> ImpastoGpuAtlas {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-l1-impasto-atlas-r16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: capacity,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-l1-impasto-atlas-r16f-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });
        let slots = (0..capacity).map(|_| SlotRecord::empty()).collect();
        let free_slots: Vec<u32> = (0..capacity).rev().collect();
        ImpastoGpuAtlas {
            texture,
            view,
            capacity,
            slots,
            free_slots,
            clock_hand: 0,
            key_to_slot: HashMap::with_capacity(capacity as usize),
        }
    }

    fn create_atlas_texture(
        device: &wgpu::Device,
        capacity: u32,
    ) -> (wgpu::Texture, wgpu::TextureView) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-l1-tile-atlas-rgba16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: capacity,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-l1-tile-atlas-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });
        (texture, view)
    }

    fn create_mask_atlas(
        device: &wgpu::Device,
        capacity: u32,
    ) -> (wgpu::Texture, wgpu::TextureView) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-l1-mask-atlas-r8"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: capacity,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-l1-mask-atlas-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });
        (texture, view)
    }

    #[inline]
    pub fn begin_frame(&mut self) {
        self.frame_counter = self.frame_counter.saturating_add(1);
    }

    #[inline]
    fn next_access_seq(&mut self) -> u64 {
        self.access_seq = self.access_seq.saturating_add(1);
        self.access_seq
    }

    /// Pins a color atlas slot so LRU eviction will NEVER evict it until unpinned.
    /// Reference-counted so overlapping/nested pin scopes compose cleanly.
    #[inline]
    pub fn pin_slot(&mut self, slot: u32) {
        if let Some(rec) = self.slots.get_mut(slot as usize) {
            if rec.pin_count == 0 {
                self.pinned_slots_count = self.pinned_slots_count.saturating_add(1);
            }
            rec.pin_count = rec.pin_count.saturating_add(1);
        }
    }

    /// Decrements the pin count for a color atlas slot.
    #[inline]
    pub fn unpin_slot(&mut self, slot: u32) {
        if let Some(rec) = self.slots.get_mut(slot as usize) {
            if rec.pin_count > 0 {
                rec.pin_count -= 1;
                if rec.pin_count == 0 {
                    self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
                }
            }
        }
    }

    /// Returns whether a color atlas slot currently has a non-zero pin count.
    #[inline]
    pub fn is_slot_pinned(&self, slot: u32) -> bool {
        self.slots
            .get(slot as usize)
            .is_some_and(|rec| rec.pin_count > 0)
    }

    /// Number of color atlas slots currently unpinned and available for LRU eviction.
    #[inline]
    pub fn unpinned_slot_count(&self) -> u32 {
        self.capacity.saturating_sub(self.pinned_slots_count)
    }

    /// Pins a mask atlas slot so LRU eviction will not evict it until unpinned.
    #[inline]
    pub fn pin_mask_slot(&mut self, slot: u32) {
        if let Some(rec) = self.mask_slots.get_mut(slot as usize) {
            rec.pin_count = rec.pin_count.saturating_add(1);
        }
    }

    /// Unpins a mask atlas slot.
    #[inline]
    pub fn unpin_mask_slot(&mut self, slot: u32) {
        if let Some(rec) = self.mask_slots.get_mut(slot as usize) {
            rec.pin_count = rec.pin_count.saturating_sub(1);
        }
    }

    /// Pins an impasto heightfield atlas slot so LRU eviction will not evict it until unpinned.
    #[inline]
    pub fn pin_impasto_slot(&mut self, slot: u32) {
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            if let Some(rec) = atlas.slots.get_mut(slot as usize) {
                rec.pin_count = rec.pin_count.saturating_add(1);
            }
        }
    }

    /// Unpins an impasto heightfield atlas slot.
    #[inline]
    pub fn unpin_impasto_slot(&mut self, slot: u32) {
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            if let Some(rec) = atlas.slots.get_mut(slot as usize) {
                rec.pin_count = rec.pin_count.saturating_sub(1);
            }
        }
    }

    /// Releases all pins across color, mask, and impasto pools (typically at frame end).
    pub fn unpin_all_pinned(&mut self) {
        for rec in &mut self.slots {
            rec.pin_count = 0;
        }
        self.pinned_slots_count = 0;
        for rec in &mut self.mask_slots {
            rec.pin_count = 0;
        }
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            for rec in &mut atlas.slots {
                rec.pin_count = 0;
            }
        }
    }

    #[inline]
    pub fn impasto_capacity(&self) -> u32 {
        self.impasto_atlas
            .as_ref()
            .map(|a| a.capacity)
            .unwrap_or(self.impasto_desired_capacity)
    }

    #[inline]
    pub fn atlas_texture(&self) -> &wgpu::Texture {
        &self.atlas_texture
    }

    #[inline]
    pub fn atlas_view(&self) -> &wgpu::TextureView {
        &self.atlas_array_view
    }

    #[inline]
    pub fn mask_atlas_view(&self) -> &wgpu::TextureView {
        &self.mask_atlas_view
    }

    #[inline]
    pub fn mask_atlas_texture(&self) -> &wgpu::Texture {
        &self.mask_atlas_texture
    }

    /// Returns the lazily-allocated `R16Float` impasto heightfield `Texture2DArray` view
    /// (or a 1×1×1 dummy view when no impasto tiles exist yet).
    #[inline]
    pub fn impasto_atlas_view(&self) -> &wgpu::TextureView {
        self.impasto_atlas
            .as_ref()
            .map(|a| &a.view)
            .unwrap_or(&self.dummy_impasto_view)
    }

    /// Ensures the `R16Float` impasto atlas is allocated and returns a reference to its texture.
    pub fn ensure_impasto_atlas_texture(&mut self, device: &wgpu::Device) -> &wgpu::Texture {
        let cap = self.impasto_desired_capacity;
        let atlas = self
            .impasto_atlas
            .get_or_insert_with(|| Self::create_impasto_atlas(device, cap));
        &atlas.texture
    }

    #[inline]
    pub fn has_impasto_atlas(&self) -> bool {
        self.impasto_atlas.is_some()
    }

    #[inline]
    pub fn capacity(&self) -> u32 {
        self.capacity
    }

    pub fn stats(&self) -> GpuPoolStats {
        let used = (self.key_to_slot.len() + self.solid_color_to_slot.len()) as u32;
        let (imp_used_bytes, imp_cap_bytes) = self
            .impasto_atlas
            .as_ref()
            .map(|a| {
                (
                    a.key_to_slot.len() as u64 * BYTES_R16F as u64,
                    a.capacity as u64 * BYTES_R16F as u64,
                )
            })
            .unwrap_or((0, 0));
        GpuPoolStats {
            slots_used: used,
            slots_capacity: self.capacity,
            used_bytes: used as u64 * BYTES_16F as u64
                + self.mask_key_to_slot.len() as u64 * (TILE_SIZE * TILE_SIZE) as u64
                + imp_used_bytes,
            capacity_bytes: self.capacity as u64 * BYTES_16F as u64
                + self.mask_capacity as u64 * (TILE_SIZE * TILE_SIZE) as u64
                + imp_cap_bytes,
            evictions: self.evictions,
            mipmaps_generated: self.mipmaps_generated,
        }
    }

    /// Looks up a resident GPU tile slot and touches its monotonic LRU sequence + clock ref bit.
    pub fn get_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
        let &slot = self.key_to_slot.get(key)?;
        let seq = self.next_access_seq();
        let rec = &mut self.slots[slot as usize];
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        Some(slot)
    }

    /// Looks up a resident shared `SolidColor` VRAM slot and touches its monotonic LRU sequence.
    pub fn get_solid_color_slot(&mut self, rgba16f: [u16; 4]) -> Option<u32> {
        let &slot = self.solid_color_to_slot.get(&rgba16f)?;
        let seq = self.next_access_seq();
        let rec = &mut self.slots[slot as usize];
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        Some(slot)
    }

    /// Ensures a single shared `Rgba16Float` VRAM slot exists for uniform `rgba16f` solid color,
    /// uploading once per unique solid color so full-canvas solid backgrounds consume 1 slot total.
    pub fn ensure_solid_color_slot(&mut self, queue: &wgpu::Queue, rgba16f: [u16; 4]) -> u32 {
        if let Some(slot) = self.get_solid_color_slot(rgba16f) {
            return slot;
        }
        let slot = self.acquire_solid_color_slot(rgba16f);
        self.upload_rgba16f_scratch.resize(BYTES_16F, 0);
        let mut px = [0u8; 8];
        px[0..2].copy_from_slice(&rgba16f[0].to_le_bytes());
        px[2..4].copy_from_slice(&rgba16f[1].to_le_bytes());
        px[4..6].copy_from_slice(&rgba16f[2].to_le_bytes());
        px[6..8].copy_from_slice(&rgba16f[3].to_le_bytes());
        for chunk in self.upload_rgba16f_scratch.chunks_exact_mut(8) {
            chunk.copy_from_slice(&px);
        }
        Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, &self.upload_rgba16f_scratch);
        slot
    }

    /// Looks up a resident GPU tile slot only if its cached version matches `expected_version`.
    pub fn get_slot_if_version(&mut self, key: &GpuTileKey, expected_version: u64) -> Option<u32> {
        let &slot = self.key_to_slot.get(key)?;
        if self.slots[slot as usize].version != expected_version {
            return None;
        }
        let seq = self.next_access_seq();
        let rec = &mut self.slots[slot as usize];
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        Some(slot)
    }

    /// Looks up a resident GPU mask tile slot and touches its monotonic LRU sequence.
    pub fn get_mask_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
        let &slot = self.mask_key_to_slot.get(key)?;
        let seq = self.next_access_seq();
        let rec = &mut self.mask_slots[slot as usize];
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        Some(slot)
    }

    /// Looks up a resident GPU `R16Float` impasto heightfield tile slot and touches its monotonic LRU sequence.
    pub fn get_impasto_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
        let seq = self.next_access_seq();
        let atlas = self.impasto_atlas.as_mut()?;
        let &slot = atlas.key_to_slot.get(key)?;
        let rec = &mut atlas.slots[slot as usize];
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        Some(slot)
    }

    /// Grows the `R16Float` impasto atlas texture array if all slots are pinned and capacity < max_layers.
    fn try_grow_impasto_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
        let max_layers = device.limits().max_texture_array_layers.max(16);
        let Some(atlas) = self.impasto_atlas.as_mut() else {
            return false;
        };
        if atlas.capacity >= max_layers {
            return false;
        }
        let old_cap = atlas.capacity;
        let new_cap = (old_cap.saturating_mul(2)).min(max_layers);
        if new_cap <= old_cap {
            return false;
        }
        let new_atlas_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-l1-impasto-atlas-r16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: new_cap,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-impasto-atlas-grow-copy"),
        });
        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &atlas.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: &new_atlas_tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: old_cap,
            },
        );
        queue.submit(Some(encoder.finish()));

        atlas.view = new_atlas_tex.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-l1-impasto-atlas-r16f-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });
        atlas.texture = new_atlas_tex;
        atlas.capacity = new_cap;
        atlas.slots.resize_with(new_cap as usize, SlotRecord::empty);
        for s in (old_cap..new_cap).rev() {
            atlas.free_slots.push(s);
        }
        self.impasto_atlas_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
        true
    }

    /// Grows the `R8Unorm` mask atlas texture array if all slots are pinned and capacity < max_layers.
    fn try_grow_mask_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
        let max_layers = device.limits().max_texture_array_layers.max(16);
        if self.mask_capacity >= max_layers {
            return false;
        }
        let old_cap = self.mask_capacity;
        let new_cap = (old_cap.saturating_mul(2)).min(max_layers);
        if new_cap <= old_cap {
            return false;
        }
        let (new_tex, new_view) = Self::create_mask_atlas(device, new_cap);
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-mask-atlas-grow-copy"),
        });
        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &self.mask_atlas_texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: &new_tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: old_cap,
            },
        );
        queue.submit(Some(encoder.finish()));

        self.mask_atlas_texture = new_tex;
        self.mask_atlas_view = new_view;
        self.mask_capacity = new_cap;
        self.mask_slots
            .resize_with(new_cap as usize, SlotRecord::empty);
        for s in (old_cap..new_cap).rev() {
            self.mask_free_slots.push(s);
        }
        self.atlas_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
        true
    }

    /// Lazily allocates an `R16Float` impasto heightfield slot (creating the atlas on first use).
    pub fn acquire_impasto_slot(
        &mut self,
        device: &wgpu::Device,
        key: GpuTileKey,
        version: u64,
    ) -> u32 {
        self.acquire_impasto_slot_inner(device, None, key, version)
    }

    fn acquire_impasto_slot_inner(
        &mut self,
        device: &wgpu::Device,
        queue: Option<&wgpu::Queue>,
        key: GpuTileKey,
        version: u64,
    ) -> u32 {
        let seq = self.next_access_seq();
        let cap = self.impasto_desired_capacity;
        let impasto_id = &mut self.impasto_atlas_id;
        let atlas = self.impasto_atlas.get_or_insert_with(|| {
            *impasto_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
            Self::create_impasto_atlas(device, cap)
        });
        if let Some(&existing) = atlas.key_to_slot.get(&key) {
            let rec = &mut atlas.slots[existing as usize];
            rec.version = version;
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            return existing;
        }
        if let Some(free_idx) = pop_free_slot(&atlas.slots, &mut atlas.free_slots) {
            let rec = &mut atlas.slots[free_idx];
            rec.key = Some(key);
            rec.solid_color = None;
            rec.version = version;
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            atlas.key_to_slot.insert(key, free_idx as u32);
            return free_idx as u32;
        }

        let victim_opt = select_clock_victim(&mut atlas.slots, &mut atlas.clock_hand);
        let victim = match victim_opt {
            Some(v) => v,
            None => {
                // Every impasto slot is currently pinned: grow cleanly if queue is available!
                if let Some(q) = queue {
                    if self.try_grow_impasto_atlas(device, q) {
                        let atlas = self.impasto_atlas.as_mut().expect("impasto atlas grown");
                        if let Some(free_idx) = pop_free_slot(&atlas.slots, &mut atlas.free_slots) {
                            let rec = &mut atlas.slots[free_idx];
                            rec.key = Some(key);
                            rec.solid_color = None;
                            rec.version = version;
                            rec.last_access_seq = seq;
                            rec.ref_bit = true;
                            atlas.key_to_slot.insert(key, free_idx as u32);
                            return free_idx as u32;
                        }
                    }
                }
                let atlas = self.impasto_atlas.as_mut().expect("impasto atlas exists");
                select_oldest_pinned_fallback(&atlas.slots)
            }
        };

        let atlas = self.impasto_atlas.as_mut().expect("impasto atlas exists");
        if let Some(old) = atlas.slots[victim].key.take() {
            atlas.key_to_slot.remove(&old);
            self.evictions = self.evictions.saturating_add(1);
        }
        // Update fields in-place to preserve `pin_count` if extreme fallback was hit
        let rec = &mut atlas.slots[victim];
        rec.key = Some(key);
        rec.solid_color = None;
        rec.version = version;
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        atlas.key_to_slot.insert(key, victim as u32);
        victim as u32
    }

    /// Ensures a CPU/L2/L3 `R16Float` impasto [`TileData`] is uploaded to the lazily-allocated
    /// GPU `R16Float` impasto atlas. Skips redundant uploads when `version` matches.
    pub fn ensure_impasto_uploaded(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        key: GpuTileKey,
        tile: &TileData,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<u32, String> {
        let seq = self.next_access_seq();
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            if let Some(&slot) = atlas.key_to_slot.get(&key) {
                let rec = &mut atlas.slots[slot as usize];
                rec.last_access_seq = seq;
                rec.ref_bit = true;
                if rec.version == tile.version {
                    return Ok(slot);
                }
            }
        }
        tile.write_r16f_into(scratch, &mut self.upload_r16f_scratch)?;
        let slot = self.acquire_impasto_slot_inner(device, Some(queue), key, tile.version);
        if let Some(atlas) = self.impasto_atlas.as_ref() {
            Self::write_r16f_slice(&atlas.texture, queue, slot, &self.upload_r16f_scratch);
        }
        Ok(slot)
    }

    fn write_r16f_slice(texture: &wgpu::Texture, queue: &wgpu::Queue, slot: u32, r16f: &[u8]) {
        debug_assert_eq!(r16f.len(), BYTES_R16F);
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: 0,
                    y: 0,
                    z: slot,
                },
                aspect: wgpu::TextureAspect::All,
            },
            r16f,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some((TILE_SIZE * 2) as u32), // 512 bytes (exact multiple of 256!)
                rows_per_image: Some(TILE_SIZE as u32),
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Writes 131,072 bytes (`256×256` `R16Float`, `bytes_per_row = 512`) into impasto atlas `slot`.
    pub fn upload_impasto_r16f_slot(&self, queue: &wgpu::Queue, slot: u32, r16f: &[u8]) {
        let Some(atlas) = self.impasto_atlas.as_ref() else {
            return;
        };
        Self::write_r16f_slice(&atlas.texture, queue, slot, r16f);
    }

    /// Evicts a single cached `R16Float` impasto tile key if resident.
    pub fn evict_impasto_key(&mut self, key: &GpuTileKey) {
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            if let Some(slot) = atlas.key_to_slot.remove(key) {
                let rec = &mut atlas.slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.pin_count = 0;
                rec.ref_bit = false;
                atlas.free_slots.push(slot);
            }
        }
    }

    /// Evicts a single cached mask tile key if resident.
    pub fn evict_mask_key(&mut self, key: &GpuTileKey) {
        if let Some(slot) = self.mask_key_to_slot.remove(key) {
            let rec = &mut self.mask_slots[slot as usize];
            rec.key = None;
            rec.version = 0;
            rec.pin_count = 0;
            rec.ref_bit = false;
            self.mask_free_slots.push(slot);
        }
    }

    fn allocate_color_victim(&mut self) -> usize {
        if let Some(free_idx) = pop_free_slot(&self.slots, &mut self.free_slots) {
            return free_idx;
        }
        let victim_idx = match select_clock_victim(&mut self.slots, &mut self.clock_hand) {
            Some(idx) => idx,
            None => {
                // Extreme fallback: every slot in the color atlas is simultaneously pinned.
                // NEVER reset `pin_count` or decrement `pinned_slots_count` here so active
                // pin-scope holders' subsequent `unpin_slot()` calls remain balanced!
                select_oldest_pinned_fallback(&self.slots)
            }
        };
        if let Some(old_key) = self.slots[victim_idx].key.take() {
            self.key_to_slot.remove(&old_key);
            self.evictions = self.evictions.saturating_add(1);
        } else if let Some(old_solid) = self.slots[victim_idx].solid_color.take() {
            self.solid_color_to_slot.remove(&old_solid);
            self.evictions = self.evictions.saturating_add(1);
        }
        victim_idx
    }

    fn acquire_solid_color_slot(&mut self, rgba16f: [u16; 4]) -> u32 {
        let seq = self.next_access_seq();
        if let Some(&existing) = self.solid_color_to_slot.get(&rgba16f) {
            let rec = &mut self.slots[existing as usize];
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            return existing;
        }
        let victim_idx = self.allocate_color_victim();
        let rec = &mut self.slots[victim_idx];
        rec.key = None;
        rec.solid_color = Some(rgba16f);
        rec.version = 0;
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        self.solid_color_to_slot.insert(rgba16f, victim_idx as u32);
        victim_idx as u32
    }

    /// Allocates a free slot or evicts the least-recently-used unpinned slot from the L1 VRAM pool.
    pub fn acquire_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {
        let seq = self.next_access_seq();
        if let Some(&existing) = self.key_to_slot.get(&key) {
            let rec = &mut self.slots[existing as usize];
            rec.version = version;
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            return existing;
        }

        let victim_idx = self.allocate_color_victim();
        let rec = &mut self.slots[victim_idx];
        rec.key = Some(key);
        rec.solid_color = None;
        rec.version = version;
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        self.key_to_slot.insert(key, victim_idx as u32);
        victim_idx as u32
    }

    /// Ensures a CPU/L2/L3 [`TileData`] is uploaded to an L1 VRAM `Rgba16Float` slot,
    /// deduplicating uniform `SolidColor` tiles onto a single shared slot per unique color,
    /// reusing a persistent scratch upload buffer (zero per-tile 512 KB heap allocations!),
    /// and skipping redundant GPU uploads when `version` matches.
    pub fn ensure_tile_uploaded(
        &mut self,
        queue: &wgpu::Queue,
        key: GpuTileKey,
        tile: &TileData,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<u32, String> {
        if let Some(solid_16f) = tile.solid_rgba16f() {
            // If this key previously held a non-solid per-tile slot, release it.
            self.evict_key(&key);
            return Ok(self.ensure_solid_color_slot(queue, solid_16f));
        }

        if let Some(&slot) = self.key_to_slot.get(&key) {
            let seq = self.next_access_seq();
            let rec = &mut self.slots[slot as usize];
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            if rec.version == tile.version {
                return Ok(slot);
            }
        }

        // Fast zero-copy path when tile is already Raw Rgba16Float
        if tile.format == TileFormat::Rgba16Float {
            if let crate::tiles::TileStorage::Raw(ref raw_16f) = tile.storage {
                let slot = self.acquire_slot(key, tile.version);
                Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, raw_16f);
                return Ok(slot);
            }
        }

        tile.write_rgba16f_into(
            scratch,
            &mut self.upload_rgba16f_scratch,
            &mut self.upload_rgba8_scratch,
        )?;
        let slot = self.acquire_slot(key, tile.version);
        Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, &self.upload_rgba16f_scratch);
        Ok(slot)
    }

    fn write_rgba16f_slice(
        texture: &wgpu::Texture,
        queue: &wgpu::Queue,
        slot: u32,
        rgba16f: &[u8],
    ) {
        debug_assert_eq!(rgba16f.len(), BYTES_16F);
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: 0,
                    y: 0,
                    z: slot,
                },
                aspect: wgpu::TextureAspect::All,
            },
            rgba16f,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some((TILE_SIZE * 8) as u32), // 2048 bytes (multiple of 256)
                rows_per_image: Some(TILE_SIZE as u32),
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Directly writes 524,288 bytes of `Rgba16Float` pixel data into `slot`.
    pub fn upload_rgba16f_slot(&self, queue: &wgpu::Queue, slot: u32, rgba16f: &[u8]) {
        Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, rgba16f);
    }

    /// Uploads an 8-bit mask tile (`65,536` bytes) into the compact `R8Unorm` mask atlas,
    /// protecting pinned mask slots and cleanly growing capacity if all slots are pinned.
    pub fn ensure_mask_uploaded(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        key: GpuTileKey,
        tile: &TileData,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<u32, String> {
        if let Some(&slot) = self.mask_key_to_slot.get(&key) {
            let seq = self.next_access_seq();
            let rec = &mut self.mask_slots[slot as usize];
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            if rec.version == tile.version {
                return Ok(slot);
            }
        }
        let slot = self.acquire_mask_slot(device, queue, key, tile.version);
        if let crate::tiles::TileStorage::Raw(ref raw_mask) = tile.storage {
            Self::write_mask8_slice(&self.mask_atlas_texture, queue, slot, raw_mask);
            return Ok(slot);
        }
        tile.write_mask8_into(scratch, &mut self.upload_mask8_scratch)?;
        Self::write_mask8_slice(
            &self.mask_atlas_texture,
            queue,
            slot,
            &self.upload_mask8_scratch,
        );
        Ok(slot)
    }

    fn write_mask8_slice(texture: &wgpu::Texture, queue: &wgpu::Queue, slot: u32, mask8: &[u8]) {
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: 0,
                    y: 0,
                    z: slot,
                },
                aspect: wgpu::TextureAspect::All,
            },
            mask8,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(TILE_SIZE as u32), // 256 bytes (exact alignment!)
                rows_per_image: Some(TILE_SIZE as u32),
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
        );
    }

    fn acquire_mask_slot(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        key: GpuTileKey,
        version: u64,
    ) -> u32 {
        let seq = self.next_access_seq();
        if let Some(&existing) = self.mask_key_to_slot.get(&key) {
            let rec = &mut self.mask_slots[existing as usize];
            rec.version = version;
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            return existing;
        }
        if let Some(free_idx) = pop_free_slot(&self.mask_slots, &mut self.mask_free_slots) {
            let rec = &mut self.mask_slots[free_idx];
            rec.key = Some(key);
            rec.solid_color = None;
            rec.version = version;
            rec.last_access_seq = seq;
            rec.ref_bit = true;
            self.mask_key_to_slot.insert(key, free_idx as u32);
            return free_idx as u32;
        }
        let victim = match select_clock_victim(&mut self.mask_slots, &mut self.mask_clock_hand) {
            Some(v) => v,
            None => {
                if self.try_grow_mask_atlas(device, queue) {
                    if let Some(free_idx) =
                        pop_free_slot(&self.mask_slots, &mut self.mask_free_slots)
                    {
                        let rec = &mut self.mask_slots[free_idx];
                        rec.key = Some(key);
                        rec.solid_color = None;
                        rec.version = version;
                        rec.last_access_seq = seq;
                        rec.ref_bit = true;
                        self.mask_key_to_slot.insert(key, free_idx as u32);
                        return free_idx as u32;
                    }
                }
                select_oldest_pinned_fallback(&self.mask_slots)
            }
        };
        if let Some(old) = self.mask_slots[victim].key.take() {
            self.mask_key_to_slot.remove(&old);
        }
        let rec = &mut self.mask_slots[victim];
        rec.key = Some(key);
        rec.solid_color = None;
        rec.version = version;
        rec.last_access_seq = seq;
        rec.ref_bit = true;
        self.mask_key_to_slot.insert(key, victim as u32);
        victim as u32
    }

    /// Internal helper: uploads all `dispatches` uniforms into the dynamic uniform buffer
    /// in ONE `queue.write_buffer` and encodes every compute downsample + atlas copy into
    /// **ONE `CommandEncoder` + ONE `queue.submit`**!
    fn submit_mipmap_jobs(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        dispatches: &[(MipmapUniforms, u32)],
    ) {
        if dispatches.is_empty() {
            return;
        }
        self.ensure_mipmap_uniform_capacity(device, dispatches.len());
        let stride = MIPMAP_UNIFORM_STRIDE as usize;
        let total_bytes = dispatches.len() * stride;
        self.mipmap_uniform_staging.clear();
        self.mipmap_uniform_staging.resize(total_bytes, 0);
        for (i, (u, _)) in dispatches.iter().enumerate() {
            let src = bytemuck::bytes_of(u);
            let off = i * stride;
            self.mipmap_uniform_staging[off..off + src.len()].copy_from_slice(src);
        }
        queue.write_buffer(&self.mipmap_uniform_buf, 0, &self.mipmap_uniform_staging);

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-mipmap-batch-compute-encoder"),
        });

        for (i, &(_, dst_slot)) in dispatches.iter().enumerate() {
            let dyn_off = (i as u32) * (MIPMAP_UNIFORM_STRIDE as u32);
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("ink-mipmap-compute-pass"),
                    timestamp_writes: None,
                });
                pass.set_pipeline(&self.mipmap_pipeline);
                pass.set_bind_group(0, &self.mipmap_bind_group, &[dyn_off]);
                // 256 / 16 = 16 workgroups along X and Y
                pass.dispatch_workgroups(16, 16, 1);
            }

            // Copy compute output from scratch 2D texture into destination atlas slice
            encoder.copy_texture_to_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.mipmap_scratch_tex,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyTextureInfo {
                    texture: &self.atlas_texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: dst_slot,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::Extent3d {
                    width: TILE_SIZE as u32,
                    height: TILE_SIZE as u32,
                    depth_or_array_layers: 1,
                },
            );
        }

        queue.submit(Some(encoder.finish()));
        self.mipmaps_generated = self
            .mipmaps_generated
            .saturating_add(dispatches.len() as u64);
        self.mipmap_submits = self.mipmap_submits.saturating_add(1);
    }

    /// Generates a batch of parent mipmap tiles (LOD `1..=3`) on the GPU using the
    /// dynamic-offset `cs_downsample` compute shader in **ONE `CommandEncoder` + ONE `queue.submit`**
    /// (automatically chunking only when VRAM pool unpinned capacity is tight).
    ///
    /// Returns the destination atlas slot for each input job in matching order.
    pub fn generate_mipmap_batch(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        jobs: &[MipmapBatchJob],
    ) -> Vec<u32> {
        if jobs.is_empty() {
            return Vec::new();
        }
        let mut dst_slots = Vec::with_capacity(jobs.len());
        let mut dispatches: Vec<(MipmapUniforms, u32)> = Vec::with_capacity(jobs.len());
        let mut chunk_pins: Vec<u32> = Vec::with_capacity(jobs.len() * 5);

        for job in jobs {
            if self.unpinned_slot_count() <= 5 && !dispatches.is_empty() {
                self.submit_mipmap_jobs(device, queue, &dispatches);
                dispatches.clear();
                for s in chunk_pins.drain(..) {
                    self.unpin_slot(s);
                }
            }
            for s in job.child_slots.into_iter().flatten() {
                self.pin_slot(s);
                chunk_pins.push(s);
            }
            let dst_slot = self.acquire_slot(job.parent_key.clone(), job.version);
            self.pin_slot(dst_slot);
            chunk_pins.push(dst_slot);
            dst_slots.push(dst_slot);
            let uniforms = MipmapUniforms {
                child_slots: [
                    job.child_slots[0].map(|s| s as i32).unwrap_or(-1),
                    job.child_slots[1].map(|s| s as i32).unwrap_or(-1),
                    job.child_slots[2].map(|s| s as i32).unwrap_or(-1),
                    job.child_slots[3].map(|s| s as i32).unwrap_or(-1),
                ],
                _pad: [0; 4],
            };
            dispatches.push((uniforms, dst_slot));
        }

        if !dispatches.is_empty() {
            self.submit_mipmap_jobs(device, queue, &dispatches);
        }
        for s in chunk_pins {
            self.unpin_slot(s);
        }
        dst_slots
    }

    /// Generates a parent mipmap tile (LOD `target_lod` in `1..=3`) on the GPU using the
    /// `cs_downsample` compute shader from up to 4 child atlas slots `(TL, TR, BL, BR)`.
    ///
    /// Pass `None` for any unallocated/empty child quadrant. Returns the destination atlas slot.
    pub fn generate_mipmap_tile(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        parent_key: GpuTileKey,
        child_slots: [Option<u32>; 4],
        version: u64,
    ) -> u32 {
        let slots = self.generate_mipmap_batch(
            device,
            queue,
            &[MipmapBatchJob {
                parent_key,
                child_slots,
                version,
            }],
        );
        slots[0]
    }

    /// Reads back a `256×256` `Rgba16Float` atlas slice (524,288 bytes) from GPU VRAM into CPU memory.
    pub fn readback_slot_rgba16f(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        slot: u32,
    ) -> Result<Vec<u8>, String> {
        let staging = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-tile-readback-staging"),
            size: BYTES_16F as u64,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-tile-readback-encoder"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &self.atlas_texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: 0,
                    y: 0,
                    z: slot,
                },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &staging,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some((TILE_SIZE * 8) as u32), // 2048 bytes (aligned to 256)
                    rows_per_image: Some(TILE_SIZE as u32),
                },
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(Some(encoder.finish()));

        let slice = staging.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |res| {
            let _ = tx.send(res);
        });
        let _ = device.poll(wgpu::PollType::wait_indefinitely());
        rx.recv()
            .map_err(|_| "GPU readback channel closed".to_string())?
            .map_err(|e| format!("GPU readback map_async failed: {e}"))?;

        let data = slice
            .get_mapped_range()
            .map_err(|e| format!("GPU readback get_mapped_range failed: {e}"))?
            .to_vec();
        staging.unmap();
        Ok(data)
    }

    /// Evicts a single cached tile key from L1 VRAM if resident (e.g. tile erased completely empty).
    pub fn evict_key(&mut self, key: &GpuTileKey) {
        if let Some(slot) = self.key_to_slot.remove(key) {
            let rec = &mut self.slots[slot as usize];
            rec.key = None;
            rec.version = 0;
            rec.ref_bit = false;
            if rec.pin_count > 0 {
                rec.pin_count = 0;
                self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
            }
            self.free_slots.push(slot);
        }
    }

    /// Invalidates all cached VRAM slices belonging to a document.
    pub fn invalidate_document(&mut self, doc_id: &str) {
        let Some(doc_key) = self.lookup_doc_id(doc_id) else {
            return;
        };
        let free_slots = &mut self.free_slots;
        self.key_to_slot.retain(|k, &mut slot| {
            if k.doc_id == doc_key {
                let rec = &mut self.slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.ref_bit = false;
                if rec.pin_count > 0 {
                    rec.pin_count = 0;
                    self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
                }
                free_slots.push(slot);
                false
            } else {
                true
            }
        });
        let mask_free = &mut self.mask_free_slots;
        self.mask_key_to_slot.retain(|k, &mut slot| {
            if k.doc_id == doc_key {
                let rec = &mut self.mask_slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.pin_count = 0;
                rec.ref_bit = false;
                mask_free.push(slot);
                false
            } else {
                true
            }
        });
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            let imp_free = &mut atlas.free_slots;
            atlas.key_to_slot.retain(|k, &mut slot| {
                if k.doc_id == doc_key {
                    let rec = &mut atlas.slots[slot as usize];
                    rec.key = None;
                    rec.version = 0;
                    rec.pin_count = 0;
                    rec.ref_bit = false;
                    imp_free.push(slot);
                    false
                } else {
                    true
                }
            });
        }
    }

    /// Invalidates all cached VRAM slices belonging to a specific layer.
    pub fn invalidate_layer(&mut self, doc_id: &str, layer_id: &str) {
        let (Some(doc_key), Some(layer_key)) =
            (self.lookup_doc_id(doc_id), self.lookup_layer_id(layer_id))
        else {
            return;
        };
        let free_slots = &mut self.free_slots;
        self.key_to_slot.retain(|k, &mut slot| {
            if k.doc_id == doc_key && k.layer_id == layer_key {
                let rec = &mut self.slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.ref_bit = false;
                if rec.pin_count > 0 {
                    rec.pin_count = 0;
                    self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
                }
                free_slots.push(slot);
                false
            } else {
                true
            }
        });
        let mask_free = &mut self.mask_free_slots;
        self.mask_key_to_slot.retain(|k, &mut slot| {
            if k.doc_id == doc_key && k.layer_id == layer_key {
                let rec = &mut self.mask_slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.pin_count = 0;
                rec.ref_bit = false;
                mask_free.push(slot);
                false
            } else {
                true
            }
        });
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            let imp_free = &mut atlas.free_slots;
            atlas.key_to_slot.retain(|k, &mut slot| {
                if k.doc_id == doc_key && k.layer_id == layer_key {
                    let rec = &mut atlas.slots[slot as usize];
                    rec.key = None;
                    rec.version = 0;
                    rec.pin_count = 0;
                    rec.ref_bit = false;
                    imp_free.push(slot);
                    false
                } else {
                    true
                }
            });
        }
    }

    /// O(resident_slots) lazy sync: evicts any resident VRAM tiles for `doc` whose layer or
    /// tile was removed or mutated, without iterating or uploading offscreen document tiles.
    pub fn prune_stale_document_keys(&mut self, doc: &crate::document::Document) {
        let Some(doc_key) = self.lookup_doc_id(&doc.id) else {
            return;
        };
        let mut layer_map: HashMap<u32, &crate::document::LayerNode> =
            HashMap::with_capacity(doc.layers.len());
        for layer in &doc.layers {
            if let Some(lid) = self.lookup_layer_id(&layer.meta.id) {
                layer_map.insert(lid, layer);
            }
        }

        let slots = &mut self.slots;
        let pinned_count = &mut self.pinned_slots_count;
        let free_slots = &mut self.free_slots;
        self.key_to_slot.retain(|k, &mut slot| {
            if k.doc_id != doc_key {
                return true;
            }
            let valid = if let Some(layer) = layer_map.get(&k.layer_id) {
                if k.lod == 0 {
                    layer
                        .grid
                        .tiles
                        .get(&k.coord)
                        .is_some_and(|t| slots[slot as usize].version == t.version)
                } else {
                    let expected = compute_lod_tile_version(&layer.grid, k.lod, k.coord);
                    expected != 0 && slots[slot as usize].version == expected
                }
            } else {
                false
            };
            if !valid {
                let rec = &mut slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.ref_bit = false;
                if rec.pin_count > 0 {
                    rec.pin_count = 0;
                    *pinned_count = pinned_count.saturating_sub(1);
                }
                free_slots.push(slot);
            }
            valid
        });

        let mask_slots = &mut self.mask_slots;
        let mask_free = &mut self.mask_free_slots;
        self.mask_key_to_slot.retain(|k, &mut slot| {
            if k.doc_id != doc_key {
                return true;
            }
            let valid = layer_map.get(&k.layer_id).is_some_and(|layer| {
                layer.grid.has_mask
                    && layer
                        .grid
                        .mask_tiles
                        .get(&k.coord)
                        .is_some_and(|t| mask_slots[slot as usize].version == t.version)
            });
            if !valid {
                let rec = &mut mask_slots[slot as usize];
                rec.key = None;
                rec.version = 0;
                rec.pin_count = 0;
                rec.ref_bit = false;
                mask_free.push(slot);
            }
            valid
        });

        if let Some(atlas) = self.impasto_atlas.as_mut() {
            let imp_slots = &mut atlas.slots;
            let imp_free = &mut atlas.free_slots;
            atlas.key_to_slot.retain(|k, &mut slot| {
                if k.doc_id != doc_key {
                    return true;
                }
                let valid = layer_map.get(&k.layer_id).is_some_and(|layer| {
                    layer
                        .grid
                        .impasto_tiles
                        .get(&k.coord)
                        .is_some_and(|t| imp_slots[slot as usize].version == t.version)
                });
                if !valid {
                    let rec = &mut imp_slots[slot as usize];
                    rec.key = None;
                    rec.version = 0;
                    rec.pin_count = 0;
                    rec.ref_bit = false;
                    imp_free.push(slot);
                }
                valid
            });
        }
    }

    /// Flushes all resident slots (e.g. explicit GPU cache purge).
    pub fn flush_all(&mut self) {
        self.key_to_slot.clear();
        self.solid_color_to_slot.clear();
        self.pinned_slots_count = 0;
        for rec in &mut self.slots {
            *rec = SlotRecord::empty();
        }
        self.free_slots = (0..self.capacity).rev().collect();
        self.clock_hand = 0;
        self.mask_key_to_slot.clear();
        for rec in &mut self.mask_slots {
            *rec = SlotRecord::empty();
        }
        self.mask_free_slots = (0..self.mask_capacity).rev().collect();
        self.mask_clock_hand = 0;
        if let Some(atlas) = self.impasto_atlas.as_mut() {
            atlas.key_to_slot.clear();
            for rec in &mut atlas.slots {
                *rec = SlotRecord::empty();
            }
            atlas.free_slots = (0..atlas.capacity).rev().collect();
            atlas.clock_hand = 0;
        }
    }
}

/// Returns `Some(rgba16f)` if every in-bounds LOD-0 tile covered by `(lod, coord)` within
/// `[0..doc_w, 0..doc_h]` exists in `grid` and shares the exact same uniform `SolidColor`.
///
/// Allows LOD 0..=3 rendering & mipmap generation to reuse a single shared VRAM slot with
/// zero compute mipmap overhead for uniform solid backgrounds and fills.
pub fn uniform_solid_color_for_lod_tile(
    grid: &SparseLayerGrid,
    lod: u8,
    coord: TileCoord,
    doc_w: u32,
    doc_h: u32,
) -> Option<[u16; 4]> {
    if lod == 0 {
        return grid.tiles.get(&coord).and_then(|t| t.solid_rgba16f());
    }
    let scale = 1i32 << lod;
    let doc_tiles_x = doc_w.max(1).div_ceil(TILE_SIZE as u32) as i32;
    let doc_tiles_y = doc_h.max(1).div_ceil(TILE_SIZE as u32) as i32;
    let start_tx = (coord.tx * scale).max(0);
    let start_ty = (coord.ty * scale).max(0);
    let end_tx = (coord.tx * scale + scale).min(doc_tiles_x);
    let end_ty = (coord.ty * scale + scale).min(doc_tiles_y);

    if start_tx >= end_tx || start_ty >= end_ty {
        return None;
    }

    let mut expected: Option<[u16; 4]> = None;
    for ty in start_ty..end_ty {
        for tx in start_tx..end_tx {
            let tile = grid.tiles.get(&TileCoord::new(tx, ty))?;
            let solid = tile.solid_rgba16f()?;
            match expected {
                None => expected = Some(solid),
                Some(prev) if prev == solid => {}
                Some(_) => return None,
            }
        }
    }
    expected
}

/// Computes a deterministic 64-bit version for mipmap tile `(lod, coord)` purely from its
/// 4 child quadrant versions (down to LOD-0 per-tile `TileData::version`).
///
/// Returns `0` when all descendant LOD-0 tiles are absent/empty.
/// Unmodified sibling subtrees retain the exact same version across localized strokes, so
/// untouched LOD 1..3 tiles stay resident in VRAM with zero invalidation or recompute!
pub fn compute_lod_tile_version(grid: &SparseLayerGrid, lod: u8, coord: TileCoord) -> u64 {
    if lod == 0 {
        return grid.tiles.get(&coord).map(|t| t.version).unwrap_or(0);
    }
    let c0 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2, coord.ty * 2));
    let c1 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2 + 1, coord.ty * 2));
    let c2 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2, coord.ty * 2 + 1));
    let c3 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1));
    if (c0 | c1 | c2 | c3) == 0 {
        return 0;
    }
    let mut h: u64 = 0xcbf29ce484222325 ^ (lod as u64);
    for v in [c0, c1, c2, c3] {
        h ^= v.wrapping_add(0x9e3779b97f4a7c15);
        h = h.wrapping_mul(0x100000001b3);
        h ^= h >> 31;
    }
    if h == 0 { 1 } else { h }
}

/// Ensures tile `(lod, coord)` of `grid` is resident in `tile_pool`, recursively uploading
/// missing LOD-0 children and generating parent mipmaps while pinning each resolved sibling
/// so computing later siblings or acquiring the destination slot can NEVER evict an earlier one.
///
/// Uniform `SolidColor` regions at any LOD `0..=3` resolve in O(1) VRAM via the shared solid
/// slot cache with zero mipmap generation overhead.
#[allow(clippy::too_many_arguments)]
pub fn ensure_grid_lod_tile_recursive(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    tile_pool: &mut GpuTilePool,
    doc_id: &str,
    layer_id: &str,
    grid: &SparseLayerGrid,
    doc_w: u32,
    doc_h: u32,
    lod: u8,
    coord: TileCoord,
    scratch: Option<&dyn ScratchBackend>,
) -> Option<u32> {
    let doc_key = tile_pool.intern_doc(doc_id);
    let layer_key = tile_pool.intern_layer(layer_id);
    ensure_grid_lod_tile_recursive_interned(
        device,
        queue,
        tile_pool,
        doc_key,
        layer_key,
        grid,
        doc_w,
        doc_h,
        lod,
        coord,
        scratch,
    )
}

#[allow(clippy::too_many_arguments)]
fn ensure_grid_lod_tile_recursive_interned(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    tile_pool: &mut GpuTilePool,
    doc_key: u32,
    layer_key: u32,
    grid: &SparseLayerGrid,
    doc_w: u32,
    doc_h: u32,
    lod: u8,
    coord: TileCoord,
    scratch: Option<&dyn ScratchBackend>,
) -> Option<u32> {
    if lod == 0 {
        let tile = grid.tiles.get(&coord)?;
        let key = GpuTileKey {
            doc_id: doc_key,
            layer_id: layer_key,
            lod: 0,
            coord,
        };
        return tile_pool.ensure_tile_uploaded(queue, key, tile, scratch).ok();
    }

    let key = GpuTileKey {
        doc_id: doc_key,
        layer_id: layer_key,
        lod,
        coord,
    };

    if let Some(solid_16f) = uniform_solid_color_for_lod_tile(grid, lod, coord, doc_w, doc_h) {
        tile_pool.evict_key(&key);
        return Some(tile_pool.ensure_solid_color_slot(queue, solid_16f));
    }

    let expected_ver = compute_lod_tile_version(grid, lod, coord);
    if expected_ver == 0 {
        tile_pool.evict_key(&key);
        return None;
    }

    if let Some(slot) = tile_pool.get_slot_if_version(&key, expected_ver) {
        return Some(slot);
    }

    let child_coords = [
        TileCoord::new(coord.tx * 2, coord.ty * 2),
        TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
        TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
        TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
    ];
    let mut child_slots = [None; 4];
    for (qi, cc) in child_coords.iter().enumerate() {
        if let Some(slot) = ensure_grid_lod_tile_recursive_interned(
            device,
            queue,
            tile_pool,
            doc_key,
            layer_key,
            grid,
            doc_w,
            doc_h,
            lod - 1,
            *cc,
            scratch,
        ) {
            tile_pool.pin_slot(slot);
            child_slots[qi] = Some(slot);
        }
    }

    let res = if child_slots.iter().any(|s| s.is_some()) {
        Some(tile_pool.generate_mipmap_tile(
            device,
            queue,
            key,
            child_slots,
            expected_ver,
        ))
    } else {
        tile_pool.evict_key(&key);
        None
    };

    for s in child_slots.into_iter().flatten() {
        tile_pool.unpin_slot(s);
    }

    res
}

fn grid_has_any_tile_in_lod(grid: &SparseLayerGrid, lod: u8, coord: TileCoord) -> bool {
    if lod == 0 {
        return grid.tiles.contains_key(&coord);
    }
    let scale = 1i32 << lod;
    let base_tx = coord.tx * scale;
    let base_ty = coord.ty * scale;
    for dy in 0..scale {
        for dx in 0..scale {
            if grid.tiles.contains_key(&TileCoord::new(base_tx + dx, base_ty + dy)) {
                return true;
            }
        }
    }
    false
}

/// Regenerates all dirty/requested mipmap tiles across LOD 1 -> 2 -> 3 in a **SINGLE batched
/// `CommandEncoder` + `queue.submit`** (gracefully chunking only when tight VRAM limits require it).
///
/// Preserves evicted-sibling safety identically to [`ensure_grid_lod_tile_recursive`] and skips
/// compute completely for uniform `SolidColor` regions and unmodified sibling subtrees.
#[allow(clippy::too_many_arguments)]
pub fn regenerate_grid_lods_batched(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    tile_pool: &mut GpuTilePool,
    doc_id: &str,
    layer_id: &str,
    grid: &SparseLayerGrid,
    doc_w: u32,
    doc_h: u32,
    dirty_lods: &[Vec<TileCoord>; 3],
    evict_dirty_first: bool,
    scratch: Option<&dyn ScratchBackend>,
) {
    if dirty_lods[0].is_empty() && dirty_lods[1].is_empty() && dirty_lods[2].is_empty() {
        return;
    }

    let doc_key = tile_pool.intern_doc(doc_id);
    let layer_key = tile_pool.intern_layer(layer_id);

    // 1. Optionally evict explicitly dirty keys first so stale versions are never reused
    if evict_dirty_first {
        for (lod_idx, coords) in dirty_lods.iter().enumerate() {
            let target_lod = (lod_idx + 1) as u8;
            for &coord in coords {
                tile_pool.evict_key(&GpuTileKey {
                    doc_id: doc_key,
                    layer_id: layer_key,
                    lod: target_lod,
                    coord,
                });
            }
        }
    }

    // 2. Build dependency DAG top-down (LOD 3 -> 2 -> 1), skipping solid-color & up-to-date tiles
    let mut levels: [HashSet<TileCoord>; 3] = [
        dirty_lods[0].iter().copied().collect(),
        dirty_lods[1].iter().copied().collect(),
        dirty_lods[2].iter().copied().collect(),
    ];
    let mut expected_versions: [HashMap<TileCoord, u64>; 3] = [
        HashMap::new(),
        HashMap::new(),
        HashMap::new(),
    ];

    for lod_idx in (0..3usize).rev() {
        let lod = (lod_idx + 1) as u8;
        let current: Vec<TileCoord> = levels[lod_idx].iter().copied().collect();
        for coord in current {
            let key = GpuTileKey {
                doc_id: doc_key,
                layer_id: layer_key,
                lod,
                coord,
            };
            if let Some(solid_16f) = uniform_solid_color_for_lod_tile(grid, lod, coord, doc_w, doc_h)
            {
                tile_pool.evict_key(&key);
                let _ = tile_pool.ensure_solid_color_slot(queue, solid_16f);
                levels[lod_idx].remove(&coord);
                continue;
            }
            let expected_ver = compute_lod_tile_version(grid, lod, coord);
            if expected_ver == 0 {
                tile_pool.evict_key(&key);
                levels[lod_idx].remove(&coord);
                continue;
            }
            if tile_pool.get_slot_if_version(&key, expected_ver).is_some() {
                levels[lod_idx].remove(&coord);
                continue;
            }
            expected_versions[lod_idx].insert(coord, expected_ver);
            if lod > 1 {
                let child_coords = [
                    TileCoord::new(coord.tx * 2, coord.ty * 2),
                    TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
                    TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
                    TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
                ];
                for cc in child_coords {
                    if grid_has_any_tile_in_lod(grid, lod - 1, cc) {
                        levels[lod_idx - 1].insert(cc);
                    }
                }
            }
        }
    }

    // 3. Emit LOD 1 -> 2 -> 3 bottom-up into ONE dynamic-uniform CommandEncoder + queue.submit!
    let mut dispatches: Vec<(MipmapUniforms, u32)> = Vec::with_capacity(
        levels[0].len() + levels[1].len() + levels[2].len(),
    );
    let mut chunk_pins: Vec<u32> = Vec::with_capacity(dispatches.capacity() * 5);

    for (lod_idx, level_set) in levels.iter().enumerate() {
        if level_set.is_empty() {
            continue;
        }
        let lod = (lod_idx + 1) as u8;
        let mut coords: Vec<TileCoord> = level_set.iter().copied().collect();
        coords.sort_by_key(|c| (c.ty, c.tx));

        for coord in coords {
            let parent_key = GpuTileKey {
                doc_id: doc_key,
                layer_id: layer_key,
                lod,
                coord,
            };
            let parent_ver = expected_versions[lod_idx]
                .get(&coord)
                .copied()
                .unwrap_or_else(|| compute_lod_tile_version(grid, lod, coord));

            // If pool unpinned space is tight, submit current batch and release pins first
            if tile_pool.unpinned_slot_count() <= 5 && !dispatches.is_empty() {
                tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
                dispatches.clear();
                for s in chunk_pins.drain(..) {
                    tile_pool.unpin_slot(s);
                }
            }

            let child_coords = [
                TileCoord::new(coord.tx * 2, coord.ty * 2),
                TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
                TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
                TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
            ];
            let mut child_slots = [None; 4];

            for (qi, cc) in child_coords.iter().enumerate() {
                if lod == 1 {
                    if let Some(tile) = grid.tiles.get(cc) {
                        let ckey = GpuTileKey {
                            doc_id: doc_key,
                            layer_id: layer_key,
                            lod: 0,
                            coord: *cc,
                        };
                        if let Ok(slot) = tile_pool.ensure_tile_uploaded(queue, ckey, tile, scratch)
                        {
                            tile_pool.pin_slot(slot);
                            chunk_pins.push(slot);
                            child_slots[qi] = Some(slot);
                        }
                    }
                } else if let Some(solid_16f) =
                    uniform_solid_color_for_lod_tile(grid, lod - 1, *cc, doc_w, doc_h)
                {
                    let slot = tile_pool.ensure_solid_color_slot(queue, solid_16f);
                    tile_pool.pin_slot(slot);
                    chunk_pins.push(slot);
                    child_slots[qi] = Some(slot);
                } else {
                    let ckey = GpuTileKey {
                        doc_id: doc_key,
                        layer_id: layer_key,
                        lod: lod - 1,
                        coord: *cc,
                    };
                    let child_ver = expected_versions[lod_idx - 1]
                        .get(cc)
                        .copied()
                        .unwrap_or_else(|| compute_lod_tile_version(grid, lod - 1, *cc));
                    if child_ver != 0 {
                        if let Some(slot) = tile_pool.get_slot_if_version(&ckey, child_ver) {
                            tile_pool.pin_slot(slot);
                            chunk_pins.push(slot);
                            child_slots[qi] = Some(slot);
                        } else {
                            // Only reachable under ultra-tight VRAM chunk eviction: flush pending batch
                            // and regenerate the evicted child cleanly.
                            if !dispatches.is_empty() {
                                tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
                                dispatches.clear();
                                for s in chunk_pins.drain(..) {
                                    tile_pool.unpin_slot(s);
                                }
                                // Re-pin earlier quadrants of this tile so they stay protected
                                for prev_s in child_slots.iter().take(qi).flatten() {
                                    tile_pool.pin_slot(*prev_s);
                                    chunk_pins.push(*prev_s);
                                }
                            }
                            if let Some(slot) = ensure_grid_lod_tile_recursive_interned(
                                device,
                                queue,
                                tile_pool,
                                doc_key,
                                layer_key,
                                grid,
                                doc_w,
                                doc_h,
                                lod - 1,
                                *cc,
                                scratch,
                            ) {
                                tile_pool.pin_slot(slot);
                                chunk_pins.push(slot);
                                child_slots[qi] = Some(slot);
                            }
                        }
                    }
                }
            }

            if child_slots.iter().any(|s| s.is_some()) {
                let dst_slot = tile_pool.acquire_slot(parent_key, parent_ver);
                tile_pool.pin_slot(dst_slot);
                chunk_pins.push(dst_slot);
                dispatches.push((
                    MipmapUniforms {
                        child_slots: [
                            child_slots[0].map(|s| s as i32).unwrap_or(-1),
                            child_slots[1].map(|s| s as i32).unwrap_or(-1),
                            child_slots[2].map(|s| s as i32).unwrap_or(-1),
                            child_slots[3].map(|s| s as i32).unwrap_or(-1),
                        ],
                        _pad: [0; 4],
                    },
                    dst_slot,
                ));
            } else {
                tile_pool.evict_key(&parent_key);
            }
        }
    }

    if !dispatches.is_empty() {
        tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
    }
    for s in chunk_pins {
        tile_pool.unpin_slot(s);
    }
}