Skip to content

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

20.7 KB
Raw Blame
//! 3-Slice Baked Layer Stack Cache Invalidation Tracker, Frustum Bounds,
//! LOD Selection (LOD 0..3), and Dirty-Rect Top-Left Scissor Projection.
//!
//! Computes deterministic 64-bit hashes (zero heap String allocations per frame)
//! for `below_active_cache`, `above_active_cache`, and intra-folder sibling caches.

use super::layer_tree::{
    is_node_visible, layer_has_active_mask, partition_layer_stack, CompositingUnit,
    LayerStackPartition, LayerTreeNode,
};
use super::{CompositorDisplayConfig, OnionSkinFrame};
use crate::document::{CanvasColorMode, CanvasDimensions, Document, LayerNode, LayerType};
use crate::types::CameraState;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

/// Document-space axis-aligned bounding box (clamped to `[0..doc_w, 0..doc_h]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DocBounds {
    pub min_x: i32,
    pub min_y: i32,
    pub max_x: i32,
    pub max_y: i32,
}

impl DocBounds {
    #[inline]
    pub fn is_empty(self) -> bool {
        self.max_x <= self.min_x || self.max_y <= self.min_y
    }

    #[inline]
    pub fn intersect(self, other: Self) -> Self {
        Self {
            min_x: self.min_x.max(other.min_x),
            min_y: self.min_y.max(other.min_y),
            max_x: self.max_x.min(other.max_x),
            max_y: self.max_y.min(other.max_y),
        }
    }
}

/// Top-left physical-pixel scissor rect for `wgpu::RenderPass::set_scissor_rect`
/// and `CommandEncoder::copy_texture_to_texture`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScissorRect {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

impl ScissorRect {
    #[inline]
    pub fn full(width: u32, height: u32) -> Self {
        Self {
            x: 0,
            y: 0,
            width,
            height,
        }
    }

    #[inline]
    pub fn is_empty(self) -> bool {
        self.width == 0 || self.height == 0
    }

    #[inline]
    pub fn union(self, other: Self) -> Self {
        if self.is_empty() {
            return other;
        }
        if other.is_empty() {
            return self;
        }
        let x0 = self.x.min(other.x);
        let y0 = self.y.min(other.y);
        let x1 = self.x.saturating_add(self.width).max(other.x.saturating_add(other.width));
        let y1 = self.y.saturating_add(self.height).max(other.y.saturating_add(other.height));
        Self {
            x: x0,
            y: y0,
            width: x1.saturating_sub(x0),
            height: y1.saturating_sub(y0),
        }
    }

    #[inline]
    pub fn clamp(self, viewport_w: u32, viewport_h: u32) -> Self {
        let x0 = self.x.min(viewport_w);
        let y0 = self.y.min(viewport_h);
        let x1 = self.x.saturating_add(self.width).min(viewport_w);
        let y1 = self.y.saturating_add(self.height).min(viewport_h);
        Self {
            x: x0,
            y: y0,
            width: x1.saturating_sub(x0),
            height: y1.saturating_sub(y0),
        }
    }

    /// Expands vertically by `pad_y` physical pixels (clamped to `[0..viewport_h]`).
    /// Used by horizontal separable blur/SDF passes so the subsequent vertical pass
    /// never reads stale pixels outside the dirty scissor rect.
    #[inline]
    pub fn expand_y(self, pad_y: i32, viewport_w: u32, viewport_h: u32) -> Self {
        if self.is_empty() {
            return self;
        }
        let pad = pad_y.max(0) as u32;
        let y0 = self.y.saturating_sub(pad);
        let y1 = self.y.saturating_add(self.height).saturating_add(pad).min(viewport_h);
        let x0 = self.x.min(viewport_w);
        let x1 = self.x.saturating_add(self.width).min(viewport_w);
        Self {
            x: x0,
            y: y0,
            width: x1.saturating_sub(x0),
            height: y1.saturating_sub(y0),
        }
    }

    #[inline]
    pub fn expand(self, pad: u32, viewport_w: u32, viewport_h: u32) -> Self {
        if self.is_empty() {
            return self;
        }
        let x0 = self.x.saturating_sub(pad).min(viewport_w);
        let y0 = self.y.saturating_sub(pad).min(viewport_h);
        let x1 = self
            .x
            .saturating_add(self.width)
            .saturating_add(pad)
            .min(viewport_w);
        let y1 = self
            .y
            .saturating_add(self.height)
            .saturating_add(pad)
            .min(viewport_h);
        Self {
            x: x0,
            y: y0,
            width: x1.saturating_sub(x0),
            height: y1.saturating_sub(y0),
        }
    }
}

