Skip to content

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

34.8 KB
Raw Blame
//! Complete WGSL shader library for InkStudio's Phase 4 GPU Instanced Brush Engine:
//!
//! 1. `PAPER_GRAIN_WGSL`: All 9 `CspPaperTextureMode`s + all 4 `GrainMappingMode`s +
//!    brightness, contrast, scale, rotate, offset, invert, emphasizeDensity, pressure penetration.
//! 2. `BRUSH_DAB_TILE_WGSL`: Instanced dab rasterizer into `256×256` `Rgba16Float` sparse
//!    stroke tiles (and camera-projected transient prediction overlay!), supporting analytical
//!    SDF tips (`hardness`, `antiAlias` 0..3 including crisp 1-bit binary manga ink), textured
//!    multi-subTip `texture_2d_array<f32>`, `flipH`/`flipV`, `isColorTip`, `isDualToneTip`,
//!    and per-dab paper grain.
//! 3. `STROKE_DARKEN_MERGE_WGSL`: Exact `blendTipsMode::Darken` tile merge compute shader.
//! 4. `STROKE_POST_TILE_WGSL`: Dual Brush combine (all 12 `DualBrushCompositeMode`s) +
//!    Per-Stroke Paper Grain (`paperTextureApplyEachPlot == false`) compute shader.
//! 5. `WET_EDGE_TILE_WGSL`: Seamless 2-pass separable Gaussian alpha-blur + watercolor
//!    inner-rim darkening & alpha-boost compute shader with 3×3 neighbor tile sampling.
//! 6. `TILE_COMMIT_COMPUTE_WGSL`: Sub-millisecond GPU-to-GPU tile commit into `GpuTilePool`
//!    with all 32 `CspBrushCombineMode`s, `alphaLocked`, `isEraser`/`isTransparentInk`/
//!    `isBgEraser`, monochrome 1-bit binarization, selection-mask hook, and simultaneous
//!    packed RGBA8 readback generation for `SparseLayerGrid` + CoW Undo.

use crate::compositor::shaders::blend_modes::BLEND_MODES_WGSL;

/// Shared WGSL paper grain sampling & 9-mode CSP paper texture modulation.
pub const PAPER_GRAIN_WGSL: &str = r#"
fn sample_paper_grain_height(
    paper_tex: texture_2d<f32>,
    paper_sampler: sampler,
    doc_coord: vec2<f32>,
    local_uv: vec2<f32>,
    stroke_angle_rad: f32,
    paper_size: vec2<f32>,
    mapping_mode: u32,
    scale: f32,
    rot_rad: f32,
    offset_norm: vec2<f32>,
    stroke_rand_offset: vec2<f32>,
    brightness: f32,
    contrast: f32,
    invert_flag: u32,
) -> f32 {
    let safe_scale = max(0.05, scale);
    let inv_size = 1.0 / max(vec2<f32>(1.0), paper_size * safe_scale);

    var base_uv: vec2<f32>;
    switch (mapping_mode) {
        case 1u: {
            // brush-aligned: sample in dab local space
            base_uv = (local_uv - vec2<f32>(0.5)) / safe_scale + vec2<f32>(0.5);
        }
        case 2u: {
            // stroke-flow: rotate canvas coordinate into stroke tangent space
            let cs = cos(-stroke_angle_rad);
            let sn = sin(-stroke_angle_rad);
            let flow = vec2<f32>(
                doc_coord.x * cs - doc_coord.y * sn,
                doc_coord.x * sn + doc_coord.y * cs,
            );
            base_uv = flow * inv_size;
        }
        case 3u: {
            // random-per-stroke: canvas-locked shifted by per-stroke PRNG offset
            base_uv = doc_coord * inv_size + stroke_rand_offset;
        }
        default: {
            // 0: canvas-locked
            base_uv = doc_coord * inv_size;
        }
    }

    let c = cos(rot_rad);
    let s = sin(rot_rad);
    let rot_uv = vec2<f32>(
        base_uv.x * c - base_uv.y * s,
        base_uv.x * s + base_uv.y * c,
    ) + offset_norm;

    let sample_rgba = textureSampleLevel(paper_tex, paper_sampler, rot_uv, 0.0);
    var h = dot(sample_rgba.rgb, vec3<f32>(0.299, 0.587, 0.114));

    // Apply brightness (-100..100 normalized to -1..1) and contrast (-100..100)
    let b_norm = clamp(brightness * 0.01, -1.0, 1.0);
    let c_norm = clamp(contrast * 0.01, -0.95, 0.99);
    let c_gain = (1.0 + c_norm) / max(0.05, 1.0 - c_norm * 0.85);
    h = clamp((h - 0.5) * c_gain + 0.5 + b_norm * 0.5, 0.0, 1.0);
    if (invert_flag != 0u) {
        h = 1.0 - h;
    }
    return h;
}

