Skip to content

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

5.8 KB
Raw Blame
//! Sparse virtual tile store (`256×256` tiles) with Copy-on-Write (`Arc<TileData>`),
//! solid-color zero-allocation fast tiles, 1-bit / 8-bit / 32-bit / 16-bit-float GPU working
//! formats, and unified per-layer raster + non-destructive 8-bit mask tiling.

pub mod format;
pub mod grid;
pub mod tile_data;

use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};

pub const TILE_SIZE: usize = 256;
pub const TILE_SIZE_I32: i32 = 256;
pub const TILE_PIXELS: usize = TILE_SIZE * TILE_SIZE; // 65,536
pub const BYTES_1BIT: usize = TILE_PIXELS / 8; // 8,192 bytes (8 KB)
pub const BYTES_8BIT: usize = TILE_PIXELS; // 65,536 bytes (64 KB)
pub const BYTES_R16F: usize = TILE_PIXELS * 2; // 131,072 bytes (128 KB, R16Float heightfield)
pub const BYTES_32BIT: usize = TILE_PIXELS * 4; // 262,144 bytes (256 KB)
pub const BYTES_16F: usize = TILE_PIXELS * 8; // 524,288 bytes (512 KB, 4×f16)

/// Supported sparse tile storage formats.
///
/// - `Monochrome1Bit`: 8 KB per tile (manga line art, 32× smaller than RGBA8)
/// - `Grayscale8Bit`: 64 KB per tile (grayscale ink / non-destructive 8-bit layer masks)
/// - `Color32Bit`: 256 KB per tile (standard sRGB RGBA8)
/// - `Rgba16Float`: 512 KB per tile (internal 16-bit half-float GPU working format, zero 8-bit banding)
/// - `Height16Float`: 128 KB per tile (lazily-allocated R16Float impasto 3D paint heightfield)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum TileFormat {
    #[serde(rename = "monochrome-1bit")]
    Monochrome1Bit,
    #[serde(rename = "grayscale-8bit")]
    Grayscale8Bit,
    #[default]
    #[serde(rename = "color-32bit")]
    Color32Bit,
    #[serde(rename = "rgba-16f")]
    Rgba16Float,
    #[serde(rename = "height-16f")]
    Height16Float,
}

impl TileFormat {
    #[inline]
    pub const fn byte_size(self) -> usize {
        match self {
            Self::Monochrome1Bit => BYTES_1BIT,
            Self::Grayscale8Bit => BYTES_8BIT,
            Self::Color32Bit => BYTES_32BIT,
            Self::Rgba16Float => BYTES_16F,
            Self::Height16Float => BYTES_R16F,
        }
    }

    /// Maps to the `.ink` v2 archive / `INKG` format tag byte (`0=1bit, 1=8bit, 2=32bit, 3=16f, 4=r16f`).
    #[inline]
    pub const fn to_ink_byte(self) -> u8 {
        match self {
            Self::Monochrome1Bit => 0,
            Self::Grayscale8Bit => 1,
            Self::Color32Bit => 2,
            Self::Rgba16Float => 3,
            Self::Height16Float => 4,
        }
    }

    #[inline]
    pub const fn from_ink_byte(b: u8) -> Option<Self> {
        match b {
            0 => Some(Self::Monochrome1Bit),
            1 => Some(Self::Grayscale8Bit),
            2 => Some(Self::Color32Bit),
            3 => Some(Self::Rgba16Float),
            4 => Some(Self::Height16Float),
            _ => None,
        }
    }

    /// Returns the persistent storage format used for `.ink` serialization boundaries
    /// (16-bit working tiles quantize with dithering to `Color32Bit` for v2 compatibility;
    /// `Height16Float` persists natively as R16F).
    #[inline]
    pub const fn io_storage_format(self) -> Self {
        match self {
            Self::Rgba16Float => Self::Color32Bit,
            other => other,
        }
    }
}

/// Distinguishes a layer's primary raster plane, non-destructive 8-bit mask plane,
/// and lazily-allocated `R16Float` impasto 3D heightfield plane.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TileKind {
    Raster,
    Mask,
    ImpastoHeight,
}

/// Signed integer 2D tile coordinate in document tile space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TileCoord {
    pub tx: i32,
    pub ty: i32,
}

impl TileCoord {
    #[inline]
    pub const fn new(tx: i32, ty: i32) -> Self {
        Self { tx, ty }
    }

    /// Top-left pixel coordinate of this tile at `lod` (`0` = 256 px, `1` = 512 px, ...).
    #[inline]
    pub const fn doc_origin(self, lod: u8) -> (i32, i32) {
        let span = TILE_SIZE_I32 << lod;
        (self.tx * span, self.ty * span)
    }

    /// Returns the parent tile coordinate at `lod + 1` (using arithmetic right-shift / Euclidean floor).
    #[inline]
    pub const fn parent(self) -> Self {
        Self {
            tx: self.tx.div_euclid(2),
            ty: self.ty.div_euclid(2),
        }
    }
}

/// Maps a document pixel coordinate to its enclosing tile index at `lod` (`0..=3`).
#[inline]
pub const fn pixel_to_tile_coord(pixel: i32, lod: u8) -> i32 {
    let span = TILE_SIZE_I32 << lod;
    pixel.div_euclid(span)
}

/// Uniquely identifies any tile across multi-tab documents, layers, raster/mask planes, and LODs.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TileKey {
    pub doc_id: String,
    pub layer_id: String,
    pub kind: TileKind,
    pub lod: u8,
    pub coord: TileCoord,
}

static NEXT_TILE_VERSION: AtomicU64 = AtomicU64::new(1);
static NEXT_ACCESS_SEQ: AtomicU64 = AtomicU64::new(1);

#[inline]
pub fn allocate_tile_version() -> u64 {
    NEXT_TILE_VERSION.fetch_add(1, Ordering::Relaxed) + 1
}

#[inline]
pub fn reserve_tile_version(version: u64) {
    let _ = NEXT_TILE_VERSION.fetch_max(version, Ordering::Relaxed);
}

#[inline]
pub fn next_access_seq() -> u64 {
    NEXT_ACCESS_SEQ.fetch_add(1, Ordering::Relaxed) + 1
}

pub use format::{
    convert_tile_bytes, detect_solid_color, expand_solid_to_raw, get_pixel_1bit, is_raw_empty,
    pack_rgba8_to_1bit, pack_rgba8_to_8bit, pack_rgba8_to_mask8, parse_hex_rgba8,
    rgba16f_to_rgba8_dithered, rgba16f_to_rgba8_lossless, rgba8_pixel_to_f16, rgba8_to_rgba16f,
    set_pixel_1bit, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, unpack_mask8_to_rgba8,
};
pub use grid::{CowTileDelta, RectI32, SparseLayerGrid};
pub use tile_data::{TileData, TileStorage};