/// Selects mipmap LOD (`0..=3`) automatically from effective zoom.
#[inline]
pub fn select_lod_for_zoom(zoom: f32) -> u8 {
    if zoom <= 0.125 {
        3
    } else if zoom <= 0.25 {
        2
    } else if zoom <= 0.5 {
        1
    } else {
        0
    }
}

/// Calculates the document-space AABB visible inside `(viewport_css_w, viewport_css_h)`
/// under `camera` (pan, zoom, rotation, flipX, flipY) for viewport frustum tile culling.
pub fn calculate_visible_doc_bounds(
    viewport_css_w: f32,
    viewport_css_h: f32,
    camera: &CameraState,
    doc_w: u32,
    doc_h: u32,
) -> DocBounds {
    let rad = (-camera.rotation).to_radians();
    let cos_r = rad.cos();
    let sin_r = rad.sin();
    let fx = if camera.flip_x { -1.0 } else { 1.0 };
    let fy = if camera.flip_y { -1.0 } else { 1.0 };
    let safe_zoom = camera.zoom.max(0.001);
    let half_w = doc_w as f32 * 0.5;
    let half_h = doc_h as f32 * 0.5;

    let corners = [
        (0.0f32, 0.0f32),
        (viewport_css_w, 0.0),
        (viewport_css_w, viewport_css_h),
        (0.0, viewport_css_h),
    ];

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;

    for (cx, cy) in corners {
        let sx = (cx - camera.pan_x) / safe_zoom;
        let sy = (cy - camera.pan_y) / safe_zoom;
        let rx = sx * cos_r - sy * sin_r;
        let ry = sx * sin_r + sy * cos_r;
        let doc_x = rx * fx + half_w;
        let doc_y = ry * fy + half_h;
        min_x = min_x.min(doc_x);
        min_y = min_y.min(doc_y);
        max_x = max_x.max(doc_x);
        max_y = max_y.max(doc_y);
    }

    DocBounds {
        min_x: (min_x.floor() as i32).clamp(0, doc_w as i32),
        min_y: (min_y.floor() as i32).clamp(0, doc_h as i32),
        max_x: (max_x.ceil() as i32).clamp(0, doc_w as i32),
        max_y: (max_y.ceil() as i32).clamp(0, doc_h as i32),
    }
}

/// Projects a document-space AABB into `wgpu` top-left physical-pixel scissor coordinates
/// clamped strictly to `[0..viewport_w, 0..viewport_h]`. Returns `None` if completely offscreen.
#[allow(clippy::too_many_arguments)]
pub fn doc_bounds_to_scissor(
    bounds: DocBounds,
    camera: &CameraState,
    doc_w: u32,
    doc_h: u32,
    viewport_w: u32,
    viewport_h: u32,
    dpr: f32,
    pad_px: i32,
) -> Option<ScissorRect> {
    if bounds.is_empty() || viewport_w == 0 || viewport_h == 0 {
        return None;
    }
    let rad = camera.rotation.to_radians();
    let cos_r = rad.cos();
    let sin_r = rad.sin();
    let fx = if camera.flip_x { -1.0 } else { 1.0 };
    let fy = if camera.flip_y { -1.0 } else { 1.0 };
    let half_w = doc_w as f32 * 0.5;
    let half_h = doc_h as f32 * 0.5;
    let safe_dpr = dpr.max(0.05);

    let xs = [bounds.min_x as f32, bounds.max_x as f32];
    let ys = [bounds.min_y as f32, bounds.max_y as f32];

    let mut min_sx = f32::INFINITY;
    let mut min_sy = f32::INFINITY;
    let mut max_sx = f32::NEG_INFINITY;
    let mut max_sy = f32::NEG_INFINITY;

    for &x in &xs {
        let dx = (x - half_w) * fx;
        for &y in &ys {
            let dy = (y - half_h) * fy;
            let sx = (camera.pan_x + camera.zoom * (dx * cos_r - dy * sin_r)) * safe_dpr;
            let sy = (camera.pan_y + camera.zoom * (dx * sin_r + dy * cos_r)) * safe_dpr;
            min_sx = min_sx.min(sx);
            min_sy = min_sy.min(sy);
            max_sx = max_sx.max(sx);
            max_sy = max_sy.max(sy);
        }
    }

    let pad = pad_px.max(0) as f32;
    let x0 = (min_sx - pad).floor().clamp(0.0, viewport_w as f32) as u32;
    let y0 = (min_sy - pad).floor().clamp(0.0, viewport_h as f32) as u32;
    let x1 = (max_sx + pad).ceil().clamp(0.0, viewport_w as f32) as u32;
    let y1 = (max_sy + pad).ceil().clamp(0.0, viewport_h as f32) as u32;

    if x1 <= x0 || y1 <= y0 {
        return None;
    }
    Some(ScissorRect {
        x: x0,
        y: y0,
        width: x1 - x0,
        height: y1 - y0,
    })
}

