Skip to content

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

56.2 KB
Raw Blame
//! Multiplayer Collaboration GPU Draft Fast-Path & Direct Binary Tile Delta Sync (`collab/mod.rs`).
//!
//! 1. **Per-Peer GPU Draft Layers (`RemotePeerDraftManager`)**: Routes incoming remote peer
//!    live strokes directly into sparse `256×256` `Rgba16Float` GPU tiles on DX12 (zero DOM
//!    `<canvas>`, zero WebView2 raster decoding!) with zero-flicker handoff until committed
//!    tile deltas arrive.
//! 2. **Direct Binary Wire Codec (`encode_tile_delta_packet`, `apply_tile_delta_packet`,
//!    `encode_layer_mask_packet`, `apply_layer_mask_packet`)**: Exact byte-for-byte parity
//!    with `src-tauri/src/server.rs` (`EMPTY`, `RAW`, `LZ4`, `SOLID`, `SUBRECT_LZ4`), reading
//!    and writing directly on `Document`'s `SparseLayerGrid` without JS pixel/LZ4 round-trips!

use crate::document::{Document, LayerId};
use crate::memory::ScratchBackend;
use crate::tiles::{
    parse_hex_rgba8, TileCoord, TileData, TileFormat, TileKind, TileStorage, TILE_SIZE,
};
use crate::types::CameraState;
use bytemuck::{Pod, Zeroable};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

pub const TILE_CODEC_EMPTY: u8 = 0;
pub const TILE_CODEC_RAW: u8 = 1;
pub const TILE_CODEC_LZ4: u8 = 2;
pub const TILE_CODEC_SOLID: u8 = 3;
pub const TILE_CODEC_SUBRECT_LZ4: u8 = 4;
pub const TILE_PACKET_HEADER_BYTES: usize = 14;
pub const TILE_SUBRECT_HEADER_BYTES: usize = 6;
pub const TILE_BYTES_1BIT: usize = 8192;
pub const TILE_BYTES_8BIT: usize = 65536;
pub const TILE_BYTES_32BIT: usize = 262_144;

/// A single point streamed from a remote collaborator's live stroke chunk.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteStrokePoint {
    pub x: f32,
    pub y: f32,
    #[serde(default = "default_one")]
    pub pressure: f32,
}

fn default_one() -> f32 {
    1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteStrokeStartParams {
    pub peer_id: String,
    pub stroke_id: String,
    pub layer_id: LayerId,
    #[serde(default = "default_black")]
    pub color: String,
    #[serde(default = "default_size")]
    pub size: f32,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default = "default_hardness")]
    pub hardness: f32,
    #[serde(default)]
    pub is_eraser: bool,
    #[serde(default = "default_true")]
    pub use_pressure_size: bool,
}

fn default_black() -> String {
    "#000000".to_string()
}
fn default_size() -> f32 {
    12.0
}
fn default_hardness() -> f32 {
    0.85
}
fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppliedTileDeltaInfo {
    pub layer_id: LayerId,
    pub tx: i32,
    pub ty: i32,
    pub codec: u8,
    pub cleared: bool,
}

// ============================================================================
// Direct Binary Wire Tile Delta Codec (100% Parity with src-tauri/src/server.rs)
// ============================================================================

fn format_code_of(fmt: TileFormat) -> u8 {
    match fmt {
        TileFormat::Monochrome1Bit => 1,
        TileFormat::Grayscale8Bit => 2,
        TileFormat::Color32Bit | TileFormat::Rgba16Float | TileFormat::Height16Float => 4,
    }
}

fn format_from_code(code: u8) -> Option<TileFormat> {
    match code {
        1 => Some(TileFormat::Monochrome1Bit),
        2 => Some(TileFormat::Grayscale8Bit),
        4 => Some(TileFormat::Color32Bit),
        _ => None,
    }
}

fn expected_tile_bytes(code: u8) -> Option<usize> {
    match code {
        1 => Some(TILE_BYTES_1BIT),
        2 => Some(TILE_BYTES_8BIT),
        4 => Some(TILE_BYTES_32BIT),
        _ => None,
    }
}