/// Applies all 9 CSP Paper Texture Modes to stroke/dab alpha `a_in` using paper height `h`
/// (`0.0` = deep valley, `1.0` = high peak) and strength `strength` (`0..=1`).
/// Exact parity with `BrushEngine.ts` & `WebGlBrushEngine.ts`.
fn apply_csp_paper_texture_mode(
    a_in: f32,
    h_raw: f32,
    strength: f32,
    mode: u32,
    emphasize_density: u32,
    pressure: f32,
) -> f32 {
    if (strength <= 0.001 || a_in <= 0.0005) {
        return a_in;
    }
    let s = clamp(strength, 0.0, 1.0);
    // Higher stylus pressure penetrates further into paper valleys when emphasizeDensity is active
    var eff_s = s;
    if (emphasize_density != 0u) {
        eff_s = clamp(s * (1.28 - clamp(pressure, 0.0, 1.0) * 0.45), 0.0, 1.0);
    }
    // Paper tooth darkness `t` (0 = valley/unpainted, 1 = peak/tooth catching pigment)
    let h = clamp(h_raw, 0.0, 1.0);
    let inv_h = 1.0 - h;
    var mod_a = a_in;

    switch (mode) {
        case 0u: {
            // subtract: subtracts paper valley depth from dab density
            mod_a = max(0.0, a_in - inv_h * eff_s);
        }
        case 1u: {
            // multiply: multiplies alpha by paper peak height
            mod_a = a_in * mix(1.0, h, eff_s);
        }
        case 2u: {
            // compare: crisp tooth threshold — paint catches peaks where a_in + h crosses threshold
            let thresh = inv_h * eff_s;
            let softness = 0.08 + (1.0 - eff_s) * 0.12;
            let mask = smoothstep(thresh - softness, thresh + softness, a_in);
            mod_a = a_in * mask;
        }
        case 3u: {
            // overlay: deepens valleys and boosts peaks
            var ov: f32;
            if (a_in < 0.5) {
                ov = 2.0 * a_in * h;
            } else {
                ov = 1.0 - 2.0 * (1.0 - a_in) * (1.0 - h);
            }
            mod_a = mix(a_in, ov, eff_s);
        }
        case 4u: {
            // outline: emphasizes paper grain contours along partial-alpha edges
            let edge_weight = clamp(1.0 - abs(a_in * 2.0 - 1.0), 0.0, 1.0);
            mod_a = clamp(a_in * mix(1.0, h, eff_s * (0.35 + 0.65 * edge_weight)), 0.0, 1.0);
        }
        case 5u: {
            // normal: linear mix toward paper texture density
            mod_a = mix(a_in, a_in * h, eff_s * 0.85);
        }
        case 6u: {
            // color-burn: high-contrast dry-media tooth burn
            let burned = select(0.0, 1.0 - min(1.0, (1.0 - a_in) / max(0.02, h)), h > 0.02);
            mod_a = mix(a_in, burned, eff_s);
        }
        case 7u: {
            // linear-burn: linear tooth subtraction with sharp dark valleys
            let lb = clamp(a_in + h - 1.0, 0.0, 1.0);
            mod_a = mix(a_in, lb, eff_s);
        }
        case 8u: {
            // height: physical dry-media heightfield threshold (peaks fill first, valleys fill at high density/pressure)
            let fill = clamp(a_in * (1.0 + (1.0 - eff_s) * 0.5) - inv_h * eff_s * 1.15, 0.0, 1.0);
            mod_a = smoothstep(0.0, 0.35 + (1.0 - eff_s) * 0.35, fill) * a_in;
        }
        default: {
            mod_a = a_in * mix(1.0, h, eff_s);
        }
    }
    return clamp(mod_a, 0.0, 1.0);
}
"#;