/// Fast, deterministic 64-bit FNV-1a hasher (stable across runs, zero randomization).
pub(crate) struct Fnv1a64(u64);

impl Fnv1a64 {
    #[inline]
    pub fn new() -> Self {
        Self(0xcbf29ce484222325)
    }

    #[inline]
    pub fn write_f32(&mut self, v: f32) {
        let bits = if v == 0.0 { 0u32 } else { v.to_bits() };
        self.write(&bits.to_le_bytes());
    }

    #[inline]
    pub fn write_f64(&mut self, v: f64) {
        let bits = if v == 0.0 { 0u64 } else { v.to_bits() };
        self.write(&bits.to_le_bytes());
    }

    #[inline]
    pub fn write_bool(&mut self, v: bool) {
        self.write(&[u8::from(v)]);
    }

    pub fn write_json_opt(&mut self, v: Option<&serde_json::Value>) {
        match v {
            None => self.write(&[0]),
            Some(val) => {
                self.write(&[1]);
                self.write_json(val);
            }
        }
    }

    fn write_json(&mut self, v: &serde_json::Value) {
        match v {
            serde_json::Value::Null => self.write(&[0]),
            serde_json::Value::Bool(b) => {
                self.write(&[1, u8::from(*b)]);
            }
            serde_json::Value::Number(n) => {
                self.write(&[2]);
                if let Some(f) = n.as_f64() {
                    self.write_f64(f);
                }
            }
            serde_json::Value::String(s) => {
                self.write(&[3]);
                s.hash(self);
            }
            serde_json::Value::Array(arr) => {
                self.write(&[4]);
                arr.len().hash(self);
                for item in arr {
                    self.write_json(item);
                }
            }
            serde_json::Value::Object(map) => {
                self.write(&[5]);
                map.len().hash(self);
                for (k, val) in map {
                    k.hash(self);
                    self.write_json(val);
                }
            }
        }
    }
}

