Skip to content

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

59.6 KB
Raw Blame
//! Phase 4 Comprehensive Parity Tests & 4K Textured Dual-Brush Benchmark.
//!
//! Ports key behavioral parity tests from:
//! - `src/utils/__tests__/strokeStabilizerAndTabletResilience.test.ts`
//! - `src/utils/__tests__/strokePipelineIntegration.test.ts`
//! - `src/utils/__tests__/sutGoldenParity.test.ts`
//!
//! Plus headless DX12 GPU verification for:
//! - 1-bit binary manga inking (`antiAlias == 0`), dual-tone tips, `blendTipsMode::Compare`
//! - All 9 `CspPaperTextureMode`s (per-dab & per-stroke) & all 12 `DualBrushCompositeMode`s
//! - Seamless 2-pass GPU watercolor `wetEdge` across the `x = 256` tile boundary
//! - `brushCombineMode` (`Multiply`/`Add`/`Behind`/`Clear`/`CompareDensity`), `alphaLocked`,
//!   locked/hidden layer guards, and end-to-end `EngineHandle` CoW Undo/Redo
//! - 4096×4096 300px textured dual-brush frame-time, latency, and tile-commit benchmark.

use crate::brush::{
    apply_color_dynamics, compute_csp_tilt_magnitude, evaluate_csp_sensor,
    generate_builtin_paper_texture, generate_builtin_tip, resolve_dab_angle_rad,
    resolve_tip_flip_signs, select_sub_tip_index, BrushDynamics, BrushTextureKind,
    CompiledSensorLuts, CspAngleDynamicsMode, CspBlendTipsMode, CspBrushCombineMode,
    CspDualBrushConfig, CspPaperTextureMode, CspSensorConfig, CspSpraySettings, CspSubTipOrder,
    CspTipFlipMode, DualBrushCompositeMode, GpuBrushDab, NativeBrushConfig, StrokeDabEmitter,
    Xoshiro256StarStar,
};
use crate::clock;
use crate::compositor::{CompositorDisplayConfig, FlattenOptions};
use crate::document::{CanvasColorMode, CanvasDimensions, Document};
use crate::engine::{EngineConfig, EngineHandle};
use crate::gpu::GpuRenderer;
use crate::io::png_codec::{decode_png_rgba8, encode_rgba8_to_png};
use crate::stroke::{
    apply_csp_post_correction, build_predicted_segments, calculate_stroke_width,
    centripetal_catmull_rom_to_bezier, evaluate_csp_taper_factors, ArcLengthResampler,
    CompiledCurveLut, CspTaperSettings, FlickTaperConfig, GlobalPressureCurve, InputStabilizer,
    NativeStrokePipeline, PerspectiveMode, PerspectiveRulerConfig, PerspectiveSnapSession,
    PredictionConfig, SplineGenerator, StabilizerConfig, StraightRulerConfig,
    StraightRulerSnapSession, StrokePipelineConfig, StrokePoint, TaperEngine, VanishingPoint,
};
use crate::tiles::{RectI32, TileCoord};
use crate::types::{
    CameraState, CursorConfig, EngineCommand, EngineEvent, NativeInputSample, SurfaceTarget,
    ViewportRect,
};
use std::collections::HashMap;
use std::time::{Duration, Instant};

fn make_headless_renderer(w: u32, h: u32, doc_w: u32, doc_h: u32) -> Option<GpuRenderer> {
    match GpuRenderer::new(
        SurfaceTarget::Headless {
            width: w,
            height: h,
        },
        doc_w,
        doc_h,
    ) {
        Ok(r) => Some(r),
        Err(err) => {
            eprintln!("Skipping DX12 Phase 4 GPU test (no adapter available): {err}");
            None
        }
    }
}

fn make_blank_doc(id: impl Into<String>, name: impl Into<String>, w: u32, h: u32) -> Document {
    Document::new_blank(
        id,
        name,
        CanvasDimensions {
            width: w,
            height: h,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "transparent",
        60.0,
        50,
    )
}

fn make_stroke_points_line(
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    count: usize,
    width: f32,
) -> Vec<StrokePoint> {
    let mut pts = Vec::with_capacity(count);
    for i in 0..count {
        let t = if count <= 1 {
            0.0
        } else {
            i as f64 / (count - 1) as f64
        };
        pts.push(StrokePoint {
            x: x0 + (x1 - x0) * t,
            y: y0 + (y1 - y0) * t,
            pressure: 0.85,
            width,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.5,
            timestamp_ms: i as f64 * 4.0,
            is_corner: false,
        });
    }
    pts
}

fn emit_line_stroke_gpu(
    renderer: &mut GpuRenderer,
    doc: &mut Document,
    layer_id: &str,
    brush: NativeBrushConfig,
    pts: &[StrokePoint],
    seed: u64,
    alpha_locked: bool,
) -> Vec<(TileCoord, Vec<u8>, u64)> {
    let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
    let mut primary = StrokeDabEmitter::new(brush.clone(), seed, tip_count, tip_aspect);
    let mut secondary = brush.build_secondary_brush_config().map(|sec| {
        let (sc, sa) = renderer.resolve_brush_tip_metrics(&sec);
        StrokeDabEmitter::new(sec, seed ^ 0x517C_C1B7_2722_0A95, sc, sa)
    });

    let rand_off = primary.stroke_grain_offset;
    let is_mono = doc.color_mode == CanvasColorMode::Monochrome;
    renderer.begin_gpu_stroke(
        doc.dimensions.width,
        doc.dimensions.height,
        is_mono || brush.anti_alias == 0,
        brush.clone(),
        rand_off,
    );

    let mut spline = SplineGenerator::new(0.0);
    let mut p_dabs = Vec::new();
    let mut s_dabs = Vec::new();
    if let Some(&first) = pts.first() {
        spline.push_knot(first);
        primary.emit_initial_point(&first, None, 0.0, &mut p_dabs);
        if let Some(sec) = secondary.as_mut() {
            let mut sp = first;
            sp.width = sec.config().size * first.pressure.max(0.2);
            sec.emit_initial_point(&sp, None, 0.0, &mut s_dabs);
        }
    }
    for &pt in pts.iter().skip(1) {
        let segs = spline.push_knot(pt);
        for seg in &segs {
            primary.emit_segment(seg, None, 0.0, &mut p_dabs);
            if let Some(sec) = secondary.as_mut() {
                let mut sseg = *seg;
                let ratio = (sec.config().size / brush.size.max(0.5)).clamp(0.05, 8.0);
                sseg.p0.width *= ratio;
                sseg.p3.width *= ratio;
                sec.emit_segment(&sseg, None, 0.0, &mut s_dabs);
            }
        }
    }
    for seg in spline.finish() {
        primary.emit_segment(&seg, None, 0.0, &mut p_dabs);
        if let Some(sec) = secondary.as_mut() {
            let mut sseg = seg;
            let ratio = (sec.config().size / brush.size.max(0.5)).clamp(0.05, 8.0);
            sseg.p0.width *= ratio;
            sseg.p3.width *= ratio;
            sec.emit_segment(&sseg, None, 0.0, &mut s_dabs);
        }
    }

    renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);

    let doc_id = doc.id.clone();
    let committed = {
        let layer = doc.layer(layer_id).expect("layer exists");
        renderer
            .commit_gpu_stroke_to_layer(
                &doc_id,
                layer_id,
                &layer.grid,
                None,
                alpha_locked,
                is_mono,
            )
            .expect("gpu stroke commit succeeds")
    };

    let ret_tiles = committed.tiles.clone();
    let mut before_map = HashMap::new();
    {
        let layer = doc.layer_mut(layer_id).expect("layer exists");
        for (coord, _, _) in &committed.tiles {
            before_map.insert(*coord, layer.grid.tiles.get(coord).cloned());
        }
        let (_deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
            layer_id,
            committed.tiles,
            &before_map,
            128,
        );
        renderer.regenerate_layer_mipmaps(&doc_id, layer_id, &mut layer.grid, &cleared, None);
    }
    renderer.clear_live_stroke();
    ret_tiles
}