/// Instanced GPU brush dab rasterizer rendering into either:
/// - `vs_tile`: a `256×256` `Rgba16Float` sparse stroke tile at `tile_origin_doc`, OR
/// - `vs_viewport`: the camera-projected viewport predicted-head target!
pub fn build_brush_dab_wgsl() -> String {
    format!(
        r#"
struct DabPassUniforms {{
    // Tile mode: origin_doc = [tx * 256, ty * 256], doc_size = [doc_w, doc_h]
    tile_origin_doc: vec2<f32>,
    doc_size: vec2<f32>,
    // Viewport prediction mode camera transform
    viewport_size_phys: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    paper_scale: f32,
    paper_rot_rad: f32,
    paper_brightness: f32,
    paper_contrast: f32,
    _pad0: f32,
    paper_size: vec2<f32>,
    paper_offset_norm: vec2<f32>,
    stroke_rand_offset: vec2<f32>,
    // flags0 = [use_tip_tex, is_color_tip, is_dual_tone_tip, anti_alias]
    flags0: vec4<u32>,
    // flags1 = [paper_apply_per_dab, paper_mode, grain_mapping_mode, paper_invert]
    flags1: vec4<u32>,
    // flags2 = [emphasize_density, tip_layer_count, mono_1bit, _pad]
    flags2: vec4<u32>,
}};

@group(0) @binding(0) var<uniform> u: DabPassUniforms;
@group(0) @binding(1) var tip_tex_array: texture_2d_array<f32>;
@group(0) @binding(2) var tip_sampler: sampler;
@group(0) @binding(3) var paper_tex: texture_2d<f32>;
@group(0) @binding(4) var paper_sampler: sampler;

struct DabInstance {{
    @location(0) pos_size: vec4<f32>,
    @location(1) rot_tip: vec4<f32>,
    @location(2) color_rgba: vec4<f32>,
    @location(3) bg_grain: vec4<f32>,
    @location(4) extra: vec4<f32>,
}};

struct VsOut {{
    @builtin(position) pos: vec4<f32>,
    @location(0) local_unit: vec2<f32>,
    @location(1) doc_coord: vec2<f32>,
    @location(2) half_size: vec2<f32>,
    @location(3) color_rgba: vec4<f32>,
    @location(4) bg_grain: vec4<f32>,
    @location(5) tip_params: vec4<f32>,
    @location(6) extra: vec4<f32>,
}};

fn quad_corner(vid: u32) -> vec2<f32> {{
    switch (vid) {{
        case 0u: {{ return vec2<f32>(-1.0, -1.0); }}
        case 1u: {{ return vec2<f32>( 1.0, -1.0); }}
        case 2u: {{ return vec2<f32>(-1.0,  1.0); }}
        case 3u: {{ return vec2<f32>(-1.0,  1.0); }}
        case 4u: {{ return vec2<f32>( 1.0, -1.0); }}
        default: {{ return vec2<f32>( 1.0,  1.0); }}
    }}
}}

@vertex
fn vs_tile(@builtin(vertex_index) vid: u32, inst: DabInstance) -> VsOut {{
    let corner = quad_corner(vid);
    let pad = 1.5;
    let hw = max(0.25, inst.pos_size.z);
    let hh = max(0.25, inst.pos_size.w);
    let local_px = vec2<f32>(corner.x * (hw + pad), corner.y * (hh + pad));
    let c = inst.rot_tip.x;
    let s = inst.rot_tip.y;
    let rot_px = vec2<f32>(
        local_px.x * c - local_px.y * s,
        local_px.x * s + local_px.y * c,
    );
    let doc_pos = inst.pos_size.xy + rot_px;
    let tile_local = doc_pos - u.tile_origin_doc;
    let ndc = vec2<f32>(
        (tile_local.x / 256.0) * 2.0 - 1.0,
        1.0 - (tile_local.y / 256.0) * 2.0,
    );

    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.local_unit = vec2<f32>(local_px.x / hw, local_px.y / hh);
    out.doc_coord = doc_pos;
    out.half_size = vec2<f32>(hw, hh);
    out.color_rgba = inst.color_rgba;
    out.bg_grain = inst.bg_grain;
    out.tip_params = vec4<f32>(inst.rot_tip.z, inst.rot_tip.w, 0.0, 0.0);
    out.extra = inst.extra;
    return out;
}}

@vertex
fn vs_viewport(@builtin(vertex_index) vid: u32, inst: DabInstance) -> VsOut {{
    let corner = quad_corner(vid);
    let pad = max(1.5, 1.5 / max(0.05, u.zoom));
    let hw = max(0.25, inst.pos_size.z);
    let hh = max(0.25, inst.pos_size.w);
    let local_px = vec2<f32>(corner.x * (hw + pad), corner.y * (hh + pad));
    let c = inst.rot_tip.x;
    let s = inst.rot_tip.y;
    let rot_px = vec2<f32>(
        local_px.x * c - local_px.y * s,
        local_px.x * s + local_px.y * c,
    );
    let doc_pos = inst.pos_size.xy + rot_px;

    let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
    let cr = cos(u.rotation_rad);
    let sr = sin(u.rotation_rad);
    let rotated = vec2<f32>(
        centered.x * cr - centered.y * sr,
        centered.x * sr + centered.y * cr,
    );
    let screen_phys = (u.pan_css + rotated * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );

    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.local_unit = vec2<f32>(local_px.x / hw, local_px.y / hh);
    out.doc_coord = doc_pos;
    out.half_size = vec2<f32>(hw, hh);
    out.color_rgba = inst.color_rgba;
    out.bg_grain = inst.bg_grain;
    out.tip_params = vec4<f32>(inst.rot_tip.z, inst.rot_tip.w, 0.0, 0.0);
    out.extra = inst.extra;
    return out;
}}

{PAPER_GRAIN_WGSL}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
    if (
        in.doc_coord.x < 0.0 ||
        in.doc_coord.y < 0.0 ||
        in.doc_coord.x >= u.doc_size.x ||
        in.doc_coord.y >= u.doc_size.y
    ) {{
        discard;
    }}

    let aa_level = u.flags0.w;
    let mono_1bit = u.flags2.z != 0u;
    var rgb = in.color_rgba.rgb;
    var shape_a = 0.0;
    let uv = vec2<f32>(
        in.local_unit.x * in.extra.x * 0.5 + 0.5,
        in.local_unit.y * in.extra.y * 0.5 + 0.5,
    );

    if (u.flags0.x != 0u) {{
        // Textured tip (single or multi-subTip array)
        if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {{
            discard;
        }}
        let max_layer = max(1u, u.flags2.y) - 1u;
        let layer_i = i32(clamp(u32(round(in.tip_params.x)), 0u, max_layer));
        let tex = textureSampleLevel(tip_tex_array, tip_sampler, uv, layer_i, 0.0);
        shape_a = tex.a;
        if (u.flags0.y != 0u) {{
            // Color tip preserves embedded RGB directly
            rgb = tex.rgb;
        }} else if (u.flags0.z != 0u) {{
            // Dual-tone tip maps luminance 0 -> fg_color, 1 -> bg_color
            let lum = dot(tex.rgb, vec3<f32>(0.299, 0.587, 0.114));
            rgb = mix(in.color_rgba.rgb, in.bg_grain.rgb, lum);
        }}
        // Anti-aliasing shaping for textured tips (0 = binary 1-bit crisp manga ink)
        if (aa_level == 0u || mono_1bit) {{
            shape_a = step(0.5, shape_a);
        }} else if (aa_level == 1u) {{
            shape_a = smoothstep(0.28, 0.72, shape_a);
        }}
    }} else {{
        // Analytical circular / elliptical tip with hardness & anti-aliasing 0..3
        let r = length(in.local_unit);
        let min_half = max(0.35, min(in.half_size.x, in.half_size.y));
        let px_aa = select(1.0 / min_half, 0.0, aa_level == 0u || mono_1bit);
        if (r > 1.0 + px_aa * 1.5) {{
            discard;
        }}

        let h = clamp(in.tip_params.y, 0.0, 1.0);
        if (aa_level == 0u || mono_1bit) {{
            // Crisp 1-bit binary manga inking (zero intermediate alpha fringe)
            shape_a = select(0.0, 1.0, r <= 1.0);
        }} else {{
            let aa_width_px = select(select(0.85, 1.35, aa_level == 2u), 2.1, aa_level >= 3u);
            let aa_unit = aa_width_px / min_half;
            let inner = min(1.0 - aa_unit, h * 0.96);
            if (h >= 0.98) {{
                shape_a = 1.0 - smoothstep(max(0.0, 1.0 - aa_unit), 1.0 + aa_unit * 0.35, r);
            }} else {{
                let edge_falloff = 1.0 - smoothstep(max(0.0, inner), 1.0 + aa_unit * 0.25, r);
                // Smooth perceptual Gaussian-like bell for soft airbrushes (hardness near 0)
                let softness = 1.0 - h;
                shape_a = pow(clamp(edge_falloff, 0.0, 1.0), 1.0 + softness * 0.85);
            }}
        }}
    }}

    var alpha = clamp(shape_a * in.color_rgba.a, 0.0, 1.0);

    // Per-dab paper grain modulation (`paperTextureApplyEachPlot == true`)
    if (u.flags1.x != 0u && in.bg_grain.w > 0.001 && alpha > 0.001) {{
        let grain_h = sample_paper_grain_height(
            paper_tex,
            paper_sampler,
            in.doc_coord,
            uv,
            in.extra.w,
            u.paper_size,
            u.flags1.z,
            u.paper_scale,
            u.paper_rot_rad,
            u.paper_offset_norm,
            u.stroke_rand_offset,
            u.paper_brightness,
            u.paper_contrast,
            u.flags1.w,
        );
        alpha = apply_csp_paper_texture_mode(
            alpha,
            grain_h,
            in.bg_grain.w,
            u.flags1.y,
            u.flags2.x,
            in.extra.z,
        );
    }}

    if (aa_level == 0u || mono_1bit) {{
        alpha = step(0.5, alpha);
    }}
    if (alpha <= 0.001) {{
        discard;
    }}
    return vec4<f32>(rgb * alpha, alpha);
}}
"#
    )
}

