A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
//! Fast pixel format conversions between `Monochrome1Bit`, `Grayscale8Bit`,
//! `Color32Bit` (RGBA8), `Mask8Bit`, and internal `Rgba16Float` (4×f16).
//!
//! Includes solid-color tile detection/expansion and 4×4 Bayer ordered dithering
//! when quantizing `Rgba16Float` down to 8-bit at I/O boundaries.
use super::{
TileFormat, BYTES_16F, BYTES_1BIT, BYTES_32BIT, BYTES_8BIT, BYTES_R16F, TILE_PIXELS, TILE_SIZE,
};
use half::f16;
use std::sync::LazyLock;
/// Precomputed LUT mapping every `u8` (0..=255) to its exact normalized IEEE-754 `f16` bits (`v / 255.0`).
static U8_TO_F16_BITS: LazyLock<[u16; 256]> = LazyLock::new(|| {
let mut lut = [0u16; 256];
for (i, slot) in lut.iter_mut().enumerate() {
*slot = f16::from_f32(i as f32 / 255.0).to_bits();
}
lut
});
/// Normalized 4×4 Bayer ordered-dither threshold matrix centered in `[-0.46875, +0.46875]`.
const BAYER_4X4: [[f32; 4]; 4] = [
[-0.46875, 0.03125, -0.34375, 0.15625],
[0.28125, -0.21875, 0.40625, -0.09375],
[-0.28125, 0.21875, -0.40625, 0.09375],
[0.46875, -0.03125, 0.34375, -0.15625],
];
/// Converts a single RGBA8 pixel `[r, g, b, a]` to 4× IEEE-754 `f16` bits.
#[inline]
pub fn rgba8_pixel_to_f16(rgba8: [u8; 4]) -> [u16; 4] {
let lut = &*U8_TO_F16_BITS;
[
lut[rgba8[0] as usize],
lut[rgba8[1] as usize],
lut[rgba8[2] as usize],
lut[rgba8[3] as usize],
]
}
/// Converts a single 4× `f16` pixel back to RGBA8 with lossless rounding for 8-bit-origin values.
#[inline]
pub fn f16_pixel_to_rgba8(px: [u16; 4]) -> [u8; 4] {
[
(f16::from_bits(px[0]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
(f16::from_bits(px[1]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
(f16::from_bits(px[2]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
(f16::from_bits(px[3]).to_f32().clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
]
}
/// Parses `#rgb`, `#rrggbb`, `#rrggbbaa`, or `"transparent"` into `[r, g, b, a]`.
pub fn parse_hex_rgba8(hex: &str) -> Option<[u8; 4]> {
let s = hex.trim();
if s.eq_ignore_ascii_case("transparent") {
return Some([0, 0, 0, 0]);
}
let h = s.strip_prefix('#').unwrap_or(s);
match h.len() {
3 => {
let r = u8::from_str_radix(&h[0..1], 16).ok()?;
let g = u8::from_str_radix(&h[1..2], 16).ok()?;
let b = u8::from_str_radix(&h[2..3], 16).ok()?;
Some([r * 17, g * 17, b * 17, 255])
}
6 => {
let r = u8::from_str_radix(&h[0..2], 16).ok()?;
let g = u8::from_str_radix(&h[2..4], 16).ok()?;
let b = u8::from_str_radix(&h[4..6], 16).ok()?;
Some([r, g, b, 255])
}
8 => {
let r = u8::from_str_radix(&h[0..2], 16).ok()?;
let g = u8::from_str_radix(&h[2..4], 16).ok()?;
let b = u8::from_str_radix(&h[4..6], 16).ok()?;
let a = u8::from_str_radix(&h[6..8], 16).ok()?;
Some([r, g, b, a])
}
_ => None,
}
}
/// Sets a single pixel in an 8,192-byte MSB-first 1-bit monochrome tile.
#[inline]
pub fn set_pixel_1bit(data: &mut [u8], x: usize, y: usize, ink: bool) {
debug_assert!(x < TILE_SIZE && y < TILE_SIZE && data.len() == BYTES_1BIT);
let pixel_idx = y * TILE_SIZE + x;
let byte_idx = pixel_idx >> 3;
let bit_mask = 1u8 << (7 - (pixel_idx & 7));
if ink {
data[byte_idx] |= bit_mask;
} else {
data[byte_idx] &= !bit_mask;
}
}
/// Reads a single pixel (`0` or `1`) from an 8,192-byte MSB-first 1-bit monochrome tile.
#[inline]
pub fn get_pixel_1bit(data: &[u8], x: usize, y: usize) -> u8 {
debug_assert!(x < TILE_SIZE && y < TILE_SIZE && data.len() == BYTES_1BIT);
let pixel_idx = y * TILE_SIZE + x;
let byte_idx = pixel_idx >> 3;
let bit_offset = 7 - (pixel_idx & 7);
(data[byte_idx] >> bit_offset) & 1
}
/// Unpacks an 8,192-byte 1-bit tile into 262,144-byte RGBA8 using `ink_rgba` for set bits
/// and `paper_rgba` for cleared bits.
pub fn unpack_1bit_to_rgba8(
src_1bit: &[u8],
dst_rgba8: &mut [u8],
ink_rgba: [u8; 4],
paper_rgba: [u8; 4],
) {
assert_eq!(src_1bit.len(), BYTES_1BIT);
assert_eq!(dst_rgba8.len(), BYTES_32BIT);
for (byte_i, &b) in src_1bit.iter().enumerate() {
let base = byte_i * 32;
if b == 0 {
if paper_rgba == [0, 0, 0, 0] {
dst_rgba8[base..base + 32].fill(0);
} else {
for p in 0..8 {
let off = base + p * 4;
dst_rgba8[off..off + 4].copy_from_slice(&paper_rgba);
}
}
continue;
}
for bit in 0..8 {
let off = base + bit * 4;
let color = if (b & (0x80 >> bit)) != 0 {
&ink_rgba
} else {
&paper_rgba
};
dst_rgba8[off..off + 4].copy_from_slice(color);
}
}
}
/// Packs 262,144-byte RGBA8 into an 8,192-byte 1-bit monochrome tile using ITU-R BT.601
/// perceptual luminance thresholding (`alpha >= 24 && lum < threshold`, matching `pixelCodec.ts`).
pub fn pack_rgba8_to_1bit(src_rgba8: &[u8], dst_1bit: &mut [u8], threshold: u8) {
assert_eq!(src_rgba8.len(), BYTES_32BIT);
assert_eq!(dst_1bit.len(), BYTES_1BIT);
let thresh1000 = u32::from(threshold) * 1000;
for (byte_i, dst_byte) in dst_1bit.iter_mut().enumerate() {
let base = byte_i * 32;
let mut out = 0u8;
for bit in 0..8 {
let off = base + bit * 4;
let a = src_rgba8[off + 3];
if a >= 24 {
let lum1000 = u32::from(src_rgba8[off]) * 299
+ u32::from(src_rgba8[off + 1]) * 587
+ u32::from(src_rgba8[off + 2]) * 114;
if lum1000 < thresh1000 {
out |= 0x80 >> bit;
}
}
}
*dst_byte = out;
}
}
/// Unpacks a 65,536-byte 8-bit grayscale tile into 262,144-byte RGBA8 (`0 -> transparent`,
/// non-zero `v -> [v, v, v, 255]`, matching `pixelCodec.ts`).
pub fn unpack_8bit_to_rgba8(src_8bit: &[u8], dst_rgba8: &mut [u8]) {
assert_eq!(src_8bit.len(), BYTES_8BIT);
assert_eq!(dst_rgba8.len(), BYTES_32BIT);
for (i, &val) in src_8bit.iter().enumerate() {
let off = i * 4;
if val == 0 {
dst_rgba8[off..off + 4].fill(0);
} else {
dst_rgba8[off] = val;
dst_rgba8[off + 1] = val;
dst_rgba8[off + 2] = val;
dst_rgba8[off + 3] = 255;
}
}
}
/// Packs 262,144-byte RGBA8 into a 65,536-byte 8-bit grayscale tile (`a < 10 -> 0`,
/// else ITU-R BT.601 luminance).
pub fn pack_rgba8_to_8bit(src_rgba8: &[u8], dst_8bit: &mut [u8]) {
assert_eq!(src_rgba8.len(), BYTES_32BIT);
assert_eq!(dst_8bit.len(), BYTES_8BIT);
for (i, dst) in dst_8bit.iter_mut().enumerate() {
let off = i * 4;
let a = src_rgba8[off + 3];
if a < 10 {
*dst = 0;
} else {
let lum = (u32::from(src_rgba8[off]) * 299
+ u32::from(src_rgba8[off + 1]) * 587
+ u32::from(src_rgba8[off + 2]) * 114
+ 500)
/ 1000;
*dst = lum.min(255) as u8;
}
}
}
/// Unpacks an 8-bit layer mask (`0 = hidden`, `255 = fully visible`) into opaque grayscale RGBA8.
pub fn unpack_mask8_to_rgba8(src_mask: &[u8], dst_rgba8: &mut [u8]) {
assert_eq!(src_mask.len(), BYTES_8BIT);
assert_eq!(dst_rgba8.len(), BYTES_32BIT);
for (i, &v) in src_mask.iter().enumerate() {
let off = i * 4;
dst_rgba8[off] = v;
dst_rgba8[off + 1] = v;
dst_rgba8[off + 2] = v;
dst_rgba8[off + 3] = 255;
}
}
/// Packs RGBA8 mask canvas pixels into 8-bit mask alpha (`lum * alpha / 255`).
pub fn pack_rgba8_to_mask8(src_rgba8: &[u8], dst_mask: &mut [u8]) {
assert_eq!(src_rgba8.len(), dst_mask.len() * 4);
for (i, dst) in dst_mask.iter_mut().enumerate() {
let off = i * 4;
let lum = (u32::from(src_rgba8[off]) * 299
+ u32::from(src_rgba8[off + 1]) * 587
+ u32::from(src_rgba8[off + 2]) * 114
+ 500)
/ 1000;
let a = u32::from(src_rgba8[off + 3]);
*dst = ((lum * a + 127) / 255).min(255) as u8;
}
}
/// Converts 262,144-byte RGBA8 into 524,288-byte `Rgba16Float` (little-endian `u16` half-floats).
pub fn rgba8_to_rgba16f(src_rgba8: &[u8], dst_16f: &mut [u8]) {
assert_eq!(src_rgba8.len(), BYTES_32BIT);
assert_eq!(dst_16f.len(), BYTES_16F);
let lut = &*U8_TO_F16_BITS;
for (i, &channel) in src_rgba8.iter().enumerate() {
let bits = lut[channel as usize].to_le_bytes();
let off = i * 2;
dst_16f[off] = bits[0];
dst_16f[off + 1] = bits[1];
}
}
/// Converts 524,288-byte `Rgba16Float` back to 262,144-byte RGBA8 using exact round-to-nearest.
/// Every 8-bit value promoted via `rgba8_to_rgba16f` round-trips bit-identically.
pub fn rgba16f_to_rgba8_lossless(src_16f: &[u8], dst_rgba8: &mut [u8]) {
assert_eq!(src_16f.len(), BYTES_16F);
assert_eq!(dst_rgba8.len(), BYTES_32BIT);
for (dst, chunk) in dst_rgba8.iter_mut().zip(src_16f.chunks_exact(2)) {
let bits = u16::from_le_bytes([chunk[0], chunk[1]]);
let v = f16::from_bits(bits).to_f32().clamp(0.0, 1.0);
*dst = (v * 255.0 + 0.5) as u8;
}
}
/// Converts 524,288-byte `Rgba16Float` to 262,144-byte RGBA8 with 4×4 Bayer ordered dithering
/// to eliminate visible 8-bit quantization banding on smooth 16-bit gradients at I/O boundaries.
/// Preserves exact `0.0 -> 0` and `1.0 -> 255` endpoints with zero noise on solid black/white/transparent.
pub fn rgba16f_to_rgba8_dithered(src_16f: &[u8], dst_rgba8: &mut [u8]) {
assert_eq!(src_16f.len(), BYTES_16F);
assert_eq!(dst_rgba8.len(), BYTES_32BIT);
for y in 0..TILE_SIZE {
let bayer_row = &BAYER_4X4[y & 3];
for x in 0..TILE_SIZE {
let dither = bayer_row[x & 3];
let px_idx = y * TILE_SIZE + x;
let src_base = px_idx * 8;
let dst_base = px_idx * 4;
for c in 0..4 {
let s_off = src_base + c * 2;
let bits = u16::from_le_bytes([src_16f[s_off], src_16f[s_off + 1]]);
let v = f16::from_bits(bits).to_f32().clamp(0.0, 1.0);
if v <= 0.0 {
dst_rgba8[dst_base + c] = 0;
} else if v >= 1.0 {
dst_rgba8[dst_base + c] = 255;
} else {
let scaled = (v * 255.0 + dither).clamp(0.0, 255.0);
dst_rgba8[dst_base + c] = (scaled + 0.5) as u8;
}
}
}
}
}
/// Converts raw tile bytes from any `TileFormat` to any other `TileFormat`.
pub fn convert_tile_bytes(
src: &[u8],
src_fmt: TileFormat,
dst_fmt: TileFormat,
mono_threshold: u8,
dither_16f_to_8: bool,
) -> Vec<u8> {
if src_fmt == dst_fmt {
return src.to_vec();
}
// Fast path RGBA8 <-> Rgba16Float
if src_fmt == TileFormat::Color32Bit && dst_fmt == TileFormat::Rgba16Float {
let mut out = vec![0u8; BYTES_16F];
rgba8_to_rgba16f(src, &mut out);
return out;
}
if src_fmt == TileFormat::Rgba16Float && dst_fmt == TileFormat::Color32Bit {
let mut out = vec![0u8; BYTES_32BIT];
if dither_16f_to_8 {
rgba16f_to_rgba8_dithered(src, &mut out);
} else {
rgba16f_to_rgba8_lossless(src, &mut out);
}
return out;
}
// Intermediate RGBA8 canonical representation
let rgba8: Vec<u8> = match src_fmt {
TileFormat::Color32Bit => src.to_vec(),
TileFormat::Monochrome1Bit => {
let mut buf = vec![0u8; BYTES_32BIT];
unpack_1bit_to_rgba8(src, &mut buf, [0, 0, 0, 255], [0, 0, 0, 0]);
buf
}
TileFormat::Grayscale8Bit => {
let mut buf = vec![0u8; BYTES_32BIT];
unpack_8bit_to_rgba8(src, &mut buf);
buf
}
TileFormat::Rgba16Float => {
let mut buf = vec![0u8; BYTES_32BIT];
if dither_16f_to_8 {
rgba16f_to_rgba8_dithered(src, &mut buf);
} else {
rgba16f_to_rgba8_lossless(src, &mut buf);
}
buf
}
TileFormat::Height16Float => {
let mut buf = vec![0u8; BYTES_32BIT];
for (i, chunk) in src.chunks_exact(2).enumerate() {
let bits = u16::from_le_bytes([chunk[0], chunk[1]]);
let h = f16::from_bits(bits).to_f32();
let g = (h.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let off = i * 4;
buf[off] = g;
buf[off + 1] = g;
buf[off + 2] = g;
buf[off + 3] = if h.abs() > 1e-5 { 255 } else { 0 };
}
buf
}
};
match dst_fmt {
TileFormat::Color32Bit => rgba8,
TileFormat::Monochrome1Bit => {
let mut out = vec![0u8; BYTES_1BIT];
pack_rgba8_to_1bit(&rgba8, &mut out, mono_threshold);
out
}
TileFormat::Grayscale8Bit => {
let mut out = vec![0u8; BYTES_8BIT];
pack_rgba8_to_8bit(&rgba8, &mut out);
out
}
TileFormat::Rgba16Float => {
let mut out = vec![0u8; BYTES_16F];
rgba8_to_rgba16f(&rgba8, &mut out);
out
}
TileFormat::Height16Float => {
let mut out = vec![0u8; BYTES_R16F];
for (i, px) in rgba8.chunks_exact(4).enumerate() {
let h = if px[3] == 0 {
0.0f32
} else {
px[0] as f32 / 255.0
};
let bits = f16::from_f32(h).to_bits().to_le_bytes();
let off = i * 2;
out[off] = bits[0];
out[off + 1] = bits[1];
}
out
}
}
}
/// Checks if a raw tile buffer is completely empty (all transparent / zero ink / zero height).
pub fn is_raw_empty(format: TileFormat, raw: &[u8]) -> bool {
match format {
TileFormat::Monochrome1Bit | TileFormat::Grayscale8Bit => raw.iter().all(|&b| b == 0),
TileFormat::Color32Bit => raw.chunks_exact(4).all(|px| px[3] == 0),
TileFormat::Rgba16Float => raw.chunks_exact(8).all(|px| {
let a_bits = u16::from_le_bytes([px[6], px[7]]);
// IEEE-754 +0.0 is 0x0000, -0.0 is 0x8000
(a_bits & 0x7FFF) == 0
}),
TileFormat::Height16Float => raw.chunks_exact(2).all(|px| {
let h_bits = u16::from_le_bytes([px[0], px[1]]);
(h_bits & 0x7FFF) == 0
}),
}
}
/// Detects if an entire raw tile consists of one uniform pixel value.
/// Returns `Some((rgba8, rgba16f))` if uniform, exiting on the first differing pixel in nanoseconds.
pub fn detect_solid_color(format: TileFormat, raw: &[u8]) -> Option<([u8; 4], [u16; 4])> {
if raw.len() != format.byte_size() {
return None;
}
match format {
TileFormat::Monochrome1Bit => {
let first = raw[0];
if first != 0x00 && first != 0xFF {
return None;
}
if raw.iter().any(|&b| b != first) {
return None;
}
let rgba8 = if first == 0xFF {
[0, 0, 0, 255]
} else {
[0, 0, 0, 0]
};
Some((rgba8, rgba8_pixel_to_f16(rgba8)))
}
TileFormat::Grayscale8Bit => {
let first = raw[0];
if raw.iter().any(|&b| b != first) {
return None;
}
let rgba8 = if first == 0 {
[0, 0, 0, 0]
} else {
[first, first, first, 255]
};
Some((rgba8, rgba8_pixel_to_f16(rgba8)))
}
TileFormat::Color32Bit => {
let first = [raw[0], raw[1], raw[2], raw[3]];
if raw.chunks_exact(4).any(|px| px != first) {
return None;
}
Some((first, rgba8_pixel_to_f16(first)))
}
TileFormat::Rgba16Float => {
let first_bytes = &raw[0..8];
if raw.chunks_exact(8).any(|px| px != first_bytes) {
return None;
}
let f16_px = [
u16::from_le_bytes([first_bytes[0], first_bytes[1]]),
u16::from_le_bytes([first_bytes[2], first_bytes[3]]),
u16::from_le_bytes([first_bytes[4], first_bytes[5]]),
u16::from_le_bytes([first_bytes[6], first_bytes[7]]),
];
Some((f16_pixel_to_rgba8(f16_px), f16_px))
}
TileFormat::Height16Float => {
let first_bytes = &raw[0..2];
if raw.chunks_exact(2).any(|px| px != first_bytes) {
return None;
}
let h_bits = u16::from_le_bytes([first_bytes[0], first_bytes[1]]);
let h = f16::from_bits(h_bits).to_f32();
let g = (h.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let a = if (h_bits & 0x7FFF) == 0 { 0 } else { 255 };
Some(([g, g, g, a], [h_bits, 0, 0, 0]))
}
}
}
/// Expands a uniform `SolidColor` into a full raw tile buffer in `format`.
pub fn expand_solid_to_raw(format: TileFormat, rgba8: [u8; 4], rgba16f: [u16; 4]) -> Vec<u8> {
match format {
TileFormat::Monochrome1Bit => {
let fill = if rgba8[3] >= 24 { 0xFF } else { 0x00 };
vec![fill; BYTES_1BIT]
}
TileFormat::Grayscale8Bit => {
let fill = if rgba8[3] == 0 { 0 } else { rgba8[0] };
vec![fill; BYTES_8BIT]
}
TileFormat::Color32Bit => {
let mut out = vec![0u8; BYTES_32BIT];
if rgba8 != [0, 0, 0, 0] {
for px in out.chunks_exact_mut(4) {
px.copy_from_slice(&rgba8);
}
}
out
}
TileFormat::Rgba16Float => {
let mut out = vec![0u8; BYTES_16F];
if rgba16f != [0, 0, 0, 0] {
let mut pattern = [0u8; 8];
pattern[0..2].copy_from_slice(&rgba16f[0].to_le_bytes());
pattern[2..4].copy_from_slice(&rgba16f[1].to_le_bytes());
pattern[4..6].copy_from_slice(&rgba16f[2].to_le_bytes());
pattern[6..8].copy_from_slice(&rgba16f[3].to_le_bytes());
for px in out.chunks_exact_mut(8) {
px.copy_from_slice(&pattern);
}
}
out
}
TileFormat::Height16Float => {
let mut out = vec![0u8; BYTES_R16F];
if (rgba16f[0] & 0x7FFF) != 0 {
let pattern = rgba16f[0].to_le_bytes();
for px in out.chunks_exact_mut(2) {
px.copy_from_slice(&pattern);
}
}
out
}
}
}
/// Expands a uniform `SolidColor` directly into RGBA16F bytes (524,288 bytes) for GPU upload.
pub fn expand_solid_to_rgba16f(rgba16f: [u16; 4]) -> Vec<u8> {
expand_solid_to_raw(TileFormat::Rgba16Float, [0, 0, 0, 0], rgba16f)
}
/// Expands a uniform mask value (`0..=255`) into 65,536-byte 8-bit mask buffer.
pub fn expand_solid_mask8(val: u8) -> Vec<u8> {
vec![val; TILE_PIXELS]
}