fn read_layer_pixel(doc: &Document, layer_id: &str, x: u32, y: u32) -> [u8; 4] {
    let layer = doc.layer(layer_id).expect("layer exists");
    let tx = (x / 256) as i32;
    let ty = (y / 256) as i32;
    let lx = (x % 256) as usize;
    let ly = (y % 256) as usize;
    let Some(tile) = layer.grid.tiles.get(&TileCoord::new(tx, ty)) else {
        return [0, 0, 0, 0];
    };
    let rgba = tile
        .to_rgba8(None, false)
        .unwrap_or_else(|_| vec![0u8; 256 * 256 * 4]);
    let idx = (ly * 256 + lx) * 4;
    [rgba[idx], rgba[idx + 1], rgba[idx + 2], rgba[idx + 3]]
}

// ============================================================================
// 1. Pressure Curves & Light-Pressure Anti-Collapse
// ============================================================================

#[test]
fn test_p4_curves_and_light_pressure_anti_collapse() {
    // Monotone Fritsch-Carlson PCHIP curve with CSP leading stub protection
    let stub_curve = [[0.0, 0.0], [0.02, 0.0], [0.5, 0.65], [1.0, 1.0]];
    let lut = CompiledCurveLut::compile(&stub_curve);
    let mut prev = -1.0f32;
    for i in 0..=100 {
        let x = i as f32 / 100.0;
        let y = lut.evaluate(x);
        assert!(y.is_finite() && (0.0..=1.0).contains(&y));
        assert!(
            y + 1e-4 >= prev,
            "PCHIP LUT must be monotone at x={x}: {y} < {prev}"
        );
        prev = y;
    }
    assert!(lut.evaluate(0.5) > 0.60 && lut.evaluate(0.5) < 0.70);

    // Anti-collapse floor: genuine light stylus contact (p > 0.005) retains a perceptible
    // hairline even under a steep curve, whereas p <= 0.005 tapers cleanly down to 0.1px.
    let steep = CompiledCurveLut::compile(&[[0.0, 0.0], [0.5, 0.02], [1.0, 1.0]]);
    let light_contact_w = calculate_stroke_width(0.02, 20.0, true, 0.0, 1.0, Some(&steep));
    let lift_zero_w = calculate_stroke_width(0.001, 20.0, true, 0.0, 1.0, Some(&steep));
    assert!(
        light_contact_w >= 0.25,
        "Genuine light contact (p=0.02) must not collapse to 0.1px, got {light_contact_w}"
    );
    assert!(
        lift_zero_w <= 0.20,
        "Near-zero exit pressure (p=0.001) should taper smoothly toward 0.1px, got {lift_zero_w}"
    );

    // Global pressure curve disabled acts as identity
    let global = GlobalPressureCurve {
        enabled: false,
        points: vec![[0.0, 0.0], [0.5, 0.9], [1.0, 1.0]],
        gamma: 1.0,
    };
    assert!((global.evaluate_raw(0.5, None) - 0.5).abs() < 1e-5);
}

// ============================================================================
// 2. Stabilizer Lag Bounds, Isotropy, Twitch Damping, & Full-Tail Catch-Up
// ============================================================================

#[test]
fn test_p4_stabilizer_lag_bounds_isotropy_twitch_and_catchup() {
    // 1. CSP base rope lengths across levels 0..50
    assert_eq!(InputStabilizer::csp_base_length_px(0.0), 0.0);
    assert!(InputStabilizer::csp_base_length_px(18.0) > 10.0);
    assert!((InputStabilizer::csp_base_length_px(50.0) - 48.0).abs() < 0.01);

    // 2. Smooth sine-wave lag stays comfortably bounded at level 18 (zero corner teleports)
    let mut stab = InputStabilizer::new(StabilizerConfig {
        stabilization: 18.0,
        sharp_corners: true,
        zoom: 1.0,
        pressure_smoothing: 0.35,
    });
    let mut max_lag = 0.0f64;
    let mut corners = 0usize;
    for i in 0..80 {
        let t = i as f64 * 4.0;
        let x = 100.0 + i as f64 * 4.0;
        let y = 200.0 + (i as f64 * 0.15).sin() * 30.0;
        let out = stab.process(x, y, 0.7, 0.0, 0.0, 0.0, t);
        if i > 10 {
            let lag = (out.x - x).hypot(out.y - y);
            max_lag = max_lag.max(lag);
        }
        if out.is_corner {
            corners += 1;
        }
    }
    assert!(
        max_lag < 28.0,
        "Smooth sine wave lag at stab=18 should stay tight, got {max_lag}"
    );
    assert_eq!(
        corners, 0,
        "Smooth sine wave must not trigger false sharp corners"
    );

    // 3. Full-tail catch-up converges all the way to the exact pen-lift raw coordinate
    let raw_end = stab.last_raw();
    let catchup = stab.flush_catch_up(340.0);
    assert!(
        !catchup.is_empty(),
        "Lagged stabilizer should emit catch-up samples"
    );
    let final_pt = catchup.last().unwrap();
    assert!((final_pt.x - raw_end.0).abs() < 1e-4);
    assert!((final_pt.y - raw_end.1).abs() < 1e-4);

    // 4. Zero diagonal anisotropy (moving along x == y yields symmetric filtered x == y)
    let mut diag = InputStabilizer::new(StabilizerConfig {
        stabilization: 25.0,
        sharp_corners: false,
        zoom: 1.0,
        pressure_smoothing: 0.3,
    });
    for i in 0..40 {
        let v = 50.0 + i as f64 * 6.0;
        let s = diag.process(v, v, 0.8, 0.0, 0.0, 0.0, i as f64 * 4.0);
        assert!(
            (s.x - s.y).abs() < 1e-6,
            "Diagonal stroke must exhibit zero X/Y anisotropy: ({}, {})",
            s.x,
            s.y
        );
    }

    // 5. Lateral 1-sample twitch suppression (Frenet damping)
    let mut twitch = InputStabilizer::new(StabilizerConfig {
        stabilization: 20.0,
        sharp_corners: false,
        zoom: 1.0,
        pressure_smoothing: 0.3,
    });
    for i in 0..20 {
        twitch.process(i as f64 * 5.0, 100.0, 0.7, 0.0, 0.0, 0.0, i as f64 * 4.0);
    }
    let spike = twitch.process(105.0, 114.0, 0.7, 0.0, 0.0, 0.0, 80.0);
    assert!(
        (spike.y - 100.0).abs() < 7.0,
        "Single-sample 14px lateral twitch must be damped strongly, got dy={}",
        (spike.y - 100.0).abs()
    );
}

// ============================================================================
// 3. Sharp Corners, CSP Post-Correction, & Ephemeral Prediction
// ============================================================================