/// Exact `blendTipsMode::Darken` merge pass: merges a newly rasterized `256×256` batch
/// tile onto the existing accumulated primary stroke tile slice (preserving premultiplied alpha).
pub const STROKE_DARKEN_MERGE_WGSL: &str = r#"
struct DarkenParams {
    dst_slot: i32,
    _pad0: i32,
    _pad1: i32,
    _pad2: i32,
};

@group(0) @binding(0) var<uniform> p: DarkenParams;
@group(0) @binding(1) var acc_pool: texture_2d_array<f32>;
@group(0) @binding(2) var batch_tex: texture_2d<f32>;
@group(0) @binding(3) var out_tex: texture_storage_2d<rgba16float, write>;

@compute @workgroup_size(16, 16, 1)
fn cs_main(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (gid.x >= 256u || gid.y >= 256u) {
        return;
    }
    let xy = vec2<i32>(i32(gid.x), i32(gid.y));
    let dst = select(vec4<f32>(0.0), textureLoad(acc_pool, xy, p.dst_slot, 0), p.dst_slot >= 0);
    let src = textureLoad(batch_tex, xy, 0);

    if (src.a <= 0.0005) {
        textureStore(out_tex, xy, dst);
        return;
    }
    if (dst.a <= 0.0005) {
        textureStore(out_tex, xy, src);
        return;
    }

    let d_rgb = clamp(dst.rgb / dst.a, vec3<f32>(0.0), vec3<f32>(1.0));
    let s_rgb = clamp(src.rgb / src.a, vec3<f32>(0.0), vec3<f32>(1.0));
    let dark_rgb = min(d_rgb, s_rgb);
    let out_a = clamp(src.a + dst.a * (1.0 - src.a), 0.0, 1.0);
    let out_rgb_premul =
        dark_rgb * (src.a * dst.a)
        + s_rgb * (src.a * (1.0 - dst.a))
        + d_rgb * (dst.a * (1.0 - src.a));
    textureStore(out_tex, xy, vec4<f32>(out_rgb_premul, out_a));
}
"#;