impl Hasher for Fnv1a64 {
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 ^= u64::from(b);
            self.0 = self.0.wrapping_mul(0x100000001b3);
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn hash_camera_and_viewport(
    h: &mut Fnv1a64,
    doc_id: &str,
    viewport_w: u32,
    viewport_h: u32,
    dpr: f32,
    dimensions: CanvasDimensions,
    camera: &CameraState,
    color_mode: CanvasColorMode,
) {
    doc_id.hash(h);
    viewport_w.hash(h);
    viewport_h.hash(h);
    h.write_f32(dpr);
    dimensions.width.hash(h);
    dimensions.height.hash(h);
    dimensions.dpi.hash(h);
    h.write_f32(camera.pan_x);
    h.write_f32(camera.pan_y);
    h.write_f32(camera.zoom);
    h.write_f32(camera.rotation);
    h.write_bool(camera.flip_x);
    h.write_bool(camera.flip_y);
    (color_mode as u8).hash(h);
}

pub(crate) fn hash_layer_node(
    h: &mut Fnv1a64,
    node: &LayerTreeNode,
    layers: &[LayerNode],
    cel_overrides: &HashMap<String, bool>,
    inherited_opacity: f32,
) {
    let Some(layer) = layers.get(node.layer_index) else {
        return;
    };
    let m = &layer.meta;
    m.id.hash(h);
    (m.layer_type as u8).hash(h);
    h.write_bool(is_node_visible(layer, cel_overrides));
    h.write_f32(m.opacity);
    h.write_f32(inherited_opacity);
    (m.blend_mode as u8).hash(h);
    h.write_bool(m.clipped.unwrap_or(false));
    layer.grid.layer_version.hash(h);
    layer.grid.tiles.len().hash(h);
    layer.grid.impasto_tiles.len().hash(h);
    if let Some(light) = m.impasto_light {
        h.write_bool(light.enabled);
        h.write_f32(light.depth);
        h.write_f32(light.gloss);
        h.write_f32(light.relief_contrast);
        h.write_f32(light.light_azimuth);
        h.write_f32(light.light_elevation);
    }

    // Mask state
    let has_mask = layer_has_active_mask(layer);
    h.write_bool(has_mask);
    if has_mask {
        layer.grid.mask_default_value.hash(h);
        layer.grid.mask_tiles.len().hash(h);
        layer.grid.mask_version.hash(h);
        m.mask_version.unwrap_or(0).hash(h);
    }

    // Screentone
    let tone = m.tone_enabled.unwrap_or(false);
    h.write_bool(tone);
    if tone {
        h.write_f32(m.tone_frequency.unwrap_or(60.0));
        h.write_f32(m.tone_angle.unwrap_or(45.0));
        m.tone_dot_shape.map(|s| s as u8).unwrap_or(0).hash(h);
        h.write_f32(m.tone_density.unwrap_or(40.0));
        m.tone_density_type.map(|d| d as u8).unwrap_or(1).hash(h);
        h.write_bool(m.is_tone_layer.unwrap_or(false));
    }

    // Layer color tint
    let tint = m.layer_color_enabled.unwrap_or(false);
    h.write_bool(tint);
    if tint {
        m.layer_color.hash(h);
        m.layer_sub_color.hash(h);
    }

    // Expression color
    m.expression_color.map(|e| e as u8).unwrap_or(0).hash(h);
    m.mono_threshold.unwrap_or(128).hash(h);
    h.write_bool(m.mono_express_black.unwrap_or(true));
    h.write_bool(m.mono_express_white.unwrap_or(true));

    // Styles & adjustments
    h.write_json_opt(m.styles.as_ref());
    if m.layer_type == LayerType::Adjustment {
        h.write_json_opt(m.adjustment_data.as_ref());
    }

    // Comic frames
    if m.layer_type == LayerType::FrameFolder {
        if let Some(frames) = &m.comic_frames {
            frames.len().hash(h);
            for f in frames {
                f.id.hash(h);
                h.write_f32(f.border_width);
                h.write_bool(f.clip_children);
                h.write_bool(f.fill_background.unwrap_or(true));
                f.fill_color.hash(h);
                f.stroke_color.hash(h);
                f.polygon.len().hash(h);
                for pt in &f.polygon {
                    h.write_f64(pt.x);
                    h.write_f64(pt.y);
                }
            }
        }
    }

    // Recurse into visible children
    node.children.len().hash(h);
    for child in &node.children {
        if let Some(cl) = layers.get(child.layer_index) {
            if is_node_visible(cl, cel_overrides) && cl.meta.opacity > 0.001 {
                hash_layer_node(h, child, layers, cel_overrides, 1.0);
            }
        }
    }
}

pub(crate) fn hash_compositing_unit(
    h: &mut Fnv1a64,
    unit: &CompositingUnit,
    layers: &[LayerNode],
    cel_overrides: &HashMap<String, bool>,
) {
    hash_layer_node(h, &unit.group.base_node, layers, cel_overrides, unit.inherited_opacity);
    unit.group.clipped_nodes.len().hash(h);
    for cn in &unit.group.clipped_nodes {
        if let Some(cl) = layers.get(cn.layer_index) {
            if is_node_visible(cl, cel_overrides)
                && cl.meta.opacity > 0.001
                && !cl.meta.layer_type.is_folder_like()
            {
                hash_layer_node(h, cn, layers, cel_overrides, unit.inherited_opacity);
            }
        }
    }
}

fn hash_onion_skins(
    h: &mut Fnv1a64,
    onion_frames: &[OnionSkinFrame],
    layers: &[LayerNode],
) {
    onion_frames.len().hash(h);
    for f in onion_frames {
        if let Some(target) = layers.iter().find(|l| l.meta.id == f.layer_id) {
            if target.meta.visible {
                let m = &target.meta;
                f.layer_id.hash(h);
                h.write_f32(f.tint[0]);
                h.write_f32(f.tint[1]);
                h.write_f32(f.tint[2]);
                h.write_f32(f.opacity);
                target.grid.layer_version.hash(h);
                // Mask properties
                let has_mask = layer_has_active_mask(target);
                h.write_bool(has_mask);
                if has_mask {
                    target.grid.mask_version.hash(h);
                    target.grid.mask_default_value.hash(h);
                    target.grid.mask_tiles.len().hash(h);
                }
                // Expression color & screentone properties
                m.expression_color.map(|e| e as u8).unwrap_or(0).hash(h);
                m.mono_threshold.unwrap_or(128).hash(h);
                h.write_bool(m.mono_express_black.unwrap_or(true));
                h.write_bool(m.mono_express_white.unwrap_or(true));
                let tone = m.tone_enabled.unwrap_or(false);
                h.write_bool(tone);
                if tone {
                    h.write_f32(m.tone_frequency.unwrap_or(60.0));
                    h.write_f32(m.tone_angle.unwrap_or(45.0));
                    h.write_f32(m.tone_density.unwrap_or(40.0));
                    m.tone_dot_shape.map(|s| s as u8).unwrap_or(0).hash(h);
                    m.tone_density_type.map(|d| d as u8).unwrap_or(0).hash(h);
                    h.write_bool(m.is_tone_layer.unwrap_or(false));
                }
            }
        }
    }
}

/// Evaluation output of [`LayerStackCacheTracker::evaluate`].
#[derive(Debug)]
pub struct StackCacheEvaluation {
    pub partition: LayerStackPartition,
    pub below_signature: u64,
    pub above_signature: u64,
    pub below_dirty: bool,
    pub above_dirty: bool,
}

/// Telemetry counters for 3-slice cache hits vs rebuilds and hover/ants fast-path skips.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StackCacheStats {
    pub below_rebuilds: u64,
    pub above_rebuilds: u64,
    pub cache_hits: u64,
    pub final_scene_hits: u64,
    pub final_scene_rebuilds: u64,
    pub live_stroke_zero_skips: u64,
}