/// Encodes one tile `(coord)` of `layer_id` straight into a wire-format `tilePacket`
/// (`14-byte header + body`: `EMPTY`, `SOLID`, `LZ4`, or `RAW`).
pub fn encode_tile_delta_packet(
    doc: &Document,
    layer_id: &str,
    coord: TileCoord,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
    let layer = doc
        .layer(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    let fmt_code = format_code_of(layer.grid.format);

    let Some(tile) = layer.grid.tiles.get(&coord) else {
        let mut pkt = Vec::with_capacity(TILE_PACKET_HEADER_BYTES);
        pkt.extend_from_slice(&coord.tx.to_le_bytes());
        pkt.extend_from_slice(&coord.ty.to_le_bytes());
        pkt.push(fmt_code);
        pkt.extend_from_slice(&0u32.to_le_bytes());
        pkt.push(TILE_CODEC_EMPTY);
        return Ok(pkt);
    };

    let ver = (tile.version & 0xFFFF_FFFF) as u32;
    let mut pkt = Vec::with_capacity(TILE_PACKET_HEADER_BYTES + 1024);
    pkt.extend_from_slice(&coord.tx.to_le_bytes());
    pkt.extend_from_slice(&coord.ty.to_le_bytes());
    pkt.push(fmt_code);
    pkt.extend_from_slice(&ver.to_le_bytes());

    match &tile.storage {
        TileStorage::SolidColor { rgba8, .. } => {
            if rgba8[3] == 0 {
                pkt.push(TILE_CODEC_EMPTY);
                return Ok(pkt);
            }
            pkt.push(TILE_CODEC_SOLID);
            match fmt_code {
                1 => pkt.push(if rgba8[3] >= 128 { 0xff } else { 0x00 }),
                2 => pkt.push(rgba8[3]),
                _ => pkt.extend_from_slice(rgba8),
            }
            Ok(pkt)
        }
        TileStorage::CompressedLz4 { compressed, .. } if tile.format == layer.grid.format => {
            pkt.push(TILE_CODEC_LZ4);
            pkt.extend_from_slice(compressed);
            Ok(pkt)
        }
        _ => {
            let raw = match layer.grid.format {
                TileFormat::Monochrome1Bit | TileFormat::Grayscale8Bit => {
                    tile.materialize_raw(scratch)?
                }
                _ => tile.to_rgba8(scratch, false)?,
            };
            // Fast solid check before LZ4
            if fmt_code == 4 && raw.len() == TILE_BYTES_32BIT {
                let first = &raw[0..4];
                if raw.as_chunks::<4>().0.iter().all(|px| px.as_slice() == first) {
                    if first[3] == 0 {
                        pkt.push(TILE_CODEC_EMPTY);
                    } else {
                        pkt.push(TILE_CODEC_SOLID);
                        pkt.extend_from_slice(first);
                    }
                    return Ok(pkt);
                }
            }
            let comp = lz4_flex::block::compress(&raw);
            if comp.len() < raw.len() {
                pkt.push(TILE_CODEC_LZ4);
                pkt.extend_from_slice(&comp);
            } else {
                pkt.push(TILE_CODEC_RAW);
                pkt.extend_from_slice(&raw);
            }
            Ok(pkt)
        }
    }
}

/// Encodes multiple tiles of `layer_id` in parallel (or all occupied tiles when `coords == None`).
pub fn encode_layer_tile_packets(
    doc: &Document,
    layer_id: &str,
    coords: Option<&[TileCoord]>,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<Vec<u8>>, String> {
    let layer = doc
        .layer(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    let target_coords: Vec<TileCoord> = match coords {
        Some(list) => list.to_vec(),
        None => layer.grid.tiles.keys().copied().collect(),
    };
    target_coords
        .par_iter()
        .map(|&c| encode_tile_delta_packet(doc, layer_id, c, scratch))
        .collect()
}

/// Decodes a wire-format `tilePacket` (`14-byte header + body`: `EMPTY` / `RAW` / `LZ4` / `SOLID` /
/// `SUBRECT_LZ4`) directly into `Document`'s `SparseLayerGrid` and increments `remote_epochs`!
pub fn apply_tile_delta_packet(
    doc: &mut Document,
    layer_id: &str,
    tile_packet: &[u8],
    bump_remote_epoch: bool,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<AppliedTileDeltaInfo, String> {
    if tile_packet.len() < TILE_PACKET_HEADER_BYTES {
        return Err("Tile packet shorter than 14-byte header".to_string());
    }
    let tx = i32::from_le_bytes([tile_packet[0], tile_packet[1], tile_packet[2], tile_packet[3]]);
    let ty = i32::from_le_bytes([tile_packet[4], tile_packet[5], tile_packet[6], tile_packet[7]]);
    let fmt_code = tile_packet[8];
    let _version = u32::from_le_bytes([
        tile_packet[9],
        tile_packet[10],
        tile_packet[11],
        tile_packet[12],
    ]);
    let codec = tile_packet[13];
    let body = &tile_packet[TILE_PACKET_HEADER_BYTES..];
    let coord = TileCoord::new(tx, ty);

    let tile_fmt =
        format_from_code(fmt_code).ok_or_else(|| format!("Unknown tile format code: {fmt_code}"))?;
    let expected_len = expected_tile_bytes(fmt_code).unwrap();

    let layer = doc
        .layer_mut(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;

    let cleared = match codec {
        TILE_CODEC_EMPTY => {
            layer.grid.remove_tile(coord);
            true
        }
        TILE_CODEC_SOLID => {
            let rgba = match fmt_code {
                1 => {
                    let b = *body.first().ok_or("Empty 1-bit solid body")?;
                    if b == 0 {
                        [0, 0, 0, 0]
                    } else {
                        [0, 0, 0, 255]
                    }
                }
                2 => {
                    let v = *body.first().ok_or("Empty 8-bit solid body")?;
                    [v, v, v, v]
                }
                4 => {
                    if body.len() < 4 {
                        return Err("Truncated 32-bit solid tile body".to_string());
                    }
                    [body[0], body[1], body[2], body[3]]
                }
                _ => return Err("Unsupported solid format".to_string()),
            };
            if rgba[3] == 0 {
                layer.grid.remove_tile(coord);
                true
            } else {
                let td = TileData::new_solid(tile_fmt, TileKind::Raster, rgba);
                layer.grid.set_tile(coord, Arc::new(td));
                false
            }
        }
        TILE_CODEC_RAW => {
            if body.len() != expected_len {
                return Err(format!(
                    "RAW tile size mismatch: got {}, expected {}",
                    body.len(),
                    expected_len
                ));
            }
            let td = TileData::from_raw_auto_compact(tile_fmt, TileKind::Raster, body.to_vec());
            if td.is_empty(scratch) {
                layer.grid.remove_tile(coord);
                true
            } else {
                layer.grid.set_tile(coord, Arc::new(td));
                false
            }
        }
        TILE_CODEC_LZ4 => {
            let raw = lz4_flex::block::decompress(body, expected_len)
                .map_err(|e| format!("LZ4 tile decompress failed: {e}"))?;
            if raw.len() != expected_len {
                return Err(format!(
                    "LZ4 tile size mismatch: got {}, expected {}",
                    raw.len(),
                    expected_len
                ));
            }
            let td = TileData::from_raw_auto_compact(tile_fmt, TileKind::Raster, raw);
            if td.is_empty(scratch) {
                layer.grid.remove_tile(coord);
                true
            } else {
                layer.grid.set_tile(coord, Arc::new(td));
                false
            }
        }
        TILE_CODEC_SUBRECT_LZ4 => {
            if body.len() < TILE_SUBRECT_HEADER_BYTES + 1 {
                return Err("Truncated SUBRECT_LZ4 header".to_string());
            }
            let rx = body[0] as usize;
            let ry = body[1] as usize;
            let rw = u16::from_le_bytes([body[2], body[3]]) as usize;
            let rh = u16::from_le_bytes([body[4], body[5]]) as usize;
            if rw == 0 || rh == 0 || rx + rw > TILE_SIZE || ry + rh > TILE_SIZE {
                return Err("Invalid SUBRECT_LZ4 bounds".to_string());
            }
            let (row_bytes, stride, col_off) = match fmt_code {
                1 => (rw >> 3, 32usize, rx >> 3),
                2 => (rw, 256usize, rx),
                4 => (rw * 4, 1024usize, rx * 4),
                _ => return Err("Unsupported subrect format".to_string()),
            };
            let expected_sub = row_bytes * rh;
            let sub_raw = lz4_flex::block::decompress(&body[TILE_SUBRECT_HEADER_BYTES..], expected_sub)
                .map_err(|e| format!("SUBRECT_LZ4 decompress failed: {e}"))?;
            if sub_raw.len() != expected_sub {
                return Err(format!(
                    "SUBRECT_LZ4 size mismatch: got {}, expected {}",
                    sub_raw.len(),
                    expected_sub
                ));
            }

            let mut base_raw = match layer.grid.tiles.get(&coord) {
                Some(t) => {
                    if t.format == tile_fmt {
                        t.materialize_raw(scratch)?
                    } else {
                        let rgba = t.to_rgba8(scratch, false)?;
                        crate::tiles::convert_tile_bytes(
                            &rgba,
                            TileFormat::Color32Bit,
                            tile_fmt,
                            layer.meta.mono_threshold.unwrap_or(128),
                            false,
                        )
                    }
                }
                None => vec![0u8; expected_len],
            };
            if base_raw.len() != expected_len {
                base_raw.resize(expected_len, 0);
            }
            for r in 0..rh {
                let dst_off = (ry + r) * stride + col_off;
                let src_off = r * row_bytes;
                base_raw[dst_off..dst_off + row_bytes]
                    .copy_from_slice(&sub_raw[src_off..src_off + row_bytes]);
            }
            let td = TileData::from_raw_auto_compact(tile_fmt, TileKind::Raster, base_raw);
            if td.is_empty(scratch) {
                layer.grid.remove_tile(coord);
                true
            } else {
                layer.grid.set_tile(coord, Arc::new(td));
                false
            }
        }
        other => return Err(format!("Unknown tile codec: {other}")),
    };

    if bump_remote_epoch {
        let ep = layer.grid.remote_epochs.entry(coord).or_insert(0);
        *ep = ep.saturating_add(1);
    }
    doc.dirty_for_render = true;

    Ok(AppliedTileDeltaInfo {
        layer_id: layer_id.to_string(),
        tx,
        ty,
        codec,
        cleared,
    })
}

/// Encodes a layer's non-destructive 8-bit mask as compact `[flags: u8, width: u32 LE, height: u32 LE, default: u8, lz4_bytes...]`.
pub fn encode_layer_mask_packet(
    doc: &Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
    let layer = doc
        .layer(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    let w = doc.dimensions.width;
    let h = doc.dimensions.height;
    let rect = crate::tiles::RectI32::new(0, 0, w, h);
    let mask8 = layer.grid.read_mask8_rect(rect, scratch)?;
    let comp = lz4_flex::block::compress(&mask8);
    let mut out = Vec::with_capacity(10 + comp.len());
    out.push(0x01); // MASK_FLAG_FULL_REPLACE
    out.extend_from_slice(&w.to_le_bytes());
    out.extend_from_slice(&h.to_le_bytes());
    out.push(layer.grid.mask_default_value);
    out.extend_from_slice(&comp);
    Ok(out)
}

/// Applies an encoded 8-bit layer mask packet directly onto `Document`'s sparse mask tiles!
pub fn apply_layer_mask_packet(
    doc: &mut Document,
    layer_id: &str,
    packet: &[u8],
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(), String> {
    if packet.len() < 10 {
        return Err("Layer mask packet too short".to_string());
    }
    let w = u32::from_le_bytes([packet[1], packet[2], packet[3], packet[4]]);
    let h = u32::from_le_bytes([packet[5], packet[6], packet[7], packet[8]]);
    let default_v = packet[9];
    let expected = (w as usize).saturating_mul(h as usize);
    let raw = lz4_flex::block::decompress(&packet[10..], expected)
        .map_err(|e| format!("Mask LZ4 decompress failed: {e}"))?;
    let layer = doc
        .layer_mut(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    layer.meta.has_mask = true;
    layer.grid.has_mask = true;
    layer.grid.mask_default_value = default_v;
    layer.grid.mask_tiles.clear();
    let rect = crate::tiles::RectI32::new(0, 0, w, h);
    layer.grid.write_mask8_rect(&raw, rect, scratch)?;
    layer.meta.mask_version = Some(layer.grid.layer_version);
    doc.dirty_for_render = true;
    Ok(())
}

/// Deterministic FNV-1a 64-bit state checksum across layer metadata + sparse tile pixels
/// for instant multiplayer drift detection (zero canvas readbacks!).
pub fn compute_document_checksum(doc: &Document, scratch: Option<&dyn ScratchBackend>) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mix = |acc: &mut u64, bytes: &[u8]| {
        for &b in bytes {
            *acc ^= b as u64;
            *acc = acc.wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    mix(&mut h, &doc.dimensions.width.to_le_bytes());
    mix(&mut h, &doc.dimensions.height.to_le_bytes());
    for layer in &doc.layers {
        mix(&mut h, layer.meta.id.as_bytes());
        mix(&mut h, &[u8::from(layer.meta.visible)]);
        mix(&mut h, &layer.meta.opacity.to_bits().to_le_bytes());
        let mut coords: Vec<TileCoord> = layer.grid.tiles.keys().copied().collect();
        coords.sort_by_key(|c| (c.ty, c.tx));
        for c in coords {
            mix(&mut h, &c.tx.to_le_bytes());
            mix(&mut h, &c.ty.to_le_bytes());
            if let Some(t) = layer.grid.tiles.get(&c) {
                match &t.storage {
                    TileStorage::SolidColor { rgba8, .. } => mix(&mut h, rgba8),
                    _ => {
                        if let Ok(rgba) = t.to_rgba8(scratch, false) {
                            // Sample deterministic stride for O(1) sub-ms hashing of 4K/8K docs
                            for chunk in rgba.chunks(64) {
                                mix(&mut h, &chunk[..chunk.len().min(4)]);
                            }
                        }
                    }
                }
            }
        }
    }
    format!("{h:016x}")
}

// ============================================================================
// Per-Peer DX12 GPU Live Draft Layers (`RemotePeerDraftManager`)
// ============================================================================

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct RemoteDabUniforms {
    tile_origin_doc: [f32; 2],
    _pad: [f32; 2],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct RemoteDabInst {
    center_doc: [f32; 2],
    radius: f32,
    hardness: f32,
    color_rgba: [f32; 4],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct RemoteProjectUniforms {
    viewport_size_phys: [f32; 2],
    doc_size: [f32; 2],
    pan_css: [f32; 2],
    zoom: f32,
    rotation_rad: f32,
    flip: [f32; 2],
    dpr: f32,
    opacity: f32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct RemoteTileInst {
    tile_origin_doc: [f32; 2],
    slot_f: f32,
    _pad: f32,
}

const REMOTE_DRAFT_DAB_WGSL: &str = r#"
struct RemoteDabUniforms {
    tile_origin_doc: vec2<f32>,
    _pad: vec2<f32>,
};
@group(0) @binding(0) var<uniform> u: RemoteDabUniforms;

struct Inst {
    @location(0) center_doc: vec2<f32>,
    @location(1) radius: f32,
    @location(2) hardness: f32,
    @location(3) color_rgba: vec4<f32>,
};

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) local_px: vec2<f32>,
    @location(1) radius: f32,
    @location(2) hardness: f32,
    @location(3) color_rgba: vec4<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) vid: u32, inst: Inst) -> VsOut {
    var corner: vec2<f32>;
    switch (vid) {
        case 0u: { corner = vec2<f32>(-1.0, -1.0); }
        case 1u: { corner = vec2<f32>( 1.0, -1.0); }
        case 2u: { corner = vec2<f32>(-1.0,  1.0); }
        case 3u: { corner = vec2<f32>(-1.0,  1.0); }
        case 4u: { corner = vec2<f32>( 1.0, -1.0); }
        default: { corner = vec2<f32>( 1.0,  1.0); }
    }
    let ext = inst.radius + 1.5;
    let lp = corner * ext;
    let tile_px = (inst.center_doc + lp) - u.tile_origin_doc;
    let ndc = vec2<f32>((tile_px.x / 256.0) * 2.0 - 1.0, 1.0 - (tile_px.y / 256.0) * 2.0);
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.local_px = lp;
    out.radius = max(inst.radius, 0.5);
    out.hardness = clamp(inst.hardness, 0.0, 1.0);
    out.color_rgba = inst.color_rgba;
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    let d = length(in.local_px);
    if (d >= in.radius + 0.5) {
        discard;
    }
    let inner = in.radius * in.hardness * 0.9;
    let a = (1.0 - smoothstep(inner, in.radius + 0.5, d)) * in.color_rgba.a;
    if (a <= 0.001) {
        discard;
    }
    return vec4<f32>(in.color_rgba.rgb * a, a);
}
"#;

const REMOTE_DRAFT_PROJECT_WGSL: &str = r#"
struct RemoteProjectUniforms {
    viewport_size_phys: vec2<f32>,
    doc_size: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    opacity: f32,
};

@group(0) @binding(0) var<uniform> u: RemoteProjectUniforms;
@group(0) @binding(1) var draft_atlas: texture_2d_array<f32>;
@group(0) @binding(2) var draft_sampler: sampler;

struct TileInst {
    @location(0) tile_origin_doc: vec2<f32>,
    @location(1) slot_f: f32,
    @location(2) _pad: f32,
};

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
    @location(1) doc_coord: vec2<f32>,
    @location(2) @interpolate(flat) slot_i: i32,
};

@vertex
fn vs_main(@builtin(vertex_index) vid: u32, inst: TileInst) -> VsOut {
    var uv: vec2<f32>;
    switch (vid) {
        case 0u: { uv = vec2<f32>(0.0, 0.0); }
        case 1u: { uv = vec2<f32>(1.0, 0.0); }
        case 2u: { uv = vec2<f32>(0.0, 1.0); }
        case 3u: { uv = vec2<f32>(0.0, 1.0); }
        case 4u: { uv = vec2<f32>(1.0, 0.0); }
        default: { uv = vec2<f32>(1.0, 1.0); }
    }
    let doc_pos = inst.tile_origin_doc + uv * 256.0;
    let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
    let c = cos(u.rotation_rad);
    let s = sin(u.rotation_rad);
    let rot = vec2<f32>(centered.x * c - centered.y * s, centered.x * s + centered.y * c);
    let screen_phys = (u.pan_css + rot * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = uv;
    out.doc_coord = doc_pos;
    out.slot_i = i32(round(inst.slot_f));
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    if (in.doc_coord.x < 0.0 || in.doc_coord.y < 0.0 ||
        in.doc_coord.x >= u.doc_size.x || in.doc_coord.y >= u.doc_size.y) {
        discard;
    }
    let suv = clamp(in.uv, vec2<f32>(0.5 / 256.0), vec2<f32>(255.5 / 256.0));
    let px = textureSampleLevel(draft_atlas, draft_sampler, suv, in.slot_i, 0.0);
    if (px.a <= 0.001) {
        discard;
    }
    return px * u.opacity;
}
"#;

struct PeerStrokeDraft {
    peer_id: String,
    stroke_id: String,
    layer_id: LayerId,
    color_rgb: [f32; 3],
    size: f32,
    opacity: f32,
    hardness: f32,
    is_eraser: bool,
    use_pressure_size: bool,
    last_point: Option<RemoteStrokePoint>,
    carry_dist: f32,
    awaiting_tiles: Option<(u32, Instant)>,
    tile_slots: HashMap<TileCoord, u32>,
}

/// Manages sparse GPU draft tiles for all live remote peers' in-progress strokes on DX12!
pub struct RemotePeerDraftManager {
    atlas_tex: wgpu::Texture,
    atlas_view: wgpu::TextureView,
    slice_views: Vec<wgpu::TextureView>,
    free_slots: Vec<u32>,
    capacity: u32,

    dab_bgl: wgpu::BindGroupLayout,
    dab_pipeline: wgpu::RenderPipeline,
    dab_uniform_buf: wgpu::Buffer,
    dab_uniform_cap_slots: usize,
    dab_bg: wgpu::BindGroup,
    dab_inst_buf: wgpu::Buffer,
    dab_inst_cap: usize,

    proj_bgl: wgpu::BindGroupLayout,
    proj_pipeline: wgpu::RenderPipeline,
    proj_uniform_buf: wgpu::Buffer,
    proj_uniform_cap_slots: usize,
    proj_bg: wgpu::BindGroup,
    proj_inst_buf: wgpu::Buffer,
    proj_inst_cap: usize,
    uniform_slot_align: u32,
    sampler: wgpu::Sampler,

    sessions: HashMap<(String, String), PeerStrokeDraft>,
}

impl RemotePeerDraftManager {
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
        let capacity = 128u32.min(device.limits().max_texture_array_layers.max(16));
        let atlas_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-collab-remote-draft-atlas"),
            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::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let atlas_view = atlas_tex.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(capacity),
            ..Default::default()
        });
        let mut slice_views = Vec::with_capacity(capacity as usize);
        let mut free_slots = Vec::with_capacity(capacity as usize);
        for i in 0..capacity {
            slice_views.push(atlas_tex.create_view(&wgpu::TextureViewDescriptor {
                dimension: Some(wgpu::TextureViewDimension::D2),
                base_array_layer: i,
                array_layer_count: Some(1),
                ..Default::default()
            }));
            free_slots.push(capacity - 1 - i);
        }

        let uniform_slot_align = device.limits().min_uniform_buffer_offset_alignment.max(256);

        let dab_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-collab-dab-bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: true,
                    min_binding_size: std::num::NonZeroU64::new(
                        std::mem::size_of::<RemoteDabUniforms>() as u64,
                    ),
                },
                count: None,
            }],
        });
        let dab_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-collab-dab-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(REMOTE_DRAFT_DAB_WGSL)),
        });
        let dab_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-collab-dab-pl"),
            bind_group_layouts: &[Some(&dab_bgl)],
            immediate_size: 0,
        });
        let dab_vlayout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<RemoteDabInst>() as u64,
            step_mode: wgpu::VertexStepMode::Instance,
            attributes: &[
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x2,
                },
                wgpu::VertexAttribute {
                    offset: 8,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32,
                },
                wgpu::VertexAttribute {
                    offset: 12,
                    shader_location: 2,
                    format: wgpu::VertexFormat::Float32,
                },
                wgpu::VertexAttribute {
                    offset: 16,
                    shader_location: 3,
                    format: wgpu::VertexFormat::Float32x4,
                },
            ],
        };
        let dab_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-collab-dab-pipeline"),
            layout: Some(&dab_pl),
            vertex: wgpu::VertexState {
                module: &dab_shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(dab_vlayout)],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &dab_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let dab_uniform_cap_slots = 64usize;
        let dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-collab-dab-uniforms"),
            size: (dab_uniform_cap_slots as u64) * (uniform_slot_align as u64),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ink-collab-dab-bg"),
            layout: &dab_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                    buffer: &dab_uniform_buf,
                    offset: 0,
                    size: std::num::NonZeroU64::new(
                        std::mem::size_of::<RemoteDabUniforms>() as u64,
                    ),
                }),
            }],
        });
        let dab_inst_cap = 2048usize;
        let dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-collab-dab-insts"),
            size: (dab_inst_cap * std::mem::size_of::<RemoteDabInst>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let proj_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-collab-proj-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: std::num::NonZeroU64::new(
                            std::mem::size_of::<RemoteProjectUniforms>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let proj_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-collab-proj-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(REMOTE_DRAFT_PROJECT_WGSL)),
        });
        let proj_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-collab-proj-pl"),
            bind_group_layouts: &[Some(&proj_bgl)],
            immediate_size: 0,
        });
        let proj_vlayout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<RemoteTileInst>() as u64,
            step_mode: wgpu::VertexStepMode::Instance,
            attributes: &[
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x2,
                },
                wgpu::VertexAttribute {
                    offset: 8,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32,
                },
                wgpu::VertexAttribute {
                    offset: 12,
                    shader_location: 2,
                    format: wgpu::VertexFormat::Float32,
                },
            ],
        };
        let proj_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-collab-proj-pipeline"),
            layout: Some(&proj_pl),
            vertex: wgpu::VertexState {
                module: &proj_shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(proj_vlayout)],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &proj_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let proj_uniform_cap_slots = 32usize;
        let proj_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-collab-proj-uniforms"),
            size: (proj_uniform_cap_slots as u64) * (uniform_slot_align as u64),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let proj_inst_cap = 256usize;
        let proj_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-collab-proj-insts"),
            size: (proj_inst_cap * std::mem::size_of::<RemoteTileInst>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-collab-draft-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        let proj_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ink-collab-proj-bg"),
            layout: &proj_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &proj_uniform_buf,
                        offset: 0,
                        size: std::num::NonZeroU64::new(
                            std::mem::size_of::<RemoteProjectUniforms>() as u64,
                        ),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        });

        Self {
            atlas_tex,
            atlas_view,
            slice_views,
            free_slots,
            capacity,
            dab_bgl,
            dab_pipeline,
            dab_uniform_buf,
            dab_uniform_cap_slots,
            dab_bg,
            dab_inst_buf,
            dab_inst_cap,
            proj_bgl,
            proj_pipeline,
            proj_uniform_buf,
            proj_uniform_cap_slots,
            proj_bg,
            proj_inst_buf,
            proj_inst_cap,
            uniform_slot_align,
            sampler,
            sessions: HashMap::new(),
        }
    }

    pub fn active_session_count(&self) -> usize {
        self.sessions.len()
    }

    pub fn has_active_drafts(&self) -> bool {
        self.sessions.values().any(|s| !s.tile_slots.is_empty())
    }

    pub fn start_stroke(&mut self, params: RemoteStrokeStartParams) {
        let key = (params.peer_id.clone(), params.stroke_id.clone());
        if let Some(old) = self.sessions.remove(&key) {
            self.free_slots.extend(old.tile_slots.into_values());
        }
        let rgba = parse_hex_rgba8(&params.color).unwrap_or([0, 0, 0, 255]);
        let color_rgb = if params.is_eraser {
            [1.0, 1.0, 1.0]
        } else {
            [
                rgba[0] as f32 / 255.0,
                rgba[1] as f32 / 255.0,
                rgba[2] as f32 / 255.0,
            ]
        };
        self.sessions.insert(
            key,
            PeerStrokeDraft {
                peer_id: params.peer_id,
                stroke_id: params.stroke_id,
                layer_id: params.layer_id,
                color_rgb,
                size: params.size.clamp(1.0, 1024.0),
                opacity: params.opacity.clamp(0.01, 1.0),
                hardness: params.hardness.clamp(0.0, 1.0),
                is_eraser: params.is_eraser,
                use_pressure_size: params.use_pressure_size,
                last_point: None,
                carry_dist: 0.0,
                awaiting_tiles: None,
                tile_slots: HashMap::new(),
            },
        );
    }

    /// Stamps incoming remote peer stroke chunk points directly into sparse DX12 GPU draft tiles!
    pub fn push_chunk(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        peer_id: &str,
        stroke_id: &str,
        points: &[RemoteStrokePoint],
    ) {
        if points.is_empty() {
            return;
        }
        let key = (peer_id.to_string(), stroke_id.to_string());
        let Some(sess) = self.sessions.get_mut(&key) else {
            return;
        };

        // Generate smoothly spaced dabs along the remote polyline
        let mut dabs: Vec<RemoteDabInst> = Vec::with_capacity(points.len() * 4);
        let alpha_per_dab = if sess.is_eraser { 0.45 } else { 0.85 };
        for &pt in points {
            let p_scale = if sess.use_pressure_size {
                pt.pressure.clamp(0.08, 1.0)
            } else {
                1.0
            };
            let radius = (sess.size * p_scale * 0.5).max(0.75);
            if let Some(prev) = sess.last_point {
                let dx = pt.x - prev.x;
                let dy = pt.y - prev.y;
                let dist = dx.hypot(dy);
                let step = (radius * 0.35).max(1.0);
                let mut d = step - sess.carry_dist;
                while d <= dist {
                    let t = if dist > 1e-4 { d / dist } else { 1.0 };
                    let lp = prev.pressure + (pt.pressure - prev.pressure) * t;
                    let lr = if sess.use_pressure_size {
                        (sess.size * lp.clamp(0.08, 1.0) * 0.5).max(0.75)
                    } else {
                        radius
                    };
                    dabs.push(RemoteDabInst {
                        center_doc: [prev.x + dx * t, prev.y + dy * t],
                        radius: lr,
                        hardness: sess.hardness,
                        color_rgba: [
                            sess.color_rgb[0],
                            sess.color_rgb[1],
                            sess.color_rgb[2],
                            alpha_per_dab,
                        ],
                    });
                    d += step;
                }
                sess.carry_dist = (dist - (d - step)).max(0.0);
            } else {
                dabs.push(RemoteDabInst {
                    center_doc: [pt.x, pt.y],
                    radius,
                    hardness: sess.hardness,
                    color_rgba: [
                        sess.color_rgb[0],
                        sess.color_rgb[1],
                        sess.color_rgb[2],
                        alpha_per_dab,
                    ],
                });
            }
            sess.last_point = Some(pt);
        }

        if dabs.is_empty() {
            return;
        }

        // Bin dabs into sparse 256×256 tiles
        let mut bins: HashMap<TileCoord, Vec<RemoteDabInst>> = HashMap::new();
        for &dab in &dabs {
            let r = dab.radius + 2.0;
            let tx0 = ((dab.center_doc[0] - r).floor() as i32).div_euclid(TILE_SIZE as i32);
            let ty0 = ((dab.center_doc[1] - r).floor() as i32).div_euclid(TILE_SIZE as i32);
            let tx1 = ((dab.center_doc[0] + r).ceil() as i32).div_euclid(TILE_SIZE as i32);
            let ty1 = ((dab.center_doc[1] + r).ceil() as i32).div_euclid(TILE_SIZE as i32);
            for ty in ty0..=ty1 {
                for tx in tx0..=tx1 {
                    bins.entry(TileCoord::new(tx, ty)).or_default().push(dab);
                }
            }
        }

        // Pack all binned tiles' instances & uniforms into ONE encoder + ONE queue.submit!
        struct TileStampJob {
            slot: u32,
            is_new: bool,
            coord: TileCoord,
            inst_start: usize,
            inst_count: u32,
        }
        let mut jobs: Vec<TileStampJob> = Vec::with_capacity(bins.len());
        let mut packed_insts: Vec<RemoteDabInst> = Vec::new();
        for (coord, list) in bins {
            if list.is_empty() {
                continue;
            }
            let (slot, is_new) = if let Some(&s) = sess.tile_slots.get(&coord) {
                (s, false)
            } else if let Some(s) = self.free_slots.pop() {
                sess.tile_slots.insert(coord, s);
                (s, true)
            } else {
                continue;
            };
            let inst_start = packed_insts.len();
            let inst_count = list.len() as u32;
            packed_insts.extend_from_slice(&list);
            jobs.push(TileStampJob {
                slot,
                is_new,
                coord,
                inst_start,
                inst_count,
            });
        }
        if jobs.is_empty() {
            return;
        }

        if packed_insts.len() > self.dab_inst_cap {
            self.dab_inst_cap = packed_insts.len().next_power_of_two();
            self.dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-collab-dab-insts"),
                size: (self.dab_inst_cap * std::mem::size_of::<RemoteDabInst>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        queue.write_buffer(&self.dab_inst_buf, 0, bytemuck::cast_slice(&packed_insts));

        let stride = self.uniform_slot_align as usize;
        let u_size = std::mem::size_of::<RemoteDabUniforms>();
        if jobs.len() > self.dab_uniform_cap_slots {
            self.dab_uniform_cap_slots = jobs.len().next_power_of_two();
            self.dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-collab-dab-uniforms"),
                size: (self.dab_uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-collab-dab-bg"),
                layout: &self.dab_bgl,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.dab_uniform_buf,
                        offset: 0,
                        size: std::num::NonZeroU64::new(u_size as u64),
                    }),
                }],
            });
        }
        let mut uniform_staging = vec![0u8; jobs.len() * stride];
        for (idx, job) in jobs.iter().enumerate() {
            let u = RemoteDabUniforms {
                tile_origin_doc: [
                    (job.coord.tx * TILE_SIZE as i32) as f32,
                    (job.coord.ty * TILE_SIZE as i32) as f32,
                ],
                _pad: [0.0, 0.0],
            };
            let dst = idx * stride;
            uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
        }
        queue.write_buffer(&self.dab_uniform_buf, 0, &uniform_staging);

        let inst_stride = std::mem::size_of::<RemoteDabInst>() as u64;
        let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-collab-dab-enc"),
        });
        for (idx, job) in jobs.iter().enumerate() {
            let dyn_off = (idx as u32) * self.uniform_slot_align;
            let byte_start = (job.inst_start as u64) * inst_stride;
            let byte_end = byte_start + (job.inst_count as u64) * inst_stride;
            let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("ink-collab-dab-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &self.slice_views[job.slot as usize],
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: if job.is_new {
                            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
                        } else {
                            wgpu::LoadOp::Load
                        },
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.dab_pipeline);
            pass.set_bind_group(0, &self.dab_bg, &[dyn_off]);
            pass.set_vertex_buffer(0, self.dab_inst_buf.slice(byte_start..byte_end));
            pass.draw(0..6, 0..job.inst_count);
        }
        queue.submit(Some(enc.finish()));
    }

    /// Transitions a finished remote stroke into zero-flicker handoff until its committed tile deltas arrive.
    pub fn finish_stroke(&mut self, peer_id: &str, stroke_id: &str, expected_tile_count: u32) {
        let key = (peer_id.to_string(), stroke_id.to_string());
        if expected_tile_count == 0 {
            self.dispose_stroke(peer_id, stroke_id);
            return;
        }
        if let Some(sess) = self.sessions.get_mut(&key) {
            sess.awaiting_tiles = Some((expected_tile_count, Instant::now()));
        }
    }

    /// Notifies awaiting remote draft sessions when a committed tile delta lands for `layer_id`.
    pub fn notify_tile_delta_landed(&mut self, layer_id: &str) {
        let mut to_remove = Vec::new();
        let now = Instant::now();
        for (key, sess) in self.sessions.iter_mut() {
            if let Some((ref mut rem, finished_at)) = sess.awaiting_tiles {
                if sess.layer_id == layer_id {
                    *rem = rem.saturating_sub(1);
                }
                if *rem == 0 || now.duration_since(finished_at) > Duration::from_secs(3) {
                    to_remove.push(key.clone());
                }
            }
        }
        for key in to_remove {
            if let Some(old) = self.sessions.remove(&key) {
                self.free_slots.extend(old.tile_slots.into_values());
            }
        }
    }

    pub fn dispose_stroke(&mut self, peer_id: &str, stroke_id: &str) {
        if let Some(old) = self
            .sessions
            .remove(&(peer_id.to_string(), stroke_id.to_string()))
        {
            self.free_slots.extend(old.tile_slots.into_values());
        }
    }

    pub fn dispose_peer(&mut self, peer_id: &str) {
        let keys: Vec<(String, String)> = self
            .sessions
            .keys()
            .filter(|(p, _)| p == peer_id)
            .cloned()
            .collect();
        for k in keys {
            if let Some(old) = self.sessions.remove(&k) {
                self.free_slots.extend(old.tile_slots.into_values());
            }
        }
    }

    pub fn clear_all(&mut self) {
        for (_, old) in self.sessions.drain() {
            self.free_slots.extend(old.tile_slots.into_values());
        }
    }

    /// Encodes all active remote peer GPU draft strokes directly into `encoder` (zero extra `queue.submit`!).
    #[allow(clippy::too_many_arguments)]
    pub fn encode_drafts(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        doc_w: u32,
        doc_h: u32,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        // Expire any stale awaiting sessions cleanly
        let now = Instant::now();
        let expired: Vec<(String, String)> = self
            .sessions
            .iter()
            .filter(|(_, s)| {
                s.awaiting_tiles
                    .is_some_and(|(_, t)| now.duration_since(t) > Duration::from_secs(3))
            })
            .map(|(k, _)| k.clone())
            .collect();
        for k in expired {
            if let Some(old) = self.sessions.remove(&k) {
                self.free_slots.extend(old.tile_slots.into_values());
            }
        }

        if self.sessions.is_empty() || vp_w == 0 || vp_h == 0 {
            return;
        }

        let _ = (self.capacity, &self.atlas_tex);
        let mut packed_insts: Vec<RemoteTileInst> = Vec::new();
        let mut draw_ranges: Vec<(usize, u32, f32)> = Vec::new();
        for sess in self.sessions.values() {
            let _ = (&sess.peer_id, &sess.stroke_id);
            if sess.tile_slots.is_empty() {
                continue;
            }
            let start = packed_insts.len();
            for (&coord, &slot) in &sess.tile_slots {
                packed_insts.push(RemoteTileInst {
                    tile_origin_doc: [
                        (coord.tx * TILE_SIZE as i32) as f32,
                        (coord.ty * TILE_SIZE as i32) as f32,
                    ],
                    slot_f: slot as f32,
                    _pad: 0.0,
                });
            }
            draw_ranges.push((start, (packed_insts.len() - start) as u32, sess.opacity));
        }
        if draw_ranges.is_empty() {
            return;
        }

        if packed_insts.len() > self.proj_inst_cap {
            self.proj_inst_cap = packed_insts.len().next_power_of_two();
            self.proj_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-collab-proj-insts"),
                size: (self.proj_inst_cap * std::mem::size_of::<RemoteTileInst>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        queue.write_buffer(&self.proj_inst_buf, 0, bytemuck::cast_slice(&packed_insts));

        let stride = self.uniform_slot_align as usize;
        let u_size = std::mem::size_of::<RemoteProjectUniforms>();
        if draw_ranges.len() > self.proj_uniform_cap_slots {
            self.proj_uniform_cap_slots = draw_ranges.len().next_power_of_two();
            self.proj_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-collab-proj-uniforms"),
                size: (self.proj_uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.proj_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-collab-proj-bg"),
                layout: &self.proj_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                            buffer: &self.proj_uniform_buf,
                            offset: 0,
                            size: std::num::NonZeroU64::new(u_size as u64),
                        }),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(&self.atlas_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(&self.sampler),
                    },
                ],
            });
        }
        let mut uniform_staging = vec![0u8; draw_ranges.len() * stride];
        for (idx, &(_, _, opacity)) in draw_ranges.iter().enumerate() {
            let u = RemoteProjectUniforms {
                viewport_size_phys: [vp_w as f32, vp_h as f32],
                doc_size: [doc_w as f32, doc_h as f32],
                pan_css: [camera.pan_x, camera.pan_y],
                zoom: camera.zoom.max(0.01),
                rotation_rad: camera.rotation.to_radians(),
                flip: [
                    if camera.flip_x { -1.0 } else { 1.0 },
                    if camera.flip_y { -1.0 } else { 1.0 },
                ],
                dpr: dpr.max(0.05),
                opacity,
            };
            let dst = idx * stride;
            uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
        }
        queue.write_buffer(&self.proj_uniform_buf, 0, &uniform_staging);

        let inst_stride = std::mem::size_of::<RemoteTileInst>() as u64;
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("ink-collab-proj-pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: target_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.proj_pipeline);
        for (idx, &(start, count, _)) in draw_ranges.iter().enumerate() {
            let dyn_off = (idx as u32) * self.uniform_slot_align;
            let byte_start = (start as u64) * inst_stride;
            let byte_end = byte_start + (count as u64) * inst_stride;
            pass.set_bind_group(0, &self.proj_bg, &[dyn_off]);
            pass.set_vertex_buffer(0, self.proj_inst_buf.slice(byte_start..byte_end));
            pass.draw(0..6, 0..count);
        }
    }

    /// Composites all active remote peer GPU draft strokes directly onto `target_view` at 120+ FPS!
    #[allow(clippy::too_many_arguments)]
    pub fn render_drafts(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        doc_w: u32,
        doc_h: u32,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        if self.sessions.is_empty() || vp_w == 0 || vp_h == 0 {
            return;
        }
        let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-collab-proj-enc"),
        });
        self.encode_drafts(
            device,
            queue,
            &mut enc,
            doc_w,
            doc_h,
            camera,
            vp_w,
            vp_h,
            dpr,
            target_view,
        );
        queue.submit(Some(enc.finish()));
    }
}