#[test]
fn test_p4_sharp_corners_post_correction_and_ephemeral_prediction() {
    // 1. Sharp 90-degree corner detection with bounded convergence plan (no teleport)
    let mut stab = InputStabilizer::new(StabilizerConfig {
        stabilization: 18.0,
        sharp_corners: true,
        zoom: 1.0,
        pressure_smoothing: 0.35,
    });
    let mut t = 0.0;
    for i in 0..12 {
        stab.process(100.0 + i as f64 * 8.0, 100.0, 0.7, 0.0, 0.0, 0.0, t);
        t += 4.0;
    }
    let apex_x = 100.0 + 11.0 * 8.0;
    // Sudden 90-degree turn straight down
    let turn = stab.process(apex_x, 125.0, 0.7, 0.0, 0.0, 0.0, t + 4.0);
    assert!(turn.is_corner, "90-degree turn must trigger sharp corner");
    assert!(
        turn.corner_convergence.is_some(),
        "Lagged sharp corner should produce a smooth CornerConvergencePlan"
    );

    // 2. CSP Post-Correction smooths wavy points while pinning endpoints and sharp corners
    let mut noisy = Vec::new();
    for i in 0..15 {
        let is_corner = i == 7;
        let x = if i <= 7 { i as f64 * 10.0 } else { 70.0 };
        let y = if i <= 7 {
            if is_corner || i == 0 {
                0.0
            } else if i % 2 == 0 {
                3.0
            } else {
                -3.0
            }
        } else {
            (i - 7) as f64 * 10.0
        };
        noisy.push(StrokePoint {
            x,
            y,
            pressure: 0.7,
            width: 10.0,
            is_corner,
            ..Default::default()
        });
    }
    let corrected = apply_csp_post_correction(&noisy, 4);
    assert_eq!(corrected.len(), noisy.len());
    // Endpoints & sharp corner vertex strictly pinned
    assert!((corrected[0].x - noisy[0].x).abs() < 1e-9);
    assert!((corrected[7].x - 70.0).abs() < 1e-9 && (corrected[7].y - 0.0).abs() < 1e-9);
    assert!((corrected[14].y - noisy[14].y).abs() < 1e-9);
    // Interior oscillation reduced
    assert!(corrected[3].y.abs() < noisy[3].y.abs());

    // 3. Strictly ephemeral stroke head prediction never mutates spline knots or stabilizer
    let mut pipe = NativeStrokePipeline::new();
    let cfg = StrokePipelineConfig {
        base_size: 16.0,
        stabilization: 22.0,
        zoom: 1.0,
        ..Default::default()
    };
    pipe.begin(10.0, 10.0, 0.7, 0.0, 0.0, 0.0, 0.0, false, None, cfg);
    for i in 1..15 {
        pipe.push_move(
            10.0 + i as f64 * 12.0,
            10.0,
            0.7,
            0.0,
            0.0,
            0.0,
            i as f64 * 4.0,
            false,
        );
    }
    let knots_before = pipe.spline().knots().len();
    let raw_before = pipe.stabilizer().last_raw();
    let predicted = build_predicted_segments(
        pipe.spline(),
        pipe.stabilizer(),
        1.0,
        PredictionConfig::default(),
    );
    assert!(
        !predicted.is_empty(),
        "Fast stabilized stroke should yield transient predicted head segments"
    );
    assert_eq!(pipe.spline().knots().len(), knots_before);
    assert_eq!(pipe.stabilizer().last_raw(), raw_before);
}

// ============================================================================
// 4. Spline, Arc-Length Carry-Over, Taper Engine, & Ballistic Flick Gates
// ============================================================================

#[test]
fn test_p4_spline_arc_length_taper_and_ballistic_flick() {
    // 1. Centripetal Catmull-Rom handle clamping + exact arc-length carry-over
    let pts = make_stroke_points_line(0.0, 0.0, 120.0, 0.0, 5, 10.0);
    let seg1 = centripetal_catmull_rom_to_bezier(pts[0], pts[0], pts[1], pts[2], 0.0);
    let seg2 = centripetal_catmull_rom_to_bezier(pts[0], pts[1], pts[2], pts[3], 0.0);
    let d01 = (seg1.p3.x - seg1.p0.x).hypot(seg1.p3.y - seg1.p0.y);
    let h1 = (seg1.cp1x - seg1.p0.x).hypot(seg1.cp1y - seg1.p0.y);
    assert!(
        h1 <= d01 * 0.49,
        "Catmull-Rom handle must be clamped <= 0.48*d12"
    );

    let mut resampler = ArcLengthResampler::new();
    let mut s1 = resampler.resample_segment(&seg1, |_, _| 7.0);
    let s2 = resampler.resample_segment(&seg2, |_, _| 7.0);
    s1.extend(s2);
    assert!(s1.len() >= 7);
    for w in s1.windows(2) {
        let gap = (w[1].point.x - w[0].point.x).hypot(w[1].point.y - w[0].point.y);
        assert!(
            (gap - 7.0).abs() < 0.75,
            "Exact arc-length carry-over should keep uniform ~7px spacing across segment seam, got {gap}"
        );
    }

    // 2. G-Pen 3-stage Hermite S-curve monotonicity
    let mut prev = -1.0f32;
    for i in 0..=20 {
        let p = i as f32 / 20.0;
        let m = TaperEngine::map_pressure(p);
        assert!(m >= prev);
        prev = m;
    }
    assert_eq!(TaperEngine::map_pressure(0.0), 0.0);
    assert_eq!(TaperEngine::map_pressure(1.0), 1.0);

    // 3. Ballistic flick taper parity gates (zoomed-out 0.1x, brisk flick, >32ms dwell)
    let zoomed_out_pts = vec![
        StrokePoint {
            x: 1000.0,
            y: 1000.0,
            pressure: 0.6,
            width: 8.0,
            timestamp_ms: 0.0,
            ..Default::default()
        },
        StrokePoint {
            x: 1032.0,
            y: 1000.0,
            pressure: 0.55,
            width: 7.5,
            timestamp_ms: 8.0,
            ..Default::default()
        },
        StrokePoint {
            x: 1064.0,
            y: 1000.0,
            pressure: 0.5,
            width: 7.0,
            timestamp_ms: 16.0,
            ..Default::default()
        },
    ];
    // 4 doc px/ms * 0.1 zoom = 0.4 screen px/ms < 0.55 threshold -> suppressed!
    assert!(
        TaperEngine::compute_flick_taper(
            &zoomed_out_pts,
            20.0,
            0.1,
            12.0,
            FlickTaperConfig::default()
        )
        .is_empty(),
        "Slow screen-space flick at 0.1x zoom must be suppressed"
    );
    // Dwell > 32ms at 1.0x zoom -> suppressed!
    assert!(
        TaperEngine::compute_flick_taper(
            &zoomed_out_pts,
            80.0,
            1.0,
            12.0,
            FlickTaperConfig::default()
        )
        .is_empty(),
        "Dwell > 32ms before pen lift must suppress ballistic flick"
    );
    // True fast flick at 1.0x zoom -> emits monotonically decaying razor tail
    let flick = TaperEngine::compute_flick_taper(
        &zoomed_out_pts,
        20.0,
        1.0,
        12.0,
        FlickTaperConfig::default(),
    );
    assert!(
        flick.len() >= 4,
        "Fast flick at 1.0x zoom should emit tail points"
    );
    assert!(flick.last().unwrap().width < zoomed_out_pts.last().unwrap().width * 0.4);

    // 4. CspTaperSettings per-channel targets & modes
    let taper_cfg = CspTaperSettings {
        use_in: true,
        in_length: 40.0,
        use_out: true,
        out_length: 50.0,
        in_out_type: 3, // Fade
        starting_sharpness: 0.85,
        ending_sharpness: 0.85,
        affect_size: true,
        min_size_ratio: 0.1,
        affect_opacity: true,
        affect_density: true,
        min_density_ratio: 0.2,
        ..Default::default()
    };
    let start_f = evaluate_csp_taper_factors(&taper_cfg, 2.0, Some(200.0), 1.0);
    let mid_f = evaluate_csp_taper_factors(&taper_cfg, 100.0, Some(200.0), 1.0);
    let end_f = evaluate_csp_taper_factors(&taper_cfg, 198.0, Some(200.0), 1.0);
    assert!(start_f.size < 0.25 && mid_f.size > 0.99 && end_f.size < 0.25);
    assert!(start_f.opacity < 0.35 && mid_f.opacity > 0.99 && end_f.opacity < 0.35);
}

// ============================================================================
// 5. Straight & Perspective Ruler Snapping
// ============================================================================

