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
//! Native `wgpu` + WGSL Layer Compositor for InkStudio (Phase 3).
//!
//! Renders the entire InkStudio layer stack natively on DX12 in `Rgba16Float` precision:
//! - All 28 blend modes (`0..=27`)
//! - Clipping-mask chains (`clipped: true`) with continuous-alpha clipping
//! - Nested `folder` and comic `frame-folder` (`pass-through` and isolated)
//! - Non-destructive 8-bit layer masks (`mask_tiles`)
//! - CSP Expression Color (`color` / `gray` / `monochrome`), two-tone Layer Color tint,
//! and 1-bit rational-lattice Screentones (`circle` / `euclidean` / `line` / `diamond`)
//! - Non-destructive Adjustment Layers (`curves`, `levels`, `gradient-map`, `color-balance`)
//! - Non-destructive Layer Styles (`stroke`, `dropShadow`, `outerGlow`) cached per layer version
//! - 3-slice baked layer stack caching (`below_active_cache`, `active_unit_surface`,
//! `above_dynamic` + `above_active_cache`) with dirty-rect scissor updates & WYSIWYG live strokes
//! - Viewport display passes: animation onion skins, CMYK soft proof + gamut warning,
//! perceptual B/W value check, adaptive high-zoom pixel grid, artboard checkerboard/chrome
//! - Headless document-space GPU flattening (`render_document_flattened`) for export,
//! timelapse capture, Navigator preview, and async per-layer thumbnails
pub mod frame_geometry;
pub mod layer_tree;
pub mod lut;
pub mod renderer;
pub mod shaders;
pub mod stack_cache;
pub mod targets;
pub use renderer::{
LiveGpuStrokeOverlay, LiveImpastoOverlay, WgpuCompositor,
};
pub use stack_cache::{
calculate_visible_doc_bounds, doc_bounds_to_scissor, select_lod_for_zoom, DocBounds,
LayerStackCacheTracker, ScissorRect, StackCacheEvaluation, StackCacheStats,
};
use crate::tiles::{parse_hex_rgba8, RectI32};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Supported CMYK Soft Proofing ICC profile standards matching `src/types/editor.ts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CmykStandard {
#[default]
#[serde(rename = "japan-color-2001")]
JapanColor2001,
#[serde(rename = "us-web-coated-swop")]
UsWebCoatedSwop,
#[serde(rename = "iso-coated-v2")]
IsoCoatedV2,
}
impl CmykStandard {
#[inline]
pub fn to_shader_code(self) -> u32 {
match self {
Self::JapanColor2001 => 0,
Self::UsWebCoatedSwop => 1,
Self::IsoCoatedV2 => 2,
}
}
}
/// CMYK Soft Proofing & out-of-gamut warning configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SoftProofConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub standard: CmykStandard,
#[serde(default)]
pub gamut_warning: bool,
#[serde(default = "default_gamut_warning_color")]
pub gamut_warning_color: String,
}
fn default_gamut_warning_color() -> String {
"#808080".to_string()
}
impl Default for SoftProofConfig {
fn default() -> Self {
Self {
enabled: false,
standard: CmykStandard::JapanColor2001,
gamut_warning: false,
gamut_warning_color: default_gamut_warning_color(),
}
}
}
/// A single animation onion-skin ghost frame tinted and composited behind the active cel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OnionSkinFrame {
pub layer_id: String,
/// RGB tint color in `[0.0..=1.0]` (e.g. blue for previous cels, green for next cels).
pub tint: [f32; 3],
/// Ghost opacity in `[0.0..=1.0]`.
pub opacity: f32,
}
fn default_true() -> bool {
true
}
fn default_matte_color() -> [f32; 4] {
[0.086, 0.086, 0.086, 1.0]
}
/// Complete viewport display configuration pushed from the frontend UI to `ink-engine`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompositorDisplayConfig {
#[serde(default = "default_true")]
pub show_checkerboard: bool,
#[serde(default = "default_matte_color")]
pub matte_color: [f32; 4],
#[serde(default)]
pub soft_proof: SoftProofConfig,
#[serde(default)]
pub value_check_enabled: bool,
#[serde(default = "default_true")]
pub show_pixel_grid: bool,
#[serde(default)]
pub onion_skin_frames: Vec<OnionSkinFrame>,
#[serde(default)]
pub cel_visibility_overrides: HashMap<String, bool>,
#[serde(default = "default_true")]
pub layer_stack_caching: bool,
}
impl Default for CompositorDisplayConfig {
fn default() -> Self {
Self {
show_checkerboard: true,
matte_color: default_matte_color(),
soft_proof: SoftProofConfig::default(),
value_check_enabled: false,
show_pixel_grid: true,
onion_skin_frames: Vec::new(),
cel_visibility_overrides: HashMap::new(),
layer_stack_caching: true,
}
}
}
/// Options for headless document-space GPU flattening (`render_document_flattened`).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FlattenOptions {
/// Optional maximum output dimension in pixels (preserving aspect ratio).
/// `None` renders at full document resolution (`width × height`).
#[serde(default)]
pub max_dim: Option<u32>,
/// Optional document-space sub-region to render (e.g. Webtoon slice export).
#[serde(default)]
pub region: Option<RectI32>,
/// Fill opaque white background behind transparent artwork (e.g. JPEG/timelapse/Navigator).
#[serde(default)]
pub fill_white_background: bool,
/// Render 16px checkerboard behind transparent areas (ignored if `fill_white_background` is true).
#[serde(default)]
pub show_checkerboard: bool,
/// Apply CMYK soft proof during flatten (e.g. proofed export or Navigator).
#[serde(default)]
pub apply_soft_proof: bool,
#[serde(default)]
pub soft_proof: SoftProofConfig,
/// Apply perceptual B/W value check during flatten.
#[serde(default)]
pub apply_value_check: bool,
#[serde(default)]
pub cel_visibility_overrides: HashMap<String, bool>,
#[serde(default)]
pub onion_skin_frames: Vec<OnionSkinFrame>,
}
/// Stroke placement position for non-destructive Layer Styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokePosition {
Outside = 0,
Inside = 1,
Center = 2,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeStyle {
pub enabled: bool,
pub size: f32,
pub color: [f32; 3],
pub opacity: f32,
pub position: StrokePosition,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DropShadowStyle {
pub enabled: bool,
pub color: [f32; 3],
pub opacity: f32,
pub offset_x: f32,
pub offset_y: f32,
pub blur: f32,
pub spread: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OuterGlowStyle {
pub enabled: bool,
pub color: [f32; 3],
pub opacity: f32,
pub blur: f32,
pub spread: f32,
}
/// Parsed non-destructive layer styles (`stroke`, `dropShadow`, `outerGlow`).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ParsedLayerStyles {
pub stroke: Option<StrokeStyle>,
pub drop_shadow: Option<DropShadowStyle>,
pub outer_glow: Option<OuterGlowStyle>,
}
impl ParsedLayerStyles {
pub fn has_active(&self) -> bool {
self.stroke.is_some_and(|s| s.enabled && s.size > 0.0 && s.opacity > 0.001)
|| self.drop_shadow.is_some_and(|s| s.enabled && s.opacity > 0.001)
|| self.outer_glow.is_some_and(|s| s.enabled && s.opacity > 0.001)
}
/// Conservative expansion margin in document pixels needed around a chunk/tile so
/// strokes, drop shadows, and outer glows don't clip at chunk boundaries.
pub fn max_margin_doc_px(&self) -> f32 {
let mut margin = 0.0f32;
if let Some(s) = self.stroke {
if s.enabled && s.opacity > 0.001 {
margin = margin.max(s.size);
}
}
if let Some(g) = self.outer_glow {
if g.enabled && g.opacity > 0.001 {
margin = margin.max(g.blur * 2.0 + 4.0);
}
}
if let Some(sh) = self.drop_shadow {
if sh.enabled && sh.opacity > 0.001 {
let off = sh.offset_x.abs().max(sh.offset_y.abs());
margin = margin.max(off + sh.blur * 2.0 + 4.0);
}
}
margin.ceil()
}
}
/// Parses a CSS `#rgb` / `#rrggbb` / `#rrggbbaa` hex string into normalized `[r, g, b]` in `0..=1`.
pub fn hex_to_rgb_f32(hex: &str, default: [f32; 3]) -> [f32; 3] {
if let Some(rgba) = parse_hex_rgba8(hex) {
[
rgba[0] as f32 / 255.0,
rgba[1] as f32 / 255.0,
rgba[2] as f32 / 255.0,
]
} else {
default
}
}
/// Parses `LayerNodeMeta::styles` JSON into strongly-typed [`ParsedLayerStyles`].
pub fn parse_layer_styles(val: Option<&serde_json::Value>) -> ParsedLayerStyles {
let Some(obj) = val.and_then(|v| v.as_object()) else {
return ParsedLayerStyles::default();
};
let stroke = obj.get("stroke").and_then(|v| v.as_object()).map(|s| {
let enabled = s.get("enabled").and_then(|b| b.as_bool()).unwrap_or(false);
let size = s
.get("size")
.and_then(|n| n.as_f64())
.unwrap_or(0.0)
.clamp(0.0, 200.0) as f32;
let opacity = s
.get("opacity")
.and_then(|n| n.as_f64())
.unwrap_or(1.0)
.clamp(0.0, 1.0) as f32;
let color = s
.get("color")
.and_then(|c| c.as_str())
.map(|hex| hex_to_rgb_f32(hex, [0.0, 0.0, 0.0]))
.unwrap_or([0.0, 0.0, 0.0]);
let position = match s.get("position").and_then(|p| p.as_str()) {
Some("inside") => StrokePosition::Inside,
Some("center") => StrokePosition::Center,
_ => StrokePosition::Outside,
};
StrokeStyle {
enabled,
size,
color,
opacity,
position,
}
});
let drop_shadow = obj.get("dropShadow").and_then(|v| v.as_object()).map(|s| {
let enabled = s.get("enabled").and_then(|b| b.as_bool()).unwrap_or(false);
let opacity = s
.get("opacity")
.and_then(|n| n.as_f64())
.unwrap_or(0.5)
.clamp(0.0, 1.0) as f32;
let color = s
.get("color")
.and_then(|c| c.as_str())
.map(|hex| hex_to_rgb_f32(hex, [0.0, 0.0, 0.0]))
.unwrap_or([0.0, 0.0, 0.0]);
let (offset_x, offset_y) = if s.contains_key("offsetX") || s.contains_key("offsetY") {
(
s.get("offsetX").and_then(|n| n.as_f64()).unwrap_or(0.0) as f32,
s.get("offsetY").and_then(|n| n.as_f64()).unwrap_or(0.0) as f32,
)
} else {
let dist = s.get("distance").and_then(|n| n.as_f64()).unwrap_or(0.0);
let angle_rad = s
.get("angle")
.and_then(|n| n.as_f64())
.unwrap_or(0.0)
.to_radians();
(
(dist * angle_rad.cos()) as f32,
(dist * angle_rad.sin()) as f32,
)
};
let blur = s
.get("blur")
.and_then(|n| n.as_f64())
.unwrap_or(0.0)
.clamp(0.0, 200.0) as f32;
let raw_spread = s.get("spread").and_then(|n| n.as_f64()).unwrap_or(0.0);
let spread = (raw_spread / 100.0).clamp(0.0, 1.0) as f32;
DropShadowStyle {
enabled,
color,
opacity,
offset_x,
offset_y,
blur,
spread,
}
});
let outer_glow = obj.get("outerGlow").and_then(|v| v.as_object()).map(|s| {
let enabled = s.get("enabled").and_then(|b| b.as_bool()).unwrap_or(false);
let opacity = s
.get("opacity")
.and_then(|n| n.as_f64())
.unwrap_or(0.75)
.clamp(0.0, 1.0) as f32;
let color = s
.get("color")
.and_then(|c| c.as_str())
.map(|hex| hex_to_rgb_f32(hex, [1.0, 1.0, 0.0]))
.unwrap_or([1.0, 1.0, 0.0]);
let blur = s
.get("blur")
.and_then(|n| n.as_f64())
.unwrap_or(0.0)
.clamp(0.0, 200.0) as f32;
let raw_spread = s.get("spread").and_then(|n| n.as_f64()).unwrap_or(0.0);
let spread = (raw_spread / 100.0).clamp(0.0, 1.0) as f32;
OuterGlowStyle {
enabled,
color,
opacity,
blur,
spread,
}
});
ParsedLayerStyles {
stroke,
drop_shadow,
outer_glow,
}
}