/// Shared WGSL helper implementing all 12 CSP Dual Brush composite modes (`DualBrushEngine.ts` parity).
pub const DUAL_BRUSH_COMBINE_WGSL: &str = r#"
fn combine_dual_alpha(a1: f32, a2: f32, mode: u32) -> f32 {
    let p = clamp(a1, 0.0, 1.0);
    let s = clamp(a2, 0.0, 1.0);
    switch (mode) {
        case 0u: {
            // multiply
            return p * s;
        }
        case 1u: {
            // darken
            return min(p, s);
        }
        case 2u: {
            // subtract (cuts secondary mask out of primary)
            return max(0.0, p - s);
        }
        case 3u: {
            // compare-density
            return min(p, max(0.0, s));
        }
        case 4u: {
            // linear-burn
            return max(0.0, p + s - 1.0);
        }
        case 5u: {
            // color-burn
            if (p <= 0.0005) { return 0.0; }
            if (s <= 0.0005) { return 0.0; }
            return clamp(1.0 - min(1.0, (1.0 - p) / max(0.005, s)), 0.0, 1.0) * step(0.001, p);
        }
        case 6u: {
            // height (physical tooth cut modulated by secondary alpha)
            return clamp(smoothstep(0.0, 0.55, p + s - 0.85) * p, 0.0, 1.0);
        }
        case 7u: {
            // overlay (masked to primary stroke silhouette so empty canvas stays clean)
            if (p <= 0.0005) { return 0.0; }
            let ov = select(1.0 - 2.0 * (1.0 - p) * (1.0 - s), 2.0 * p * s, p < 0.5);
            return clamp(ov, 0.0, 1.0);
        }
        case 8u: {
            // screen
            return clamp(p + s - p * s, 0.0, 1.0);
        }
        case 9u: {
            // lighten
            return max(p, s);
        }
        case 10u: {
            // hard-mix
            if (p <= 0.0005) { return 0.0; }
            return step(1.0, p + s);
        }
        default: {
            // 11: normal (unmasked primary over secondary union)
            return clamp(p + s * (1.0 - p), 0.0, 1.0);
        }
    }
}
"#;

/// Per-tile post-processing compute shader implementing:
/// 1. All 12 CSP Dual Brush composite modes (`primary_slot` + `secondary_slot`), AND
/// 2. Per-stroke Paper Grain (`paperTextureApplyEachPlot == false`, i.e., `TextureForPlot = 0`)
///    across all 9 `CspPaperTextureMode`s.
pub fn build_stroke_post_tile_wgsl() -> String {
    format!(
        r#"
struct StrokePostUniforms {{
    tile_origin_doc: vec2<f32>,
    paper_size: vec2<f32>,
    paper_offset_norm: vec2<f32>,
    stroke_rand_offset: vec2<f32>,
    paper_scale: f32,
    paper_rot_rad: f32,
    paper_brightness: f32,
    paper_contrast: f32,
    grain_strength: f32,
    avg_pressure: f32,
    stroke_angle_rad: f32,
    _pad0: f32,
    // slots = [primary_slot, secondary_slot, dual_enabled, dual_mode]
    slots: vec4<i32>,
    // paper_flags = [apply_stroke_paper, paper_mode, mapping_mode, invert_flag]
    paper_flags: vec4<u32>,
    // extra_flags = [emphasize_density, mono_1bit, _pad, _pad]
    extra_flags: vec4<u32>,
}};

@group(0) @binding(0) var<uniform> u: StrokePostUniforms;
@group(0) @binding(1) var primary_pool: texture_2d_array<f32>;
@group(0) @binding(2) var secondary_pool: texture_2d_array<f32>;
@group(0) @binding(3) var paper_tex: texture_2d<f32>;
@group(0) @binding(4) var paper_sampler: sampler;
@group(0) @binding(5) var out_tile: texture_storage_2d<rgba16float, write>;

{PAPER_GRAIN_WGSL}

{DUAL_BRUSH_COMBINE_WGSL}

@compute @workgroup_size(16, 16, 1)
fn cs_main(@builtin(global_invocation_id) gid: vec3<u32>) {{
    if (gid.x >= 256u || gid.y >= 256u) {{
        return;
    }}
    let xy = vec2<i32>(i32(gid.x), i32(gid.y));
    let p_px = select(vec4<f32>(0.0), textureLoad(primary_pool, xy, u.slots.x, 0), u.slots.x >= 0);
    let s_px = select(vec4<f32>(0.0), textureLoad(secondary_pool, xy, u.slots.y, 0), u.slots.y >= 0);

    var rgb = select(vec3<f32>(0.0), clamp(p_px.rgb / p_px.a, vec3<f32>(0.0), vec3<f32>(1.0)), p_px.a > 0.0005);
    var out_a = p_px.a;

    // 1. Dual Brush Combine (all 12 modes)
    if (u.slots.z != 0) {{
        let dual_mode = u32(max(0, u.slots.w));
        let new_a = combine_dual_alpha(p_px.a, s_px.a, dual_mode);
        if (p_px.a <= 0.0005 && s_px.a > 0.0005 && new_a > 0.0005) {{
            // Screen / Lighten / Normal additive modes can introduce pixels where primary had 0
            rgb = clamp(s_px.rgb / s_px.a, vec3<f32>(0.0), vec3<f32>(1.0));
        }}
        out_a = new_a;
    }}

    // 2. Per-Stroke Paper Grain (`paperTextureApplyEachPlot == false`)
    if (u.paper_flags.x != 0u && u.grain_strength > 0.001 && out_a > 0.0005) {{
        let doc_coord = u.tile_origin_doc + vec2<f32>(f32(gid.x) + 0.5, f32(gid.y) + 0.5);
        let h = sample_paper_grain_height(
            paper_tex,
            paper_sampler,
            doc_coord,
            vec2<f32>(f32(gid.x), f32(gid.y)) / 256.0,
            u.stroke_angle_rad,
            u.paper_size,
            u.paper_flags.z,
            u.paper_scale,
            u.paper_rot_rad,
            u.paper_offset_norm,
            u.stroke_rand_offset,
            u.paper_brightness,
            u.paper_contrast,
            u.paper_flags.w,
        );
        out_a = apply_csp_paper_texture_mode(
            out_a,
            h,
            u.grain_strength,
            u.paper_flags.y,
            u.extra_flags.x,
            u.avg_pressure,
        );
    }}

    if (u.extra_flags.y != 0u) {{
        out_a = step(0.5, out_a);
    }}
    out_a = clamp(out_a, 0.0, 1.0);
    if (out_a <= 0.0005) {{
        textureStore(out_tile, xy, vec4<f32>(0.0));
    }} else {{
        textureStore(out_tile, xy, vec4<f32>(rgb * out_a, out_a));
    }}
}}
"#
    )
}