#[test]
fn test_p4_straight_and_perspective_ruler_snapping() {
    // Straight ruler at y = 100, angle = 0 deg
    let sr = StraightRulerConfig {
        enabled: true,
        visible: true,
        snap_enabled: true,
        x: 200.0,
        y: 100.0,
        angle: 0.0,
        length: 600.0,
        locked: false,
    };
    // Within 26/zoom (=26px) of y=100 -> snaps directly onto y=100
    let s_edge = StraightRulerSnapSession::begin(&sr, 150.0, 112.0, 1.0, false);
    assert!(s_edge.snapped_to_edge);
    let (sx, sy) = s_edge.snap(300.0, 145.0, false);
    assert!((sx - 300.0).abs() < 1e-6 && (sy - 100.0).abs() < 1e-6);

    // Outside 26px -> parallel guideline through start y=250
    let s_par = StraightRulerSnapSession::begin(&sr, 150.0, 250.0, 1.0, false);
    assert!(!s_par.snapped_to_edge);
    let (px, py) = s_par.snap(320.0, 290.0, false);
    assert!((px - 320.0).abs() < 1e-6 && (py - 250.0).abs() < 1e-6);

    // Alt override bypasses snap completely
    let (ax, ay) = s_edge.snap(300.0, 145.0, true);
    assert!((ax - 300.0).abs() < 1e-6 && (ay - 145.0).abs() < 1e-6);

    // 2-Point Perspective Ruler: VP0 at (0, 200), VP1 at (800, 200)
    let pr = PerspectiveRulerConfig {
        enabled: true,
        visible: true,
        snap_enabled: true,
        mode: PerspectiveMode::TwoPoint,
        horizon_angle: 0.0,
        vanishing_points: vec![
            VanishingPoint {
                id: "vp1".into(),
                x: 0.0,
                y: 200.0,
                enabled: true,
            },
            VanishingPoint {
                id: "vp2".into(),
                x: 800.0,
                y: 200.0,
                enabled: true,
            },
        ],
    };
    let mut ps = PerspectiveSnapSession::begin(&pr, 400.0, 400.0, false);
    // Below 4 doc px lock threshold -> holds at start
    let (hx, hy) = ps.snap(401.0, 401.5, false);
    assert!((hx - 400.0).abs() < 1e-6 && (hy - 400.0).abs() < 1e-6);
    assert!(ps.locked_axis().is_none());

    // Move strongly downward (>4px) -> locks vertical axis (dir = (0, 1))
    let (vx, vy) = ps.snap(403.0, 440.0, false);
    assert!(ps.locked_axis().is_some());
    assert!((vx - 400.0).abs() < 1e-5 && (vy - 440.0).abs() < 1e-5);
}

// ============================================================================
// 6. CSP Sensors, Dynamics, Spray, & PRNG Determinism
// ============================================================================

#[test]
fn test_p4_csp_sensors_dynamics_spray_and_prng_determinism() {
    // 1. Deterministic Xoshiro256** seeded by stroke ID
    let mut r1 = Xoshiro256StarStar::seed_from_u64(0xCAFE_BABE_1234_5678);
    let mut r2 = Xoshiro256StarStar::seed_from_u64(0xCAFE_BABE_1234_5678);
    for _ in 0..64 {
        assert_eq!(r1.next_u64(), r2.next_u64());
    }

    // 2. Spherical tilt magnitude & multi-channel evaluate_csp_sensor
    assert!(compute_csp_tilt_magnitude(0.0, 0.0) < 1e-5);
    assert!(compute_csp_tilt_magnitude(60.0, 0.0) > 0.85);
    let sensor = CspSensorConfig {
        use_pressure: true,
        pressure_min: 0.2,
        use_velocity: true,
        velocity_min: 0.3,
        velocity_invert: true,
        use_distance: true,
        distance_min: 0.1,
        distance_max_px: 200.0,
        ..Default::default()
    };
    let luts = CompiledSensorLuts::from_sensor(Some(&sensor));
    let v_low = evaluate_csp_sensor(&sensor, Some(&luts), 0.2, 0.0, 2.0, 0.0, 0.5);
    let v_high = evaluate_csp_sensor(&sensor, Some(&luts), 1.0, 0.0, 0.0, 200.0, 0.5);
    assert!(v_high > v_low * 3.0);

    // 3. All 7 angle dynamics modes & all 6 sub-tip orders & flip modes
    let all_angles = [
        CspAngleDynamicsMode::None,
        CspAngleDynamicsMode::InitialDirection,
        CspAngleDynamicsMode::Direction,
        CspAngleDynamicsMode::Tilt,
        CspAngleDynamicsMode::Twist,
        CspAngleDynamicsMode::Random,
        CspAngleDynamicsMode::DirectionRandom,
    ];
    for mode in all_angles {
        let a = resolve_dab_angle_rad(15.0, mode, 0.6, 0.2, 30.0, 10.0, 45.0, 0.5, 0.4, 0.3);
        assert!(a.is_finite());
    }
    let all_orders = [
        CspSubTipOrder::Sequential,
        CspSubTipOrder::Reverse,
        CspSubTipOrder::Random,
        CspSubTipOrder::RandomNoRepeat,
        CspSubTipOrder::Once,
        CspSubTipOrder::Direction,
    ];
    let mut rng = Xoshiro256StarStar::seed_from_u64(42);
    for order in all_orders {
        let idx = select_sub_tip_index(5, order, 3, 2, 1.2, rng.next_f32());
        assert!(idx < 5);
    }
    let (fx0, fy0) = resolve_tip_flip_signs(
        CspTipFlipMode::Alternate,
        CspTipFlipMode::None,
        0,
        rng.next_f32(),
        rng.next_f32(),
    );
    let (fx1, _) = resolve_tip_flip_signs(
        CspTipFlipMode::Alternate,
        CspTipFlipMode::None,
        1,
        rng.next_f32(),
        rng.next_f32(),
    );
    assert_eq!(fx0, 1.0);
    assert_eq!(fx1, -1.0);
    assert_eq!(fy0, 1.0);

    // 4. Per-dab color jitter & spray scatter produce multiple varied dabs
    let shifted = apply_color_dynamics(
        [0.9, 0.2, 0.2],
        [0.1, 0.2, 0.9],
        &BrushDynamics {
            color_jitter_enabled: true,
            color_jitter_per_dab: true,
            hue_jitter: 0.4,
            fg_bg_jitter: 0.5,
            temperature_jitter: 0.3,
            ..Default::default()
        },
        0.7,
        0.5,
        0.0,
        0.0,
        0.4,
    );
    assert!((shifted[0] - 0.9).abs() + (shifted[2] - 0.2).abs() > 0.1);

    let spray_cfg = NativeBrushConfig {
        size: 40.0,
        spacing: 0.25,
        spray: Some(CspSpraySettings {
            enabled: true,
            particle_size: 8.0,
            density: 5.0,
            ..Default::default()
        }),
        ..Default::default()
    };
    let mut emitter = StrokeDabEmitter::new(spray_cfg, 999, 1, 1.0);
    let mut dabs = Vec::new();
    let pts = make_stroke_points_line(20.0, 20.0, 120.0, 20.0, 4, 40.0);
    let seg = centripetal_catmull_rom_to_bezier(pts[0], pts[1], pts[2], pts[3], 0.0);
    emitter.emit_segment(&seg, None, 0.0, &mut dabs);
    assert!(
        dabs.len() >= 10,
        "Spray emitter should scatter multiple particles per step, got {}",
        dabs.len()
    );
}

// ============================================================================
// 7. Procedural Tips, All 7 Seamless 512x512 Surface Heightfields, & PNG Codec
// ============================================================================

#[test]
fn test_p4_procedural_tips_seamless_surfaces_and_png_roundtrip() {
    // 1. Pure-Rust PNG encode -> decode roundtrip
    let mut src = vec![0u8; 16 * 16 * 4];
    for i in 0..(16 * 16) {
        src[i * 4] = (i % 256) as u8;
        src[i * 4 + 1] = ((i * 7) % 256) as u8;
        src[i * 4 + 2] = 180;
        src[i * 4 + 3] = 255;
    }
    let png = encode_rgba8_to_png(16, 16, &src).expect("encode_rgba8_to_png");
    let (dw, dh, decoded) = decode_png_rgba8(&png).expect("decode_png_rgba8");
    assert_eq!((dw, dh), (16, 16));
    assert_eq!(decoded, src);

    // 2. All 7 seamless 512x512 surface heightfields have rich dynamic range & periodic wrap
    let surfaces = [
        "linen-canvas",
        "coarse-burlap",
        "fine-cotton",
        "cold-press-watercolor",
        "rough-pastel",
        "gesso-board",
        "stipple-grain",
    ];
    for id in surfaces {
        let (w, h, rgba) = generate_builtin_paper_texture(id)
            .unwrap_or_else(|| panic!("Missing built-in surface texture {id}"));
        assert_eq!((w, h), (512, 512));
        let mut min_v = 255u8;
        let mut max_v = 0u8;
        for px in rgba.chunks_exact(4) {
            min_v = min_v.min(px[0]);
            max_v = max_v.max(px[0]);
        }
        assert!(
            max_v - min_v >= 40,
            "Surface {id} should have rich tonal contrast, got [{min_v}, {max_v}]"
        );
    }

    // 3. Built-in procedural brush tips
    for tip_id in [
        "pro:sumi-fude-brush-256",
        "pro:soft-tapered-liner",
        "pro:watercolor-wash",
        "pro:luminous-bloom",
    ] {
        let (tw, th, rgba) = generate_builtin_tip(tip_id)
            .unwrap_or_else(|| panic!("Missing built-in procedural tip {tip_id}"));
        assert_eq!((tw, th), (256, 256));
        let non_zero = rgba.chunks_exact(4).filter(|p| p[3] > 20).count();
        assert!(
            non_zero > 500,
            "Built-in tip {tip_id} must contain visible alpha"
        );
    }
}