/// Pure invalidation tracker for the 3-slice GPU cache (`below_active_cache` + `above_active_cache`).
#[derive(Debug, Default)]
pub struct LayerStackCacheTracker {
    last_below_sig: Option<u64>,
    last_above_sig: Option<u64>,
    pub stats: StackCacheStats,
}

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

    pub fn evaluate(
        &self,
        doc: &Document,
        display: &CompositorDisplayConfig,
        viewport_w: u32,
        viewport_h: u32,
        dpr: f32,
        camera: &CameraState,
    ) -> StackCacheEvaluation {
        let partition = partition_layer_stack(
            &doc.layers,
            &display.cel_visibility_overrides,
            doc.active_layer_id.as_deref(),
        );

        let mut hb = Fnv1a64::new();
        0xBEEF_0001u32.hash(&mut hb);
        hash_camera_and_viewport(
            &mut hb,
            &doc.id,
            viewport_w,
            viewport_h,
            dpr,
            doc.dimensions,
            camera,
            doc.color_mode,
        );
        hash_onion_skins(&mut hb, &display.onion_skin_frames, &doc.layers);
        partition.below_units.len().hash(&mut hb);
        for unit in &partition.below_units {
            hash_compositing_unit(&mut hb, unit, &doc.layers, &display.cel_visibility_overrides);
        }
        let below_signature = hb.finish();

        let mut above_signature = 0u64;
        if !partition.above_cached_units.is_empty() {
            let mut ha = Fnv1a64::new();
            0xAB0E_0002u32.hash(&mut ha);
            hash_camera_and_viewport(
                &mut ha,
                &doc.id,
                viewport_w,
                viewport_h,
                dpr,
                doc.dimensions,
                camera,
                doc.color_mode,
            );
            (partition.above_strategy as u8).hash(&mut ha);
            (partition.above_cache_blend_mode as u8).hash(&mut ha);
            partition.above_cached_units.len().hash(&mut ha);
            for unit in &partition.above_cached_units {
                hash_compositing_unit(&mut ha, unit, &doc.layers, &display.cel_visibility_overrides);
            }
            above_signature = ha.finish();
        }

        let below_dirty = self.last_below_sig != Some(below_signature);
        let above_dirty =
            !partition.above_cached_units.is_empty() && self.last_above_sig != Some(above_signature);

        StackCacheEvaluation {
            partition,
            below_signature,
            above_signature,
            below_dirty,
            above_dirty,
        }
    }

    pub fn commit(&mut self, below_sig: u64, above_sig: u64, has_above: bool) {
        self.last_below_sig = Some(below_sig);
        self.last_above_sig = if has_above { Some(above_sig) } else { None };
    }

    pub fn invalidate_all(&mut self) {
        self.last_below_sig = None;
        self.last_above_sig = None;
    }

    pub fn invalidate_below(&mut self) {
        self.last_below_sig = None;
    }

    pub fn invalidate_above(&mut self) {
        self.last_above_sig = None;
    }

    pub fn last_signatures(&self) -> (Option<u64>, Option<u64>) {
        (self.last_below_sig, self.last_above_sig)
    }
}