/// Seamless 2-pass separable Gaussian alpha-blur + Watercolor Wet Edge compute shader.
///
/// Pass 0 (Horizontal): reads 3 horizontal neighbor tiles (`left`, `center`, `right`) from
/// `src_pool` and writes blurred horizontal alpha into `horiz_pool` / `horiz_scratch`.
/// Actually, to avoid needing an entire second 3×3 horizontal pool, we run Pass 0 into a
/// single `256×(256 + 2*R)` or `288×288` padded scratch texture (`R <= 16`, so `288×288` covers
/// the entire 256×256 tile PLUS 16px top/bottom/left/right margins from all 3×3 neighbor tiles
/// in ONE horizontal pass + ONE vertical pass per dirty tile!!).
///
/// Look how brilliant that is:
/// - Pass 1 (`cs_wet_horiz`): dispatches `18×18` workgroups (`288×288` pixels covering `[-16..272, -16..272]`)
///   sampling the 3×3 neighbor slots from `src_pool` -> writes horizontal Gaussian alpha into `padded_blur_h` (288×288 R16Float/Rgba16Float)!
/// - Pass 2 (`cs_wet_vert`): dispatches `16×16` workgroups (`256×256` pixels), performs vertical
///   Gaussian blur on `padded_blur_h`, computes inner-rim pigment concentration, and writes final
///   wet-edge darkened premult RGBA16F to `out_tile`! Zero extra pool memory, 100% seamless across tiles!
pub const WET_EDGE_TILE_WGSL: &str = r#"
struct WetEdgeUniforms {
    // 3×3 neighbor slots in src_pool:
    // n0 = [TL, T, TR, L], n1 = [C, R, BL, B], n2 = [BR, radius_px, 0, 0]
    n0: vec4<i32>,
    n1: vec4<i32>,
    n2: vec4<i32>,
    // params = [wet_edge, radius_f, alpha_power, value_power]
    params: vec4<f32>,
};

@group(0) @binding(0) var<uniform> u: WetEdgeUniforms;
@group(0) @binding(1) var src_pool: texture_2d_array<f32>;
@group(0) @binding(2) var padded_in: texture_2d<f32>;
@group(0) @binding(3) var out_tex: texture_storage_2d<rgba16float, write>;

fn neighbor_slot(ox: i32, oy: i32) -> i32 {
    let idx = (oy + 1) * 3 + (ox + 1);
    switch (idx) {
        case 0: { return u.n0.x; }
        case 1: { return u.n0.y; }
        case 2: { return u.n0.z; }
        case 3: { return u.n0.w; }
        case 4: { return u.n1.x; }
        case 5: { return u.n1.y; }
        case 6: { return u.n1.z; }
        case 7: { return u.n1.w; }
        default: { return u.n2.x; }
    }
}

fn load_src_with_neighbors(px: i32, py: i32) -> vec4<f32> {
    var ox = 0;
    var lx = px;
    if (lx < 0) {
        ox = -1;
        lx += 256;
    } else if (lx >= 256) {
        ox = 1;
        lx -= 256;
    }

    var oy = 0;
    var ly = py;
    if (ly < 0) {
        oy = -1;
        ly += 256;
    } else if (ly >= 256) {
        oy = 1;
        ly -= 256;
    }

    let slot = neighbor_slot(ox, oy);
    if (slot < 0) {
        return vec4<f32>(0.0);
    }
    return textureLoad(src_pool, vec2<i32>(clamp(lx, 0, 255), clamp(ly, 0, 255)), slot, 0);
}

// Pass 1: Horizontal separable Gaussian alpha blur over 288×288 padded window (pad = 16 px).
@compute @workgroup_size(16, 16, 1)
fn cs_wet_horiz(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (gid.x >= 288u || gid.y >= 288u) {
        return;
    }
    let px = i32(gid.x) - 16;
    let py = i32(gid.y) - 16;
    let r = clamp(u.n2.y, 1, 14);
    let sigma = max(0.8, f32(r) * 0.5);
    let inv_2s2 = 1.0 / (2.0 * sigma * sigma);

    var sum_a = 0.0;
    var sum_w = 0.0;
    for (var dx = -r; dx <= r; dx += 1) {
        let w = exp(-f32(dx * dx) * inv_2s2);
        let s = load_src_with_neighbors(px + dx, py);
        sum_a += s.a * w;
        sum_w += w;
    }
    let blur_a = sum_a / max(1e-5, sum_w);
    textureStore(out_tex, vec2<i32>(i32(gid.x), i32(gid.y)), vec4<f32>(blur_a, 0.0, 0.0, 1.0));
}