// ============================================================================
// 8. GPU Parity: 1-Bit Binary Manga Inking, Dual-Tone Tips, & Compare Blend
// ============================================================================

#[test]
fn test_p4_gpu_binary_manga_inking_and_dualtone_compare_tips() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
        return;
    };

    // 1. Crisp 1-bit binary manga inking (`anti_alias == 0`) -> ONLY alpha 0 or 255!
    let mut doc = make_blank_doc("doc-bin", "Binary", 256, 256);
    let lid = doc.active_layer_id.clone().unwrap();
    let bin_brush = NativeBrushConfig {
        fg_color: [0.0, 0.0, 0.0],
        size: 18.0,
        hardness: 1.0,
        anti_alias: 0,
        spacing: 0.12,
        ..Default::default()
    };
    let pts = make_stroke_points_line(40.0, 128.0, 210.0, 128.0, 12, 18.0);
    let committed = emit_line_stroke_gpu(&mut renderer, &mut doc, &lid, bin_brush, &pts, 11, false);
    assert!(!committed.is_empty());
    let mut opaque_count = 0usize;
    let mut intermediate_count = 0usize;
    for (_, rgba, _) in &committed {
        for px in rgba.chunks_exact(4) {
            if px[3] == 255 {
                opaque_count += 1;
            } else if px[3] != 0 {
                intermediate_count += 1;
            }
        }
    }
    assert!(opaque_count > 1000, "Binary manga ink should draw solid pixels");
    assert_eq!(
        intermediate_count, 0,
        "antiAlias==0 must emit strict 1-bit binary alpha (0 or 255), found {intermediate_count} gray pixels"
    );

    // 2. Dual-tone custom tip (left=black->FG red, right=white->BG blue) uploaded via PNG
    let mut dt_tip = vec![0u8; 32 * 32 * 4];
    for y in 0..32usize {
        for x in 0..32usize {
            let idx = (y * 32 + x) * 4;
            let lum = if x < 16 { 0u8 } else { 255u8 };
            dt_tip[idx] = lum;
            dt_tip[idx + 1] = lum;
            dt_tip[idx + 2] = lum;
            dt_tip[idx + 3] = 255;
        }
    }
    let dt_png = encode_rgba8_to_png(32, 32, &dt_tip).unwrap();
    renderer
        .upload_brush_texture(
            "test-dualtone-tip".into(),
            BrushTextureKind::Tip,
            true,
            32,
            32,
            dt_png,
        )
        .expect("upload dualtone tip PNG");

    let mut doc_dt = make_blank_doc("doc-dt", "DualTone", 256, 256);
    let lid_dt = doc_dt.active_layer_id.clone().unwrap();
    let dt_brush = NativeBrushConfig {
        fg_color: [1.0, 0.0, 0.0],
        bg_color: [0.0, 0.0, 1.0],
        size: 64.0,
        spacing: 1.5,
        tip_key: Some("test-dualtone-tip".into()),
        is_dual_tone_tip: true,
        ..Default::default()
    };
    let dot = make_stroke_points_line(128.0, 128.0, 128.0, 128.0, 1, 64.0);
    emit_line_stroke_gpu(&mut renderer, &mut doc_dt, &lid_dt, dt_brush, &dot, 22, false);
    let left_px = read_layer_pixel(&doc_dt, &lid_dt, 112, 128);
    let right_px = read_layer_pixel(&doc_dt, &lid_dt, 144, 128);
    assert!(
        left_px[0] > 200 && left_px[2] < 40,
        "Left half of dual-tone tip must map to FG red, got {left_px:?}"
    );
    assert!(
        right_px[2] > 200 && right_px[0] < 40,
        "Right half of dual-tone tip must map to BG blue, got {right_px:?}"
    );

    // 3. `blend_tips_mode::Compare` keeps overlapping dabs bounded (unlike `Normal` which compounds)
    let mut doc_cmp = make_blank_doc("doc-cmp", "Compare", 256, 256);
    let mut doc_norm = make_blank_doc("doc-norm", "Normal", 256, 256);
    let lid_cmp = doc_cmp.active_layer_id.clone().unwrap();
    let lid_norm = doc_norm.active_layer_id.clone().unwrap();
    let dense_pts = make_stroke_points_line(40.0, 128.0, 200.0, 128.0, 20, 32.0);
    let base_semi = NativeBrushConfig {
        fg_color: [0.1, 0.2, 0.8],
        size: 32.0,
        hardness: 0.9,
        flow: 0.4,
        brush_density: 0.4,
        spacing: 0.08,
        blend_tips_mode: CspBlendTipsMode::Compare,
        ..Default::default()
    };
    let mut norm_semi = base_semi.clone();
    norm_semi.blend_tips_mode = CspBlendTipsMode::Normal;

    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc_cmp,
        &lid_cmp,
        base_semi,
        &dense_pts,
        33,
        false,
    );
    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc_norm,
        &lid_norm,
        norm_semi,
        &dense_pts,
        33,
        false,
    );
    let cmp_px = read_layer_pixel(&doc_cmp, &lid_cmp, 120, 128);
    let norm_px = read_layer_pixel(&doc_norm, &lid_norm, 120, 128);
    assert!(
        cmp_px[3] < 130 && norm_px[3] > 220,
        "Compare blend must stay bounded (~0.4*255) while Normal compounds to ~255: cmp={} norm={}",
        cmp_px[3],
        norm_px[3]
    );
}

// ============================================================================
// 9. GPU Parity: All 9 Paper Texture Modes & All 12 Dual Brush Composite Modes
// ============================================================================

