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
//! Direct Native Rust & GPU Gradient Engine (`gradient.rs`).
//!
//! Renders Linear, Radial, Conical, Diamond, and Rotatable Bicubic Mesh Gradients with
//! `clamp` / `repeat` / `reflect`, `normal` / `multiply` / `screen` / `overlay` blend modes,
//! 4×4 Bayer dithering, 8-band Kubelka-Munk pigment blending, `SparseSelectionMask` clipping,
//! `alphaLocked`, live GPU preview overlays, and atomic CoW Undo commits!
use crate::document::{Document, LayerId};
use crate::memory::ScratchBackend;
use crate::natural_paint::pigment::mix_pigments_srgb;
use crate::tiles::{parse_hex_rgba8, CowTileDelta, RectI32, TileKind};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::f32::consts::TAU;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GradientType {
#[default]
Linear,
Radial,
Conical,
Diamond,
Mesh,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GradientRepeatMode {
#[default]
Clamp,
Repeat,
Reflect,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GradientBlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GradientStop {
pub position: f32,
pub color: String,
#[serde(default = "default_one")]
pub opacity: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GradientMeshNode {
pub u: f32,
pub v: f32,
pub color: String,
#[serde(default = "default_one")]
pub opacity: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GradientMeshParams {
pub cols: usize,
pub rows: usize,
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
#[serde(default)]
pub rotation: f32,
pub nodes: Vec<GradientMeshNode>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GradientParams {
#[serde(default)]
pub gradient_type: GradientType,
pub stops: Vec<GradientStop>,
#[serde(default)]
pub start: [f32; 2],
#[serde(default)]
pub end: [f32; 2],
#[serde(default)]
pub repeat: GradientRepeatMode,
#[serde(default)]
pub blend_mode: GradientBlendMode,
#[serde(default = "default_one")]
pub opacity: f32,
#[serde(default = "default_true")]
pub dither: bool,
#[serde(default)]
pub reverse: bool,
#[serde(default)]
pub pigment_blending: bool,
#[serde(default)]
pub mesh: Option<GradientMeshParams>,
#[serde(default)]
pub layer_id: Option<LayerId>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GradientCommitResult {
pub modified: bool,
pub layer_id: LayerId,
pub dirty_rect: RectI32,
}
fn default_one() -> f32 {
1.0
}
fn default_true() -> bool {
true
}
const BAYER_4X4: [f32; 16] = [
0.0 / 16.0 - 0.5,
0.0,
2.0 / 16.0 - 0.5,
10.0 / 16.0 - 0.5,
12.0 / 16.0 - 0.5,
4.0 / 16.0 - 0.5,
14.0 / 16.0 - 0.5,
6.0 / 16.0 - 0.5,
3.0 / 16.0 - 0.5,
11.0 / 16.0 - 0.5,
1.0 / 16.0 - 0.5,
9.0 / 16.0 - 0.5,
15.0 / 16.0 - 0.5,
7.0 / 16.0 - 0.5,
13.0 / 16.0 - 0.5,
5.0 / 16.0 - 0.5,
];
/// Pre-baked 1024-entry gradient ramp LUT for O(1) per-pixel evaluation!
fn build_stop_lut(stops: &[GradientStop], reverse: bool, pigment_blending: bool) -> [[f32; 4]; 1024] {
let mut parsed: Vec<(f32, [f32; 4])> = stops
.iter()
.map(|s| {
let rgba = parse_hex_rgba8(&s.color).unwrap_or([0, 0, 0, 255]);
let pos = if reverse {
1.0 - s.position.clamp(0.0, 1.0)
} else {
s.position.clamp(0.0, 1.0)
};
(
pos,
[
rgba[0] as f32 / 255.0,
rgba[1] as f32 / 255.0,
rgba[2] as f32 / 255.0,
(rgba[3] as f32 / 255.0) * s.opacity.clamp(0.0, 1.0),
],
)
})
.collect();
if parsed.is_empty() {
parsed.push((0.0, [0.0, 0.0, 0.0, 1.0]));
parsed.push((1.0, [1.0, 1.0, 1.0, 1.0]));
}
parsed.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut lut = [[0.0f32; 4]; 1024];
for (i, entry) in lut.iter_mut().enumerate() {
let t = i as f32 / 1023.0;
if t <= parsed[0].0 {
*entry = parsed[0].1;
continue;
}
let last = parsed.len() - 1;
if t >= parsed[last].0 {
*entry = parsed[last].1;
continue;
}
let mut idx = 0;
while idx + 1 < parsed.len() && parsed[idx + 1].0 < t {
idx += 1;
}
let (p0, c0) = parsed[idx];
let (p1, c1) = parsed[idx + 1];
let span = (p1 - p0).max(1e-6);
let f = ((t - p0) / span).clamp(0.0, 1.0);
let rgb = if pigment_blending {
mix_pigments_srgb([c0[0], c0[1], c0[2]], [c1[0], c1[1], c1[2]], f, 0.85)
} else {
[
c0[0] + (c1[0] - c0[0]) * f,
c0[1] + (c1[1] - c0[1]) * f,
c0[2] + (c1[2] - c0[2]) * f,
]
};
let a = c0[3] + (c1[3] - c0[3]) * f;
*entry = [rgb[0], rgb[1], rgb[2], a];
}
lut
}
#[inline]
fn apply_repeat(t: f32, mode: GradientRepeatMode) -> f32 {
match mode {
GradientRepeatMode::Clamp => t.clamp(0.0, 1.0),
GradientRepeatMode::Repeat => t.rem_euclid(1.0),
GradientRepeatMode::Reflect => {
let m = t.rem_euclid(2.0);
if m <= 1.0 {
m
} else {
2.0 - m
}
}
}
}
#[inline]
fn smooth_hermite(t: f32) -> f32 {
let x = t.clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
#[inline]
fn eval_grad_blend(dst: [f32; 3], src: [f32; 3], mode: GradientBlendMode) -> [f32; 3] {
match mode {
GradientBlendMode::Normal => src,
GradientBlendMode::Multiply => [dst[0] * src[0], dst[1] * src[1], dst[2] * src[2]],
GradientBlendMode::Screen => [
1.0 - (1.0 - dst[0]) * (1.0 - src[0]),
1.0 - (1.0 - dst[1]) * (1.0 - src[1]),
1.0 - (1.0 - dst[2]) * (1.0 - src[2]),
],
GradientBlendMode::Overlay => {
let ov = |d: f32, s: f32| {
if d < 0.5 {
2.0 * d * s
} else {
1.0 - 2.0 * (1.0 - d) * (1.0 - s)
}
};
[ov(dst[0], src[0]), ov(dst[1], src[1]), ov(dst[2], src[2])]
}
}
}
/// Evaluates a gradient across `rect` into a straight RGBA8 buffer (used for both GPU live
/// preview textures and direct sparse-tile commits!).
pub fn render_gradient_rgba8(params: &GradientParams, rect: RectI32) -> Vec<u8> {
let w = rect.width as usize;
let h = rect.height as usize;
let mut out = vec![0u8; w * h * 4];
if w == 0 || h == 0 {
return out;
}
let op = params.opacity.clamp(0.0, 1.0);
let dither = params.dither;
if params.gradient_type == GradientType::Mesh {
if let Some(ref mesh) = params.mesh {
let cols = mesh.cols.max(1);
let rows = mesh.rows.max(1);
let parsed_nodes: Vec<(f32, f32, [f32; 4])> = mesh
.nodes
.iter()
.map(|n| {
let c = parse_hex_rgba8(&n.color).unwrap_or([255, 255, 255, 255]);
(
n.u,
n.v,
[
c[0] as f32 / 255.0,
c[1] as f32 / 255.0,
c[2] as f32 / 255.0,
(c[3] as f32 / 255.0) * n.opacity.clamp(0.0, 1.0),
],
)
})
.collect();
let stride = cols + 1;
let expected_nodes = stride * (rows + 1);
let mut has_deformed_uv = false;
if parsed_nodes.len() == expected_nodes {
'uv_check: for r in 0..=rows {
let ev = r as f32 / rows as f32;
for c in 0..=cols {
let eu = c as f32 / cols as f32;
let n = &parsed_nodes[r * stride + c];
if (n.0 - eu).abs() > 1e-3 || (n.1 - ev).abs() > 1e-3 {
has_deformed_uv = true;
break 'uv_check;
}
}
}
}
let cx = mesh.x + mesh.width * 0.5;
let cy = mesh.y + mesh.height * 0.5;
let c_rot = (-mesh.rotation).cos();
let s_rot = (-mesh.rotation).sin();
let inv_w = 1.0 / mesh.width.max(1.0);
let inv_h = 1.0 / mesh.height.max(1.0);
let eval_tri = |px: f32,
py: f32,
a: (f32, f32, [f32; 4]),
b: (f32, f32, [f32; 4]),
c: (f32, f32, [f32; 4])|
-> Option<[f32; 4]> {
let v0x = b.0 - a.0;
let v0y = b.1 - a.1;
let v1x = c.0 - a.0;
let v1y = c.1 - a.1;
let det = v0x * v1y - v1x * v0y;
if det.abs() < 1e-7 {
return None;
}
let inv_det = 1.0 / det;
let vx = px - a.0;
let vy = py - a.1;
let w1 = (vx * v1y - v1x * vy) * inv_det;
let w2 = (v0x * vy - vx * v0y) * inv_det;
let w0 = 1.0 - w1 - w2;
if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
let s0 = w0.clamp(0.0, 1.0);
let s1 = w1.clamp(0.0, 1.0);
let s2 = w2.clamp(0.0, 1.0);
let sum = (s0 + s1 + s2).max(1e-6);
let (f0, f1, f2) = (s0 / sum, s1 / sum, s2 / sum);
return Some([
a.2[0] * f0 + b.2[0] * f1 + c.2[0] * f2,
a.2[1] * f0 + b.2[1] * f1 + c.2[1] * f2,
a.2[2] * f0 + b.2[2] * f1 + c.2[2] * f2,
a.2[3] * f0 + b.2[3] * f1 + c.2[3] * f2,
]);
}
None
};
out.par_chunks_mut(w * 4)
.enumerate()
.for_each(|(ry, row)| {
let py = rect.y as f32 + ry as f32 + 0.5;
for rx in 0..w {
let px = rect.x as f32 + rx as f32 + 0.5;
let dx = px - cx;
let dy = py - cy;
let lx = dx * c_rot - dy * s_rot;
let ly = dx * s_rot + dy * c_rot;
let u = (lx * inv_w + 0.5).clamp(0.0, 1.0);
let v = (ly * inv_h + 0.5).clamp(0.0, 1.0);
let mut col = if has_deformed_uv && parsed_nodes.len() == expected_nodes {
let mut hit: Option<[f32; 4]> = None;
'quad_loop: for r in 0..rows {
for c in 0..cols {
let p00 = parsed_nodes[r * stride + c];
let p10 = parsed_nodes[r * stride + c + 1];
let p01 = parsed_nodes[(r + 1) * stride + c];
let p11 = parsed_nodes[(r + 1) * stride + c + 1];
if let Some(res) = eval_tri(u, v, p00, p10, p11)
.or_else(|| eval_tri(u, v, p00, p11, p01))
{
hit = Some(res);
break 'quad_loop;
}
}
}
let mut c = hit.unwrap_or_else(|| {
let mut acc = [0.0f32; 4];
let mut wsum = 0.0f32;
for &(nu, nv, nc) in &parsed_nodes {
let du = u - nu;
let dv = v - nv;
let d2 = du * du + dv * dv;
let wt = 1.0 / (d2 * d2 + 1e-6);
acc[0] += nc[0] * wt;
acc[1] += nc[1] * wt;
acc[2] += nc[2] * wt;
acc[3] += nc[3] * wt;
wsum += wt;
}
let inv = 1.0 / wsum.max(1e-6);
[acc[0] * inv, acc[1] * inv, acc[2] * inv, acc[3] * inv]
});
c[3] *= op;
c
} else {
let col_f = (u * cols as f32).min(cols as f32 - 1e-5);
let row_f = (v * rows as f32).min(rows as f32 - 1e-5);
let ci = col_f.floor() as usize;
let ri = row_f.floor() as usize;
let fu = smooth_hermite(col_f - ci as f32);
let fv = smooth_hermite(row_f - ri as f32);
let get_c = |c: usize, r: usize| -> [f32; 4] {
parsed_nodes
.get(r * stride + c)
.map(|n| n.2)
.unwrap_or([0.0, 0.0, 0.0, 1.0])
};
let c00 = get_c(ci, ri);
let c10 = get_c((ci + 1).min(cols), ri);
let c01 = get_c(ci, (ri + 1).min(rows));
let c11 = get_c((ci + 1).min(cols), (ri + 1).min(rows));
let top = [
c00[0] + (c10[0] - c00[0]) * fu,
c00[1] + (c10[1] - c00[1]) * fu,
c00[2] + (c10[2] - c00[2]) * fu,
c00[3] + (c10[3] - c00[3]) * fu,
];
let bot = [
c01[0] + (c11[0] - c01[0]) * fu,
c01[1] + (c11[1] - c01[1]) * fu,
c01[2] + (c11[2] - c01[2]) * fu,
c01[3] + (c11[3] - c01[3]) * fu,
];
[
top[0] + (bot[0] - top[0]) * fv,
top[1] + (bot[1] - top[1]) * fv,
top[2] + (bot[2] - top[2]) * fv,
(top[3] + (bot[3] - top[3]) * fv) * op,
]
};
if dither {
let b = BAYER_4X4[(ry & 3) * 4 + (rx & 3)] / 255.0;
col[0] += b;
col[1] += b;
col[2] += b;
}
let o = rx * 4;
row[o] = (col[0] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 1] = (col[1] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 2] = (col[2] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 3] = (col[3] * 255.0).round().clamp(0.0, 255.0) as u8;
}
});
return out;
}
}
let lut = build_stop_lut(¶ms.stops, params.reverse, params.pigment_blending);
let sx = params.start[0];
let sy = params.start[1];
let dx = params.end[0] - sx;
let dy = params.end[1] - sy;
let len2 = (dx * dx + dy * dy).max(1e-6);
let len = len2.sqrt();
let ux = dx / len;
let uy = dy / len;
let base_ang = dy.atan2(dx);
let gtype = params.gradient_type;
let repeat = params.repeat;
out.par_chunks_mut(w * 4)
.enumerate()
.for_each(|(ry, row)| {
let py = rect.y as f32 + ry as f32 + 0.5;
for rx in 0..w {
let px = rect.x as f32 + rx as f32 + 0.5;
let vx = px - sx;
let vy = py - sy;
let raw_t = match gtype {
GradientType::Linear => (vx * dx + vy * dy) / len2,
GradientType::Radial => vx.hypot(vy) / len,
GradientType::Conical => {
let a = (vy.atan2(vx) - base_ang).rem_euclid(TAU);
a / TAU
}
GradientType::Diamond => {
let along = (vx * ux + vy * uy).abs();
let perp = (-vx * uy + vy * ux).abs();
(along + perp) / len
}
GradientType::Mesh => 0.0,
};
let t = apply_repeat(raw_t, repeat);
let li = ((t * 1023.0).round() as usize).min(1023);
let mut col = lut[li];
col[3] *= op;
if dither {
let b = BAYER_4X4[(ry & 3) * 4 + (rx & 3)] / 255.0;
col[0] += b;
col[1] += b;
col[2] += b;
}
let o = rx * 4;
row[o] = (col[0] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 1] = (col[1] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 2] = (col[2] * 255.0).round().clamp(0.0, 255.0) as u8;
row[o + 3] = (col[3] * 255.0).round().clamp(0.0, 255.0) as u8;
}
});
out
}
/// Commits a gradient directly onto `Document`'s target layer respecting active
/// `SparseSelectionMask`, `alphaLocked`, blend mode, and recording an atomic CoW Undo step!
pub fn commit_gradient_to_document(
doc: &mut Document,
params: &GradientParams,
scratch: Option<&dyn ScratchBackend>,
) -> Result<GradientCommitResult, String> {
let layer_id = params
.layer_id
.clone()
.or_else(|| doc.active_layer_id.clone())
.ok_or_else(|| "No active layer for gradient".to_string())?;
let (alpha_locked, mono_thresh) = {
let l = doc
.layer(&layer_id)
.ok_or_else(|| format!("Layer not found: {layer_id}"))?;
if !l.meta.layer_type.has_tiles() || l.meta.locked {
return Err("Target layer is locked or non-raster".to_string());
}
(
l.meta.alpha_locked.unwrap_or(false),
l.meta.mono_threshold.unwrap_or(128),
)
};
let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
let active_sel = doc.selection.as_ref().filter(|s| !s.is_empty());
let work_rect = match active_sel {
Some(sel) => sel.bounds.intersect(doc_rect),
None => doc_rect,
};
if work_rect.is_empty() {
return Ok(GradientCommitResult {
modified: false,
layer_id,
dirty_rect: RectI32::empty(),
});
}
let sel_mask = active_sel.map(|s| s.read_rect(work_rect));
let grad_rgba = render_gradient_rgba8(params, work_rect);
let mut dst_rgba = doc
.layer(&layer_id)
.ok_or_else(|| format!("Layer not found: {layer_id}"))?
.grid
.read_rgba8_rect(work_rect, false, scratch)?;
let blend = params.blend_mode;
let w = work_rect.width as usize;
dst_rgba
.par_chunks_mut(w * 4)
.enumerate()
.for_each(|(ry, row)| {
let roff = ry * w;
for rx in 0..w {
let o = rx * 4;
let g_off = (roff + rx) * 4;
let mut sa = grad_rgba[g_off + 3] as f32 / 255.0;
if let Some(ref sm) = sel_mask {
sa *= sm[roff + rx] as f32 / 255.0;
}
if sa <= 1e-4 {
continue;
}
let src_rgb = [
grad_rgba[g_off] as f32 / 255.0,
grad_rgba[g_off + 1] as f32 / 255.0,
grad_rgba[g_off + 2] as f32 / 255.0,
];
let dst_rgb = [
row[o] as f32 / 255.0,
row[o + 1] as f32 / 255.0,
row[o + 2] as f32 / 255.0,
];
let da = row[o + 3] as f32 / 255.0;
let blended = if da > 1e-4 {
eval_grad_blend(dst_rgb, src_rgb, blend)
} else {
src_rgb
};
if alpha_locked {
if da <= 1e-4 {
continue;
}
row[o] = ((dst_rgb[0] + (blended[0] - dst_rgb[0]) * sa) * 255.0)
.round()
.clamp(0.0, 255.0) as u8;
row[o + 1] = ((dst_rgb[1] + (blended[1] - dst_rgb[1]) * sa) * 255.0)
.round()
.clamp(0.0, 255.0) as u8;
row[o + 2] = ((dst_rgb[2] + (blended[2] - dst_rgb[2]) * sa) * 255.0)
.round()
.clamp(0.0, 255.0) as u8;
} else {
let out_a = (sa + da * (1.0 - sa)).clamp(0.0, 1.0);
if out_a <= 1e-5 {
continue;
}
let inv_a = 1.0 / out_a;
for c in 0..3 {
let premul = blended[c] * (sa * da)
+ src_rgb[c] * (sa * (1.0 - da))
+ dst_rgb[c] * (da * (1.0 - sa));
row[o + c] = (premul * inv_a * 255.0).round().clamp(0.0, 255.0) as u8;
}
row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
}
}
});
let deltas = {
let layer = doc
.layer_mut(&layer_id)
.ok_or_else(|| format!("Layer not found: {layer_id}"))?;
let before = layer.grid.snapshot_all_cow(TileKind::Raster);
let touched = layer
.grid
.write_rgba8_rect(&dst_rgba, work_rect, mono_thresh, scratch)?;
let mut d = Vec::with_capacity(touched.len());
for coord in touched {
let b = before.get(&coord).cloned();
let a = layer.grid.tiles.get(&coord).cloned();
let same = match (&b, &a) {
(None, None) => true,
(Some(x), Some(y)) => Arc::ptr_eq(x, y) || x.version == y.version,
_ => false,
};
if !same {
d.push(CowTileDelta {
layer_id: layer_id.clone(),
coord,
kind: TileKind::Raster,
before: b,
after: a,
remote_epoch: layer.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
});
}
}
d
};
let modified = !deltas.is_empty();
if modified {
doc.record_stroke_deltas(&layer_id, "gradient", "Gradient", deltas, None, None);
}
Ok(GradientCommitResult {
modified,
layer_id,
dirty_rect: work_rect,
})
}