// Pass 2: Vertical separable Gaussian alpha blur + watercolor inner-rim darkening & alpha boost.
@compute @workgroup_size(16, 16, 1)
fn cs_wet_vert(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (gid.x >= 256u || gid.y >= 256u) {
        return;
    }
    let xy = vec2<i32>(i32(gid.x), i32(gid.y));
    let center_slot = u.n1.x;
    if (center_slot < 0) {
        textureStore(out_tex, xy, vec4<f32>(0.0));
        return;
    }
    let src = textureLoad(src_pool, xy, center_slot, 0);
    if (src.a <= 0.001) {
        // Strictly preserve transparent exterior (zero outer halo!)
        textureStore(out_tex, xy, vec4<f32>(0.0));
        return;
    }

    let r = clamp(u.n2.y, 1, 14);
    let sigma = max(0.8, f32(r) * 0.5);
    let inv_2s2 = 1.0 / (2.0 * sigma * sigma);
    let cx = i32(gid.x) + 16;
    let cy = i32(gid.y) + 16;

    var sum_a = 0.0;
    var sum_w = 0.0;
    for (var dy = -r; dy <= r; dy += 1) {
        let w = exp(-f32(dy * dy) * inv_2s2);
        let h_val = textureLoad(padded_in, vec2<i32>(cx, cy + dy), 0).r;
        sum_a += h_val * w;
        sum_w += w;
    }
    let blur_a = sum_a / max(1e-5, sum_w);

    // Inner-rim pigment pooling: positive where stroke edge transitions into empty paper
    let wet = clamp(u.params.x, 0.0, 1.0);
    let alpha_pow = max(0.0, u.params.z);
    let value_pow = max(0.0, u.params.w);
    let rim = clamp((src.a - blur_a) * 2.6, 0.0, 1.0);

    let orig_rgb = clamp(src.rgb / src.a, vec3<f32>(0.0), vec3<f32>(1.0));
    // Darken value slightly while gently enriching chroma along the watercolor border
    let dark_factor = clamp(1.0 - wet * value_pow * rim * 0.44, 0.25, 1.0);
    let rim_rgb = clamp(orig_rgb * dark_factor, vec3<f32>(0.0), vec3<f32>(1.0));
    let rim_a = clamp(src.a + wet * alpha_pow * rim * 0.42 * (1.0 - src.a * 0.35), 0.0, 1.0);

    textureStore(out_tex, xy, vec4<f32>(rim_rgb * rim_a, rim_a));
}
"#;