#[test]
fn test_p4_gpu_all_9_paper_modes_and_12_dual_brush_modes() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
        return;
    };

    let pts = make_stroke_points_line(32.0, 128.0, 224.0, 128.0, 16, 48.0);

    // 1. All 9 CSP Paper Texture modes (both per-dab and per-stroke)
    let all_paper_modes = [
        CspPaperTextureMode::Subtract,
        CspPaperTextureMode::Multiply,
        CspPaperTextureMode::Compare,
        CspPaperTextureMode::Overlay,
        CspPaperTextureMode::Outline,
        CspPaperTextureMode::Normal,
        CspPaperTextureMode::ColorBurn,
        CspPaperTextureMode::LinearBurn,
        CspPaperTextureMode::Height,
    ];
    for (i, mode) in all_paper_modes.iter().enumerate() {
        for apply_each_plot in [true, false] {
            let mut doc = make_blank_doc(format!("doc-p-{i}-{apply_each_plot}"), "Paper", 256, 256);
            let lid = doc.active_layer_id.clone().unwrap();
            let brush = NativeBrushConfig {
                fg_color: [0.2, 0.2, 0.2],
                size: 48.0,
                hardness: 0.85,
                flow: 0.8,
                spacing: 0.12,
                surface_texture_id: Some("cold-press-watercolor".into()),
                grain: 0.75,
                texture_density: 0.75,
                paper_texture_mode: *mode,
                paper_texture_apply_each_plot: apply_each_plot,
                ..Default::default()
            };
            let committed = emit_line_stroke_gpu(
                &mut renderer,
                &mut doc,
                &lid,
                brush,
                &pts,
                100 + i as u64,
                false,
            );
            let mut max_a = 0u8;
            let mut inked = 0usize;
            for (_, rgba, _) in &committed {
                for y in 118..138usize {
                    for x in 60..190usize {
                        let a = rgba[(y * 256 + x) * 4 + 3];
                        if a > 0 {
                            inked += 1;
                            max_a = max_a.max(a);
                        }
                    }
                }
            }
            assert!(
                inked > 500 && max_a > 40,
                "Paper mode {:?} (each_plot={apply_each_plot}) must render visible inked pixels",
                mode
            );
        }
    }

    // 2. All 12 Dual Brush composite modes + verify Multiply carves out alpha vs unmasked baseline
    let mut base_doc = make_blank_doc("doc-dual-base", "DualBase", 256, 256);
    let base_lid = base_doc.active_layer_id.clone().unwrap();
    let base_brush = NativeBrushConfig {
        fg_color: [0.1, 0.1, 0.1],
        size: 48.0,
        hardness: 0.95,
        spacing: 0.1,
        ..Default::default()
    };
    let base_tiles = emit_line_stroke_gpu(
        &mut renderer,
        &mut base_doc,
        &base_lid,
        base_brush.clone(),
        &pts,
        200,
        false,
    );
    let base_alpha_sum: u64 = base_tiles
        .iter()
        .flat_map(|(_, b, _)| b.chunks_exact(4).map(|p| p[3] as u64))
        .sum();

    let all_dual_modes = [
        DualBrushCompositeMode::Multiply,
        DualBrushCompositeMode::Darken,
        DualBrushCompositeMode::Subtract,
        DualBrushCompositeMode::CompareDensity,
        DualBrushCompositeMode::LinearBurn,
        DualBrushCompositeMode::ColorBurn,
        DualBrushCompositeMode::Height,
        DualBrushCompositeMode::Overlay,
        DualBrushCompositeMode::Screen,
        DualBrushCompositeMode::Lighten,
        DualBrushCompositeMode::HardMix,
        DualBrushCompositeMode::Normal,
    ];
    for (i, dmode) in all_dual_modes.iter().enumerate() {
        let mut doc = make_blank_doc(format!("doc-dual-{i}"), "Dual", 256, 256);
        let lid = doc.active_layer_id.clone().unwrap();
        let mut b = base_brush.clone();
        b.dual_brush = true;
        b.dual_brush_config = Some(CspDualBrushConfig {
            enabled: true,
            combine_mode: *dmode,
            link_size: false,
            size: 20.0,
            spacing: 1.4, // wide spacing so secondary leaves gaps -> clearly modulates primary!
            hardness: 0.85,
            density: 0.85,
            ..Default::default()
        });
        let tiles = emit_line_stroke_gpu(
            &mut renderer,
            &mut doc,
            &lid,
            b,
            &pts,
            200 + i as u64,
            false,
        );
        let alpha_sum: u64 = tiles
            .iter()
            .flat_map(|(_, buf, _)| buf.chunks_exact(4).map(|p| p[3] as u64))
            .sum();
        assert!(
            alpha_sum > 0,
            "Dual mode {:?} must produce visible stroke pixels",
            dmode
        );
        if matches!(
            dmode,
            DualBrushCompositeMode::Multiply | DualBrushCompositeMode::Subtract
        ) {
            assert!(
                alpha_sum < base_alpha_sum * 9 / 10,
                "Dual mode {:?} should carve primary stroke alpha: dual={alpha_sum} vs base={base_alpha_sum}",
                dmode
            );
        }
    }
}

// ============================================================================
// 10. GPU Watercolor Wet Edge (Rim Darkening, Zero Outer Halo, Zero Tile Seam)
// ============================================================================

#[test]
fn test_p4_gpu_watercolor_wet_edge_seamless_across_tile_boundary() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(512, 256, 512, 256) else {
        return;
    };

    let mut doc = make_blank_doc("doc-wet", "WetEdge", 512, 256);
    let lid = doc.active_layer_id.clone().unwrap();

    // Horizontal stroke crossing x = 256 tile boundary cleanly!
    let wet_brush = NativeBrushConfig {
        fg_color: [0.35, 0.55, 0.85],
        size: 72.0,
        hardness: 0.92,
        flow: 0.65,
        brush_density: 0.65,
        blend_tips_mode: CspBlendTipsMode::Compare,
        spacing: 0.1,
        wet_edge: 0.9,
        wet_edge_radius: 5.0,
        wet_edge_alpha_power: 1.0,
        wet_edge_value_power: 1.0,
        ..Default::default()
    };
    let pts = make_stroke_points_line(140.0, 128.0, 380.0, 128.0, 24, 72.0);
    let tiles = emit_line_stroke_gpu(&mut renderer, &mut doc, &lid, wet_brush, &pts, 404, false);
    assert!(
        tiles.len() >= 2,
        "Stroke crossing x=256 must touch both tile (0,0) and (1,0)"
    );

    // 1. Inner rim vs center: scan vertically at x=200 from center (y=128) toward edge (y=92..106)
    let center = read_layer_pixel(&doc, &lid, 200, 128);
    let mut max_rim_alpha = 0u8;
    let mut min_rim_lum = 255.0f32;
    for y in 92..106u32 {
        let px = read_layer_pixel(&doc, &lid, 200, y);
        if px[3] > 30 {
            max_rim_alpha = max_rim_alpha.max(px[3]);
            let lum = 0.299 * px[0] as f32 + 0.587 * px[1] as f32 + 0.114 * px[2] as f32;
            min_rim_lum = min_rim_lum.min(lum);
        }
    }
    let center_lum =
        0.299 * center[0] as f32 + 0.587 * center[1] as f32 + 0.114 * center[2] as f32;
    assert!(
        max_rim_alpha > center[3] || min_rim_lum < center_lum - 8.0,
        "Wet edge must darken or concentrate inner rim: center={center:?} (lum={center_lum:.1}), max_rim_a={max_rim_alpha}, min_rim_lum={min_rim_lum:.1}"
    );

    // 2. Zero outer halo far outside stroke silhouette (y = 60, >68px away from centerline)
    let outside = read_layer_pixel(&doc, &lid, 200, 60);
    assert_eq!(
        outside[3], 0,
        "Wet edge must never bleed an outer halo outside stroke silhouette"
    );

    // 3. Zero seam across x = 255 vs x = 256 tile boundary along both center and wet rim
    for y in [100u32, 128u32, 156u32] {
        let left = read_layer_pixel(&doc, &lid, 255, y);
        let right = read_layer_pixel(&doc, &lid, 256, y);
        let max_diff = (0..4)
            .map(|c| (left[c] as i32 - right[c] as i32).abs())
            .max()
            .unwrap();
        assert!(
            max_diff <= 10,
            "2-pass wet edge must be seamless across tile seam x=255|256 at y={y}: left={left:?} right={right:?}"
        );
    }
}

// ============================================================================
// 11. Combine Modes, Alpha Lock, Locked Layer Guard, & End-to-End CoW Undo/Redo
// ============================================================================