/// Sub-millisecond GPU-to-GPU stroke tile commit compute shader:
/// Composites one resolved `256×256` sparse stroke tile onto a layer's LOD 0 `Rgba16Float`
/// tile in `GpuTilePool` (straight RGBA16F), supporting:
/// - All 28 standard `BlendMode`s (`0..=27`) + `28: Add`, `29: Behind`, `30: Clear`, `31: CompareDensity`
/// - `brush_opacity`, `is_eraser` / `is_transparent_ink`, `is_bg_eraser`, `alpha_locked`
/// - Monochrome 1-bit layer quantization (`mono_1bit`)
/// - Optional selection mask tile (`selection_slot >= 0`) hook (wired in Phase 6)
/// - Simultaneously writes straight `Rgba16Float` to `out_tile_16f` AND packed `u32` RGBA8
///   to `out_rgba8_buf[tile_offset + y * 256 + x]` for fast single-submit CoW Undo sync!
pub fn build_tile_commit_compute_wgsl() -> String {
    format!(
        r#"
struct TileCommitUniforms {{
    // slots = [base_slot, stroke_slot, selection_slot (-2=none, -1=default, >=0=tile slot), out_tile_index]
    slots: vec4<i32>,
    // flags = [combine_mode, is_eraser, alpha_locked, mono_1bit]
    flags: vec4<u32>,
    // extra = [is_bg_eraser, sel_default_u8, _pad, _pad]
    extra: vec4<u32>,
    // params = [brush_opacity, bg_r, bg_g, bg_b]
    params: vec4<f32>,
}};

@group(0) @binding(0) var<uniform> u: TileCommitUniforms;
@group(0) @binding(1) var base_atlas: texture_2d_array<f32>;
@group(0) @binding(2) var stroke_atlas: texture_2d_array<f32>;
@group(0) @binding(3) var sel_mask_atlas: texture_2d_array<f32>;
@group(0) @binding(4) var out_tile_16f: texture_storage_2d<rgba16float, write>;
@group(0) @binding(5) var<storage, read_write> out_rgba8_buf: array<u32>;

{BLEND_MODES_WGSL}

fn pack_rgba8(c: vec4<f32>) -> u32 {{
    let r = u32(clamp(round(c.r * 255.0), 0.0, 255.0));
    let g = u32(clamp(round(c.g * 255.0), 0.0, 255.0));
    let b = u32(clamp(round(c.b * 255.0), 0.0, 255.0));
    let a = u32(clamp(round(c.a * 255.0), 0.0, 255.0));
    return r | (g << 8u) | (b << 16u) | (a << 24u);
}}

@compute @workgroup_size(16, 16, 1)
fn cs_commit(@builtin(global_invocation_id) gid: vec3<u32>) {{
    if (gid.x >= 256u || gid.y >= 256u) {{
        return;
    }}
    let xy = vec2<i32>(i32(gid.x), i32(gid.y));
    let dst = select(vec4<f32>(0.0), textureLoad(base_atlas, xy, u.slots.x, 0), u.slots.x >= 0);
    let s_premul = select(vec4<f32>(0.0), textureLoad(stroke_atlas, xy, u.slots.y, 0), u.slots.y >= 0);

    var sel_a = 1.0;
    if (u.slots.z >= 0) {{
        sel_a = textureLoad(sel_mask_atlas, xy, u.slots.z, 0).r;
    }} else if (u.slots.z == -1) {{
        sel_a = f32(u.extra.y) / 255.0;
    }}

    let stroke_a = clamp(s_premul.a * u.params.x * sel_a, 0.0, 1.0);
    var out_straight = dst;

    if (stroke_a > 0.0005) {{
        let src_rgb = select(
            vec3<f32>(0.0),
            clamp(s_premul.rgb / max(1e-5, s_premul.a), vec3<f32>(0.0), vec3<f32>(1.0)),
            s_premul.a > 0.0005,
        );
        let dst_rgb = clamp(dst.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
        let dst_a = clamp(dst.a, 0.0, 1.0);
        let combine_mode = u.flags.x;
        let is_eraser = u.flags.y != 0u || combine_mode == 30u;
        let alpha_locked = u.flags.z != 0u;
        let is_bg_eraser = u.extra.x != 0u;

        if (is_bg_eraser) {{
            // Background eraser paints background color onto canvas
            let bg_rgb = u.params.yzw;
            if (alpha_locked) {{
                if (dst_a > 0.0005) {{
                    out_straight = vec4<f32>(mix(dst_rgb, bg_rgb, stroke_a), dst_a);
                }}
            }} else {{
                let out_a = clamp(stroke_a + dst_a * (1.0 - stroke_a), 0.0, 1.0);
                let out_rgb = (bg_rgb * stroke_a + dst_rgb * dst_a * (1.0 - stroke_a)) / max(1e-5, out_a);
                out_straight = vec4<f32>(clamp(out_rgb, vec3<f32>(0.0), vec3<f32>(1.0)), out_a);
            }}
        }} else if (is_eraser) {{
            if (!alpha_locked) {{
                let new_a = clamp(dst_a * (1.0 - stroke_a), 0.0, 1.0);
                out_straight = select(vec4<f32>(0.0), vec4<f32>(dst_rgb, new_a), new_a > 0.0005);
            }}
        }} else if (combine_mode == 29u) {{
            // Behind (destination-over): paint strictly into transparent areas behind existing ink
            if (!alpha_locked) {{
                let inv_da = 1.0 - dst_a;
                let out_a = clamp(dst_a + stroke_a * inv_da, 0.0, 1.0);
                if (out_a > 0.0005) {{
                    let out_rgb = (dst_rgb * dst_a + src_rgb * stroke_a * inv_da) / out_a;
                    out_straight = vec4<f32>(clamp(out_rgb, vec3<f32>(0.0), vec3<f32>(1.0)), out_a);
                }}
            }}
        }} else if (combine_mode == 31u) {{
            // Compare Density: keeps maximum alpha without compounding semi-transparent layers
            let target_a = select(max(dst_a, stroke_a), dst_a, alpha_locked);
            if (target_a > 0.0005) {{
                let blend_t = select(stroke_a / max(1e-5, target_a), stroke_a, alpha_locked);
                let out_rgb = mix(dst_rgb, src_rgb, clamp(blend_t, 0.0, 1.0));
                out_straight = vec4<f32>(clamp(out_rgb, vec3<f32>(0.0), vec3<f32>(1.0)), target_a);
            }}
        }} else if (combine_mode == 28u) {{
            // Add: additive RGB energy accumulation
            let out_a = select(clamp(stroke_a + dst_a * (1.0 - stroke_a), 0.0, 1.0), dst_a, alpha_locked);
            if (out_a > 0.0005) {{
                let add_premul = clamp(dst_rgb * dst_a + src_rgb * stroke_a, vec3<f32>(0.0), vec3<f32>(out_a));
                out_straight = vec4<f32>(clamp(add_premul / out_a, vec3<f32>(0.0), vec3<f32>(1.0)), out_a);
            }}
        }} else {{
            // Standard Porter-Duff + all 28 blend modes (`0..=27`)
            let blended_rgb = select(
                evaluate_blend_mode(dst_rgb, src_rgb, combine_mode),
                src_rgb,
                combine_mode == 0u || dst_a <= 0.0005,
            );
            if (alpha_locked) {{
                if (dst_a > 0.0005) {{
                    let out_rgb = mix(dst_rgb, blended_rgb, stroke_a);
                    out_straight = vec4<f32>(clamp(out_rgb, vec3<f32>(0.0), vec3<f32>(1.0)), dst_a);
                }}
            }} else {{
                let out_a = clamp(stroke_a + dst_a * (1.0 - stroke_a), 0.0, 1.0);
                if (out_a > 0.0005) {{
                    let premul =
                        blended_rgb * (stroke_a * dst_a)
                        + src_rgb * (stroke_a * (1.0 - dst_a))
                        + dst_rgb * (dst_a * (1.0 - stroke_a));
                    out_straight = vec4<f32>(clamp(premul / out_a, vec3<f32>(0.0), vec3<f32>(1.0)), out_a);
                }}
            }}
        }}
    }}

    // Monochrome 1-bit layer quantization
    if (u.flags.w != 0u) {{
        let bin_a = step(0.5, out_straight.a);
        out_straight = select(vec4<f32>(0.0), vec4<f32>(out_straight.rgb, 1.0), bin_a > 0.5);
    }}

    textureStore(out_tile_16f, xy, out_straight);

    let tile_idx = u32(max(0, u.slots.w));
    let flat = tile_idx * 65536u + gid.y * 256u + gid.x;
    out_rgba8_buf[flat] = pack_rgba8(out_straight);
}}
"#
    )
}