#[test]
fn test_p4_gpu_combine_modes_alpha_lock_and_end_to_end_cow_undo_redo() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
        return;
    };

    // 1. Alpha Lock prevents painting on transparent pixels while recoloring existing opaque pixels
    let mut doc = make_blank_doc("doc-lock", "AlphaLock", 256, 256);
    let lid = doc.active_layer_id.clone().unwrap();
    // First stroke: blue stripe at y=128
    let blue = NativeBrushConfig {
        fg_color: [0.0, 0.2, 1.0],
        size: 30.0,
        hardness: 1.0,
        ..Default::default()
    };
    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc,
        &lid,
        blue,
        &make_stroke_points_line(40.0, 128.0, 210.0, 128.0, 12, 30.0),
        1,
        false,
    );
    // Second stroke with alpha_locked = true: red vertical stroke crossing y=128 from y=40 to y=210
    let red = NativeBrushConfig {
        fg_color: [1.0, 0.1, 0.0],
        size: 30.0,
        hardness: 1.0,
        ..Default::default()
    };
    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc,
        &lid,
        red,
        &make_stroke_points_line(128.0, 40.0, 128.0, 210.0, 12, 30.0),
        2,
        true,
    );
    let overlap = read_layer_pixel(&doc, &lid, 128, 128);
    let outside = read_layer_pixel(&doc, &lid, 128, 60);
    assert!(
        overlap[0] > 200 && overlap[3] > 200,
        "AlphaLock must allow recoloring opaque intersection, got {overlap:?}"
    );
    assert_eq!(
        outside[3], 0,
        "AlphaLock must NOT paint onto transparent pixels, got {outside:?}"
    );

    // 2. `CspBrushCombineMode::Behind` paints behind existing opaque pixels without overwriting them
    let green_behind = NativeBrushConfig {
        fg_color: [0.0, 1.0, 0.0],
        size: 30.0,
        hardness: 1.0,
        brush_combine_mode: CspBrushCombineMode::Behind,
        ..Default::default()
    };
    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc,
        &lid,
        green_behind,
        &make_stroke_points_line(128.0, 40.0, 128.0, 210.0, 12, 30.0),
        3,
        false,
    );
    let still_red = read_layer_pixel(&doc, &lid, 128, 128);
    let new_green = read_layer_pixel(&doc, &lid, 128, 60);
    assert!(
        still_red[0] > 200 && still_red[1] < 80,
        "Behind mode must preserve existing opaque red pixel, got {still_red:?}"
    );
    assert!(
        new_green[1] > 200 && new_green[3] > 200,
        "Behind mode must paint into empty transparent background, got {new_green:?}"
    );

    // 3. `CspBrushCombineMode::Clear` erases pixels cleanly
    let clear_brush = NativeBrushConfig {
        size: 40.0,
        hardness: 1.0,
        brush_combine_mode: CspBrushCombineMode::Clear,
        ..Default::default()
    };
    emit_line_stroke_gpu(
        &mut renderer,
        &mut doc,
        &lid,
        clear_brush,
        &make_stroke_points_line(128.0, 128.0, 128.0, 128.0, 1, 40.0),
        4,
        false,
    );
    assert_eq!(
        read_layer_pixel(&doc, &lid, 128, 128)[3],
        0,
        "Clear mode must erase center to alpha=0"
    );

    // 4. End-to-end EngineHandle stroke -> StrokeCommitted event -> CoW Undo -> CoW Redo
    let (handle, mut producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: 256,
            height: 256,
        },
        EngineConfig {
            doc_width: 256,
            doc_height: 256,
            show_checkerboard: false,
            matte_color: [0.0, 0.0, 0.0, 1.0],
            ..Default::default()
        },
    ) {
        Ok(p) => p,
        Err(_) => return,
    };

    {
        let docs_lock = handle.documents();
        docs_lock.write().create_document(
            "e2e-doc",
            "E2E Stroke Doc",
            CanvasDimensions {
                width: 256,
                height: 256,
                dpi: 300,
            },
            CanvasColorMode::Color,
            "transparent",
            60.0,
        );
    }
    handle.send_command(EngineCommand::SyncActiveDocument);
    handle.send_command(EngineCommand::SetVisible(true));
    handle.send_command(EngineCommand::SetViewport(ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 256,
        height_px: 256,
        dpr: 1.0,
    }));
    handle.send_command(EngineCommand::SetCamera(CameraState {
        pan_x: 128.0,
        pan_y: 128.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    }));
    handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
    handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
        NativeBrushConfig {
            fg_color: [0.95, 0.15, 0.25],
            size: 28.0,
            hardness: 0.95,
            spacing: 0.12,
            ..Default::default()
        },
    )));

    let now = clock::now_ms();
    producers.wintab.push_batch(&[
        NativeInputSample {
            phys_x: 64.0,
            phys_y: 128.0,
            pressure: 0.8,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now,
            buttons: 1,
            phase: 1,
            backend: 1,
        },
        NativeInputSample {
            phys_x: 128.0,
            phys_y: 128.0,
            pressure: 0.9,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now + 4.0,
            buttons: 1,
            phase: 2,
            backend: 1,
        },
        NativeInputSample {
            phys_x: 192.0,
            phys_y: 128.0,
            pressure: 0.8,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now + 8.0,
            buttons: 1,
            phase: 2,
            backend: 1,
        },
        NativeInputSample {
            phys_x: 192.0,
            phys_y: 128.0,
            pressure: 0.0,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            timestamp_ms: now + 12.0,
            buttons: 0,
            phase: 3,
            backend: 1,
        },
    ]);

    let mut committed_ev = None;
    let deadline = Instant::now() + Duration::from_secs(3);
    while Instant::now() < deadline && committed_ev.is_none() {
        for ev in handle.events().try_iter() {
            if let EngineEvent::StrokeCommitted {
                doc_id,
                layer_id,
                entry_id,
                dirty_rect,
                history,
                points,
            } = ev
            {
                committed_ev = Some((doc_id, layer_id, entry_id, dirty_rect, history, points));
                break;
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }

    let (doc_id, layer_id, _entry_id, dirty_rect, history, points) =
        committed_ev.expect("EngineHandle must emit StrokeCommitted after pen lift");
    assert!(!dirty_rect.is_empty());
    assert!(points.len() >= 2);
    assert!(history.can_undo);

    // Verify committed pixels exist on active layer
    let docs_lock = handle.documents();
    let after_commit_alpha: u64 = {
        let mgr = docs_lock.read();
        let d = mgr.get_document(&doc_id).unwrap();
        let l = d.layer(&layer_id).unwrap();
        l.grid
            .tiles
            .values()
            .map(|t| {
                t.to_rgba8(None, false)
                    .unwrap()
                    .chunks_exact(4)
                    .map(|p| p[3] as u64)
                    .sum::<u64>()
            })
            .sum()
    };
    assert!(
        after_commit_alpha > 50_000,
        "Committed stroke must leave visible pixels on layer"
    );

    // CoW Undo restores exact transparent layer
    {
        let mut mgr = docs_lock.write();
        let d = mgr.get_document_mut(&doc_id).unwrap();
        assert!(!d.undo().changed_layer_ids.is_empty());
        let l = d.layer(&layer_id).unwrap();
        assert!(
            l.grid.tiles.is_empty(),
            "CoW Undo must restore exact empty tile grid"
        );
    }

    // CoW Redo restores exact committed pixels
    {
        let mut mgr = docs_lock.write();
        let d = mgr.get_document_mut(&doc_id).unwrap();
        assert!(!d.redo().changed_layer_ids.is_empty());
        let l = d.layer(&layer_id).unwrap();
        let redo_alpha: u64 = l
            .grid
            .tiles
            .values()
            .map(|t| {
                t.to_rgba8(None, false)
                    .unwrap()
                    .chunks_exact(4)
                    .map(|p| p[3] as u64)
                    .sum::<u64>()
            })
            .sum();
        assert_eq!(
            redo_alpha, after_commit_alpha,
            "CoW Redo must restore exact pixel sum"
        );
    }

    handle.shutdown();
}

// ============================================================================
// 12. 4096×4096 300px Textured Dual-Brush Benchmark
// ============================================================================

#[test]
fn test_phase4_benchmark_4k_300px_textured_dual_brush() {
    let _dx12_guard = crate::lock_dx12_test();
    let Some(mut renderer) = make_headless_renderer(1920, 1080, 4096, 4096) else {
        return;
    };

    let mut doc = make_blank_doc("bench-4k", "4K Dual Benchmark", 4096, 4096);
    let lid = doc.active_layer_id.clone().unwrap();
    renderer.sync_document(&mut doc, None).expect("initial sync");

    let brush = NativeBrushConfig {
        fg_color: [0.18, 0.34, 0.62],
        bg_color: [0.92, 0.88, 0.78],
        size: 300.0,
        min_size_factor: 0.25,
        opacity: 0.9,
        flow: 0.75,
        brush_density: 0.8,
        hardness: 0.7,
        anti_alias: 2,
        spacing: 0.12,
        stabilization: 12.0,
        tip_key: Some("pro:watercolor-wash-256".into()),
        surface_texture_id: Some("cold-press-watercolor".into()),
        grain: 0.65,
        texture_density: 0.65,
        paper_texture_mode: CspPaperTextureMode::Subtract,
        wet_edge: 0.35,
        wet_edge_radius: 4.0,
        dual_brush: true,
        dual_brush_config: Some(CspDualBrushConfig {
            enabled: true,
            combine_mode: DualBrushCompositeMode::Multiply,
            link_size: true,
            size_ratio: 0.55,
            spacing: 0.35,
            hardness: 0.8,
            density: 0.85,
            tip_key: Some("pro:sumi-fude-brush-256".into()),
            ..Default::default()
        }),
        ..Default::default()
    };

    // Pre-warm tips & paper texture (mirrors one-time brush selection upload)
    let (p_tip_count, p_tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
    let sec_cfg = brush.build_secondary_brush_config().unwrap();
    let (s_tip_count, s_tip_aspect) = renderer.resolve_brush_tip_metrics(&sec_cfg);

    let viewport = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 1920,
        height_px: 1080,
        dpr: 1.0,
    };
    let camera = CameraState {
        pan_x: 960.0,
        pan_y: 540.0,
        zoom: 0.25,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let display = CompositorDisplayConfig::default();
    let cursor_cfg = CursorConfig::default();

    // Warm up 3-slice compositor cache with 1 frame before stroke timing
    renderer.render_document_frame_with_brush(
        &doc,
        None,
        &display,
        &viewport,
        &camera,
        &[],
        false,
        false,
        &[],
        None,
        &cursor_cfg,
        None,
        true,
    );

    // Begin stroke across 4096×4096 canvas (~1920px curved sweep over 60 frames)
    let mut pipeline = NativeStrokePipeline::new();
    let pipe_cfg = StrokePipelineConfig {
        base_size: brush.size,
        min_size_factor: brush.min_size_factor,
        stabilization: brush.stabilization,
        zoom: camera.zoom as f64,
        ..Default::default()
    };
    let mut p_emit = StrokeDabEmitter::new(brush.clone(), 0xB34C_4096, p_tip_count, p_tip_aspect);
    let mut s_emit = StrokeDabEmitter::new(sec_cfg.clone(), 0xB34C_4097, s_tip_count, s_tip_aspect);
    let rand_off = p_emit.stroke_grain_offset;
    renderer.begin_gpu_stroke(4096, 4096, false, brush.clone(), rand_off);

    let mut frame_times_ms = Vec::with_capacity(60);
    let mut total_primary_dabs = 0usize;
    let mut total_secondary_dabs = 0usize;

    let step0 = pipeline.begin(600.0, 2048.0, 0.75, 0.0, 0.0, 0.0, 0.0, false, None, pipe_cfg);
    let mut p_dabs = Vec::new();
    let mut s_dabs = Vec::new();
    if let Some(pt0) = step0.initial_point {
        p_emit.emit_initial_point(&pt0, None, 0.0, &mut p_dabs);
        let mut sp0 = pt0;
        sp0.width *= 0.55;
        s_emit.emit_initial_point(&sp0, None, 0.0, &mut s_dabs);
    }
    renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);

    for frame in 1..=60usize {
        let t_frame = Instant::now();
        let x = 600.0 + frame as f64 * 32.0;
        let y = 2048.0 + (frame as f64 * 0.14).sin() * 340.0;
        let pressure = 0.65 + 0.30 * (frame as f32 / 60.0 * std::f32::consts::PI).sin();

        let step = pipeline.push_move(x, y, pressure, 0.0, 0.0, 0.0, frame as f64 * 4.0, false);
        p_dabs.clear();
        s_dabs.clear();
        for seg in &step.sealed_segments {
            p_emit.emit_segment(seg, None, 0.0, &mut p_dabs);
            let mut sseg = *seg;
            sseg.p0.width *= 0.55;
            sseg.p3.width *= 0.55;
            s_emit.emit_segment(&sseg, None, 0.0, &mut s_dabs);
        }
        total_primary_dabs += p_dabs.len();
        total_secondary_dabs += s_dabs.len();

        let mut pred_dabs: Vec<GpuBrushDab> = Vec::new();
        let pred_segs = build_predicted_segments(
            pipeline.spline(),
            pipeline.stabilizer(),
            camera.zoom as f64,
            PredictionConfig::default(),
        );
        if !pred_segs.is_empty() {
            let mut pred_emit = p_emit.clone();
            for pseg in &pred_segs {
                pred_emit.emit_segment(pseg, None, 0.0, &mut pred_dabs);
            }
        }

        if !p_dabs.is_empty() || !s_dabs.is_empty() {
            renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
        }

        renderer.render_document_frame_with_brush(
            &doc,
            None,
            &display,
            &viewport,
            &camera,
            &[],
            false,
            true,
            &pred_dabs,
            None,
            &cursor_cfg,
            Some((960.0, 540.0)),
            false,
        );
        frame_times_ms.push(t_frame.elapsed().as_secs_f64() * 1000.0);
    }

    let sparse_tiles_allocated = renderer.brush_engine().touched_tile_count();

    // Measure pen-up GPU tile commit + mipmap regen latency
    let t_commit = Instant::now();
    let doc_id = doc.id.clone();
    let committed = {
        let layer = doc.layer(&lid).unwrap();
        renderer
            .commit_gpu_stroke_to_layer(&doc_id, &lid, &layer.grid, None, false, false)
            .expect("4K dual commit")
    };
    let gpu_commit_ms = t_commit.elapsed().as_secs_f64() * 1000.0;

    let mut before_map = HashMap::new();
    {
        let layer = doc.layer_mut(&lid).unwrap();
        for (c, _, _) in &committed.tiles {
            before_map.insert(*c, layer.grid.tiles.get(c).cloned());
        }
        let (_deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
            &lid,
            committed.tiles,
            &before_map,
            128,
        );
        renderer.regenerate_layer_mipmaps(&doc_id, &lid, &mut layer.grid, &cleared, None);
    }
    let total_commit_with_cow_and_mips_ms = t_commit.elapsed().as_secs_f64() * 1000.0;
    renderer.clear_live_stroke();

    // Verify sparse allocation is vastly smaller than a full 4096×4096 FBO (256 tiles)
    let full_4k_tiles = (4096 / 256) * (4096 / 256); // 256 tiles
    assert!(
        sparse_tiles_allocated > 0 && sparse_tiles_allocated < full_4k_tiles / 2,
        "Sparse GPU stroke pool should allocate far fewer than 256 4K tiles, got {sparse_tiles_allocated}"
    );

    // Quick sanity flatten check on dirty rect
    let (fw, fh, fbytes) = renderer
        .render_document_flattened(
            &doc,
            None,
            &FlattenOptions {
                max_dim: Some(512),
                show_checkerboard: false,
                ..Default::default()
            },
        )
        .expect("4K flatten check");
    assert_eq!((fw, fh), (512, 512));
    assert!(fbytes.chunks_exact(4).any(|p| p[3] > 20));

    frame_times_ms.sort_by(|a, b| a.total_cmp(b));
    let avg_ms = frame_times_ms.iter().sum::<f64>() / frame_times_ms.len() as f64;
    let p50_ms = frame_times_ms[frame_times_ms.len() / 2];
    let p95_ms = frame_times_ms[(frame_times_ms.len() * 95 / 100).min(frame_times_ms.len() - 1)];

    println!(
        "\n[PHASE 4 BENCHMARK — 4096x4096 Canvas | 300px Textured Dual Brush + Wet Edge + Cold-Press Grain]\n\
         - Adapter:                  {}\n\
         - Stroke Dabs Emitted:      primary={} secondary={}\n\
         - Sparse GPU Tiles Used:    {} / {} ({:.1}% of full 4K FBO)\n\
         - Input->Present Frame:     avg={:.2} ms | p50={:.2} ms | p95={:.2} ms\n\
         - Pen-Up GPU Commit:        gpu_commit={:.2} ms | total(GPU+CoW+Mips)={:.2} ms\n\
         - Committed Dirty Rect:     {:?}\n",
        renderer.adapter_name(),
        total_primary_dabs,
        total_secondary_dabs,
        sparse_tiles_allocated,
        full_4k_tiles,
        (sparse_tiles_allocated as f64 / full_4k_tiles as f64) * 100.0,
        avg_ms,
        p50_ms,
        p95_ms,
        gpu_commit_ms,
        total_commit_with_cow_and_mips_ms,
        committed.dirty_rect,
    );
    let _ = RectI32::empty();
}