A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
engine impovements in rust
Soraffacfefd8d7d
diff --git a/crates/ink-engine/src/brush/procedural_tips.rs b/crates/ink-engine/src/brush/procedural_tips.rsindex e008068..bee9cff 100644--- a/crates/ink-engine/src/brush/procedural_tips.rs+++ b/crates/ink-engine/src/brush/procedural_tips.rs@@ -150,13 +150,15 @@ fn write_gray_height_pixel(rgba: &mut [u8], off: usize, height: f32) {}// =============================================================================-// 1. SEAMLESS 512×512 SURFACE & PAPER HEIGHTFIELDS+// 1. SEAMLESS 1024×1024 HIGH-DPI (2×) SURFACE & PAPER HEIGHTFIELDS// =============================================================================/// Generates any of InkStudio's 7 built-in seamless `SurfaceTextureId` heightfields-/// or 6 procedural paper textures natively in Rust as a 512×512 RGBA8 grayscale tile.+/// or 6 procedural paper textures natively in Rust as a 1024×1024 high-DPI (2× oversampled)+/// RGBA8 grayscale tile matching `buildSurfaceHeightField` in `src/utils/proceduralBrushTips.ts`.pub fn generate_builtin_paper_texture(id: &str) -> Option<(u32, u32, Vec<u8>)> {- let size = 512usize;+ let size = 1024usize;+ let inv_size = 1.0f32 / size as f32;let mut rgba = vec![0u8; size * size * 4];match id {"default" | "cold-press-default" => {@@ -165,11 +167,13 @@ pub fn generate_builtin_paper_texture(id: &str) -> Option<(u32, u32, Vec<u8>)> {let n_med = make_periodic_grid(48, &mut rng);let n_fine = make_periodic_grid(128, &mut rng);for y in 0..size {+ let ny = y as f32 * inv_size;let row = y * size * 4;for x in 0..size {- let c = sample_periodic(&n_coarse, 16, x as f32 / 32.0, y as f32 / 32.0);- let m = sample_periodic(&n_med, 48, x as f32 / (512.0 / 48.0), y as f32 / (512.0 / 48.0));- let f = sample_periodic(&n_fine, 128, x as f32 / 4.0, y as f32 / 4.0);+ let nx = x as f32 * inv_size;+ let c = sample_periodic(&n_coarse, 16, nx * 16.0, ny * 16.0);+ let m = sample_periodic(&n_med, 48, nx * 48.0, ny * 48.0);+ let f = sample_periodic(&n_fine, 128, nx * 128.0, ny * 128.0);let h = clamp01(c * 0.45 + m * 0.35 + f * 0.20);write_gray_height_pixel(&mut rgba, row + x * 4, h);}@@ -177,156 +181,264 @@ pub fn generate_builtin_paper_texture(id: &str) -> Option<(u32, u32, Vec<u8>)> {Some((size as u32, size as u32, rgba))}"linen-canvas" | "canvas-weave" => {- let mut rng = Sfc32::new(0x11AE_CA45);- let n_slub = make_periodic_grid(32, &mut rng);- let n_micro = make_periodic_grid(128, &mut rng);- let tau = std::f32::consts::TAU;- let threads = 32.0f32;+ // 80 Belgian linen threads across 1024 high-DPI texels (12.8 texels/thread -> ~5.5px at scale=0.85)+ // Purely continuous, band-limited cylindrical yarn geometry (ZERO per-texel white noise -> silky 3D normals!)+ let mut rng = Sfc32::new(0x07A1_1F01);+ let threads = 80usize;+ let threads_f = threads as f32;+ let mut warp_slub = vec![0.0f32; threads];+ let mut weft_slub = vec![0.0f32; threads];+ let mut warp_jitter = vec![0.0f32; threads];+ let mut weft_jitter = vec![0.0f32; threads];+ let mut warp_height = vec![0.0f32; threads];+ let mut weft_height = vec![0.0f32; threads];+ for i in 0..threads {+ warp_slub[i] = 0.82 + rng.next_f32() * 0.30;+ weft_slub[i] = 0.82 + rng.next_f32() * 0.30;+ warp_jitter[i] = (rng.next_f32() - 0.5) * 0.18;+ weft_jitter[i] = (rng.next_f32() - 0.5) * 0.18;+ warp_height[i] = 0.90 + rng.next_f32() * 0.15;+ weft_height[i] = 0.88 + rng.next_f32() * 0.15;+ }+ let g_fiber = make_periodic_grid(128, &mut rng);+ let g_undul = make_periodic_grid(32, &mut rng);+ let g_drift = make_periodic_grid(16, &mut rng);+ let pi = std::f32::consts::PI;+ let half_pi = std::f32::consts::FRAC_PI_2;+for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let warp_phase = u * threads * tau;- let weft_phase = v * threads * tau;- let slub_x = sample_periodic(&n_slub, 32, u * 32.0, v * 8.0) - 0.5;- let slub_y = sample_periodic(&n_slub, 32, u * 8.0, v * 32.0) - 0.5;- let warp = 0.5 + 0.5 * (warp_phase + slub_x * 0.45).sin();- let weft = 0.5 + 0.5 * (weft_phase + slub_y * 0.45).sin();- // Over-under plain weave alternation- let checker = ((u * threads).floor() as i32 + (v * threads).floor() as i32) & 1;- let weave = if checker == 0 {- warp * 0.72 + weft * 0.28+ let nx = x as f32 * inv_size;+ let drift_x = (sample_periodic(&g_drift, 16, nx * 16.0, ny * 16.0) - 0.5) * 0.24;+ let drift_y =+ (sample_periodic(&g_drift, 16, nx * 16.0 + 7.3, ny * 16.0 + 4.9) - 0.5)+ * 0.24;++ let tx = (nx * threads_f + drift_x).rem_euclid(threads_f);+ let ty = (ny * threads_f + drift_y).rem_euclid(threads_f);+ let col_cell = (tx.floor() as usize) % threads;+ let row_cell = (ty.floor() as usize) % threads;+ let frac_x = tx - tx.floor();+ let frac_y = ty - ty.floor();++ let parity = ((row_cell + col_cell) & 1) == 0;+ let dx = (frac_x - 0.5 + warp_jitter[col_cell] * 0.15) * 2.0;+ let dy = (frac_y - 0.5 + weft_jitter[row_cell] * 0.15) * 2.0;++ let warp_cyl =+ ((dx.abs() / warp_slub[col_cell].max(0.60)).min(1.0) * half_pi).cos();+ let weft_cyl =+ ((dy.abs() / weft_slub[row_cell].max(0.60)).min(1.0) * half_pi).cos();++ let warp_twist =+ 0.93 + 0.07 * ((frac_x * 2.2 + ny * threads_f * 2.5) * pi).sin();+ let weft_twist =+ 0.93 + 0.07 * ((frac_y * 2.2 - nx * threads_f * 2.5) * pi).sin();++ let warp_arch = warp_cyl+ * (0.64 + 0.36 * (dy * half_pi).cos())+ * warp_twist+ * warp_height[col_cell];+ let weft_arch = weft_cyl+ * (0.64 + 0.36 * (dx * half_pi).cos())+ * weft_twist+ * weft_height[row_cell];++ let over = if parity { warp_arch } else { weft_arch };+ let under = if parity {+ weft_arch * 0.44} else {- weft * 0.72 + warp * 0.28+ warp_arch * 0.44};- let micro = sample_periodic(&n_micro, 128, u * 128.0, v * 128.0);- let h = clamp01(weave * 0.82 + micro * 0.18);+ let base_weave = over.max(under);++ let fiber = sample_periodic(&g_fiber, 128, nx * 128.0, ny * 128.0);+ let undul = sample_periodic(&g_undul, 32, nx * 32.0, ny * 32.0);+ let h = clamp01(base_weave * 0.82 + fiber * 0.11 + undul * 0.07).powf(0.95);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}"coarse-burlap" => {- let mut rng = Sfc32::new(0xB041_AF02);- let n_slub = make_periodic_grid(24, &mut rng);- let n_fiber = make_periodic_grid(96, &mut rng);- let tau = std::f32::consts::TAU;- let threads = 16.0f32;+ // 64 heavy twisted jute/burlap threads across 1024 high-DPI texels (16 texels/thread!)+ let mut rng = Sfc32::new(0x07A2_2B02);+ let threads = 64usize;+ let threads_f = threads as f32;+ let mut warp_thick = vec![0.0f32; threads];+ let mut weft_thick = vec![0.0f32; threads];+ for i in 0..threads {+ warp_thick[i] = 0.72 + rng.next_f32() * 0.42;+ weft_thick[i] = 0.72 + rng.next_f32() * 0.42;+ }+ let g_rough = make_periodic_grid(256, &mut rng);+ let g_drift = make_periodic_grid(32, &mut rng);+ let pi = std::f32::consts::PI;+ let half_pi = std::f32::consts::FRAC_PI_2;+for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let sx = sample_periodic(&n_slub, 24, u * 24.0, v * 6.0) - 0.5;- let sy = sample_periodic(&n_slub, 24, u * 6.0, v * 24.0) - 0.5;- let warp = (0.5 + 0.5 * (u * threads * tau + sx * 0.8).sin()).powf(0.75);- let weft = (0.5 + 0.5 * (v * threads * tau + sy * 0.8).sin()).powf(0.75);- let checker = ((u * threads).floor() as i32 + (v * threads).floor() as i32) & 1;- let weave = if checker == 0 {- warp.max(weft * 0.6)+ let nx = x as f32 * inv_size;+ let drift_x = (sample_periodic(&g_drift, 32, nx * 32.0, ny * 32.0) - 0.5) * 0.25;+ let drift_y =+ (sample_periodic(&g_drift, 32, nx * 32.0 + 13.0, ny * 32.0 + 5.0) - 0.5)+ * 0.25;+ let tx = (nx * threads_f + drift_x).rem_euclid(threads_f);+ let ty = (ny * threads_f + drift_y).rem_euclid(threads_f);+ let c_cell = (tx.floor() as usize) % threads;+ let r_cell = (ty.floor() as usize) % threads;+ let fx = (tx - tx.floor() - 0.5) * 2.0;+ let fy = (ty - ty.floor() - 0.5) * 2.0;+ let parity = ((r_cell + c_cell) & 1) == 0;+ let twist_w = 0.84 + 0.16 * ((ny * threads_f * 4.0 + fx * 2.2) * pi).sin();+ let twist_h = 0.84 + 0.16 * ((nx * threads_f * 4.0 - fy * 2.2) * pi).sin();+ let warp_c =+ ((fx.abs() / warp_thick[c_cell].max(0.55)).min(1.0) * half_pi).cos()+ * twist_w;+ let weft_c =+ ((fy.abs() / weft_thick[r_cell].max(0.55)).min(1.0) * half_pi).cos()+ * twist_h;+ let weave = if parity {+ warp_c.max(weft_c * 0.40)} else {- weft.max(warp * 0.6)+ weft_c.max(warp_c * 0.40)};- let pocket = smoothstep(0.15, 0.52, warp.max(weft));- let fiber = sample_periodic(&n_fiber, 96, u * 96.0, v * 96.0);- let h = clamp01((weave * 0.78 + fiber * 0.22) * (0.25 + 0.75 * pocket));+ let rough = sample_periodic(&g_rough, 256, nx * 256.0, ny * 256.0);+ let h = clamp01(weave * 0.82 + rough * 0.18 - 0.04).powf(1.04);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}"fine-cotton" | "fine-paper" => {- let mut rng = Sfc32::new(0xF1AE_C077);- let n_low = make_periodic_grid(24, &mut rng);- let n_med = make_periodic_grid(64, &mut rng);- let n_hi = make_periodic_grid(128, &mut rng);+ let mut rng = Sfc32::new(0x07A3_3C03);+ let threads = 160.0f32;+ let tau = std::f32::consts::TAU;+ let g_gesso = make_periodic_grid(128, &mut rng);+ let g_micro = make_periodic_grid(256, &mut rng);for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;+ let wy = (ny * tau * threads).sin();let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let lo = sample_periodic(&n_low, 24, u * 24.0, v * 24.0);- let md = sample_periodic(&n_med, 64, u * 64.0, v * 64.0);- let hi = sample_periodic(&n_hi, 128, u * 128.0, v * 128.0);- let h = clamp01(0.32 + lo * 0.22 + md * 0.26 + hi * 0.20);+ let nx = x as f32 * inv_size;+ let wx = (nx * tau * threads).sin();+ let checker = ((nx + ny) * tau * (threads * 0.5)).sin() * 0.16;+ let weave = (wx * 0.5 + 0.5) * 0.36 + (wy * 0.5 + 0.5) * 0.36 + 0.14 + checker;+ let gesso = sample_periodic(&g_gesso, 128, nx * 128.0, ny * 128.0);+ let micro = sample_periodic(&g_micro, 256, nx * 256.0, ny * 256.0);+ let h = clamp01(weave * 0.58 + gesso * 0.24 + micro * 0.14 + rng.next_f32() * 0.04);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}- "cold-press-watercolor" => {- let mut rng = Sfc32::new(0xCA1D_F4E5);- let domes = make_cellular_dome_field(size, 36, &mut rng, 1.15);- let n_med = make_periodic_grid(48, &mut rng);- let n_fine = make_periodic_grid(128, &mut rng);+ "cold-press-watercolor" | "rough-cold-press" => {+ let mut rng = Sfc32::new(0x07A4_4D04);+ let coarse_domes = make_cellular_dome_field(256, 48, &mut rng, 1.15);+ let fine_domes = make_cellular_dome_field(256, 96, &mut rng, 1.15);+ let g_fiber = make_periodic_grid(256, &mut rng);+ let g_undul = make_periodic_grid(64, &mut rng);for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;+ let sy = ny * 256.0;+ let y0 = (sy.floor() as usize) & 255;+ let y1 = (y0 + 1) & 255;+ let ty = sy - sy.floor();let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let d = domes[y * size + x];- let m = sample_periodic(&n_med, 48, u * 48.0, v * 48.0);- let f = sample_periodic(&n_fine, 128, u * 128.0, v * 128.0);- let h = clamp01(d * 0.56 + m * 0.28 + f * 0.16);+ let nx = x as f32 * inv_size;+ let sx = nx * 256.0;+ let x0 = (sx.floor() as usize) & 255;+ let x1 = (x0 + 1) & 255;+ let tx = sx - sx.floor();+ let c_top = coarse_domes[y0 * 256 + x0] * (1.0 - tx)+ + coarse_domes[y0 * 256 + x1] * tx;+ let c_bot = coarse_domes[y1 * 256 + x0] * (1.0 - tx)+ + coarse_domes[y1 * 256 + x1] * tx;+ let d1 = c_top * (1.0 - ty) + c_bot * ty;+ let f_top =+ fine_domes[y0 * 256 + x0] * (1.0 - tx) + fine_domes[y0 * 256 + x1] * tx;+ let f_bot =+ fine_domes[y1 * 256 + x0] * (1.0 - tx) + fine_domes[y1 * 256 + x1] * tx;+ let d2 = f_top * (1.0 - ty) + f_bot * ty;+ let fiber = sample_periodic(&g_fiber, 256, nx * 256.0, ny * 256.0);+ let undul = sample_periodic(&g_undul, 64, nx * 64.0, ny * 64.0);+ let raw = d1 * 0.48 + d2 * 0.26 + fiber * 0.14 + undul * 0.08 + rng.next_f32() * 0.04;+ let h = clamp01((raw - 0.12) / 0.74).powf(1.06);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}"rough-pastel" | "charcoal-paper" | "painterly-chalk-grain" => {- let mut rng = Sfc32::new(0x9A57_E104);- let domes = make_cellular_dome_field(size, 52, &mut rng, 1.35);- let n_rib = make_periodic_grid(32, &mut rng);- let n_tooth = make_periodic_grid(128, &mut rng);+ let mut rng = Sfc32::new(0x07A5_5E05);+ let domes = make_cellular_dome_field(256, 60, &mut rng, 1.35);+ let g_grit = make_periodic_grid(256, &mut rng);let tau = std::f32::consts::TAU;for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;+ let rib = (ny * tau * 96.0).sin() * 0.15;+ let sy = ny * 256.0;+ let y0 = (sy.floor() as usize) & 255;+ let y1 = (y0 + 1) & 255;+ let ty = sy - sy.floor();let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let d = domes[y * size + x];- let laid = 0.5 + 0.5 * (v * 40.0 * tau).sin();- let r = sample_periodic(&n_rib, 32, u * 32.0, v * 32.0);- let t = sample_periodic(&n_tooth, 128, u * 128.0, v * 128.0);- let h = clamp01(d * 0.44 + laid * 0.22 + r * 0.16 + t * 0.18);+ let nx = x as f32 * inv_size;+ let chain = (nx * tau * 16.0).sin() * 0.06;+ let sx = nx * 256.0;+ let x0 = (sx.floor() as usize) & 255;+ let x1 = (x0 + 1) & 255;+ let tx = sx - sx.floor();+ let top = domes[y0 * 256 + x0] * (1.0 - tx) + domes[y0 * 256 + x1] * tx;+ let bot = domes[y1 * 256 + x0] * (1.0 - tx) + domes[y1 * 256 + x1] * tx;+ let d = top * (1.0 - ty) + bot * ty;+ let grit = sample_periodic(&g_grit, 256, nx * 256.0, ny * 256.0);+ let raw = d * 0.48 + grit * 0.30 + rng.next_f32() * 0.14 + rib + chain;+ let h = clamp01((raw - 0.14) / 0.72).powf(1.15);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}"gesso-board" | "sketch-paper" => {- let mut rng = Sfc32::new(0x6E55_0B0A);- let n_brush = make_periodic_grid(24, &mut rng);- let n_fine = make_periodic_grid(96, &mut rng);+ let mut rng = Sfc32::new(0x07A6_6F06);+ let g_brush_h = make_periodic_grid(128, &mut rng);+ let g_brush_v = make_periodic_grid(128, &mut rng);+ let g_micro = make_periodic_grid(256, &mut rng);for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- // Subtle anisotropic gesso brush streaks + mineral tooth- let streak_h = sample_periodic(&n_brush, 24, u * 8.0, v * 24.0);- let streak_v = sample_periodic(&n_brush, 24, u * 24.0, v * 8.0);- let fine = sample_periodic(&n_fine, 96, u * 96.0, v * 96.0);- let h = clamp01(0.24 + streak_h * 0.28 + streak_v * 0.22 + fine * 0.26);+ let nx = x as f32 * inv_size;+ let h_streak = sample_periodic(&g_brush_h, 128, nx * 28.0, ny * 220.0);+ let v_streak = sample_periodic(&g_brush_v, 128, nx * 220.0, ny * 28.0);+ let micro = sample_periodic(&g_micro, 256, nx * 256.0, ny * 256.0);+ let raw = h_streak * 0.38 + v_streak * 0.30 + micro * 0.24 + rng.next_f32() * 0.08;+ let h = clamp01((raw - 0.12) / 0.76);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}Some((size as u32, size as u32, rgba))}"stipple-grain" | "noise-grain" => {- let mut rng = Sfc32::new(0x5719_91E7);- let n_med = make_periodic_grid(64, &mut rng);- let n_hi = make_periodic_grid(128, &mut rng);+ let mut rng = Sfc32::new(0x07A7_7007);+ let g_med = make_periodic_grid(128, &mut rng);+ let g_fine = make_periodic_grid(256, &mut rng);for y in 0..size {- let v = y as f32 / size as f32;+ let ny = y as f32 * inv_size;let row = y * size * 4;for x in 0..size {- let u = x as f32 / size as f32;- let m = sample_periodic(&n_med, 64, u * 64.0, v * 64.0);- let hi = sample_periodic(&n_hi, 128, u * 128.0, v * 128.0);- let speckle = rng.next_f32();- let h = clamp01(m * 0.28 + hi * 0.34 + speckle * 0.38);+ let nx = x as f32 * inv_size;+ let m = sample_periodic(&g_med, 128, nx * 128.0, ny * 128.0);+ let f = sample_periodic(&g_fine, 256, nx * 256.0, ny * 256.0);+ let raw = m * 0.28 + f * 0.36 + rng.next_f32() * 0.36;+ let h = clamp01((raw - 0.14) / 0.72);write_gray_height_pixel(&mut rgba, row + x * 4, h);}}diff --git a/crates/ink-engine/src/brush_feel_tests.rs b/crates/ink-engine/src/brush_feel_tests.rsnew file mode 100644index 0000000..96d068a--- /dev/null+++ b/crates/ink-engine/src/brush_feel_tests.rs@@ -0,0 +1,459 @@+//! Brush-feel reference metrics for line-art inking (G-Pen class brushes).+//!+//! These tests drive the real [`NativeStrokePipeline`] with synthetic, timestamped stylus+//! traces (240 Hz WinInk cadence) and measure the three things an inker actually feels:+//! 1. Pressure response: latency of the pressure path and exactness of the curve.+//! 2. Taper: how thin the ends of a fast stroke really get when the pen lifts mid-motion.+//! 3. Stabilizer: lag, settle time after the hand stops, and the shape of the pen-up tail.++use crate::stroke::{+ calculate_stroke_width, InputStabilizer, NativeStrokePipeline, StabilizerConfig,+ StrokePipelineConfig, StrokePoint,+};++const HZ: f64 = 240.0;+const DT: f64 = 1000.0 / HZ;++fn gpen_cfg(stabilization: f32) -> StrokePipelineConfig {+ StrokePipelineConfig {+ base_size: 12.0,+ min_size_factor: 0.0,+ use_pressure: true,+ stabilization,+ enable_flick_taper: true,+ zoom: 1.0,+ ..Default::default()+ }+}++/// Runs a trace `(x, y, pressure, t_ms)` through the pipeline and returns the finalized points.+fn run_trace(trace: &[(f64, f64, f32, f64)], cfg: StrokePipelineConfig) -> Vec<StrokePoint> {+ let mut pipe = NativeStrokePipeline::new();+ let (x0, y0, p0, t0) = trace[0];+ pipe.begin(x0, y0, p0, 0.0, 0.0, 0.0, t0, false, None, cfg);+ for &(x, y, p, t) in &trace[1..] {+ pipe.push_move(x, y, p, 0.0, 0.0, 0.0, t, false);+ }+ let lift_t = trace.last().unwrap().3 + DT;+ pipe.end(lift_t).finalized_points.unwrap()+}++/// A fast flick: 3 px/ms, pressure ramps 0 -> 0.8 over 20 ms, holds, then releases to 0+/// over the final 25 ms while the hand is still moving (classic hair/eyelash stroke).+fn fast_flick_trace() -> Vec<(f64, f64, f32, f64)> {+ let total_ms = 140.0;+ let n = (total_ms / DT) as usize;+ (0..=n)+ .map(|i| {+ let t = i as f64 * DT;+ let x = 100.0 + 3.0 * t;+ let y = 200.0;+ let p = if t < 20.0 {+ 0.8 * (t / 20.0)+ } else if t > total_ms - 25.0 {+ 0.8 * ((total_ms - t) / 25.0).max(0.0)+ } else {+ 0.8+ } as f32;+ (x, y, p, t)+ })+ .collect()+}++#[test]+fn brush_feel_pressure_path_has_low_latency() {+ // Step response of the pressure path: 0.2 -> 0.8 while moving slowly.+ let mut stab = InputStabilizer::new(StabilizerConfig {+ stabilization: 0.0,+ ..Default::default()+ });+ let mut t = 0.0;+ for i in 0..24 {+ stab.process(i as f64, 0.0, 0.2, 0.0, 0.0, 0.0, t);+ t += DT;+ }+ let mut rise_ms = None;+ for i in 0..120 {+ let s = stab.process(24.0 + i as f64, 0.0, 0.8, 0.0, 0.0, 0.0, t);+ if rise_ms.is_none() && s.pressure >= 0.2 + 0.9 * 0.6 {+ rise_ms = Some(i as f64 * DT);+ }+ t += DT;+ }+ let mut fall_ms = None;+ for i in 0..120 {+ let s = stab.process(144.0 + i as f64, 0.0, 0.2, 0.0, 0.0, 0.0, t);+ if fall_ms.is_none() && s.pressure <= 0.8 - 0.9 * 0.6 {+ fall_ms = Some(i as f64 * DT);+ }+ t += DT;+ }+ let rise = rise_ms.expect("pressure never rose");+ let fall = fall_ms.expect("pressure never fell");+ eprintln!("[brush-feel] pressure 90% rise = {rise:.1} ms, 90% fall = {fall:.1} ms");+ assert!(rise <= 17.0, "pressure attack too sluggish: {rise} ms");+ assert!(fall <= 21.0, "pressure release too sluggish (blunt tapers): {fall} ms");++ // Steady pressure must be reproduced exactly (predictable curve, no filter bias).+ let mut steady = 0.0;+ for i in 0..60 {+ steady = stab+ .process(300.0 + i as f64, 0.0, 0.437, 0.0, 0.0, 0.0, t)+ .pressure;+ t += DT;+ }+ assert!((steady - 0.437).abs() < 1e-3, "steady pressure biased: {steady}");+}++#[test]+fn brush_feel_pressure_jitter_is_still_suppressed() {+ // Cheap-tablet ±0.02 alternating pressure noise at constant hand pressure.+ let mut stab = InputStabilizer::new(StabilizerConfig::default());+ let mut t = 0.0;+ let mut outs = Vec::new();+ for i in 0..200 {+ let noise = if i % 2 == 0 { 0.02 } else { -0.02 };+ let s = stab.process(i as f64 * 0.8, 0.0, 0.5 + noise, 0.0, 0.0, 0.0, t);+ if i > 40 {+ outs.push(s.pressure);+ }+ t += DT;+ }+ let max = outs.iter().cloned().fold(f32::MIN, f32::max);+ let min = outs.iter().cloned().fold(f32::MAX, f32::min);+ eprintln!("[brush-feel] jitter ripple = {:.4}", max - min);+ assert!(max - min < 0.03, "pressure jitter leaks through: ripple {}", max - min);+}++#[test]+fn brush_feel_fast_stroke_tapers_to_a_point() {+ let trace = fast_flick_trace();+ for stab in [0.0f32, 6.0, 15.0] {+ let pts = run_trace(&trace, gpen_cfg(stab));+ let first = pts.first().unwrap();+ let last = pts.last().unwrap();+ let max_w = pts.iter().map(|p| p.width).fold(0.0f32, f32::max);+ eprintln!(+ "[brush-feel] stab={stab:>4}: start w={:.2} end w={:.2} max w={:.2} pts={}",+ first.width,+ last.width,+ max_w,+ pts.len()+ );+ assert!(max_w > 8.0, "stroke body never reached full width (stab={stab})");+ assert!(+ first.width <= 0.12 * max_w + 0.3,+ "start is blunt (stab={stab}): {}",+ first.width+ );+ assert!(+ last.width <= 0.12 * max_w + 0.3,+ "end is blunt on a fast release (stab={stab}): {}",+ last.width+ );+ // Width over the last quarter of the stroke must decrease monotonically+ // (no "bulb" or re-thickening at the tail).+ let tail_start = pts.len() * 3 / 4;+ let mut prev = f32::MAX;+ for p in &pts[tail_start..] {+ assert!(+ p.width <= prev + 0.05,+ "tail re-thickens (stab={stab}): {} after {}",+ p.width,+ prev+ );+ prev = p.width;+ }+ }+}++#[test]+fn brush_feel_stabilizer_settles_without_rubber_banding() {+ // Hand moves at 1.2 px/ms then stops dead; tablet keeps reporting the resting position.+ for level in [6.0f32, 15.0, 30.0] {+ let mut stab = InputStabilizer::new(StabilizerConfig {+ stabilization: level,+ zoom: 1.0,+ ..Default::default()+ });+ let mut t = 0.0;+ let mut x = 0.0;+ for _ in 0..96 {+ stab.process(x, 0.0, 0.6, 0.0, 0.0, 0.0, t);+ x += 1.2 * DT;+ t += DT;+ }+ let stop_x = x - 1.2 * DT;+ let mut settle_ms = None;+ let mut overshoot = 0.0f64;+ for i in 0..240 {+ let s = stab.process(stop_x, 0.0, 0.6, 0.0, 0.0, 0.0, t);+ overshoot = overshoot.max(s.x - stop_x);+ if settle_ms.is_none() && (stop_x - s.x).abs() < 0.5 {+ settle_ms = Some(i as f64 * DT);+ }+ t += DT;+ }+ let settle = settle_ms.unwrap_or(f64::INFINITY);+ eprintln!("[brush-feel] stab={level:>4}: settle after stop = {settle:.1} ms, overshoot = {overshoot:.3}px");+ assert!(overshoot < 0.05, "stabilizer overshoots (rubber band) at {level}");+ assert!(+ settle < 120.0 + level as f64 * 4.0,+ "stabilizer drags after the hand stops at level {level}: {settle} ms"+ );+ }+}++/// Slow careful line (0.15 px/ms) with 10 Hz ±1.5 px hand tremor; returns lateral RMS of output.+fn tremor_rms(level: f32, hz: f64) -> f64 {+ let dt = 1000.0 / hz;+ let mut stab = InputStabilizer::new(StabilizerConfig {+ stabilization: level,+ zoom: 1.0,+ ..Default::default()+ });+ let n = (2000.0 / dt) as usize;+ let mut sum = 0.0;+ let mut cnt = 0usize;+ for i in 0..n {+ let t = i as f64 * dt;+ let x = 0.15 * t;+ let y = 1.5 * (2.0 * std::f64::consts::PI * 10.0 * t / 1000.0).sin();+ let s = stab.process(x, y, 0.6, 0.0, 0.0, 0.0, t);+ if t > 300.0 {+ sum += s.y * s.y;+ cnt += 1;+ }+ }+ (sum / cnt as f64).sqrt()+}++#[test]+fn brush_feel_slow_line_tremor_is_smoothed() {+ let raw_rms = 1.5 / 2f64.sqrt();+ for level in [6.0f32, 15.0, 30.0] {+ let rms = tremor_rms(level, 240.0);+ eprintln!(+ "[brush-feel] tremor stab={level:>4}: output RMS {rms:.3}px ({:.0}% of raw)",+ 100.0 * rms / raw_rms+ );+ // Thresholds pinned to the pre-settle-floor smoothing so the "no rubber band"+ // fix can never silently trade away slow-line steadiness.+ let limit = if level >= 15.0 { 0.17 } else { 0.36 };+ assert!(rms < raw_rms * limit, "tremor not smoothed at level {level}: {rms}");+ }+}++#[test]+fn brush_feel_settle_is_sample_rate_invariant() {+ // Same gesture sampled at 60 Hz (mouse), 240 Hz (Windows Ink) and 1 kHz (WinTab).+ let settle = |hz: f64| -> f64 {+ let dt = 1000.0 / hz;+ let mut stab = InputStabilizer::new(StabilizerConfig {+ stabilization: 15.0,+ zoom: 1.0,+ ..Default::default()+ });+ let mut t = 0.0;+ while t < 400.0 {+ stab.process(t * 1.0, 0.0, 0.6, 0.0, 0.0, 0.0, t);+ t += dt;+ }+ let stop_x = (t - dt) * 1.0;+ let start = t;+ loop {+ let s = stab.process(stop_x, 0.0, 0.6, 0.0, 0.0, 0.0, t);+ if (stop_x - s.x).abs() < 0.5 || t - start > 2000.0 {+ return t - start;+ }+ t += dt;+ }+ };+ let (a, b, c) = (settle(60.0), settle(240.0), settle(1000.0));+ eprintln!("[brush-feel] settle @60Hz={a:.0}ms @240Hz={b:.0}ms @1kHz={c:.0}ms");+ let lo = a.min(b).min(c);+ let hi = a.max(b).max(c);+ assert!(hi < 200.0, "settle too slow at some sample rate: {a} / {b} / {c}");+ assert!(hi - lo < 60.0, "settle differs too much across sample rates: {a} / {b} / {c}");+}++#[test]+fn brush_feel_pen_up_tail_follows_the_curve() {+ // Quarter-circle arc (r = 80) drawn quickly with heavy stabilization, lift at the end.+ let r = 80.0;+ let n = 60;+ let trace: Vec<(f64, f64, f32, f64)> = (0..=n)+ .map(|i| {+ let a = std::f64::consts::FRAC_PI_2 * i as f64 / n as f64;+ (200.0 + r * a.cos(), 200.0 + r * a.sin(), 0.6, i as f64 * DT)+ })+ .collect();+ let pts = run_trace(+ &trace,+ StrokePipelineConfig {+ enable_flick_taper: false,+ ..gpen_cfg(30.0)+ },+ );+ // Every finalized point must stay close to the true arc (radius 80).+ let mut worst = 0.0f64;+ for p in &pts {+ let d = ((p.x - 200.0).hypot(p.y - 200.0) - r).abs();+ worst = worst.max(d);+ }+ let last = pts.last().unwrap();+ eprintln!("[brush-feel] arc stab=30: worst radial error = {worst:.2}px, pts={}", pts.len());+ assert!((last.x - 200.0).abs() < 1e-3 && (last.y - 280.0).abs() < 1e-3, "tail must land on the lift point");+ assert!(worst < 6.0, "pen-up tail cuts the curve (straight chord): {worst}px");+}++#[test]+fn brush_feel_pressure_curve_is_monotone_and_exact() {+ // Width must be a strictly non-decreasing function of pressure for a plain G-Pen.+ let mut prev = 0.0f32;+ for i in 0..=1000 {+ let p = i as f32 / 1000.0;+ let w = calculate_stroke_width(p, 12.0, true, 0.0, 1.0, None);+ assert!(w + 1e-6 >= prev, "width not monotone at p={p}: {w} < {prev}");+ prev = w;+ }+ assert!((calculate_stroke_width(1.0, 12.0, true, 0.0, 1.0, None) - 12.0).abs() < 1e-5);+ assert!((calculate_stroke_width(0.5, 12.0, true, 0.0, 1.0, None) - 6.0).abs() < 1e-5);+}++#[test]+fn brush_feel_diagonal_after_vertical_touchdown_never_bends_or_elbows() {+ // Reproduces the exact initial-tangent lock bug: pen touches down, slips 1px vertically+ // on contact, then pulls smoothly down-left along a straight diagonal with G-Pen defaults+ // (stabilization = 10, sharp_corners = true). Must never track vertically or kink!+ let mut trace = vec![+ (400.0, 100.0, 0.08f32, 0.0),+ (400.0, 101.0, 0.20, DT), // 1px vertical touchdown skid+ ];+ let dir_x = -0.55;+ let dir_y = 0.8351646544245033; // unit vector down-left+ for i in 2..=70 {+ let s = (i - 1) as f64 * 3.5;+ trace.push((400.0 + dir_x * s, 101.0 + dir_y * s, 0.65, i as f64 * DT));+ }++ let pts = run_trace(+ &trace,+ StrokePipelineConfig {+ sharp_corners: true,+ enable_flick_taper: false,+ ..gpen_cfg(10.0)+ },+ );++ let mut max_perp_err = 0.0f64;+ let mut false_corners = 0usize;+ for p in &pts {+ if p.is_corner {+ false_corners += 1;+ }+ // Perpendicular distance to the diagonal ray starting at (400, 101)+ let rx = p.x - 400.0;+ let ry = p.y - 101.0;+ let perp = (rx * (-dir_y) + ry * dir_x).abs();+ max_perp_err = max_perp_err.max(perp);+ }+ eprintln!(+ "[brush-feel] diagonal w/ vertical touchdown: max_perp_err={max_perp_err:.3}px, false_corners={false_corners}"+ );+ assert_eq!(+ false_corners, 0,+ "diagonal stroke must not trigger false sharp corners"+ );+ assert!(+ max_perp_err < 1.25,+ "diagonal stroke bent off-axis after vertical touchdown: {max_perp_err:.3}px"+ );+}++#[test]+fn brush_feel_freehand_line_rejects_micro_twitches_and_liftoff_hooks() {+ // Freehand diagonal stroke with:+ // 1. A 4px touchdown skid at start,+ // 2. A 1-sample 5px sideways digitizer twitch mid-stroke,+ // 3. A 7px sideways 90-degree stylus lift-off wobble as pressure collapses to near-zero.+ // With G-Pen defaults (stab=10, sharp_corners=true), NONE of these may cause a 90° hook!+ let mut trace = Vec::new();+ let mut t = 0.0;+ trace.push((300.0, 100.0, 0.05f32, t));+ t += DT;+ // Slight touchdown jitter+ trace.push((297.5, 100.5, 0.12, t));+ t += DT;+ for i in 1..=50 {+ let mut x = 300.0 - i as f64 * 2.0;+ let mut y = 100.0 + i as f64 * 3.5;+ let p = if i < 45 {+ 0.65+ } else {+ (0.65 * (50 - i) as f32 / 5.0).max(0.02)+ };+ // Mid-stroke 1-sample 5px sideways twitch+ if i == 25 {+ x -= 5.0;+ y -= 2.0;+ }+ trace.push((x, y, p, t));+ t += DT;+ }+ // Lift-off 90-degree sideways tilt hook right as pressure collapses to 0.01+ let (lx, ly, _, _) = *trace.last().unwrap();+ trace.push((lx - 7.0, ly - 4.0, 0.01, t));++ let pts = run_trace(+ &trace,+ StrokePipelineConfig {+ sharp_corners: true,+ enable_flick_taper: false,+ ..gpen_cfg(10.0)+ },+ );++ let corners = pts.iter().filter(|p| p.is_corner).count();+ let last = pts.last().unwrap();+ let end_err = (last.x - lx).hypot(last.y - ly);+ eprintln!(+ "[brush-feel] twitch+liftoff guard: corners={corners}, end_err_from_clean_end={end_err:.3}px"+ );+ assert_eq!(corners, 0, "micro-twitches must never snap sharp corners");+ assert!(+ end_err < 1.5,+ "stylus lift-off sideways wobble leaked into stroke end: {end_err:.3}px"+ );+}++#[test]+fn brush_feel_intentional_240hz_sharp_corner_still_snaps_cleanly() {+ // Real intentional 90-degree L-corner at 240Hz (~3.5px/sample) MUST still trigger sharp corner!+ let mut stab = InputStabilizer::new(StabilizerConfig {+ stabilization: 12.0,+ sharp_corners: true,+ zoom: 1.0,+ pressure_smoothing: 0.35,+ });+ let mut t = 0.0;+ for i in 0..20 {+ stab.process(100.0 + i as f64 * 3.5, 100.0, 0.7, 0.0, 0.0, 0.0, t);+ t += DT;+ }+ let apex_x = 100.0 + 19.0 * 3.5;+ let mut snapped_apex = None;+ for j in 1..=8 {+ let s = stab.process(apex_x, 100.0 + j as f64 * 3.5, 0.7, 0.0, 0.0, 0.0, t);+ if s.is_corner {+ snapped_apex = Some((s.x, s.y));+ break;+ }+ t += DT;+ }+ let (ax, ay) = snapped_apex.expect("intentional 240Hz 90-degree corner must snap");+ assert!(+ (ax - apex_x).abs() < 4.0 && (ay - 100.0).abs() < 4.0,+ "corner apex drifted too far: ({ax}, {ay}) vs ({apex_x}, 100.0)"+ );+}diff --git a/crates/ink-engine/src/compositor/renderer.rs b/crates/ink-engine/src/compositor/renderer.rsindex 5083ebc..259eb34 100644--- a/crates/ink-engine/src/compositor/renderer.rs+++ b/crates/ink-engine/src/compositor/renderer.rs@@ -102,6 +102,8 @@ pub(crate) struct TileInstanceGpu {pub(crate) mask_slice: i32,pub(crate) mask_default: f32,pub(crate) _pad: f32,+ pub(crate) neighbors_cardinal: [i32; 4], // (L, R, T, B); -1 = empty, -2 = clamp-to-self+ pub(crate) neighbors_diag: [i32; 4], // (TL, TR, BL, BR)}#[repr(C)]@@ -827,6 +829,8 @@ impl CompositorPipelines {wgpu::VertexAttribute { offset: 20, shader_location: 3, format: wgpu::VertexFormat::Sint32 },wgpu::VertexAttribute { offset: 24, shader_location: 4, format: wgpu::VertexFormat::Float32 },wgpu::VertexAttribute { offset: 28, shader_location: 5, format: wgpu::VertexFormat::Float32 },+ wgpu::VertexAttribute { offset: 32, shader_location: 6, format: wgpu::VertexFormat::Sint32x4 },+ wgpu::VertexAttribute { offset: 48, shader_location: 7, format: wgpu::VertexFormat::Sint32x4 },],};let layer_tile_blend = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {@@ -1670,7 +1674,7 @@ impl FrameRenderView {let lod = if force_lod_zero {0} else {- select_lod_for_zoom(camera.zoom)+ select_lod_for_zoom(camera.zoom * safe_dpr)};let mut h = Fnv1a64::new();hash_camera_and_viewport(@@ -2476,7 +2480,22 @@ impl WgpuCompositor {}if let Some(overlay) = gpu_stroke_overlay.as_mut().filter(|ov| ov.brush_engine.is_active()) {+ let has_impasto_shadow = overlay.live_impasto.is_some()+ || overlay.brush_engine.active_impasto_overlay_with_id().is_some()+ || active_layer.grid.has_impasto();+ let imp_pad = if has_impasto_shadow {+ ((12.0 * view.camera.zoom * view.dpr).ceil() as u32).clamp(12, 48)+ } else {+ 0+ };let update_scissor = precomputed_gpu_update_scissor+ .map(|s| {+ if imp_pad > 0 {+ s.expand(imp_pad, view.viewport_w, view.viewport_h)+ } else {+ s+ }+ }).unwrap_or(full_scissor).clamp(view.viewport_w, view.viewport_h);let clamped_pred_scissor = precomputed_pred_scissor;@@ -2615,9 +2634,10 @@ impl WgpuCompositor {.as_ref().map(|li| (0u64, li.height_atlas_view, li.height_tile_map)).or_else(|| engine_imp_overlay.map(|(id, v, m, _)| (id, v, m)));- // Scissored impasto height projection (expanded >= 22 px so 18 px raymarch samples valid heights!)+ // Scissored impasto height projection (expanded for 7.8 doc-px directional cast-shadow reach!)+ let height_pad = ((12.0 * view.camera.zoom * view.dpr).ceil() as u32).clamp(22, 64);let height_scissor =- update_scissor.expand(22, view.viewport_w, view.viewport_h);+ update_scissor.expand(height_pad, view.viewport_w, view.viewport_h);project_impasto_height_tiles(device,queue,@@ -5673,7 +5693,8 @@ fn render_raster_layer_tiles(false,scissor,);- let height_scissor = scissor.expand(22, ctx.view.viewport_w, ctx.view.viewport_h);+ let height_pad = ((12.0 * ctx.view.camera.zoom * ctx.view.dpr).ceil() as u32).clamp(22, 64);+ let height_scissor = scissor.expand(height_pad, ctx.view.viewport_w, ctx.view.viewport_h);project_impasto_height_tiles(ctx.device,ctx.queue,@@ -5935,6 +5956,12 @@ fn render_raster_layer_tiles_direct(} else {-1};+ let lookup_warped = |dx: i32, dy: i32| -> i32 {+ warped_map+ .get(&TileCoord::new(coord.tx + dx, coord.ty + dy))+ .map(|&s| s as i32)+ .unwrap_or(-2)+ };TileInstanceGpu {tile_origin_doc: [(coord.tx * TILE_SIZE as i32) as f32,@@ -5945,6 +5972,18 @@ fn render_raster_layer_tiles_direct(mask_slice,mask_default,_pad: 0.0,+ neighbors_cardinal: [+ lookup_warped(-1, 0),+ lookup_warped(1, 0),+ lookup_warped(0, -1),+ lookup_warped(0, 1),+ ],+ neighbors_diag: [+ lookup_warped(-1, -1),+ lookup_warped(1, -1),+ lookup_warped(-1, 1),+ lookup_warped(1, 1),+ ],}}).collect();@@ -6184,8 +6223,13 @@ fn collect_visible_tile_instances(let doc_key = tile_pool.intern_doc(&doc.id);let layer_key = tile_pool.intern_layer(&layer.meta.id);+ let max_doc_tx = (doc.dimensions.width.max(1) as i32 - 1).div_euclid(span);+ let max_doc_ty = (doc.dimensions.height.max(1) as i32 - 1).div_euclid(span);+if view.lod == 0 {let mask_default = layer.grid.mask_default_value as f32 / 255.0;+ let mut visible_entries: Vec<(TileCoord, i32, i32)> = Vec::new();+ let mut visible_slots: HashMap<TileCoord, i32> = HashMap::new();for (&coord, tile) in &layer.grid.tiles {if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {continue;@@ -6194,7 +6238,7 @@ fn collect_visible_tile_instances(let Some(s) = tile_pool.get_solid_color_slot(solid_16f) else {continue;};- s+ s as i32} else {let key = GpuTileKey {doc_id: doc_key,@@ -6205,8 +6249,9 @@ fn collect_visible_tile_instances(let Some(s) = tile_pool.get_slot(&key) else {continue;};- s+ s as i32};+ visible_slots.insert(coord, atlas_slice);let mask_slice = if use_sparse_mask {let mkey = GpuTileKey {doc_id: doc_key,@@ -6227,26 +6272,77 @@ fn collect_visible_tile_instances(} else {-1};+ visible_entries.push((coord, atlas_slice, mask_slice));+ }+ let mut lookup_neighbor = |tx: i32, ty: i32| -> i32 {+ if tx < 0 || ty < 0 || tx > max_doc_tx || ty > max_doc_ty {+ return -2;+ }+ let nc = TileCoord::new(tx, ty);+ if let Some(&s) = visible_slots.get(&nc) {+ return s;+ }+ match layer.grid.tiles.get(&nc) {+ None => -1,+ Some(tile) => {+ if let Some(solid_16f) = tile.solid_rgba16f() {+ tile_pool+ .get_solid_color_slot(solid_16f)+ .map(|s| s as i32)+ .unwrap_or(-2)+ } else {+ tile_pool+ .get_slot(&GpuTileKey {+ doc_id: doc_key,+ layer_id: layer_key,+ lod: 0,+ coord: nc,+ })+ .map(|s| s as i32)+ .unwrap_or(-2)+ }+ }+ }+ };++ instances.reserve(visible_entries.len());+ for (coord, atlas_slice, mask_slice) in visible_entries {instances.push(TileInstanceGpu {tile_origin_doc: [(coord.tx * span) as f32, (coord.ty * span) as f32],tile_size_doc: [span as f32, span as f32],- atlas_slice: atlas_slice as i32,+ atlas_slice,mask_slice,mask_default,_pad: 0.0,+ neighbors_cardinal: [+ lookup_neighbor(coord.tx - 1, coord.ty),+ lookup_neighbor(coord.tx + 1, coord.ty),+ lookup_neighbor(coord.tx, coord.ty - 1),+ lookup_neighbor(coord.tx, coord.ty + 1),+ ],+ neighbors_diag: [+ lookup_neighbor(coord.tx - 1, coord.ty - 1),+ lookup_neighbor(coord.tx + 1, coord.ty - 1),+ lookup_neighbor(coord.tx - 1, coord.ty + 1),+ lookup_neighbor(coord.tx + 1, coord.ty + 1),+ ],});}} else {+ let mut all_parents: HashSet<TileCoord> = HashSet::new();let mut parent_coords: HashSet<TileCoord> = HashSet::new();for &coord in layer.grid.tiles.keys() {let ptx = coord.tx.div_euclid(scale);let pty = coord.ty.div_euclid(scale);+ let pcoord = TileCoord::new(ptx, pty);+ all_parents.insert(pcoord);if ptx >= min_tx && ptx <= max_tx && pty >= min_ty && pty <= max_ty {- parent_coords.insert(TileCoord::new(ptx, pty));+ parent_coords.insert(pcoord);}}- for pcoord in parent_coords {+ let mut visible_slots: HashMap<TileCoord, i32> = HashMap::with_capacity(parent_coords.len());+ for &pcoord in &parent_coords {let atlas_slice = if let Some(solid_16f) = uniform_solid_color_for_lod_tile(&layer.grid,view.lod,@@ -6257,7 +6353,7 @@ fn collect_visible_tile_instances(let Some(s) = tile_pool.get_solid_color_slot(solid_16f) else {continue;};- s+ s as i32} else {let key = GpuTileKey {doc_id: doc_key,@@ -6268,15 +6364,67 @@ fn collect_visible_tile_instances(let Some(s) = tile_pool.get_slot(&key) else {continue;};- s+ s as i32};+ visible_slots.insert(pcoord, atlas_slice);+ }++ let mut lookup_neighbor = |tx: i32, ty: i32| -> i32 {+ if tx < 0 || ty < 0 || tx > max_doc_tx || ty > max_doc_ty {+ return -2;+ }+ let nc = TileCoord::new(tx, ty);+ if let Some(&s) = visible_slots.get(&nc) {+ return s;+ }+ if !all_parents.contains(&nc) {+ return -1;+ }+ if let Some(solid_16f) = uniform_solid_color_for_lod_tile(+ &layer.grid,+ view.lod,+ nc,+ doc.dimensions.width,+ doc.dimensions.height,+ ) {+ tile_pool+ .get_solid_color_slot(solid_16f)+ .map(|s| s as i32)+ .unwrap_or(-2)+ } else {+ tile_pool+ .get_slot(&GpuTileKey {+ doc_id: doc_key,+ layer_id: layer_key,+ lod: view.lod,+ coord: nc,+ })+ .map(|s| s as i32)+ .unwrap_or(-2)+ }+ };++ instances.reserve(visible_slots.len());+ for (&pcoord, &atlas_slice) in &visible_slots {instances.push(TileInstanceGpu {tile_origin_doc: [(pcoord.tx * span) as f32, (pcoord.ty * span) as f32],tile_size_doc: [span as f32, span as f32],- atlas_slice: atlas_slice as i32,+ atlas_slice,mask_slice: -1,mask_default: 1.0,_pad: 0.0,+ neighbors_cardinal: [+ lookup_neighbor(pcoord.tx - 1, pcoord.ty),+ lookup_neighbor(pcoord.tx + 1, pcoord.ty),+ lookup_neighbor(pcoord.tx, pcoord.ty - 1),+ lookup_neighbor(pcoord.tx, pcoord.ty + 1),+ ],+ neighbors_diag: [+ lookup_neighbor(pcoord.tx - 1, pcoord.ty - 1),+ lookup_neighbor(pcoord.tx + 1, pcoord.ty - 1),+ lookup_neighbor(pcoord.tx - 1, pcoord.ty + 1),+ lookup_neighbor(pcoord.tx + 1, pcoord.ty + 1),+ ],});}}diff --git a/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs b/crates/ink-engine/src/compositor/shaders/impasto_lighting.rsindex 830ef1d..4b524e6 100644--- a/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs+++ b/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs@@ -3,10 +3,15 @@//! 1. `IMPASTO_HEIGHT_PROJECT_WGSL`: Projects sparse `256×256` `R16Float` impasto heightfield//! tiles (from `GpuTilePool::impasto_atlas` and/or an active live stroke's height tiles)//! into a viewport-space `R16Float` heightfield target.-//! 2. `IMPASTO_LIGHTING_WGSL`: Computes 3×3 smoothed Sobel normals from `R16Float`, directional-//! diffuse lighting, 5-tap directional cast shadows, local concavity micro-AO, chromatic-//! trough deepening, and 2-lobe Blinn-Phong gloss specular over the layer's `Rgba16Float`-//! color surface.+//! 2. `IMPASTO_LIGHTING_WGSL`: Exact GPU port of InkStudio's sculptural 3D impasto relief shader+//! (`NaturalPaintRenderer.ts`):+//! - Hardware-bilinear 2D separable `[0.22, 0.56, 0.22]` pre-smoothed heightfield (silky oil crests!)+//! - Document-space-invariant 3×3 Sobel normal derivation + centered directional diffuse+//! - 5-tap directional 3D ray-marched cast self-shadows on paint ridges AND spatial cast drop+//! shadows onto bare canvas / lower layers & semi-transparent paint edges+//! - Bristle-valley micro-AO, subsurface scattering shadow floor, and chromatic shadow deepening+//! - Specular shadow suppression, adaptive dark-pigment oil sheen + warm studio key lift, and+//! two-lobe oil gloss (broad satin wrap + crisp glossy crest catchlights)./// Projects sparse `256×256` `R16Float` height tiles (from both base layer atlas and optional live/// stroke atlas) into a viewport `R16Float` surface with seamless cross-tile 3×3 neighbor bilinear@@ -163,7 +168,8 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {}"#;-/// Fullscreen scissored Impasto 3D Relief Lighting pass (`Rgba16Float` color + `R16Float` height -> lit `Rgba16Float`).+/// Fullscreen scissored Impasto 3D Relief Lighting + Spatial Cast Shadows pass+/// (`Rgba16Float` color + `R16Float` height -> lit `Rgba16Float`).pub const IMPASTO_LIGHTING_WGSL: &str = r#"struct ImpastoLightUniforms {viewport_size_phys: vec2<f32>,@@ -200,106 +206,249 @@ fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {return out;}-fn sample_height(uv: vec2<f32>, min_uv: vec2<f32>, max_uv: vec2<f32>) -> f32 {+fn sample_raw_h(uv: vec2<f32>, min_uv: vec2<f32>, max_uv: vec2<f32>) -> f32 {return max(textureSampleLevel(height_tex, lin_sampler, clamp(uv, min_uv, max_uv), 0.0).r, 0.0);}+// Exact hardware-bilinear 2D separable Gaussian smoothing in 4 taps!+// Eliminates single-pixel stair-stepping so oil crests look buttery, liquid, and sculptural.+fn sample_smooth_h(+ uv: vec2<f32>,+ doc_step: vec2<f32>,+ min_uv: vec2<f32>,+ max_uv: vec2<f32>,+ depth_scale: f32,+) -> f32 {+ let o = doc_step * 0.52;+ let a = sample_raw_h(uv + vec2<f32>(-o.x, -o.y), min_uv, max_uv);+ let b = sample_raw_h(uv + vec2<f32>( o.x, -o.y), min_uv, max_uv);+ let c = sample_raw_h(uv + vec2<f32>(-o.x, o.y), min_uv, max_uv);+ let d = sample_raw_h(uv + vec2<f32>( o.x, o.y), min_uv, max_uv);+ return (a + b + c + d) * 0.25 * depth_scale;+}++// 6-tap directional 3D heightfield cast-shadow raymarcher with soft physical penumbra+fn eval_cast_shadow(+ uv: vec2<f32>,+ h_origin: f32,+ dl_uv: vec2<f32>,+ ray_slope: f32,+ shadow_scale: f32,+ doc_step: vec2<f32>,+ min_uv: vec2<f32>,+ max_uv: vec2<f32>,+ depth_scale: f32,+) -> f32 {+ var max_occ = 0.0;++ // Tap 0: 1.2 doc px (tight contact occlusion right next to thick ridge walls)+ var occ = sample_smooth_h(uv + dl_uv * 1.2, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 1.2);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.94);+ }+ // Tap 1: 2.5 doc px+ occ = sample_smooth_h(uv + dl_uv * 2.5, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 2.5);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.72);+ }+ // Tap 2: 4.1 doc px+ occ = sample_smooth_h(uv + dl_uv * 4.1, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 4.1);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.48);+ }+ // Tap 3: 5.9 doc px+ occ = sample_smooth_h(uv + dl_uv * 5.9, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 5.9);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.26);+ }+ // Tap 4: 7.8 doc px+ occ = sample_smooth_h(uv + dl_uv * 7.8, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 7.8);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.11);+ }+ // Tap 5: 9.6 doc px (soft far penumbra tail for tall palette-knife & impasto walls)+ occ = sample_smooth_h(uv + dl_uv * 9.6, doc_step, min_uv, max_uv, depth_scale) - (h_origin + ray_slope * 9.6);+ if (occ > 0.0) {+ max_occ = max(max_occ, occ * 0.035);+ }++ return clamp(max_occ * shadow_scale, 0.0, 1.0);+}+@fragmentfn fs_main(in: VsOut) -> @location(0) vec4<f32> {let coord = vec2<i32>(in.clip_pos.xy);let base = textureLoad(color_tex, coord, 0);- if (base.a <= 1e-4 || u.params1.w < 0.5) {+ if (u.params1.w < 0.5) {+ return base;+ }++ let imp_depth = clamp(u.params0.x, 0.0, 2.5);+ if (imp_depth <= 0.01) {return base;}+ let imp_gloss = clamp(u.params0.y, 0.0, 1.5);+ let imp_contrast = clamp(u.params0.z, 0.0, 3.0);+ let zoom_scale = clamp(u.params0.w, 0.25, 4.0);+let tex_dims = max(vec2<f32>(1.0), vec2<f32>(textureDimensions(height_tex)));let inv_tex = vec2<f32>(1.0) / tex_dims;let min_uv = vec2<f32>(0.5) * inv_tex;let max_uv = max(min_uv, (u.viewport_size_phys - vec2<f32>(0.5)) * inv_tex);-- let depth = max(u.params0.x, 0.0);- let gloss = clamp(u.params0.y, 0.0, 1.5);- let contrast = clamp(u.params0.z, 0.0, 3.0);- let step_px = clamp(u.params1.z, 1.0, 2.5);- let dx = inv_tex.x * step_px;- let dy = inv_tex.y * step_px;-let uv = in.clip_pos.xy * inv_tex;- // 3x3 height neighborhood for Sobel normal & concavity micro-AO- let h00 = sample_height(uv + vec2<f32>(-dx, -dy), min_uv, max_uv);- let h10 = sample_height(uv + vec2<f32>(0.0, -dy), min_uv, max_uv);- let h20 = sample_height(uv + vec2<f32>( dx, -dy), min_uv, max_uv);- let h01 = sample_height(uv + vec2<f32>(-dx, 0.0), min_uv, max_uv);- let h11 = sample_height(uv, min_uv, max_uv);- let h21 = sample_height(uv + vec2<f32>( dx, 0.0), min_uv, max_uv);- let h02 = sample_height(uv + vec2<f32>(-dx, dy), min_uv, max_uv);- let h12 = sample_height(uv + vec2<f32>(0.0, dy), min_uv, max_uv);- let h22 = sample_height(uv + vec2<f32>( dx, dy), min_uv, max_uv);-- let gx = (h20 + 2.0 * h21 + h22) - (h00 + 2.0 * h01 + h02);- let gy = (h02 + 2.0 * h12 + h22) - (h00 + 2.0 * h10 + h20);-- if (h11 < 1e-4 && abs(gx) + abs(gy) < 1e-4) {- return base;- }- // Lightly smoothed center height for stability against single-pixel quantization- let h_avg = (h00 + h10 + h20 + h01 + h21 + h02 + h12 + h22) * 0.125;- let h_smooth = h11 * 0.5 + h_avg * 0.5;+ // Document-space 1px step in UV space so normals & spatial cast shadows stay locked to artwork at every zoom!+ let doc_step = inv_tex * zoom_scale;+ let depth_scale = imp_depth * 1.75;- let slope_scale = 3.8 * depth * contrast;- let n = normalize(vec3<f32>(-gx * slope_scale, -gy * slope_scale, 1.0));let l = normalize(u.light_dir.xyz);- let v = vec3<f32>(0.0, 0.0, 1.0);- let h_vec = normalize(l + v);-- let ndotl = clamp(dot(n, l), 0.0, 1.0);- let ndotl_flat = max(l.z, 0.15);- // Relative directional shading normalized around flat canvas response (so flat pixels stay true to base color!)- let rel_diff = (ndotl - ndotl_flat) / max(ndotl_flat, 0.25);-- // 5-tap directional cast shadow march toward light source- let l_xy_len = max(length(l.xy), 1e-4);- let march_dir = (l.xy / l_xy_len) * inv_tex * (1.8 * step_px);- let slope_rise = max(l.z / l_xy_len, 0.25) * (0.28 / max(depth, 0.15));- var shadow_occ = 0.0;- for (var s: i32 = 1; s <= 5; s = s + 1) {- let sf = f32(s);- let h_tap = sample_height(uv + march_dir * sf, min_uv, max_uv);- let excess = h_tap - (h_smooth + slope_rise * sf * 0.22);- shadow_occ = max(shadow_occ, clamp(excess * 1.65, 0.0, 1.0));+ let horiz_len = max(length(l.xy), 1e-4);+ let dl = l.xy / horiz_len;+ let dl_uv = dl * doc_step;+ let ray_slope = (l.z / horiz_len) * 0.088;++ let shadow_scale = 1.65 + imp_contrast * 1.50;+ let under_shadow_scale = 0.14 + imp_depth * 0.22;+ let shadow_rgb = vec3<f32>(24.0 / 255.0, 21.0 / 255.0, 32.0 / 255.0);++ // 1. Bare canvas / lower-layer pixel: thick impasto ridges cast real 3D spatial drop shadows!+ if (base.a <= 0.003) {+ if (imp_depth > 0.22) {+ let cast_s = eval_cast_shadow(+ uv,+ 0.0,+ dl_uv,+ ray_slope,+ shadow_scale,+ doc_step,+ min_uv,+ max_uv,+ depth_scale,+ );+ if (cast_s > 0.05) {+ let shadow_a = min(0.28, pow(cast_s, 1.25) * under_shadow_scale);+ return vec4<f32>(shadow_rgb * shadow_a, shadow_a);+ }+ }+ return base;}- let cast_shadow = 1.0 - shadow_occ * clamp(u.params1.y, 0.0, 0.65);- // Micro-AO from local valley concavity- let concavity = clamp((h_avg - h11) * 2.6, 0.0, 1.0);- let micro_ao = 1.0 - concavity * clamp(u.params1.x, 0.0, 0.6) * 0.5;+ // 2. Painted pixel: 3x3 smoothed Sobel normals + centered diffuse + 5-tap self-shadow ++ // micro-AO + chromatic shadow deepening + adaptive dark-oil satin sheen & 2-lobe gloss!+ let dx = doc_step.x;+ let dy = doc_step.y;+ let h_tl = sample_smooth_h(uv + vec2<f32>(-dx, -dy), doc_step, min_uv, max_uv, depth_scale);+ let h_t = sample_smooth_h(uv + vec2<f32>(0.0, -dy), doc_step, min_uv, max_uv, depth_scale);+ let h_tr = sample_smooth_h(uv + vec2<f32>( dx, -dy), doc_step, min_uv, max_uv, depth_scale);+ let h_l = sample_smooth_h(uv + vec2<f32>(-dx, 0.0), doc_step, min_uv, max_uv, depth_scale);+ let h_c = sample_smooth_h(uv, doc_step, min_uv, max_uv, depth_scale);+ let h_r = sample_smooth_h(uv + vec2<f32>( dx, 0.0), doc_step, min_uv, max_uv, depth_scale);+ let h_bl = sample_smooth_h(uv + vec2<f32>(-dx, dy), doc_step, min_uv, max_uv, depth_scale);+ let h_b = sample_smooth_h(uv + vec2<f32>(0.0, dy), doc_step, min_uv, max_uv, depth_scale);+ let h_br = sample_smooth_h(uv + vec2<f32>( dx, dy), doc_step, min_uv, max_uv, depth_scale);++ let gx_paint = (h_tr + 2.0 * h_r + h_br) - (h_tl + 2.0 * h_l + h_bl);+ let gy_paint = (h_bl + 2.0 * h_b + h_br) - (h_tl + 2.0 * h_t + h_tr);++ if (h_c < 1e-4 && abs(gx_paint) + abs(gy_paint) < 1e-4) {+ return base;+ }- // Unpremultiply base color- let inv_a = 1.0 / max(base.a, 1e-5);- let straight = clamp(base.rgb * inv_a, vec3<f32>(0.0), vec3<f32>(1.0));+ let hp_raw = sample_raw_h(uv, min_uv, max_uv);+ let relief_scale = 4.0 + imp_depth * 8.0;+ let nx = -(gx_paint * relief_scale);+ let ny = -(gy_paint * relief_scale);+ let inv_nlen = inverseSqrt(nx * nx + ny * ny + 1.0);+ let n = vec3<f32>(nx * inv_nlen, ny * inv_nlen, inv_nlen);++ let grad_mag = sqrt(gx_paint * gx_paint + gy_paint * gy_paint);+ let slope_mask = min(1.0, grad_mag * 2.8);++ // Centered directional diffuse: flat paint (0,0,1) produces delta=0 (preserves true pigment hue!)+ let n_dot_l = dot(n, l);+ let raw_diff = n_dot_l - l.z;+ let diff_amp = 0.36 + imp_contrast * 0.52;+ let diffuse_delta = raw_diff * diff_amp;++ // Real directional 3D cast self-shadow from neighboring taller bristle ridges+ let cast_shadow = eval_cast_shadow(+ uv,+ h_c,+ dl_uv,+ ray_slope,+ shadow_scale,+ doc_step,+ min_uv,+ max_uv,+ depth_scale,+ );+ let cast_darken_scale = 0.30 + imp_contrast * 0.26;+ let cast_darken = cast_shadow * cast_darken_scale;++ // Deep bristle-valley micro-AO+ let avg_h = (h_t + h_b + h_l + h_r + (h_tl + h_tr + h_bl + h_br) * 0.5) * (1.0 / 6.0);+ let concavity = max(0.0, avg_h - h_c);+ let ao_scale = 1.0 + imp_contrast * 1.5;+ let ao = min(0.28, concavity * ao_scale);++ // Unpremultiply base color (straight sRGB 0..1)+ let alpha_in = clamp(base.a, 0.0, 1.0);+ let inv_a = 1.0 / max(alpha_in, 1e-5);+ var rgb = clamp(base.rgb * inv_a, vec3<f32>(0.0), vec3<f32>(1.0));+ let base_lum = dot(rgb, vec3<f32>(0.299, 0.587, 0.114));++ // Physical oil subsurface scattering floor: light translucent pigments hold rich luminous shadows!+ let sss_floor = 0.44 + base_lum * 0.18;+ let shade_mult = clamp(1.0 + diffuse_delta - ao - cast_darken, sss_floor, 1.28);++ // Chromatic richness in shadows: real oil crevices & cast shadows deepen in chroma instead of muddying!+ let shadow_amt = 1.0 - shade_mult;+ if (shadow_amt > 0.02) {+ let sat_boost = 1.0 + shadow_amt * 0.50;+ rgb = clamp(vec3<f32>(base_lum) + (rgb - vec3<f32>(base_lum)) * sat_boost, vec3<f32>(0.0), vec3<f32>(1.0));+ }- // Diffuse relief modulation with subtle warm/cool oil shading & chromatic shadow richness- let shade = clamp(1.0 + rel_diff * 0.54 * clamp(contrast, 0.2, 2.0), 0.48, 1.45) * cast_shadow * micro_ao;- var lit = straight * shade;+ // Physically suppress specular reflections inside real directional cast shadows!+ let spec_vis = max(0.06, 1.0 - cast_shadow * 0.88);+ let oil_thickness_mask = min(1.0, 0.24 + hp_raw * 1.15) * spec_vis;++ // Adaptive sheen: dark/Prussian oil gets crisp sculptural studio sheen; bright oil gets soft creamy luster!+ let dark_sheen_boost = 1.55 - base_lum * 0.94;+ let spec_factor = slope_mask * oil_thickness_mask * dark_sheen_boost;+ let key_lift_base = (0.20 + imp_gloss * 0.30) * (0.45 + imp_contrast * 0.55) * (110.0 / 255.0);+ let key_lift = max(0.0, raw_diff) * spec_factor * key_lift_base;++ // Two-lobe oil sheen (broad satin wrap + crisp glossy crest catchlights)+ let h_vec = normalize(l + vec3<f32>(0.0, 0.0, 1.0));+ let n_dot_h = max(0.0, dot(n, h_vec));+ var total_spec = key_lift;+ if (n_dot_h > 0.0) {+ let satin_amp = (0.12 + imp_gloss * 0.24) * (0.45 + imp_depth * 0.60);+ let gloss_amp = imp_gloss * (0.24 + imp_depth * 0.44);+ let satin_exp = 10.0 + imp_gloss * 11.0;+ let gloss_exp = 30.0 + imp_gloss * 46.0;+ let s_pow = pow(n_dot_h, satin_exp);+ let g_pow = pow(n_dot_h, gloss_exp);+ total_spec = total_spec + (s_pow * satin_amp * (124.0 / 255.0) + g_pow * gloss_amp * (195.0 / 255.0)) * spec_factor;+ }- // Subtle chromatic saturation boost in recessed troughs (oil paint subsurface scattering)- if (shade < 0.98) {- let luma = dot(lit, vec3<f32>(0.2126, 0.7152, 0.0722));- let shadow_amt = clamp((0.98 - shade) * 0.55, 0.0, 0.25);- lit = mix(vec3<f32>(luma), lit, 1.0 + shadow_amt);+ // Warm studio highlight tint (#fffbf2) + rich sculpted shadows+ let warm_tint = vec3<f32>(1.0, 0.985, 0.955);+ var lit = clamp(rgb * shade_mult + warm_tint * total_spec, vec3<f32>(0.0), vec3<f32>(1.0));+ var out_a = alpha_in;++ // Subtle under-edge spatial cast shadow behind thick impasto edges (never darkens thin blended edges!)+ if (out_a < 0.98 && imp_depth > 0.22 && cast_shadow > 0.06) {+ let under_a = min(0.24, pow(cast_shadow, 1.25) * under_shadow_scale);+ let comb_a = out_a + under_a * (1.0 - out_a);+ if (comb_a > 0.001) {+ let bg_w = under_a * (1.0 - out_a);+ lit = clamp((lit * out_a + shadow_rgb * bg_w) / comb_a, vec3<f32>(0.0), vec3<f32>(1.0));+ out_a = comb_a;+ }}- // 2-lobe Blinn-Phong specular highlight (broad satin oil sheen + tight ridge glint)- let relief_mask = smoothstep(0.015, 0.22, h_smooth) * smoothstep(0.0, 0.18, abs(gx) + abs(gy) + h_smooth * 0.35);- let ndoth = max(dot(n, h_vec), 0.0);- let sheen = pow(ndoth, 14.0) * 0.12 * gloss;- let glint = pow(ndoth, 56.0) * 0.42 * gloss;- let spec = (sheen + glint) * relief_mask * cast_shadow * clamp(contrast, 0.2, 2.2);- // Warm tungsten-daylight specular slightly tinted toward paint color for satin oil realism- let spec_tint = mix(vec3<f32>(1.0, 0.99, 0.97), straight, 0.15);- lit = clamp(lit + spec_tint * spec, vec3<f32>(0.0), vec3<f32>(1.0));-- return vec4<f32>(lit * base.a, base.a);+ return vec4<f32>(lit * out_a, out_a);}"#;diff --git a/crates/ink-engine/src/compositor/shaders/layer_tile.rs b/crates/ink-engine/src/compositor/shaders/layer_tile.rsindex a61f9c6..701dfbd 100644--- a/crates/ink-engine/src/compositor/shaders/layer_tile.rs+++ b/crates/ink-engine/src/compositor/shaders/layer_tile.rs@@ -60,6 +60,12 @@ struct TileInstance {{@location(3) mask_slice: i32,@location(4) mask_default: f32,@location(5) _pad: f32,+ // Adjacent tile atlas slices for seamless cross-tile bilinear / supersampled filtering:+ // >= 0: resident neighbor atlas slice+ // -1 : genuinely empty in-bounds sparse neighbor tile (samples as transparent vec4(0.0))+ // -2 : document border or off-frustum neighbor (clamps cleanly to center tile edge)+ @location(6) neighbors_cardinal: vec4<i32>, // (L, R, T, B)+ @location(7) neighbors_diag: vec4<i32>, // (TL, TR, BL, BR)}};struct VsOut {{@@ -69,6 +75,8 @@ struct VsOut {{@location(2) @interpolate(flat) atlas_slice: i32,@location(3) @interpolate(flat) mask_slice: i32,@location(4) @interpolate(flat) mask_default: f32,+ @location(5) @interpolate(flat) neighbors_cardinal: vec4<i32>,+ @location(6) @interpolate(flat) neighbors_diag: vec4<i32>,}};@vertex@@ -104,6 +112,8 @@ fn vs_main(@builtin(vertex_index) vid: u32, inst: TileInstance) -> VsOut {{out.atlas_slice = inst.atlas_slice;out.mask_slice = inst.mask_slice;out.mask_default = inst.mask_default;+ out.neighbors_cardinal = inst.neighbors_cardinal;+ out.neighbors_diag = inst.neighbors_diag;return out;}}@@ -111,25 +121,83 @@ fn vs_main(@builtin(vertex_index) vid: u32, inst: TileInstance) -> VsOut {{{SCREENTONE_WGSL}-fn sample_tile_straight(uv: vec2<f32>, slice: i32, use_nearest: bool) -> vec4<f32> {{- if (slice < 0) {{+fn load_tile_texel_with_neighbors(+ lx: i32,+ ly: i32,+ slot_c: i32,+ card: vec4<i32>,+ diag: vec4<i32>,+) -> vec4<f32> {{+ var enc = slot_c;+ var px = lx;+ var py = ly;+ if (lx < 0) {{+ px = lx + 256;+ if (ly < 0) {{+ py = ly + 256;+ enc = diag.x; // TL+ }} else if (ly >= 256) {{+ py = ly - 256;+ enc = diag.z; // BL+ }} else {{+ enc = card.x; // L+ }}+ }} else if (lx >= 256) {{+ px = lx - 256;+ if (ly < 0) {{+ py = ly + 256;+ enc = diag.y; // TR+ }} else if (ly >= 256) {{+ py = ly - 256;+ enc = diag.w; // BR+ }} else {{+ enc = card.y; // R+ }}+ }} else if (ly < 0) {{+ py = ly + 256;+ enc = card.z; // T+ }} else if (ly >= 256) {{+ py = ly - 256;+ enc = card.w; // B+ }}++ if (enc == -1) {{return vec4<f32>(0.0);}}- if (use_nearest) {{- let coord = clamp(vec2<i32>(floor(uv * 256.0)), vec2<i32>(0), vec2<i32>(255));- return textureLoad(tile_atlas, coord, slice, 0);+ if (enc < -1) {{+ // Document border or off-frustum fallback: clamp cleanly to center tile edge+ return textureLoad(+ tile_atlas,+ clamp(vec2<i32>(lx, ly), vec2<i32>(0), vec2<i32>(255)),+ slot_c,+ 0,+ );}}- // Halo-free premultiplied 2x2 bilinear interpolation over straight-alpha Rgba16Float tiles+ return textureLoad(+ tile_atlas,+ clamp(vec2<i32>(px, py), vec2<i32>(0), vec2<i32>(255)),+ enc,+ 0,+ );+}}++fn sample_tile_bilinear_premul(+ uv: vec2<f32>,+ slot_c: i32,+ card: vec4<i32>,+ diag: vec4<i32>,+) -> vec4<f32> {{+ // Halo-free premultiplied 2x2 bilinear interpolation seamlessly crossing tile boundarieslet p = uv * 256.0 - vec2<f32>(0.5);let p_floor = floor(p);- let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));- let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));+ let i0 = vec2<i32>(p_floor);+ let i1 = i0 + vec2<i32>(1, 1);let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));- let c00 = textureLoad(tile_atlas, i0, slice, 0);- let c10 = textureLoad(tile_atlas, vec2<i32>(i1.x, i0.y), slice, 0);- let c01 = textureLoad(tile_atlas, vec2<i32>(i0.x, i1.y), slice, 0);- let c11 = textureLoad(tile_atlas, i1, slice, 0);+ let c00 = load_tile_texel_with_neighbors(i0.x, i0.y, slot_c, card, diag);+ let c10 = load_tile_texel_with_neighbors(i1.x, i0.y, slot_c, card, diag);+ let c01 = load_tile_texel_with_neighbors(i0.x, i1.y, slot_c, card, diag);+ let c11 = load_tile_texel_with_neighbors(i1.x, i1.y, slot_c, card, diag);let p00 = vec4<f32>(c00.rgb * c00.a, c00.a);let p10 = vec4<f32>(c10.rgb * c10.a, c10.a);@@ -138,7 +206,43 @@ fn sample_tile_straight(uv: vec2<f32>, slice: i32, use_nearest: bool) -> vec4<f3let top = mix(p00, p10, f.x);let bot = mix(p01, p11, f.x);- let premul = mix(top, bot, f.y);+ return mix(top, bot, f.y);+}}++fn sample_tile_straight(+ uv: vec2<f32>,+ d_uv_x: vec2<f32>,+ d_uv_y: vec2<f32>,+ slice: i32,+ card: vec4<i32>,+ diag: vec4<i32>,+ use_nearest: bool,+) -> vec4<f32> {{+ if (slice < 0) {{+ return vec4<f32>(0.0);+ }}+ if (use_nearest) {{+ let coord = clamp(vec2<i32>(floor(uv * 256.0)), vec2<i32>(0), vec2<i32>(255));+ return textureLoad(tile_atlas, coord, slice, 0);+ }}++ // When zoomed out between LOD levels (1.05..2+ tile texels per physical pixel),+ // 2x2 subpixel supersampling eliminates thin-line breaks, cuts, and shimmering.+ let texels_per_px = max(length(d_uv_x), length(d_uv_y)) * 256.0;+ var premul: vec4<f32>;+ if (texels_per_px > 1.05) {{+ let ox = d_uv_x * 0.25;+ let oy = d_uv_y * 0.25;+ premul = (+ sample_tile_bilinear_premul(uv - ox - oy, slice, card, diag) ++ sample_tile_bilinear_premul(uv + ox - oy, slice, card, diag) ++ sample_tile_bilinear_premul(uv - ox + oy, slice, card, diag) ++ sample_tile_bilinear_premul(uv + ox + oy, slice, card, diag)+ ) * 0.25;+ }} else {{+ premul = sample_tile_bilinear_premul(uv, slice, card, diag);+ }}+if (premul.a <= 0.0001) {{return vec4<f32>(0.0);}}@@ -158,8 +262,9 @@ fn sample_sparse_mask(uv: vec2<f32>, mask_slice: i32, mask_default: f32, use_nea}}let p = uv * 256.0 - vec2<f32>(0.5);let p_floor = floor(p);- let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));- let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));+ let p_i = vec2<i32>(p_floor);+ let i0 = clamp(p_i, vec2<i32>(0), vec2<i32>(255));+ let i1 = clamp(p_i + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));let m00 = textureLoad(mask_atlas, i0, mask_slice, 0).r;let m10 = textureLoad(mask_atlas, vec2<i32>(i1.x, i0.y), mask_slice, 0).r;@@ -193,6 +298,8 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{// Compute derivatives in strictly uniform control flow BEFORE any early discardlet d_doc_x = dpdx(in.doc_coord);let d_doc_y = dpdy(in.doc_coord);+ let d_uv_x = dpdx(in.tex_uv);+ let d_uv_y = dpdy(in.tex_uv);if (in.doc_coord.x < 0.0 ||@@ -204,7 +311,15 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{}}let use_nearest = u.tone_flags.w != 0u;- var final_color = sample_tile_straight(in.tex_uv, in.atlas_slice, use_nearest);+ var final_color = sample_tile_straight(+ in.tex_uv,+ d_uv_x,+ d_uv_y,+ in.atlas_slice,+ in.neighbors_cardinal,+ in.neighbors_diag,+ use_nearest,+ );if (final_color.a < 0.002) {{discard;}}diff --git a/crates/ink-engine/src/compositor/shaders/live_dab.rs b/crates/ink-engine/src/compositor/shaders/live_dab.rsindex 5f252a0..c7d3d79 100644--- a/crates/ink-engine/src/compositor/shaders/live_dab.rs+++ b/crates/ink-engine/src/compositor/shaders/live_dab.rs@@ -98,8 +98,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {} else {let p = in.uv * 256.0 - vec2<f32>(0.5);let p_floor = floor(p);- let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));- let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));+ let p_i = vec2<i32>(p_floor);+ let i0 = clamp(p_i, vec2<i32>(0), vec2<i32>(255));+ let i1 = clamp(p_i + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));let m00 = textureLoad(mask_atlas, i0, in.slot_i, 0).r;let m10 = textureLoad(mask_atlas, vec2<i32>(i1.x, i0.y), in.slot_i, 0).r;@@ -192,8 +193,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {if (u._pad > 0.5) {let p = in.uv * 256.0 - vec2<f32>(0.5);let p_floor = floor(p);- let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));- let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));+ let p_i = vec2<i32>(p_floor);+ let i0 = clamp(p_i, vec2<i32>(0), vec2<i32>(255));+ let i1 = clamp(p_i + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));let c00 = textureLoad(stroke_atlas, i0, in.slot_i, 0);diff --git a/crates/ink-engine/src/compositor_tests.rs b/crates/ink-engine/src/compositor_tests.rsindex ac69d73..f0be49d 100644--- a/crates/ink-engine/src/compositor_tests.rs+++ b/crates/ink-engine/src/compositor_tests.rs@@ -1373,6 +1373,8 @@ fn test_dx12_frame_arenas_mid_frame_flush_preserves_uniform_offsets() {mask_slice: -1,mask_default: 1.0,_pad: 0.0,+ neighbors_cardinal: [-2; 4],+ neighbors_diag: [-2; 4],};// Draw 1: fits cleanly in initial capacity (0 flushes)@@ -1796,3 +1798,112 @@ fn test_dx12_compositor_targets_lazy_allocation_and_export_cleanup() {"export_targets MUST be freed immediately after render_layer_thumbnail_gpu!");}++/// Regression Test: Thin black stroke crossing tile boundaries (`x=256`, `x=512`) must render+/// smoothly without cuts, dropouts, or left-edge sawtooth notches when zoomed out (LOD 0/1/2).+#[test]+fn test_dx12_zoomed_out_thin_line_across_tile_seam_has_no_cuts() {+ let _dx12_guard = crate::lock_dx12_test();+ let Some(mut renderer) = try_headless_renderer(512, 512) else {+ return;+ };++ let mut doc = make_empty_doc("doc-tile-seam-cut-regression", 1024, 1024);+ doc.layers.push(LayerNode {+ meta: LayerNodeMeta::new_raster("l1", "Lineart"),+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),+ });++ // Draw a 4px-thick black horizontal band across x = 200..800 at y = 510..514,+ // crossing both x=256 (LOD-0 seam) and x=512 (LOD-0 + LOD-1 seam) cleanly!+ fill_layer_rect(+ &mut doc,+ "l1",+ RectI32::new(200, 510, 600, 4),+ [0, 0, 0, 255],+ );+ // Also draw a 4px-thick black diagonal crossing x=512 around y=256 (seam intersection!)+ for step in 0..200 {+ let x = 412 + step;+ let y = 156 + step;+ fill_layer_rect(+ &mut doc,+ "l1",+ RectI32::new(x, y, 4, 4),+ [0, 0, 0, 255],+ );+ }++ let _ = renderer.sync_document(&mut doc, None);+ let vp = ViewportRect {+ x_px: 0,+ y_px: 0,+ width_px: 512,+ height_px: 512,+ dpr: 1.0,+ };++ // Test at zoom = 0.5 (LOD 1), zoom = 0.42 (LOD 1 + non-power-of-two supersampling),+ // and zoom = 0.6 (LOD 0 + non-power-of-two supersampling) with fractional pan offsets+ // that place the tile seam right on subpixel edges.+ for &(zoom, pan_x, pan_y) in &[+ (0.5f32, 256.25f32, 256.25f32),+ (0.42f32, 256.3f32, 256.1f32),+ (0.6f32, 256.4f32, 256.2f32),+ ] {+ let cam = CameraState {+ pan_x,+ pan_y,+ zoom,+ ..CameraState::default()+ };+ let _ = renderer.render_document_frame(+ &doc,+ None,+ &CompositorDisplayConfig::default(),+ &vp,+ &cam,+ &[],+ false,+ false,+ &CursorConfig::default(),+ None,+ true,+ );+ let (_, _, rgba) = renderer+ .readback_headless_rgba8()+ .expect("headless readback");++ // Project the horizontal stroke center (doc_y = 512) into screen Y and check continuity+ // across the x = 512 seam (which projects to screen_x = pan_x).+ let sy_center = (pan_y + (512.0 - 512.0) * zoom).round() as usize;+ let sx_seam = pan_x.round() as usize;+ let mut column_mins = Vec::new();+ for sx in (sx_seam - 20)..=(sx_seam + 20) {+ let mut min_luma = 255u8;+ for dy in -2i32..=2i32 {+ let sy = (sy_center as i32 + dy).clamp(0, 511) as usize;+ let idx = (sy * 512 + sx) * 4;+ min_luma = min_luma.min(rgba[idx]);+ }+ column_mins.push((sx, min_luma));+ }++ let avg_away: f32 = column_mins+ .iter()+ .filter(|(sx, _)| (*sx as i32 - sx_seam as i32).abs() >= 6)+ .map(|(_, v)| *v as f32)+ .sum::<f32>()+ / column_mins+ .iter()+ .filter(|(sx, _)| (*sx as i32 - sx_seam as i32).abs() >= 6)+ .count() as f32;++ for (sx, luma) in &column_mins {+ assert!(+ (*luma as f32 - avg_away).abs() <= 18.0,+ "Detected tile seam cut/notch at zoom={zoom}, sx={sx} (seam={sx_seam}): luma={luma}, avg_away={avg_away:.1}"+ );+ }+ }+}diff --git a/crates/ink-engine/src/engine.rs b/crates/ink-engine/src/engine.rsindex 6eebc82..a2dc744 100644--- a/crates/ink-engine/src/engine.rs+++ b/crates/ink-engine/src/engine.rs@@ -710,6 +710,7 @@ struct EngineThreadState {policy: InteractionPolicy,navigator: NativeCameraNavigator,+ stylus_nav_backend: u8,// Phase 4 full native stroke & GPU brush statestroke_pipeline: NativeStrokePipeline,@@ -832,6 +833,7 @@ impl EngineThreadState {perspective_ruler: None,policy: InteractionPolicy::default(),navigator: NativeCameraNavigator::default(),+ stylus_nav_backend: 0,stroke_pipeline: NativeStrokePipeline::new(),active_gpu_stroke: None,frame_dirty_doc_bounds: None,@@ -1529,16 +1531,21 @@ impl EngineThreadState {}}ActiveStrokeKind::NaturalPaint { simulator, .. } => {- if self.pending_np_pts.is_empty() {+ if self.pending_np_pts.is_empty() && !finish_ribbon {return;}self.pending_np_capsules.clear();- simulator.step_points(- &self.pending_np_pts,- &active.brush,- &mut self.pending_np_capsules,- );- self.pending_np_pts.clear();+ if !self.pending_np_pts.is_empty() {+ simulator.step_points(+ &self.pending_np_pts,+ &active.brush,+ &mut self.pending_np_capsules,+ );+ self.pending_np_pts.clear();+ }+ if finish_ribbon {+ simulator.flush_pending_tap(&active.brush, &mut self.pending_np_capsules);+ }if self.pending_np_capsules.is_empty() {return;}@@ -2491,6 +2498,23 @@ impl EngineThreadState {.render_brush_preview_rgba8(&brush, width, height);let _ = reply.send(res);}+ EngineCommand::RenderScratchpadPreview {+ brush,+ strokes,+ width,+ height,+ reply,+ } => {+ let res = self.renderer.render_scratchpad_preview_rgba8(+ &brush,+ &strokes,+ width,+ height,+ &self.global_pressure_curve,+ self.global_pressure_lut.as_ref(),+ );+ let _ = reply.send(res);+ }_ => {}}}@@ -2570,6 +2594,11 @@ impl EngineThreadState {}}EngineCommand::SetCamera(cam) => {+ // Never allow an in-flight async JS camera echo to snap `self.camera`+ // backward while the native 120-240 Hz navigator actively owns a gesture.+ if self.navigator.is_active() {+ continue;+ }let sanitized = CameraState {zoom: clamp_zoom(cam.zoom),..cam@@ -2605,7 +2634,8 @@ impl EngineThreadState {EngineCommand::SetMaskMode(enabled) => {self.mask_mode = enabled;}- cmd @ EngineCommand::RenderBrushPreview { .. } => {+ cmd @ EngineCommand::RenderBrushPreview { .. }+ | cmd @ EngineCommand::RenderScratchpadPreview { .. } => {if self.is_any_stroke_active() {self.deferred_readback_cmds.push_back(cmd);} else {@@ -2660,6 +2690,7 @@ impl EngineThreadState {self.finish_and_commit_gpu_stroke(clock::now_ms());}self.navigator.cancel();+ self.stylus_nav_backend = 0;self.cursor_local_phys = None;self.newest_input_timestamp_ms = 0.0;} else {@@ -2957,6 +2988,14 @@ impl EngineThreadState {}if sample.phase == 4 {+ if self.stylus_nav_backend != 0 && self.stylus_nav_backend == sample.backend {+ self.stylus_nav_backend = 0;+ if self.navigator.end() {+ self.pending_camera_emit = true;+ self.pending_camera_commit = true;+ self.dirty = true;+ }+ }if self.is_any_stroke_active()&& (self.active_stroke_backend == 0 || self.active_stroke_backend == sample.backend){@@ -3004,6 +3043,37 @@ impl EngineThreadState {self.latest_pointer_pressure = sample.pressure;self.pointer_stat_dirty = true;+ if self.stylus_nav_backend != 0 {+ if sample.backend != self.stylus_nav_backend {+ return;+ }+ match sample.phase {+ 2 => {+ let snap_15_deg = (sample.buttons & (0x0200 | 0x0800)) != 0;+ if self.navigator.update(+ local_css_x,+ local_css_y,+ snap_15_deg,+ self.policy.is_webtoon_mode,+ &mut self.camera,+ ) {+ self.dirty = true;+ self.pending_camera_emit = true;+ }+ }+ 3 | 0 => {+ self.stylus_nav_backend = 0;+ if self.navigator.end() {+ self.pending_camera_emit = true;+ self.pending_camera_commit = true;+ self.dirty = true;+ }+ }+ _ => {}+ }+ return;+ }+if self.navigator.is_active() {if self.is_any_stroke_active() {self.finish_and_commit_gpu_stroke(sample.timestamp_ms);@@ -3017,8 +3087,38 @@ impl EngineThreadState {match sample.phase {1 => {- // Never start a brush stroke while Space navigation or Ctrl/Shift+Alt brush resize is held- if space_held || ctrl_or_shift_with_alt {+ // Space + Stylus Drag -> native 120-240 Hz Pan / Shift+Rotate / Ctrl+ZoomDrag+ if space_held && !ctrl_or_shift_with_alt {+ if (sample.backend == 1 || sample.backend == 2)+ && self+ .hit_test+ .should_capture_native_nav(sample.phys_x, sample.phys_y)+ {+ if self.is_any_stroke_active() {+ self.finish_and_commit_gpu_stroke(sample.timestamp_ms);+ }+ let gesture = if (sample.buttons & 0x0800) != 0 {+ crate::types::NativeNavGesture::ZoomDrag+ } else if (sample.buttons & 0x0100) != 0 {+ crate::types::NativeNavGesture::Rotate+ } else {+ crate::types::NativeNavGesture::Pan+ };+ self.navigator.begin(+ gesture,+ local_css_x,+ local_css_y,+ self.viewport.css_width(),+ self.viewport.css_height(),+ &self.camera,+ );+ self.stylus_nav_backend = sample.backend;+ self.dirty = true;+ }+ return;+ }+ // Never start a brush stroke while Ctrl/Shift+Alt brush resize is held+ if ctrl_or_shift_with_alt {return;}// Never let a stray mouse down interrupt an active stylus stroke@@ -3145,6 +3245,7 @@ impl EngineThreadState {self.finish_and_commit_gpu_stroke(timestamp_ms);}let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);+ self.stylus_nav_backend = 0;self.navigator.begin(gesture,lx,@@ -3180,6 +3281,7 @@ impl EngineThreadState {if timestamp_ms > self.newest_input_timestamp_ms {self.newest_input_timestamp_ms = timestamp_ms;}+ self.stylus_nav_backend = 0;if self.navigator.end() {self.pending_camera_emit = true;self.pending_camera_commit = true;@@ -3237,13 +3339,13 @@ impl EngineThreadState {continue;}// Always deliver move/up for an already-active mouse stroke so hover packets- // never drop drag/release; gate only fresh mouse-down against WinTab CXO_SYSTEM- // echo using the same 100ms window as `ll_mouse_proc` (Windows Ink synthesized- // mouse events carry MI_WP_SIGNATURE and are already filtered in `ll_mouse_proc`).+ // never drop drag/release; gate fresh mouse-down against recent stylus packets+ // (both WinTab CXO_SYSTEM echo and Windows Ink) using the same 150ms window as `ll_mouse_proc`.let is_active_mouse_continuation =(phase == 2 || phase == 3) && self.active_stroke_backend == 3;if !is_active_mouse_continuation- && timestamp_ms - self.last_wintab_sample_ms < 100.0+ && (timestamp_ms - self.last_wintab_sample_ms < 150.0+ || timestamp_ms - self.last_tablet_sample_ms < 150.0){continue;}diff --git a/crates/ink-engine/src/gpu.rs b/crates/ink-engine/src/gpu.rsindex a39e570..7139af0 100644--- a/crates/ink-engine/src/gpu.rs+++ b/crates/ink-engine/src/gpu.rs@@ -1547,6 +1547,332 @@ impl GpuRenderer {res}+ /// Re-renders user-drawn Brush Studio scratchpad strokes on DX12 with the live-edited+ /// [`NativeBrushConfig`] (full fidelity for Size, Pressure Curve, Stabilization, Taper,+ /// Dual Brush, Grain/Texture, Natural Paint Bristles, Color Mixing, Wet Edge, and Impasto).+ pub fn render_scratchpad_preview_rgba8(+ &mut self,+ brush: &NativeBrushConfig,+ strokes: &[crate::types::ScratchpadStrokeInput],+ width: u32,+ height: u32,+ global_pressure_curve: &crate::stroke::GlobalPressureCurve,+ global_pressure_lut: Option<&crate::stroke::CompiledCurveLut>,+ ) -> Result<(u32, u32, Vec<u8>), String> {+ let w = width.clamp(32, 1024);+ let h = height.clamp(32, 1024);++ if strokes.is_empty() {+ return Ok((w, h, vec![0u8; (w as usize) * (h as usize) * 4]));+ }++ if self.brush_engine.is_active() {+ return Err("Cannot render scratchpad preview during active stroke".to_string());+ }++ let mut doc = Document::new_blank(+ "__studio_scratchpad_doc__",+ "Brush Studio Scratchpad",+ CanvasDimensions {+ width: w,+ height: h,+ dpi: 72,+ },+ CanvasColorMode::Color,+ "transparent",+ 60.0,+ 1,+ );+ doc.layers+ .retain(|l| !Document::is_background_layer_id(&l.meta.id));+ if doc.layers.is_empty() {+ let _ = doc.add_layer(+ crate::document::LayerNodeMeta::new_raster("scratchpad-layer", "Scratchpad"),+ None,+ true,+ false,+ );+ }+ let doc_id = doc.id.clone();+ let layer_id = doc.layers[0].meta.id.clone();+ doc.active_layer_id = Some(layer_id.clone());++ let brush_pressure_lut = brush+ .pressure_curve+ .as_ref()+ .filter(|pts| pts.len() >= 2)+ .map(|pts| crate::stroke::CompiledCurveLut::compile(pts));++ // Reset ephemeral dirty brush state before replaying the scratchpad sequence+ self.clean_dirty_brush(Some("__studio_scratchpad__"));++ for (stroke_idx, stroke_in) in strokes.iter().enumerate() {+ if stroke_in.points.is_empty() {+ continue;+ }+ let mut preview_brush = brush.clone();+ preview_brush.size = preview_brush.size.clamp(0.5, 220.0);+ if preview_brush.is_effective_eraser() {+ preview_brush.is_eraser = false;+ preview_brush.is_transparent_ink = false;+ preview_brush.brush_combine_mode = crate::brush::CspBrushCombineMode::Normal;+ }+ preview_brush.fg_color = [+ stroke_in.color[0].clamp(0.0, 1.0),+ stroke_in.color[1].clamp(0.0, 1.0),+ stroke_in.color[2].clamp(0.0, 1.0),+ ];+ preview_brush.preset_key = Some("__studio_scratchpad__".to_string());++ let pipe_cfg = crate::stroke::StrokePipelineConfig {+ base_size: preview_brush.size,+ min_size_factor: preview_brush.min_size_factor,+ use_pressure: preview_brush.use_pressure,+ pressure_curve_gamma: preview_brush.pressure_curve_gamma,+ brush_pressure_lut: brush_pressure_lut.clone(),+ global_pressure_curve: global_pressure_curve.clone(),+ global_pressure_lut: global_pressure_lut.cloned(),+ stabilization: preview_brush.stabilization,+ sharp_corners: preview_brush.sharp_corners,+ post_correction: preview_brush.post_correction,+ smoothing: preview_brush.smoothing,+ enable_flick_taper: preview_brush.enable_flick_taper,+ zoom: 1.0,+ straight_ruler: None,+ perspective_ruler: None,+ };++ let mut pipeline = crate::stroke::NativeStrokePipeline::new();+ let first = stroke_in.points[0];+ let first_ts = if first.timestamp_ms.is_finite() && first.timestamp_ms > 0.0 {+ first.timestamp_ms+ } else {+ 0.0+ };+ let _ = pipeline.begin(+ first.x as f64,+ first.y as f64,+ first.pressure,+ first.tilt_x,+ first.tilt_y,+ first.twist,+ first_ts,+ false,+ None,+ pipe_cfg,+ );+ let mut last_ts = first_ts;+ for (pt_idx, pt) in stroke_in.points.iter().enumerate().skip(1) {+ let ts = if pt.timestamp_ms.is_finite() && pt.timestamp_ms > last_ts {+ pt.timestamp_ms+ } else {+ last_ts + 4.0 + (pt_idx as f64) * 0.001+ };+ last_ts = ts;+ let _ = pipeline.push_move(+ pt.x as f64,+ pt.y as f64,+ pt.pressure,+ pt.tilt_x,+ pt.tilt_y,+ pt.twist,+ ts,+ false,+ );+ }+ let end_step = pipeline.end(last_ts + 4.0);+ let pts = end_step+ .finalized_points+ .unwrap_or_else(|| pipeline.committed_points().to_vec());+ if pts.is_empty() {+ continue;+ }++ let total_len: f64 = pts+ .windows(2)+ .map(|win| (win[1].x - win[0].x).hypot(win[1].y - win[0].y))+ .sum();+ let exit_vel = pts.last().map(|p| p.velocity).unwrap_or(0.0);+ let seed = if stroke_in.seed != 0 {+ stroke_in.seed+ } else {+ 0x51A0_0001u64.wrapping_add((stroke_idx as u64).wrapping_mul(0x9E37_79B9))+ };++ if preview_brush.is_natural_paint_brush() {+ let mut sim = BristleRibbonSimulator::new(&preview_brush, seed as u32);+ let mut caps = Vec::with_capacity(512);+ sim.step_points(&pts, &preview_brush, &mut caps);+ sim.flush_pending_tap(&preview_brush, &mut caps);+ self.begin_natural_paint_stroke(&doc_id, &layer_id, w, h, preview_brush.clone());+ if let Some(layer) = doc.layer(&layer_id).cloned() {+ let _ = self.dispatch_natural_paint_capsules(&doc, &layer, &caps, None);+ }+ let batch = self.commit_natural_paint_to_layer()?;+ if let Some(layer) = doc.layer_mut(&layer_id) {+ let empty_snap = HashMap::new();+ let _ = layer.grid.apply_gpu_committed_tiles(+ &layer_id,+ batch.color_tiles,+ &empty_snap,+ 128,+ );+ if !batch.impasto_tiles.is_empty() {+ let _ = layer.grid.apply_gpu_committed_impasto_tiles(+ &layer_id,+ batch.impasto_tiles,+ &empty_snap,+ );+ layer.meta.impasto_light = preview_brush.impasto_layer_light();+ }+ }+ } else if preview_brush.is_ribbon_brush() {+ let (tw, th, sub_c) = self.resolve_ribbon_tip_dims(&preview_brush);+ let mut rb = RibbonMeshBuilder::new(tw, th, sub_c, seed);+ let mut verts = Vec::with_capacity(512);+ let segs = polyline_to_bezier_segments(&pts, 0.0);+ let mut sampled = Vec::with_capacity(pts.len() * 2);+ sampled.push(pts[0]);+ for seg in &segs {+ let chord = (seg.p3.x - seg.p0.x).hypot(seg.p3.y - seg.p0.y);+ let steps = ((chord / 3.5).ceil() as usize).clamp(2, 16);+ for s in 1..=steps {+ sampled.push(seg.sample_point(s as f64 / steps as f64));+ }+ }+ let _ = rb.push_points(&sampled, &preview_brush, &mut verts);+ let _ = rb.finish(&preview_brush, &mut verts);+ let mut sec_verts = Vec::new();+ if let Some(scfg) = preview_brush.build_secondary_brush_config() {+ if scfg.is_ribbon {+ let (stw, sth, ssub) = self.resolve_ribbon_tip_dims(&scfg);+ let mut srb =+ RibbonMeshBuilder::new(stw, sth, ssub, seed ^ 0xA5A5_5A5A_F0F0_0F0F);+ let _ = srb.push_points(&sampled, &scfg, &mut sec_verts);+ let _ = srb.finish(&scfg, &mut sec_verts);+ }+ }+ self.begin_gpu_stroke(w, h, false, preview_brush.clone(), [0.0, 0.0]);+ let is_once =+ preview_brush.ribbon_repeat_mode == crate::brush::RibbonRepeatMode::Once;+ let _ = self.stamp_gpu_ribbon_vertices(&verts, &sec_verts, is_once);+ if let Some(layer) = doc.layer_mut(&layer_id) {+ let batch = self.commit_gpu_stroke_to_layer(+ &doc_id,+ &layer_id,+ &layer.grid,+ None,+ false,+ false,+ )?;+ let empty_snap = HashMap::new();+ let _ = layer+ .grid+ .apply_gpu_committed_tiles(&layer_id, batch.tiles, &empty_snap, 128);+ }+ self.clear_live_stroke();+ } else if preview_brush.is_color_mixing_stamp_brush() {+ let metrics = self.resolve_brush_tip_metrics(&preview_brush);+ let mut emitter =+ StrokeDabEmitter::new(preview_brush.clone(), seed, metrics.0, metrics.1);+ let mut sec_emitter = preview_brush.build_secondary_brush_config().map(|sc| {+ let sm = self.resolve_brush_tip_metrics(&sc);+ StrokeDabEmitter::new(sc, seed ^ 0xA5A5_5A5A_F0F0_0F0F, sm.0, sm.1)+ });+ let mut dabs = Vec::with_capacity(256);+ let mut s_dabs = Vec::with_capacity(256);+ if pts.len() < 2 {+ emitter.emit_initial_point(&pts[0], Some(total_len), exit_vel, &mut dabs);+ if let Some(ref mut se) = sec_emitter {+ se.emit_initial_point(&pts[0], Some(total_len), exit_vel, &mut s_dabs);+ }+ } else {+ let segs = polyline_to_bezier_segments(&pts, 0.0);+ for seg in &segs {+ emitter.emit_segment(seg, Some(total_len), exit_vel, &mut dabs);+ if let Some(ref mut se) = sec_emitter {+ se.emit_segment(seg, Some(total_len), exit_vel, &mut s_dabs);+ }+ }+ }+ self.begin_natural_paint_stroke(&doc_id, &layer_id, w, h, preview_brush.clone());+ self.set_natural_paint_stroke_rand_offset(emitter.stroke_grain_offset);+ if let Some(layer) = doc.layer(&layer_id).cloned() {+ let _ = self.dispatch_color_mixing_dabs_with_secondary(+ &doc, &layer, &dabs, &s_dabs, None,+ );+ }+ let batch = self.commit_natural_paint_to_layer()?;+ if let Some(layer) = doc.layer_mut(&layer_id) {+ let empty_snap = HashMap::new();+ let _ = layer.grid.apply_gpu_committed_tiles(+ &layer_id,+ batch.color_tiles,+ &empty_snap,+ 128,+ );+ }+ } else {+ let metrics = self.resolve_brush_tip_metrics(&preview_brush);+ let mut emitter =+ StrokeDabEmitter::new(preview_brush.clone(), seed, metrics.0, metrics.1);+ let mut sec_emitter = preview_brush.build_secondary_brush_config().map(|sc| {+ let sm = self.resolve_brush_tip_metrics(&sc);+ StrokeDabEmitter::new(sc, seed ^ 0xA5A5_5A5A_F0F0_0F0F, sm.0, sm.1)+ });+ let mut p_dabs = Vec::with_capacity(256);+ let mut s_dabs = Vec::with_capacity(256);+ if pts.len() < 2 {+ emitter.emit_initial_point(&pts[0], Some(total_len), exit_vel, &mut p_dabs);+ if let Some(ref mut se) = sec_emitter {+ se.emit_initial_point(&pts[0], Some(total_len), exit_vel, &mut s_dabs);+ }+ } else {+ let segs = polyline_to_bezier_segments(&pts, 0.0);+ for seg in &segs {+ emitter.emit_segment(seg, Some(total_len), exit_vel, &mut p_dabs);+ if let Some(ref mut se) = sec_emitter {+ se.emit_segment(seg, Some(total_len), exit_vel, &mut s_dabs);+ }+ }+ }+ self.begin_gpu_stroke(+ w,+ h,+ false,+ preview_brush.clone(),+ emitter.stroke_grain_offset,+ );+ let _ = self.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);+ if let Some(layer) = doc.layer_mut(&layer_id) {+ let batch = self.commit_gpu_stroke_to_layer(+ &doc_id,+ &layer_id,+ &layer.grid,+ None,+ false,+ false,+ )?;+ let empty_snap = HashMap::new();+ let _ = layer+ .grid+ .apply_gpu_committed_tiles(&layer_id, batch.tiles, &empty_snap, 128);+ }+ self.clear_live_stroke();+ }+ }++ let opts = FlattenOptions {+ fill_white_background: false,+ show_checkerboard: false,+ ..Default::default()+ };+ let res = self.render_document_flattened(&doc, None, &opts);+ self.tile_pool.invalidate_document(&doc.id);+ self.clean_dirty_brush(Some("__studio_scratchpad__"));+ res+ }+/// Regenerates dirty LOD 1..3 compute mipmap tiles directly on GPU for `layer_id`/// in **ONE batched `CommandEncoder` + ONE `queue.submit`** and evicts any LOD 0 tiles/// that became completely transparent.diff --git a/crates/ink-engine/src/io/wal.rs b/crates/ink-engine/src/io/wal.rsindex 423f4fd..9d2d1bb 100644--- a/crates/ink-engine/src/io/wal.rs+++ b/crates/ink-engine/src/io/wal.rs@@ -679,8 +679,11 @@ fn apply_td_wal_frame(let g = grids.entry(raw_lid.to_string()).or_insert_with(|| SparseLayerGrid::new(fmt));- g.format = fmt;if let Some(d) = after_data {+ // Only a frame that carries pixels may define the layer's storage format. A+ // removal-only frame (eraser cleared a tile) encodes a placeholder format and+ // used to silently convert 1-bit/grayscale layers to 32-bit color on recovery.+ g.format = fmt;if d.len() == fmt.byte_size() {g.set_tile(coord,diff --git a/crates/ink-engine/src/lib.rs b/crates/ink-engine/src/lib.rsindex b276b51..52eb18e 100644--- a/crates/ink-engine/src/lib.rs+++ b/crates/ink-engine/src/lib.rs@@ -41,6 +41,8 @@ mod regression_dx12_tests;mod brush_parity_dx12_tests;#[cfg(test)]mod audit_regression_tests;+#[cfg(test)]+mod brush_feel_tests;pub use camera::{clamp_zoom, compute_smooth_rotation_delta, doc_to_viewport_css, viewport_css_to_doc,@@ -91,7 +93,8 @@ pub use tiles::{pub use types::{BrushParams, CameraState, CursorConfig, EngineCommand, EngineDiagnostics, EngineEvent,InteractionPolicy, NativeInputSample, NativeNavEvent, NativeNavGesture, NativeToolKind,- SurfaceTarget, ThumbnailUpdate, UiRect, ViewportRect, WheelNavMode,+ ScratchpadStrokeInput, ScratchpadStrokePoint, SurfaceTarget, ThumbnailUpdate, UiRect,+ ViewportRect, WheelNavMode,};/// Serializes DX12 GPU test device allocations across all test modules so default paralleldiff --git a/crates/ink-engine/src/natural_paint/bristle_ribbon.rs b/crates/ink-engine/src/natural_paint/bristle_ribbon.rsindex 098da7f..ef58050 100644--- a/crates/ink-engine/src/natural_paint/bristle_ribbon.rs+++ b/crates/ink-engine/src/natural_paint/bristle_ribbon.rs@@ -1,15 +1,20 @@//! Multi-Bristle Continuous Ribbon & Hybrid Trajectory Physics (`bristle_ribbon.rs`).//!-//! Native Rust port of `src/engine/BristleRibbonEngine.ts`:+//! Faithful high-precision Rust port of InkStudio's `BristleRibbonEngine.ts` ++//! `SpatialBristleReservoir` bristle geometry & dynamics://! - All 7 physical ferrule profiles (`round`, `flat`, `filbert`, `fan`, `rake`, `knife`, `custom`)-//! - 4..64 independent bristle strands with clumping, stiffness spring lag, length, irregularity,-//! pressure/tilt splay (`bristleSplaySensor`), staggered start delay, and pressure lift-off+//! - Macro clump ribs & carved canyons (`4..64` independent bristle strands with alternating+//! bold primary oil ribs, delicate secondary hairs, organic hair meander, width/ridge breathing,+//! flexibility lag, staggered touchdown entry ramp, pressure lift-off, and outer-flank feathering)+//! - Zero detached start stub: anchors frame on pointer-down, aligns cleanly along true initial+//! stroke direction on first motion (with `flush_pending_tap` for single click-taps)//! - Parallel-transported local frame `(tangent, normal)` with reversal-safe axis damping-//! (no pinwheel artifacts on 180° hairpin reversals!) + curvature inner-clamp-//! - Cohesive 5-band under-bed capsules so broad oil/acrylic strokes look solid and painterly-//! while fine outer bristles break up organically on dry-brush/low-pressure passes+//! (zero pinwheel artifacts on 180° hairpin zig-zags!) + signed-curvature inner-turn clamp+//! - Cohesive 5-band flat-ribbon under-bed (skipped for `rake`, `fan`, `knife`) with delayed+//! staggered entry & pressure lift-off so thick oil has solid body while starts & light edges+//! reveal crisp individual bristles and woven linen tooth//! - Hybrid mode (`BrushRenderMode::BristleHybrid`) emitting both continuous strands and-//! tip-modulated stamp capsules for textured bristle brushes.+//! tip-modulated stamp capsules for textured bristle / pastel / casein brushes.use crate::brush::{evaluate_csp_sensor, BristleProfilePreset, BristleSettings, BrushRenderMode,@@ -19,20 +24,28 @@ use crate::natural_paint::pigment::{MAX_BRISTLES, UNDERBED_BANDS, UNDERBED_SLOT_use crate::stroke::StrokePoint;use bytemuck::{Pod, Zeroable};-/// GPU-ready bristle capsule segment (`64` bytes, 16-byte aligned) passed directly into-/// `BRISTLE_PICKUP_UPDATE_WGSL` and `NATURAL_PAINT_RASTER_WGSL`.+/// GPU-ready bristle capsule segment (`80` bytes, 16-byte aligned) passed directly into+/// `cs_update_bristle_load` and `cs_raster_natural_paint`.#[repr(C)]#[derive(Debug, Clone, Copy, Pod, Zeroable)]pub struct GpuBristleCapsule {/// `[x0, y0, x1, y1]` — segment start/end in document pixel space.pub p0_p1: [f32; 4],- /// `[r0, r1, pressure, opacity]`+ /// `[r0, r1, pressure, alpha1]` — strand radius at start/end, pressure, end contact/flank/entry alpha envelope.pub geom: [f32; 4],- /// `[bristle_idx_f, edge_weight, groove_scale, flags_f]`- /// flags bit 0 (1.0): is_underbed, bit 1 (2.0): is_hybrid_stamp, bit 2 (4.0): is_knife+ /// `[bristle_idx_f, across_v, flank_drop, flags_f]`+ /// - `bristle_idx_f`: `0..63` real bristles, `64..68` 5-band under-bed+ /// - `across_v`: normalized ferrule offset `[-1..+1]` (for StrokeFlow grain & edge ridges)+ /// - `flank_drop`: outer-flank dry-brush tooth load factor (`0.32..1.0`)+ /// - `flags_f`: bit 0 (1.0): is_underbed, bit 1 (2.0): is_hybrid_stamp, bit 2 (4.0): is_knifepub strand: [f32; 4],- /// `[stroke_dist, ds_step, tilt_mag, tangent_angle]`+ /// `[arc_u0, arc_u1, tilt_mag, tangent_angle]` — continuous stroke arc-length at start/end, tilt, tangent angle.pub motion: [f32; 4],+ /// `[alpha0, h0_scale, h1_scale, length_factor]`+ /// - `alpha0`: start contact/flank/entry alpha envelope (smoothly interpolated `alpha0..alpha1`)+ /// - `h0_scale`, `h1_scale`: sculptural height multiplier at start/end (`groove_weight * contact_env * ridge_breath`, or `0.36` for under-bed)+ /// - `length_factor`: per-bristle relative length (`0.32..1.0`, shorter outer bristles deplete paint earlier!)+ pub phys: [f32; 4],}impl GpuBristleCapsule {@@ -48,64 +61,102 @@ impl GpuBristleCapsule {}}-/// Deterministic fast hash in `[0..1)` for repeatable bristle layout.+/// Deterministic fast PRNG matching `deterministicBristleRand` in `colorMixingEngine.ts`.+struct BristleRand {+ state: u32,+}++impl BristleRand {+ fn new(seed: u32) -> Self {+ Self { state: seed | 1 }+ }++ #[inline]+ fn next_f32(&mut self) -> f32 {+ self.state = self.state.wrapping_mul(1664525).wrapping_add(1013904223);+ let mut x = self.state;+ x ^= x >> 16;+ x = x.wrapping_mul(0x45D9_F3B);+ x ^= x >> 16;+ (x as f32) / 4_294_967_296.0+ }+}+#[inline]-fn hash_u32_f32(seed: u32) -> f32 {- let mut x = seed.wrapping_mul(0x27D4_EB2D);- x ^= x >> 15;- x = x.wrapping_mul(0x85EB_CA6B);- x ^= x >> 13;- (x as f32) / 4_294_967_296.0+fn wrap_pi(mut a: f32) -> f32 {+ let tau = std::f32::consts::TAU;+ let pi = std::f32::consts::PI;+ while a > pi {+ a -= tau;+ }+ while a < -pi {+ a += tau;+ }+ a}#[derive(Debug, Clone)]struct BristleStrand {index: usize,- /// Normalized lateral position across ferrule `[-1..+1]`.- lateral_u: f32,- /// Normalized longitudinal offset along ferrule `[-1..+1]` (round/filbert depth).- longitudinal_v: f32,- /// Clump cluster target lateral position `[-1..+1]`.- clump_center_u: f32,- /// Relative radius multiplier.- width_factor: f32,- /// Relative length factor (longer bristles drag slightly behind and touch down earlier).+ /// Normalized lateral position across ferrule `[-1..+1]` (already pulled toward macro clump center).+ offset: f32,+ /// Relative strand radius share (pre-multiplied by profile separation & organic tuft size variety).+ rel_radius: f32,+ /// Relative length factor `[0.32..1.0]` — shorter/outer strands exhaust paint earlier & lift off first.length_factor: f32,- /// Outer edge ridge mounding weight (`0..=1`, highest near `|u| -> 1`).- edge_weight: f32,- /// Minimum pressure required to stay in contact (outer short bristles lift off first!).- lift_off_pressure: f32,- /// Staggered touchdown distance in pixels (scaled by brush radius).- start_delay_factor: f32,- /// Individual spring stiffness multiplier.- stiffness_factor: f32,- /// Groove crown height weight (`0.5..=1.25`).- groove_scale: f32,+ /// Multi-scale sculptural relief height weight `[0.20..1.85]` (macro clump crest + inner tuft + edge ridge).+ groove_weight: f32,+ /// Staggered touchdown delay `[0..1]` for ragged natural brush starts.+ start_delay: f32,+ /// Organic along-stroke meander phase `[0..2π)`.+ wander_phase: f32,+ /// Organic along-stroke meander spatial frequency `[0.012..0.034]`.+ wander_freq: f32,// Dynamic world-space tip state- cur_x: f32,- cur_y: f32,+ lag_x: f32,+ lag_y: f32,prev_x: f32,prev_y: f32,prev_radius: f32,- initialized: bool,+ prev_alpha: f32,+ prev_h_scale: f32,+ prev_arc_u: f32,}#[derive(Debug, Clone)]struct UnderbedBand {- lateral_u: f32,+ /// Normalized band index `[-1..+1]` across the 5 bands.+ u_band: f32,+ /// Normalized ferrule lateral span (`u_band * 0.70`).+ raw_band_off: f32,bristle_idx: usize,prev_x: f32,prev_y: f32,prev_radius: f32,+ prev_alpha: f32,+ prev_h_scale: f32,+ prev_arc_u: f32,initialized: bool,}+#[derive(Debug, Clone, Copy)]+struct PendingTap {+ x: f32,+ y: f32,+ pressure: f32,+ width: f32,+ tilt_mag: f32,+ eff_opacity: f32,+ twist_deg: f32,+}+/// Stateful multi-bristle trajectory physics simulator per active stroke.pub struct BristleRibbonSimulator {profile: BristleProfilePreset,render_mode: BrushRenderMode,settings: BristleSettings,+ dry_brush: f32,strands: Vec<BristleStrand>,underbed: Vec<UnderbedBand>,@@ -116,9 +167,17 @@ pub struct BristleRibbonSimulator {// Parallel-transported stroke framehas_frame: bool,+ has_direction: bool,+ emitted_motion: bool,+ pending_tap: Option<PendingTap>,last_x: f32,last_y: f32,last_pressure: f32,+ last_width: f32,+ last_tilt_x: f32,+ last_tilt_y: f32,+ last_twist: f32,+ prev_angle: f32,tangent_x: f32,tangent_y: f32,normal_x: f32,@@ -130,167 +189,181 @@ pub struct BristleRibbonSimulator {}impl BristleRibbonSimulator {- /// Initializes a deterministic bristle bundle matching `config.bristle` and `config.render_mode`.+ /// Initializes a deterministic bristle bundle matching `SpatialBristleReservoir::reset`+ /// in `colorMixingEngine.ts` with macro clump ribs, organic tuft widths, and relief contrast.pub fn new(config: &NativeBrushConfig, stroke_seed: u32) -> Self {let bs = config.bristle.unwrap_or_default();let count = (bs.count as usize).clamp(4, MAX_BRISTLES);let clumping = bs.clumping.clamp(0.0, 1.0);let irregularity = bs.irregularity.clamp(0.0, 1.0);let edge_ridge = bs.edge_ridge.clamp(0.0, 1.0);+ let dry_brush = config+ .natural_paint+ .map(|n| n.dry_brush.clamp(0.0, 1.0))+ .unwrap_or(0.0);++ let seed = stroke_seed+ .wrapping_add((count as u32).wrapping_mul(73))+ .wrapping_add(((clumping * 1000.0).round() as u32).wrapping_mul(19))+ .wrapping_add(((irregularity * 1000.0).round() as u32).wrapping_mul(31));+ let mut rand = BristleRand::new(seed);++ // Generate organic macro clump centers so bristles form bold primary oil ribs + fine secondary striations!+ let clump_count = if bs.profile == BristleProfilePreset::Rake {+ ((count as f32 * (0.48 - clumping * 0.24)).round() as usize).max(4)+ } else {+ ((6.0 + (1.0 - clumping) * 7.0).round() as usize).max(4)+ };+ let mut clump_centers = Vec::with_capacity(clump_count);+ let mut clump_heights = Vec::with_capacity(clump_count);+ for c in 0..clump_count {+ let u = if clump_count > 1 {+ ((c as f32 / (clump_count - 1) as f32) * 2.0 - 1.0) * 0.90+ } else {+ 0.0+ };+ let center = u + (rand.next_f32() - 0.5) * 0.14 * irregularity.max(0.25);+ clump_centers.push(center.clamp(-0.94, 0.94));+ // Alternating bold high paint ribs & deeper carved canyons between clumps+ clump_heights.push(0.62 + rand.next_f32() * 0.68);+ }- let clump_groups = ((count as f32 * (1.0 - clumping * 0.68)).round() as usize).clamp(2, count);let mut strands = Vec::with_capacity(count);+ let base_share = 2.0 / (count.max(4) as f32);+ let sep_factor = match bs.profile {+ BristleProfilePreset::Rake => 0.54,+ BristleProfilePreset::Fan => 0.56,+ BristleProfilePreset::Knife => 1.25,+ _ => 0.84 + clumping * 0.22,+ };for i in 0..count {- let t = if count > 1 {- (i as f32) / (count - 1) as f32+ let u = if count > 1 {+ (i as f32 / (count - 1) as f32) * 2.0 - 1.0} else {- 0.5+ 0.0};- let base_u = t * 2.0 - 1.0; // -1..+1- let r1 = hash_u32_f32(stroke_seed ^ (i as u32).wrapping_mul(1664525).wrapping_add(1013904223));- let r2 = hash_u32_f32(stroke_seed ^ (i as u32).wrapping_mul(22695477).wrapping_add(1));- let r3 = hash_u32_f32(stroke_seed ^ (i as u32).wrapping_mul(1103515245).wrapping_add(12345));- let r4 = hash_u32_f32(stroke_seed ^ (i as u32).wrapping_mul(636413622).wrapping_add(97));-- // Profile-shaped cross-section layout- let (mut lat_u, lon_v, mut width_f, mut len_f, lift_p) = match bs.profile {- BristleProfilePreset::Round => {- // Concentric Vogel-spiral round tuft- let ring = ((i as f32 + 0.5) / count as f32).sqrt();- let theta = (i as f32) * 2.399_963_2 + r1 * 0.35;- let u = ring * theta.cos();- let v = ring * theta.sin();- let wf = 0.85 + 0.35 * (1.0 - ring * 0.5);- let lf = 1.0 - ring * 0.25;- let lp = ring * 0.32;- (u, v, wf, lf, lp)- }- BristleProfilePreset::Flat => {- // Chisel-edge rectangular ferrule — uniform length, crisp outer corners- let u = base_u + (r1 - 0.5) * (0.14 * irregularity);- let v = (r2 - 0.5) * 0.24;- let wf = 1.05 + (r3 - 0.5) * 0.25 * irregularity;- let lf = 0.95 + (r4 - 0.5) * 0.12 * irregularity;- let lp = base_u.abs() * 0.18;- (u, v, wf, lf, lp)+ let abs_u = u.abs();++ // Pull toward nearest macro clump center+ let mut nearest = u;+ let mut nearest_idx = 0usize;+ let mut best_d = 99.0f32;+ for (c, &cc) in clump_centers.iter().enumerate() {+ let d = (u - cc).abs();+ if d < best_d {+ best_d = d;+ nearest = cc;+ nearest_idx = c;}+ }+ let clump_pull = match bs.profile {+ BristleProfilePreset::Rake => clumping * 0.54,+ BristleProfilePreset::Knife => 0.0,+ _ => clumping * 0.72,+ };+ let jitter_scale = if bs.profile == BristleProfilePreset::Rake {+ 0.52+ } else {+ 0.92+ };+ let mut offset = u + (nearest - u) * clump_pull;+ if bs.profile != BristleProfilePreset::Knife {+ offset += (rand.next_f32() - 0.5) * base_share * jitter_scale * irregularity;+ }+ offset = offset.clamp(-1.0, 1.0);++ // Profile-dependent strand length & density envelope+ let profile_envelope = match bs.profile {+ BristleProfilePreset::Round => (1.0 - abs_u * abs_u * 0.88).max(0.18).sqrt(),BristleProfilePreset::Filbert => {- // Oval dome tip — longest in center, tapered soft oval edges- let u = base_u + (r1 - 0.5) * (0.16 * irregularity);- let dome = (1.0 - (base_u * base_u).min(0.95)).sqrt();- let v = (r2 - 0.5) * 0.42 * dome;- let wf = 0.85 + 0.38 * dome;- let lf = 0.72 + 0.34 * dome;- let lp = (1.0 - dome) * 0.42;- (u, v, wf, lf, lp)- }- BristleProfilePreset::Fan => {- // Wide splayed arc of slender separated wisps- let u = base_u * 1.15 + (r1 - 0.5) * (0.20 * irregularity);- let arc = -0.35 * base_u * base_u;- let wf = 0.58 + 0.28 * r3;- let lf = 0.85 + 0.25 * (1.0 - base_u.abs());- let lp = 0.08 + base_u.abs() * 0.35;- (u, arc, wf, lf, lp)- }- BristleProfilePreset::Rake => {- // Deliberately spaced teeth (discrete comb grooves)- let teeth = (count / 3).clamp(4, 14);- let tooth_idx = i % teeth;- let tooth_u = (tooth_idx as f32 / (teeth - 1).max(1) as f32) * 2.0 - 1.0;- let u = tooth_u + (r1 - 0.5) * (0.04 + 0.05 * irregularity);- let v = (r2 - 0.5) * 0.15;- let wf = 0.62 + 0.18 * r3;- let lf = 0.95 + (r4 - 0.5) * 0.1;- let lp = 0.05 + r2 * 0.12;- (u, v, wf, lf, lp)+ (1.0 - abs_u.powf(2.6) * 0.72).max(0.25).powf(0.7)}- BristleProfilePreset::Knife => {- // Palette knife — crisp metallic straight blade with strong paint edge ridges- let u = base_u;- let v = 0.0;- let wf = 1.35;- let lf = 1.0;- let lp = 0.0;- (u, v, wf, lf, lp)- }- BristleProfilePreset::Custom => {- let u = base_u + (r1 - 0.5) * (0.28 * irregularity);- let v = (r2 - 0.5) * 0.55;- let wf = 0.8 + 0.4 * r3;- let lf = 0.8 + 0.3 * r4;- let lp = base_u.abs() * 0.28;- (u, v, wf, lf, lp)+ BristleProfilePreset::Fan => 0.62 + 0.38 * (1.0 - abs_u * 0.55),+ BristleProfilePreset::Rake => 0.78 + 0.22 * (1.0 - abs_u * 0.30),+ BristleProfilePreset::Knife => 1.0,+ BristleProfilePreset::Flat | BristleProfilePreset::Custom => {+ 1.0 - abs_u.powi(5) * 0.25}};- let group_id = (i * clump_groups) / count.max(1);- let clump_center_u = if clump_groups > 1 {- (group_id as f32 / (clump_groups - 1) as f32) * 2.0 - 1.0+ // Shorter/outer bristles exhaust paint earlier -> organic dry-brush fringes!+ let len_var = 1.0 - rand.next_f32() * irregularity * 0.52;+ let length_factor = (profile_envelope * len_var).clamp(0.32, 1.0);++ // Staggered longitudinal entry & organic hair meander (eliminates flat ruler-cut starts!)+ let edge_stagger = if bs.profile == BristleProfilePreset::Knife {+ 0.04+ } else {+ abs_u.powf(1.55) * 0.65+ };+ let start_delay = (edge_stagger + rand.next_f32() * (0.28 + irregularity * 0.48))+ .clamp(0.0, 1.0);+ let wander_phase = rand.next_f32() * std::f32::consts::TAU;+ let wander_freq = 0.012 + rand.next_f32() * 0.022;++ // Relative strand radius (varied organic tufts: bold macro paint ribs + delicate fine hairs!)+ let size_mix = if bs.profile == BristleProfilePreset::Knife {+ 1.0+ } else {+ 0.52 + rand.next_f32().powf(0.8) * 1.05 * irregularity.max(0.35)+ };+ let rel_radius = (base_share * sep_factor * size_mix).max(0.014);++ // Multi-scale sculptural relief: clump macro height + inner strand crown + edge paint ridge!+ let edge_boost = if abs_u > 0.70 {+ ((abs_u - 0.70) / 0.30).powf(1.25) * edge_ridge * 1.35} else {0.0};- // Pull strands toward their clump center proportionally to `clumping`- if bs.profile != BristleProfilePreset::Knife && bs.profile != BristleProfilePreset::Rake- {- lat_u = lat_u + (clump_center_u - lat_u) * (clumping * 0.55);- }- lat_u = lat_u.clamp(-1.18, 1.18);-- // Edge ridge weight peaks sharply near |u| ~ 0.85..1.0- let abs_u = lat_u.abs().min(1.0);- let edge_w = (abs_u * abs_u * abs_u) * edge_ridge;- width_f = (width_f * (1.0 + (r3 - 0.5) * 0.35 * irregularity)).clamp(0.35, 1.85);- len_f = (len_f * bs.length.clamp(0.25, 2.0)).clamp(0.25, 2.2);-- let groove_scale = match bs.profile {- BristleProfilePreset::Knife => 0.35 + edge_w * 1.45,- BristleProfilePreset::Rake => 1.28,- _ => (0.68 + 0.48 * r4 + edge_w * 0.55).clamp(0.4, 1.5),+ let clump_crest = clump_heights[nearest_idx] * (1.0 - (best_d * 2.4).min(0.65));+ let tuft_contrast = 0.32 + clump_crest * 0.55 + rand.next_f32().powf(0.75) * 0.42;+ let strand_peak = if bs.profile == BristleProfilePreset::Knife {+ 0.58 + edge_boost * 1.35+ } else {+ (0.38 + 0.62 * profile_envelope) * tuft_contrast + edge_boost};+ let groove_weight = strand_peak.clamp(0.20, 1.85);strands.push(BristleStrand {index: i,- lateral_u: lat_u,- longitudinal_v: lon_v,- clump_center_u,- width_factor: width_f,- length_factor: len_f,- edge_weight: edge_w,- lift_off_pressure: lift_p,- start_delay_factor: if bs.profile == BristleProfilePreset::Knife {- 0.0- } else {- abs_u * 0.14 * irregularity + r2 * 0.08 * irregularity- },- stiffness_factor: (0.82 + 0.36 * r1).clamp(0.5, 1.3),- groove_scale,- cur_x: 0.0,- cur_y: 0.0,+ offset,+ rel_radius,+ length_factor,+ groove_weight,+ start_delay,+ wander_phase,+ wander_freq,+ lag_x: 0.0,+ lag_y: 0.0,prev_x: 0.0,prev_y: 0.0,prev_radius: 1.0,- initialized: false,+ prev_alpha: 0.0,+ prev_h_scale: 0.0,+ prev_arc_u: 0.0,});}- // 5-band cohesive under-bed spans [-0.72, -0.36, 0.0, +0.36, +0.72] across ferrule- // with dedicated reservoir slots (`64..69`) so they NEVER collide with real bristles `0..64`!- // (skipped for Rake & Fan which should expose discrete bristle gaps!)+ // 5-band cohesive flat-ribbon under-bed (skipped for Rake, Fan, AND Knife!).+ // Knife's 16 overlapping flat blade strands already form a 100% solid blade with crisp ridges!let mut underbed = Vec::new();if !matches!(bs.profile,- BristleProfilePreset::Rake | BristleProfilePreset::Fan+ BristleProfilePreset::Rake | BristleProfilePreset::Fan | BristleProfilePreset::Knife) {for b in 0..UNDERBED_BANDS {- let u = (b as f32 / (UNDERBED_BANDS.saturating_sub(1).max(1) as f32)) * 1.44 - 0.72;+ let u_band = (b as f32 / (UNDERBED_BANDS.saturating_sub(1).max(1) as f32)) * 2.0 - 1.0;underbed.push(UnderbedBand {- lateral_u: u,+ u_band,+ raw_band_off: u_band * 0.70,bristle_idx: UNDERBED_SLOT_BASE + b,prev_x: 0.0,prev_y: 0.0,- prev_radius: 1.0,+ prev_radius: 1.2,+ prev_alpha: 0.0,+ prev_h_scale: 0.0,+ prev_arc_u: 0.0,initialized: false,});}@@ -311,15 +384,24 @@ impl BristleRibbonSimulator {profile: bs.profile,render_mode: config.render_mode,settings: bs,+ dry_brush,strands,underbed,size_luts,op_luts,splay_luts,has_frame: false,+ has_direction: false,+ emitted_motion: false,+ pending_tap: None,last_x: 0.0,last_y: 0.0,last_pressure: 0.5,+ last_width: config.size.max(2.0),+ last_tilt_x: 0.0,+ last_tilt_y: 0.0,+ last_twist: 0.0,+ prev_angle: config.custom_tip_angle.to_radians(),tangent_x: 1.0,tangent_y: 0.0,normal_x: 0.0,@@ -337,6 +419,137 @@ impl BristleRibbonSimulator {self.strands.len()}+ #[inline]+ fn compute_splay(&self, config: &NativeBrushConfig, pressure: f32, tilt_mag: f32, velocity: f32) -> f32 {+ let splay_strength = self.settings.splay.clamp(0.0, 1.0);+ let stiffness = self.settings.stiffness.clamp(0.0, 1.0);+ let flex = 1.0 - stiffness * 0.45;+ let splay_val = config+ .bristle_splay_sensor+ .as_ref()+ .map(|s| {+ evaluate_csp_sensor(+ s,+ Some(&self.splay_luts),+ pressure,+ tilt_mag,+ velocity,+ self.stroke_distance,+ 0.5,+ )+ })+ .unwrap_or(pressure);+ let p_splay = 1.0 + (splay_val - 0.5) * splay_strength * 0.65 * flex;+ let tilt_splay = if config.use_tilt {+ tilt_mag * config.tilt_scale.max(0.1) * (0.45 + splay_strength * 0.80)+ } else {+ 0.0+ };+ (p_splay + tilt_splay).clamp(0.45, 2.6)+ }++ /// Evaluates effective brush diameter matching `BristleRibbonEngine.ts`.+ #[inline]+ fn eval_width(&self, config: &NativeBrushConfig, pressure: f32, tilt_mag: f32, velocity: f32) -> f32 {+ let size_factor = if let Some(ref s) = config.size_sensor {+ evaluate_csp_sensor(+ s,+ Some(&self.size_luts),+ pressure,+ tilt_mag,+ velocity,+ self.stroke_distance,+ 0.5,+ )+ .clamp(config.min_size_factor.max(0.05), 4.0)+ } else if config.use_pressure {+ let min_f = config.min_size_factor.clamp(0.05, 1.0);+ min_f + (1.0 - min_f) * pressure+ } else {+ 1.0+ };+ let raw_w = config.size * size_factor;+ if raw_w.is_finite() {+ raw_w.clamp(1.5, 2048.0)+ } else {+ config.size.clamp(1.5, 2048.0)+ }+ }++ /// Emits a cohesive single-tap dab if the user clicked & released without dragging.+ pub fn flush_pending_tap(+ &mut self,+ config: &NativeBrushConfig,+ out_capsules: &mut Vec<GpuBristleCapsule>,+ ) {+ if self.emitted_motion {+ self.pending_tap = None;+ return;+ }+ let Some(tap) = self.pending_tap.take() else {+ return;+ };+ let is_knife = self.profile == BristleProfilePreset::Knife;+ let splay = self.compute_splay(config, tap.pressure, tap.tilt_mag, 0.0);+ let half_w = tap.width * 0.5 * splay;+ let twist_rad = tap.twist_deg.to_radians();+ let cos_tw = twist_rad.cos();+ let sin_tw = twist_rad.sin();+ let r_nx = self.normal_x * cos_tw - self.normal_y * sin_tw;+ let r_ny = self.normal_x * sin_tw + self.normal_y * cos_tw;+ let tangent_angle = self.tangent_y.atan2(self.tangent_x);+ let flags = if is_knife { 4.0 } else { 0.0 };++ for st in &self.strands {+ let abs_off = st.offset.abs();+ let long_off = (st.start_delay - 0.35) * tap.width * if is_knife { 0.04 } else { 0.25 };+ let bx = tap.x + r_nx * (st.offset * half_w) + self.tangent_x * long_off;+ let by = tap.y + r_ny * (st.offset * half_w) + self.tangent_y * long_off;+ let strand_rad = (st.rel_radius * half_w * 1.45).max(0.85);+ let entry_fade = if is_knife { 1.0 } else { (1.0 - st.start_delay * 0.65).max(0.15) };+ let flank_fade = if is_knife {+ 1.0+ } else {+ 1.0 - ((abs_off - 0.55).max(0.0) / 0.45).powf(1.5) * 0.55+ };+ let init_alpha = tap.eff_opacity * entry_fade * flank_fade * 0.70;+ if init_alpha <= 0.01 {+ continue;+ }+ let dab_half = (strand_rad * 0.55).max(0.5);+ let sx0 = bx - self.tangent_x * dab_half;+ let sy0 = by - self.tangent_y * dab_half;+ let sx1 = bx + self.tangent_x * dab_half;+ let sy1 = by + self.tangent_y * dab_half;+ let r_eff = strand_rad * (0.7 + 0.3 * entry_fade) * 0.85;+ let h_scale = st.groove_weight * entry_fade * 0.65;++ out_capsules.push(GpuBristleCapsule {+ p0_p1: [sx0, sy0, sx1, sy1],+ geom: [r_eff, r_eff, tap.pressure, init_alpha],+ strand: [st.index as f32, st.offset, flank_fade, flags],+ motion: [0.0, dab_half * 2.0, tap.tilt_mag, tangent_angle],+ phys: [init_alpha, h_scale, h_scale, st.length_factor],+ });+ }++ if self.render_mode == BrushRenderMode::BristleHybrid {+ let mid_idx = (self.strands.len() / 2) as f32;+ out_capsules.push(GpuBristleCapsule {+ p0_p1: [+ tap.x,+ tap.y,+ tap.x + self.tangent_x * 0.5,+ tap.y + self.tangent_y * 0.5,+ ],+ geom: [half_w, half_w, tap.pressure, tap.eff_opacity * 0.65],+ strand: [mid_idx, 0.0, 1.0, 2.0],+ motion: [0.0, 0.5, tap.tilt_mag, tangent_angle],+ phys: [tap.eff_opacity * 0.65, 0.45, 0.45, 1.0],+ });+ }+ }+/// Steps the multi-bristle physical simulation across a slice of stabilized stroke points/// and emits continuous GPU capsules (`GpuBristleCapsule`) ready for compute pickup + raster.pub fn step_points(@@ -367,70 +580,34 @@ impl BristleRibbonSimulator {0.5};let pressure = if config.use_pressure {- raw_pressure.clamp(0.02, 1.0)+ raw_pressure.clamp(0.05, 1.0)} else {1.0};- let raw_tilt = (pt.tilt_x * pt.tilt_x + pt.tilt_y * pt.tilt_y).sqrt() / 90.0;- let tilt_mag = if raw_tilt.is_finite() {- raw_tilt.clamp(0.0, 1.0)+ let tilt_x = if config.use_tilt && pt.tilt_x.is_finite() {+ pt.tilt_x} else {0.0};- let raw_vel = pt.velocity as f32;- let velocity = if raw_vel.is_finite() {- raw_vel.clamp(0.0, 10.0)+ let tilt_y = if config.use_tilt && pt.tilt_y.is_finite() {+ pt.tilt_y} else {0.0};-- // Evaluate effective brush radius using CSP size sensor + min_size_factor- let size_factor = if let Some(ref s) = config.size_sensor {- evaluate_csp_sensor(- s,- Some(&self.size_luts),- pressure,- tilt_mag,- velocity,- self.stroke_distance,- 0.5,- )- .clamp(config.min_size_factor.max(0.05), 4.0)- } else if config.use_pressure {- let min_f = config.min_size_factor.clamp(0.05, 1.0);- min_f + (1.0 - min_f) * pressure+ let tilt_deg = (tilt_x * tilt_x + tilt_y * tilt_y).sqrt().min(90.0);+ let tilt_mag = if tilt_deg > 0.0 {+ tilt_deg.to_radians().sin()} else {- 1.0+ 0.0};-- // Evaluate dynamic splay expansion from pressure, tilt, and optional bristleSplaySensor- let splay_sensor_val = config- .bristle_splay_sensor- .as_ref()- .map(|s| {- evaluate_csp_sensor(- s,- Some(&self.splay_luts),- pressure,- tilt_mag,- velocity,- self.stroke_distance,- 0.5,- )- })- .unwrap_or(pressure);- let splay_expand =- 1.0 + self.settings.splay * (0.45 * splay_sensor_val + 0.35 * tilt_mag);-- let raw_radius = config.size * 0.5 * size_factor * splay_expand;- let brush_radius = if raw_radius.is_finite() {- raw_radius.clamp(0.75, 1024.0)+ let twist_deg = if pt.twist.is_finite() { pt.twist } else { 0.0 };+ let velocity = if pt.velocity.is_finite() {+ (pt.velocity as f32).clamp(0.0, 10.0)} else {- 1.0+ 0.0};- let thickness_ratio = config.thickness.clamp(0.15, 1.0);- // Opacity / density modulation+ let width = self.eval_width(config, pressure, tilt_mag, velocity);let op_factor = if let Some(ref s) = config.opacity_sensor {evaluate_csp_sensor(s,@@ -448,220 +625,418 @@ impl BristleRibbonSimulator {if !self.has_frame {self.has_frame = true;+ self.has_direction = false;+ self.emitted_motion = false;self.last_x = px;self.last_y = py;self.last_pressure = pressure;+ self.last_width = width;+ self.last_tilt_x = tilt_x;+ self.last_tilt_y = tilt_y;+ self.last_twist = twist_deg;let a = self.fixed_angle_rad;+ self.prev_angle = a;self.tangent_x = a.cos();self.tangent_y = a.sin();self.normal_x = -self.tangent_y;self.normal_y = self.tangent_x;- self.init_positions(px, py, brush_radius, thickness_ratio);- // Emit initial touchdown dabs so single-tap dots paint cleanly!- self.emit_touchdown(- px,- py,- brush_radius,+ self.pending_tap = Some(PendingTap {+ x: px,+ y: py,pressure,- eff_opacity,+ width,tilt_mag,- out_capsules,- );+ eff_opacity,+ twist_deg,+ });return;}let dx = px - self.last_x;let dy = py - self.last_y;let dist = (dx * dx + dy * dy).sqrt();- if dist < 0.35 {+ if dist < 0.25 {return;}- // Subdivide large jumps into smooth physical substeps without double-subdividing- // already-sampled Bezier segments (keeps capsule counts ~150-400/frame instead of 3,000!).- let max_step = (brush_radius * 0.28).clamp(3.5, 16.0);- let steps = ((dist / max_step).ceil() as usize).clamp(1, 16);+ self.emitted_motion = true;+ self.pending_tap = None;++ let is_knife = self.profile == BristleProfilePreset::Knife;+ let is_rake = self.profile == BristleProfilePreset::Rake;+ let is_fan = self.profile == BristleProfilePreset::Fan;+ let avg_w = ((self.last_width + width) * 0.5).max(2.0);+ let init_entry_zone = if is_knife {+ avg_w * 0.2+ } else {+ (avg_w * 0.95).max(18.0)+ };++ // Match pre-Rust adaptive substepping: denser in the staggered entry zone so bristles fade in smoothly!+ let width_step = (avg_w * (config.spacing * 2.8).max(0.14)).clamp(4.0, 26.0);+ let mut target_step = if self.stroke_distance < init_entry_zone * 1.4 {+ width_step.min((init_entry_zone * 0.18).max(3.5))+ } else {+ width_step+ };+ let p_delta = (pressure - self.last_pressure).abs();+ if p_delta > 0.14 {+ target_step = target_step.min((dist / (p_delta * 10.0).ceil()).max(3.5));+ }+ let steps = ((dist / target_step).ceil() as usize).clamp(1, 24);+let prev_x = self.last_x;let prev_y = self.last_y;let prev_p = self.last_pressure;+ let prev_w = self.last_width;+ let prev_tx_tilt = self.last_tilt_x;+ let prev_ty_tilt = self.last_tilt_y;+ let prev_tw = self.last_twist;++ let stiffness = self.settings.stiffness.clamp(0.05, 1.0);+ let base_follow = 0.42 + stiffness * 0.58;+ let follow_rate_k = if base_follow >= 0.995 {+ 10.0+ } else {+ -(1.0 - base_follow).ln() * 0.42+ };+ let tuft_width_boost = if is_rake {+ 1.38+ } else if is_fan {+ 1.24+ } else if is_knife {+ 1.18+ } else {+ 1.82+ };+ let irreg = self.settings.irregularity.clamp(0.0, 1.0);+ let strand_flags = if is_knife { 4.0 } else { 0.0 };for s in 1..=steps {let frac = s as f32 / steps as f32;- let sx = prev_x + dx * frac;- let sy = prev_y + dy * frac;- let sp = prev_p + (pressure - prev_p) * frac;+ let cx = prev_x + dx * frac;+ let cy = prev_y + dy * frac;+ let sp = (prev_p + (pressure - prev_p) * frac).clamp(0.05, 1.0);+ let sw = (prev_w + (width - prev_w) * frac).max(1.5);+ let stx_tilt = prev_tx_tilt + (tilt_x - prev_tx_tilt) * frac;+ let sty_tilt = prev_ty_tilt + (tilt_y - prev_ty_tilt) * frac;+ let st_deg = (stx_tilt * stx_tilt + sty_tilt * sty_tilt).sqrt().min(90.0);+ let st_mag = if st_deg > 0.0 {+ st_deg.to_radians().sin()+ } else {+ 0.0+ };+ let stw_deg = prev_tw + (twist_deg - prev_tw) * frac;+let step_dx = dx / steps as f32;let step_dy = dy / steps as f32;let step_len = dist / steps as f32;+ if step_len < 0.12 {+ continue;+ }+ let slice_prev_arc = self.stroke_distance;self.stroke_distance += step_len;+ let slice_follow = if base_follow >= 0.995 {+ 1.0+ } else {+ 1.0 - (-follow_rate_k * step_len).exp()+ };++ let inst_tx = step_dx / step_len;+ let inst_ty = step_dy / step_len;+ let inst_angle = inst_ty.atan2(inst_tx);+ let entry_zone = if is_knife {+ sw * 0.2+ } else {+ (sw * 0.95).max(18.0)+ };- // Parallel-transported tangent update with reversal-safe axis damping- if self.follow_direction && step_len > 1e-4 {- let dir_x = step_dx / step_len;- let dir_y = step_dy / step_len;- let dot = self.tangent_x * dir_x + self.tangent_y * dir_y;- // If user sharply reverses direction (dot < -0.35), keep the ferrule axis aligned- // smoothly rather than spinning 180° in place (prevents pinwheel artifacts!)- let target_x = if dot < -0.35 { -dir_x } else { dir_x };- let target_y = if dot < -0.35 { -dir_y } else { dir_y };- let turn_rate = (step_len / (brush_radius * 0.45).max(3.0)).clamp(0.08, 0.62);- let nx = self.tangent_x + (target_x - self.tangent_x) * turn_rate;- let ny = self.tangent_y + (target_y - self.tangent_y) * turn_rate;- let nlen = (nx * nx + ny * ny).sqrt().max(1e-5);- self.tangent_x = nx / nlen;- self.tangent_y = ny / nlen;-- // Apply custom_tip_angle offset- let ca = self.fixed_angle_rad.cos();- let sa = self.fixed_angle_rad.sin();- let rot_tx = self.tangent_x * ca - self.tangent_y * sa;- let rot_ty = self.tangent_x * sa + self.tangent_y * ca;- self.normal_x = -rot_ty;- self.normal_y = rot_tx;+ let mut signed_turn = 0.0f32;+ if !self.has_direction {+ self.tangent_x = inst_tx;+ self.tangent_y = inst_ty;+ self.prev_angle = inst_angle;+ self.has_direction = true;++ // Re-align initial bristle anchors to the TRUE stroke direction with organic longitudinal stagger!+ let init_nx = -self.tangent_y;+ let init_ny = self.tangent_x;+ let init_splay = self.compute_splay(config, prev_p, st_mag, velocity);+ let init_half_w = (prev_w * 0.5 * init_splay).max(1.0);+ for st in &mut self.strands {+ let long_stagger = if is_knife {+ 0.0+ } else {+ (st.start_delay - 0.35) * prev_w * 0.38+ };+ let ix = prev_x + init_nx * (st.offset * init_half_w) + self.tangent_x * long_stagger;+ let iy = prev_y + init_ny * (st.offset * init_half_w) + self.tangent_y * long_stagger;+ st.prev_x = ix;+ st.prev_y = iy;+ st.lag_x = ix;+ st.lag_y = iy;+ let rake_c = if is_rake {+ if st.offset.abs() < 0.58 { 1.24 } else { 0.86 }+ } else {+ 1.0+ };+ st.prev_radius = (st.rel_radius * init_half_w * tuft_width_boost * rake_c * 0.72).max(0.75);+ st.prev_alpha = if is_knife { eff_opacity } else { 0.0 };+ st.prev_h_scale = if is_knife { st.groove_weight } else { 0.0 };+ st.prev_arc_u = 0.0;+ }+ } else if self.follow_direction {+ // Reversal-safe physical hand-held brush orientation (zero pinwheel on 180° hairpin reversals!)+ let d_theta = wrap_pi(inst_angle - self.prev_angle);+ if d_theta.abs() > std::f32::consts::PI * 0.58 {+ let flipped_target = if d_theta > 0.0 {+ d_theta - std::f32::consts::PI+ } else {+ d_theta + std::f32::consts::PI+ };+ let max_turn = ((step_len / (sw * 0.75).max(12.0)) * 0.55).min(0.28);+ signed_turn = (flipped_target * 0.35).clamp(-max_turn, max_turn);+ } else {+ let max_turn =+ ((step_len / (sw * 0.45).max(8.0)) * (0.45 + stiffness * 0.45)).min(0.35);+ signed_turn = (d_theta * (0.45 + stiffness * 0.40)).clamp(-max_turn, max_turn);+ }+ let next_angle = self.prev_angle + signed_turn;+ self.prev_angle = next_angle;+ self.tangent_x = next_angle.cos();+ self.tangent_y = next_angle.sin();}+ // Base perpendicular normal (rotated by brush angle / barrel twist / tilt azimuth)+ let mut frame_rot = self.fixed_angle_rad + stw_deg.to_radians();+ if config.use_tilt && st_mag > 0.12 {+ let tilt_az = sty_tilt.atan2(stx_tilt);+ let rel_tilt = wrap_pi(tilt_az - self.prev_angle);+ frame_rot += rel_tilt * st_mag * 0.45;+ }+ let cos_r = frame_rot.cos();+ let sin_r = frame_rot.sin();+ let base_nx = -self.tangent_y;+ let base_ny = self.tangent_x;+ self.normal_x = base_nx * cos_r - base_ny * sin_r;+ self.normal_y = base_nx * sin_r + base_ny * cos_r;++ let splay = self.compute_splay(config, sp, st_mag, velocity);+ let half_w = sw * 0.5 * splay;let tangent_angle = self.tangent_y.atan2(self.tangent_x);- let is_knife = self.profile == BristleProfilePreset::Knife;- let max_strand_r = (brush_radius * 0.48).max(0.75);- let base_strand_r = ((brush_radius * 1.95) / (self.strands.len() as f32).max(4.0))- .clamp(0.75, max_strand_r);-- // 1. Emit cohesive 5-band under-bed first (provides smooth painterly paint body)- let underbed_r = (brush_radius * 0.44).clamp(1.2, 512.0);- for band in &mut self.underbed {- let lat_off = band.lateral_u * brush_radius;- let bx = sx + self.normal_x * lat_off;- let by = sy + self.normal_y * lat_off;- if band.initialized {- let bdx = bx - band.prev_x;- let bdy = by - band.prev_y;- let blen = (bdx * bdx + bdy * bdy).sqrt();- if blen >= 0.25 {++ // Signed curvature kappa = dTheta / ds -> clamp inner-turn normal offset to prevent fold-over+ let kappa = signed_turn / step_len.max(0.5);+ let abs_kappa = kappa.abs();+ let max_inner_radius = if abs_kappa > 1e-4 {+ (0.85 / abs_kappa).max(3.0)+ } else {+ f32::INFINITY+ };++ // 1. Emit cohesive 5-band flat-ribbon under-bed FIRST (so bristles rasterize & carve ON TOP!)+ // Slightly recessed behind leading bristle tips so organic staggered hairs always form the end edge!+ if !self.underbed.is_empty() {+ let band_rad = (half_w * 0.19).max(1.2);+ let recess = sw * 0.14;+ let bed_cx = cx - self.tangent_x * recess;+ let bed_cy = cy - self.tangent_y * recess;+ let prev_bed_cx = bed_cx - step_dx;+ let prev_bed_cy = bed_cy - step_dy;++ for band in &mut self.underbed {+ let mut local_band_span = band.raw_band_off * half_w;+ if kappa * local_band_span > 0.0 && local_band_span.abs() > max_inner_radius {+ let excess = local_band_span.abs() - max_inner_radius;+ local_band_span = local_band_span.signum()+ * local_band_span.abs().min(max_inner_radius + excess * 0.12);+ }+ let bx = bed_cx + self.normal_x * local_band_span;+ let by = bed_cy + self.normal_y * local_band_span;++ let abs_ub = band.u_band.abs();+ let band_entry_delay = abs_ub * 0.28;+ let bed_entry = ((self.stroke_distance+ - entry_zone * (0.25 + band_entry_delay))+ / (entry_zone * 0.55).max(8.0))+ .clamp(0.0, 1.0);+ let bed_pressure_lift = ((sp - (0.16 + abs_ub * 0.14)) / 0.28).clamp(0.0, 1.0);+ let a_cur = (eff_opacity * 0.95 * bed_entry * bed_pressure_lift).clamp(0.0, 0.98);+ let h_cur = 0.26 * bed_entry * bed_pressure_lift;++ if !band.initialized {+ band.prev_x = prev_bed_cx + self.normal_x * local_band_span;+ band.prev_y = prev_bed_cy + self.normal_y * local_band_span;+ band.prev_radius = band_rad;+ band.prev_alpha = 0.0;+ band.prev_h_scale = 0.0;+ band.prev_arc_u = slice_prev_arc;+ band.initialized = true;+ }++ if a_cur > 0.015 || band.prev_alpha > 0.015 {out_capsules.push(GpuBristleCapsule {p0_p1: [band.prev_x, band.prev_y, bx, by],- geom: [- band.prev_radius,- underbed_r,- sp,- (eff_opacity * 0.72).clamp(0.02, 1.0),- ],+ geom: [band.prev_radius, band_rad, sp, a_cur],strand: [band.bristle_idx as f32,- band.lateral_u.abs(),- 0.45,+ band.raw_band_off,+ 1.0 - abs_ub * 0.25,1.0, // bit 0: is_underbed],- motion: [self.stroke_distance, blen, tilt_mag, tangent_angle],+ motion: [band.prev_arc_u, self.stroke_distance, st_mag, tangent_angle],+ phys: [band.prev_alpha, band.prev_h_scale, h_cur, 1.0],});- band.prev_x = bx;- band.prev_y = by;- band.prev_radius = underbed_r;}- } else {+band.prev_x = bx;band.prev_y = by;- band.prev_radius = underbed_r;- band.initialized = true;+ band.prev_radius = band_rad;+ band.prev_alpha = a_cur;+ band.prev_h_scale = h_cur;+ band.prev_arc_u = self.stroke_distance;}}- // 2. Step each physical bristle strand with stiffness spring lag & pressure lift-off- let stiffness = self.settings.stiffness.clamp(0.05, 1.0);- let clumping = self.settings.clumping.clamp(0.0, 1.0);-+ // 2. Advance every physical bristle strand with meander, tuft stagger, flexibility lag,+ // staggered entry ramp, pressure lift-off, flank feathering & ridge breathing!for st in &mut self.strands {- // Staggered touchdown & low-pressure outer bristle lift-off- let delay_px = st.start_delay_factor * brush_radius;- if self.stroke_distance < delay_px {- continue;- }- if sp < st.lift_off_pressure * 0.85 {- st.initialized = false;- continue;+ let raw_off = st.offset;+ let abs_off = raw_off.abs();++ // Organic bristle hair meander along arc length+ let meander = if is_knife {+ 0.0+ } else {+ (self.stroke_distance * st.wander_freq + st.wander_phase).sin()+ * (0.028 + irreg * 0.056)+ };+ let mut local_span = (raw_off + meander).clamp(-0.98, 0.98) * half_w;++ // Inner-turn curvature fold clamp+ if kappa * local_span > 0.0 && local_span.abs() > max_inner_radius {+ let excess = local_span.abs() - max_inner_radius;+ local_span = local_span.signum()+ * local_span.abs().min(max_inner_radius + excess * 0.12);}- let contact_ramp = if st.lift_off_pressure > 0.01 {- ((sp - st.lift_off_pressure * 0.85) / 0.22).clamp(0.15, 1.0)++ // Longitudinal brush tuft stagger so start/end & edge hairs sit naturally forward/back+ let long_offset = if is_knife {+ 0.0} else {+ (st.start_delay - 0.45) * sw * if is_rake { 0.36 } else { 0.24 }+ };+ let target_x = cx + self.normal_x * local_span + self.tangent_x * long_offset;+ let target_y = cy + self.normal_y * local_span + self.tangent_y * long_offset;++ // Step-size-invariant flexibility lag+ let bx = st.lag_x + (target_x - st.lag_x) * slice_follow;+ let by = st.lag_y + (target_y - st.lag_y) * slice_follow;+ st.lag_x = bx;+ st.lag_y = by;++ let bdx = bx - st.prev_x;+ let bdy = by - st.prev_y;+ let strand_dist = (bdx * bdx + bdy * bdy).sqrt();++ // Natural bristle width undulation along stroke length+ let width_breath = if is_knife {1.0+ } else {+ 0.88 + 0.18 * (self.stroke_distance * 0.035 + st.wander_phase * 1.7).sin()};+ let rake_center_boost = if is_rake {+ if abs_off < 0.58 { 1.24 } else { 0.86 }+ } else {+ 1.0+ };+ let strand_rad =+ (st.rel_radius * half_w * tuft_width_boost * rake_center_boost * width_breath)+ .max(0.75);- // Target ferrule anchor point (clumping dynamically tightens under low pressure)- let dyn_clump = clumping * (1.0 - sp * 0.35);- let eff_u = st.lateral_u + (st.clump_center_u - st.lateral_u) * (dyn_clump * 0.28);- let target_x = sx- + self.normal_x * (eff_u * brush_radius)- + self.tangent_x * (st.longitudinal_v * brush_radius * thickness_ratio);- let target_y = sy- + self.normal_y * (eff_u * brush_radius)- + self.tangent_y * (st.longitudinal_v * brush_radius * thickness_ratio);-- // Spring stiffness integration toward target anchor (longer bristles lag more!)- let follow = (stiffness * st.stiffness_factor / st.length_factor.max(0.4))- .clamp(0.18, 0.98);- if st.initialized {- st.cur_x += (target_x - st.cur_x) * follow;- st.cur_y += (target_y - st.cur_y) * follow;+ // Staggered organic entry feathering: each bristle fades in at its own arcLength+ let start_gate = st.start_delay * entry_zone * if is_rake { 0.65 } else { 0.52 };+ let entry_ramp = if !is_knife && self.stroke_distance < start_gate + entry_zone * 0.48+ {+ let t_entry =+ (self.stroke_distance - start_gate) / (entry_zone * 0.48).max(4.0);+ if t_entry <= 0.0 {+ 0.0+ } else if t_entry >= 1.0 {+ 1.0+ } else {+ t_entry * t_entry * (3.0 - 2.0 * t_entry)+ }} else {- st.cur_x = target_x;- st.cur_y = target_y;- st.prev_x = target_x;- st.prev_y = target_y;- st.prev_radius = (base_strand_r * st.width_factor).max(0.65);- st.initialized = true;- continue;- }+ 1.0+ };- // Curvature inner-clamp: keep strand within 1.35× brush_radius of spine center- let rel_x = st.cur_x - sx;- let rel_y = st.cur_y - sy;- let max_reach = brush_radius * 1.35;- let reach2 = rel_x * rel_x + rel_y * rel_y;- if reach2 > max_reach * max_reach {- let inv = max_reach / reach2.sqrt();- st.cur_x = sx + rel_x * inv;- st.cur_y = sy + rel_y * inv;- }+ // Physical pressure-driven bristle lift-off+ let lift_thresh = (1.0 - st.length_factor) * (0.28 + self.dry_brush * 0.34);+ let contact_lift = if is_knife {+ 1.0+ } else {+ ((sp - lift_thresh) / 0.36).clamp(0.0, 1.0)+ };+ let smooth_lift = contact_lift * contact_lift * (3.0 - 2.0 * contact_lift);- let sdx = st.cur_x - st.prev_x;- let sdy = st.cur_y - st.prev_y;- let slen = (sdx * sdx + sdy * sdy).sqrt();- if slen < 0.2 {- continue;- }+ // Outer-flank dry-brush feathering: outer edges naturally reveal woven linen tooth!+ let flank_drop = if is_knife {+ 1.0+ } else {+ 1.0 - ((abs_off - 0.62).max(0.0) / 0.38).powf(1.5)+ * if is_rake { 0.50 } else { 0.68 }+ };- let cur_r = (base_strand_r * st.width_factor * (0.7 + 0.35 * contact_ramp))- .clamp(0.65, brush_radius * 0.65);- let flags = if is_knife { 4.0 } else { 0.0 };-- out_capsules.push(GpuBristleCapsule {- p0_p1: [st.prev_x, st.prev_y, st.cur_x, st.cur_y],- geom: [- st.prev_radius,- cur_r,- sp,- (eff_opacity * contact_ramp).clamp(0.02, 1.0),- ],- strand: [st.index as f32, st.edge_weight, st.groove_scale, flags],- motion: [self.stroke_distance, slen, tilt_mag, tangent_angle],- });+ // Subtle along-stroke ridge modulation so 3D paint crests breathe organically+ let ridge_breath = if is_knife {+ 1.0+ } else {+ 0.84 + 0.22 * (self.stroke_distance * 0.042 + st.wander_phase).sin()+ };++ let contact_env = entry_ramp * smooth_lift;+ let eff_alpha = eff_opacity * contact_env * (0.50 + 0.50 * flank_drop);+ let eff_rad = (strand_rad * (0.58 + 0.42 * contact_env)).max(0.70);+ let eff_h_scale = st.groove_weight * contact_env * ridge_breath;++ if (eff_alpha > 0.003 || st.prev_alpha > 0.003) && strand_dist > 0.05 {+ out_capsules.push(GpuBristleCapsule {+ p0_p1: [st.prev_x, st.prev_y, bx, by],+ geom: [st.prev_radius, eff_rad, sp, eff_alpha],+ strand: [st.index as f32, raw_off, flank_drop, strand_flags],+ motion: [st.prev_arc_u, self.stroke_distance, st_mag, tangent_angle],+ phys: [st.prev_alpha, st.prev_h_scale, eff_h_scale, st.length_factor],+ });+ }- st.prev_x = st.cur_x;- st.prev_y = st.cur_y;- st.prev_radius = cur_r;+ st.prev_x = bx;+ st.prev_y = by;+ st.prev_radius = eff_rad;+ st.prev_alpha = eff_alpha;+ st.prev_h_scale = eff_h_scale;+ st.prev_arc_u = self.stroke_distance;}// 3. BristleHybrid mode: emit textured stamp-modulated hybrid capsules along spineif self.render_mode == BrushRenderMode::BristleHybrid {self.hybrid_accum_dist += step_len;- let hybrid_spacing = (brush_radius * 2.0 * config.spacing.clamp(0.06, 0.5)).max(2.0);+ let hybrid_spacing = (sw * config.spacing.clamp(0.06, 0.5)).max(2.0);if self.hybrid_accum_dist >= hybrid_spacing {self.hybrid_accum_dist = 0.0;let mid_idx = (self.strands.len() / 2) as f32;+ let ha = eff_opacity * 0.65;out_capsules.push(GpuBristleCapsule {- p0_p1: [sx, sy, sx + self.tangent_x * 0.5, sy + self.tangent_y * 0.5],- geom: [brush_radius, brush_radius, sp, eff_opacity * 0.65],- strand: [mid_idx, 0.25, 0.85, 2.0], // bit 1: is_hybrid_stamp- motion: [self.stroke_distance, hybrid_spacing, tilt_mag, tangent_angle],+ p0_p1: [cx, cy, cx + self.tangent_x * 0.5, cy + self.tangent_y * 0.5],+ geom: [half_w, half_w, sp, ha],+ strand: [mid_idx, 0.0, 0.85, 2.0], // bit 1: is_hybrid_stamp+ motion: [+ slice_prev_arc,+ self.stroke_distance,+ st_mag,+ tangent_angle,+ ],+ phys: [ha, 0.48, 0.48, 1.0],});}}@@ -670,78 +1045,9 @@ impl BristleRibbonSimulator {self.last_x = px;self.last_y = py;self.last_pressure = pressure;- }-- fn init_positions(&mut self, cx: f32, cy: f32, brush_radius: f32, thickness_ratio: f32) {- for band in &mut self.underbed {- let x = cx + self.normal_x * (band.lateral_u * brush_radius);- let y = cy + self.normal_y * (band.lateral_u * brush_radius);- band.prev_x = x;- band.prev_y = y;- band.prev_radius = (brush_radius * 0.44).clamp(1.2, 512.0);- band.initialized = true;- }- let max_base_r = (brush_radius * 0.48).max(0.75);- let base_r = ((brush_radius * 1.95) / (self.strands.len() as f32).max(4.0))- .clamp(0.75, max_base_r);- for st in &mut self.strands {- let x = cx- + self.normal_x * (st.lateral_u * brush_radius)- + self.tangent_x * (st.longitudinal_v * brush_radius * thickness_ratio);- let y = cy- + self.normal_y * (st.lateral_u * brush_radius)- + self.tangent_y * (st.longitudinal_v * brush_radius * thickness_ratio);- st.cur_x = x;- st.cur_y = y;- st.prev_x = x;- st.prev_y = y;- st.prev_radius = (base_r * st.width_factor).max(0.65);- st.initialized = true;- }- }-- #[allow(clippy::too_many_arguments)]- fn emit_touchdown(- &self,- cx: f32,- cy: f32,- brush_radius: f32,- pressure: f32,- eff_opacity: f32,- tilt_mag: f32,- out_capsules: &mut Vec<GpuBristleCapsule>,- ) {- let tangent_angle = self.tangent_y.atan2(self.tangent_x);- let is_knife = self.profile == BristleProfilePreset::Knife;- for st in &self.strands {- if pressure < st.lift_off_pressure * 0.85 {- continue;- }- out_capsules.push(GpuBristleCapsule {- p0_p1: [- st.cur_x,- st.cur_y,- st.cur_x + self.tangent_x * 0.4,- st.cur_y + self.tangent_y * 0.4,- ],- geom: [st.prev_radius, st.prev_radius, pressure, eff_opacity * 0.85],- strand: [- st.index as f32,- st.edge_weight,- st.groove_scale,- if is_knife { 4.0 } else { 0.0 },- ],- motion: [0.0, 0.5, tilt_mag, tangent_angle],- });- }- if self.render_mode == BrushRenderMode::BristleHybrid {- let mid_idx = (self.strands.len() / 2) as f32;- out_capsules.push(GpuBristleCapsule {- p0_p1: [cx, cy, cx + self.tangent_x * 0.5, cy + self.tangent_y * 0.5],- geom: [brush_radius, brush_radius, pressure, eff_opacity * 0.65],- strand: [mid_idx, 0.25, 0.85, 2.0],- motion: [0.0, 0.5, tilt_mag, tangent_angle],- });- }+ self.last_width = width;+ self.last_tilt_x = tilt_x;+ self.last_tilt_y = tilt_y;+ self.last_twist = twist_deg;}}diff --git a/crates/ink-engine/src/natural_paint/natural_paint.rs b/crates/ink-engine/src/natural_paint/natural_paint.rsindex 15e3dc9..7de9238 100644--- a/crates/ink-engine/src/natural_paint/natural_paint.rs+++ b/crates/ink-engine/src/natural_paint/natural_paint.rs@@ -35,7 +35,7 @@ use std::num::NonZeroU64;const NP_UNIFORM_STRIDE: u64 = 256;-/// Output of `cs_update_bristle_load` consumed by `cs_raster_natural_paint` (`96` bytes).+/// Output of `cs_update_bristle_load` consumed by `cs_raster_natural_paint` (`128` bytes).#[repr(C)]#[derive(Debug, Clone, Copy, Pod, Zeroable)]struct GpuResolvedCapsule {@@ -43,10 +43,14 @@ struct GpuResolvedCapsule {geom: [f32; 4],strand: [f32; 4],motion: [f32; 4],- /// `[r, g, b, deposit_alpha]` resolved on GPU after canvas pickup + KM mixing.- resolved_rgba: [f32; 4],- /// `[wetness, load, pigment_strength, blur_strength]`- resolved_state: [f32; 4],+ /// `[r0, g0, b0, eff_alpha0]` — start-of-segment sRGB color & alpha.+ rgba0: [f32; 4],+ /// `[r1, g1, b1, eff_alpha1]` — end-of-segment sRGB color & alpha.+ rgba1: [f32; 4],+ /// `[load0, load1, h0, h1]` — start/end squeezed paint load & sculptural height.+ load_h: [f32; 4],+ /// `[wetness, pigment_strength, blur_strength, length_factor]`+ meta: [f32; 4],}#[repr(C)]@@ -62,7 +66,7 @@ struct PickupUniforms {counts0: [u32; 4],/// `[total_slots_u, bristle_count_u, use_blur_u, perceptual_u]`counts1: [u32; 4],- /// `[blur_strength, brush_size, auto_clean_u_f, 0.0]`+ /// `[blur_strength, brush_size, auto_clean_u_f, init_paint_load]`extra: [f32; 4],/// `[grid_ox, grid_oy, grid_w, grid_h]` — O(1) dense bounding-box tile lookup gridgrid_info: [i32; 4],@@ -91,6 +95,10 @@ struct RasterTileUniforms {rect: [u32; 4],/// `[bin_start, bin_count, track_cov_u, 0]` — per-tile binned capsule slicebin_info: [u32; 4],+ /// `[contrast_factor, brightness_norm, inverted_f, rand_cos]`+ paper_fx: [f32; 4],+ /// `[stroke_off_x, stroke_off_y, rand_sin, 0.0]`+ paper_off: [f32; 4],}#[repr(C)]@@ -190,6 +198,7 @@ struct RawCapsule {{geom: vec4<f32>,strand: vec4<f32>,motion: vec4<f32>,+ phys: vec4<f32>,}};struct ResolvedCapsule {{@@ -197,8 +206,10 @@ struct ResolvedCapsule {{geom: vec4<f32>,strand: vec4<f32>,motion: vec4<f32>,- resolved_rgba: vec4<f32>,- resolved_state: vec4<f32>,+ rgba0: vec4<f32>,+ rgba1: vec4<f32>,+ load_h: vec4<f32>,+ cap_meta: vec4<f32>,}};struct PickupUniforms {{@@ -300,7 +311,7 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{let cap_count = u.counts0.w;let mode = u.counts0.x;- let amount = clamp(u.paint0.x, 0.0, 1.0);+ let eff_amount = clamp(u.paint0.x, 0.0, 1.0);let density = clamp(u.paint0.y, 0.0, 1.0);let stretch = clamp(u.paint0.z, 0.0, 1.0);let wetness = clamp(u.paint0.w, 0.0, 1.0);@@ -308,12 +319,24 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{let viscosity = clamp(u.paint1.y, 0.0, 1.0);let charge_p = clamp(u.paint1.z, 0.0, 1.0);let fg = u.fg_pigment.xyz;+ let init_load = clamp(u.extra.w, 0.0, 1.0);let max_slot_f = f32(total_slots - 1u);+ let is_pure_blender = (mode == 2u) || (eff_amount <= 0.005);+ let is_full_fresh = (!is_pure_blender) && (eff_amount >= 0.995);+ let viscosity_resist = 1.0 - viscosity * 0.50;+ let mode_pickup_mult = select(select(0.90, 1.35, mode == 1u), 1.05, mode == 3u);+var slot = bristle_load[tid];var prev_step_dist = -1e9;var prev_step_pos = vec2<f32>(-1e9, -1e9);+ var prev_out_rgb = slot.color_load.rgb;+ var prev_out_load = clamp(slot.color_load.w, 0.0, 1.0);+ if (is_pure_blender) {{+ prev_out_load = clamp(slot.state_carry.x, 0.0, 1.0);+ }}+for (var i: u32 = 0u; i < cap_count; i = i + 1u) {{let cap = capsules_in[i];let b_idx = u32(clamp(cap.strand.x + 0.5, 0.0, max_slot_f));@@ -326,75 +349,133 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{var carry_a = clamp(slot.state_carry.x, 0.0, 1.0);var has_canvas = slot.state_carry.y;- // When spatial_mixing == false, all strands emitted at the exact same stroke substep share- // the single unified reservoir — evaluate pickup & KM once per substep instead of 35x!+ let pressure = clamp(cap.geom.z, 0.05, 1.0);+ let seg_vec = cap.p0_p1.zw - cap.p0_p1.xy;+ let ds = length(seg_vec);+ let length_f = clamp(cap.phys.w, 0.32, 1.0);+ let flank_drop = clamp(cap.strand.z, 0.25, 1.0);+ let flags_bits = u32(cap.strand.w + 0.5);+ let is_underbed = ((flags_bits & 1u) != 0u);+let same_nonspatial_substep = (!is_spatial)&& (i > 0u)&& (cap_count > 8u)- && (abs(cap.motion.x - prev_step_dist) <= 0.01)- && (length(cap.p0_p1.xy - prev_step_pos) <= max(u.extra.y * 1.6, 12.0));+ && (abs(cap.motion.y - prev_step_dist) <= 0.01)+ && (length(cap.p0_p1.zw - prev_step_pos) <= max(u.extra.y * 1.6, 12.0));++ let start_rgb = prev_out_rgb;+ let start_load = prev_out_load;if (!same_nonspatial_substep) {{- prev_step_dist = cap.motion.x;- prev_step_pos = cap.p0_p1.xy;+ prev_step_dist = cap.motion.y;+ prev_step_pos = cap.p0_p1.zw;++ // 1. Per-bristle paint depletion along stroke arc (shorter outer bristles exhaust earlier -> dry-brush tail!)+ if (!is_pure_blender && depletion > 0.001 && ds > 0.0) {{+ let exhaust_dist = 110.0 + (1.0 - depletion) * 1150.0;+ let load_endurance = 1.0 - eff_amount * 0.25;+ let drop = (ds / exhaust_dist)+ * depletion+ * (1.0 / length_f)+ * load_endurance+ * (1.15 - charge_p * pressure * 0.45);+ cur_load = max(0.0, cur_load - drop);+ }}- let pressure = clamp(cap.geom.z, 0.02, 1.0);- let ds = max(cap.motion.y, 0.25);- let r = max(cap.geom.x, cap.geom.y);- let canvas = sample_canvas_footprint(cap.p0_p1.x, cap.p0_p1.y, r);+ // 2. Sample LEADING tip `p1` (+ slight forward lookahead) so forward motion reads TRUE+ // underlying canvas pigment without self-dilution, while loops pick up earlier passes!+ var canvas = vec4<f32>(0.0);+ if (!is_full_fresh) {{+ let r = max(cap.geom.x, cap.geom.y);+ var sample_pt = cap.p0_p1.zw;+ if (ds > 0.25) {{+ let dir = seg_vec / ds;+ sample_pt = sample_pt + dir * min(r * 0.35, 2.5);+ }}+ canvas = sample_canvas_footprint(sample_pt.x, sample_pt.y, r);+ }}- let step_scale = clamp(ds / 18.0, 0.14, 1.0);- if (canvas.a > 0.015) {{- var pickup_rate = 0.0;- if (mode == 2u) {{- // Smear: strong immediate canvas pickup, zero fresh fg- pickup_rate = clamp(0.45 + wetness * 0.45 + (1.0 - stretch) * 0.25, 0.2, 0.92);+ // 3. Exact pre-Rust continuous-distance equilibrium pigment mixing (`SpatialBristleReservoir::stepBristle`)+ if (is_full_fresh) {{+ cur_rgb = fg;+ carry_a = 1.0;+ }} else if (canvas.a > 0.015 && (wetness > 0.005 || is_pure_blender)) {{+ if (is_pure_blender) {{if (has_canvas < 0.5) {{cur_rgb = canvas.rgb;+ carry_a = canvas.a;has_canvas = 1.0;}} else {{- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale);+ let smudge_dist = (7.0 + stretch * 46.0) * (0.70 + viscosity * 0.55);+ let pickup = select(+ min(0.75, canvas.a * viscosity_resist * 0.45),+ 1.0 - exp(-(ds * canvas.a * viscosity_resist * (0.55 + 0.45 * pressure)) / smudge_dist),+ ds > 0.0+ );+ cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup);+ carry_a = min(1.0, carry_a * 0.72 + canvas.a * 0.28);}}- carry_a = max(carry_a, canvas.a * (0.65 + 0.35 * stretch));- }} else if (mode == 1u) {{- // Running Color: fluid high-pickup wet bleeding- pickup_rate = clamp((wetness * 0.65 + (1.0 - amount) * 0.45) * (0.45 + 0.55 * pressure), 0.1, 0.88);- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.82);- carry_a = max(carry_a, canvas.a * (0.5 + 0.45 * stretch));- has_canvas = 1.0;- }} else if (mode == 3u) {{- // Impasto Mix: viscous heavy-body oil swirl- pickup_rate = clamp((wetness * 0.52 + (1.0 - amount) * 0.38) * (1.0 - viscosity * 0.28) * (0.4 + 0.6 * pressure), 0.08, 0.82);- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);- carry_a = max(carry_a, canvas.a * (0.55 + 0.4 * stretch));- has_canvas = 1.0;}} else {{- // Blend: balanced painterly mixing- pickup_rate = clamp((wetness * 0.48 + (1.0 - amount) * 0.42) * (0.45 + 0.55 * pressure), 0.05, 0.80);- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);- carry_a = max(carry_a, canvas.a * (0.45 + 0.45 * stretch));+ // Loaded brush crossing wet paint: true physical equilibrium between canvas & fresh fg!+ // Per-bristle marbled pickup variation: outer bristles & protruding hairs pick up rich+ // underlying pigment (vivid green halo & picked-up streaks), while thick loaded belly+ // tufts preserve luminous fresh color (just like real hog-bristle oil!).+ let abs_off = abs(cap.strand.y);+ let br_hash = fract(sin(f32(tid) * 12.9898 + 4.1414) * 43758.5453);+ let edge_boost = 0.72 + abs_off * abs_off * 0.90;+ let strand_var = 0.56 + br_hash * 0.88;+ let length_pick = 0.85 + length_f * 0.30;+ let bristle_pickup_mod = select(+ clamp(edge_boost * strand_var * length_pick, 0.42, 1.85),+ 0.72,+ is_underbed+ );++ let amount_allowance = max(0.0, 1.0 - pow(eff_amount, 1.9));+ let load_ratio = select(0.0, min(1.0, cur_load / init_load), init_load > 0.05);+ let depletion_pickup_boost = (1.0 - load_ratio) * 0.40 * (1.0 - eff_amount * 0.50);++ let w_canvas = 2.05+ * wetness+ * canvas.a+ * viscosity_resist+ * mode_pickup_mult+ * bristle_pickup_mod+ * (amount_allowance + depletion_pickup_boost)+ * (0.55 + 0.45 * pressure);+ let w_fresh = eff_amount+ * (0.48 + 0.52 * cur_load)+ * select(1.0, 0.72, mode == 1u);+ let w_total = w_canvas + w_fresh;+ let eq_fresh_ratio = select(1.0, w_fresh / w_total, w_total > 1e-4);++ let eq_color = mix_paint_color(canvas.rgb, fg, eq_fresh_ratio);+ let char_dist = (11.0 + stretch * 28.0) * (0.70 + viscosity * 0.55);+ let step_rate = select(+ min(0.35, (1.0 - eq_fresh_ratio) * 0.50 * canvas.a),+ 1.0 - exp(-(ds * max(0.45, w_total)) / char_dist),+ ds > 0.0+ );+ cur_rgb = mix_paint_color(cur_rgb, eq_color, step_rate);+ carry_a = min(1.0, max(carry_a, 0.50 + cur_load * 0.50));has_canvas = 1.0;}}- // Fresh pigment recharge from the loaded brush belly during wet mixing- if (mode != 2u && cur_load > 0.02 && amount > 0.01) {{- let fg_feed = clamp(amount * cur_load * step_scale * 0.88, 0.0, 0.55);- cur_rgb = mix_paint_color(cur_rgb, fg, fg_feed);- }}- }} else {{- // Over empty canvas: carry decays smoothly according to color_stretch- let decay = clamp(ds / max(18.0 + stretch * 180.0, 12.0), 0.005, 0.35);- carry_a = max(0.0, carry_a * (1.0 - decay));- // Loaded brushes slowly pull back toward fresh fg paint along empty strokes if amount is high- if (mode != 2u && cur_load > 0.08 && amount > 0.2) {{- let recharge = clamp(amount * cur_load * step_scale * 0.06, 0.0, 0.08);- cur_rgb = mix_paint_color(cur_rgb, fg, recharge);+ }} else if (ds > 0.0) {{+ // Moving over dry / unpainted canvas+ if (is_pure_blender) {{+ if (has_canvas >= 0.5) {{+ let drag_dist = max(28.0, stretch * 720.0);+ let decay = 1.0 - exp(-ds / drag_dist);+ carry_a = max(0.0, carry_a * (1.0 - decay * 1.45));+ }}+ }} else if (has_canvas >= 0.5 && cur_load > 0.02) {{+ // Smoothly recover toward loaded fg color as picked-up streaks trail off+ let recover_dist = max(24.0, (0.20 + stretch * 0.80) * (220.0 / max(0.18, eff_amount)));+ let recover = 1.0 - exp(-ds / recover_dist);+ cur_rgb = mix_paint_color(cur_rgb, fg, recover);}}}}- // Paint load depletion along stroke distance (reduced by chargePerPressure when pressing hard!)- let dep_step = ds * depletion * 0.0018 * (1.0 - charge_p * pressure * 0.45);- cur_load = max(0.0, cur_load - dep_step);-slot.color_load = vec4<f32>(cur_rgb, cur_load);slot.dirty_wet = vec4<f32>(cur_rgb, wetness);slot.state_carry = vec4<f32>(carry_a, has_canvas, fg.r, fg.g);@@ -402,23 +483,44 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{slot.fg_meta.w = 1.0;}}- // Compute effective deposit opacity for this capsule- var dep_a = cap.geom.w * density;- if (mode == 2u) {{- // Smear deposits only carried canvas pigment!- dep_a = dep_a * clamp(carry_a * (0.55 + 0.45 * stretch), 0.0, 1.0);- }} else {{- let load_vis = clamp(0.12 + cur_load * 0.88 + carry_a * 0.42, 0.0, 1.0);- dep_a = dep_a * load_vis * clamp(0.25 + amount * 0.75 + carry_a * 0.45, 0.0, 1.0);- }}+ // Effective squeezed load under stylus pressure+ let squeezed_load = select(+ clamp(cur_load * (1.0 - charge_p * 0.32 + charge_p * 0.62 * pressure), 0.0, 1.0),+ carry_a,+ is_pure_blender+ );+ let load_cov = select(+ min(1.0, pow(max(0.0, squeezed_load), 0.58) * 1.12),+ carry_a,+ is_pure_blender+ );+ let pressure_alpha = 0.34 + 0.66 * pow(pressure, 0.78);+ let step_a = clamp(density * load_cov * pressure_alpha, 0.0, 1.0);++ // If pure blender hasn't touched canvas paint yet, emit zero alpha+ let blender_gate = select(1.0, select(0.0, 1.0, has_canvas >= 0.5), is_pure_blender);+ let eff_a0 = clamp(step_a * cap.phys.x * blender_gate, 0.0, 1.0);+ let eff_a1 = clamp(step_a * cap.geom.w * blender_gate, 0.0, 1.0);++ let eff_load0 = clamp(start_load * flank_drop * blender_gate, 0.0, 1.0);+ let eff_load1 = clamp(squeezed_load * flank_drop * blender_gate, 0.0, 1.0);++ let h_mod = (0.28 + 0.72 * squeezed_load) * (0.45 + 0.55 * pressure) * blender_gate;+ let h0 = select(cap.phys.y * h_mod, eff_load0 * cap.phys.y, is_underbed);+ let h1 = select(cap.phys.z * h_mod, eff_load1 * cap.phys.z, is_underbed);++ prev_out_rgb = cur_rgb;+ prev_out_load = squeezed_load;var out_cap: ResolvedCapsule;out_cap.p0_p1 = cap.p0_p1;out_cap.geom = cap.geom;out_cap.strand = cap.strand;out_cap.motion = cap.motion;- out_cap.resolved_rgba = vec4<f32>(cur_rgb, clamp(dep_a, 0.0, 1.0));- out_cap.resolved_state = vec4<f32>(wetness, cur_load, u.fg_pigment.w, u.extra.x);+ out_cap.rgba0 = vec4<f32>(start_rgb, eff_a0);+ out_cap.rgba1 = vec4<f32>(cur_rgb, eff_a1);+ out_cap.load_h = vec4<f32>(eff_load0, eff_load1, h0, h1);+ out_cap.cap_meta = vec4<f32>(wetness, u.fg_pigment.w, u.extra.x, length_f);capsules_out[i] = out_cap;}}@@ -438,8 +540,10 @@ struct ResolvedCapsule {{geom: vec4<f32>,strand: vec4<f32>,motion: vec4<f32>,- resolved_rgba: vec4<f32>,- resolved_state: vec4<f32>,+ rgba0: vec4<f32>,+ rgba1: vec4<f32>,+ load_h: vec4<f32>,+ cap_meta: vec4<f32>,}};struct RasterTileUniforms {{@@ -453,6 +557,8 @@ struct RasterTileUniforms {{sel_info: vec4<f32>,rect: vec4<u32>,bin_info: vec4<u32>,+ paper_fx: vec4<f32>,+ paper_off: vec4<f32>,}};@group(0) @binding(0) var<uniform> u: RasterTileUniforms;@@ -468,46 +574,103 @@ struct RasterTileUniforms {{@group(0) @binding(10) var<storage, read> binned_indices: array<u32>;@group(0) @binding(11) var cov_pool: texture_2d_array<f32>;@group(0) @binding(12) var dst_cov: texture_storage_2d<rgba16float, write>;--fn sample_surface_height(doc_px: vec2<f32>, stroke_dist: f32, tangent_ang: f32) -> f32 {{+@group(0) @binding(13) var surface_sampler: sampler;++// High-DPI 2x oversampled bilinear + 2-tap rotated-grid anti-aliased surface heightfield lookup+// matching `evaluateMappedSurfaceHeight` in `NaturalPaintRenderer.ts`!+fn sample_surface_height(+ doc_px: vec2<f32>,+ arc_u: f32,+ across_v: f32,+ half_brush_w: f32,+ seg_cos: f32,+ seg_sin: f32,+) -> f32 {{if (u.flags1.x == 0u) {{return 0.5;}}- let dims = vec2<f32>(textureDimensions(surface_tex, 0));- let scale = max(u.surface1.x, 0.05);+ let dims = max(vec2<f32>(textureDimensions(surface_tex, 0)), vec2<f32>(1.0));+ let inv_scale = 1.0 / max(u.surface1.x, 0.05);let rot = u.surface1.y;let mode = u.flags0.x;var p = doc_px;if (mode == 1u) {{- // StrokeAligned: rotate world coordinates into stroke tangent frame- let ca = cos(-tangent_ang);- let sa = sin(-tangent_ang);- p = vec2<f32>(doc_px.x * ca - doc_px.y * sa, doc_px.x * sa + doc_px.y * ca);+ // BrushAligned: brush-local tangent/normal frame+ p = vec2<f32>(+ doc_px.x * seg_cos + doc_px.y * seg_sin,+ -doc_px.x * seg_sin + doc_px.y * seg_cos,+ );}} else if (mode == 2u) {{- // BrushScale: scale paper tooth inversely with brush size- let bs = clamp(u.surface1.w / 48.0, 0.35, 3.5);- p = doc_px / bs;+ // StrokeFlow: continuous UV along stroke arcLength & across brush width+ p = vec2<f32>(arc_u, across_v * max(8.0, half_brush_w));}} else if (mode == 3u) {{- // OrganicDrift: gentle drift along stroke length to eliminate repetitive tiling- p = doc_px + vec2<f32>(stroke_dist * 0.13, stroke_dist * 0.07);+ // RandomPerStroke: deterministic random rotation & offset per stroke+ let rc = u.paper_fx.w;+ let rs = u.paper_off.z;+ p = vec2<f32>(+ doc_px.x * rc - doc_px.y * rs + u.paper_off.x,+ doc_px.x * rs + doc_px.y * rc + u.paper_off.y,+ );}}- let c = cos(rot);- let s = sin(rot);- let rp = vec2<f32>(p.x * c - p.y * s, p.x * s + p.y * c) / scale;- let uv = fract(rp / max(dims, vec2<f32>(1.0)));- let tc = vec2<i32>(clamp(uv * dims, vec2<f32>(0.0), dims - vec2<f32>(1.0)));- var h = textureLoad(surface_tex, tc, 0).r;-- if (u.flags1.y != 0u && u.surface1.z > 0.005) {{- let d2 = vec2<f32>(textureDimensions(dual_surface_tex, 0));- let uv2 = fract((rp * 1.73) / max(d2, vec2<f32>(1.0)));- let tc2 = vec2<i32>(clamp(uv2 * d2, vec2<f32>(0.0), d2 - vec2<f32>(1.0)));- let h2 = textureLoad(dual_surface_tex, tc2, 0).r;- h = mix(h, h2, clamp(u.surface1.z, 0.0, 1.0));+ var tp = p * inv_scale;+ if (abs(rot) > 1e-4) {{+ let c = cos(rot);+ let s = sin(rot);+ tp = vec2<f32>(tp.x * c - tp.y * s, tp.x * s + tp.y * c);}}- return clamp(h, 0.0, 1.0);++ // 2x-DPI oversampled texels (`SURFACE_TEXELS_PER_PX = 2.0`) with 2-tap rotated-grid AA (zero moire!)+ let texels_per_px = select(1.0, 2.0, dims.x >= 768.0);+ let htp = tp * texels_per_px;+ let inv_dims = vec2<f32>(1.0) / dims;+ let uv_a = (htp + vec2<f32>(-0.32, 0.24)) * inv_dims;+ let uv_b = (htp + vec2<f32>(0.32, -0.24)) * inv_dims;+ let g_a = textureSampleLevel(surface_tex, surface_sampler, uv_a, 0.0).r;+ let g_b = textureSampleLevel(surface_tex, surface_sampler, uv_b, 0.0).r;+ var g = (g_a + g_b) * 0.5;++ if (u.flags1.y != 0u && u.surface1.z > 0.01) {{+ let d2 = max(vec2<f32>(textureDimensions(dual_surface_tex, 0)), vec2<f32>(1.0));+ let uv2 = (htp * 1.35) / d2;+ let dg = textureSampleLevel(dual_surface_tex, surface_sampler, uv2, 0.0).r;+ g = mix(g, dg, clamp(u.surface1.z * 0.5, 0.0, 0.5));+ }}++ if (u.paper_fx.z > 0.5) {{+ g = 1.0 - g;+ }}+ g = g + u.paper_fx.y;+ g = (g - 0.5) * u.paper_fx.x + 0.5;+ return clamp(g, 0.0, 1.0);+}}++// Physical Paint <-> Canvas Tooth contact evaluation:+// - Firm pressure + heavy paint load -> fills canvas valleys 100% smoothly like butter (zero waffle grid!)+// - Light pressure / low load / outer flanks / dryBrush / pastel -> skips valleys & catches crisp woven peaks!+fn evaluate_tooth_contact(+ h_canvas: f32,+ eff_load: f32,+ curved_p: f32,+ tilt_reduction: f32,+ grain_depth: f32,+ dry_brush: f32,+ effective_dry: f32,+ softness_inv: f32,+) -> f32 {{+ let c_load = clamp(eff_load, 0.0, 1.0);+ let penetration = clamp((curved_p * 0.50 + c_load * 0.50) * (0.38 + 0.62 * c_load) * tilt_reduction, 0.0, 1.0);+ let valley_fill = smoothstep(0.45, 0.84, penetration);+ let cutoff = effective_dry * (1.0 - penetration * 0.82) * 0.82;+ let ct = clamp((h_canvas - cutoff) * softness_inv, 0.0, 1.0);+ let smooth_t = ct * ct * (3.0 - 2.0 * ct);+ let mask_strength = clamp(+ (grain_depth + dry_brush) * (1.0 - valley_fill * 0.96),+ 0.0,+ 1.0,+ );+ return 1.0 - mask_strength + mask_strength * smooth_t;}}@compute @workgroup_size(8, 8, 1)@@ -522,7 +685,11 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{var cur_col = textureLoad(color_pool, lp, slot, 0);var cur_h = max(textureLoad(height_pool, lp, slot, 0).r, 0.0);let track_cov = (u.bin_info.z != 0u);- var cur_cov = select(0.0, textureLoad(cov_pool, lp, slot, 0).r, track_cov);+ let meta_in = select(vec4<f32>(0.0), textureLoad(cov_pool, lp, slot, 0), track_cov);+ var cur_cov = meta_in.r;+ var last_arc_u = select(-9999.0, (meta_in.g - 1.0) * 10.0, meta_in.g > 0.5);+ var last_bristle = i32(round(meta_in.b)) - 2; // -2=none, -1=underbed, 0..63=bristle+ var stroke_a = meta_in.a;let bin_start = u.bin_info.x;let bin_count = u.bin_info.y;@@ -537,7 +704,7 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{textureStore(dst_color, lp, cur_col);textureStore(dst_height, lp, vec4<f32>(cur_h, 0.0, 0.0, 0.0));if (track_cov) {{- textureStore(dst_cov, lp, vec4<f32>(cur_cov, 0.0, 0.0, 1.0));+ textureStore(dst_cov, lp, meta_in);}}return;}}@@ -547,171 +714,345 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{let granulation = clamp(u.surface0.y, 0.0, 1.0);let pen_curve = clamp(u.surface0.z, 0.25, 3.0);let pen_is_linear = abs(pen_curve - 1.0) < 0.005;- let grain_strength = clamp(u.surface0.w, 0.0, 1.0);- let need_surf = (dry_brush > 0.005) || (granulation > 0.005) || (grain_strength > 0.005);+ let grain_depth = clamp(u.surface0.w, 0.0, 1.0);+ let has_grain_or_dry = (grain_depth > 0.005) || (dry_brush > 0.005);+ let need_surf = has_grain_or_dry || (granulation > 0.005);+ let has_static_grain = (u.flags0.x == 0u) || (u.flags0.x == 3u);++ let effective_dry = max(dry_brush, grain_depth * 0.68);+ let softness_inv = 1.0 / max(0.06, 0.14 + (1.0 - effective_dry) * 0.22);let impasto_enabled = (u.flags0.y != 0u);let impasto_depth = clamp(u.impasto0.x, 0.0, 2.5);- let bristle_relief = clamp(u.impasto0.y, 0.0, 1.5);- let edge_ridge = clamp(u.impasto0.z, 0.0, 1.5);- let hardness = clamp(u.impasto0.w, 0.0, 1.0);+ let bristle_relief = select(0.40, clamp(u.impasto0.y, 0.0, 1.5), impasto_enabled);let alpha_lock = (u.flags0.z != 0u);+ let mode = u.flags0.w;let base_alpha_lock = cur_col.a;let use_blur = (u.flags1.w != 0u) && (u.extra.x > 0.01);let blur_str = clamp(u.extra.x, 0.0, 1.0);let pigment_str = clamp(u.extra.y, 0.0, 1.0);- let soft_edge = mix(0.55, 0.14, hardness);- let soft_inner = max(0.0, 1.0 - soft_edge);-- // Lazy ONCE-per-pixel surface heightfield cache (ZERO redundant cos/sin/textureLoad per capsule!)- var has_surf_h = false;- var surf_h = 0.5;- var surf_tooth = 1.0;-- // Linear premultiplied accumulator for all overlapping capsules at this pixel,- // allowing ONE single perceptual/Kubelka-Munk composite against `cur_col` after the loop!- var acc_premul = vec3<f32>(0.0);- var acc_a = 0.0;+ let use_pigment_blend = pigment_str > 0.005;++ let half_brush_w = max(2.0, u.surface1.w * 0.5);+ let self_pass_window = max(14.0, half_brush_w * 0.90);+ let edge_soft = clamp(1.4 + (1.0 - bristle_relief) * 1.0, 1.25, 2.5);+ let half_edge_soft = edge_soft * 0.5;+ let inv_edge_soft = 1.0 / edge_soft;+ let pi = 3.14159265;++ // Cache static canvas tooth once per hit pixel+ var has_static_h = false;+ var static_h_canvas = 0.5;+ var last_h_canvas = 0.5;+ var did_paint_hit = false;+ var did_impasto_hit = false;var max_blur_f = 0.0;- // Accumulated 3D impasto sculpt state- var imp_hit = false;- var imp_max_target = 0.0;- var imp_blend_acc = 0.0;- var imp_build_acc = 0.0;- var imp_smear_cov = 0.0;-for (var bi: u32 = 0u; bi < bin_count; bi = bi + 1u) {{let cap = capsules[binned_indices[bin_start + bi]];- let a = cap.p0_p1.xy;- let b = cap.p0_p1.zw;- let r_max = max(cap.geom.x, cap.geom.y) + 1.5;+ let a0 = cap.rgba0.a;+ let a1 = cap.rgba1.a;+ if (a0 <= 0.002 && a1 <= 0.002) {{+ continue;+ }}- // Fast AABB reject per capsule- if (doc_pos.x < min(a.x, b.x) - r_max || doc_pos.x > max(a.x, b.x) + r_max ||- doc_pos.y < min(a.y, b.y) - r_max || doc_pos.y > max(a.y, b.y) + r_max) {{+ let p0 = cap.p0_p1.xy;+ let p1 = cap.p0_p1.zw;+ let r_max = max(cap.geom.x, cap.geom.y) + 1.5;+ if (doc_pos.x < min(p0.x, p1.x) - r_max || doc_pos.x > max(p0.x, p1.x) + r_max ||+ doc_pos.y < min(p0.y, p1.y) - r_max || doc_pos.y > max(p0.y, p1.y) + r_max) {{continue;}}- let ab = b - a;+ let ab = p1 - p0;let ab2 = dot(ab, ab);var t = 0.0;- if (ab2 > 1e-5) {{- t = clamp(dot(doc_pos - a, ab) / ab2, 0.0, 1.0);+ if (ab2 > 1e-6) {{+ t = clamp(dot(doc_pos - p0, ab) / ab2, 0.0, 1.0);}}- let closest = a + ab * t;+ let closest = p0 + ab * t;let diff = doc_pos - closest;- let r = max(mix(cap.geom.x, cap.geom.y, t), 0.5);- let d2 = dot(diff, diff);- if (d2 >= r * r) {{+ let rad = max(mix(cap.geom.x, cap.geom.y, t), 0.5);+ let max_r = rad + 0.85;+ let dist2 = dot(diff, diff);+ if (dist2 >= max_r * max_r) {{continue;}}- let d = sqrt(d2);-- let lat = d / r; // 0 at strand core, 1 at outer edge- var cov = 1.0 - smoothstep(soft_inner, 1.0, lat);let flags_bits = u32(cap.strand.w + 0.5);let is_underbed = ((flags_bits & 1u) != 0u);let is_hybrid = ((flags_bits & 2u) != 0u);- let is_knife = ((flags_bits & 4u) != 0u);-- // BristleHybrid mode: modulate hybrid stamp capsule by brush tip texture- if (is_hybrid && u.flags1.z != 0u) {{- let ang = cap.motion.w;- let ca = cos(-ang);- let sa = sin(-ang);- let rel = (doc_pos - a) / max(r, 1.0);- let rot_rel = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);- let tip_uv = rot_rel * 0.5 + vec2<f32>(0.5);- if (tip_uv.x < 0.0 || tip_uv.x > 1.0 || tip_uv.y < 0.0 || tip_uv.y > 1.0) {{- continue;+ let bristle_idx = select(i32(round(cap.strand.x)), -1, is_underbed);++ let arc_u = mix(cap.motion.x, cap.motion.y, t);+ let is_same_pass = (last_arc_u > -9000.0) && (abs(arc_u - last_arc_u) < self_pass_window);+ let is_same_bristle = is_same_pass && (!is_underbed) && (last_bristle == bristle_idx);++ // Skip exact duplicate trailing endcap of the same continuous bristle+ if (is_same_bristle && t <= 0.0001) {{+ continue;+ }}++ let pressure = clamp(cap.geom.z, 0.05, 1.0);+ let tilt_mag = clamp(cap.motion.z, 0.0, 1.0);+ let load = mix(cap.load_h.x, cap.load_h.y, t);+ let raw_h = mix(cap.load_h.z, cap.load_h.w, t);+ let interp_a = mix(a0, a1, t);++ var base_alpha = 0.0;+ var groove_crown = 1.0;+ var trough_carve = 0.0;+ var eff_load_for_tooth = load;+ var max_local_h = raw_h;++ if (is_underbed) {{+ let core_r = rad * 0.62;+ if (dist2 <= core_r * core_r) {{+ base_alpha = interp_a;+ groove_crown = 1.0;+ }} else {{+ let norm_d = sqrt(dist2) / rad;+ let flank_t = clamp((norm_d - 0.62) / 0.38, 0.0, 1.0);+ let core_env = 1.0 - flank_t * flank_t * (3.0 - 2.0 * flank_t);+ base_alpha = interp_a * core_env;+ groove_crown = 0.55 + 0.45 * core_env;+ eff_load_for_tooth = load * (0.28 + 0.72 * core_env);}}- let tdims = vec2<f32>(textureDimensions(tip_array, 0));- let tcoord = vec2<i32>(clamp(tip_uv * tdims, vec2<f32>(0.0), tdims - vec2<f32>(1.0)));- let tip_a = textureLoad(tip_array, tcoord, 0, 0).a;- cov = cov * tip_a;+ max_local_h = raw_h * groove_crown;+ }} else {{+ let dist = sqrt(dist2);+ let norm_d = dist / rad;+ let aa_edge = 1.0 - clamp((dist - (rad - half_edge_soft)) * inv_edge_soft, 0.0, 1.0);+ base_alpha = interp_a * aa_edge;++ // BristleHybrid mode: modulate hybrid stamp capsule by brush tip texture (or soft radial falloff)+ if (is_hybrid) {{+ if (u.flags1.z != 0u) {{+ let ang = cap.motion.w;+ let ca = cos(-ang);+ let sa = sin(-ang);+ let rel = (doc_pos - p0) / max(rad, 1.0);+ let rot_rel = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);+ let tip_uv = rot_rel * 0.5 + vec2<f32>(0.5);+ if (tip_uv.x < 0.0 || tip_uv.x > 1.0 || tip_uv.y < 0.0 || tip_uv.y > 1.0) {{+ continue;+ }}+ let tdims = vec2<f32>(textureDimensions(tip_array, 0));+ let tcoord = vec2<i32>(clamp(tip_uv * tdims, vec2<f32>(0.0), tdims - vec2<f32>(1.0)));+ let tip_a = textureLoad(tip_array, tcoord, 0, 0).a;+ base_alpha = base_alpha * tip_a;+ }} else {{+ base_alpha = base_alpha * (1.0 - smoothstep(0.35, 1.0, norm_d));+ }}+ }}++ let u_crown = max(0.0, 1.0 - norm_d * norm_d);+ groove_crown = select(0.0, sqrt(u_crown) * (0.35 + 0.65 * u_crown), u_crown > 0.0);+ if (norm_d > 0.60 && norm_d < 0.98) {{+ trough_carve = sin(((norm_d - 0.60) / 0.38) * pi) * 0.36 * bristle_relief;+ }}+ max_local_h = raw_h * (0.14 + 1.02 * groove_crown * (0.42 + 0.58 * bristle_relief));}}- if (cov <= 1e-4) {{+ base_alpha = base_alpha * sel_a;+ if (base_alpha <= 0.002) {{continue;}}- // Evaluate surface heightfield AT MOST ONCE per hit pixel- let pressure = clamp(cap.geom.z, 0.02, 1.0);- let load = clamp(cap.resolved_state.y, 0.0, 1.0);- if (need_surf && !has_surf_h) {{- surf_h = sample_surface_height(doc_pos, cap.motion.x, cap.motion.w);- if (grain_strength > 0.005) {{- surf_tooth = mix(1.0, clamp(0.18 + surf_h * 0.95, 0.0, 1.0), grain_strength);- }}- has_surf_h = true;+ // Same-bristle / same-pass underbed conservative early-out+ if (is_underbed && is_same_pass && stroke_a >= base_alpha && (!impasto_enabled || cur_h >= max_local_h)) {{+ last_arc_u = arc_u;+ continue;+ }}+ if (is_same_bristle && stroke_a >= base_alpha && (!impasto_enabled || cur_h >= max_local_h)) {{+ last_arc_u = arc_u;+ continue;}}- if (dry_brush > 0.005) {{- let p_pow = select(pow(pressure, pen_curve), pressure, pen_is_linear);- let penetration = clamp(p_pow * (0.30 + 0.70 * load), 0.0, 1.0);- let valley_thr = clamp(dry_brush * (1.0 - penetration * 0.72), 0.0, 0.96);- let contact = smoothstep(valley_thr - 0.08, valley_thr + 0.14, surf_h);- cov = cov * contact;- if (cov <= 1e-4) {{- continue;+ // Sample high-DPI canvas surface heightfield (cached across capsules for static modes!)+ var h_canvas = 0.5;+ if (need_surf) {{+ if (has_static_grain) {{+ if (!has_static_h) {{+ static_h_canvas = sample_surface_height(doc_pos, arc_u, cap.strand.y, half_brush_w, 1.0, 0.0);+ has_static_h = true;+ }}+ h_canvas = static_h_canvas;+ }} else {{+ let seg_len = sqrt(ab2);+ let seg_cos = select(1.0, ab.x / seg_len, seg_len > 1e-4);+ let seg_sin = select(0.0, ab.y / seg_len, seg_len > 1e-4);+ h_canvas = sample_surface_height(doc_pos, arc_u, cap.strand.y, half_brush_w, seg_cos, seg_sin);}}+ last_h_canvas = h_canvas;}}- cov = cov * surf_tooth * sel_a;-- var paint_rgb = cap.resolved_rgba.rgb;- var dep_a = clamp(cap.resolved_rgba.a * cov, 0.0, 1.0);+ var tooth_contact = 1.0;+ if (has_grain_or_dry) {{+ let curved_p = select(pow(pressure, pen_curve), pressure, pen_is_linear);+ let tilt_red = 1.0 - tilt_mag * 0.45;+ tooth_contact = evaluate_tooth_contact(+ h_canvas,+ eff_load_for_tooth,+ curved_p,+ tilt_red,+ grain_depth,+ dry_brush,+ effective_dry,+ softness_inv,+ );+ }}+ var src_a = base_alpha * tooth_contact;+ var sr_rgb = mix(cap.rgba0.rgb, cap.rgba1.rgb, t);+ // Watercolor granulation (per-capsule, non-compounding): pigment settles out of suspension+ // into recessed cold-press valleys and drains lightly off raised peaks!if (granulation > 0.005) {{- let valley = 1.0 - surf_h;- let gran_boost = clamp(1.0 + granulation * (valley * 1.75 - 0.45), 0.18, 2.0);- dep_a = clamp(dep_a * gran_boost, 0.0, 1.0);- paint_rgb = clamp(paint_rgb * (1.0 - granulation * valley * 0.14), vec3<f32>(0.0), vec3<f32>(1.0));+ let valley = 1.0 - h_canvas;+ let gran_boost = clamp(1.0 + granulation * (valley * 2.35 - 0.44), 0.16, 2.75);+ src_a = clamp(src_a * gran_boost, 0.0, 1.0);+ sr_rgb = clamp(sr_rgb * (1.0 - granulation * valley * 0.22), vec3<f32>(0.0), vec3<f32>(1.0));}}-- if (use_blur && dep_a > 1e-4) {{- max_blur_f = max(max_blur_f, clamp(blur_str * cov * 0.55, 0.0, 0.85));+ if (src_a <= 0.002) {{+ continue;+ }}+ var strand_h = select(+ max_local_h * (0.35 + 0.65 * tooth_contact),+ max_local_h * (0.45 + 0.55 * tooth_contact),+ is_underbed+ );+ // Subtle non-compounding canvas weave relief ONLY on thin outer paint fringes (buried under thick oil!)+ if (impasto_enabled && grain_depth > 0.01 && strand_h > 0.001) {{+ let paint_cover = clamp(strand_h * 1.45, 0.0, 1.0);+ let thin_weave = pow(1.0 - paint_cover, 2.2) * grain_depth;+ strand_h = max(0.0, strand_h + (h_canvas - 0.5) * thin_weave * 0.06);}}- if (dep_a > 1e-4) {{- let c_lin = srgb_to_lin_fast(paint_rgb);- let inv_d = 1.0 - dep_a;- acc_premul = c_lin * dep_a + acc_premul * inv_d;- acc_a = dep_a + acc_a * inv_d;+ did_paint_hit = true;+ if (use_blur) {{+ max_blur_f = max(max_blur_f, clamp(blur_str * src_a * 0.55, 0.0, 0.85));}}- // Accumulate 3D Impasto Heightfield target in the same pass- if (impasto_enabled && impasto_depth > 0.005) {{- let edge_w = cap.strand.y;- let groove_s = cap.strand.z;- let macro_arch = clamp(1.0 - edge_w * edge_w * 0.82, 0.14, 1.0);- let crown = (1.0 - lat * lat) * (0.55 + 0.45 * bristle_relief * groove_s);- let trough = smoothstep(0.55, 0.92, lat) * (1.0 - smoothstep(0.92, 1.0, lat)) * bristle_relief * 0.22;- let ridge_bump = edge_w * edge_ridge * smoothstep(0.35, 0.88, lat) * 0.35;- let knife_flat = select(1.0, 0.65 + ridge_bump * 1.4, is_knife);- let underbed_scale = select(1.0, 0.55, is_underbed);- let target_h = max(- 0.0,- (crown * macro_arch - trough * 0.55 + ridge_bump)- * knife_flat- * impasto_depth- * 2.4- * (0.30 + 0.70 * load)- * (0.45 + 0.55 * pressure),- );- imp_hit = true;- imp_max_target = max(imp_max_target, target_h);- let blend_h = clamp(cov * underbed_scale * 0.42, 0.0, 0.72);- imp_blend_acc = 1.0 - (1.0 - imp_blend_acc) * (1.0 - blend_h);- imp_build_acc = imp_build_acc + target_h * cov * underbed_scale * 0.025;- imp_smear_cov = 1.0 - (1.0 - imp_smear_cov) * (1.0 - cov * 0.45);+ // Exact pre-Rust same-bristle / same-pass / cross-pass accumulation & 3D trough carving!+ if (is_underbed) {{+ if (is_same_pass) {{+ if (src_a > stroke_a) {{+ if (last_bristle < 0) {{+ // Blend onto existing canvas if cur_col had underlying paint, else overwrite stroke color+ if (cur_col.a > stroke_a + 0.01) {{+ let inc_a = clamp((src_a - stroke_a) / max(0.001, 1.0 - stroke_a), 0.0, 1.0);+ cur_col = composite_pigment_over(cur_col, vec4<f32>(sr_rgb, inc_a), pigment_str);+ }} else {{+ cur_col = vec4<f32>(sr_rgb, max(cur_col.a, src_a));+ }}+ }} else {{+ let fill_w = (src_a - stroke_a) / max(0.001, src_a);+ cur_col = vec4<f32>(mix(cur_col.rgb, sr_rgb, fill_w), max(cur_col.a, src_a));+ }}+ stroke_a = src_a;+ cur_cov = max(cur_cov, src_a);+ }}+ if (impasto_enabled && strand_h > cur_h) {{+ cur_h = strand_h;+ did_impasto_hit = true;+ }}+ }} else {{+ let deposit_a = min(1.0, src_a * 0.94);+ cur_col = composite_pigment_over(cur_col, vec4<f32>(sr_rgb, deposit_a), pigment_str);+ stroke_a = min(1.0, deposit_a + stroke_a * (1.0 - deposit_a));+ cur_cov = min(1.0, cur_cov + deposit_a * (1.0 - cur_cov));+ if (impasto_enabled) {{+ if (mode == 2u) {{+ cur_h = mix(cur_h, max(cur_h * 0.86, strand_h), deposit_a * 0.65);+ }} else {{+ cur_h = cur_h * (1.0 - deposit_a * 0.72) + strand_h * (0.28 + deposit_a * 0.72);+ }}+ did_impasto_hit = true;+ }}+ last_bristle = -1;+ }}+ }} else if (is_same_bristle) {{+ if (src_a > stroke_a) {{+ if (cur_col.a > stroke_a + 0.01) {{+ let inc_a = clamp((src_a - stroke_a) / max(0.001, 1.0 - stroke_a), 0.0, 1.0);+ cur_col = composite_pigment_over(cur_col, vec4<f32>(sr_rgb, inc_a), pigment_str);+ }} else {{+ cur_col = vec4<f32>(sr_rgb, max(cur_col.a, src_a));+ }}+ stroke_a = src_a;+ cur_cov = max(cur_cov, src_a);+ }}+ if (impasto_enabled && strand_h > cur_h) {{+ cur_h = strand_h;+ did_impasto_hit = true;+ }}+ }} else if (is_same_pass) {{+ let over_bed = (last_bristle == -1);+ let max_a = max(stroke_a, src_a);+ let min_a = min(stroke_a, src_a);+ let overlap_pool = select(0.25, 0.35, over_bed) + granulation * 0.65;+ let target_a = min(1.0, max_a + min_a * overlap_pool);+ if (target_a > 0.0005) {{+ let blend_w = select(+ src_a / max(0.001, src_a + stroke_a),+ min(0.92, src_a * 1.15),+ over_bed+ );+ let diff_c = sr_rgb - cur_col.rgb;+ let dist_c2 = dot(diff_c, diff_c);+ var next_rgb: vec3<f32>;+ if (!over_bed && use_pigment_blend && cur_col.a > 0.002 && dist_c2 > 0.038) {{+ next_rgb = mix_pigments_fast_srgb(cur_col.rgb, sr_rgb, blend_w, pigment_str);+ }} else {{+ next_rgb = mix(cur_col.rgb, sr_rgb, blend_w);+ }}+ cur_col = vec4<f32>(next_rgb, max(cur_col.a, target_a));+ stroke_a = target_a;+ cur_cov = max(cur_cov, target_a);+ }}+ if (impasto_enabled) {{+ if (over_bed) {{+ if (trough_carve > 0.01) {{+ cur_h = max(cur_h * (1.0 - trough_carve), strand_h);+ }} else {{+ cur_h = max(cur_h, cur_h * 0.42 + strand_h);+ }}+ if (groove_crown > 0.25) {{+ last_bristle = bristle_idx;+ }}+ }} else {{+ if (trough_carve > 0.01 && strand_h < cur_h) {{+ cur_h = cur_h * (1.0 - trough_carve * 0.35);+ }} else if (strand_h > cur_h) {{+ cur_h = strand_h;+ last_bristle = bristle_idx;+ }}+ }}+ did_impasto_hit = true;+ }}+ }} else {{+ // Cross-pass (new stroke over existing paint or looping pass!):+ // Full 8-band Kubelka-Munk composite + physical wet-paint height re-sculpting!+ let deposit_a = min(1.0, src_a * 0.97);+ cur_col = composite_pigment_over(cur_col, vec4<f32>(sr_rgb, deposit_a), pigment_str);+ stroke_a = min(1.0, deposit_a + stroke_a * (1.0 - deposit_a));+ cur_cov = min(1.0, cur_cov + deposit_a * (1.0 - cur_cov));+ if (impasto_enabled) {{+ if (mode == 2u) {{+ // Pure blender smears & carves subtle bristle grooves into existing impasto+ cur_h = mix(cur_h, max(cur_h * 0.85, strand_h), deposit_a * 0.72);+ }} else {{+ cur_h = cur_h * (1.0 - deposit_a * 0.78) + strand_h * (0.22 + deposit_a * 0.85);+ }}+ did_impasto_hit = true;+ }}+ last_bristle = bristle_idx;}}+ last_arc_u = arc_u;}}- // Perform optional 3x3 blur + ONE perceptual/subtractive Kubelka-Munk composite per hit pixel!- if (acc_a > 1e-4) {{+ if (did_paint_hit) {{+ // Optional 3x3 local softening blur when useBlur is enabledif (use_blur && max_blur_f > 1e-4) {{var sum_rgb = vec3<f32>(0.0);var sum_a = 0.0;@@ -729,33 +1070,20 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{}}}}- let eff_a = clamp(acc_a, 0.0, 1.0);- let batch_rgb = lin_to_srgb_fast(clamp(acc_premul / max(acc_a, 1e-5), vec3<f32>(0.0), vec3<f32>(1.0)));- let next_col = composite_pigment_over(cur_col, vec4<f32>(batch_rgb, eff_a), pigment_str);- cur_col = select(next_col, vec4<f32>(next_col.rgb, base_alpha_lock), alpha_lock);- if (track_cov) {{- cur_cov = clamp(cur_cov + eff_a * (1.0 - cur_cov), 0.0, 1.0);+ if (alpha_lock) {{+ cur_col.a = base_alpha_lock;}}- }}-- if (imp_hit) {{- let mode = u.flags0.w;- if (mode == 2u) {{- cur_h = mix(cur_h, max(cur_h * 0.88, imp_max_target * 0.55), imp_smear_cov);- }} else {{- let max_h = 3.0 * impasto_depth;- let sculpted = mix(cur_h, max(cur_h, imp_max_target), clamp(imp_blend_acc, 0.0, 0.88));- cur_h = clamp(sculpted + imp_build_acc, 0.0, max_h);+ if (u.extra.z < 0.5) {{+ cur_col.a = select(0.0, 1.0, cur_col.a >= 0.5);}}}}- if (u.extra.z < 0.5) {{- cur_col.a = select(0.0, 1.0, cur_col.a >= 0.5);- }}textureStore(dst_color, lp, cur_col);textureStore(dst_height, lp, vec4<f32>(cur_h, 0.0, 0.0, 0.0));if (track_cov) {{- textureStore(dst_cov, lp, vec4<f32>(cur_cov, 0.0, 0.0, 1.0));+ let enc_arc = select(0.0, clamp(last_arc_u * 0.1 + 1.0, 1.0, 65000.0), last_arc_u > -9000.0);+ let enc_br = f32(clamp(last_bristle + 2, 0, 66));+ textureStore(dst_cov, lp, vec4<f32>(cur_cov, enc_arc, enc_br, stroke_a));}}}}"#@@ -1490,8 +1818,8 @@ impl GpuNaturalPaintEngine {dyn_uniform_compute_entry(0, std::mem::size_of::<RasterTileUniforms>()),tex_array_compute_entry(1),tex_array_compute_entry(2),- tex_2d_compute_entry(3),- tex_2d_compute_entry(4),+ tex_2d_filterable_compute_entry(3),+ tex_2d_filterable_compute_entry(4),tex_array_compute_entry(5),storage_compute_entry(6, true),storage_tex_compute_entry(7, wgpu::TextureFormat::Rgba16Float),@@ -1500,6 +1828,7 @@ impl GpuNaturalPaintEngine {storage_compute_entry(10, true),tex_array_compute_entry(11),storage_tex_compute_entry(12, wgpu::TextureFormat::Rgba16Float),+ sampler_compute_entry(13),],});let raster_src = build_natural_paint_raster_wgsl();@@ -1900,8 +2229,9 @@ impl GpuNaturalPaintEngine {if config.is_natural_paint_brush() {let need_wet = config.wet_edge > 0.01;- self.pools- .configure_cmix_post_pools(device, need_wet, need_wet);+ // Always enable cmix_cov (Rgba16Float) for NaturalPaint so cs_raster_natural_paint tracks+ // exact per-pixel (cov, last_arc_u, last_bristle, stroke_a) same-pass/cross-pass state!+ self.pools.configure_cmix_post_pools(device, need_wet, true);let _ = self.dirty_bank.acquire_bristle_buffer_with_id(device,queue,@@ -2099,7 +2429,7 @@ impl GpuNaturalPaintEngine {// Evaluate CSP paint sensors using cached pre-compiled LUTs (ZERO per-frame LUT rebuilds!)let avg_p = capsules.iter().map(|c| c.geom[2]).sum::<f32>() / capsules.len() as f32;let avg_tilt = capsules.iter().map(|c| c.motion[2]).sum::<f32>() / capsules.len() as f32;- let avg_dist = capsules.last().map(|c| c.motion[0]).unwrap_or(0.0);+ let avg_dist = capsules.last().map(|c| c.motion[1]).unwrap_or(0.0);let eff_amount = config.amount_of_paint_sensor.as_ref()@@ -2195,6 +2525,11 @@ impl GpuNaturalPaintEngine {}).unwrap_or(np.dry_brush);+ let init_paint_load = if np.enabled {+ np.paint_load.clamp(0.0, 1.0)+ } else {+ config.amount_of_paint.clamp(0.0, 1.0)+ };let pigment_str = config.effective_pigment_strength();let pickup_u = PickupUniforms {fg_pigment: [@@ -2230,7 +2565,7 @@ impl GpuNaturalPaintEngine {},config.size,if np.auto_clean { 1.0 } else { 0.0 },- 0.0,+ init_paint_load,],grid_info,};@@ -2286,6 +2621,14 @@ impl GpuNaturalPaintEngine {Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),None => -2.0,};+ let contrast_factor = if config.paper_texture_contrast.abs() > 1e-4 {+ (1.0 + config.paper_texture_contrast / 100.0).max(0.05).powi(2)+ } else {+ 1.0+ };+ let brightness_norm = config.paper_texture_brightness / 100.0;+ let rand_rot = (self.stroke_rand_offset[0] * 17.31 + self.stroke_rand_offset[1] * 11.73)+ * std::f32::consts::TAU;raster_jobs.push((slot, *rect));raster_uniforms.push(RasterTileUniforms {tile_info: [@@ -2337,6 +2680,18 @@ impl GpuNaturalPaintEngine {sel_info: [sel_slot_f, sel_default_f, 0.0, 0.0],rect: *rect,bin_info: [bin_start, bin_count, u32::from(track_cov), 0],+ paper_fx: [+ contrast_factor,+ brightness_norm,+ if config.paper_texture_invert { 1.0 } else { 0.0 },+ rand_rot.cos(),+ ],+ paper_off: [+ self.stroke_rand_offset[0] * 512.0,+ self.stroke_rand_offset[1] * 512.0,+ rand_rot.sin(),+ 0.0,+ ],});}@@ -2535,6 +2890,10 @@ impl GpuNaturalPaintEngine {&self.pools.cmix_cov_scratch_view,),},+ wgpu::BindGroupEntry {+ binding: 13,+ resource: wgpu::BindingResource::Sampler(&self.cmix_paper_sampler),+ },],});self.cached_np_raster_bg = Some((raster_key, bg));diff --git a/crates/ink-engine/src/phase2_tests.rs b/crates/ink-engine/src/phase2_tests.rsindex 63bc8f0..778e844 100644--- a/crates/ink-engine/src/phase2_tests.rs+++ b/crates/ink-engine/src/phase2_tests.rs@@ -14,7 +14,8 @@ use crate::memory::{};use crate::tiles::{pack_rgba8_to_1bit, pack_rgba8_to_8bit, rgba16f_to_rgba8_dithered, rgba16f_to_rgba8_lossless,- rgba8_to_rgba16f, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, RectI32, SparseLayerGrid,+ rgba8_to_rgba16f, unpack_1bit_to_rgba8, unpack_8bit_to_rgba8, CowTileDelta, RectI32,+ SparseLayerGrid,TileCoord, TileData, TileFormat, TileKind, TileStorage, BYTES_16F, BYTES_1BIT, BYTES_32BIT,BYTES_8BIT, TILE_PIXELS, TILE_SIZE,};@@ -940,6 +941,54 @@ fn test_zero_copy_ink_roundtrip_wal_recovery_and_timelapse_png() {.unwrap();assert_eq!(wal_px, [0, 0, 0, 255], "Post-checkpoint WAL stroke must replay accurately");+ // 2b. Raster-journal style frames (current state only, no `before`) followed by an eraser+ // that clears the whole tile: replay must remove the tile WITHOUT converting the 1-bit+ // layer to 32-bit color (removal frames carry only a placeholder format byte).+ let mono_fmt = doc.layer("layer-mono").unwrap().grid.format;+ let journal_stroke: Vec<CowTileDelta> = wal_deltas+ .iter()+ .map(|d| CowTileDelta {+ before: None,+ ..d.clone()+ })+ .collect();+ let erased_coord = journal_stroke[0].coord;+ let journal_erase = vec![CowTileDelta {+ layer_id: "layer-mono".to_string(),+ kind: TileKind::Raster,+ coord: erased_coord,+ before: None,+ after: None,+ remote_epoch: 0,+ }];+ let (recovered2, replayed2, _) = replay_recovery_into_document(+ "doc-recovered-2",+ &manifest_json,+ Some(&checkpoint_bytes),+ &[+ WalRawEntry {+ entry_type: 1,+ payload: encode_cow_deltas_to_wal_payload(&journal_stroke, None).unwrap(),+ },+ WalRawEntry {+ entry_type: 1,+ payload: encode_cow_deltas_to_wal_payload(&journal_erase, None).unwrap(),+ },+ ],+ 50,+ )+ .expect("journal replay failed");+ assert_eq!(replayed2, 2);+ let mono_rec = recovered2.layer("layer-mono").unwrap();+ assert_eq!(+ mono_rec.grid.format, mono_fmt,+ "eraser removal frame must not change the layer's storage format"+ );+ assert!(+ mono_rec.grid.get_tile(erased_coord).is_none(),+ "erased tile must be removed on replay"+ );+// 3. Flattened PNG timelapse frame generationlet (fw, fh, png) = doc.render_flattened_png(256, true, None)diff --git a/crates/ink-engine/src/phase5_tests.rs b/crates/ink-engine/src/phase5_tests.rsindex 38c3c17..f2b82fe 100644--- a/crates/ink-engine/src/phase5_tests.rs+++ b/crates/ink-engine/src/phase5_tests.rs@@ -1302,6 +1302,84 @@ fn test_p5_native_mask_mode_stroke_and_gpu_brush_preview() {handle.shutdown();}+#[test]+fn test_p5_brush_studio_live_scratchpad_preview_replays_edits() {+ let _dx12_guard = crate::lock_dx12_test();+ let (handle, _producers) = match EngineHandle::spawn(+ SurfaceTarget::Headless {+ width: 320,+ height: 240,+ },+ EngineConfig {+ doc_width: 512,+ doc_height: 512,+ ..Default::default()+ },+ ) {+ Ok(pair) => pair,+ Err(err) => {+ eprintln!("Skipping DX12 scratchpad preview test (no adapter): {err}");+ return;+ }+ };++ let stroke = crate::types::ScratchpadStrokeInput {+ points: (0..=24)+ .map(|i| {+ let t = i as f32 / 24.0;+ crate::types::ScratchpadStrokePoint {+ x: 40.0 + t * 200.0,+ y: 90.0 + (t * std::f32::consts::TAU).sin() * 26.0,+ pressure: 0.75,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ timestamp_ms: i as f64 * 4.0,+ }+ })+ .collect(),+ color: [0.1, 0.25, 0.85],+ seed: 0x1234_5678,+ };++ let render_with_size = |size: f32| -> usize {+ let (tx, rx) = crossbeam_channel::bounded(1);+ handle.send_command(EngineCommand::RenderScratchpadPreview {+ brush: Box::new(NativeBrushConfig {+ size,+ opacity: 1.0,+ flow: 1.0,+ hardness: 1.0,+ spacing: 0.08,+ ..NativeBrushConfig::default()+ }),+ strokes: vec![stroke.clone()],+ width: 280,+ height: 180,+ reply: tx,+ });+ let (pw, ph, rgba) = rx+ .recv_timeout(Duration::from_secs(5))+ .expect("receive scratchpad preview")+ .expect("scratchpad preview ok");+ assert_eq!((pw, ph), (280, 180));+ rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 20).count()+ };++ let thin_px = render_with_size(6.0);+ let thick_px = render_with_size(36.0);+ assert!(+ thin_px > 200,+ "thin scratchpad stroke must render visible pixels (got {thin_px})"+ );+ assert!(+ thick_px > thin_px * 3,+ "editing brush size from 6px to 36px must visibly widen the recorded stroke ({thin_px} -> {thick_px})"+ );++ handle.shutdown();+}+// ============================================================================// 8. 4096×4096 Heavy 250px Impasto Oil & Wet Mixing Filbert Benchmark// ============================================================================@@ -2070,16 +2148,18 @@ fn test_p5_underbed_bands_do_not_corrupt_bristles_0_to_4() {test_caps.push(GpuBristleCapsule {p0_p1: [x0, yb, x1, yb],geom: [4.0, 4.0, 0.9, 0.8],- strand: [b as f32, 0.1, 0.8, 0.0],- motion: [(step as f32 + 1.0) * 24.0, 24.0, 0.0, 0.0],+ strand: [b as f32, 0.1, 1.0, 0.0],+ motion: [step as f32 * 24.0, (step as f32 + 1.0) * 24.0, 0.0, 0.0],+ phys: [0.8, 0.8, 0.8, 1.0],});// Underbed bands 64..68 travel across bottom RED half (y = 160..200)let yu = 160.0 + b as f32 * 10.0;test_caps.push(GpuBristleCapsule {p0_p1: [x0, yu, x1, yu],geom: [8.0, 8.0, 0.9, 0.6],- strand: [(UNDERBED_SLOT_BASE + b) as f32, 0.2, 0.45, 1.0],- motion: [(step as f32 + 1.0) * 24.0, 24.0, 0.0, 0.0],+ strand: [(UNDERBED_SLOT_BASE + b) as f32, 0.2, 1.0, 1.0],+ motion: [step as f32 * 24.0, (step as f32 + 1.0) * 24.0, 0.0, 0.0],+ phys: [0.6, 0.36, 0.36, 1.0],});}}@@ -2462,3 +2542,498 @@ fn test_p5_natural_paint_gpu_rgba8_pack_matches_cpu_dithered() {"GPU Bayer-dithered RGBA8 pack must match CPU rgba16f_to_rgba8_dithered! max_diff={max_diff}, mean_diff={mean_diff:.5}");}++#[test]+#[ignore]+fn test_p5_visual_natural_paint_verification() {+ let _dx12_guard = crate::lock_dx12_test();+ let out_dir = std::path::PathBuf::from(+ r"C:\Users\sora\.gemini\antigravity\brain\d8d4cafd-4d41-415e-8dcd-c9ac7ae877bf\scratch\renders",+ );+ let _ = std::fs::create_dir_all(&out_dir);++ let save_doc = |renderer: &mut GpuRenderer, doc: &Document, name: &str| {+ let opts = FlattenOptions {+ fill_white_background: true,+ show_checkerboard: false,+ ..Default::default()+ };+ let (w, h, rgba) = renderer+ .render_document_flattened(doc, None, &opts)+ .expect("flatten visual doc");+ let png = crate::io::png_codec::encode_rgba8_to_png(w, h, &rgba).expect("encode png");+ std::fs::write(out_dir.join(name), png).expect("write png");+ };++ let make_curve_pts = |x0: f64, y0: f64, x1: f64, y1: f64, amp: f64, n: usize, w: f32, p0: f32, p1: f32| {+ let mut pts = Vec::with_capacity(n);+ for i in 0..n {+ let t = i as f64 / (n - 1).max(1) as f64;+ let x = x0 + (x1 - x0) * t;+ let y = y0 + (y1 - y0) * t + (t * std::f64::consts::PI).sin() * amp;+ let pressure = (p0 + (p1 - p0) * t as f32) * (0.45 + 0.55 * (t * std::f64::consts::PI).sin() as f32).clamp(0.35, 1.0);+ pts.push(StrokePoint {+ x,+ y,+ pressure: pressure.clamp(0.12, 1.0),+ width: w,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ velocity: 0.4,+ timestamp_ms: i as f64 * 4.0,+ is_corner: false,+ });+ }+ pts+ };++ // Scene 1: Deep Prussian Blue overlapping strokes (Ref Image 1)+ {+ let Some(mut renderer) = make_headless_renderer(768, 512, 768, 512) else {+ return;+ };+ let mut doc = make_doc("vis-blue", 768, 512);+ let lid = doc.layers[0].meta.id.clone();+ let prussian = [0.04, 0.20, 0.42];+ let mut oil = make_oil_impasto_brush(prussian, 64.0);+ oil.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Filbert,+ count: 24,+ clumping: 0.56,+ stiffness: 0.64,+ length: 1.0,+ splay: 0.34,+ irregularity: 0.44,+ edge_ridge: 0.32,+ });+ oil.impasto = Some(ImpastoSettings {+ enabled: true,+ depth: 0.86,+ bristle_relief: 0.90,+ gloss: 0.50,+ relief_contrast: 0.72,+ light_azimuth: 225.0,+ light_elevation: 32.0,+ });+ oil.surface_texture_id = Some("linen-canvas".to_string());+ oil.grain = 0.46;+ oil.texture_density = 0.46;+ oil.paper_texture_scale = 0.85;+ oil.paper_texture_contrast = 24.0;+ oil.natural_paint.as_mut().unwrap().dry_brush = 0.32;++ for (k, (y0, y1, amp)) in [+ (160.0, 90.0, -30.0),+ (230.0, 140.0, -20.0),+ (310.0, 200.0, -15.0),+ (380.0, 260.0, 10.0),+ (430.0, 320.0, 20.0),+ ]+ .iter()+ .enumerate()+ {+ let pts = make_curve_pts(80.0 + k as f64 * 25.0, *y0, 620.0 + k as f64 * 12.0, *y1, *amp, 40, 64.0, 0.88, 0.82);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, oil.clone(), &pts, 100 + k as u32);+ }+ save_doc(&mut renderer, &doc, "scene1_blue_strokes.png");+ }++ // Scene 2: Red & Blue parallel bars (Ref Image 2)+ {+ let Some(mut renderer) = make_headless_renderer(768, 512, 768, 512) else {+ return;+ };+ let mut doc = make_doc("vis-redblue", 768, 512);+ let lid = doc.layers[0].meta.id.clone();++ let make_flat = |fg: [f32; 3]| {+ let mut b = make_oil_impasto_brush(fg, 92.0);+ b.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Flat,+ count: 38,+ clumping: 0.44,+ stiffness: 0.72,+ length: 0.95,+ splay: 0.30,+ irregularity: 0.36,+ edge_ridge: 0.42,+ });+ b.impasto = Some(ImpastoSettings {+ enabled: true,+ depth: 0.84,+ bristle_relief: 0.86,+ gloss: 0.48,+ relief_contrast: 0.74,+ light_azimuth: 225.0,+ light_elevation: 32.0,+ });+ b.surface_texture_id = Some("linen-canvas".to_string());+ b.grain = 0.42;+ b.texture_density = 0.42;+ b.paper_texture_scale = 0.85;+ b.paper_texture_contrast = 24.0;+ b+ };+ let red_b = make_flat([0.92, 0.08, 0.06]);+ let blue_b = make_flat([0.04, 0.36, 0.84]);+ let p_red1 = make_line_points(90.0, 140.0, 720.0, 140.0, 48, 92.0, 0.92);+ let p_red2 = make_line_points(95.0, 200.0, 720.0, 200.0, 48, 92.0, 0.92);+ let p_blu1 = make_line_points(90.0, 290.0, 720.0, 290.0, 48, 92.0, 0.92);+ let p_blu2 = make_line_points(95.0, 355.0, 720.0, 355.0, 48, 92.0, 0.92);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, red_b.clone(), &p_red1, 201);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, red_b, &p_red2, 202);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_b.clone(), &p_blu1, 203);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_b, &p_blu2, 204);+ save_doc(&mut renderer, &doc, "scene2_red_blue_bars.png");+ }++ // Scene 3: Circular Blue Impasto + Yellow Mixing Over Wet Blue (Ref Images 3 & 4)+ {+ let Some(mut renderer) = make_headless_renderer(768, 768, 768, 768) else {+ return;+ };+ let mut doc = make_doc("vis-circle-mix", 768, 768);+ let lid = doc.layers[0].meta.id.clone();++ let mut blue_oil = make_oil_impasto_brush([0.04, 0.24, 0.56], 82.0);+ blue_oil.impasto = Some(ImpastoSettings {+ enabled: true,+ depth: 0.86,+ bristle_relief: 0.90,+ gloss: 0.52,+ relief_contrast: 0.74,+ light_azimuth: 225.0,+ light_elevation: 32.0,+ });+ blue_oil.surface_texture_id = Some("linen-canvas".to_string());+ blue_oil.grain = 0.44;+ blue_oil.texture_density = 0.44;+ blue_oil.paper_texture_scale = 0.85;+ blue_oil.paper_texture_contrast = 24.0;++ // Spiral circle of deep blue oil+ let mut circle_pts = Vec::new();+ for i in 0..140 {+ let t = i as f64 / 139.0;+ let ang = t * std::f64::consts::TAU * 2.2;+ let rad = 220.0 - t * 110.0;+ circle_pts.push(StrokePoint {+ x: 384.0 + ang.cos() * rad,+ y: 384.0 + ang.sin() * rad,+ pressure: 0.90,+ width: 82.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ velocity: 0.4,+ timestamp_ms: i as f64 * 4.0,+ is_corner: false,+ });+ }+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, blue_oil, &circle_pts, 301);++ // Now paint bright Yellow over wet Blue with Creamy Oil Filbert (yellow + blue -> vivid green streaks!)+ let mut yellow_filbert = make_wet_filbert_brush([1.0, 0.92, 0.04], 84.0);+ yellow_filbert.amount_of_paint = 0.72;+ yellow_filbert.color_stretch = 0.85;+ yellow_filbert.natural_paint.as_mut().unwrap().paint_load = 0.72;+ yellow_filbert.natural_paint.as_mut().unwrap().wetness = 0.82;+ yellow_filbert.natural_paint.as_mut().unwrap().pigment_mixing_strength = 0.95;+ yellow_filbert.impasto = Some(ImpastoSettings {+ enabled: true,+ depth: 0.76,+ bristle_relief: 0.82,+ gloss: 0.54,+ relief_contrast: 0.68,+ light_azimuth: 225.0,+ light_elevation: 32.0,+ });+ yellow_filbert.surface_texture_id = Some("linen-canvas".to_string());+ yellow_filbert.grain = 0.36;+ yellow_filbert.texture_density = 0.36;+ yellow_filbert.paper_texture_scale = 0.85;++ let mut yellow_pts = Vec::new();+ for i in 0..80 {+ let t = i as f64 / 79.0;+ let x = 150.0 + t * 440.0 + (t * std::f64::consts::TAU).sin() * 25.0;+ let y = 480.0 - t * 230.0 + (t * std::f64::consts::TAU * 1.5).cos() * 28.0;+ yellow_pts.push(StrokePoint {+ x,+ y,+ pressure: 0.88,+ width: 84.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ velocity: 0.4,+ timestamp_ms: i as f64 * 4.0,+ is_corner: false,+ });+ }+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, yellow_filbert, &yellow_pts, 302);+ save_doc(&mut renderer, &doc, "scene3_circle_and_yellow_mix.png");+ }++ // Scene 4: Showcase of distinct Natural Paint brushes (Rake, Knife, Gouache, Watercolor, Fan, Pastel, Blender)+ {+ let Some(mut renderer) = make_headless_renderer(1024, 1024, 1024, 1024) else {+ return;+ };+ let mut doc = make_doc("vis-showcase", 1024, 1024);+ let lid = doc.layers[0].meta.id.clone();++ // Vertical blue wet paint strip on right side (x=660..840) to test mixing/blending on every brush!+ let mut base_blue = make_oil_impasto_brush([0.08, 0.28, 0.72], 90.0);+ base_blue.impasto.as_mut().unwrap().depth = 0.70;+ let strip_pts = make_line_points(740.0, 50.0, 740.0, 970.0, 64, 90.0, 0.90);+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, base_blue, &strip_pts, 400);++ // 1. Impasto Bristle Oil (Crimson)+ let mut b1 = make_oil_impasto_brush([0.85, 0.14, 0.16], 56.0);+ b1.grain = 0.46;+ b1.texture_density = 0.46;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b1, &make_line_points(70.0, 100.0, 920.0, 100.0, 50, 56.0, 0.88), 401);++ // 2. Dry Bristle Rake (Prussian Blue)+ let mut b2 = make_oil_impasto_brush([0.06, 0.24, 0.52], 56.0);+ b2.bristle.as_mut().unwrap().profile = BristleProfilePreset::Rake;+ b2.bristle.as_mut().unwrap().count = 34;+ b2.bristle.as_mut().unwrap().clumping = 0.58;+ b2.bristle.as_mut().unwrap().irregularity = 0.52;+ b2.natural_paint.as_mut().unwrap().dry_brush = 0.38;+ b2.grain = 0.38;+ b2.texture_density = 0.38;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b2, &make_line_points(70.0, 220.0, 920.0, 220.0, 50, 56.0, 0.85), 402);++ // 3. Palette Knife (Warm Ochre Yellow)+ let mut b3 = make_oil_impasto_brush([0.96, 0.76, 0.12], 62.0);+ b3.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Knife,+ count: 16,+ clumping: 0.05,+ stiffness: 0.96,+ length: 0.65,+ splay: 0.15,+ irregularity: 0.18,+ edge_ridge: 0.92,+ });+ b3.impasto = Some(ImpastoSettings {+ enabled: true,+ depth: 0.92,+ bristle_relief: 0.32,+ gloss: 0.68,+ relief_contrast: 0.82,+ light_azimuth: 225.0,+ light_elevation: 30.0,+ });+ b3.surface_texture_id = Some("coarse-burlap".to_string());+ b3.grain = 0.44;+ b3.texture_density = 0.44;+ b3.natural_paint.as_mut().unwrap().dry_brush = 0.44;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b3, &make_line_points(70.0, 350.0, 920.0, 350.0, 50, 62.0, 0.92), 403);++ // 4. Splayed Bristle Fan (Forest Green)+ let mut b4 = make_oil_impasto_brush([0.14, 0.54, 0.24], 66.0);+ b4.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Fan,+ count: 36,+ clumping: 0.64,+ stiffness: 0.78,+ length: 1.25,+ splay: 0.56,+ irregularity: 0.58,+ edge_ridge: 0.16,+ });+ b4.surface_texture_id = Some("coarse-burlap".to_string());+ b4.grain = 0.46;+ b4.texture_density = 0.46;+ b4.natural_paint.as_mut().unwrap().dry_brush = 0.48;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b4, &make_line_points(70.0, 480.0, 920.0, 480.0, 50, 66.0, 0.86), 404);++ // 5. Soft Oil Pastel (Coral Orange)+ let mut b5 = make_oil_impasto_brush([0.94, 0.42, 0.18], 46.0);+ b5.render_mode = BrushRenderMode::BristleHybrid;+ b5.bristle.as_mut().unwrap().profile = BristleProfilePreset::Flat;+ b5.surface_texture_id = Some("rough-pastel".to_string());+ b5.grain = 0.78;+ b5.texture_density = 0.78;+ b5.paper_texture_contrast = 36.0;+ b5.natural_paint.as_mut().unwrap().dry_brush = 0.66;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b5, &make_line_points(70.0, 610.0, 920.0, 610.0, 50, 46.0, 0.72), 405);++ // 6. Dry Bristle Blender (Smearing right across the blue strip!)+ let mut b6 = make_oil_impasto_brush([1.0, 1.0, 1.0], 62.0);+ b6.bristle.as_mut().unwrap().profile = BristleProfilePreset::Fan;+ b6.mixing_mode = NaturalMixingMode::Smear;+ b6.amount_of_paint = 0.0;+ b6.color_stretch = 0.85;+ b6.natural_paint.as_mut().unwrap().paint_load = 0.0;+ b6.natural_paint.as_mut().unwrap().depletion_rate = 0.0;+ b6.natural_paint.as_mut().unwrap().wetness = 0.92;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b6, &make_line_points(680.0, 740.0, 960.0, 740.0, 40, 62.0, 0.88), 406);++ // 7. Granulating Watercolor (Turquoise on separate layer so no impasto lighting)+ let mut b7 = make_wet_filbert_brush([0.08, 0.56, 0.74], 54.0);+ b7.bristle.as_mut().unwrap().profile = BristleProfilePreset::Round;+ b7.flow = 0.58;+ b7.opacity = 0.72;+ b7.density_of_paint = 0.65;+ b7.wet_edge = 0.58;+ b7.wet_edge_radius = 3.0;+ b7.impasto = None;+ b7.surface_texture_id = Some("cold-press-watercolor".to_string());+ b7.grain = 0.56;+ b7.texture_density = 0.56;+ b7.natural_paint.as_mut().unwrap().granulation = 0.76;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, b7, &make_line_points(70.0, 880.0, 640.0, 880.0, 50, 54.0, 0.82), 407);++ // Keep strong impasto light on showcase layer+ doc.layer_mut(&lid).unwrap().meta.impasto_light = Some(ImpastoLayerLight {+ enabled: true,+ depth: 0.82,+ gloss: 0.50,+ relief_contrast: 0.72,+ light_azimuth: 225.0,+ light_elevation: 32.0,+ });+ save_doc(&mut renderer, &doc, "scene4_showcase.png");+ }++ // Scene 5: Aqueous & Matte Natural Paint brushes (Watercolor, Sumi Ink, Velvet Gouache, Matte Casein, Heavy Body Acrylic, Wide Hog Flat)+ {+ let Some(mut renderer) = make_headless_renderer(1024, 1024, 1024, 1024) else {+ return;+ };+ let mut doc = make_doc("vis-matte-water", 1024, 1024);+ let lid = doc.layers[0].meta.id.clone();++ // 1. Granulating Watercolor (Cerulean Blue + overlapping Magenta wash -> granulation + wet edge + purple mix!)+ let mut wc1 = make_wet_filbert_brush([0.08, 0.46, 0.78], 62.0);+ wc1.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Round,+ count: 28,+ clumping: 0.14,+ stiffness: 0.32,+ length: 1.35,+ splay: 0.52,+ irregularity: 0.22,+ edge_ridge: 0.05,+ });+ wc1.flow = 0.58;+ wc1.opacity = 0.72;+ wc1.density_of_paint = 0.65;+ wc1.wet_edge = 0.58;+ wc1.wet_edge_radius = 3.0;+ wc1.impasto = None;+ wc1.surface_texture_id = Some("cold-press-watercolor".to_string());+ wc1.grain = 0.56;+ wc1.texture_density = 0.56;+ wc1.natural_paint.as_mut().unwrap().dry_brush = 0.14;+ wc1.natural_paint.as_mut().unwrap().granulation = 0.76;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, wc1.clone(), &make_line_points(80.0, 120.0, 920.0, 120.0, 48, 62.0, 0.78), 501);+ wc1.fg_color = [0.82, 0.18, 0.48];+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, wc1, &make_line_points(280.0, 80.0, 740.0, 180.0, 40, 56.0, 0.72), 502);++ // 2. Sumi Ink Wash (Deep Carbon Sumi with dry flying-white tail!)+ let mut sumi = make_wet_filbert_brush([0.06, 0.07, 0.09], 56.0);+ sumi.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Round,+ count: 26,+ clumping: 0.32,+ stiffness: 0.42,+ length: 1.4,+ splay: 0.48,+ irregularity: 0.36,+ edge_ridge: 0.08,+ });+ sumi.flow = 0.82;+ sumi.opacity = 0.90;+ sumi.density_of_paint = 0.86;+ sumi.wet_edge = 0.48;+ sumi.wet_edge_radius = 2.5;+ sumi.impasto = None;+ sumi.surface_texture_id = Some("cold-press-watercolor".to_string());+ sumi.grain = 0.50;+ sumi.texture_density = 0.50;+ sumi.natural_paint.as_mut().unwrap().depletion_rate = 0.38;+ sumi.natural_paint.as_mut().unwrap().dry_brush = 0.42;+ sumi.natural_paint.as_mut().unwrap().granulation = 0.58;+ let sumi_pts: Vec<StrokePoint> = (0..56).map(|i| {+ let t = i as f32 / 55.0;+ StrokePoint {+ x: (80.0 + t * 860.0) as f64,+ y: (310.0 + (t * 4.5).sin() * 22.0) as f64,+ pressure: (0.95 - t * 0.55).max(0.25),+ width: 56.0,+ tilt_x: 0.0,+ tilt_y: 0.0,+ twist: 0.0,+ velocity: 0.5,+ timestamp_ms: i as f64 * 4.0,+ is_corner: false,+ }+ }).collect();+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, sumi, &sumi_pts, 503);++ // 3. Velvet Gouache (Rich Opaque Matte Terracotta + Cream overlap)+ let mut gouache = make_wet_filbert_brush([0.78, 0.32, 0.20], 54.0);+ gouache.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Filbert,+ count: 34,+ clumping: 0.18,+ stiffness: 0.48,+ length: 1.05,+ splay: 0.32,+ irregularity: 0.20,+ edge_ridge: 0.08,+ });+ gouache.amount_of_paint = 0.88;+ gouache.density_of_paint = 0.96;+ gouache.impasto = None;+ gouache.surface_texture_id = Some("gesso-board".to_string());+ gouache.grain = 0.28;+ gouache.texture_density = 0.28;+ gouache.natural_paint.as_mut().unwrap().paint_load = 0.88;+ gouache.natural_paint.as_mut().unwrap().dry_brush = 0.18;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, gouache.clone(), &make_line_points(80.0, 500.0, 920.0, 500.0, 48, 54.0, 0.88), 504);+ gouache.fg_color = [0.95, 0.88, 0.72];+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, gouache, &make_line_points(260.0, 465.0, 720.0, 535.0, 40, 46.0, 0.80), 505);++ // 4. Matte Casein & Tempera (Deep Emerald + Gold Ochre)+ let mut casein = make_wet_filbert_brush([0.12, 0.42, 0.32], 54.0);+ casein.render_mode = BrushRenderMode::BristleHybrid;+ casein.amount_of_paint = 0.86;+ casein.density_of_paint = 0.96;+ casein.impasto = None;+ casein.surface_texture_id = Some("gesso-board".to_string());+ casein.grain = 0.36;+ casein.texture_density = 0.36;+ casein.natural_paint.as_mut().unwrap().paint_load = 0.86;+ casein.natural_paint.as_mut().unwrap().dry_brush = 0.36;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, casein, &make_line_points(80.0, 690.0, 920.0, 690.0, 48, 54.0, 0.85), 506);++ // 5. Heavy Body Acrylic (Cobalt Blue on separate subtle satin impasto layer? Draw flat + Wide Hog Flat below)+ let mut acrylic = make_oil_impasto_brush([0.16, 0.34, 0.82], 58.0);+ acrylic.bristle = Some(BristleSettings {+ profile: BristleProfilePreset::Flat,+ count: 30,+ clumping: 0.38,+ stiffness: 0.76,+ length: 0.90,+ splay: 0.25,+ irregularity: 0.30,+ edge_ridge: 0.28,+ });+ acrylic.impasto = None;+ acrylic.surface_texture_id = Some("fine-cotton".to_string());+ acrylic.grain = 0.32;+ acrylic.texture_density = 0.32;+ run_natural_paint_stroke(&mut renderer, &mut doc, &lid, acrylic, &make_line_points(80.0, 860.0, 920.0, 860.0, 48, 58.0, 0.88), 507);++ // Keep layer matte (no impasto light) so Watercolor, Sumi, Gouache, Casein show true matte/water look+ doc.layer_mut(&lid).unwrap().meta.impasto_light = None;+ save_doc(&mut renderer, &doc, "scene5_matte_and_water.png");+ }+}diff --git a/crates/ink-engine/src/stroke/spline.rs b/crates/ink-engine/src/stroke/spline.rsindex 7c9fefa..73e0052 100644--- a/crates/ink-engine/src/stroke/spline.rs+++ b/crates/ink-engine/src/stroke/spline.rs@@ -120,7 +120,7 @@ pub fn centripetal_catmull_rom_to_bezier(let scale = (1.0 - tension.clamp(0.0, 1.0)).max(0.0);// Incoming tangent at p1- let (mut t1x, mut t1y) = if left_corner || d01 < 1e-3 {+ let (t1x, t1y) = if left_corner || d01 < 1e-3 {((p2.x - p1.x) * scale, (p2.y - p1.y) * scale)} else {let m1x = ((p1.x - p0.x) / dt0 - (p2.x - p0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1) * dt1;@@ -129,7 +129,7 @@ pub fn centripetal_catmull_rom_to_bezier(};// Outgoing tangent at p2- let (mut t2x, mut t2y) = if right_corner || d23 < 1e-3 {+ let (t2x, t2y) = if right_corner || d23 < 1e-3 {((p2.x - p1.x) * scale, (p2.y - p1.y) * scale)} else {let m2x = ((p2.x - p1.x) / dt1 - (p3.x - p1.x) / (dt1 + dt2) + (p3.x - p2.x) / dt2) * dt1;@@ -137,32 +137,47 @@ pub fn centripetal_catmull_rom_to_bezier((m2x * scale, m2y * scale)};- // Clamp handle lengths to 0.48 * d12 to completely eliminate cusps and overshoot loops+ // Clamp handle lengths to 0.48 * d12 and prevent backward-pointing handles (hairpin+ // overshoot loops when two knots nearly reverse without an explicit sharp corner).+ let chord_ux = (p2.x - p1.x) / d12;+ let chord_uy = (p2.y - p1.y) / d12;let max_handle = 0.48 * d12;- let h1x = t1x / 3.0;- let h1y = t1y / 3.0;++ let mut h1x = t1x / 3.0;+ let mut h1y = t1y / 3.0;+ let h1_fwd = h1x * chord_ux + h1y * chord_uy;+ if h1_fwd < 0.0 {+ // Project out backward component so cp1 never shoots behind p1 to create a loop+ h1x -= h1_fwd * chord_ux;+ h1y -= h1_fwd * chord_uy;+ }let h1_len = h1x.hypot(h1y);if h1_len > max_handle && h1_len > 1e-6 {let f = max_handle / h1_len;- t1x *= f;- t1y *= f;+ h1x *= f;+ h1y *= f;}- let h2x = t2x / 3.0;- let h2y = t2y / 3.0;+ let mut h2x = t2x / 3.0;+ let mut h2y = t2y / 3.0;+ let h2_fwd = h2x * chord_ux + h2y * chord_uy;+ if h2_fwd < 0.0 {+ h2x -= h2_fwd * chord_ux;+ h2y -= h2_fwd * chord_uy;+ }let h2_len = h2x.hypot(h2y);if h2_len > max_handle && h2_len > 1e-6 {let f = max_handle / h2_len;- t2x *= f;- t2y *= f;+ h2x *= f;+ h2y *= f;}CubicBezierSegment {p0: p1,- cp1x: p1.x + t1x / 3.0,- cp1y: p1.y + t1y / 3.0,- cp2x: p2.x - t2x / 3.0,- cp2y: p2.y - t2y / 3.0,+ cp1x: p1.x + h1x,+ cp1y: p1.y + h1y,+ cp2x: p2.x - h2x,+ cp2y: p2.y - h2y,p3: p2,}}@@ -197,8 +212,15 @@ pub fn generate_provisional_segment(let m1y = ((p1.y - prev.y) / dt0 - (p2.y - prev.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1) * dt1;let max_handle = 0.48 * d12;+ let chord_ux = chord_x / d12;+ let chord_uy = chord_y / d12;let mut h1x = m1x / 3.0;let mut h1y = m1y / 3.0;+ let h1_fwd = h1x * chord_ux + h1y * chord_uy;+ if h1_fwd < 0.0 {+ h1x -= h1_fwd * chord_ux;+ h1y -= h1_fwd * chord_uy;+ }let h1_len = h1x.hypot(h1y);if h1_len > max_handle && h1_len > 1e-6 {let f = max_handle / h1_len;diff --git a/crates/ink-engine/src/stroke/stabilizer.rs b/crates/ink-engine/src/stroke/stabilizer.rsindex d6dc6ac..7977df8 100644--- a/crates/ink-engine/src/stroke/stabilizer.rs+++ b/crates/ink-engine/src/stroke/stabilizer.rs@@ -1,15 +1,17 @@//! Native Rust port of `src/engine/InputStabilizer.ts` + CSP Post-Correction.//!-//! Preserves 100% behavioral parity with InkStudio's CSP-calibrated stabilizer:+//! CSP-calibrated input stabilizer://! - 1-Euro asymmetric attack/decay filter for pen pressure//! - CSP stabilization slider (0..50) mapped via `baseLengthPx = 3.5 + 23.5*t + 21.0*t^2`//! - Velocity-adaptive tightening so fast gestures never rubber-band-//! - Isotropic 3-stage exponential smoothing cascade (zero axis anisotropy on diagonals)-//! - Frenet-frame lateral twitch damping (suppresses 1–2 sample lateral micro-spikes)-//! - Targeted hardware backtrack spike guard (rejects transient stylus jump-backs)-//! - Sharp-corner snapping (`sharpCorners`) with smooth bounded `CornerConvergencePlan`-//! sub-steps (never hard-teleporting)-//! - Full-tail catch-up target (`get_catch_up_target`) for exact pen-lift convergence+//! - Strictly isotropic 3-stage exponential smoothing cascade (zero axis/tangent locking+//! and zero directional anisotropy on diagonals or curves)+//! - Targeted 1-sample hardware backtrack & lift-off twitch guards (rejects transient+//! digitizer jump-backs and near-zero-pressure nib lift wobbles without fighting real turns)+//! - Confirmed sharp-corner snapping (`sharpCorners`) with bounded `CornerConvergencePlan`+//! sub-steps (requires sustained outgoing travel or decisive excursion, never firing on+//! single-packet micro-jitter or stroke-start landing skids)+//! - Curvature-preserving cubic Bézier pen-up catch-up (`flush_catch_up`)//! - CSP Post-Correction (`apply_csp_post_correction`, 0..5 passes preserving sharp corners)use super::StrokePoint;@@ -152,19 +154,22 @@ pub struct InputStabilizer {last_raw_y: f64,last_timestamp_ms: f64,last_pressure: f32,+ last_raw_pressure: f32,last_tilt_x: f32,last_tilt_y: f32,last_twist: f32,- // Velocity & Frenet tangent tracking+ // Velocity & tangent tracking (used for lookahead & spike rejection, never anisotropic damping)ema_vel_doc_per_ms: f64,tangent_x: f64,tangent_y: f64,has_tangent: bool,+ total_travel_screen: f64,- // Backtrack spike guard & sharp-corner state+ // Backtrack/lift-off spike guard & sharp-corner staterecent_raw: Vec<RawEntry>,backtrack_hold_count: u32,+ liftoff_hold_count: u32,initialized: bool,sample_count: u64,last_corner_sample: u64,@@ -189,6 +194,7 @@ impl InputStabilizer {last_raw_y: 0.0,last_timestamp_ms: 0.0,last_pressure: 0.5,+ last_raw_pressure: 0.5,last_tilt_x: 0.0,last_tilt_y: 0.0,last_twist: 0.0,@@ -196,8 +202,10 @@ impl InputStabilizer {tangent_x: 1.0,tangent_y: 0.0,has_tangent: false,+ total_travel_screen: 0.0,recent_raw: Vec::with_capacity(16),backtrack_hold_count: 0,+ liftoff_hold_count: 0,initialized: false,sample_count: 0,last_corner_sample: 0,@@ -212,9 +220,11 @@ impl InputStabilizer {self.pressure_filter.reset();self.initialized = false;self.has_tangent = false;+ self.total_travel_screen = 0.0;self.ema_vel_doc_per_ms = 0.0;self.recent_raw.clear();self.backtrack_hold_count = 0;+ self.liftoff_hold_count = 0;self.sample_count = 0;self.last_corner_sample = 0;}@@ -251,6 +261,14 @@ impl InputStabilizer {3.5 + 23.5 * t + 21.0 * t * t}+ /// Per-stage time constant (ms) bounding how long the stabilized tip may trail a pen that+ /// has slowed down or stopped. Grows with the stabilization level so heavy settings still+ /// glide, but never drags (level 6 ≈ 13 ms, level 20 ≈ 28 ms, level 50 ≈ 61 ms per stage).+ #[inline]+ pub fn settle_tau_ms(stabilization: f32) -> f64 {+ 6.0 + 1.1 * (stabilization as f64).clamp(0.0, 50.0)+ }+/// Processes a single incoming pointer sample in document space.#[allow(clippy::too_many_arguments)]pub fn process(@@ -284,9 +302,13 @@ impl InputStabilizer {self.last_raw_y = raw_y;self.last_timestamp_ms = timestamp_ms;self.last_pressure = safe_p;+ self.last_raw_pressure = safe_p;self.last_tilt_x = tilt_x;self.last_tilt_y = tilt_y;self.last_twist = twist;+ self.total_travel_screen = 0.0;+ self.backtrack_hold_count = 0;+ self.liftoff_hold_count = 0;self.sample_count = 1;self.recent_raw.clear();self.recent_raw.push(RawEntry {@@ -318,31 +340,56 @@ impl InputStabilizer {let raw_dist_doc = raw_dx.hypot(raw_dy);let raw_dist_screen = raw_dist_doc * safe_zoom;- // 1. Targeted hardware backtrack spike guard:- // If the stylus is moving steadily forward and a single isolated packet jumps sharply- // backward (>= 135 deg reversal) for just 1 sample during fast motion, hold it for 1 sample- // so it doesn't inject a V-glitch hook into the stroke.+ // 1. Targeted hardware spike & stylus lift-off twitch guards:+ // (a) Single-packet backward reversal during brisk motion (>= 141 deg): hold for 1 sample+ // so isolated digitizer jump-backs never inject a V-glitch hook.+ // (b) Stylus lift-off wobble: when pressure collapses sharply to near-zero (nib breaking+ // contact with the tablet) and the coil reports a sudden sharp sideways/backward jump+ // (> 75 deg from the stroke trajectory), hold so pen-up never draws a hook.+ // Clean tapered flicks along the stroke direction (fwd_dot > 0.25) pass untouched.let mut eff_x = raw_x;let mut eff_y = raw_y;- if self.has_tangent && raw_dist_screen > 2.0 && self.ema_vel_doc_per_ms * safe_zoom > 0.35 {+ let mut held_glitch = false;+ let is_liftoff_pressure = (safe_p <= 0.035 && self.last_raw_pressure > 0.06)+ || (safe_p <= 0.015 && self.last_raw_pressure <= 0.035);++ if self.has_tangent && self.total_travel_screen >= 6.0 && raw_dist_screen > 1.5 {let ux = raw_dx / raw_dist_doc.max(1e-6);let uy = raw_dy / raw_dist_doc.max(1e-6);let fwd_dot = ux * self.tangent_x + uy * self.tangent_y;- if fwd_dot < -0.78 && self.backtrack_hold_count == 0 {- // Transient 1-sample reversal: damp sharply rather than reversing trajectory++ if is_liftoff_pressure && fwd_dot < 0.25 && self.liftoff_hold_count < 2 {+ self.liftoff_hold_count += 1;+ eff_x = self.last_raw_x;+ eff_y = self.last_raw_y;+ held_glitch = true;+ } else if raw_dist_screen > 2.0+ && self.ema_vel_doc_per_ms * safe_zoom > 0.35+ && fwd_dot < -0.78+ && self.backtrack_hold_count == 0+ {self.backtrack_hold_count = 1;eff_x = self.last_raw_x;eff_y = self.last_raw_y;+ held_glitch = true;} else {self.backtrack_hold_count = 0;+ if !is_liftoff_pressure {+ self.liftoff_hold_count = 0;+ }}} else {self.backtrack_hold_count = 0;+ if !is_liftoff_pressure {+ self.liftoff_hold_count = 0;+ }}let step_dx = eff_x - self.last_raw_x;let step_dy = eff_y - self.last_raw_y;let step_dist_doc = step_dx.hypot(step_dy);+ let step_dist_screen = step_dist_doc * safe_zoom;+ self.total_travel_screen += step_dist_screen;let inst_vel = step_dist_doc / dt_ms;self.ema_vel_doc_per_ms = self.ema_vel_doc_per_ms * 0.72 + inst_vel * 0.28;@@ -356,15 +403,28 @@ impl InputStabilizer {self.last_tilt_y = smooth_ty;self.last_twist = twist;self.last_pressure = filtered_p;+ self.last_raw_pressure = safe_p;let level = self.config.stabilization.clamp(0.0, 50.0);// Zero stabilization fast-path: pass raw pointer directlyif level <= 0.001 {- if step_dist_doc > 1e-4 {- self.tangent_x = step_dx / step_dist_doc;- self.tangent_y = step_dy / step_dist_doc;- self.has_tangent = true;+ if step_dist_doc > 1e-4 && self.total_travel_screen >= 2.0 {+ let nx = step_dx / step_dist_doc;+ let ny = step_dy / step_dist_doc;+ if self.has_tangent {+ let bx = self.tangent_x * 0.55 + nx * 0.45;+ let by = self.tangent_y * 0.55 + ny * 0.45;+ let blen = bx.hypot(by);+ if blen > 1e-5 {+ self.tangent_x = bx / blen;+ self.tangent_y = by / blen;+ }+ } else {+ self.tangent_x = nx;+ self.tangent_y = ny;+ self.has_tangent = true;+ }}self.s1_x = eff_x;self.s1_y = eff_y;@@ -377,7 +437,9 @@ impl InputStabilizer {self.last_raw_x = eff_x;self.last_raw_y = eff_y;self.last_timestamp_ms = timestamp_ms;- self.push_raw_history(eff_x, eff_y);+ if !held_glitch {+ self.push_raw_history(eff_x, eff_y);+ }return StabilizedSample {x: eff_x,y: eff_y,@@ -388,14 +450,20 @@ impl InputStabilizer {timestamp_ms,velocity: self.ema_vel_doc_per_ms,is_corner: false,- should_emit: step_dist_doc > 0.05 || (safe_p - filtered_p).abs() > 0.05,+ should_emit: !held_glitch+ && (step_dist_doc > 0.05 || (safe_p - filtered_p).abs() > 0.05),corner_convergence: None,};}- // 2. Sharp-corner detection (before smoothing cascade swallows the apex!)+ // 2. Confirmed sharp-corner detection (before smoothing cascade swallows a genuine apex).+ // Never snaps during initial touchdown travel or during lift-off pressure collapse,+ // and requires either sustained multi-sample outgoing motion or a decisive large turn.let mut corner_convergence: Option<CornerConvergencePlan> = None;if self.config.sharp_corners+ && !held_glitch+ && !is_liftoff_pressure+ && self.total_travel_screen >= 12.0&& self.recent_raw.len() >= 3&& self.sample_count.saturating_sub(self.last_corner_sample) >= 3{@@ -433,7 +501,13 @@ impl InputStabilizer {self.last_raw_x = eff_x;self.last_raw_y = eff_y;self.last_timestamp_ms = timestamp_ms;- self.push_raw_history(eff_x, eff_y);+ // Reset raw history to start cleanly from the snapped apex+ self.recent_raw.clear();+ self.recent_raw.push(RawEntry {+ x: apex_x,+ y: apex_y,+ });+ self.recent_raw.push(RawEntry { x: eff_x, y: eff_y });return StabilizedSample {x: apex_x,y: apex_y,@@ -450,30 +524,17 @@ impl InputStabilizer {}}- // 3. Rotation-invariant Frenet-frame lateral twitch detection & damping- // Matches `InputStabilizer.ts` lines 632-670: keeps tangent tracking crisp while- // strongly attenuating sudden 1–2 sample lateral micro-spikes and hardware twitches- // without introducing any X/Y axis anisotropy on diagonals.- let mut lateral_spike_energy = 0.0f64;+ // 3. Step-length guard (strictly scalar so filtering remains 100% isotropic):+ // Prevents a sudden isolated perpendicular spike from inflating the scalar gain `k`+ // across all 3 stages, while applying the EXACT SAME gain to X and Y so the filter+ // can NEVER lock onto an axis or bend a diagonal line!let mut effective_step_doc = step_dist_doc;if self.has_tangent && step_dist_doc > 1e-4 {let along = step_dx * self.tangent_x + step_dy * self.tangent_y;- let nx = -self.tangent_y;- let ny = self.tangent_x;- let lateral = step_dx * nx + step_dy * ny;- let lateral_screen = lateral.abs() * safe_zoom;- let along_screen = along.max(0.0) * safe_zoom;-- // Prevent sudden perpendicular twitch spikes from inflating spatial alpha along the strokeeffective_step_doc = step_dist_doc.min(along.max(0.0).max(0.62 * step_dist_doc));-- if lateral_screen > 1.5 {- let ratio = lateral_screen / (along_screen + 1.5);- lateral_spike_energy = clamp_f64((ratio - 0.35) * 0.85, 0.0, 1.0);- }}- // 4. Velocity-adaptive CSP-calibrated isotropic 3-stage exponential cascade+ // 4. Velocity-adaptive CSP-calibrated strictly isotropic 3-stage exponential cascade// Matches CSP steady-state lag bounds:// - Level 1: ~3.5px screen lag// - Level 18..20: ~14..16px screen lag (always <= 18px on smooth sine waves)@@ -491,43 +552,26 @@ impl InputStabilizer {let stage_len = (eff_len_doc / 3.0).max(1e-4);let dist_to_target = (eff_x - self.s1_x).hypot(eff_y - self.s1_y);let ds = effective_step_doc.max(dist_to_target * 0.12);- let k_along = clamp_f64(ds / (ds + stage_len), 0.04, 0.92);-- if lateral_spike_energy > 0.05 && self.has_tangent {- let tx = self.tangent_x;- let ty = self.tangent_y;- let nx = -ty;- let ny = tx;- let perp_stage_len = stage_len * (1.0 + 5.8 * lateral_spike_energy);- let k_perp = clamp_f64(ds / (ds + perp_stage_len), 0.02, 0.65);-- let advance = |sx: f64, sy: f64, gx: f64, gy: f64| -> (f64, f64) {- let ex = gx - sx;- let ey = gy - sy;- let e_along = ex * tx + ey * ty;- let e_perp = ex * nx + ey * ny;- let d_along = k_along * e_along;- let d_perp = k_perp * e_perp;- (sx + d_along * tx + d_perp * nx, sy + d_along * ty + d_perp * ny)- };-- let (n1x, n1y) = advance(self.s1_x, self.s1_y, eff_x, eff_y);- self.s1_x = n1x;- self.s1_y = n1y;- let (n2x, n2y) = advance(self.s2_x, self.s2_y, self.s1_x, self.s1_y);- self.s2_x = n2x;- self.s2_y = n2y;- let (n3x, n3y) = advance(self.s3_x, self.s3_y, self.s2_x, self.s2_y);- self.s3_x = n3x;- self.s3_y = n3y;- } else {- self.s1_x += (eff_x - self.s1_x) * k_along;- self.s1_y += (eff_y - self.s1_y) * k_along;- self.s2_x += (self.s1_x - self.s2_x) * k_along;- self.s2_y += (self.s1_y - self.s2_y) * k_along;- self.s3_x += (self.s2_x - self.s3_x) * k_along;- self.s3_y += (self.s2_y - self.s3_y) * k_along;- }+ // Time-based convergence floor. The distance-driven gain above tends to zero as the+ // residual lag shrinks, so once the hand slows or stops the line used to creep toward+ // the pen asymptotically (~400 ms at level 6) — the "rubbery" drag inkers complain+ // about. A per-millisecond time constant guarantees a bounded settle time and makes the+ // settle feel identical at 60 Hz mouse, 240 Hz Windows Ink, and 1 kHz WinTab rates.+ // While the pen is still travelling (slow careful lines, tremor) the floor relaxes 2.5x so+ // jitter smoothing is preserved; it bites fully only once the pen has actually stopped.+ let motion = clamp_f64(inst_vel * safe_zoom / 0.08, 0.0, 1.0);+ let settle_tau_ms = Self::settle_tau_ms(level) * (1.0 + 1.5 * motion);+ let k_time = 1.0 - (-dt_ms / settle_tau_ms).exp();+ let k = clamp_f64((ds / (ds + stage_len)).max(k_time), 0.0, 0.92);++ // Strictly isotropic 3-stage convex cascade: identical scalar gain in every direction+ // (zero axis bias, zero tangent lock-in, zero elbowing on diagonals or curves).+ self.s1_x += (eff_x - self.s1_x) * k;+ self.s1_y += (eff_y - self.s1_y) * k;+ self.s2_x += (self.s1_x - self.s2_x) * k;+ self.s2_y += (self.s1_y - self.s2_y) * k;+ self.s3_x += (self.s2_x - self.s3_x) * k;+ self.s3_y += (self.s2_y - self.s3_y) * k;// Hard lag leash so smooth sine waves at medium stabilization (18..20) never exceed CSP ceilinglet max_leash_doc = (base_len_screen * 1.12) / safe_zoom;@@ -546,8 +590,9 @@ impl InputStabilizer {let out_dy = self.s3_y - self.last_out_y;let out_dist_doc = out_dx.hypot(out_dy);- // Update smooth Frenet tangent from stabilized motion (fallback to raw motion at start)- if out_dist_doc > (0.35 / safe_zoom) {+ // Update smooth tangent ONLY from meaningful stabilized output motion (never from a+ // 0.5px raw touchdown micro-step, which can point in an arbitrary quantized direction).+ if out_dist_doc > (0.5 / safe_zoom) && self.total_travel_screen >= 3.0 {let nx = out_dx / out_dist_doc;let ny = out_dy / out_dist_doc;if self.has_tangent {@@ -563,10 +608,6 @@ impl InputStabilizer {self.tangent_y = ny;self.has_tangent = true;}- } else if !self.has_tangent && step_dist_doc > (0.5 / safe_zoom) {- self.tangent_x = step_dx / step_dist_doc;- self.tangent_y = step_dy / step_dist_doc;- self.has_tangent = true;}let min_emit_doc = (0.35 / safe_zoom).max(0.05);@@ -579,7 +620,9 @@ impl InputStabilizer {self.last_raw_x = eff_x;self.last_raw_y = eff_y;self.last_timestamp_ms = timestamp_ms;- self.push_raw_history(eff_x, eff_y);+ if !held_glitch {+ self.push_raw_history(eff_x, eff_y);+ }StabilizedSample {x: self.s3_x,@@ -611,7 +654,10 @@ impl InputStabilizer {Some((self.last_raw_x, self.last_raw_y, dist))}- /// Generates smooth catch-up samples from `last_out` to `last_raw` on pen-up.+ /// Generates curvature-preserving cubic Bézier catch-up samples from `last_out` (`s3`)+ /// through the cascade state `(s2, s1)` to `last_raw` on pen-up.+ /// Guarantees C1 tangent continuity at `last_out`, zero overshoot (convex hull property),+ /// and exact convergence onto the final lift coordinate without straight-chord corner cutting.pub fn flush_catch_up(&mut self, final_timestamp_ms: f64) -> Vec<StabilizedSample> {let Some((tx, ty, dist)) = self.get_catch_up_target() else {return Vec::new();@@ -620,15 +666,24 @@ impl InputStabilizer {let step_len = (6.0 / safe_zoom).max(1.5);let steps = ((dist / step_len).ceil() as usize).clamp(1, 16);let mut out = Vec::with_capacity(steps);- let sx = self.last_out_x;- let sy = self.last_out_y;+ let p0x = self.last_out_x;+ let p0y = self.last_out_y;+ let p1x = self.s2_x;+ let p1y = self.s2_y;+ let p2x = self.s1_x;+ let p2y = self.s1_y;let start_t = self.last_timestamp_ms;let dt_total = (final_timestamp_ms - start_t).max(1.0);for i in 1..=steps {- let frac = i as f64 / steps as f64;- let x = sx + (tx - sx) * frac;- let y = sy + (ty - sy) * frac;+ let u = i as f64 / steps as f64;+ let inv = 1.0 - u;+ let b0 = inv * inv * inv;+ let b1 = 3.0 * inv * inv * u;+ let b2 = 3.0 * inv * u * u;+ let b3 = u * u * u;+ let x = b0 * p0x + b1 * p1x + b2 * p2x + b3 * tx;+ let y = b0 * p0y + b1 * p1y + b2 * p2y + b3 * ty;out.push(StabilizedSample {x,y,@@ -636,7 +691,7 @@ impl InputStabilizer {tilt_x: self.last_tilt_x,tilt_y: self.last_tilt_y,twist: self.last_twist,- timestamp_ms: start_t + dt_total * frac,+ timestamp_ms: start_t + dt_total * u,velocity: self.ema_vel_doc_per_ms,is_corner: false,should_emit: true,@@ -662,48 +717,95 @@ impl InputStabilizer {}}- /// Detects a genuine sharp corner (>= 55 deg directional turn over meaningful chord length)- /// while ignoring micro-jitter and smooth sine curves.+ /// Detects a genuine intentional sharp corner (>= 72 deg directional turn) while strictly+ /// rejecting 1-sample digitizer twitches, touchdown wobbles, and smooth curves.+ ///+ /// Two confirmation paths:+ /// - Path A (decisive single excursion): incoming leg >= 10 screen px AND outgoing excursion+ /// >= 14 screen px at >= 72 deg (handles 60 Hz mouse / fast flick corners).+ /// - Path B (multi-sample confirmed corner for 240–500 Hz tablets): candidate apex 1–3 samples+ /// back with incoming leg >= 10 screen px and >= 2 consecutive coherent outgoing samples+ /// spanning >= 8 screen px at >= 72 deg.fn detect_sharp_corner(&self, cur_x: f64, cur_y: f64, zoom: f64) -> Option<(f64, f64)> {let n = self.recent_raw.len();if n < 3 {return None;}- let apex = self.recent_raw[n - 1];- let min_leg_doc = (3.0 / zoom).max(1.0);+ let in_min_doc = (10.0 / zoom).max(3.0);+ let single_out_min_doc = (14.0 / zoom).max(5.0);+ let multi_out_min_doc = (8.0 / zoom).max(2.5);+ // Corner threshold: turning angle >= ~72 degrees (cos < 0.31)+ const MAX_CORNER_COS: f64 = 0.31;++ let find_incoming_vec = |apex_idx: usize| -> Option<(f64, f64, f64)> {+ let apex = self.recent_raw[apex_idx];+ for i in (0..apex_idx).rev() {+ let cand = self.recent_raw[i];+ let dx = apex.x - cand.x;+ let dy = apex.y - cand.y;+ let len = dx.hypot(dy);+ if len >= in_min_doc {+ return Some((dx, dy, len));+ }+ }+ None+ };- // Outgoing leg: apex -> cur- let out_dx = cur_x - apex.x;- let out_dy = cur_y - apex.y;+ // Path A: Decisive single excursion from the most recent raw point+ let last_apex = self.recent_raw[n - 1];+ let out_dx = cur_x - last_apex.x;+ let out_dy = cur_y - last_apex.y;let out_len = out_dx.hypot(out_dy);- if out_len < min_leg_doc {- return None;+ if out_len >= single_out_min_doc {+ if let Some((in_dx, in_dy, in_len)) = find_incoming_vec(n - 1) {+ let cos_angle =+ ((in_dx * out_dx + in_dy * out_dy) / (in_len * out_len)).clamp(-1.0, 1.0);+ if cos_angle < MAX_CORNER_COS {+ return Some((last_apex.x, last_apex.y));+ }+ }}- // Walk backward to find an incoming anchor at least `min_leg_doc * 1.5` away from apex- let mut prev_anchor: Option<RawEntry> = None;- for i in (0..(n - 1)).rev() {- let cand = self.recent_raw[i];- let d = (apex.x - cand.x).hypot(apex.y - cand.y);- if d >= min_leg_doc * 1.5 {- prev_anchor = Some(cand);- break;+ // Path B: Multi-sample confirmed corner (apex 1..=3 samples back, >= 2 coherent outgoing steps)+ let max_back = (n - 1).min(4);+ for back in 2..=max_back {+ let apex_idx = n - back;+ let apex = self.recent_raw[apex_idx];+ let odx = cur_x - apex.x;+ let ody = cur_y - apex.y;+ let olen = odx.hypot(ody);+ if olen < multi_out_min_doc {+ continue;+ }+ let Some((in_dx, in_dy, in_len)) = find_incoming_vec(apex_idx) else {+ continue;+ };+ let cos_angle = ((in_dx * odx + in_dy * ody) / (in_len * olen)).clamp(-1.0, 1.0);+ if cos_angle >= MAX_CORNER_COS {+ continue;+ }+ // Confirm intermediate samples from apex -> cur progress coherently along outgoing ray+ let uox = odx / olen;+ let uoy = ody / olen;+ let mut prev_proj = 0.0f64;+ let mut coherent = true;+ for j in (apex_idx + 1)..n {+ let pt = self.recent_raw[j];+ let rx = pt.x - apex.x;+ let ry = pt.y - apex.y;+ let proj = rx * uox + ry * uoy;+ let perp = (rx * (-uoy) + ry * uox).abs();+ if proj < prev_proj - (0.5 / zoom) || perp > olen * 0.35 + (1.0 / zoom) {+ coherent = false;+ break;+ }+ prev_proj = proj;+ }+ if coherent && olen > prev_proj {+ return Some((apex.x, apex.y));}- }- let anchor = prev_anchor?;- let in_dx = apex.x - anchor.x;- let in_dy = apex.y - anchor.y;- let in_len = in_dx.hypot(in_dy);- if in_len < min_leg_doc {- return None;}- let cos_angle =- ((in_dx * out_dx + in_dy * out_dy) / (in_len * out_len)).clamp(-1.0, 1.0);- // Corner threshold: turning angle >= ~62 degrees (cos < 0.47)- if cos_angle < 0.47 {- return Some((apex.x, apex.y));- }None}}diff --git a/crates/ink-engine/src/types.rs b/crates/ink-engine/src/types.rsindex 791d458..d0cbf3d 100644--- a/crates/ink-engine/src/types.rs+++ b/crates/ink-engine/src/types.rs@@ -346,6 +346,33 @@ pub enum NativeNavEvent {},}+/// Recorded stylus sample point for Brush Studio live scratchpad replay.+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ScratchpadStrokePoint {+ pub x: f32,+ pub y: f32,+ pub pressure: f32,+ #[serde(default)]+ pub tilt_x: f32,+ #[serde(default)]+ pub tilt_y: f32,+ #[serde(default)]+ pub twist: f32,+ #[serde(default)]+ pub timestamp_ms: f64,+}++/// Recorded Brush Studio scratchpad stroke re-rendered live when brush parameters change.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ScratchpadStrokeInput {+ pub points: Vec<ScratchpadStrokePoint>,+ pub color: [f32; 3],+ #[serde(default)]+ pub seed: u64,+}+/// Reply channel for offscreen GPU RGBA8 image renders (`(width, height, rgba8)`).pub type Rgba8ImageReply = crossbeam_channel::Sender<Result<(u32, u32, Vec<u8>), String>>;@@ -385,6 +412,14 @@ pub enum EngineCommand {height: u32,reply: Rgba8ImageReply,},+ /// Renders Brush Studio live scratchpad strokes on DX12 with the live-edited brush config.+ RenderScratchpadPreview {+ brush: Box<crate::brush::NativeBrushConfig>,+ strokes: Vec<ScratchpadStrokeInput>,+ width: u32,+ height: u32,+ reply: Rgba8ImageReply,+ },/// Updates global stylus pressure curve (`AppSettings.pressureCurve`).SetGlobalPressureCurve(crate::stroke::GlobalPressureCurve),/// Updates active straight ruler & perspective ruler snapping configurations.diff --git a/public/brushes/decoration/background/building_0.png b/public/brushes/decoration/background/building_0.pngdeleted file mode 100644index f83ae38..0000000Binary files a/public/brushes/decoration/background/building_0.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_1.png b/public/brushes/decoration/background/building_1.pngdeleted file mode 100644index d9487f6..0000000Binary files a/public/brushes/decoration/background/building_1.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_10.png b/public/brushes/decoration/background/building_10.pngdeleted file mode 100644index 7f52781..0000000Binary files a/public/brushes/decoration/background/building_10.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_11.png b/public/brushes/decoration/background/building_11.pngdeleted file mode 100644index fba2431..0000000Binary files a/public/brushes/decoration/background/building_11.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_12.png b/public/brushes/decoration/background/building_12.pngdeleted file mode 100644index 9c374b8..0000000Binary files a/public/brushes/decoration/background/building_12.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_2.png b/public/brushes/decoration/background/building_2.pngdeleted file mode 100644index e4c6ffa..0000000Binary files a/public/brushes/decoration/background/building_2.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_3.png b/public/brushes/decoration/background/building_3.pngdeleted file mode 100644index 0a6de0b..0000000Binary files a/public/brushes/decoration/background/building_3.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_4.png b/public/brushes/decoration/background/building_4.pngdeleted file mode 100644index 777d341..0000000Binary files a/public/brushes/decoration/background/building_4.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_5.png b/public/brushes/decoration/background/building_5.pngdeleted file mode 100644index dc0635d..0000000Binary files a/public/brushes/decoration/background/building_5.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_6.png b/public/brushes/decoration/background/building_6.pngdeleted file mode 100644index 8f7ce88..0000000Binary files a/public/brushes/decoration/background/building_6.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_7.png b/public/brushes/decoration/background/building_7.pngdeleted file mode 100644index a0a4a91..0000000Binary files a/public/brushes/decoration/background/building_7.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_8.png b/public/brushes/decoration/background/building_8.pngdeleted file mode 100644index 4f39343..0000000Binary files a/public/brushes/decoration/background/building_8.png and /dev/null differdiff --git a/public/brushes/decoration/background/building_9.png b/public/brushes/decoration/background/building_9.pngdeleted file mode 100644index 32b43a0..0000000Binary files a/public/brushes/decoration/background/building_9.png and /dev/null differdiff --git a/public/brushes/decoration/background/cloud_0.png b/public/brushes/decoration/background/cloud_0.pngdeleted file mode 100644index 3befb3f..0000000Binary files a/public/brushes/decoration/background/cloud_0.png and /dev/null differdiff --git a/public/brushes/decoration/background/grass_0.png b/public/brushes/decoration/background/grass_0.pngdeleted file mode 100644index 5c29278..0000000Binary files a/public/brushes/decoration/background/grass_0.png and /dev/null differdiff --git a/public/brushes/decoration/background/grass_1.png b/public/brushes/decoration/background/grass_1.pngdeleted file mode 100644index c4dc4dc..0000000Binary files a/public/brushes/decoration/background/grass_1.png and /dev/null differdiff --git a/public/brushes/decoration/background/trees_0.png b/public/brushes/decoration/background/trees_0.pngdeleted file mode 100644index 27f273b..0000000Binary files a/public/brushes/decoration/background/trees_0.png and /dev/null differdiff --git a/public/brushes/decoration/background/trees_1.png b/public/brushes/decoration/background/trees_1.pngdeleted file mode 100644index 2b4d27a..0000000Binary files a/public/brushes/decoration/background/trees_1.png and /dev/null differdiff --git a/public/brushes/decoration/background/trees_2.png b/public/brushes/decoration/background/trees_2.pngdeleted file mode 100644index 2b4bc76..0000000Binary files a/public/brushes/decoration/background/trees_2.png and /dev/null differdiff --git a/public/brushes/decoration/background/trees_3.png b/public/brushes/decoration/background/trees_3.pngdeleted file mode 100644index cdb9587..0000000Binary files a/public/brushes/decoration/background/trees_3.png and /dev/null differdiff --git a/public/brushes/decoration/background/trees_4.png b/public/brushes/decoration/background/trees_4.pngdeleted file mode 100644index f62a2f2..0000000Binary files a/public/brushes/decoration/background/trees_4.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/classic-lace_0.png b/public/brushes/decoration/clothing/classic-lace_0.pngdeleted file mode 100644index 8d67c88..0000000Binary files a/public/brushes/decoration/clothing/classic-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/cross-lace_0.png b/public/brushes/decoration/clothing/cross-lace_0.pngdeleted file mode 100644index 6aa43d3..0000000Binary files a/public/brushes/decoration/clothing/cross-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/decorative-rope_0.png b/public/brushes/decoration/clothing/decorative-rope_0.pngdeleted file mode 100644index 1baf078..0000000Binary files a/public/brushes/decoration/clothing/decorative-rope_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/ornate-scallop_0.png b/public/brushes/decoration/clothing/ornate-scallop_0.pngdeleted file mode 100644index c89e081..0000000Binary files a/public/brushes/decoration/clothing/ornate-scallop_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/rope-ribbon_0.png b/public/brushes/decoration/clothing/rope-ribbon_0.pngdeleted file mode 100644index 7c99b8b..0000000Binary files a/public/brushes/decoration/clothing/rope-ribbon_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/rose-trim_0.png b/public/brushes/decoration/clothing/rose-trim_0.pngdeleted file mode 100644index 54e55a0..0000000Binary files a/public/brushes/decoration/clothing/rose-trim_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/sakura-lace_0.png b/public/brushes/decoration/clothing/sakura-lace_0.pngdeleted file mode 100644index 93377c6..0000000Binary files a/public/brushes/decoration/clothing/sakura-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/scallop-lace_0.png b/public/brushes/decoration/clothing/scallop-lace_0.pngdeleted file mode 100644index 15681e8..0000000Binary files a/public/brushes/decoration/clothing/scallop-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/scallop-trim-lace_0.png b/public/brushes/decoration/clothing/scallop-trim-lace_0.pngdeleted file mode 100644index bcd0239..0000000Binary files a/public/brushes/decoration/clothing/scallop-trim-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/sheer-scallop_0.png b/public/brushes/decoration/clothing/sheer-scallop_0.pngdeleted file mode 100644index d51b6d4..0000000Binary files a/public/brushes/decoration/clothing/sheer-scallop_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/simple-lace_0.png b/public/brushes/decoration/clothing/simple-lace_0.pngdeleted file mode 100644index 14b7364..0000000Binary files a/public/brushes/decoration/clothing/simple-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-1_0.png b/public/brushes/decoration/clothing/standard-lace-1_0.pngdeleted file mode 100644index 71ab968..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-1_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-2_0.png b/public/brushes/decoration/clothing/standard-lace-2_0.pngdeleted file mode 100644index 0be98e4..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-2_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-3_0.png b/public/brushes/decoration/clothing/standard-lace-3_0.pngdeleted file mode 100644index 8dba62b..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-3_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-4_0.png b/public/brushes/decoration/clothing/standard-lace-4_0.pngdeleted file mode 100644index 8a97224..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-4_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-5_0.png b/public/brushes/decoration/clothing/standard-lace-5_0.pngdeleted file mode 100644index 126ff14..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-5_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/standard-lace-6_0.png b/public/brushes/decoration/clothing/standard-lace-6_0.pngdeleted file mode 100644index fe460a3..0000000Binary files a/public/brushes/decoration/clothing/standard-lace-6_0.png and /dev/null differdiff --git a/public/brushes/decoration/clothing/star-lace_0.png b/public/brushes/decoration/clothing/star-lace_0.pngdeleted file mode 100644index 7cabcde..0000000Binary files a/public/brushes/decoration/clothing/star-lace_0.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_0.png b/public/brushes/decoration/effect/bloodstain_0.pngdeleted file mode 100644index 1fb1bc9..0000000Binary files a/public/brushes/decoration/effect/bloodstain_0.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_1.png b/public/brushes/decoration/effect/bloodstain_1.pngdeleted file mode 100644index b598021..0000000Binary files a/public/brushes/decoration/effect/bloodstain_1.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_2.png b/public/brushes/decoration/effect/bloodstain_2.pngdeleted file mode 100644index 8c3030e..0000000Binary files a/public/brushes/decoration/effect/bloodstain_2.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_3.png b/public/brushes/decoration/effect/bloodstain_3.pngdeleted file mode 100644index 6789e49..0000000Binary files a/public/brushes/decoration/effect/bloodstain_3.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_4.png b/public/brushes/decoration/effect/bloodstain_4.pngdeleted file mode 100644index 66c4e15..0000000Binary files a/public/brushes/decoration/effect/bloodstain_4.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_5.png b/public/brushes/decoration/effect/bloodstain_5.pngdeleted file mode 100644index b5f843e..0000000Binary files a/public/brushes/decoration/effect/bloodstain_5.png and /dev/null differdiff --git a/public/brushes/decoration/effect/bloodstain_6.png b/public/brushes/decoration/effect/bloodstain_6.pngdeleted file mode 100644index ec32e12..0000000Binary files a/public/brushes/decoration/effect/bloodstain_6.png and /dev/null differdiff --git a/public/brushes/decoration/effect/cherry_0.png b/public/brushes/decoration/effect/cherry_0.pngdeleted file mode 100644index 2808cfa..0000000Binary files a/public/brushes/decoration/effect/cherry_0.png and /dev/null differdiff --git a/public/brushes/decoration/effect/cherry_1.png b/public/brushes/decoration/effect/cherry_1.pngdeleted file mode 100644index 7b60207..0000000Binary files a/public/brushes/decoration/effect/cherry_1.png and /dev/null differdiff --git a/public/brushes/decoration/effect/cherry_2.png b/public/brushes/decoration/effect/cherry_2.pngdeleted file mode 100644index 6ec19c1..0000000Binary files a/public/brushes/decoration/effect/cherry_2.png and /dev/null differdiff --git a/public/brushes/decoration/effect/feather_0.png b/public/brushes/decoration/effect/feather_0.pngdeleted file mode 100644index 9318521..0000000Binary files a/public/brushes/decoration/effect/feather_0.png and /dev/null differdiff --git a/public/brushes/decoration/effect/feather_1.png b/public/brushes/decoration/effect/feather_1.pngdeleted file mode 100644index 54e8aa2..0000000Binary files a/public/brushes/decoration/effect/feather_1.png and /dev/null differdiff --git a/public/brushes/decoration/effect/feather_2.png b/public/brushes/decoration/effect/feather_2.pngdeleted file mode 100644index 0299b8f..0000000Binary files a/public/brushes/decoration/effect/feather_2.png and /dev/null differdiff --git a/public/brushes/decoration/effect/feather_3.png b/public/brushes/decoration/effect/feather_3.pngdeleted file mode 100644index 271519c..0000000Binary files a/public/brushes/decoration/effect/feather_3.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_0.png b/public/brushes/decoration/effect/roses_0.pngdeleted file mode 100644index 2f41f61..0000000Binary files a/public/brushes/decoration/effect/roses_0.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_1.png b/public/brushes/decoration/effect/roses_1.pngdeleted file mode 100644index af7b7ad..0000000Binary files a/public/brushes/decoration/effect/roses_1.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_2.png b/public/brushes/decoration/effect/roses_2.pngdeleted file mode 100644index bf36d20..0000000Binary files a/public/brushes/decoration/effect/roses_2.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_3.png b/public/brushes/decoration/effect/roses_3.pngdeleted file mode 100644index 218fd5e..0000000Binary files a/public/brushes/decoration/effect/roses_3.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_4.png b/public/brushes/decoration/effect/roses_4.pngdeleted file mode 100644index 417939f..0000000Binary files a/public/brushes/decoration/effect/roses_4.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_5.png b/public/brushes/decoration/effect/roses_5.pngdeleted file mode 100644index b6de1c5..0000000Binary files a/public/brushes/decoration/effect/roses_5.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_6.png b/public/brushes/decoration/effect/roses_6.pngdeleted file mode 100644index 6225ce9..0000000Binary files a/public/brushes/decoration/effect/roses_6.png and /dev/null differdiff --git a/public/brushes/decoration/effect/roses_7.png b/public/brushes/decoration/effect/roses_7.pngdeleted file mode 100644index fb79527..0000000Binary files a/public/brushes/decoration/effect/roses_7.png and /dev/null differdiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f58f357..e13e6d6 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -7,6 +7,7 @@ mod native_engine;mod native_tools;mod os_hotkeys;mod psd_parser;+mod raster_journal;mod raster_ops;mod recovery;mod save_dialog;@@ -486,7 +487,9 @@ async fn recovery_init_session(session_id: String,manifest_json: String,) -> Result<(), String> {- recovery::init_session(&app, &session_id, &manifest_json).await+ recovery::init_session(&app, &session_id, &manifest_json).await?;+ raster_journal::baseline(&session_id);+ Ok(())}#[tauri::command]@@ -511,9 +514,10 @@ async fn recovery_checkpoint(recovery::checkpoint(&app,&session_id,- base_snapshot,- manifest_json,- thumbnail_png,+ base_snapshot.to_vec(),+ manifest_json.to_string(),+ thumbnail_png.to_vec(),+ None,).await}@@ -969,6 +973,21 @@ async fn native_engine_render_brush_preview(Ok(pack_rgba_ipc_response(w, h, rgba))}+#[tauri::command]+async fn native_engine_render_scratchpad_preview(+ brush: ink_engine::NativeBrushConfig,+ strokes: Vec<ink_engine::ScratchpadStrokeInput>,+ width: u32,+ height: u32,+) -> Result<tauri::ipc::Response, String> {+ let (w, h, rgba) = tauri::async_runtime::spawn_blocking(move || {+ native_engine::render_scratchpad_preview(brush, strokes, width, height)+ })+ .await+ .map_err(|e| format!("Scratchpad preview worker failed: {e}"))??;+ Ok(pack_rgba_ipc_response(w, h, rgba))+}+#[tauri::command]fn native_engine_set_pressure_curve(curve: ink_engine::GlobalPressureCurve) {native_engine::set_pressure_curve(curve);@@ -2032,6 +2051,7 @@ pub fn run() {native_engine_clean_dirty_brush,native_engine_set_mask_mode,native_engine_render_brush_preview,+ native_engine_render_scratchpad_preview,native_engine_set_pressure_curve,native_engine_set_rulers,native_engine_upload_brush_texture,diff --git a/src-tauri/src/native_docs.rs b/src-tauri/src/native_docs.rsindex 58dc395..dc60e2e 100644--- a/src-tauri/src/native_docs.rs+++ b/src-tauri/src/native_docs.rs@@ -1626,6 +1626,9 @@ pub async fn recovery_checkpoint_document(session_id: String,manifest_override: Option<String>,) -> Result<NativeRecoveryCheckpointResult, String> {+ // Take the WAL watermark BEFORE capturing the snapshot: frames below it are contained in+ // the snapshot; frames journaled while it encodes are kept (see `recovery::checkpoint`).+ let wal_watermark = recovery::wal_watermark(app, &session_id).await;let (generated_manifest, snapshot_bytes, thumb_png) =tokio::task::spawn_blocking(move || -> Result<(String, Vec<u8>, Vec<u8>), String> {let docs = documents_handle();@@ -1643,9 +1646,10 @@ pub async fn recovery_checkpoint_document(recovery::checkpoint(app,&session_id,- &snapshot_bytes,- &manifest_json,- &thumb_png,+ snapshot_bytes,+ manifest_json,+ thumb_png,+ Some(wal_watermark),).await?;diff --git a/src-tauri/src/native_engine.rs b/src-tauri/src/native_engine.rsindex 690bdff..2379219 100644--- a/src-tauri/src/native_engine.rs+++ b/src-tauri/src/native_engine.rs@@ -25,8 +25,8 @@ use ink_engine::{BrushParams, BrushTextureKind, CameraState, CommittedStrokePoint, CompositorDisplayConfig,CursorConfig, EngineCommand, EngineDiagnostics, FlattenOptions, GlobalPressureCurve,GpuPoolStats, HistoryStateSnapshot, InteractionPolicy, NativeBrushConfig,- PerspectiveRulerConfig, RectI32, SelectionMetaSnapshot, StraightRulerConfig, ThumbnailUpdate,- UiRect, ViewportRect,+ PerspectiveRulerConfig, RectI32, ScratchpadStrokeInput, SelectionMetaSnapshot,+ StraightRulerConfig, ThumbnailUpdate, UiRect, ViewportRect,};use serde::Serialize;use std::sync::{Arc, LazyLock, Mutex};@@ -297,9 +297,14 @@ mod win_host {return true;}// WinTab CXO_SYSTEM synthesizes Win32 mouse events without MI_WP_SIGNATURE while- // the stylus is in proximity; gate with the same 100ms window as `ink-engine`.+ // the stylus is in proximity (or briefly between rapid strokes); gate against both+ // WinTab and Windows Ink stylus activity so synthesized clicks never collide with strokes.let last_wt = tablet_input::last_wintab_activity_ms();- last_wt > 0.0 && (now_ms - last_wt) < 100.0+ if last_wt > 0.0 && (now_ms - last_wt) < 150.0 {+ return true;+ }+ let last_stylus = tablet_input::last_stylus_activity_ms();+ last_stylus > 0.0 && (now_ms - last_stylus) < 150.0}/// Clamps a physical viewport rect strictly inside `main_hwnd`'s current client rect.@@ -580,7 +585,10 @@ mod win_host {return true;}// Space + Left Drag -> native Pan / Shift+Rotate / Ctrl+ZoomDrag- if is_vk_pressed(VK_SPACE)+ // Skip pen-synthesized clicks: WinTab/Windows Ink stylus packets handle+ // Space+Stylus navigation directly in `engine.rs` at full tablet Hz.+ if !is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms)+ && is_vk_pressed(VK_SPACE)&& !hit_test.try_text_input_focused()&& hit_test.try_should_capture_native_nav(px, py){@@ -1000,6 +1008,7 @@ mod win_host {);}EngineEvent::HistoryChanged { doc_id, history } => {+ crate::raster_journal::notify_history_changed();let _ = app_handle.emit(EVENT_HISTORY,NativeHistoryEventPayload { doc_id, history },@@ -1019,6 +1028,7 @@ mod win_host {history,points,} => {+ crate::raster_journal::notify_history_changed();let _ = app_handle.emit(EVENT_STROKE_COMMITTED,NativeStrokeCommittedEventPayload {@@ -1331,6 +1341,33 @@ mod win_host {.map_err(|_| "Timed out waiting for GPU brush preview".to_string())?}+ pub fn render_scratchpad_preview(+ brush: NativeBrushConfig,+ strokes: Vec<ScratchpadStrokeInput>,+ width: u32,+ height: u32,+ ) -> Result<(u32, u32, Vec<u8>), String> {+ let rx = {+ let guard = RUNTIME+ .lock()+ .map_err(|_| "Native engine runtime lock poisoned".to_string())?;+ let Some(rt) = guard.as_ref() else {+ return Err("Native DX12 engine is not active".to_string());+ };+ let (tx, rx) = crossbeam_channel::bounded(1);+ rt.engine.send_command(EngineCommand::RenderScratchpadPreview {+ brush: Box::new(brush),+ strokes,+ width,+ height,+ reply: tx,+ });+ rx+ };+ rx.recv_timeout(std::time::Duration::from_secs(5))+ .map_err(|_| "Timed out waiting for GPU scratchpad preview".to_string())?+ }+pub fn set_pressure_curve(curve: GlobalPressureCurve) {if let Ok(guard) = RUNTIME.lock() {if let Some(rt) = guard.as_ref() {@@ -1404,6 +1441,8 @@ mod win_host {}pub fn sync_active_document() {+ // Every native document mutation path funnels through here: journal its pixels.+ crate::raster_journal::notify_history_changed();if let Ok(guard) = RUNTIME.lock() {if let Some(rt) = guard.as_ref() {rt.engine.send_command(EngineCommand::SyncActiveDocument);@@ -1753,6 +1792,14 @@ mod win_host {) -> Result<(u32, u32, Vec<u8>), String> {Err("Native DX12 engine is not supported on this OS".to_string())}+ pub fn render_scratchpad_preview(+ _brush: NativeBrushConfig,+ _strokes: Vec<ScratchpadStrokeInput>,+ _width: u32,+ _height: u32,+ ) -> Result<(u32, u32, Vec<u8>), String> {+ Err("Native DX12 engine is not supported on this OS".to_string())+ }pub fn set_pressure_curve(_curve: GlobalPressureCurve) {}pub fn set_rulers(_straight: Option<StraightRulerConfig>,@@ -1771,7 +1818,9 @@ mod win_host {pub fn set_policy(_policy: InteractionPolicy) {}pub fn set_collab_points_enabled(_enabled: bool) {}pub fn clear_canvas() {}- pub fn sync_active_document() {}+ pub fn sync_active_document() {+ crate::raster_journal::notify_history_changed();+ }pub fn set_vram_budget(_budget_bytes: u64) {}pub fn flush_gpu_pool() {}pub fn gpu_pool_stats() -> GpuPoolStats {@@ -1844,7 +1893,7 @@ pub use win_host::{liquify_begin, liquify_cancel, liquify_commit, liquify_step, remote_notify_tile_delta,remote_peer_dispose, remote_stroke_chunk, remote_stroke_dispose, remote_stroke_finish,remote_stroke_start, render_brush_preview, render_document_flattened,- render_layer_thumbnail_gpu, retouch_session, set_appearance, set_brush, set_camera,+ render_layer_thumbnail_gpu, render_scratchpad_preview, retouch_session, set_appearance, set_brush, set_camera,set_collab_points_enabled, set_cursor, set_display_config, set_document, set_full_brush,set_mask_mode, set_occluded_rects, set_policy, set_pressure_curve, set_rulers,set_tool_preview_rgba8, set_viewport, set_vram_budget, shutdown, sync_active_document,diff --git a/src-tauri/src/raster_journal.rs b/src-tauri/src/raster_journal.rsnew file mode 100644index 0000000..93c5d53--- /dev/null+++ b/src-tauri/src/raster_journal.rs@@ -0,0 +1,418 @@+//! Native raster crash journal.+//!+//! Every pixel-changing history step (DX12 brush strokes, fills, filters, transforms, undo,+//! redo, history jumps, collaborative selective undo) is appended to the document's recovery+//! WAL (`journal.wal`) as a `TD v1` frame holding the *current* state of each affected tile.+//! Without this, a crash only restored the last checkpoint, which may be up to ~25 strokes+//! or 30+ seconds of work behind.+//!+//! Design:+//! - One dedicated worker thread, so frames reach the WAL in the same order the history changed.+//! - The worker diffs each document's history stack against the applied/unapplied state it last+//! journaled, so a single generic "history changed" notification covers every code path.+//! - Frames carry "tile = current contents" (or "tile removed"), which makes replay idempotent:+//! re-applying a frame whose state a newer checkpoint already contains is harmless.+//! - Tile reads hold the document read lock only long enough to clone `Arc<TileData>` handles;+//! compression and disk I/O happen with no lock held.++use crate::native_docs;+use crate::recovery;+use ink_engine::document::{Document, DocumentManager};+use parking_lot::RwLock;+use ink_engine::io::encode_cow_deltas_to_wal_payload;+use ink_engine::tiles::{CowTileDelta, TileCoord, TileKind};+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::mpsc::{channel, Sender};+use std::sync::{LazyLock, Mutex};++const WAL_ENTRY_STROKE_TILE_DELTA: u8 = 1;+/// Tiles per WAL frame (keeps every frame far below the 64 MB frame ceiling).+const TILES_PER_FRAME: usize = 48;+/// Upper bound on tiles journaled for one scan; larger structural edits rely on checkpoints.+const MAX_TILES_PER_SCAN: usize = 32_768;++enum Job {+ Scan,+ Baseline(String),+}++static SCAN_PENDING: AtomicBool = AtomicBool::new(false);+static TX: LazyLock<Mutex<Option<Sender<Job>>>> = LazyLock::new(|| Mutex::new(None));++fn send(job: Job) {+ let Ok(mut guard) = TX.lock() else {+ return;+ };+ if guard.is_none() {+ let (tx, rx) = channel::<Job>();+ let spawned = std::thread::Builder::new()+ .name("inkstudio-raster-journal".to_string())+ .spawn(move || {+ let mut worker = JournalWorker::default();+ while let Ok(job) = rx.recv() {+ match job {+ Job::Scan => {+ SCAN_PENDING.store(false, Ordering::SeqCst);+ worker.scan();+ }+ Job::Baseline(doc_id) => worker.baseline(&doc_id),+ }+ }+ });+ if spawned.is_err() {+ return;+ }+ *guard = Some(tx);+ }+ if let Some(tx) = guard.as_ref() {+ let _ = tx.send(job);+ }+}++/// Call after anything that may have changed a document's history (cheap; coalesced).+pub fn notify_history_changed() {+ if !SCAN_PENDING.swap(true, Ordering::SeqCst) {+ send(Job::Scan);+ }+}++/// Call right after a recovery session's manifest is (re)written: history steps that already+/// exist at that moment are treated as part of the session's starting state.+pub fn baseline(doc_id: &str) {+ send(Job::Baseline(doc_id.to_string()));+}++#[derive(Clone, PartialEq, Eq, Hash)]+struct TileKey {+ layer_id: String,+ kind: u8,+ tx: i32,+ ty: i32,+}++fn kind_code(kind: TileKind) -> u8 {+ match kind {+ TileKind::Raster => 0,+ TileKind::Mask => 1,+ TileKind::ImpastoHeight => 2,+ }+}++fn kind_from_code(code: u8) -> TileKind {+ match code {+ 1 => TileKind::Mask,+ 2 => TileKind::ImpastoHeight,+ _ => TileKind::Raster,+ }+}++/// `entry id -> applied` for every history step, as of the last journal write.+type AppliedMap = HashMap<String, bool>;++#[derive(Default)]+struct JournalWorker {+ docs: HashMap<String, AppliedMap>,+}++fn applied_map(doc: &Document) -> AppliedMap {+ let index = doc.history.index();+ doc.history+ .entries()+ .iter()+ .enumerate()+ .map(|(i, e)| (e.meta.id.clone(), (i as isize) <= index && !e.meta.undone))+ .collect()+}++fn add_grid_keys(+ out: &mut HashSet<TileKey>,+ layer_id: &str,+ grid: &ink_engine::tiles::SparseLayerGrid,+) {+ for (map, kind) in [+ (&grid.tiles, TileKind::Raster),+ (&grid.mask_tiles, TileKind::Mask),+ (&grid.impasto_tiles, TileKind::ImpastoHeight),+ ] {+ for coord in map.keys() {+ out.insert(TileKey {+ layer_id: layer_id.to_string(),+ kind: kind_code(kind),+ tx: coord.tx,+ ty: coord.ty,+ });+ }+ }+}++impl JournalWorker {+ fn baseline(&mut self, doc_id: &str) {+ self.baseline_in(&native_docs::documents_handle(), doc_id);+ }++ fn scan(&mut self) {+ self.scan_in(&native_docs::documents_handle());+ }++ fn baseline_in(&mut self, docs: &RwLock<DocumentManager>, doc_id: &str) {+ let mgr = docs.read();+ if let Some(doc) = mgr.get_document(doc_id) {+ self.docs.insert(doc_id.to_string(), applied_map(doc));+ }+ }++ fn scan_in(&mut self, docs: &RwLock<DocumentManager>) {+ let mut batches: Vec<(std::path::PathBuf, Vec<CowTileDelta>)> = Vec::new();+ let scratch;+ {+ let mgr = docs.read();+ scratch = std::sync::Arc::clone(mgr.scratch_backend());+ let live_ids = mgr.document_ids();+ self.docs.retain(|id, _| live_ids.iter().any(|l| l == id));++ for doc_id in live_ids {+ let Some(doc) = mgr.get_document(&doc_id) else {+ continue;+ };+ let current = applied_map(doc);+ let Some(session_dir) = recovery::journal_ready_session_dir(&doc_id) else {+ // No live recovery session: just track state so nothing is replayed twice+ // once a session starts (its `baseline` call resets this anyway).+ self.docs.insert(doc_id, current);+ continue;+ };+ let Some(prev) = self.docs.get(&doc_id) else {+ // First sighting (no explicit baseline): adopt as the starting point.+ self.docs.insert(doc_id, current);+ continue;+ };++ let mut keys: HashSet<TileKey> = HashSet::new();+ for entry in doc.history.entries() {+ let now_applied = current.get(&entry.meta.id).copied().unwrap_or(false);+ let changed = match prev.get(&entry.meta.id) {+ Some(&was) => was != now_applied,+ None => now_applied,+ };+ if !changed {+ continue;+ }+ for d in &entry.tile_deltas {+ keys.insert(TileKey {+ layer_id: d.layer_id.clone(),+ kind: kind_code(d.kind),+ tx: d.coord.tx,+ ty: d.coord.ty,+ });+ }+ if let Some(ref tree) = entry.layer_tree_delta {+ // Structural edits (merge, rasterize, duplicate...): journal the full+ // current contents of every touched layer, plus removals of tiles that+ // existed on the other side of the edit.+ for (lid, grid) in tree.before_grids.iter().chain(tree.after_grids.iter())+ {+ add_grid_keys(&mut keys, lid, grid);+ if let Some(layer) = doc.layer(lid) {+ add_grid_keys(&mut keys, lid, &layer.grid);+ }+ }+ }+ }+ self.docs.insert(doc_id.clone(), current);++ if keys.is_empty() {+ continue;+ }+ if keys.len() > MAX_TILES_PER_SCAN {+ eprintln!(+ "[raster-journal] {} tiles changed at once in {doc_id}; deferring to next checkpoint",+ keys.len()+ );+ continue;+ }++ let mut deltas = Vec::with_capacity(keys.len());+ for k in keys {+ let Some(layer) = doc.layer(&k.layer_id) else {+ continue; // Layer deleted: removal is carried by the layer-mutation frame.+ };+ let kind = kind_from_code(k.kind);+ let coord = TileCoord::new(k.tx, k.ty);+ let tile = match kind {+ TileKind::Raster => layer.grid.get_tile(coord),+ TileKind::Mask => layer.grid.get_mask_tile(coord),+ TileKind::ImpastoHeight => layer.grid.get_impasto_tile(coord),+ }+ .cloned();+ deltas.push(CowTileDelta {+ layer_id: k.layer_id,+ kind,+ coord,+ before: None,+ after: tile,+ remote_epoch: 0,+ });+ }+ if !deltas.is_empty() {+ batches.push((session_dir, deltas));+ }+ }+ }++ self.write_batches(batches, scratch);+ }++ fn write_batches(+ &self,+ batches: Vec<(std::path::PathBuf, Vec<CowTileDelta>)>,+ scratch: std::sync::Arc<dyn ink_engine::memory::ScratchBackend>,+ ) {+ // Encode + append with no document lock held.+ for (session_dir, deltas) in batches {+ for chunk in deltas.chunks(TILES_PER_FRAME) {+ let payload = match encode_cow_deltas_to_wal_payload(chunk, Some(scratch.as_ref())) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("[raster-journal] encode failed: {e}");+ continue;+ }+ };+ if let Err(e) = recovery::append_wal_entry_blocking(+ &session_dir,+ WAL_ENTRY_STROKE_TILE_DELTA,+ &payload,+ ) {+ eprintln!("[raster-journal] append failed: {e}");+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ink_engine::document::{CanvasColorMode, CanvasDimensions};+ use ink_engine::io::{encode_document_checkpoint, replay_recovery_into_document, WalRawEntry};+ use ink_engine::memory::{InMemoryScratchBackend, MemoryBudgetConfig};+ use ink_engine::tiles::RectI32;+ use std::sync::Arc;++ fn pixel(doc: &Document, layer_id: &str, x: i32, y: i32) -> Vec<u8> {+ doc.layer(layer_id)+ .unwrap()+ .grid+ .read_rgba8_rect(RectI32::new(x, y, 1, 1), false, None)+ .unwrap()+ }++ /// Replays checkpoint + current WAL and returns the recovered pixel.+ fn recovered_pixel(+ session_dir: &std::path::Path,+ manifest: &str,+ snapshot: &[u8],+ layer_id: &str,+ ) -> (Vec<u8>, usize) {+ let frames = recovery::parse_wal_frames(+ &std::fs::read(session_dir.join("journal.wal")).unwrap_or_default(),+ );+ let entries: Vec<WalRawEntry> = frames+ .into_iter()+ .map(|f| WalRawEntry {+ entry_type: f.entry_type,+ payload: f.payload,+ })+ .collect();+ let n = entries.len();+ let (doc, _, _) =+ replay_recovery_into_document("recovered", manifest, Some(snapshot), &entries, 50)+ .expect("replay failed");+ (pixel(&doc, layer_id, 110, 110), n)+ }++ #[test]+ fn journal_tracks_strokes_undo_and_redo_end_to_end() {+ let doc_id = "doc-raster-journal-e2e";+ let docs = RwLock::new(DocumentManager::new(+ MemoryBudgetConfig::default(),+ Arc::new(InMemoryScratchBackend::new()),+ ));+ let layer_id = {+ let mut mgr = docs.write();+ let snap = mgr.create_document(+ doc_id,+ "Journal",+ CanvasDimensions {+ width: 512,+ height: 512,+ dpi: 300,+ },+ CanvasColorMode::Color,+ "#ffffff",+ 60.0,+ );+ snap.layers[0].id.clone()+ };++ // Recovery session with a checkpoint of the pre-stroke state.+ let session_dir = recovery::recovery_root_for_tests().join(doc_id);+ let _ = std::fs::remove_dir_all(&session_dir);+ std::fs::create_dir_all(&session_dir).unwrap();+ let (manifest, snapshot, _) = {+ let mgr = docs.read();+ encode_document_checkpoint(mgr.get_document(doc_id).unwrap(), None).unwrap()+ };+ std::fs::write(session_dir.join("manifest.json"), &manifest).unwrap();++ let mut worker = JournalWorker::default();+ worker.baseline_in(&docs, doc_id);+ let original = pixel(docs.read().get_document(doc_id).unwrap(), &layer_id, 110, 110);++ // 1. Stroke (red 32x32 square) -> journaled.+ {+ let mut mgr = docs.write();+ let doc = mgr.get_document_mut(doc_id).unwrap();+ let red: Vec<u8> = [220u8, 20, 30, 255].repeat(32 * 32);+ doc.ingest_dirty_rect(+ &layer_id,+ RectI32::new(100, 100, 32, 32),+ &red,+ false,+ true,+ "brush",+ "Brush Stroke",+ None,+ None,+ None,+ )+ .unwrap();+ }+ worker.scan_in(&docs);+ let (px, frames) = recovered_pixel(&session_dir, &manifest, &snapshot, &layer_id);+ assert!(frames >= 1, "stroke must produce a WAL frame");+ assert_eq!(px, vec![220, 20, 30, 255], "recovery must include the stroke");++ // 2. Nothing changed -> no new frames.+ worker.scan_in(&docs);+ assert_eq!(recovered_pixel(&session_dir, &manifest, &snapshot, &layer_id).1, frames);++ // 3. Undo -> recovery must show the pre-stroke pixels.+ docs.write().get_document_mut(doc_id).unwrap().undo();+ worker.scan_in(&docs);+ let (px, _) = recovered_pixel(&session_dir, &manifest, &snapshot, &layer_id);+ assert_eq!(px, original, "recovery must honor undo");++ // 4. Redo -> stroke is back.+ docs.write().get_document_mut(doc_id).unwrap().redo();+ worker.scan_in(&docs);+ let (px, _) = recovered_pixel(&session_dir, &manifest, &snapshot, &layer_id);+ assert_eq!(px, vec![220, 20, 30, 255], "recovery must honor redo");++ // 5. Session closed (clean save): journal must not recreate it.+ std::fs::remove_dir_all(&session_dir).unwrap();+ docs.write().get_document_mut(doc_id).unwrap().undo();+ worker.scan_in(&docs);+ assert!(!session_dir.exists(), "closed session must stay closed");+ }+}diff --git a/src-tauri/src/recovery.rs b/src-tauri/src/recovery.rsindex 4639925..237e403 100644--- a/src-tauri/src/recovery.rs+++ b/src-tauri/src/recovery.rs@@ -1,7 +1,6 @@use serde::{Deserialize, Serialize};use std::path::PathBuf;use tauri::Manager;-use tokio::io::AsyncWriteExt;pub const WAL_MAGIC: &[u8; 4] = b"INKW";pub const REPLAY_MAGIC: &[u8; 4] = b"INKR";@@ -150,7 +149,20 @@ pub struct RecoveryReplayData {pub wal_entries: Vec<WalEntryData>,}+/// Recovery root resolved once from the `AppHandle`, so non-async workers (the native raster+/// journal thread) can locate session folders without holding an `AppHandle`.+static RECOVERY_ROOT: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();+pub fn get_recovery_root(app: &tauri::AppHandle) -> PathBuf {+ if let Some(root) = RECOVERY_ROOT.get() {+ return root.clone();+ }+ let root = compute_recovery_root(app);+ let _ = RECOVERY_ROOT.set(root.clone());+ root+}++fn compute_recovery_root(app: &tauri::AppHandle) -> PathBuf {#[cfg(target_os = "windows")]{if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {@@ -164,6 +176,174 @@ pub fn get_recovery_root(app: &tauri::AppHandle) -> PathBuf {}}+#[cfg(test)]+pub fn recovery_root_for_tests() -> PathBuf {+ RECOVERY_ROOT+ .get_or_init(|| {+ std::env::temp_dir().join(format!("inkstudio_recovery_test_root_{}", std::process::id()))+ })+ .clone()+}++/// Returns the session folder only when a recovery session has been initialized for it+/// (`manifest.json` present). Journaling into a folder without a manifest would produce a+/// "crashed session" that can never be restored.+pub fn journal_ready_session_dir(session_id: &str) -> Option<PathBuf> {+ let root = RECOVERY_ROOT.get()?;+ let dir = root.join(sanitize_session_id(session_id));+ if dir.join("manifest.json").is_file() {+ Some(dir)+ } else {+ None+ }+}++fn build_wal_frame(entry_type: u8, payload: &[u8]) -> Vec<u8> {+ let mut frame = Vec::with_capacity(13 + payload.len());+ frame.extend_from_slice(WAL_MAGIC);+ frame.push(entry_type);+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());+ frame.extend_from_slice(&compute_crc32(payload).to_le_bytes());+ frame.extend_from_slice(payload);+ frame+}++/// Appends one complete frame and makes it durable. If the write fails part-way (disk full,+/// I/O error) the file is rolled back to its previous length: the WAL reader stops at the+/// first damaged frame, so a torn frame left in the middle would silently hide every frame+/// appended after it.+fn append_frame_durable(wal_path: &std::path::Path, frame: &[u8]) -> Result<(), String> {+ use std::io::Write;+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(wal_path)+ .map_err(|e| format!("Failed to open journal.wal for appending: {}", e))?;+ let prev_len = file.metadata().map(|m| m.len()).unwrap_or(0);+ let res = file+ .write_all(frame)+ .and_then(|_| file.sync_data())+ .map_err(|e| format!("Failed to write WAL frame: {}", e));+ if res.is_err() {+ let _ = file.set_len(prev_len);+ let _ = file.sync_data();+ }+ res+}++/// Replaces `dst` with `src`, retrying briefly when antivirus/indexers hold a transient handle.+/// Never deletes `dst` first, so there is no window in which neither version exists.+fn replace_file(src: &std::path::Path, dst: &std::path::Path) -> Result<(), String> {+ let mut last_err = None;+ for attempt in 0..6 {+ match std::fs::rename(src, dst) {+ Ok(()) => return Ok(()),+ Err(e) => {+ last_err = Some(e);+ std::thread::sleep(std::time::Duration::from_millis(15 * (attempt + 1)));+ }+ }+ }+ let _ = std::fs::remove_file(src);+ Err(format!(+ "Failed to replace {}: {}",+ dst.to_string_lossy(),+ last_err.map(|e| e.to_string()).unwrap_or_default()+ ))+}++/// Writes `data` to a fsync'd sibling temp file, then atomically replaces `dir/name`.+fn write_atomic_blocking(dir: &std::path::Path, name: &str, data: &[u8]) -> Result<(), String> {+ use std::io::Write;+ let seq = WAL_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let tmp = dir.join(format!("{}.{}.{}.tmp", name, std::process::id(), seq));+ let written = (|| -> std::io::Result<()> {+ let mut f = std::fs::File::create(&tmp)?;+ f.write_all(data)?;+ f.sync_all()+ })();+ if let Err(e) = written {+ let _ = std::fs::remove_file(&tmp);+ return Err(format!("Failed to write {}: {}", name, e));+ }+ replace_file(&tmp, &dir.join(name))+}++/// Drops the WAL prefix below `mark` (state already contained in a checkpoint snapshot) and+/// keeps every frame appended at or after it.+pub fn compact_wal(wal: Vec<u8>, mark: u64) -> Vec<u8> {+ let mark = mark as usize;+ if mark <= wal.len() {+ wal[mark..].to_vec()+ } else {+ // WAL shrank since the watermark (another checkpoint already compacted it):+ // everything left postdates that compaction, so keep it all.+ wal+ }+}++/// Parses consecutive `INKW` frames, stopping at the first torn, oversized or corrupt frame.+pub fn parse_wal_frames(wal_bytes: &[u8]) -> Vec<WalEntryData> {+ let mut wal_entries = Vec::new();+ let mut offset = 0;+ let total_len = wal_bytes.len();+ while offset + 13 <= total_len {+ if &wal_bytes[offset..offset + 4] != WAL_MAGIC {+ break;+ }+ let entry_type = wal_bytes[offset + 4];+ let payload_len =+ u32::from_le_bytes(wal_bytes[offset + 5..offset + 9].try_into().unwrap()) as usize;+ let expected_crc =+ u32::from_le_bytes(wal_bytes[offset + 9..offset + 13].try_into().unwrap());+ if payload_len > MAX_WAL_FRAME_PAYLOAD_BYTES || offset + 13 + payload_len > total_len {+ break;+ }+ let payload = &wal_bytes[offset + 13..offset + 13 + payload_len];+ if compute_crc32(payload) != expected_crc {+ break;+ }+ wal_entries.push(WalEntryData {+ entry_type,+ payload: payload.to_vec(),+ });+ offset += 13 + payload_len;+ }+ wal_entries+}++/// Synchronous WAL append for non-async worker threads (must NOT be called on a Tokio worker).+pub fn append_wal_entry_blocking(+ session_dir: &std::path::Path,+ entry_type: u8,+ payload: &[u8],+) -> Result<(), String> {+ if payload.len() > MAX_WAL_FRAME_PAYLOAD_BYTES {+ return Err("WAL payload exceeds 64 MB safety ceiling".to_string());+ }+ let frame = build_wal_frame(entry_type, payload);+ let _wal_guard = WAL_IO_LOCK.blocking_lock();+ if !session_dir.join("manifest.json").is_file() {+ // Session was closed (clean save) while this frame was being encoded.+ return Ok(());+ }+ append_frame_durable(&session_dir.join("journal.wal"), &frame)+}++/// Current byte length of a session's WAL. Taken *before* a checkpoint snapshot is captured:+/// every frame below this offset describes state the snapshot already contains, so a+/// checkpoint may drop exactly that prefix and must keep everything appended afterwards.+pub async fn wal_watermark(app: &tauri::AppHandle, session_id: &str) -> u64 {+ let _wal_guard = WAL_IO_LOCK.lock().await;+ let wal_path = get_recovery_root(app)+ .join(sanitize_session_id(session_id))+ .join("journal.wal");+ tokio::fs::metadata(&wal_path)+ .await+ .map(|m| m.len())+ .unwrap_or(0)+}+fn sanitize_session_id(session_id: &str) -> String {let s: String = session_id.chars()@@ -195,18 +375,21 @@ pub async fn init_session(};let lock_json = serde_json::to_string_pretty(&lock).map_err(|e| e.to_string())?;- tokio::fs::write(session_dir.join("session.lock"), lock_json.as_bytes())- .await- .map_err(|e| format!("Failed to write session.lock: {}", e))?;-- tokio::fs::write(session_dir.join("manifest.json"), manifest_json.as_bytes())- .await- .map_err(|e| format!("Failed to write manifest.json: {}", e))?;-- let wal_path = session_dir.join("journal.wal");- if !tokio::fs::try_exists(&wal_path).await.unwrap_or(false) {- let _ = tokio::fs::write(&wal_path, &[]).await;- }+ let manifest = manifest_json.to_string();+ let dir = session_dir.clone();+ tokio::task::spawn_blocking(move || -> Result<(), String> {+ write_atomic_blocking(&dir, "session.lock", lock_json.as_bytes())?;+ // Atomic + fsync'd: a crash mid-write must never leave a half-written manifest,+ // which would make the whole session unrecoverable.+ write_atomic_blocking(&dir, "manifest.json", manifest.as_bytes())?;+ let wal_path = dir.join("journal.wal");+ if !wal_path.exists() {+ let _ = std::fs::File::create(&wal_path);+ }+ Ok(())+ })+ .await+ .map_err(|e| format!("Recovery init worker failed: {}", e))??;Ok(())}@@ -245,27 +428,11 @@ pub async fn append_wal_entry(// Build WAL frame and compute CRC32 outside WAL_IO_LOCK (and off Tokio worker threads for large payloads)let frame = if payload.len() >= 262_144 {let owned = payload.to_vec();- tokio::task::spawn_blocking(move || {- let mut frame = Vec::with_capacity(13 + owned.len());- frame.extend_from_slice(WAL_MAGIC);- frame.push(entry_type);- frame.extend_from_slice(&(owned.len() as u32).to_le_bytes());- let crc = compute_crc32(&owned);- frame.extend_from_slice(&crc.to_le_bytes());- frame.extend_from_slice(&owned);- frame- })- .await- .map_err(|e| format!("WAL framing worker failed: {}", e))?+ tokio::task::spawn_blocking(move || build_wal_frame(entry_type, &owned))+ .await+ .map_err(|e| format!("WAL framing worker failed: {}", e))?} else {- let mut frame = Vec::with_capacity(13 + payload.len());- frame.extend_from_slice(WAL_MAGIC);- frame.push(entry_type);- frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());- let crc = compute_crc32(payload);- frame.extend_from_slice(&crc.to_le_bytes());- frame.extend_from_slice(payload);- frame+ build_wal_frame(entry_type, payload)};let _wal_guard = WAL_IO_LOCK.lock().await;@@ -274,76 +441,58 @@ pub async fn append_wal_entry(ensure_session_lock(&session_dir).await?;let wal_path = session_dir.join("journal.wal");- let mut file = tokio::fs::OpenOptions::new()- .create(true)- .append(true)- .open(&wal_path)+ // Durable append (fsync + torn-write rollback) off the async executor.+ tokio::task::spawn_blocking(move || append_frame_durable(&wal_path, &frame)).await- .map_err(|e| format!("Failed to open journal.wal for appending: {}", e))?;-- file.write_all(&frame)- .await- .map_err(|e| format!("Failed to write WAL frame: {}", e))?;- file.flush()- .await- .map_err(|e| format!("Failed to flush WAL frame: {}", e))?;-- Ok(())+ .map_err(|e| format!("WAL append worker failed: {}", e))?}+/// Writes a crash-recovery checkpoint.+///+/// Crash-consistency rules (each step is fsync'd before the next):+/// 1. snapshot + manifest are fully written to temp files first;+/// 2. snapshot, then manifest, are atomically swapped in;+/// 3. only then is the WAL compacted, and only the prefix below `wal_watermark` is dropped.+///+/// A crash at any point leaves a (snapshot, manifest, WAL) triple that replays to the latest+/// journaled state: WAL frames are idempotent "tile = after" writes, so replaying frames the+/// snapshot already contains is harmless, while frames journaled *during* snapshot encoding+/// (which can take seconds on large multi-layer canvases) are preserved instead of wiped.+///+/// `wal_watermark = None` keeps the legacy behavior of clearing the whole WAL (for snapshots+/// built by the caller whose capture point relative to the WAL is unknown).pub async fn checkpoint(app: &tauri::AppHandle,session_id: &str,- base_snapshot: &[u8],- manifest_json: &str,- thumbnail_png: &[u8],+ base_snapshot: Vec<u8>,+ manifest_json: String,+ thumbnail_png: Vec<u8>,+ wal_watermark: Option<u64>,) -> Result<(), String> {let _wal_guard = WAL_IO_LOCK.lock().await;let safe_id = sanitize_session_id(session_id);let session_dir = get_recovery_root(app).join(&safe_id);ensure_session_lock(&session_dir).await?;- let seq = WAL_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);-- // 1. Atomically overwrite base_snapshot.bin (write to temp file, then rename)- let snapshot_path = session_dir.join("base_snapshot.bin");- let temp_snapshot_path = session_dir.join(format!("base_snapshot.bin.{}.{}.tmp", std::process::id(), seq));- tokio::fs::write(&temp_snapshot_path, base_snapshot)- .await- .map_err(|e| format!("Failed to write temp snapshot: {}", e))?;-- if tokio::fs::rename(&temp_snapshot_path, &snapshot_path).await.is_err() {- let _ = tokio::fs::remove_file(&snapshot_path).await;- tokio::fs::rename(&temp_snapshot_path, &snapshot_path)- .await- .map_err(|e| format!("Failed to atomically rename snapshot: {}", e))?;- }+ tokio::task::spawn_blocking(move || -> Result<(), String> {+ write_atomic_blocking(&session_dir, "base_snapshot.bin", &base_snapshot)?;+ drop(base_snapshot);+ write_atomic_blocking(&session_dir, "manifest.json", manifest_json.as_bytes())?;- // 2. Truncate journal.wal to zero bytes while holding WAL_IO_LOCK- let wal_path = session_dir.join("journal.wal");- tokio::fs::write(&wal_path, &[])- .await- .map_err(|e| format!("Failed to truncate journal.wal: {}", e))?;-- // 3. Updates manifest.json and thumbnail.png- let manifest_path = session_dir.join("manifest.json");- let temp_manifest_path = session_dir.join(format!("manifest.json.{}.{}.tmp", std::process::id(), seq));- tokio::fs::write(&temp_manifest_path, manifest_json.as_bytes())- .await- .map_err(|e| format!("Failed to write temp manifest.json: {}", e))?;- if tokio::fs::rename(&temp_manifest_path, &manifest_path).await.is_err() {- let _ = tokio::fs::remove_file(&manifest_path).await;- tokio::fs::rename(&temp_manifest_path, &manifest_path)- .await- .map_err(|e| format!("Failed to rename manifest.json: {}", e))?;- }-- if !thumbnail_png.is_empty() {- let thumb_path = session_dir.join("thumbnail.png");- let _ = tokio::fs::write(&thumb_path, thumbnail_png).await;- }+ let wal_path = session_dir.join("journal.wal");+ let tail = match wal_watermark {+ Some(mark) => compact_wal(std::fs::read(&wal_path).unwrap_or_default(), mark),+ None => Vec::new(),+ };+ write_atomic_blocking(&session_dir, "journal.wal", &tail)?;- Ok(())+ if !thumbnail_png.is_empty() {+ let _ = write_atomic_blocking(&session_dir, "thumbnail.png", &thumbnail_png);+ }+ Ok(())+ })+ .await+ .map_err(|e| format!("Recovery checkpoint writer failed: {}", e))?}pub async fn close_session(app: &tauri::AppHandle, session_id: &str) -> Result<(), String> {@@ -444,51 +593,10 @@ pub async fn load_session_data(let base_snapshot = tokio::fs::read(&snapshot_path).await.ok();let wal_path = session_dir.join("journal.wal");- let mut wal_entries = Vec::new();-- if let Ok(wal_bytes) = tokio::fs::read(&wal_path).await {- let mut offset = 0;- let total_len = wal_bytes.len();-- while offset + 13 <= total_len {- if &wal_bytes[offset..offset + 4] != WAL_MAGIC {- // Bad magic header; discard remainder safely- break;- }-- let entry_type = wal_bytes[offset + 4];- let payload_len = u32::from_le_bytes(- wal_bytes[offset + 5..offset + 9]- .try_into()- .unwrap(),- ) as usize;- let expected_crc = u32::from_le_bytes(- wal_bytes[offset + 9..offset + 13]- .try_into()- .unwrap(),- );-- // Incomplete or oversized frame tail (process killed mid-write or corrupt length)- if payload_len > MAX_WAL_FRAME_PAYLOAD_BYTES || offset + 13 + payload_len > total_len {- break;- }-- let payload = &wal_bytes[offset + 13..offset + 13 + payload_len];- let actual_crc = compute_crc32(payload);-- // CRC32 mismatch (corrupted chunk)- if actual_crc != expected_crc {- break;- }-- wal_entries.push(WalEntryData {- entry_type,- payload: payload.to_vec(),- });-- offset += 13 + payload_len;- }- }+ let wal_entries = match tokio::fs::read(&wal_path).await {+ Ok(wal_bytes) => parse_wal_frames(&wal_bytes),+ Err(_) => Vec::new(),+ };Ok(RecoveryReplayData {session_id: session_id.to_string(),@@ -761,6 +869,72 @@ mod tests {assert_eq!(valid_entries[0].1, payload1);}+ fn temp_session_dir(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "inkstudio_recovery_test_{}_{}_{}",+ tag,+ std::process::id(),+ WAL_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)+ ));+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn test_durable_append_and_parse_roundtrip() {+ let dir = temp_session_dir("append");+ std::fs::write(dir.join("manifest.json"), b"{}").unwrap();+ for i in 0..5u8 {+ append_wal_entry_blocking(&dir, 1, &vec![i; 100 + i as usize]).unwrap();+ }+ let frames = parse_wal_frames(&std::fs::read(dir.join("journal.wal")).unwrap());+ assert_eq!(frames.len(), 5);+ assert_eq!(frames[3].payload, vec![3u8; 103]);++ // Session closed (manifest removed) while a frame was in flight: append is a no-op,+ // never resurrecting an unrecoverable session.+ std::fs::remove_file(dir.join("manifest.json")).unwrap();+ append_wal_entry_blocking(&dir, 1, b"late").unwrap();+ let frames = parse_wal_frames(&std::fs::read(dir.join("journal.wal")).unwrap());+ assert_eq!(frames.len(), 5);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn test_checkpoint_compaction_keeps_frames_journaled_during_snapshot() {+ // Frames A, B exist when the watermark is taken; C, D are journaled while the+ // snapshot encodes. Compaction must drop exactly A, B and keep C, D.+ let mut wal = Vec::new();+ wal.extend(build_wal_frame(1, b"A"));+ wal.extend(build_wal_frame(1, b"B"));+ let mark = wal.len() as u64;+ wal.extend(build_wal_frame(1, b"C"));+ wal.extend(build_wal_frame(3, b"D"));+ let kept = parse_wal_frames(&compact_wal(wal.clone(), mark));+ assert_eq!(kept.len(), 2);+ assert_eq!(kept[0].payload, b"C");+ assert_eq!(kept[1].entry_type, 3);++ // Watermark beyond current length (already compacted elsewhere) keeps everything.+ let all = parse_wal_frames(&compact_wal(wal.clone(), wal.len() as u64 + 99));+ assert_eq!(all.len(), 4);+ }++ #[test]+ fn test_atomic_write_replaces_without_leftovers() {+ let dir = temp_session_dir("atomic");+ write_atomic_blocking(&dir, "manifest.json", b"{\"v\":1}").unwrap();+ write_atomic_blocking(&dir, "manifest.json", b"{\"v\":2}").unwrap();+ assert_eq!(std::fs::read(dir.join("manifest.json")).unwrap(), b"{\"v\":2}");+ let leftovers = std::fs::read_dir(&dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))+ .count();+ assert_eq!(leftovers, 0);+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn test_checkpoint_payload_pack_unpack_roundtrip() {let manifest = r#"{"documentName":"Ch1","width":3000}"#;diff --git a/src-tauri/src/tablet_input.rs b/src-tauri/src/tablet_input.rsindex cdaaae4..c1f5dc0 100644--- a/src-tauri/src/tablet_input.rs+++ b/src-tauri/src/tablet_input.rs@@ -45,6 +45,7 @@ struct InkPointerState {pub struct InkPointerDecision {pub emit_phase: u8,pub prev_perf_cutoff: u64,+ pub prev_frame_id: u32,pub prev_ts_ms: f64,}@@ -177,11 +178,16 @@ impl InkStateMachine {_ => return None,};- let prev_perf_cutoff = if emit_phase == 2 {+ let prev_perf_cutoff = if emit_phase == 2 || emit_phase == 3 {st.last_perf_count} else {0};+ let prev_frame_id = if emit_phase == 2 || emit_phase == 3 {+ st.last_frame_id+ } else {+ 0+ };let prev_ts_ms = st.last_ts_ms;if newest_frame_id != 0 {@@ -195,6 +201,7 @@ impl InkStateMachine {Some(InkPointerDecision {emit_phase,prev_perf_cutoff,+ prev_frame_id,prev_ts_ms,})}@@ -217,7 +224,8 @@ impl InkStateMachine {/// WinTab tip-contact hysteresis state machine./// Debounces single-packet zero-pressure micro-dips while the stylus remains in proximity-/// (requiring >= 2 consecutive zero-contact packets or >= 12ms before emitting pen-up phase = 3).+/// WITHOUT emitting post-lift hover coordinates into the active stroke (requiring >= 2+/// consecutive zero-contact packets or >= 12ms before emitting pen-up phase = 3).#[derive(Default, Clone, Copy, Debug)]pub struct WintabContactState {pub was_down: bool,@@ -234,17 +242,19 @@ impl WintabContactState {self.last_nonzero_pressure = 0.0;}- /// Processes a WinTab packet and returns `(phase, effective_pressure, effective_tip_down)`.+ /// Processes a WinTab packet and returns `Some((phase, effective_pressure, effective_tip_down))`+ /// or `None` when holding through a single-packet zero-pressure debounce window (suppressing+ /// post-lift hover coordinates so pen-up never draws a stray hook).pub fn step(&mut self,out_of_proximity: bool,raw_pressure: f32,tip_button_down: bool,timestamp_ms: f64,- ) -> (u8, f32, bool) {+ ) -> Option<(u8, f32, bool)> {if out_of_proximity {self.reset();- return (4, 0.0, false);+ return Some((4, 0.0, false));}let raw_tip_down = raw_pressure > 0.0 || tip_button_down;@@ -257,17 +267,17 @@ impl WintabContactState {let eff_p = raw_pressure.max(0.006);if !self.was_down {self.was_down = true;- (1, eff_p, true)+ Some((1, eff_p, true))} else {- (2, eff_p, true)+ Some((2, eff_p, true))}} else if self.was_down {if self.zero_contact_streak == 0 {// First zero-pressure packet while still in proximity: hold stroke active+ // WITHOUT emitting this hover packet's coordinates into the stroke.self.zero_contact_streak = 1;self.zero_contact_start_ms = timestamp_ms;- let hold_p = self.last_nonzero_pressure.clamp(0.006, 0.03);- (2, hold_p, true)+ None} else {self.zero_contact_streak = self.zero_contact_streak.saturating_add(1);let elapsed_ms = (timestamp_ms - self.zero_contact_start_ms).max(0.0);@@ -275,14 +285,13 @@ impl WintabContactState {self.was_down = false;self.zero_contact_streak = 0;self.zero_contact_start_ms = 0.0;- (3, 0.0, false)+ Some((3, 0.0, false))} else {- let hold_p = self.last_nonzero_pressure.clamp(0.006, 0.03);- (2, hold_p, true)+ None}}} else {- (0, 0.0, false)+ Some((0, 0.0, false))}}}@@ -382,14 +391,14 @@ impl WintabCoordMapper {};// Guard against monitor/DPI layout changes or driver quirks:- // Once orientation is locked, use a wide 240px tolerance so fast manga flicks (where Win32+ // Once orientation is locked, use a wide 600px ceiling so fast manga flicks (where Win32// GetCursorPos lags behind the high-frequency WinTab packet queue) never snap backward to// lagged integer cursor coordinates!if let Some((cx, cy)) = cursor_pos {let cur_x = cx as f64;let cur_y = cy as f64;let guard_px = if self.locked_y_mode.is_some() {- 240.0+ 600.0} else {48.0};@@ -1311,14 +1320,18 @@ mod win_impl {};if let Some(raw_phase_code) = phase {- // In "auto" dual-hook mode, defer to WinTab whenever WinTab is actively delivering packets.+ // In "auto" dual-hook mode, defer to WinTab whenever WinTab is actively delivering packets+ // or the stylus is in WinTab proximity (3s window avoids stroke-start collisions on brief pauses).if WINTAB_RUNNING.load(Ordering::Relaxed) {+ let wt_prox = WINTAB_IN_PROXIMITY.load(Ordering::Acquire);let last_wt_bits = LAST_WINTAB_PACKET_MS_BITS.load(Ordering::Relaxed);- if last_wt_bits != 0 {- let last_wt_ms = f64::from_bits(last_wt_bits);- if qpc_now_ms() - last_wt_ms < 500.0 {- return;+ let wt_recent = last_wt_bits != 0+ && (qpc_now_ms() - f64::from_bits(last_wt_bits)) < 3000.0;+ if wt_prox || wt_recent {+ if let Ok(mut dedup) = INK_DEDUP.try_lock() {+ let _ = dedup.force_end_all_active();}+ return;}}let pointer_id = (wparam & 0xFFFF) as u32;@@ -1363,6 +1376,7 @@ mod win_impl {};let phase_code = decision.emit_phase;let prev_perf_cutoff = decision.prev_perf_cutoff;+ let prev_frame_id = decision.prev_frame_id;let prev_ts_ms = decision.prev_ts_ms;let mut max_perf_emitted = prev_perf_cutoff;let mut running_ts = prev_ts_ms;@@ -1393,13 +1407,22 @@ mod win_impl {let info = &history[idx];let pinfo = &info.pointerInfo;- // Skip already-emitted overlapping history samples during drag- if phase_code == 2- && prev_perf_cutoff > 0- && pinfo.PerformanceCount > 0- && pinfo.PerformanceCount <= prev_perf_cutoff- {- continue;+ // Skip already-emitted overlapping history samples during drag or pen-up+ // (always keep idx == 0 on phase_code == 3 so pen-up itself is never dropped).+ if phase_code == 2 || (phase_code == 3 && idx > 0) {+ if prev_perf_cutoff > 0+ && pinfo.PerformanceCount > 0+ && pinfo.PerformanceCount <= prev_perf_cutoff+ {+ continue;+ }+ if pinfo.PerformanceCount == 0+ && prev_frame_id != 0+ && pinfo.frameId != 0+ && (pinfo.frameId.wrapping_sub(prev_frame_id) as i32) <= 0+ {+ continue;+ }}if pinfo.PerformanceCount > max_perf_emitted {max_perf_emitted = pinfo.PerformanceCount;@@ -1675,6 +1698,9 @@ mod win_impl {sys_ext_y: i32,coord_mapper: WintabCoordMapper,contact: WintabContactState,+ last_contact_phys: (f32, f32),+ last_contact_css: (f32, f32),+ has_contact_pos: bool,was_foreground: bool,last_ts_ms: f64,engine_tx: Option<ink_engine::TabletRingProducer>,@@ -2040,15 +2066,43 @@ mod win_impl {let out_of_proximity = (pkt.pk_status & TPS_PROXIMITY) != 0;let tip_button_down = (pkt.pk_buttons & 1) != 0;- let (phase, pressure, eff_tip_down) = rt.contact.step(+ let Some((phase, pressure, eff_tip_down)) = rt.contact.step(out_of_proximity,raw_pressure,tip_button_down,sample_ts,- );+ ) else {+ // Single-packet zero-pressure debounce hold: keep stroke alive without+ // feeding post-lift hover coordinates into the stroke.+ WINTAB_IN_PROXIMITY.store(!out_of_proximity, Ordering::Release);+ STYLUS_IN_CONTACT.store(true, Ordering::Release);+ continue;+ };WINTAB_IN_PROXIMITY.store(!out_of_proximity, Ordering::Release);STYLUS_IN_CONTACT.store(eff_tip_down, Ordering::Release);+ // Record exact last in-contact coordinates and anchor pen-up (phase 3)+ // there so post-lift hover recoil never injects a hook at stroke end.+ let (emit_phys_x, emit_phys_y, emit_cx, emit_cy) = if phase == 1 || phase == 2 {+ rt.last_contact_phys = (phys_x, phys_y);+ rt.last_contact_css = (cx, cy);+ rt.has_contact_pos = true;+ (phys_x, phys_y, cx, cy)+ } else if phase == 3 && rt.has_contact_pos {+ rt.has_contact_pos = false;+ (+ rt.last_contact_phys.0,+ rt.last_contact_phys.1,+ rt.last_contact_css.0,+ rt.last_contact_css.1,+ )+ } else {+ if phase == 4 {+ rt.has_contact_pos = false;+ }+ (phys_x, phys_y, cx, cy)+ };+let mut buttons: u16 = 0;if eff_tip_down {buttons |= 1;@@ -2064,8 +2118,8 @@ mod win_impl {}let ns = ink_engine::NativeInputSample {- phys_x,- phys_y,+ phys_x: emit_phys_x,+ phys_y: emit_phys_y,pressure,tilt_x,tilt_y,@@ -2093,8 +2147,8 @@ mod win_impl {if has_js_sink && !owned_by_engine {rt.scratch_forward_js.push(TabletSample {- client_x: cx,- client_y: cy,+ client_x: emit_cx,+ client_y: emit_cy,pressure,tilt_x,tilt_y,@@ -2356,6 +2410,9 @@ mod win_impl {sys_ext_y: lc.lc_sys_ext_y,coord_mapper: WintabCoordMapper::default(),contact: WintabContactState::default(),+ last_contact_phys: (0.0, 0.0),+ last_contact_css: (0.0, 0.0),+ has_contact_pos: false,was_foreground: GetForegroundWindow() == main_hwnd as HWND,last_ts_ms: 0.0,engine_tx,@@ -2851,40 +2908,38 @@ mod tests {let mut wt = WintabContactState::default();// 1. Light pen down (e.g. 4 / 8192 = 0.000488, previously dropped by > 0.001 check!)- let (p1, pr1, down1) = wt.step(false, 0.0005, false, 100.0);+ let (p1, pr1, down1) = wt.step(false, 0.0005, false, 100.0).unwrap();assert_eq!(p1, 1);assert!(down1);assert!(pr1 >= 0.006);// 2. Normal drag- let (p2, pr2, down2) = wt.step(false, 0.35, true, 104.0);+ let (p2, pr2, down2) = wt.step(false, 0.35, true, 104.0).unwrap();assert_eq!(p2, 2);assert!(down2);assert!((pr2 - 0.35).abs() < 1e-5);- // 3. Single-packet zero-pressure micro-dip while still in proximity -> MUST NOT end stroke!- let (p3, pr3, down3) = wt.step(false, 0.0, false, 108.0);- assert_eq!(p3, 2);- assert!(down3);- assert!(pr3 >= 0.006);+ // 3. Single-packet zero-pressure micro-dip while still in proximity -> held silently+ // (does NOT end stroke AND does NOT emit post-lift hover coordinates into the stroke!)+ assert!(wt.step(false, 0.0, false, 108.0).is_none());+ assert!(wt.was_down);// 4. Next packet recovers light pressure -> continues seamlessly as phase=2- let (p4, pr4, down4) = wt.step(false, 0.02, false, 112.0);+ let (p4, pr4, down4) = wt.step(false, 0.02, false, 112.0).unwrap();assert_eq!(p4, 2);assert!(down4);assert!((pr4 - 0.02).abs() < 1e-5);- // 5. Genuine lift: 2 consecutive zero-pressure packets cleanly emit phase=3 on the 2nd packet- let (p5, _, down5) = wt.step(false, 0.0, false, 116.0);- assert_eq!(p5, 2);- assert!(down5);- let (p6, pr6, down6) = wt.step(false, 0.0, false, 120.0);+ // 5. Genuine lift: 1st zero-pressure packet is suppressed (no hover hook),+ // 2nd consecutive zero-pressure packet cleanly emits phase=3+ assert!(wt.step(false, 0.0, false, 116.0).is_none());+ let (p6, pr6, down6) = wt.step(false, 0.0, false, 120.0).unwrap();assert_eq!(p6, 3);assert!(!down6);assert_eq!(pr6, 0.0);// 6. Hover packets stay phase=0- let (p7, pr7, down7) = wt.step(false, 0.0, false, 124.0);+ let (p7, pr7, down7) = wt.step(false, 0.0, false, 124.0).unwrap();assert_eq!(p7, 0);assert!(!down7);assert_eq!(pr7, 0.0);@@ -3168,4 +3223,28 @@ mod tests {);assert!(ring_outside_again.is_none());}++ #[test]+ fn test_ink_state_machine_carries_perf_and_frame_cutoff_into_pointer_up() {+ let mut sm = InkStateMachine::default();+ let main_hwnd: isize = 1000;+ let pid: u32 = 99;++ let d1 = sm.process_message(main_hwnd, main_hwnd, pid, 1, 50, true).unwrap();+ assert_eq!(d1.emit_phase, 1);+ sm.record_emitted(pid, 1, 1000, 10.0);++ let d2 = sm.process_message(main_hwnd, main_hwnd, pid, 2, 51, true).unwrap();+ assert_eq!(d2.emit_phase, 2);+ assert_eq!(d2.prev_perf_cutoff, 1000);+ assert_eq!(d2.prev_frame_id, 50);+ sm.record_emitted(pid, 2, 2000, 14.0);++ // WM_POINTERUP MUST receive prior perf & frame cutoffs so overlapping coalesced history+ // samples from frame 51 are never replayed backward at the end of the stroke!+ let d3 = sm.process_message(main_hwnd, main_hwnd, pid, 3, 52, false).unwrap();+ assert_eq!(d3.emit_phase, 3);+ assert_eq!(d3.prev_perf_cutoff, 2000);+ assert_eq!(d3.prev_frame_id, 51);+ }}diff --git a/src/components/BrushSizePalette.tsx b/src/components/BrushSizePalette.tsxindex d83b042..b42f005 100644--- a/src/components/BrushSizePalette.tsx+++ b/src/components/BrushSizePalette.tsx@@ -61,12 +61,7 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = React.memo(({if (tool === 'decoration') {return <Sparkles className="w-3.5 h-3.5 text-ui-accent shrink-0" />;}- if (- presetId?.startsWith('pencil') ||- presetId === 'mechanical-pencil' ||- presetId === 'charcoal-pencil' ||- presetId === 'standard-chalk'- ) {+ if (presetId?.startsWith('pencil')) {return <Pencil className="w-3.5 h-3.5 text-ui-warning shrink-0" />;}if (presetId === 'square-digital') {diff --git a/src/components/BrushStudioModal.tsx b/src/components/BrushStudioModal.tsxindex b8f9b3e..9ea642f 100644--- a/src/components/BrushStudioModal.tsx+++ b/src/components/BrushStudioModal.tsx@@ -330,7 +330,10 @@ export const BrushStudioModal: React.FC<BrushStudioModalProps> = ({{/* Center Interactive Live Scratchpad */}<div className="flex-1 min-w-[320px] flex flex-col min-h-0">- <BrushStudioScratchpad brushSettings={brushSettings} />+ <BrushStudioScratchpad+ brushSettings={brushSettings}+ onPatchSettings={handlePatchSettings}+ /></div>{/* Right Parameter Inspector (Hairline SectionDisclosure stack) */}diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsxindex 129704d..ca4ae78 100644--- a/src/components/SubToolList.tsx+++ b/src/components/SubToolList.tsx@@ -725,25 +725,30 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(removeOrphanShortcut(getSubToolCommandId(brush.id));setCustomBrushes((prev) => prev.filter((b) => b.id !== brush.id));if (activePreset === brush.id) {- handleSelectBrushPreset(- isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID- );+ const fallbackId = isDecorationMode+ ? DEFAULT_DECORATION_PRESET_ID ||+ customBrushes.find((b) => b.id !== brush.id && isDecorationCategory(b.category))?.id ||+ DEFAULT_BRUSH_PRESET_ID+ : DEFAULT_BRUSH_PRESET_ID;+ handleSelectBrushPreset(fallbackId);}}};const handleCreateNewBrush = async () => {const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;- const base = buildExportableBrush('impasto-bristle-oil', customBrushes);+ const base = buildExportableBrush(DEFAULT_BRUSH_PRESET_ID, customBrushes);const targetCategory: BrushCategory = isDecorationMode? isDecorationCategory(effectiveActiveDecorationTab)? effectiveActiveDecorationTab: 'deco-effect'- : 'natural-paint';+ : isBuiltinGroupTab(effectiveActiveTab) && !isDecorationCategory(effectiveActiveTab)+ ? effectiveActiveTab+ : 'pen';const newBrush: CspBrush = {...base,id,- name: isDecorationMode ? t('New Decoration Brush') : t('New Natural Brush'),+ name: isDecorationMode ? t('New Decoration Brush') : t('New Brush'),category: targetCategory,badge: isDecorationMode ? 'Decoration' : 'Studio',importedAt: Date.now(),@@ -1975,7 +1980,9 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(onClick={() =>handleExportBrush(activePreset ||- (isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID)+ (isDecorationMode+ ? DEFAULT_DECORATION_PRESET_ID || DEFAULT_BRUSH_PRESET_ID+ : DEFAULT_BRUSH_PRESET_ID))}title={t('Export Active Brush (.inkb)')}@@ -2423,6 +2430,19 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(scopedCustomGroups.map((group, idx) => renderCustomGroupSection(group, idx, false))}{/* Decoration Tool Group Sections (Background, Clothing, Effect — CSP-style) */}+ {isDecorationMode &&+ effectiveActiveDecorationTab === 'all' &&+ decorationCustomGroups.length === 0 &&+ !activeBrushDrag &&+ DECORATION_BRUSH_SECTIONS.every((sec) => builtinGroupMemberIds[sec.id].length === 0) && (+ <div+ data-testid="subtool-decoration-empty-state"+ className="px-2 py-4 text-[10px] text-ui-muted text-center border border-dashed border-ui-default rounded-ui-sm"+ >+ {t('No decoration brushes. Import (.inkb / .sut) or click New to add one.')}+ </div>+ )}+{isDecorationMode &&(effectiveActiveDecorationTab === 'all' ||isDecorationCategory(effectiveActiveDecorationTab)) &&diff --git a/src/components/__tests__/brushStudioLivePreview.test.tsx b/src/components/__tests__/brushStudioLivePreview.test.tsxnew file mode 100644index 0000000..cc052f0--- /dev/null+++ b/src/components/__tests__/brushStudioLivePreview.test.tsx@@ -0,0 +1,535 @@+import { act } from 'react';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { createRoot, Root } from 'react-dom/client';+import { BrushStudioModal } from '../BrushStudioModal';+import { BrushStudioScratchpad } from '../brushStudio/BrushStudioScratchpad';+import { toolStoreActions, useToolStore } from '../../stores';+import { NEUTRAL_BRUSH_DEFAULTS } from '../../utils/brushPresetManager';+import type { BrushSettings } from '../../types/editor';+import * as nativeBridge from '../../utils/nativeEngineBridge';++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++interface MockCanvasDrawLog {+ clears: number;+ ellipses: Array<{ rx: number; ry: number }>;+ arcs: Array<{ r: number }>;+ strokes: number;+}++class MiniText {+ nodeType = 3;+ nodeName = '#text';+ parentNode: MiniEl | null = null;+ constructor(+ public nodeValue: string,+ public ownerDocument: MiniDoc+ ) {}+}++class MiniComment {+ nodeType = 8;+ nodeName = '#comment';+ parentNode: MiniEl | null = null;+ constructor(+ public nodeValue: string,+ public ownerDocument: MiniDoc+ ) {}+}++class MiniStyle {+ private map = new Map<string, string>();+ [key: string]: unknown;+ setProperty(k: string, v: string) {+ this.map.set(k, String(v));+ this[k] = String(v);+ }+ getPropertyValue(k: string): string {+ return this.map.get(k) ?? (typeof this[k] === 'string' ? (this[k] as string) : '');+ }+ removeProperty(k: string) {+ this.map.delete(k);+ delete this[k];+ }+}++class MiniEl extends EventTarget {+ nodeType = 1;+ nodeName: string;+ tagName: string;+ namespaceURI = 'http://www.w3.org/1999/xhtml';+ parentNode: MiniEl | null = null;+ childNodes: Array<MiniEl | MiniText | MiniComment> = [];+ style = new MiniStyle();+ className = '';+ disabled = false;+ type = '';+ checked = false;+ oninput: ((ev: Event) => void) | null = null;+ clientWidth = 560;+ clientHeight = 440;+ width = 560;+ height = 440;+ attrs = new Map<string, string>();+ private _value = '';+ mockDrawLog: MockCanvasDrawLog = { clears: 0, ellipses: [], arcs: [], strokes: 0 };+ private mockCtx: Record<string, unknown> | null = null;++ constructor(+ tag: string,+ public ownerDocument: MiniDoc+ ) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ }++ get value(): string {+ return this._value;+ }+ set value(v: string) {+ this._value = String(v);+ }+ get firstChild() {+ return this.childNodes[0] ?? null;+ }+ get textContent(): string {+ return this.childNodes+ .map((c) =>+ c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''+ )+ .join('');+ }+ set textContent(val: string) {+ this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];+ }++ getBoundingClientRect() {+ return {+ left: 0,+ top: 0,+ right: this.clientWidth,+ bottom: this.clientHeight,+ width: this.clientWidth,+ height: this.clientHeight,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ };+ }++ getContext(kind: string) {+ if (this.tagName !== 'CANVAS' || kind !== '2d') return null;+ if (!this.mockCtx) {+ const log = this.mockDrawLog;+ this.mockCtx = {+ save: () => {},+ restore: () => {},+ translate: () => {},+ rotate: () => {},+ scale: () => {},+ beginPath: () => {},+ moveTo: () => {},+ lineTo: () => {},+ fill: () => {},+ stroke: () => {+ log.strokes += 1;+ },+ clearRect: () => {+ log.clears += 1;+ },+ fillRect: () => {},+ drawImage: () => {},+ putImageData: () => {},+ ellipse: (_x: number, _y: number, rx: number, ry: number) => {+ log.ellipses.push({ rx, ry });+ },+ arc: (_x: number, _y: number, r: number) => {+ log.arcs.push({ r });+ },+ globalAlpha: 1,+ fillStyle: '#000',+ strokeStyle: '#000',+ lineCap: 'round',+ lineJoin: 'round',+ lineWidth: 1,+ globalCompositeOperation: 'source-over',+ };+ }+ return this.mockCtx;+ }++ setPointerCapture() {}+ releasePointerCapture() {}+ hasPointerCapture() {+ return false;+ }+ focus() {+ this.ownerDocument.activeElement = this;+ }+ blur() {+ if (this.ownerDocument.activeElement === this) {+ this.ownerDocument.activeElement = this.ownerDocument.body;+ }+ }+ select() {}+ scrollIntoView() {}++ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ insertBefore<T extends MiniEl | MiniText | MiniComment>(+ child: T,+ ref: MiniEl | MiniText | MiniComment | null+ ): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ if (!ref) {+ this.childNodes.push(child);+ return child;+ }+ const idx = this.childNodes.indexOf(ref);+ if (idx >= 0) this.childNodes.splice(idx, 0, child);+ else this.childNodes.push(child);+ return child;+ }++ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) this.childNodes.splice(idx, 1);+ child.parentNode = null;+ return child;+ }++ setAttribute(name: string, value: string) {+ const v = String(value);+ this.attrs.set(name, v);+ if (name === 'class') this.className = v;+ if (name === 'type') this.type = v;+ if (name === 'value') this._value = v;+ if (name === 'width') this.width = Number(v) || this.width;+ if (name === 'height') this.height = Number(v) || this.height;+ }++ getAttribute(name: string): string | null {+ if (name === 'class') return this.className || this.attrs.get('class') || null;+ return this.attrs.get(name) ?? null;+ }++ removeAttribute(name: string) {+ this.attrs.delete(name);+ if (name === 'class') this.className = '';+ }++ hasAttribute(name: string): boolean {+ return this.attrs.has(name);+ }++ override dispatchEvent(event: Event): boolean {+ if (!event.target) {+ Object.defineProperty(event, 'target', { value: this, configurable: true });+ }+ let cur: MiniEl | null = this;+ while (cur) {+ Object.defineProperty(event, 'currentTarget', { value: cur, configurable: true });+ EventTarget.prototype.dispatchEvent.call(cur, event);+ if (!event.bubbles || event.cancelBubble) break;+ cur = cur.parentNode;+ }+ return !event.defaultPrevented;+ }++ click() {+ this.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));+ }+}++class MiniDoc extends EventTarget {+ nodeType = 9;+ defaultView: unknown = globalThis;+ oninput: ((ev: Event) => void) | null = null;+ documentElement: MiniEl;+ head: MiniEl;+ body: MiniEl;+ activeElement: MiniEl | null = null;++ constructor() {+ super();+ this.documentElement = new MiniEl('html', this);+ this.head = new MiniEl('head', this);+ this.body = new MiniEl('body', this);+ this.documentElement.appendChild(this.head);+ this.documentElement.appendChild(this.body);+ this.activeElement = this.body;+ }++ createElement(tag: string) {+ return new MiniEl(tag, this);+ }+ createElementNS(_ns: string, tag: string) {+ return new MiniEl(tag, this);+ }+ createTextNode(text: string) {+ return new MiniText(text, this);+ }+ createComment(text: string) {+ return new MiniComment(text, this);+ }+}++function byTestId(rootEl: MiniEl, id: string): MiniEl | null {+ if (rootEl.getAttribute('data-testid') === id) return rootEl;+ for (const c of rootEl.childNodes) {+ if (c instanceof MiniEl) {+ const hit = byTestId(c, id);+ if (hit) return hit;+ }+ }+ return null;+}++function makePointerEvent(+ type: string,+ props: {+ button?: number;+ pointerId?: number;+ pointerType?: string;+ clientX?: number;+ clientY?: number;+ pressure?: number;+ }+): Event {+ const ev = new Event(type, { bubbles: true, cancelable: true });+ Object.assign(ev, {+ button: props.button ?? 0,+ pointerId: props.pointerId ?? 1,+ pointerType: props.pointerType ?? 'pen',+ clientX: props.clientX ?? 0,+ clientY: props.clientY ?? 0,+ pressure: props.pressure ?? 0.8,+ tiltX: 0,+ tiltY: 0,+ twist: 0,+ });+ return ev;+}++function makeTestBrush(overrides: Partial<BrushSettings> = {}): BrushSettings {+ return {+ ...NEUTRAL_BRUSH_DEFAULTS,+ color: '#1d4ed8',+ size: 10,+ opacity: 1,+ flow: 1,+ hardness: 1,+ spacing: 0.1,+ smoothing: true,+ stabilization: 0,+ usePressure: true,+ minSizeFactor: 0.1,+ ...overrides,+ };+}++describe('Brush Studio Live Preview', () => {+ let doc: MiniDoc;+ let container: MiniEl;+ let root: Root | null = null;+ const origDoc = globalThis.document;+ const origWin = globalThis.window;+ const origHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const origHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const origNode = (globalThis as Record<string, unknown>).Node;+ const origElement = (globalThis as Record<string, unknown>).Element;++ beforeEach(() => {+ doc = new MiniDoc();+ container = doc.createElement('div');+ doc.body.appendChild(container);+ const winTarget = new EventTarget();+ class HTMLIFrameElementShim extends MiniEl {}+ const mockWindow = {+ document: doc,+ addEventListener: winTarget.addEventListener.bind(winTarget),+ removeEventListener: winTarget.removeEventListener.bind(winTarget),+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),+ HTMLElement: MiniEl,+ HTMLIFrameElement: HTMLIFrameElementShim,+ Node: MiniEl,+ Element: MiniEl,+ };+ doc.defaultView = mockWindow;+ Object.defineProperty(globalThis, 'document', { value: doc, configurable: true });+ Object.defineProperty(globalThis, 'window', { value: mockWindow, configurable: true });+ (globalThis as Record<string, unknown>).HTMLElement = MiniEl;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = HTMLIFrameElementShim;+ (globalThis as Record<string, unknown>).Node = MiniEl;+ (globalThis as Record<string, unknown>).Element = MiniEl;+ vi.spyOn(nativeBridge, 'isNativeCanvasActive').mockReturnValue(false);+ toolStoreActions.updateBrushSettings(makeTestBrush({ size: 12 }));+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root!.unmount();+ });+ root = null;+ }+ Object.defineProperty(globalThis, 'document', { value: origDoc, configurable: true });+ Object.defineProperty(globalThis, 'window', { value: origWin, configurable: true });+ (globalThis as Record<string, unknown>).HTMLElement = origHTMLElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = origHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Node = origNode;+ (globalThis as Record<string, unknown>).Element = origElement;+ vi.restoreAllMocks();+ });++ it('re-renders a user-drawn stroke in real time when brush size changes', () => {+ root = createRoot(container as unknown as HTMLElement);+ const initialBs = makeTestBrush({ size: 8, spacing: 0.12 });++ act(() => {+ root!.render(<BrushStudioScratchpad brushSettings={initialBs} />);+ });++ const baseCanvas = byTestId(container, 'scratchpad-base-canvas')!;+ const draftCanvas = byTestId(container, 'scratchpad-draft-canvas')!;+ expect(baseCanvas).not.toBeNull();+ expect(draftCanvas).not.toBeNull();++ // Starter S-curve sample stroke rendered immediately on mount+ expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);++ // Draw a custom stroke on the scratchpad+ baseCanvas.mockDrawLog.ellipses.length = 0;+ act(() => {+ draftCanvas.dispatchEvent(+ makePointerEvent('pointerdown', { pointerId: 1, clientX: 80, clientY: 200, pressure: 0.8 })+ );+ draftCanvas.dispatchEvent(+ makePointerEvent('pointermove', { pointerId: 1, clientX: 260, clientY: 220, pressure: 0.8 })+ );+ draftCanvas.dispatchEvent(+ makePointerEvent('pointerup', { pointerId: 1, clientX: 260, clientY: 220, pressure: 0.8 })+ );+ });++ expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);+ const smallMaxRadius = Math.max(...baseCanvas.mockDrawLog.ellipses.map((e) => e.rx));++ // Increase brush size to 48px — recorded stroke must immediately re-render wider!+ baseCanvas.mockDrawLog.ellipses.length = 0;+ baseCanvas.mockDrawLog.clears = 0;+ act(() => {+ root!.render(+ <BrushStudioScratchpad brushSettings={makeTestBrush({ size: 48, spacing: 0.12 })} />+ );+ });++ expect(baseCanvas.mockDrawLog.clears).toBeGreaterThan(0);+ expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);+ const largeMaxRadius = Math.max(...baseCanvas.mockDrawLog.ellipses.map((e) => e.rx));+ expect(largeMaxRadius).toBeGreaterThan(smallMaxRadius * 4);+ });++ it('freezes drawn strokes when Live toggle is turned off and resumes when turned back on', () => {+ root = createRoot(container as unknown as HTMLElement);+ act(() => {+ root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 10 })} />);+ });++ const baseCanvas = byTestId(container, 'scratchpad-base-canvas')!;+ const draftCanvas = byTestId(container, 'scratchpad-draft-canvas')!;+ const liveBtn = byTestId(container, 'scratchpad-live-toggle')!;++ act(() => {+ draftCanvas.dispatchEvent(+ makePointerEvent('pointerdown', { pointerId: 2, clientX: 100, clientY: 150 })+ );+ draftCanvas.dispatchEvent(+ makePointerEvent('pointermove', { pointerId: 2, clientX: 240, clientY: 160 })+ );+ draftCanvas.dispatchEvent(+ makePointerEvent('pointerup', { pointerId: 2, clientX: 240, clientY: 160 })+ );+ });++ // Turn Live Preview OFF+ expect(liveBtn.getAttribute('aria-pressed')).toBe('true');+ act(() => {+ liveBtn.click();+ });+ expect(liveBtn.getAttribute('aria-pressed')).toBe('false');++ baseCanvas.mockDrawLog.ellipses.length = 0;+ baseCanvas.mockDrawLog.clears = 0;+ act(() => {+ root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 60 })} />);+ });+ // Frozen — no re-render on setting change+ expect(baseCanvas.mockDrawLog.clears).toBe(0);+ expect(baseCanvas.mockDrawLog.ellipses.length).toBe(0);++ // Turn Live Preview back ON — immediately replays stroke with size=60+ act(() => {+ liveBtn.click();+ });+ expect(baseCanvas.mockDrawLog.clears).toBeGreaterThan(0);+ expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);+ });++ it('exposes live quick-tune Size, Opacity, and Flow controls inside BrushStudioModal', () => {+ root = createRoot(container as unknown as HTMLElement);+ act(() => {+ root!.render(<BrushStudioModal isOpen onClose={vi.fn()} showToast={vi.fn()} />);+ });++ const sizeSlider = byTestId(container, 'scratchpad-size-slider')!;+ const opacitySlider = byTestId(container, 'scratchpad-opacity-slider')!;+ const flowSlider = byTestId(container, 'scratchpad-flow-slider')!;+ expect(sizeSlider).not.toBeNull();+ expect(opacitySlider).not.toBeNull();+ expect(flowSlider).not.toBeNull();++ // Trigger React's controlled range input onChange handler (handles both DOM input and Node-import fallback)+ const propsKey = Object.keys(sizeSlider).find((k) => k.startsWith('__reactProps$'));+ const reactProps = propsKey+ ? (sizeSlider as unknown as Record<string, { onChange?: (ev: unknown) => void }>)[propsKey]+ : undefined;+ expect(typeof reactProps?.onChange).toBe('function');+ act(() => {+ sizeSlider.value = '72';+ reactProps?.onChange?.({ target: sizeSlider, currentTarget: sizeSlider });+ });+ expect(useToolStore.getState().brushSettings.size).toBe(72);+ });++ it('dispatches recorded strokes to DX12 renderNativeScratchpadPreview when native canvas is active', async () => {+ vi.spyOn(nativeBridge, 'isNativeCanvasActive').mockReturnValue(true);+ const nativeSpy = vi+ .spyOn(nativeBridge, 'renderNativeScratchpadPreview')+ .mockResolvedValue(null);++ root = createRoot(container as unknown as HTMLElement);+ await act(async () => {+ root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 16 })} />);+ });+ expect(nativeSpy).toHaveBeenCalledTimes(1);+ expect(nativeSpy.mock.calls[0][1].size).toBe(16);+ expect(nativeSpy.mock.calls[0][4].length).toBe(1);++ // Editing brush size immediately triggers a fresh DX12 preview render on the same stroke+ await act(async () => {+ root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 42 })} />);+ });+ expect(nativeSpy.mock.calls.length).toBeGreaterThanOrEqual(2);+ const lastCall = nativeSpy.mock.calls[nativeSpy.mock.calls.length - 1];+ expect(lastCall[1].size).toBe(42);+ expect(lastCall[4].length).toBe(1);+ });+});diff --git a/src/components/brushStudio/BrushStudioScratchpad.tsx b/src/components/brushStudio/BrushStudioScratchpad.tsxindex c6e0d09..6f77be6 100644--- a/src/components/brushStudio/BrushStudioScratchpad.tsx+++ b/src/components/brushStudio/BrushStudioScratchpad.tsx@@ -1,13 +1,28 @@-import React, { useRef, useState, useCallback } from 'react';-import { Eraser, Droplets, Sun, Moon, Square } from 'lucide-react';-import type { BrushSettings, Point } from '../../types/editor';+import React, { useRef, useState, useCallback, useEffect } from 'react';+import { Eraser, Droplets, Sun, Moon, Square, Radio, Spline } from 'lucide-react';+import type { BrushSettings } from '../../types/editor';import { IconButton, SegmentedControl } from '../ui';-import { isNaturalPaintBrush } from '../../utils/brushMath';-import { cleanNativeDirtyBrush } from '../../utils/nativeEngineBridge';+import {+ cleanNativeDirtyBrush,+ isNativeCanvasActive,+ renderNativeScratchpadPreview,+} from '../../utils/nativeEngineBridge';+import {+ buildDefaultSampleStroke,+ RecordedScratchpadStroke,+ renderScratchpadStrokes2D,+ renderSingleScratchpadStroke2D,+ ScratchpadSamplePoint,+ toNativeScratchpadStrokes,+} from '../../utils/scratchpadRenderer';import { useI18n } from '../../i18n';type ScratchpadBg = 'dark' | 'gray' | 'white';+const SCRATCHPAD_W = 560;+const SCRATCHPAD_H = 440;+const MAX_RECORDED_STROKES = 24;+const BG_COLORS: Record<ScratchpadBg, string> = {dark: '#18181b',gray: '#525252',@@ -30,10 +45,12 @@ const QUICK_SWATCHES = [export interface BrushStudioScratchpadProps {brushSettings: BrushSettings;+ onPatchSettings?: (patch: Partial<BrushSettings>) => void;}export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({brushSettings,+ onPatchSettings,}) => {const { t, tc } = useI18n();const baseCanvasRef = useRef<HTMLCanvasElement | null>(null);@@ -41,29 +58,201 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({const [bgMode, setBgMode] = useState<ScratchpadBg>('white');const [testColor, setTestColor] = useState<string>(brushSettings.color || '#1d4ed8');const [useActiveColor, setUseActiveColor] = useState<boolean>(true);+ const [livePreview, setLivePreview] = useState<boolean>(true);+ const [showSampleStroke, setShowSampleStroke] = useState<boolean>(true);+ const [strokeCount, setStrokeCount] = useState<number>(0);+ const [renderRevision, setRenderRevision] = useState<number>(0);const activeColor = useActiveColor ? brushSettings.color || '#1d4ed8' : testColor;+ const strokesRef = useRef<RecordedScratchpadStroke[]>([]);+ const showSampleStrokeRef = useRef<boolean>(true);+ const nextStrokeIdRef = useRef<number>(1);+ const renderTokenRef = useRef<number>(0);+ const gpuInFlightRef = useRef<boolean>(false);+ const gpuPendingRef = useRef<{+ token: number;+ bs: BrushSettings;+ color: string;+ strokes: RecordedScratchpadStroke[];+ } | null>(null);+const sessionRef = useRef<{drawing: boolean;pointerId: number;- lastPoint: Point | null;- randState: number;+ activeStroke: RecordedScratchpadStroke | null;+ clearedSampleOnDown: boolean;}>({drawing: false,pointerId: -1,- lastPoint: null,- randState: 0x2468ace1,+ activeStroke: null,+ clearedSampleOnDown: false,});+ const paintRgbaToBase = useCallback((rgba: Uint8ClampedArray<ArrayBuffer>, w: number, h: number) => {+ const base = baseCanvasRef.current;+ if (!base) return;+ const bCtx = base.getContext('2d');+ if (!bCtx) return;+ if (typeof ImageData !== 'undefined') {+ const imgData = new ImageData(rgba, w, h);+ if (w === base.width && h === base.height) {+ bCtx.clearRect(0, 0, base.width, base.height);+ bCtx.putImageData(imgData, 0, 0);+ } else {+ const tmp = document.createElement('canvas');+ tmp.width = w;+ tmp.height = h;+ tmp.getContext('2d')?.putImageData(imgData, 0, 0);+ bCtx.clearRect(0, 0, base.width, base.height);+ bCtx.drawImage(tmp, 0, 0, base.width, base.height);+ }+ }+ }, []);++ const clearDraftIfIdle = useCallback(() => {+ if (sessionRef.current.drawing) return;+ const draft = draftCanvasRef.current;+ draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);+ }, []);++ const dispatchGpuRender = useCallback(+ (+ token: number,+ bs: BrushSettings,+ color: string,+ strokes: RecordedScratchpadStroke[]+ ) => {+ if (gpuInFlightRef.current) {+ gpuPendingRef.current = { token, bs, color, strokes };+ return;+ }+ gpuInFlightRef.current = true;+ const nativeStrokes = toNativeScratchpadStrokes(strokes, color);+ void renderNativeScratchpadPreview(+ 'brush',+ bs,+ color,+ bs.secondaryColor || '#ffffff',+ nativeStrokes,+ SCRATCHPAD_W,+ SCRATCHPAD_H+ )+ .then((img) => {+ const isCleared = strokesRef.current.length === 0 && !showSampleStrokeRef.current;+ if (isCleared) return;+ if (img) {+ // Paint the latest finished frame if it hasn't been superseded by a newer clear/reset+ if (token >= renderTokenRef.current - 1) {+ paintRgbaToBase(img.rgba, img.width, img.height);+ clearDraftIfIdle();+ }+ } else {+ // Native renderer unavailable — fall back cleanly to 2D canvas replay+ const base = baseCanvasRef.current;+ const bCtx = base?.getContext('2d');+ if (base && bCtx) {+ renderScratchpadStrokes2D(bCtx, base.width, base.height, strokes, bs, color);+ clearDraftIfIdle();+ }+ }+ })+ .finally(() => {+ gpuInFlightRef.current = false;+ const pending = gpuPendingRef.current;+ if (pending) {+ gpuPendingRef.current = null;+ dispatchGpuRender(pending.token, pending.bs, pending.color, pending.strokes);+ }+ });+ },+ [clearDraftIfIdle, paintRgbaToBase]+ );++ // Re-render once custom tip image finishes async browser decode+ useEffect(() => {+ const img = brushSettings.customTipImage;+ if (!img || (img.complete && (img.naturalWidth || img.width) > 0)) return;+ const onLoad = () => setRenderRevision((r) => r + 1);+ if (typeof img.addEventListener === 'function') {+ img.addEventListener('load', onLoad, { once: true });+ return () => img.removeEventListener('load', onLoad);+ }+ return undefined;+ }, [brushSettings.customTipImage]);++ // Live re-render whenever brushSettings, activeColor, recorded strokes, or sample state changes+ useEffect(() => {+ const base = baseCanvasRef.current;+ if (!base) return;+ const bCtx = base.getContext('2d');+ if (!bCtx) return;++ const userStrokes = strokesRef.current;+ const strokesToRender =+ userStrokes.length > 0+ ? userStrokes+ : showSampleStroke+ ? [buildDefaultSampleStroke(base.width, base.height, activeColor)]+ : [];++ if (strokesToRender.length === 0) {+ renderTokenRef.current += 1;+ gpuPendingRef.current = null;+ bCtx.clearRect(0, 0, base.width, base.height);+ return;+ }++ // When Live preview is toggled OFF, only re-render on explicit stroke additions / sample toggle,+ // leaving existing strokes frozen for side-by-side comparison.+ if (!livePreview && userStrokes.length > 0) {+ return;+ }++ const token = ++renderTokenRef.current;+ if (isNativeCanvasActive()) {+ dispatchGpuRender(token, brushSettings, activeColor, strokesToRender);+ } else {+ renderScratchpadStrokes2D(bCtx, base.width, base.height, strokesToRender, brushSettings, activeColor);+ clearDraftIfIdle();+ }+ }, [+ brushSettings,+ activeColor,+ livePreview,+ showSampleStroke,+ strokeCount,+ renderRevision,+ dispatchGpuRender,+ clearDraftIfIdle,+ ]);+const clearScratchpad = useCallback(() => {+ renderTokenRef.current += 1;+ gpuPendingRef.current = null;+ strokesRef.current = [];+ showSampleStrokeRef.current = false;+ setStrokeCount(0);+ setShowSampleStroke(false);const base = baseCanvasRef.current;const draft = draftCanvasRef.current;base?.getContext('2d')?.clearRect(0, 0, base.width, base.height);draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);}, []);- const toCanvasPoint = (e: React.PointerEvent<HTMLCanvasElement>): Point => {+ const restoreSampleStroke = useCallback(() => {+ renderTokenRef.current += 1;+ gpuPendingRef.current = null;+ strokesRef.current = [];+ showSampleStrokeRef.current = true;+ setStrokeCount(0);+ setShowSampleStroke(true);+ setRenderRevision((r) => r + 1);+ }, []);++ const extractSamplePoint = (+ e: PointerEvent | React.PointerEvent<HTMLCanvasElement>+ ): ScratchpadSamplePoint => {const canvas = draftCanvasRef.current!;const rect = canvas.getBoundingClientRect();const scaleX = canvas.width / Math.max(1, rect.width);@@ -72,119 +261,23 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({const y = (e.clientY - rect.top) * scaleY;const pressure =e.pointerType === 'mouse' ? 0.72 : Math.max(0.05, Math.min(1, e.pressure || 0.5));- const minFactor = brushSettings.minSizeFactor ?? 0.25;- const baseSize = Math.min(110, Math.max(2, brushSettings.size || 24));- const width =- brushSettings.usePressure !== false- ? baseSize * (minFactor + (1 - minFactor) * pressure)- : baseSize;return {x,y,pressure,- width,tiltX: e.tiltX ?? 0,tiltY: e.tiltY ?? 0,twist: e.twist ?? 0,- timestamp: e.timeStamp,+ timestampMs: e.timeStamp || performance.now(),};};- const nextRand = () => {- const s = sessionRef.current;- s.randState = (Math.imul(s.randState, 1664525) + 1013904223) >>> 0;- return s.randState / 4294967296;- };-- const stampSegment = (ctx: CanvasRenderingContext2D, p0: Point, p1: Point) => {- const naturalMode = isNaturalPaintBrush(brushSettings);- const isSpray = Boolean(brushSettings.spray?.enabled);- const flow = Math.max(0.08, Math.min(1, brushSettings.flow ?? 1.0));- const hardness = Math.max(0.05, Math.min(1, brushSettings.hardness ?? 0.9));- const tipImg = brushSettings.customTipImage;-- ctx.save();- ctx.fillStyle = activeColor;- ctx.strokeStyle = activeColor;- ctx.lineCap = 'round';- ctx.lineJoin = 'round';-- const dist = Math.hypot(p1.x - p0.x, p1.y - p0.y);- if (isSpray) {- const steps = Math.max(1, Math.ceil(dist / Math.max(4, p1.width * 0.25)));- const particles = Math.max(3, Math.min(14, Math.round((brushSettings.spray?.density ?? 3) * 2)));- ctx.globalAlpha = flow * 0.7;- for (let i = 0; i <= steps; i++) {- const t = steps > 0 ? i / steps : 1;- const cx = p0.x + (p1.x - p0.x) * t;- const cy = p0.y + (p1.y - p0.y) * t;- const rad = Math.max(2, (p0.width + (p1.width - p0.width) * t) * 0.55);- for (let j = 0; j < particles; j++) {- const ang = nextRand() * Math.PI * 2;- const r = Math.sqrt(nextRand()) * rad;- const pr = Math.max(0.8, (brushSettings.spray?.particleSize ?? 3) * 0.35 * (0.4 + nextRand()));- ctx.beginPath();- ctx.arc(cx + Math.cos(ang) * r, cy + Math.sin(ang) * r, pr, 0, Math.PI * 2);- ctx.fill();- }- }- ctx.restore();- return;- }-- if (naturalMode) {- const strands = Math.max(6, Math.min(18, Math.round((brushSettings.bristle?.count ?? 20) * 0.5)));- const dx = p1.x - p0.x;- const dy = p1.y - p0.y;- const len = Math.hypot(dx, dy) || 1;- const nx = -dy / len;- const ny = dx / len;- const avgW = (p0.width + p1.width) * 0.5;- for (let b = 0; b < strands; b++) {- const frac = strands > 1 ? (b / (strands - 1)) * 2 - 1 : 0;- const off = frac * avgW * 0.44;- ctx.globalAlpha = flow * (0.42 + 0.45 * (1 - Math.abs(frac) * 0.4));- ctx.lineWidth = Math.max(1.0, (avgW / strands) * 1.35);- ctx.beginPath();- ctx.moveTo(p0.x + nx * off, p0.y + ny * off);- ctx.lineTo(p1.x + nx * off, p1.y + ny * off);- ctx.stroke();- }- ctx.restore();- return;- }-- if (tipImg && tipImg.complete && (tipImg.naturalWidth || tipImg.width) > 0) {- const sp = Math.max(1.5, Math.max(p0.width, p1.width) * Math.max(0.06, brushSettings.spacing ?? 0.12));- const steps = Math.max(1, Math.ceil(dist / sp));- ctx.globalAlpha = flow;- for (let i = 0; i <= steps; i++) {- const t = steps > 0 ? i / steps : 1;- const x = p0.x + (p1.x - p0.x) * t;- const y = p0.y + (p1.y - p0.y) * t;- const w = p0.width + (p1.width - p0.width) * t;- ctx.drawImage(tipImg, x - w * 0.5, y - w * 0.5, w, w);- }- ctx.restore();- return;- }-- const avgW = Math.max(1, (p0.width + p1.width) * 0.5);- if (hardness < 0.75) {- ctx.globalAlpha = flow * 0.32;- ctx.lineWidth = avgW * 1.25;- ctx.beginPath();- ctx.moveTo(p0.x, p0.y);- ctx.lineTo(p1.x, p1.y);- ctx.stroke();- }- ctx.globalAlpha = flow;- ctx.lineWidth = avgW;- ctx.beginPath();- ctx.moveTo(p0.x, p0.y);- ctx.lineTo(p1.x, p1.y);- ctx.stroke();- ctx.restore();+ const repaintActiveDraft = (stroke: RecordedScratchpadStroke) => {+ const draft = draftCanvasRef.current;+ const dCtx = draft?.getContext('2d');+ if (!draft || !dCtx) return;+ dCtx.clearRect(0, 0, draft.width, draft.height);+ renderSingleScratchpadStroke2D(dCtx, stroke, brushSettings, activeColor);};const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {@@ -195,54 +288,107 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({const dCtx = draft.getContext('2d');if (!dCtx) return;- draft.setPointerCapture(e.pointerId);- dCtx.clearRect(0, 0, draft.width, draft.height);- const pt = toCanvasPoint(e);- sessionRef.current.drawing = true;- sessionRef.current.pointerId = e.pointerId;- sessionRef.current.lastPoint = pt;- stampSegment(dCtx, pt, { ...pt, x: pt.x + 0.1, y: pt.y + 0.1 });+ try {+ draft.setPointerCapture(e.pointerId);+ } catch {+ // Ignore synthetic pointer capture errors in tests+ }++ // Clear the starter sample stroke from base canvas the moment the user starts drawing+ let clearedSample = false;+ if (strokesRef.current.length === 0 && showSampleStrokeRef.current) {+ clearedSample = true;+ showSampleStrokeRef.current = false;+ setShowSampleStroke(false);+ const base = baseCanvasRef.current;+ base?.getContext('2d')?.clearRect(0, 0, base.width, base.height);+ }++ const pt = extractSamplePoint(e);+ const id = nextStrokeIdRef.current++;+ const stroke: RecordedScratchpadStroke = {+ id,+ points: [pt],+ color: activeColor,+ followActiveColor: useActiveColor,+ seed: ((id * 2654435761) ^ 0x2468ace1) >>> 0,+ };++ sessionRef.current = {+ drawing: true,+ pointerId: e.pointerId,+ activeStroke: stroke,+ clearedSampleOnDown: clearedSample,+ };++ repaintActiveDraft(stroke);};const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {const s = sessionRef.current;- if (!s.drawing || e.pointerId !== s.pointerId) return;- const draft = draftCanvasRef.current;- const dCtx = draft?.getContext('2d');- if (!draft || !dCtx || !s.lastPoint) return;+ if (!s.drawing || e.pointerId !== s.pointerId || !s.activeStroke) return;++ const nativeEv = e.nativeEvent as PointerEvent | undefined;+ const coalesced =+ typeof nativeEv?.getCoalescedEvents === 'function' ? nativeEv.getCoalescedEvents() : null;- const pt = toCanvasPoint(e);- stampSegment(dCtx, s.lastPoint, pt);- s.lastPoint = pt;+ if (coalesced && coalesced.length > 0) {+ for (const ce of coalesced) {+ s.activeStroke.points.push(extractSamplePoint(ce));+ }+ } else {+ s.activeStroke.points.push(extractSamplePoint(e));+ }++ repaintActiveDraft(s.activeStroke);};const finishStroke = (e: React.PointerEvent<HTMLCanvasElement>) => {const s = sessionRef.current;if (!s.drawing || e.pointerId !== s.pointerId) return;+ const finished = s.activeStroke;s.drawing = false;s.pointerId = -1;- s.lastPoint = null;+ s.activeStroke = null;+ s.clearedSampleOnDown = false;const base = baseCanvasRef.current;const draft = draftCanvasRef.current;- if (draft?.hasPointerCapture(e.pointerId)) {+ if (draft?.hasPointerCapture?.(e.pointerId)) {try {draft.releasePointerCapture(e.pointerId);} catch {// Ignore release errors}}- if (base && draft) {- const bCtx = base.getContext('2d');- const dCtx = draft.getContext('2d');- if (bCtx && dCtx) {- bCtx.save();- bCtx.globalAlpha = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));- bCtx.drawImage(draft, 0, 0);- bCtx.restore();- dCtx.clearRect(0, 0, draft.width, draft.height);++ if (!finished || finished.points.length === 0) {+ draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);+ return;+ }++ if (!livePreview) {+ // Frozen comparison mode: bake stroke straight onto base canvas+ if (base && draft) {+ const bCtx = base.getContext('2d');+ const dCtx = draft.getContext('2d');+ if (bCtx && dCtx) {+ bCtx.save();+ bCtx.globalAlpha = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));+ bCtx.drawImage(draft, 0, 0);+ bCtx.restore();+ dCtx.clearRect(0, 0, draft.width, draft.height);+ }}+ strokesRef.current = [...strokesRef.current, finished].slice(-MAX_RECORDED_STROKES);+ setStrokeCount(strokesRef.current.length);+ return;}++ // Live Preview mode: record stroke and trigger real-time replay (DX12 GPU or 2D)+ strokesRef.current = [...strokesRef.current, finished].slice(-MAX_RECORDED_STROKES);+ setStrokeCount(strokesRef.current.length);+ setRenderRevision((r) => r + 1);};return (@@ -250,7 +396,7 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({data-testid="brush-studio-scratchpad"className="flex flex-col h-full bg-ui-void">- {/* Compact Top Scratchpad Toolbar: Ink Swatches | Background Switcher | Clear */}+ {/* Compact Top Scratchpad Toolbar: Ink Swatches | Surface | Live & Sample | Clear */}<div className="px-2.5 py-1.5 border-b border-ui-subtle flex items-center justify-between gap-2 bg-ui-header shrink-0"><div className="flex items-center gap-1.5 min-w-0"><button@@ -295,6 +441,38 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({</div><div className="flex items-center gap-1.5 shrink-0">+ <button+ type="button"+ data-testid="scratchpad-live-toggle"+ aria-pressed={livePreview}+ onClick={() => setLivePreview((v) => !v)}+ title={+ livePreview+ ? t('Live Preview ON — edits update drawn strokes in real time')+ : t('Live Preview OFF — strokes stay frozen for comparison')+ }+ className={`h-6 px-2 rounded-ui-xs border text-[10px] font-medium flex items-center gap-1 cursor-pointer transition-colors ${+ livePreview+ ? 'bg-ui-accent-subtle border-ui-accent-border/50 text-ui-primary'+ : 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-secondary'+ }`}+ >+ <Radio className={`w-2.5 h-2.5 ${livePreview ? 'text-ui-accent' : 'text-ui-muted'}`} />+ <span>{t('Live')}</span>+ </button>++ {strokeCount === 0 && !showSampleStroke && (+ <IconButton+ size="xs"+ variant="subtle"+ data-testid="scratchpad-sample-btn"+ onClick={restoreSampleStroke}+ title={t('Show Sample S-Curve Stroke')}+ icon={<Spline className="w-3 h-3" />}+ label={t('Sample')}+ />+ )}+<SegmentedControl<ScratchpadBg>size="xs"aria-label={t('Scratchpad Surface')}@@ -353,14 +531,16 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({><canvasref={baseCanvasRef}- width={560}- height={440}+ data-testid="scratchpad-base-canvas"+ width={SCRATCHPAD_W}+ height={SCRATCHPAD_H}className="absolute inset-0 w-full h-full pointer-events-none"/><canvasref={draftCanvasRef}- width={560}- height={440}+ data-testid="scratchpad-draft-canvas"+ width={SCRATCHPAD_W}+ height={SCRATCHPAD_H}onPointerDown={handlePointerDown}onPointerMove={handlePointerMove}onPointerUp={finishStroke}@@ -371,6 +551,68 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({</div></div>+ {/* Live Quick-Tune Bar (Size, Opacity, Flow) for instant visual feedback from any tab */}+ {onPatchSettings && (+ <div+ data-testid="scratchpad-quick-controls"+ className="px-3 py-1.5 bg-ui-panel border-t border-ui-subtle flex items-center gap-3 shrink-0 text-[10px]"+ >+ <label className="flex-1 flex items-center gap-2 min-w-0">+ <span className="text-ui-muted shrink-0">{t('Size')}</span>+ <input+ type="range"+ data-testid="scratchpad-size-slider"+ aria-label={t('Brush Size')}+ min={1}+ max={200}+ step={1}+ value={Math.round(Math.max(1, Math.min(200, brushSettings.size ?? 14)))}+ onChange={(e) => onPatchSettings({ size: Number(e.target.value) })}+ className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"+ />+ <span className="font-ui-mono tabular-nums text-ui-secondary w-9 text-right shrink-0">+ {Math.round(brushSettings.size ?? 14)}px+ </span>+ </label>+ <div className="w-px h-3.5 bg-ui-subtle shrink-0" />+ <label className="w-28 flex items-center gap-1.5 shrink-0">+ <span className="text-ui-muted shrink-0">{t('Opacity')}</span>+ <input+ type="range"+ data-testid="scratchpad-opacity-slider"+ aria-label={t('Opacity')}+ min={1}+ max={100}+ step={1}+ value={Math.round(Math.max(1, Math.min(100, (brushSettings.opacity ?? 1) * 100)))}+ onChange={(e) => onPatchSettings({ opacity: Number(e.target.value) / 100 })}+ className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"+ />+ <span className="font-ui-mono tabular-nums text-ui-secondary w-7 text-right shrink-0">+ {Math.round((brushSettings.opacity ?? 1) * 100)}%+ </span>+ </label>+ <div className="w-px h-3.5 bg-ui-subtle shrink-0" />+ <label className="w-24 flex items-center gap-1.5 shrink-0">+ <span className="text-ui-muted shrink-0">{t('Flow')}</span>+ <input+ type="range"+ data-testid="scratchpad-flow-slider"+ aria-label={t('Flow')}+ min={5}+ max={100}+ step={1}+ value={Math.round(Math.max(5, Math.min(100, (brushSettings.flow ?? 1) * 100)))}+ onChange={(e) => onPatchSettings({ flow: Number(e.target.value) / 100 })}+ className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"+ />+ <span className="font-ui-mono tabular-nums text-ui-secondary w-7 text-right shrink-0">+ {Math.round((brushSettings.flow ?? 1) * 100)}%+ </span>+ </label>+ </div>+ )}+{/* Clean Bottom Micro-Status Readout */}<div className="h-6 px-3 bg-ui-header border-t border-ui-subtle flex items-center justify-between gap-2 shrink-0 text-[10px]"><div className="flex items-center gap-1.5 min-w-0 text-ui-muted">diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex 5bf0810..d6fc821 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -280,6 +280,28 @@ export function useCanvasPointerHandlers({}};+ // Native DX12 engine owns Space+drag (pan/rotate/zoom-drag) directly at 120–240 Hz for+ // both mouse (WH_MOUSE_LL) and stylus (WinTab/Windows Ink). Skip duplicate JS drag loops+ // so WebView2 never fights Rust over camera coordinates.+ const isNativeOwnedSpaceNav = (+ resolved: { slot: string; action: ModifierAction },+ e: React.PointerEvent<HTMLElement>+ ): boolean => {+ if (!nativeCanvasActive || e.pointerType === 'touch') return false;+ if (+ resolved.slot !== 'space' &&+ resolved.slot !== 'shiftSpace' &&+ resolved.slot !== 'ctrlSpace'+ ) {+ return false;+ }+ return (+ resolved.action === 'pan' ||+ resolved.action === 'rotate' ||+ resolved.action === 'zoom-drag'+ );+ };+// Viewport background pointer down (fallback if an unstopped event bubbles past interaction surface)const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {if (e.defaultPrevented || isWorkspaceInteractionActive()) return;@@ -310,6 +332,11 @@ export function useCanvasPointerHandlers({}return;}+ if (isNativeOwnedSpaceNav(resolved, e)) {+ e.preventDefault();+ e.stopPropagation();+ return;+ }if (dispatchModifierAction(resolved.action, e, false)) {return;}@@ -350,6 +377,11 @@ export function useCanvasPointerHandlers({}return;}+ if (isNativeOwnedSpaceNav(resolved, e)) {+ e.preventDefault();+ e.stopPropagation();+ return;+ }if (dispatchModifierAction(resolved.action, e, true)) {return;}diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.tsindex 9dfd319..29ff238 100644--- a/src/hooks/useCanvasNavigation.ts+++ b/src/hooks/useCanvasNavigation.ts@@ -24,7 +24,7 @@ export interface CameraTransformState {flipY: boolean;}-export type CameraChangeSource = 'user' | 'resize' | 'programmatic';+export type CameraChangeSource = 'user' | 'resize' | 'programmatic' | 'native';export interface CameraChangeMeta {source: CameraChangeSource;@@ -278,13 +278,23 @@ export function useCanvasNavigation({// Direct rAF-coalesced camera broadcast to CanvasArea DOM & ViewportCompositor (ZERO React setState calls)const scheduleCameraBroadcast = useCallback((source: CameraChangeSource = 'user') => {- // Preserve higher-priority user intent if multiple updates coalesce into the same frame+ // Preserve higher-priority intent if multiple updates coalesce into the same frame:+ // 'user' > 'resize' > 'programmatic' > 'native'if (cameraBroadcastRafRef.current === null) {pendingCameraSourceRef.current = source;} else if (source === 'user') {pendingCameraSourceRef.current = 'user';- } else if (source === 'resize' && pendingCameraSourceRef.current === 'programmatic') {+ } else if (+ source === 'resize' &&+ (pendingCameraSourceRef.current === 'programmatic' ||+ pendingCameraSourceRef.current === 'native')+ ) {pendingCameraSourceRef.current = 'resize';+ } else if (+ source === 'programmatic' &&+ pendingCameraSourceRef.current === 'native'+ ) {+ pendingCameraSourceRef.current = 'programmatic';}if (cameraBroadcastRafRef.current !== null) return;cameraBroadcastRafRef.current = requestAnimationFrame(() => {@@ -458,7 +468,11 @@ export function useCanvasNavigation({commitNavStateImmediate();} else {scheduleCameraBroadcast(source);- scheduleNavStateCommit();+ // Native Rust gestures emit an explicit `commit: true` on GestureEnd / wheel settle;+ // avoid triggering React tree re-renders mid-drag when the user briefly pauses.+ if (source !== 'native') {+ scheduleNavStateCommit();+ }}},[broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast, scheduleNavStateCommit]diff --git a/src/hooks/useNativeEngineViewport.ts b/src/hooks/useNativeEngineViewport.tsindex 4e81948..0436725 100644--- a/src/hooks/useNativeEngineViewport.ts+++ b/src/hooks/useNativeEngineViewport.ts@@ -985,8 +985,11 @@ export function useNativeEngineViewport({});const unsubReactCam = navigation- ? navigation.subscribeCamera((cam) => {- if (applyingNativeCameraRef.current) return;+ ? navigation.subscribeCamera((cam, meta) => {+ // Never echo native Rust camera events back over IPC (their rAF broadcast fires+ // asynchronously after `applyingNativeCameraRef` resets, which would otherwise+ // overwrite Rust's live gesture camera with 16-32ms stale coordinates -> ghosting/lag).+ if (applyingNativeCameraRef.current || meta?.source === 'native') return;void setNativeCamera({panX: cam.pan.x,panY: cam.pan.y,@@ -1011,7 +1014,7 @@ export function useNativeEngineViewport({flipY: ev.flipY,},ev.commit,- 'programmatic'+ 'native');} finally {applyingNativeCameraRef.current = false;diff --git a/src/types/editor.ts b/src/types/editor.tsindex 09bd0fb..517f9dd 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -186,76 +186,6 @@ export type BrushPresetId =| 'rough-pen'| 'dot-pen'| 'calligraphy'- | 'tapered-ink-liner'- | 'sumi-fude-brush'- | 'silk-embroidery-ribbon'- | 'fine-hair-wisp'- // Sketch section- | 'mechanical-pencil'- | 'pencil-hb-2b'- | 'pencil-6b-8b'- | 'charcoal-pencil'- | 'standard-chalk'- | 'vine-charcoal-wash'- | 'compressed-charcoal-block'- | 'conte-sanguine-crayon'- | 'col-erase-sketch-pencil'- // Brush section (Painterly Coloring & Illustration)- | 'oil-flat-alla-prima'- | 'thick-oil-impasto'- | 'dry-bristle-rake-paint'- | 'concept-matte-chalk'- | 'silky-portrait-round'- | 'canvas-scumble-oil'- | 'soft-glaze-airbrush'- | 'atmospheric-grain-shader'- | 'fine-detail-filbert'- | 'sculptural-hard-square'- | 'opaque-gouache-flat'- | 'tapered-painterly-oval'- | 'silky-hair-locks'- | 'dry-hair-sheen'- | 'rough-concept-bristle'- | 'wedge-chisel-gouache'- | 'translucent-watercolor-wash'- | 'pastel-blush-airbrush'- | 'metallic-specular-glint'- // Blend section (Dedicated Pure Blenders)- | 'blend-velvet-soft'- | 'blend-oil-bristle'- | 'blend-matte-chalk'- | 'blend-rake-hair'- | 'blend-canvas-scumble'- | 'blend-fingertip'- | 'blend-charcoal-stump'- | 'blend-gouache-softener'- | 'blend-smoke-wisps'- | 'blend-palette-knife-smear'- // Natural Paint section- | 'impasto-bristle-oil'- | 'wet-mixing-filbert'- | 'dry-bristle-rake'- | 'heavy-body-acrylic'- | 'palette-knife-impasto'- | 'velvet-gouache'- | 'granulating-watercolor'- | 'oil-bristle-blender'- | 'pastel-stick-canvas'- | 'wide-hog-flat-oil'- | 'splayed-fan-foliage'- | 'sumi-ink-wash-natural'- | 'matte-casein-tempera'- // Texture & FX section- | 'painterly-foliage-leaves'- | 'bokeh-foreground-leaves'- | 'skin-freckles-pores'- | 'ethereal-smoke-mist'- | 'craggy-rock-bone'- | 'ember-ash-spatter'- | 'painterly-clouds'- | 'woven-brocade-fabric'- | 'luminous-rim-glow'- | 'stipple-halftone-grain'| string;export interface CspEffectorCurvePoint {diff --git a/src/utils/__tests__/brushCursorRotation.test.ts b/src/utils/__tests__/brushCursorRotation.test.tsindex 819219c..339b147 100644--- a/src/utils/__tests__/brushCursorRotation.test.ts+++ b/src/utils/__tests__/brushCursorRotation.test.ts@@ -53,69 +53,42 @@ describe('Rotating Brush Cursor & "This brush rotates" Setting', () => {resetBrushSettingsCache();});- it('auto-enables rotating cursor for all rake brushes and other rotating built-in presets', () => {- // 1. Natural Paint Dry Bristle Rake (bristle-ribbon): rotates with +90° perpendicular alignment- const natRake = getBuiltinBrushConfig('dry-bristle-rake')!;- expect(resolveBrushCursorRotationSpec(natRake, 'brush')).toEqual({+ it('auto-enables rotating cursor for bristle-ribbon and directional stamp brushes while keeping fixed pens non-rotating', () => {+ // 1. Natural Paint bristle-ribbon / bristle-hybrid configs rotate with +90° perpendicular alignment+ expect(+ resolveBrushCursorRotationSpec({ renderMode: 'bristle-ribbon' }, 'brush')+ ).toEqual({enabled: true,source: 'direction',orientationOffsetDeg: 90,});-- // 2. All Natural Paint bristle-ribbon / bristle-hybrid presets rotate perpendicular to stroke- const naturalPresets = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint');- expect(naturalPresets.length).toBeGreaterThan(0);- for (const def of naturalPresets) {- const cfg = getBuiltinBrushConfig(def.id)!;- const spec = resolveBrushCursorRotationSpec(cfg, 'brush');- expect(spec.enabled, `Natural Paint brush ${def.id} should rotate`).toBe(true);- expect(spec.source).toBe('direction');- expect(spec.orientationOffsetDeg).toBe(90);- }-- // 3. Brush & Blend Rake presets (stamp directional brushes): rotate with 0° offset- const paintRake = getBuiltinBrushConfig('dry-bristle-rake-paint')!;- expect(resolveBrushCursorRotationSpec(paintRake, 'brush')).toEqual({+ expect(+ resolveBrushCursorRotationSpec({ renderMode: 'bristle-hybrid' }, 'brush')+ ).toEqual({enabled: true,source: 'direction',- orientationOffsetDeg: 0,+ orientationOffsetDeg: 90,});- const blendRake = getBuiltinBrushConfig('blend-rake-hair')!;- expect(resolveBrushCursorRotationSpec(blendRake, 'brush')).toEqual({+ // 2. Directional stamp brushes rotate with 0° offset+ expect(+ resolveBrushCursorRotationSpec({ customTipAngleDynamics: 'direction' }, 'brush')+ ).toEqual({enabled: true,source: 'direction',orientationOffsetDeg: 0,});- // 4. Other directional stamp brushes auto-rotate- for (const id of [- 'thick-oil-impasto',- 'fine-detail-filbert',- 'blend-oil-bristle',- 'blend-matte-chalk',- 'blend-canvas-scumble',- 'blend-fingertip',- 'pencil-6b-8b',- 'standard-chalk',- ]) {- const cfg = getBuiltinBrushConfig(id)!;- expect(resolveBrushCursorRotationSpec(cfg, 'brush').enabled, `${id} should rotate`).toBe(true);- }-- // 5. Fixed / non-directional brushes do NOT auto-rotate- for (const id of [+ // 3. Fixed / non-directional built-in pen presets do NOT auto-rotate+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toEqual(['g-pen',- 'calligraphy',- 'oil-flat-alla-prima',- 'concept-matte-chalk',- 'silky-portrait-round',- 'soft-glaze-airbrush','real-g-pen','textured-pen',- 'charcoal-pencil',- 'blend-velvet-soft',- ]) {+ 'rough-pen',+ 'dot-pen',+ 'calligraphy',+ ]);+ for (const id of ['g-pen', 'real-g-pen', 'textured-pen', 'dot-pen', 'calligraphy']) {const cfg = getBuiltinBrushConfig(id)!;expect(resolveBrushCursorRotationSpec(cfg, 'brush').enabled, `${id} should not auto-rotate`).toBe(false@@ -146,7 +119,7 @@ describe('Rotating Brush Cursor & "This brush rotates" Setting', () => {});it('respects explicit per-brush rotateCursor ("This brush rotates") overrides and tool gating', () => {- const natRake = getBuiltinBrushConfig('dry-bristle-rake')!;+ const natRake: Partial<BrushSettings> = { renderMode: 'bristle-ribbon' };expect(resolveBrushCursorRotationSpec({ ...natRake, rotateCursor: false }, 'brush')).toEqual({enabled: false,source: 'none',@@ -322,27 +295,45 @@ describe('Rotating Brush Cursor & "This brush rotates" Setting', () => {});it('persists rotateCursor per brush, clears manual override back to auto, and round-trips through .inkb', () => {- saveBrushSettingsImmediately('dry-bristle-rake', { rotateCursor: false });- let eff = getEffectiveBrushSettings('dry-bristle-rake');+ const customRake: CspBrush = {+ id: 'inkb-custom-rake',+ name: 'Custom Rake',+ size: 24,+ minSizeFactor: 0.2,+ flow: 1,+ opacity: 1,+ spacing: 0.1,+ hardness: 1,+ thickness: 1,+ angle: 0,+ smoothing: true,+ stabilization: 0,+ usePressure: true,+ useVelocity: false,+ renderMode: 'bristle-ribbon',+ importedAt: Date.now(),+ };+ saveBrushSettingsImmediately(customRake.id, { rotateCursor: false });+ let eff = getEffectiveBrushSettings(customRake.id, [customRake]);expect(eff.rotateCursor).toBe(false);expect(resolveBrushCursorRotationSpec(eff, 'brush').enabled).toBe(false);// Clearing override with explicit undefined returns to auto-detected rotating state- saveBrushSettingsImmediately('dry-bristle-rake', { rotateCursor: undefined });- eff = getEffectiveBrushSettings('dry-bristle-rake');+ saveBrushSettingsImmediately(customRake.id, { rotateCursor: undefined });+ eff = getEffectiveBrushSettings(customRake.id, [customRake]);expect(eff.rotateCursor).toBeUndefined();expect(resolveBrushCursorRotationSpec(eff, 'brush').enabled).toBe(true);// Enabling on a fixed brush persists and survives .inkb export/import round-trip- saveBrushSettingsImmediately('oil-flat-alla-prima', { rotateCursor: true });- const exported: CspBrush = buildExportableBrush('oil-flat-alla-prima', [], {- preset: 'oil-flat-alla-prima',+ saveBrushSettingsImmediately('g-pen', { rotateCursor: true });+ const exported: CspBrush = buildExportableBrush('g-pen', [], {+ preset: 'g-pen',rotateCursor: true,} as Partial<BrushSettings>);expect(exported.rotateCursor).toBe(true);const bytes = serializeInkbBrush(exported);- const parsed = parseInkbFile(toArrayBuffer(bytes), 'Oil Flat.inkb');+ const parsed = parseInkbFile(toArrayBuffer(bytes), 'G-Pen.inkb');expect(parsed.rotateCursor).toBe(true);});});diff --git a/src/utils/__tests__/decorationToolGroup.test.tsx b/src/utils/__tests__/decorationToolGroup.test.tsxindex 1322797..6df87a0 100644--- a/src/utils/__tests__/decorationToolGroup.test.tsx+++ b/src/utils/__tests__/decorationToolGroup.test.tsx@@ -33,6 +33,33 @@ import {} from '../../stores';import { SubToolList } from '../../components/SubToolList';import { ToolStrip } from '../../components/ToolStrip';+import type { CspBrush, DecorationCategory } from '../../types/editor';++function makeCustomDecoBrush(+ id: string,+ name: string,+ category: DecorationCategory+): CspBrush {+ return {+ id,+ name,+ category,+ badge: 'Decoration',+ size: 48,+ minSizeFactor: 0.2,+ flow: 1,+ opacity: 1,+ spacing: 0.3,+ hardness: 1,+ thickness: 1,+ angle: 0,+ smoothing: true,+ stabilization: 4,+ usePressure: false,+ useVelocity: false,+ importedAt: Date.now(),+ };+}// Minimal DOM shim matching subToolGroupsAndShortcuts.test.tsxclass MiniNode {@@ -334,142 +361,115 @@ describe('Decoration tool group (CSP-style)', () => {container = null;});- it('includes all 26 decoration brushes across Background, Clothing, and Effect with valid PNG assets', () => {+ it('keeps only the 6 core pen built-in brushes and zero built-in decoration brushes', () => {+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toEqual([+ 'g-pen',+ 'real-g-pen',+ 'textured-pen',+ 'rough-pen',+ 'dot-pen',+ 'calligraphy',+ ]);expect(DECORATION_BRUSH_SECTIONS.map((s) => s.label)).toEqual(['Background','Clothing','Effect',]);- expect(DECORATION_BRUSHES).toHaveLength(26);-- const byCat = {- 'deco-background': DECORATION_BRUSHES.filter((b) => b.category === 'deco-background'),- 'deco-clothing': DECORATION_BRUSHES.filter((b) => b.category === 'deco-clothing'),- 'deco-effect': DECORATION_BRUSHES.filter((b) => b.category === 'deco-effect'),- };- expect(byCat['deco-background']).toHaveLength(4);- expect(byCat['deco-clothing']).toHaveLength(18);- expect(byCat['deco-effect']).toHaveLength(4);-- // Clothing brushes are all CSP ribbons- for (const b of byCat['deco-clothing']) {- expect(b.settings.isRibbon).toBe(true);- }-- // Verify multi-tip counts and every PNG asset exists on disk- // @ts-expect-error process is available in vitest runtime without @types/node- const publicDir = path.resolve(process.cwd(), 'public');- for (const b of DECORATION_BRUSHES) {- expect(isDecorationPresetId(b.id)).toBe(true);- expect(b.staticTips && b.staticTips.length > 0).toBe(true);- for (const tip of b.staticTips!) {- const diskPath = path.join(publicDir, tip.assetPath);- expect(fs.existsSync(diskPath), `Missing tip asset: ${diskPath}`).toBe(true);- const bytes = fs.readFileSync(diskPath);- // PNG magic header- expect(bytes[0]).toBe(0x89);- expect(bytes[1]).toBe(0x50);- expect(bytes[2]).toBe(0x4e);- expect(bytes[3]).toBe(0x47);- }-- const cfg = getBuiltinBrushConfig(b.id);- expect(cfg).not.toBeNull();- expect(cfg!.customTipDataUrl).toBeTruthy();- if (b.staticTips!.length > 1) {- expect(cfg!.subTips?.length).toBe(b.staticTips!.length);- }- }-- expect(getBuiltinBrushConfig('deco-building')?.subTips?.length).toBe(13);- expect(getBuiltinBrushConfig('deco-building')?.isDualToneTip).toBe(true);- expect(getBuiltinBrushConfig('deco-roses')?.subTips?.length).toBe(8);- expect(getBuiltinBrushConfig('deco-bloodstain')?.subTips?.length).toBe(7);- expect(getBuiltinBrushConfig('deco-cloud')?.spray?.enabled).toBe(true);-- // Brush tool list remains cleanly separated from Decoration brushes+ expect(DECORATION_BRUSHES).toHaveLength(0);+ expect(DEFAULT_DECORATION_PRESET_ID).toBe('');expect(BUILTIN_BRUSHES.some((b) => isDecorationPresetId(b.id))).toBe(false);expect(ALL_BUILTIN_BRUSHES.length).toBe(BUILTIN_BRUSHES.length + DECORATION_BRUSHES.length);+ for (const b of BUILTIN_BRUSHES) {+ expect(getBuiltinBrushConfig(b.id)).not.toBeNull();+ }});it('remembers Brush and Decoration active presets independently when switching tools', () => {- activateSubToolPreset('real-g-pen');+ const customRoses = makeCustomDecoBrush('inkb-deco-roses', 'Custom Roses', 'deco-effect');+ activateSubToolPreset('real-g-pen', [customRoses]);expect(useToolStore.getState().tool).toBe('brush');expect(useToolStore.getState().activePresetId).toBe('real-g-pen');- // Switch to Decoration tool -> loads default Decoration brush- toolStoreActions.selectTool('decoration');+ // Pick Custom Roses inside Decoration+ activateSubToolPreset(customRoses.id, [customRoses]);expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe(DEFAULT_DECORATION_PRESET_ID);-- // Pick Roses inside Decoration- activateSubToolPreset('deco-roses');- expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe('deco-roses');+ expect(useToolStore.getState().activePresetId).toBe(customRoses.id);// Switch back to Brush -> restores Real G-PentoolStoreActions.selectTool('brush');expect(useToolStore.getState().tool).toBe('brush');expect(useToolStore.getState().activePresetId).toBe('real-g-pen');- // Switch back to Decoration -> restores Roses+ // Switch back to Decoration -> restores Custom RosestoolStoreActions.selectTool('decoration');expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe('deco-roses');+ expect(useToolStore.getState().activePresetId).toBe(customRoses.id);// Switch to Eraser then pick a color -> returns to Decoration (last paint tool)toolStoreActions.selectTool('eraser');expect(useToolStore.getState().tool).toBe('eraser');toolStoreActions.setPrimaryColor('#ff3366');expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe('deco-roses');+ expect(useToolStore.getState().activePresetId).toBe(customRoses.id);});- it('cycles Decoration subtools and groups cleanly with stepSubTool / stepSubToolGroup', () => {+ it('cycles custom Decoration subtools and groups cleanly with stepSubTool / stepSubToolGroup', () => {+ const customBrushes = [+ makeCustomDecoBrush('inkb-deco-bg-1', 'Custom Skyline', 'deco-background'),+ makeCustomDecoBrush('inkb-deco-bg-2', 'Custom Clouds', 'deco-background'),+ makeCustomDecoBrush('inkb-deco-cloth-1', 'Custom Lace', 'deco-clothing'),+ makeCustomDecoBrush('inkb-deco-fx-1', 'Custom Petals', 'deco-effect'),+ ];+ for (const b of customBrushes) {+ subToolGroupStoreActions.moveBrushToGroup(b.id, b.category as DecorationCategory);+ }+toolStoreActions.selectTool('decoration');- activateSubToolPreset('deco-building');+ activateSubToolPreset('inkb-deco-bg-1', customBrushes);- const next = stepSubTool(1);- expect(next?.presetId).toBe('deco-cloud');+ const next = stepSubTool(1, customBrushes);+ expect(next?.presetId).toBe('inkb-deco-bg-2');expect(useToolStore.getState().tool).toBe('decoration');- const grp1 = stepSubToolGroup(1);+ const grp1 = stepSubToolGroup(1, customBrushes);expect(grp1?.groupId).toBe('deco-background');- const grp2 = stepSubToolGroup(1);+ const grp2 = stepSubToolGroup(1, customBrushes);expect(grp2?.groupId).toBe('deco-clothing');expect(useSubToolGroupStore.getState().activeDecorationTab).toBe('deco-clothing');- expect(useToolStore.getState().activePresetId).toBe('deco-star-lace');+ expect(useToolStore.getState().activePresetId).toBe('inkb-deco-cloth-1');- const grp3 = activateSubToolGroup('deco-effect');+ const grp3 = activateSubToolGroup('deco-effect', customBrushes);expect(grp3?.groupName).toBe('Effect');expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe('deco-bloodstain');+ expect(useToolStore.getState().activePresetId).toBe('inkb-deco-fx-1');});- it('registers Decoration tool and all 26 decoration brushes in ShortcutManager and Quick Brushes', async () => {+ it('registers Decoration tool and custom decoration brushes in ShortcutManager and Quick Brushes', async () => {+ const customCherry = makeCustomDecoBrush('inkb-deco-cherry', 'Custom Cherry', 'deco-effect');expect(DEFAULT_COMMANDS.some((c) => c.id === 'tool.decoration' && c.toolId === 'decoration')).toBe(true);- const dynamic = buildSubToolShortcutCommands([], []);- for (const b of DECORATION_BRUSHES) {- expect(dynamic.some((c) => c.subToolPresetId === b.id)).toBe(true);- }+ const dynamic = buildSubToolShortcutCommands([customCherry], []);+ expect(dynamic.some((c) => c.subToolPresetId === customCherry.id)).toBe(true);- const resolved = resolveQuickBrush('deco-cherry', []);+ const resolved = resolveQuickBrush(customCherry.id, [customCherry]);expect(resolved).not.toBeNull();- expect(resolved!.name).toBe('Cherry');+ expect(resolved!.name).toBe('Custom Cherry');expect(resolved!.category).toBe('deco-effect');- await activateQuickBrush(resolved!, []);+ await activateQuickBrush(resolved!, [customCherry]);expect(useToolStore.getState().tool).toBe('decoration');- expect(useToolStore.getState().activePresetId).toBe('deco-cherry');+ expect(useToolStore.getState().activePresetId).toBe(customCherry.id);});- it('renders Decoration button in ToolStrip and Decoration-scoped tabs/brushes in SubToolList', () => {+ it('renders Decoration button in ToolStrip and Decoration-scoped tabs/empty state/custom brushes in SubToolList', () => {const body = (document as unknown as { body: MiniEl }).body;container = document.createElement('div') as unknown as MiniEl;body.appendChild(container);root = createRoot(container as unknown as Element);+ const customLace = makeCustomDecoBrush('inkb-deco-lace', 'Custom Lace', 'deco-clothing');+ const customRoses = makeCustomDecoBrush('inkb-deco-roses', 'Custom Roses', 'deco-effect');+act(() => {root!.render(<div>@@ -495,20 +495,31 @@ describe('Decoration tool group (CSP-style)', () => {expect(container.querySelector('[data-testid="subtool-group-tab-deco-background"]')).not.toBeNull();expect(container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]')).not.toBeNull();expect(container.querySelector('[data-testid="subtool-group-tab-deco-effect"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="subtool-decoration-empty-state"]')).not.toBeNull();- // All 26 decoration brush rows visible in All view- for (const b of DECORATION_BRUSHES) {- expect(container.querySelector(`[data-testid="subtool-row-${b.id}"]`)).not.toBeNull();- }+ // Render with custom decoration brushes assigned to categories+ act(() => {+ subToolGroupStoreActions.moveBrushToGroup(customLace.id, 'deco-clothing');+ subToolGroupStoreActions.moveBrushToGroup(customRoses.id, 'deco-effect');+ root!.render(+ <div>+ <ToolStrip />+ <SubToolList customBrushes={[customLace, customRoses]} setCustomBrushes={() => {}} />+ </div>+ );+ });++ expect(container.querySelector('[data-testid="subtool-decoration-empty-state"]')).toBeNull();+ expect(container.querySelector(`[data-testid="subtool-row-${customLace.id}"]`)).not.toBeNull();+ expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).not.toBeNull();- // Filter to Clothing tab -> only the 18 clothing brushes visible+ // Filter to Clothing tab -> only the clothing custom brush is visibleconst clothingTab = container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]');act(() => {invokeReactClick(clothingTab);});- expect(container.querySelector('[data-testid="subtool-row-deco-star-lace"]')).not.toBeNull();- expect(container.querySelector('[data-testid="subtool-row-deco-building"]')).toBeNull();- expect(container.querySelector('[data-testid="subtool-row-deco-roses"]')).toBeNull();+ expect(container.querySelector(`[data-testid="subtool-row-${customLace.id}"]`)).not.toBeNull();+ expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).toBeNull();// "+ Group" button is available in Decoration mode tooconst createGroupBtn = container.querySelector('[data-testid="subtool-create-group-btn"]');@@ -530,9 +541,9 @@ describe('Decoration tool group (CSP-style)', () => {// Move a Decoration brush into the new Decoration custom group & verify persistenceact(() => {- subToolGroupStoreActions.moveBrushToGroup('deco-roses', createdGroups[0].id);+ subToolGroupStoreActions.moveBrushToGroup(customRoses.id, createdGroups[0].id);});- expect(container.querySelector('[data-testid="subtool-row-deco-roses"]')).not.toBeNull();+ expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).not.toBeNull();// Switching back to Brush mode hides Decoration-scoped custom groupsconst brushBtn = container.querySelector('[data-testid="toolstrip-brush-btn"]');diff --git a/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx b/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsxindex e34ec8f..7db90ae 100644--- a/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx+++ b/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx@@ -62,6 +62,7 @@ const mockBridge = vi.hoisted(() => ({viewportInvalidatedListeners: new Set<() => void>(),strokeCommittedListeners: new Set<(ev: any) => void>(),historyListeners: new Set<(ev: any) => void>(),+ cameraListeners: new Set<(ev: any) => void>(),}));vi.mock('../nativeEngineBridge', async (importOriginal) => {@@ -90,7 +91,10 @@ vi.mock('../nativeEngineBridge', async (importOriginal) => {nativeUndo: (...args: any[]) => (mockBridge.nativeUndo as any)(...args),nativeRedo: (...args: any[]) => (mockBridge.nativeRedo as any)(...args),subscribeNativeCanvasActive: () => () => {},- subscribeNativeCamera: () => () => {},+ subscribeNativeCamera: (cb: (ev: any) => void) => {+ mockBridge.cameraListeners.add(cb);+ return () => mockBridge.cameraListeners.delete(cb);+ },subscribeNativeDiagnostics: () => () => {},subscribeNativePointerStat: () => () => {},subscribeNativeViewportInvalidated: (cb: () => void) => {@@ -324,6 +328,7 @@ describe('DirectComposition physical-pixel alignment, occlusion & StrokeCommittemockBridge.viewportInvalidatedListeners.clear();mockBridge.strokeCommittedListeners.clear();mockBridge.historyListeners.clear();+ mockBridge.cameraListeners.clear();MiniMutationObserver.instances = [];pendingRafs = new Map();nextRafId = 1;@@ -667,4 +672,114 @@ describe('DirectComposition physical-pixel alignment, occlusion & StrokeCommitteexpect.objectContaining({ widthPx: 0, heightPx: 0, visible: false }));});++ it('never echoes native Space+drag camera events back to Rust via setNativeCamera after rAF broadcast', () => {+ const viewportEl = miniDoc.createElement('div');+ viewportEl.rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };++ const cameraSubs = new Set<(cam: any, meta?: any) => void>();+ let liveCam = { pan: { x: 500, y: 400 }, zoom: 1, rotation: 0, flipX: false, flipY: false };+ let pendingSource: any = 'user';+ let rafPending = false;+ const mockNav: any = {+ getCameraState: () => liveCam,+ subscribeCamera: (cb: any) => {+ cameraSubs.add(cb);+ return () => cameraSubs.delete(cb);+ },+ setCameraLive: (next: any, commit = false, source = 'programmatic') => {+ liveCam = { ...liveCam, ...next };+ if (commit) {+ cameraSubs.forEach((cb) => cb(liveCam, { source }));+ } else {+ pendingSource = source;+ if (!rafPending) {+ rafPending = true;+ requestAnimationFrame(() => {+ rafPending = false;+ const emitSrc = pendingSource;+ cameraSubs.forEach((cb) => cb(liveCam, { source: emitSrc }));+ });+ }+ }+ },+ };++ const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };+ const layer = useDocumentStore.getState().documents[0].layers[0];++ function CameraSyncHarness() {+ const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);+ useNativeEngineViewport({+ viewportRef: vpRef,+ navigation: mockNav,+ dimensions: { width: 1024, height: 1024, dpi: 300 },+ showCheckerboard: true,+ hasOpenDocument: true,+ tool: 'brush',+ brushSettings,+ primaryColor: '#000000',+ activeLayer: layer,+ isMaskMode: false,+ isSquare: false,+ thicknessRatio: 1,+ thicknessVertical: false,+ tipAngleDeg: 0,+ isResizingBrush: false,+ isSpaceDown: true,+ isPanning: false,+ isRotating: false,+ isZoomDragging: false,+ isRotateModifier: false,+ pan: { x: 500, y: 400 },+ zoom: 1,+ rotation: 0,+ flipX: false,+ flipY: false,+ });+ return null;+ }++ root = createRoot(hostEl as any);+ act(() => {+ root!.render(<CameraSyncHarness />);+ });++ // Clear initial mount camera push+ mockBridge.setNativeCamera.mockClear();++ // Simulate Rust emitting live Space+drag camera updates (commit: false) followed by rAF flush+ act(() => {+ for (const cb of mockBridge.cameraListeners) {+ cb({ panX: 520, panY: 410, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: false });+ }+ flushRaf();+ for (const cb of mockBridge.cameraListeners) {+ cb({ panX: 560, panY: 430, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: false });+ }+ flushRaf();+ for (const cb of mockBridge.cameraListeners) {+ cb({ panX: 590, panY: 445, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: true });+ }+ });++ // Zero stale camera echoes sent back to Rust during native drag!+ expect(mockBridge.setNativeCamera).not.toHaveBeenCalled();++ // User-initiated React camera change (e.g. Navigator drag) MUST still push to Rust+ act(() => {+ cameraSubs.forEach((cb) =>+ cb({ pan: { x: 700, y: 500 }, zoom: 1.5, rotation: 0, flipX: false, flipY: false }, { source: 'user' })+ );+ });+ expect(mockBridge.setNativeCamera).toHaveBeenCalledTimes(1);+ expect(mockBridge.setNativeCamera).toHaveBeenCalledWith({+ panX: 700,+ panY: 500,+ zoom: 1.5,+ rotation: 0,+ flipX: false,+ flipY: false,+ });+ });});diff --git a/src/utils/__tests__/phase5NativeRouting.test.ts b/src/utils/__tests__/phase5NativeRouting.test.tsindex c2a4f7a..7f1e55e 100644--- a/src/utils/__tests__/phase5NativeRouting.test.ts+++ b/src/utils/__tests__/phase5NativeRouting.test.ts@@ -4,14 +4,26 @@ import {buildNativeBrushConfigPayload,canNativeEngineHandleBrush,} from '../nativeEngineBridge';-import type { BrushSettings } from '../../types/editor';+import {+ DEFAULT_BRISTLE_SETTINGS,+ DEFAULT_IMPASTO_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+ type BrushSettings,+} from '../../types/editor';describe('Phase 5: 100% Native Rust + wgpu Brush Routing & Serialization', () => {const rasterLayer = { type: 'raster' as const, locked: false, visible: true };const vectorLayer = { type: 'vector' as const, locked: false, visible: true };it('routes 100% of built-in brush presets natively on raster layers and mask mode', () => {- expect(BUILTIN_BRUSHES.length).toBeGreaterThan(20);+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toEqual([+ 'g-pen',+ 'real-g-pen',+ 'textured-pen',+ 'rough-pen',+ 'dot-pen',+ 'calligraphy',+ ]);for (const preset of BUILTIN_BRUSHES) {const cfg = getBuiltinBrushConfig(preset.id);const bs: BrushSettings = {@@ -36,9 +48,7 @@ describe('Phase 5: 100% Native Rust + wgpu Brush Routing & Serialization', () =>});it('serializes all Phase 5 Natural Paint, Bristle, Impasto, Ribbon, and Color Mixing fields for ink-engine', async () => {- const impastoPreset = BUILTIN_BRUSHES.find((b) => getBuiltinBrushConfig(b.id)?.impasto?.enabled);- expect(impastoPreset).toBeDefined();- const cfg = getBuiltinBrushConfig(impastoPreset!.id);+ const cfg = getBuiltinBrushConfig('g-pen');const bs: BrushSettings = {size: 64,@@ -51,8 +61,12 @@ describe('Phase 5: 100% Native Rust + wgpu Brush Routing & Serialization', () =>usePressure: true,smoothing: true,stabilization: 4,- preset: impastoPreset!.id,+ preset: 'g-pen',...cfg,+ renderMode: 'bristle-ribbon',+ bristle: { ...DEFAULT_BRISTLE_SETTINGS },+ naturalPaint: { ...DEFAULT_NATURAL_PAINT_SETTINGS },+ impasto: { ...DEFAULT_IMPASTO_SETTINGS, enabled: true },colorMixing: true,perceptualMixing: true,mixGroundColor: true,@@ -64,7 +78,7 @@ describe('Phase 5: 100% Native Rust + wgpu Brush Routing & Serialization', () =>};const payload = await buildNativeBrushConfigPayload('brush', bs, '#1d4ed8', '#facc15', false);- expect(payload.presetKey).toBe(impastoPreset!.id);+ expect(payload.presetKey).toBe('g-pen');expect(payload.colorMixing).toBe(true);expect(payload.perceptualMixing).toBe(true);expect(payload.mixGroundColor).toBe(true);diff --git a/src/utils/__tests__/quickBrushPanel.test.tsx b/src/utils/__tests__/quickBrushPanel.test.tsxindex 35b057a..aa428ba 100644--- a/src/utils/__tests__/quickBrushPanel.test.tsx+++ b/src/utils/__tests__/quickBrushPanel.test.tsx@@ -518,17 +518,17 @@ describe('Quick-Access Brush Panel State, Persistence, Shortcuts & UI', () => {// Add brushes and verify clicking a brush tile selects that brush in useToolStoreact(() => {workspaceStoreActions.addQuickBrush('g-pen');- workspaceStoreActions.addQuickBrush('soft-glaze-airbrush');+ workspaceStoreActions.addQuickBrush('real-g-pen');});- const airbrushTile = dom.container.findByAttr(+ const realGPenTile = dom.container.findByAttr('data-testid',- 'quick-brush-tile-soft-glaze-airbrush'+ 'quick-brush-tile-real-g-pen');act(() => {- invokeReactProp(airbrushTile, 'onClick');+ invokeReactProp(realGPenTile, 'onClick');});expect(useToolStore.getState().tool).toBe('brush');- expect(useToolStore.getState().activePresetId).toBe('soft-glaze-airbrush');+ expect(useToolStore.getState().activePresetId).toBe('real-g-pen');// Pinning and clicking Eraser activates eraser toolact(() => {diff --git a/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsx b/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsxindex 21328a6..0165635 100644--- a/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsx+++ b/src/utils/__tests__/subToolGroupsAndShortcuts.test.tsx@@ -604,7 +604,8 @@ describe('Custom SubTool Groups (CSP-style) & Instrument Navigation', () => {it('moves brushes freely between built-in groups, reorders within them, and persists across reload', () => {const importedBrush = createSampleCustomBrush('inkb-imported-1', 'Imported Pen');- // Move built-in 'g-pen' from Pen -> Sketch+ // Move built-in 'real-g-pen' and 'g-pen' from Pen -> Sketch+ expect(subToolGroupStoreActions.moveBrushToGroup('real-g-pen', 'sketch')).toBe(true);expect(subToolGroupStoreActions.moveBrushToGroup('g-pen', 'sketch')).toBe(true);// Move imported brush from Imported -> Penexpect(subToolGroupStoreActions.moveBrushToGroup(importedBrush.id, 'pen')).toBe(true);@@ -627,12 +628,13 @@ describe('Custom SubTool Groups (CSP-style) & Instrument Navigation', () => {expect(penIds).not.toContain('g-pen');expect(penIds).toContain(importedBrush.id);expect(sketchIds).toContain('g-pen');+ expect(sketchIds).toContain('real-g-pen');- // Reorder 'g-pen' right before 'mechanical-pencil' inside Sketch+ // Reorder 'g-pen' right before 'real-g-pen' inside SketchsubToolGroupStoreActions.reorderBrushInGroup('sketch','g-pen',- 'mechanical-pencil',+ 'real-g-pen','before',sketchIds);@@ -645,7 +647,7 @@ describe('Custom SubTool Groups (CSP-style) & Instrument Navigation', () => {reloaded.builtinGroupOrders);expect(sketchAfter[0]).toBe('g-pen');- expect(sketchAfter[1]).toBe('mechanical-pencil');+ expect(sketchAfter[1]).toBe('real-g-pen');// Resetting 'g-pen' returns it to its factory Pen groupsubToolGroupStoreActions.removeBrushFromAllGroups('g-pen');diff --git a/src/utils/decorationBrushes.ts b/src/utils/decorationBrushes.tsindex 3f2584f..c751bab 100644--- a/src/utils/decorationBrushes.ts+++ b/src/utils/decorationBrushes.ts@@ -11,7 +11,7 @@ export const DECORATION_CATEGORY_SET = new Set<string>(DECORATION_BRUSH_SECTIONS.map((s) => s.id));-export const DEFAULT_DECORATION_PRESET_ID: BrushPresetId = 'deco-building';+export const DEFAULT_DECORATION_PRESET_ID: BrushPresetId = '';export function isDecorationCategory(category: string | undefined): category is DecorationCategory {return Boolean(category && DECORATION_CATEGORY_SET.has(category));@@ -19,7 +19,12 @@ export function isDecorationCategory(category: string | undefined): category isexport function resolveStaticBrushAssetUrl(assetPath: string): string {if (!assetPath) return '';- if (assetPath.startsWith('data:') || assetPath.startsWith('http://') || assetPath.startsWith('https://') || assetPath.startsWith('blob:')) {+ if (+ assetPath.startsWith('data:') ||+ assetPath.startsWith('http://') ||+ assetPath.startsWith('https://') ||+ assetPath.startsWith('blob:')+ ) {return assetPath;}const base =@@ -33,2142 +38,7 @@ export function resolveStaticBrushAssetUrl(assetPath: string): string {return `${cleanBase}${cleanPath}`;}-export const DECORATION_BRUSHES: BuiltinBrushDefinition[] = [- {- "id": "deco-building",- "category": "deco-background",- "name": "Building",- "badge": "Background",- "badgeBg": "bg-emerald-500/15",- "badgeText": "text-emerald-300",- "badgeBorder": "border-emerald-500/30",- "desc": "Multi-tip manga cityscape buildings with primary outline and secondary fill",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/background/building_0.png",- "width": 156,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_1.png",- "width": 111,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_2.png",- "width": 100,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_3.png",- "width": 167,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_4.png",- "width": 122,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_5.png",- "width": 133,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_6.png",- "width": 144,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_7.png",- "width": 133,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_8.png",- "width": 144,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_9.png",- "width": 178,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_10.png",- "width": 189,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_11.png",- "width": 189,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/background/building_12.png",- "width": 167,- "height": 300,- "isDualToneTip": true- }- ],- "settings": {- "size": 500,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.35,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 1,- "stabilization": 5,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 1,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "intervalSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 1,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.8- },- "flipH": "random",- "subTipOrder": "sequential",- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-cloud",- "category": "deco-background",- "name": "Cloud",- "badge": "Background",- "badgeBg": "bg-emerald-500/15",- "badgeText": "text-emerald-300",- "badgeBorder": "border-emerald-500/30",- "desc": "Soft scattered cloud clusters for sky backgrounds",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/background/cloud_0.png",- "width": 284,- "height": 281- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": true,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.3,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 1,- "stabilization": 6,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": true,- "useVelocity": false,- "useTilt": false,- "pressureCurve": [- [- 0,- 0- ],- [- 0.3169,- 0.6948- ],- [- 1,- 1- ]- ],- "sizeSensor": {- "usePressure": true,- "pressureMin": 0,- "pressureCurve": [- [- 0,- 0- ],- [- 0.3169,- 0.6948- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "densitySensor": {- "usePressure": true,- "pressureMin": 0,- "pressureCurve": [- [- 0,- 0- ],- [- 0.7545,- 0.2818- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0- },- "intervalSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0- },- "subTipOrder": "sequential",- "spray": {- "enabled": true,- "size": 300,- "density": 2,- "bias": 1,- "sizeSensor": {- "usePressure": true,- "pressureMin": 0.03,- "pressureCurve": [- [- 0,- 0- ],- [- 0.3169,- 0.6948- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "densitySensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0- }- },- "useGpu": true- }- },- {- "id": "deco-grass",- "category": "deco-background",- "name": "Grass",- "badge": "Background",- "badgeBg": "bg-emerald-500/15",- "badgeText": "text-emerald-300",- "badgeBorder": "border-emerald-500/30",- "desc": "Randomized grass tuft scatter for ground and foliage",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/background/grass_0.png",- "width": 300,- "height": 258- },- {- "assetPath": "brushes/decoration/background/grass_1.png",- "width": 300,- "height": 254- }- ],- "settings": {- "size": 250,- "brushSizeUnit": 0,- "minSizeFactor": 0.85,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.5,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 1,- "stabilization": 2,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0.2,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.85- },- "intervalSensor": {- "usePressure": true,- "pressureMin": 0.6,- "pressureCurve": [- [- 0,- 1- ],- [- 0.7455,- 0.0091- ],- [- 0.7545,- 0- ],- [- 1,- 0- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.2- },- "flipH": "alternate",- "subTipOrder": "random",- "spray": {- "enabled": true,- "size": 150,- "density": 2,- "bias": 0.5,- "sizeSensor": {- "usePressure": true,- "pressureMin": 0.5,- "pressureCurve": [- [- 0,- 0.1- ],- [- 0.7364,- 1- ],- [- 0.7455,- 1- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.8- },- "densitySensor": {- "usePressure": true,- "pressureMin": 0.1,- "pressureCurve": [- [- 0,- 0.1273- ],- [- 0.6,- 1- ],- [- 0.6091,- 1- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.45- }- },- "useGpu": true- }- },- {- "id": "deco-trees",- "category": "deco-background",- "name": "Trees",- "badge": "Background",- "badgeBg": "bg-emerald-500/15",- "badgeText": "text-emerald-300",- "badgeBorder": "border-emerald-500/30",- "desc": "Multi-tip tree silhouettes for instant forest backgrounds",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/background/trees_0.png",- "width": 177,- "height": 300- },- {- "assetPath": "brushes/decoration/background/trees_1.png",- "width": 236,- "height": 300- },- {- "assetPath": "brushes/decoration/background/trees_2.png",- "width": 115,- "height": 300- },- {- "assetPath": "brushes/decoration/background/trees_3.png",- "width": 236,- "height": 300- },- {- "assetPath": "brushes/decoration/background/trees_4.png",- "width": 216,- "height": 300- }- ],- "settings": {- "size": 400,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.7,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "intervalSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.5- },- "flipH": "alternate",- "subTipOrder": "random",- "useGpu": true- }- },- {- "id": "deco-star-lace",- "category": "deco-clothing",- "name": "Star Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Continuous ribbon star-pattern lace trim",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/star-lace_0.png",- "width": 300,- "height": 199- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": false,- "antiAlias": 1,- "stabilization": 6,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 84.5,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-sakura-lace",- "category": "deco-clothing",- "name": "Sakura Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Continuous ribbon cherry-petal lace trim",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/sakura-lace_0.png",- "width": 300,- "height": 144- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": false,- "antiAlias": 1,- "stabilization": 6,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 84.5,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-cross-lace",- "category": "deco-clothing",- "name": "Cross Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Continuous ribbon gothic cross lace trim",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/cross-lace_0.png",- "width": 300,- "height": 107- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": false,- "antiAlias": 1,- "stabilization": 6,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 84.5,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-rope-ribbon",- "category": "deco-clothing",- "name": "Rope Ribbon",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone twisted rope ribbon trim",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/rope-ribbon_0.png",- "width": 90,- "height": 101,- "isDualToneTip": true- }- ],- "settings": {- "size": 100,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-sheer-scallop",- "category": "deco-clothing",- "name": "Sheer Scallop",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone delicate sheer scalloped lace ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/sheer-scallop_0.png",- "width": 176,- "height": 138,- "isDualToneTip": true- }- ],- "settings": {- "size": 475.8,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-scallop-trim-lace",- "category": "deco-clothing",- "name": "Scallop Trim Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone scalloped trim lace ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/scallop-trim-lace_0.png",- "width": 93,- "height": 111,- "isDualToneTip": true- }- ],- "settings": {- "size": 285.2,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-scallop-lace",- "category": "deco-clothing",- "name": "Scallop Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone classic scallop lace ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/scallop-lace_0.png",- "width": 115,- "height": 150,- "isDualToneTip": true- }- ],- "settings": {- "size": 254.1,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-ornate-scallop",- "category": "deco-clothing",- "name": "Ornate Scallop",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone ornate scalloped lace ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/ornate-scallop_0.png",- "width": 215,- "height": 252,- "isDualToneTip": true- }- ],- "settings": {- "size": 250,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-simple-lace",- "category": "deco-clothing",- "name": "Simple Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone clean simple lace trim ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/simple-lace_0.png",- "width": 109,- "height": 151,- "isDualToneTip": true- }- ],- "settings": {- "size": 299.7,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-decorative-rope",- "category": "deco-clothing",- "name": "Decorative Rope",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone braided decorative cord ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/decorative-rope_0.png",- "width": 70,- "height": 115,- "isDualToneTip": true- }- ],- "settings": {- "size": 314.9,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.019,- "hardness": 1,- "thickness": 1,- "thicknessVertical": false,- "antiAlias": 2,- "stabilization": 50,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": true,- "useVelocity": false,- "useTilt": false,- "pressureCurve": [- [- 0,- 0- ],- [- 0.2636,- 0.5091- ],- [- 1,- 1- ]- ],- "sizeSensor": {- "usePressure": true,- "pressureMin": 0,- "pressureCurve": [- [- 0,- 0- ],- [- 0.2636,- 0.5091- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-rose-trim",- "category": "deco-clothing",- "name": "Rose Trim",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Dual-tone rose floral lace trim ribbon",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/rose-trim_0.png",- "width": 100,- "height": 151,- "isDualToneTip": true- }- ],- "settings": {- "size": 396.8,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 10,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "isRibbon": true,- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-1",- "category": "deco-clothing",- "name": "Standard Lace 1",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Detailed eyelet ribbon lace trim",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-1_0.png",- "width": 300,- "height": 246- }- ],- "settings": {- "size": 157.4,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-2",- "category": "deco-clothing",- "name": "Standard Lace 2",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Wide floral scallop ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-2_0.png",- "width": 277,- "height": 300- }- ],- "settings": {- "size": 325.5,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-3",- "category": "deco-clothing",- "name": "Standard Lace 3",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Fine scalloped border ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-3_0.png",- "width": 300,- "height": 205- }- ],- "settings": {- "size": 113.2,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-4",- "category": "deco-clothing",- "name": "Standard Lace 4",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Ornate embroidery ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-4_0.png",- "width": 300,- "height": 243- }- ],- "settings": {- "size": 219,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-5",- "category": "deco-clothing",- "name": "Standard Lace 5",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Delicate frill border ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-5_0.png",- "width": 300,- "height": 240- }- ],- "settings": {- "size": 140.3,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 270,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-standard-lace-6",- "category": "deco-clothing",- "name": "Standard Lace 6",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Layered crochet ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/standard-lace-6_0.png",- "width": 300,- "height": 243- }- ],- "settings": {- "size": 359.4,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 5,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-classic-lace",- "category": "deco-clothing",- "name": "Classic Lace",- "badge": "Clothing",- "badgeBg": "bg-pink-500/15",- "badgeText": "text-pink-300",- "badgeBorder": "border-pink-500/30",- "desc": "Classic frilled ribbon lace",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/clothing/classic-lace_0.png",- "width": 300,- "height": 295- }- ],- "settings": {- "size": 211.9,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.1,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 1,- "stabilization": 5,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngle": 90,- "subTipOrder": "sequential",- "isRibbon": true,- "useGpu": true- }- },- {- "id": "deco-bloodstain",- "category": "deco-effect",- "name": "Bloodstain",- "badge": "Effect",- "badgeBg": "bg-violet-500/15",- "badgeText": "text-violet-300",- "badgeBorder": "border-violet-500/30",- "desc": "Multi-tip directional splatter and bloodstain spray",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/effect/bloodstain_0.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_1.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_2.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_3.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_4.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_5.png",- "width": 300,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/bloodstain_6.png",- "width": 300,- "height": 300- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.8,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "thicknessSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": true,- "velocityMin": 0.23,- "velocityCurve": [- [- 0,- 1- ],- [- 1,- 0- ]- ],- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.7- },- "antiAlias": 1,- "stabilization": 0,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": true,- "useVelocity": false,- "useTilt": false,- "pressureCurve": [- [- 0,- 0- ],- [- 0.364,- 0.0439- ],- [- 0.5263,- 1- ],- [- 1,- 1- ]- ],- "sizeSensor": {- "usePressure": true,- "pressureMin": 0,- "pressureCurve": [- [- 0,- 0- ],- [- 0.364,- 0.0439- ],- [- 0.5263,- 1- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 1,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.71- },- "intervalSensor": {- "usePressure": true,- "pressureMin": 0.3,- "pressureCurve": [- [- 0,- 1- ],- [- 0.0091,- 1- ],- [- 1,- 0- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": true,- "velocityMin": 0.5,- "velocityCurve": [- [- 0,- 1- ],- [- 1,- 0- ]- ],- "invertVelocity": false,- "useRandom": false,- "randomMin": 0.86- },- "customTipAngle": 90,- "customTipAngleDynamics": "direction",- "flipH": "alternate",- "flipV": "alternate",- "subTipOrder": "random",- "spray": {- "enabled": true,- "size": 400,- "density": 2,- "bias": 1,- "sizeSensor": {- "usePressure": true,- "pressureMin": 0,- "pressureCurve": [- [- 0,- 0- ],- [- 0.2895,- 0.0351- ],- [- 0.5351,- 1- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": true,- "velocityMin": 0.2,- "velocityCurve": [- [- 0,- 1- ],- [- 1,- 0- ]- ],- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.5- },- "densitySensor": {- "usePressure": true,- "pressureMin": 0.18,- "pressureCurve": [- [- 0,- 0- ],- [- 1,- 1- ]- ],- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": true,- "velocityMin": 0.2,- "velocityCurve": [- [- 0,- 1- ],- [- 1,- 0- ]- ],- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- }- },- "useGpu": true- }- },- {- "id": "deco-cherry",- "category": "deco-effect",- "name": "Cherry",- "badge": "Effect",- "badgeBg": "bg-violet-500/15",- "badgeText": "text-violet-300",- "badgeBorder": "border-violet-500/30",- "desc": "Dual-tone fluttering cherry blossom petals",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/effect/cherry_0.png",- "width": 298,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/cherry_1.png",- "width": 298,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/cherry_2.png",- "width": 297,- "height": 300,- "isDualToneTip": true- }- ],- "settings": {- "size": 300,- "brushSizeUnit": 0,- "minSizeFactor": 0.85,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 1.2,- "hardness": 1,- "thickness": 1,- "thicknessVertical": true,- "antiAlias": 1,- "stabilization": 2,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.85- },- "intervalSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.52- },- "customTipAngleDynamics": "direction-random",- "customTipRotationRandomScale": 1,- "flipH": "alternate",- "flipV": "alternate",- "subTipOrder": "random",- "isDualToneTip": true,- "useGpu": true- }- },- {- "id": "deco-feather",- "category": "deco-effect",- "name": "Feather",- "badge": "Effect",- "badgeBg": "bg-violet-500/15",- "badgeText": "text-violet-300",- "badgeBorder": "border-violet-500/30",- "desc": "Multi-tip floating feathers with gentle spray scatter",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/effect/feather_0.png",- "width": 138,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/feather_1.png",- "width": 300,- "height": 268- },- {- "assetPath": "brushes/decoration/effect/feather_2.png",- "width": 188,- "height": 300- },- {- "assetPath": "brushes/decoration/effect/feather_3.png",- "width": 188,- "height": 300- }- ],- "settings": {- "size": 200,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 0.8,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 1.5,- "hardness": 1,- "thickness": 1.5,- "thicknessVertical": true,- "antiAlias": 2,- "stabilization": 2,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": false,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 1,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "subTipOrder": "sequential",- "spray": {- "enabled": true,- "size": 120,- "density": 2,- "bias": 0,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 1,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0.4- },- "densitySensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": true,- "randomMin": 0- }- },- "useGpu": true- }- },- {- "id": "deco-roses",- "category": "deco-effect",- "name": "Roses",- "badge": "Effect",- "badgeBg": "bg-violet-500/15",- "badgeText": "text-violet-300",- "badgeBorder": "border-violet-500/30",- "desc": "Multi-tip dual-tone blooming roses scatter",- "icon": "sparkles",- "staticTips": [- {- "assetPath": "brushes/decoration/effect/roses_0.png",- "width": 300,- "height": 294,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_1.png",- "width": 284,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_2.png",- "width": 300,- "height": 297,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_3.png",- "width": 214,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_4.png",- "width": 272,- "height": 300,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_5.png",- "width": 300,- "height": 294,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_6.png",- "width": 300,- "height": 228,- "isDualToneTip": true- },- {- "assetPath": "brushes/decoration/effect/roses_7.png",- "width": 297,- "height": 300,- "isDualToneTip": true- }- ],- "settings": {- "size": 755,- "brushSizeUnit": 0,- "minSizeFactor": 0,- "opacity": 1,- "flow": 1,- "adjustDensityByGap": false,- "blendTipsMode": "darken",- "brushCombineMode": "normal",- "spacing": 0.64,- "hardness": 1,- "thickness": 1,- "thicknessVertical": false,- "antiAlias": 3,- "stabilization": 0,- "postCorrection": 0,- "sharpCorners": false,- "smoothing": true,- "usePressure": false,- "useVelocity": false,- "useTilt": true,- "sizeSensor": {- "usePressure": false,- "pressureMin": 0,- "useTilt": false,- "tiltMin": 0,- "invertTilt": false,- "useVelocity": false,- "velocityMin": 0,- "invertVelocity": false,- "useRandom": false,- "randomMin": 0- },- "customTipAngleDynamics": "tilt",- "subTipOrder": "random",- "isDualToneTip": true,- "useGpu": true- }- }-];+export const DECORATION_BRUSHES: BuiltinBrushDefinition[] = [];const DECORATION_PRESET_ID_SET = new Set<string>(DECORATION_BRUSHES.map((b) => b.id));diff --git a/src/utils/nativeEngineBridge.ts b/src/utils/nativeEngineBridge.tsindex 0255af1..8f67787 100644--- a/src/utils/nativeEngineBridge.ts+++ b/src/utils/nativeEngineBridge.ts@@ -13,6 +13,7 @@ import type {import type { PerspectiveRuler, StraightRuler } from '../types/perspective';import type { PressureCurveSettings } from '../types/settings';import { resolveDualBrushConfig } from './dualBrushConfig';+import { isBuiltinSurfaceTextureUrl } from './proceduralBrushTips';type ToneDotShape = NonNullable<LayerItem['toneDotShape']>;type ToneDensityType = NonNullable<LayerItem['toneDensityType']>;@@ -956,6 +957,22 @@ export function setNativeCollabPointsEnabled(enabled: boolean): Promise<void> {});}+export interface NativeScratchpadStrokePoint {+ x: number;+ y: number;+ pressure: number;+ tiltX: number;+ tiltY: number;+ twist: number;+ timestampMs: number;+}++export interface NativeScratchpadStrokeInput {+ points: NativeScratchpadStrokePoint[];+ color: [number, number, number];+ seed: number;+}+/*** Renders a GPU-accelerated S-curve brush preview directly on DX12 via `ink-engine`.*/@@ -981,6 +998,37 @@ export async function renderNativeBrushPreview(}}+/**+ * Re-renders Brush Studio scratchpad strokes directly on DX12 via `ink-engine`+ * with the live-edited BrushSettings so every parameter change updates in real time.+ */+export async function renderNativeScratchpadPreview(+ tool: ToolType,+ bs: BrushSettings,+ primaryColor: string,+ secondaryColor: string,+ strokes: NativeScratchpadStrokeInput[],+ width: number,+ height: number+): Promise<NativeFlattenedImage | null> {+ if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;+ try {+ const config = await buildNativeBrushConfigPayload(tool, bs, primaryColor, secondaryColor, false);+ const raw = await invokeNative<ArrayBuffer | Uint8Array>(+ 'native_engine_render_scratchpad_preview',+ {+ brush: config,+ strokes,+ width: Math.max(32, Math.min(1024, Math.round(width))),+ height: Math.max(32, Math.min(1024, Math.round(height))),+ }+ );+ return decodePackedRgbaResponse(raw);+ } catch {+ return null;+ }+}+function sanitizeOptionalCurveForNative(curve: unknown): [number, number][] | null {if (!Array.isArray(curve) || curve.length === 0) return null;const valid: [number, number][] = [];@@ -1147,7 +1195,12 @@ export async function buildNativeBrushConfigPayload(}}- const paperKey = await ensureNativeTextureUploaded(safeBs.paperTexture, 'paper');+ const isBuiltinSurfacePaper = Boolean(+ safeBs.surfaceTextureId && (!safeBs.paperTexture || isBuiltinSurfaceTextureUrl(safeBs.paperTexture))+ );+ const paperKey = isBuiltinSurfacePaper+ ? null+ : await ensureNativeTextureUploaded(safeBs.paperTexture, 'paper');// Dual brush secondary tip(s)const dualCfg = resolveDualBrushConfig(safeBs as BrushSettings);diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.tsindex e61dc51..3ce504b 100644--- a/src/utils/presetBrushes.ts+++ b/src/utils/presetBrushes.ts@@ -3,38 +3,12 @@ import {BrushPresetId,BrushSettings,CspSubTip,- DEFAULT_BRUSH_DYNAMICS,} from '../types/editor';import { CSP_PRESSURE_CURVE_PRESETS } from './brushMath';import {generateRealGPenTip,generateRoughPenRibbonTip,generateCalligraphyTip,- generateMechanicalPencilTip,- generateHb2bPencilTip,- generate6b8bPencilTip,- generateCharcoalTip,- generateChalkTip,- generateOilFlatAllaPrimaTip,- generateImpastoFilbertTip,- generateDryBristleRakePaintTip,- generateConceptMatteChalkTip,- generateMineralGrainDualTip,- generateSilkyPortraitRoundTip,- generateCanvasScumbleSubTip,- generateAtmosphericGrainTip,- generateDetailFilbertTip,- generateBlendOilBristleTip,- generateBlendMatteChalkTip,- generateBlendRakeHairTip,- generateBlendCanvasScumbleTip,- generateBlendFingertipTip,- generateFinePaperTexture,- generateSketchPaperTexture,- generateCharcoalPaperTexture,- generatePainterlyChalkGrainTexture,- generateNaturalTipByProfile,- getSurfaceTextureDataUrl,getSurfaceTextureGradField,} from './proceduralBrushTips';@@ -46,14 +20,6 @@ import {isDecorationPresetId,resolveStaticBrushAssetUrl,} from './decorationBrushes';-import {- PRO_BLEND_BRUSHES,- PRO_NATURAL_PAINT_BRUSHES,- PRO_PAINT_BRUSHES,- PRO_PEN_BRUSHES,- PRO_SKETCH_BRUSHES,- PRO_TEXTURE_FX_BRUSHES,-} from './proPresetBrushes';export {DECORATION_BRUSHES,@@ -84,7 +50,7 @@ export interface BuiltinBrushDefinition {icon: 'pen' | 'pencil' | 'paintbrush' | 'droplets' | 'palette' | 'sparkles';settings: Partial<BrushSettings>;tipGenerator?: () => string; // Returns Base64 PNG data URL- subTipGenerators?: Array<() => string>; // Multi-tip procedural generators (e.g., Rough Pen ribbon, Canvas Scumble)+ subTipGenerators?: Array<() => string>; // Multi-tip procedural generators (e.g., Rough Pen ribbon)subTipDimensions?: { width: number; height: number }; // Explicit dimensions for subTips metadata (default 256x256)staticTips?: StaticBrushTip[]; // Pre-extracted static PNG brush tips (e.g., CSP Decoration brushes)dualTipGenerator?: () => string; // Optional secondary tip generator for built-in Dual Brushes@@ -420,1692 +386,6 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},- ...PRO_PEN_BRUSHES,-- // =========================================================================- // SKETCH SECTION- // =========================================================================- {- id: 'mechanical-pencil',- category: 'sketch',- name: 'Mechanical Pencil',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Firm 0.5mm Lead — Thin, Tilt-Independent, Crisp Edge & Minimal Grain',- icon: 'pencil',- tipGenerator: generateMechanicalPencilTip,- paperTextureGenerator: generateFinePaperTexture,- settings: {- size: 2.8,- minSizeFactor: 0.72,- flow: 0.44,- opacity: 0.94,- hardness: 0.95,- antiAlias: 1,- spacing: 0.1,- stabilization: 6,- sharpCorners: true,- usePressure: true,- useTilt: false,- smoothing: true,- pressureCurve: CSP_PRESSURE_CURVE_PRESETS.firm.points,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- densitySensor: { usePressure: true, pressureMin: 0.35 },- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- grain: 0.34,- textureDensity: 0.34,- paperTextureMode: 'compare',- paperTextureScale: 0.7,- paperTextureContrast: 22,- useGpu: true,- },- },- {- id: 'pencil-hb-2b',- category: 'sketch',- name: 'HB / 2B Pencil',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Classic Graphite — Moderate Tooth, Smooth Pressure Flow & Gentle Tilt Shading',- icon: 'pencil',- tipGenerator: generateHb2bPencilTip,- paperTextureGenerator: generateSketchPaperTexture,- settings: {- size: 5.5,- minSizeFactor: 0.45,- flow: 0.38,- opacity: 0.96,- hardness: 0.78,- antiAlias: 2,- spacing: 0.13,- stabilization: 5,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 0.95,- smoothing: true,- pressureCurve: [- [0, 0],- [0.3, 0.24],- [0.7, 0.7],- [1, 1],- ],- opacitySensor: { usePressure: true, pressureMin: 0.14 },- densitySensor: { usePressure: true, pressureMin: 0.25 },- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- grain: 0.64,- textureDensity: 0.64,- paperTextureMode: 'compare',- paperTextureScale: 0.75,- paperTextureContrast: 28,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.06,- flowJitter: 0.14,- },- useGpu: true,- },- },- {- id: 'pencil-6b-8b',- category: 'sketch',- name: '6B / 8B Pencil',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Rich Soft Graphite — Strong Paper Tooth, Heavy-Pressure Clog & Broad Tilt Edge',- icon: 'pencil',- tipGenerator: generate6b8bPencilTip,- paperTextureGenerator: generateSketchPaperTexture,- settings: {- size: 9,- minSizeFactor: 0.36,- flow: 0.56,- opacity: 1.0,- hardness: 0.65,- antiAlias: 2,- thickness: 0.7,- spacing: 0.14,- stabilization: 4,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 2.1,- smoothing: true,- pressureCurve: [- [0, 0],- [0.25, 0.28],- [0.6, 0.74],- [1, 1],- ],- opacitySensor: { usePressure: true, pressureMin: 0.18 },- densitySensor: { usePressure: true, pressureMin: 0.3 },- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.28,- flipH: 'random',- flipV: 'random',- grain: 0.86,- textureDensity: 0.86,- paperTextureMode: 'compare',- paperTextureScale: 0.9,- paperTextureContrast: 38,- paperTextureBrightness: -4,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.1,- flowJitter: 0.18,- },- useGpu: true,- },- },- {- id: 'charcoal-pencil',- category: 'sketch',- name: 'Charcoal Pencil',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Deep Matte Dry Carbon — Jagged Edge, Aggressive Tooth, Edge Crumbs & Tilt Shading',- icon: 'pencil',- tipGenerator: generateCharcoalTip,- paperTextureGenerator: generateCharcoalPaperTexture,- settings: {- size: 16,- minSizeFactor: 0.3,- flow: 0.68,- opacity: 1.0,- hardness: 0.5,- antiAlias: 2,- thickness: 0.72,- spacing: 0.18,- stabilization: 3,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 2.2,- smoothing: true,- pressureCurve: [- [0, 0],- [0.22, 0.3],- [0.55, 0.76],- [1, 1],- ],- opacitySensor: { usePressure: true, pressureMin: 0.2 },- densitySensor: { usePressure: true, pressureMin: 0.32 },- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- grain: 0.92,- textureDensity: 0.92,- paperTextureMode: 'compare',- paperTextureScale: 1.0,- paperTextureContrast: 48,- paperTextureBrightness: -6,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.2,- angleJitter: 1.0,- roundnessJitter: 0.16,- scatter: 0.05,- scatterBothAxes: true,- count: 1,- flowJitter: 0.22,- },- useGpu: true,- },- },- {- id: 'standard-chalk',- category: 'sketch',- name: 'Standard Chalk',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Powdery Dry Chalk Stick — Heavy Mineral Tooth & Tilt Shading',- icon: 'pencil',- tipGenerator: generateChalkTip,- paperTextureGenerator: generateCharcoalPaperTexture,- settings: {- size: 22,- minSizeFactor: 0.45,- flow: 0.52,- opacity: 0.96,- hardness: 0.6,- antiAlias: 2,- thickness: 0.62,- customTipAngle: 18,- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.18,- flipH: 'random',- flipV: 'random',- spacing: 0.16,- stabilization: 4,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.7,- smoothing: true,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- grain: 0.88,- textureDensity: 0.88,- paperTextureMode: 'compare',- paperTextureScale: 1.05,- paperTextureContrast: 44,- paperTextureBrightness: -4,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.08,- angleJitter: 0.15,- flowJitter: 0.16,- scatter: 0.03,- },- useGpu: true,- },- },- ...PRO_SKETCH_BRUSHES,-- // =========================================================================- // BRUSH SECTION (PRO PAINTERLY ILLUSTRATION & COLORING SUITE)- // =========================================================================- {- id: 'oil-flat-alla-prima',- category: 'brush',- name: 'Alla-Prima Oil Flat',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Asymmetric Flat Hog-Bristle — Crisp Architectural Edge & Feathered Tail for Lost-and-Found Planes',- icon: 'paintbrush',- tipGenerator: generateOilFlatAllaPrimaTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 38,- minSizeFactor: 0.34,- flow: 0.9,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- thickness: 0.72,- customTipAngle: -22,- customTipAngleDynamics: 'none',- flipH: 'none',- flipV: 'none',- spacing: 0.05,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.78,- densityOfPaint: 0.92,- colorStretch: 0.54,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'multiply',- grain: 0.2,- textureDensity: 0.2,- paperTextureScale: 0.9,- paperTextureContrast: 10,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- useGpu: true,- },- },- {- id: 'thick-oil-impasto',- category: 'brush',- name: 'Loaded Impasto Oil',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Chiseled Multi-Tuft Hog-Bristle Filbert — Bold Impasto Ridges & Rich Directional Color Drag',- icon: 'paintbrush',- tipGenerator: generateImpastoFilbertTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 42,- minSizeFactor: 0.38,- flow: 0.96,- opacity: 1.0,- hardness: 0.9,- antiAlias: 2,- thickness: 0.66,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.07,- adjustDensityByGap: false,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'running_color',- amountOfPaint: 0.84,- densityOfPaint: 0.96,- colorStretch: 0.76,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'compare',- grain: 0.28,- textureDensity: 0.28,- paperTextureScale: 0.95,- paperTextureContrast: 20,- opacitySensor: { usePressure: true, pressureMin: 0.42 },- densityOfPaintSensor: { usePressure: true, pressureMin: 0.55 },- useGpu: true,- },- },- {- id: 'dry-bristle-rake-paint',- category: 'brush',- name: 'Dry Bristle Rake',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Separated Organic Bristle Clusters — Expressive Dry Highlights, Cheek Scratches, Hair & Fabric Tooth',- icon: 'paintbrush',- tipGenerator: generateDryBristleRakePaintTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 40,- minSizeFactor: 0.36,- flow: 0.92,- opacity: 1.0,- hardness: 0.92,- antiAlias: 2,- thickness: 0.86,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.042,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'running_color',- amountOfPaint: 0.82,- densityOfPaint: 0.94,- colorStretch: 0.7,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'multiply',- grain: 0.24,- textureDensity: 0.24,- paperTextureScale: 0.88,- paperTextureContrast: 10,- opacitySensor: { usePressure: true, pressureMin: 0.24 },- useGpu: true,- },- },- {- id: 'concept-matte-chalk',- category: 'brush',- name: 'Concept Matte Chalk / Gouache',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Sculptural Chipped Square Chalk + Mineral Dual Brush — Crisp Concept-Art Planes & Velvety Matte Tooth',- icon: 'paintbrush',- tipGenerator: generateConceptMatteChalkTip,- dualTipGenerator: generateMineralGrainDualTip,- paperTextureGenerator: generatePainterlyChalkGrainTexture,- settings: {- size: 44,- minSizeFactor: 0.26,- flow: 0.95,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- thickness: 0.56,- customTipAngle: -28,- customTipAngleDynamics: 'none',- customTipRotationRandomScale: 0,- flipH: 'none',- flipV: 'none',- spacing: 0.08,- adjustDensityByGap: false,- stabilization: 6,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 1.3,- smoothing: true,- pressureCurve: [- [0, 0],- [0.24, 0.2],- [0.6, 0.76],- [1, 1],- ],- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.86,- densityOfPaint: 0.95,- colorStretch: 0.38,- grain: 0.56,- textureDensity: 0.56,- paperTextureMode: 'compare',- paperTextureScale: 0.9,- paperTextureContrast: 24,- paperTextureBrightness: -2,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- dualBrush: true,- dualBrushCompositeMode: 'multiply',- dualLinkSize: true,- dualScale: 1.15,- dualSpacing: 0.12,- dualDensity: 0.96,- dualAngleDynamics: 'random',- dualFlipH: 'random',- dualFlipV: 'random',- dualBrushConfig: {- enabled: true,- compositeMode: 'multiply',- linkSizeWithMain: true,- sizeRatio: 1.15,- spacing: 0.12,- density: 0.96,- angleDynamics: 'random',- flipH: 'random',- flipV: 'random',- },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.02,- angleJitter: 0.015,- flowJitter: 0.05,- },- useGpu: true,- },- },- {- id: 'silky-portrait-round',- category: 'brush',- name: 'Silky Portrait Round',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Creamy Organic Portrait Round — Luminous Skin Glazing, Rose Petals & Velvety Pigment Blend',- icon: 'paintbrush',- tipGenerator: generateSilkyPortraitRoundTip,- settings: {- size: 32,- minSizeFactor: 0.24,- flow: 0.82,- opacity: 1.0,- hardness: 0.72,- antiAlias: 3,- thickness: 0.92,- customTipAngleDynamics: 'none',- flipH: 'none',- flipV: 'none',- spacing: 0.055,- adjustDensityByGap: false,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- pressureCurve: [- [0, 0],- [0.28, 0.24],- [0.7, 0.76],- [1, 1],- ],- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.62,- densityOfPaint: 0.84,- colorStretch: 0.62,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.14 },- useGpu: true,- },- },- {- id: 'canvas-scumble-oil',- category: 'brush',- name: 'Canvas Scumble / Old Master',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Multi-Tip Dry-Oil Scumble — Broken-Color Tweed, Umber Grounds & Linen Peak Patina',- icon: 'paintbrush',- subTipGenerators: [- () => generateCanvasScumbleSubTip(0),- () => generateCanvasScumbleSubTip(1),- () => generateCanvasScumbleSubTip(2),- () => generateCanvasScumbleSubTip(3),- ],- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 52,- minSizeFactor: 0.34,- flow: 0.88,- opacity: 1.0,- hardness: 0.76,- antiAlias: 2,- thickness: 0.84,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- customTipRotationRandomScale: 0.65,- flipH: 'random',- flipV: 'random',- spacing: 0.11,- adjustDensityByGap: false,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.1,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.76,- densityOfPaint: 0.88,- colorStretch: 0.46,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'compare',- grain: 0.66,- textureDensity: 0.66,- paperTextureScale: 0.92,- paperTextureContrast: 30,- opacitySensor: { usePressure: true, pressureMin: 0.2 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.12,- flowJitter: 0.14,- colorJitterEnabled: true,- temperatureJitter: 0.03,- },- useGpu: true,- },- },- {- id: 'soft-glaze-airbrush',- category: 'brush',- name: 'Soft Glaze Airbrush',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Silky Zero-Banding Airbrush — Atmospheric Halation, Soft Shadow Glazes & Luminous Glow',- icon: 'paintbrush',- settings: {- size: 64,- minSizeFactor: 0.55,- flow: 0.26,- opacity: 1.0,- hardness: 0.0,- antiAlias: 3,- spacing: 0.055,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- adjustDensityByGap: true,- pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,- opacitySensor: { usePressure: true, pressureMin: 0.06 },- useGpu: true,- },- },- {- id: 'atmospheric-grain-shader',- category: 'brush',- name: 'Atmospheric Grain Shader',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Organic Mineral-Cloud Stipple — Dusty Skies, Painterly Film Grain & Textured Mist',- icon: 'paintbrush',- tipGenerator: generateAtmosphericGrainTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('stipple-grain'),- settings: {- size: 58,- minSizeFactor: 0.44,- flow: 0.42,- opacity: 1.0,- hardness: 0.18,- antiAlias: 2,- spacing: 0.1,- stabilization: 5,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.1,- smoothing: true,- adjustDensityByGap: true,- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- surfaceTextureId: 'stipple-grain',- grain: 0.54,- textureDensity: 0.54,- paperTextureMode: 'multiply',- paperTextureScale: 0.85,- paperTextureContrast: 24,- opacitySensor: { usePressure: true, pressureMin: 0.08 },- densitySensor: { usePressure: true, pressureMin: 0.16 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.1,- angleJitter: 1.0,- flowJitter: 0.18,- scatter: 0.1,- scatterBothAxes: true,- count: 1,- },- useGpu: true,- },- },- {- id: 'fine-detail-filbert',- category: 'brush',- name: 'Detail & Specular Liner',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Springy Tapered Sable Detail Filbert — Crisp Gold Filigree, Eyelashes & Glowing Specular Glints',- icon: 'paintbrush',- tipGenerator: generateDetailFilbertTip,- settings: {- size: 10,- minSizeFactor: 0.1,- flow: 0.98,- opacity: 1.0,- hardness: 0.9,- antiAlias: 2,- thickness: 0.84,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.045,- adjustDensityByGap: false,- stabilization: 11,- sharpCorners: true,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.94,- densityOfPaint: 0.98,- colorStretch: 0.2,- taper: {- useIn: false,- inLength: 0,- inRatio: 0,- useOut: true,- outLength: 16,- outRatio: 0.22,- inOutType: 2,- endingSharpness: 0.78,- affectSize: true,- minSizeRatio: 0.08,- },- useGpu: true,- },- },- ...PRO_PAINT_BRUSHES,-- // =========================================================================- // BLEND SECTION (DEDICATED PURE BLENDERS PAIRED TO EVERY PAINTING STYLE)- // =========================================================================- {- id: 'blend-velvet-soft',- category: 'blend',- name: 'Velvet Skin Blend',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Silky Optical Skin Blender — Soft CSP Blur Diffusion & Kubelka-Munk Tonal Harmony',- icon: 'droplets',- settings: {- size: 42,- minSizeFactor: 0.42,- flow: 0.72,- opacity: 1.0,- hardness: 0.22,- antiAlias: 3,- spacing: 0.08,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.76,- colorStretch: 0.78,- useBlur: true,- blurStrength: 0.38,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- useGpu: true,- },- },- {- id: 'blend-oil-bristle',- category: 'blend',- name: 'Oil Bristle Smudge',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Directional Flat Bristle Smudger — Pulls & Blends Wet Oil While Keeping Brushwork Alive',- icon: 'droplets',- tipGenerator: generateBlendOilBristleTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 44,- minSizeFactor: 0.36,- flow: 0.88,- opacity: 1.0,- hardness: 0.76,- antiAlias: 2,- thickness: 0.68,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.048,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.9,- colorStretch: 0.88,- useBlur: false,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'multiply',- grain: 0.18,- textureDensity: 0.18,- paperTextureScale: 0.9,- paperTextureContrast: 10,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- useGpu: true,- },- },- {- id: 'blend-matte-chalk',- category: 'blend',- name: 'Matte Chalk Blender',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Velvety Concept-Art Chalk Blender — Melts Hard Planes into Soft Matte Gradients with Tooth Intact',- icon: 'droplets',- tipGenerator: generateBlendMatteChalkTip,- paperTextureGenerator: generatePainterlyChalkGrainTexture,- settings: {- size: 48,- minSizeFactor: 0.36,- flow: 0.86,- opacity: 1.0,- hardness: 0.44,- antiAlias: 2,- thickness: 0.7,- customTipAngle: 0,- customTipAngleDynamics: 'direction',- customTipRotationRandomScale: 0,- flipH: 'none',- flipV: 'none',- spacing: 0.09,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.25,- smoothing: true,- pressureCurve: [- [0, 0],- [0.26, 0.24],- [0.64, 0.78],- [1, 1],- ],- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.92,- colorStretch: 0.82,- useBlur: true,- blurStrength: 0.14,- grain: 0.54,- textureDensity: 0.54,- paperTextureMode: 'compare',- paperTextureScale: 0.94,- paperTextureContrast: 24,- paperTextureBrightness: -2,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- angleJitter: 0.025,- flowJitter: 0.06,- },- useGpu: true,- },- },- {- id: 'blend-rake-hair',- category: 'blend',- name: 'Rake Hair & Fur Smear',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Fine Multi-Strand Rake Blender — Pulls Wispy Hair, Mane, Fur & Feather Threads Across Edges',- icon: 'droplets',- tipGenerator: generateBlendRakeHairTip,- settings: {- size: 36,- minSizeFactor: 0.32,- flow: 0.92,- opacity: 1.0,- hardness: 0.82,- antiAlias: 2,- thickness: 0.82,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.055,- adjustDensityByGap: false,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.1,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.94,- colorStretch: 0.92,- useBlur: false,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.24 },- useGpu: true,- },- },- {- id: 'blend-canvas-scumble',- category: 'blend',- name: 'Canvas Scumble Melter',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Porous Dry-Bristle Scumble Blender — Dissolves Hard Edges Directly into Authentic Canvas Grain',- icon: 'droplets',- tipGenerator: generateBlendCanvasScumbleTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 48,- minSizeFactor: 0.34,- flow: 0.84,- opacity: 1.0,- hardness: 0.56,- antiAlias: 2,- thickness: 0.86,- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.45,- flipH: 'random',- flipV: 'random',- spacing: 0.055,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.86,- colorStretch: 0.72,- useBlur: true,- blurStrength: 0.12,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'multiply',- grain: 0.42,- textureDensity: 0.42,- paperTextureScale: 0.9,- paperTextureContrast: 16,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- useGpu: true,- },- },- {- id: 'blend-fingertip',- category: 'blend',- name: 'Wet Finger Tip',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'CSP Finger Tip Smudger — Firm Directional Paint Pulling for Flowing Hair, Mist & Long Trails',- icon: 'droplets',- tipGenerator: generateBlendFingertipTip,- settings: {- size: 28,- minSizeFactor: 0.28,- flow: 0.94,- opacity: 1.0,- hardness: 0.56,- antiAlias: 2,- thickness: 0.86,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.045,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.96,- colorStretch: 0.95,- useBlur: false,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.26 },- useGpu: true,- },- },- ...PRO_BLEND_BRUSHES,-- // =========================================================================- // NATURAL PAINT SECTION (Realistic Impasto, Bristle Ribbon & Pigment Mixing)- // =========================================================================- {- id: 'impasto-bristle-oil',- category: 'natural-paint',- name: 'Impasto Bristle Oil',- badge: 'Oil',- badgeBg: 'bg-rose-500/15',- badgeText: 'text-rose-300',- badgeBorder: 'border-rose-500/30',- desc: 'Thick Tactile Oil Paint with Pronounced 3D Bristle Ridges, Specular Sheen & Linen Weave Fringes',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('filbert'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 46,- minSizeFactor: 0.35,- flow: 0.94,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- spacing: 0.05,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'filbert',- count: 24,- clumping: 0.56,- stiffness: 0.64,- length: 1.0,- splay: 0.34,- irregularity: 0.44,- edgeRidge: 0.32,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'impasto_mix',- amountOfPaint: 0.88,- densityOfPaint: 0.96,- colorStretch: 0.74,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.9,- paintLoad: 0.88,- depletionRate: 0.2,- wetness: 0.54,- viscosity: 0.68,- autoClean: true,- chargePerPressure: 0.52,- dryBrush: 0.32,- },- impasto: {- enabled: true,- depth: 0.86,- bristleRelief: 0.90,- gloss: 0.50,- reliefContrast: 0.72,- lightAzimuth: 225,- lightElevation: 32,- },- surfaceTextureId: 'linen-canvas',- grainMappingMode: 'canvas-locked',- grain: 0.46,- textureDensity: 0.46,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 24,- useGpu: true,- },- },- {- id: 'wet-mixing-filbert',- category: 'natural-paint',- name: 'Creamy Oil Filbert',- badge: 'Oil',- badgeBg: 'bg-rose-500/15',- badgeText: 'text-rose-300',- badgeBorder: 'border-rose-500/30',- desc: 'Buttery Oil Filbert with Per-Bristle Spatial Color Pickup & Vibrant Multi-Color Curved Streaks',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('filbert'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 54,- minSizeFactor: 0.38,- flow: 0.94,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- spacing: 0.045,- stabilization: 12,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.25,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'filbert',- count: 32,- clumping: 0.36,- stiffness: 0.56,- length: 1.15,- splay: 0.38,- irregularity: 0.3,- edgeRidge: 0.22,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'running_color',- amountOfPaint: 0.76,- densityOfPaint: 0.94,- colorStretch: 0.85,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.95,- paintLoad: 0.76,- depletionRate: 0.14,- wetness: 0.82,- viscosity: 0.4,- autoClean: true,- chargePerPressure: 0.48,- dryBrush: 0.24,- },- impasto: {- enabled: true,- depth: 0.66,- bristleRelief: 0.72,- gloss: 0.56,- reliefContrast: 0.60,- lightAzimuth: 225,- lightElevation: 34,- },- surfaceTextureId: 'linen-canvas',- grainMappingMode: 'canvas-locked',- grain: 0.36,- textureDensity: 0.36,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 20,- useGpu: true,- },- },- {- id: 'dry-bristle-rake',- category: 'natural-paint',- name: 'Dry Bristle Rake',- badge: 'Dry',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Stiff Separated Bristles with Crisp Parallel Tracks, Paint Exhaustion & Linen Weave Breakup',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('rake'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 48,- minSizeFactor: 0.42,- flow: 0.94,- opacity: 1.0,- hardness: 0.94,- antiAlias: 2,- spacing: 0.05,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'rake',- count: 34,- clumping: 0.58,- stiffness: 0.84,- length: 0.95,- splay: 0.28,- irregularity: 0.52,- edgeRidge: 0.14,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.9,- densityOfPaint: 0.97,- colorStretch: 0.72,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.86,- paintLoad: 0.9,- depletionRate: 0.26,- wetness: 0.42,- viscosity: 0.68,- autoClean: true,- chargePerPressure: 0.5,- dryBrush: 0.34,- },- impasto: {- enabled: true,- depth: 0.58,- bristleRelief: 0.86,- gloss: 0.34,- reliefContrast: 0.64,- lightAzimuth: 225,- lightElevation: 36,- },- surfaceTextureId: 'linen-canvas',- grainMappingMode: 'canvas-locked',- grain: 0.38,- textureDensity: 0.38,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 26,- useGpu: true,- },- },- {- id: 'heavy-body-acrylic',- category: 'natural-paint',- name: 'Heavy Body Acrylic',- badge: 'Acrylic',- badgeBg: 'bg-orange-500/15',- badgeText: 'text-orange-300',- badgeBorder: 'border-orange-500/30',- desc: 'Opaque Springy Flat Bristle Acrylic with Crisp Edges, Satin Relief & Controlled Wet Blending',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('flat'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('fine-cotton'),- settings: {- size: 42,- minSizeFactor: 0.32,- flow: 0.95,- opacity: 1.0,- hardness: 0.92,- antiAlias: 2,- spacing: 0.05,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.1,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'flat',- count: 30,- clumping: 0.38,- stiffness: 0.76,- length: 0.9,- splay: 0.25,- irregularity: 0.3,- edgeRidge: 0.28,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.9,- densityOfPaint: 0.96,- colorStretch: 0.58,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.85,- paintLoad: 0.9,- depletionRate: 0.18,- wetness: 0.45,- viscosity: 0.62,- autoClean: true,- chargePerPressure: 0.45,- dryBrush: 0.24,- },- impasto: {- enabled: true,- depth: 0.62,- bristleRelief: 0.64,- gloss: 0.34,- reliefContrast: 0.58,- lightAzimuth: 225,- lightElevation: 36,- },- surfaceTextureId: 'fine-cotton',- grainMappingMode: 'canvas-locked',- grain: 0.32,- textureDensity: 0.32,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 18,- useGpu: true,- },- },- {- id: 'palette-knife-impasto',- category: 'natural-paint',- name: 'Palette Knife',- badge: 'Knife',- badgeBg: 'bg-fuchsia-500/15',- badgeText: 'text-fuchsia-300',- badgeBorder: 'border-fuchsia-500/30',- desc: 'Sharp-Edged Painting Knife with Heavy Border Paint Ridges & Bold Spatial Scraping',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('knife'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),- settings: {- size: 56,- minSizeFactor: 0.45,- flow: 0.96,- opacity: 1.0,- hardness: 0.98,- antiAlias: 2,- spacing: 0.045,- stabilization: 9,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 1.35,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'knife',- count: 16,- clumping: 0.05,- stiffness: 0.96,- length: 0.65,- splay: 0.15,- irregularity: 0.18,- edgeRidge: 0.92,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'impasto_mix',- amountOfPaint: 0.85,- densityOfPaint: 0.98,- colorStretch: 0.76,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.9,- paintLoad: 0.85,- depletionRate: 0.36,- wetness: 0.68,- viscosity: 0.78,- autoClean: true,- chargePerPressure: 0.58,- dryBrush: 0.44,- },- impasto: {- enabled: true,- depth: 0.92,- bristleRelief: 0.32,- gloss: 0.68,- reliefContrast: 0.82,- lightAzimuth: 225,- lightElevation: 30,- },- surfaceTextureId: 'coarse-burlap',- grainMappingMode: 'canvas-locked',- grain: 0.44,- textureDensity: 0.44,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 26,- useGpu: true,- },- },- {- id: 'velvet-gouache',- category: 'natural-paint',- name: 'Velvet Gouache',- badge: 'Matte',- badgeBg: 'bg-violet-500/15',- badgeText: 'text-violet-300',- badgeBorder: 'border-violet-500/30',- desc: 'Smooth Matte Opaque Gouache with Gentle Wet Reactivation & Fine Gesso Tooth',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('filbert'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),- settings: {- size: 38,- minSizeFactor: 0.28,- flow: 0.94,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- spacing: 0.05,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.0,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'filbert',- count: 34,- clumping: 0.18,- stiffness: 0.48,- length: 1.05,- splay: 0.32,- irregularity: 0.2,- edgeRidge: 0.08,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.88,- densityOfPaint: 0.96,- colorStretch: 0.55,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.88,- paintLoad: 0.88,- depletionRate: 0.14,- wetness: 0.55,- viscosity: 0.35,- autoClean: true,- chargePerPressure: 0.38,- dryBrush: 0.18,- },- impasto: {- enabled: true,- depth: 0.16,- bristleRelief: 0.22,- gloss: 0.04,- reliefContrast: 0.25,- lightAzimuth: 225,- lightElevation: 42,- },- surfaceTextureId: 'gesso-board',- grainMappingMode: 'canvas-locked',- grain: 0.28,- textureDensity: 0.28,- paperTextureMode: 'multiply',- paperTextureScale: 0.9,- paperTextureContrast: 16,- useGpu: true,- },- },- {- id: 'granulating-watercolor',- category: 'natural-paint',- name: 'Granulating Watercolor',- badge: 'Water',- badgeBg: 'bg-cyan-500/15',- badgeText: 'text-cyan-300',- badgeBorder: 'border-cyan-500/30',- desc: 'Translucent Watercolor Glaze with Wet Edge Rim & Pigment Settling into Cold-Press Valleys',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('round'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),- settings: {- size: 44,- minSizeFactor: 0.22,- flow: 0.58,- opacity: 0.72,- hardness: 0.65,- antiAlias: 2,- spacing: 0.055,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.35,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'round',- count: 28,- clumping: 0.14,- stiffness: 0.32,- length: 1.35,- splay: 0.52,- irregularity: 0.22,- edgeRidge: 0.05,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.72,- densityOfPaint: 0.65,- colorStretch: 0.65,- wetEdge: 0.58,- wetEdgeRadius: 3.0,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.92,- paintLoad: 0.72,- depletionRate: 0.12,- wetness: 0.68,- viscosity: 0.15,- autoClean: true,- chargePerPressure: 0.45,- dryBrush: 0.14,- granulation: 0.76,- },- impasto: {- enabled: false,- depth: 0.0,- bristleRelief: 0.0,- gloss: 0.0,- reliefContrast: 0.0,- lightAzimuth: 225,- lightElevation: 42,- },- surfaceTextureId: 'cold-press-watercolor',- grainMappingMode: 'canvas-locked',- grain: 0.56,- textureDensity: 0.56,- paperTextureMode: 'multiply',- paperTextureScale: 0.95,- paperTextureContrast: 24,- useGpu: true,- },- },- {- id: 'oil-bristle-blender',- category: 'natural-paint',- name: 'Dry Bristle Blender',- badge: 'Blend',- badgeBg: 'bg-teal-500/15',- badgeText: 'text-teal-300',- badgeBorder: 'border-teal-500/30',- desc: 'Zero-Load Physical Fan Bristle Blender — Pulls & Harmonizes Paint with Relief Grooves Intact',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('fan'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 52,- minSizeFactor: 0.35,- flow: 0.9,- opacity: 1.0,- hardness: 0.75,- antiAlias: 2,- spacing: 0.05,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'fan',- count: 32,- clumping: 0.34,- stiffness: 0.62,- length: 1.15,- splay: 0.42,- irregularity: 0.35,- edgeRidge: 0.14,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.92,- colorStretch: 0.85,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.92,- paintLoad: 0.0,- depletionRate: 0.0,- wetness: 0.92,- viscosity: 0.45,- autoClean: true,- chargePerPressure: 0.35,- dryBrush: 0.22,- },- impasto: {- enabled: true,- depth: 0.45,- bristleRelief: 0.68,- gloss: 0.32,- reliefContrast: 0.48,- lightAzimuth: 225,- lightElevation: 36,- },- surfaceTextureId: 'linen-canvas',- grainMappingMode: 'canvas-locked',- grain: 0.3,- textureDensity: 0.3,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- useGpu: true,- },- },- {- id: 'pastel-stick-canvas',- category: 'natural-paint',- name: 'Soft Oil Pastel',- badge: 'Pastel',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Creamy Oil Pastel with Broad Stylus Tilt Shading & Crisp Coverage Across Rough Paper Peaks',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('flat'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('rough-pastel'),- settings: {- size: 32,- minSizeFactor: 0.4,- flow: 0.92,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- spacing: 0.055,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.85,- smoothing: true,- renderMode: 'bristle-hybrid',- bristle: {- profile: 'flat',- count: 26,- clumping: 0.22,- stiffness: 0.88,- length: 0.7,- splay: 0.55,- irregularity: 0.48,- edgeRidge: 0.15,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.85,- densityOfPaint: 0.92,- colorStretch: 0.48,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.86,- paintLoad: 0.85,- depletionRate: 0.26,- wetness: 0.4,- viscosity: 0.74,- autoClean: true,- chargePerPressure: 0.72,- dryBrush: 0.66,- },- impasto: {- enabled: true,- depth: 0.38,- bristleRelief: 0.32,- gloss: 0.14,- reliefContrast: 0.52,- lightAzimuth: 315,- lightElevation: 45,- },- surfaceTextureId: 'rough-pastel',- grainMappingMode: 'canvas-locked',- grain: 0.78,- textureDensity: 0.78,- paperTextureMode: 'compare',- paperTextureScale: 0.95,- paperTextureContrast: 36,- useGpu: true,- },- },- ...PRO_NATURAL_PAINT_BRUSHES,-- // =========================================================================- // TEXTURE & FX SECTION (FOLIAGE, FRECKLES, SMOKE, ROCK, EMBER, CLOUDS, GLOW)- // =========================================================================- ...PRO_TEXTURE_FX_BRUSHES,];export const ALL_BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [diff --git a/src/utils/proPresetBrushes.ts b/src/utils/proPresetBrushes.tsdeleted file mode 100644index c7af3ab..0000000--- a/src/utils/proPresetBrushes.ts+++ /dev/null@@ -1,2014 +0,0 @@-/**- * proPresetBrushes.ts- * Expanded world-class professional brush presets for InkStudio across all 6 built-in sections:- * Pen (+4), Sketch (+4), Brush (+10), Blend (+4), Natural Paint (+4), and Texture & FX (+10).- *- * Strictly additive — leaves all 35 original built-in brushes completely untouched.- */--import { DEFAULT_BRUSH_DYNAMICS } from '../types/editor';-import { CSP_PRESSURE_CURVE_PRESETS } from './brushMath';-import type { BuiltinBrushDefinition } from './presetBrushes';-import {- generateCharcoalPaperTexture,- generateFinePaperTexture,- generateMineralGrainDualTip,- generateNaturalTipByProfile,- generatePainterlyChalkGrainTexture,- generateSketchPaperTexture,- getSurfaceTextureDataUrl,-} from './proceduralBrushTips';-import {- generateBlendGouachePadTip,- generateBlendKnifeSmearTip,- generateBlendSmokeWispTip,- generateBlendTortillonTip,- generateBokehLeafSubTip,- generateCharcoalBlockTip,- generateColErasePencilTip,- generateConceptBristleSubTip,- generateConteCrayonTip,- generateCraggyRockSubTip,- generateDryHairSheenTip,- generateEmberSpatterSubTip,- generateFineStippleSubTip,- generateHairLocksTip,- generateHairWispTip,- generateHardSquareTip,- generateLuminousBloomTip,- generateMetallicGlintTip,- generatePainterlyCloudSubTip,- generatePainterlyGouacheFlatTip,- generatePainterlyLeafSubTip,- generatePainterlyOvalTip,- generateSilkThreadRibbonTip,- generateSkinFrecklesSubTip,- generateSmokeDualMaskTip,- generateSmokeTendrilSubTip,- generateSoftTaperedLinerTip,- generateSumiBrushTip,- generateVineCharcoalTip,- generateWatercolorWashTip,- generateWedgeChiselTip,- generateWovenFabricTip,-} from './proProceduralBrushTips';--// =============================================================================-// PEN SECTION PRO ADDITIONS (+4)-// =============================================================================--export const PRO_PEN_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'tapered-ink-liner',- category: 'pen',- name: 'Soft Tapered Liner',- badge: 'Pen',- badgeBg: 'bg-indigo-500/15',- badgeText: 'text-indigo-300',- badgeBorder: 'border-indigo-500/30',- desc: 'Silky Painted-Ink Sable Nib — Razor Start/End Taper for Hair Wisps, Glasses & Painterly Lineart',- icon: 'pen',- tipGenerator: generateSoftTaperedLinerTip,- settings: {- size: 10,- minSizeFactor: 0.04,- flow: 0.96,- opacity: 1.0,- hardness: 0.86,- antiAlias: 3,- thickness: 0.92,- customTipAngleDynamics: 'direction',- spacing: 0.04,- stabilization: 12,- sharpCorners: true,- usePressure: true,- useTilt: false,- smoothing: true,- pressureCurve: [- [0.0, 0.0],- [0.32, 0.22],- [0.72, 0.78],- [1.0, 1.0],- ],- opacitySensor: { usePressure: true, pressureMin: 0.35 },- taper: {- useIn: true,- inLength: 22,- inRatio: 0.2,- useOut: true,- outLength: 28,- outRatio: 0.25,- inOutType: 2,- startingSharpness: 0.85,- endingSharpness: 0.88,- affectSize: true,- minSizeRatio: 0.04,- },- useGpu: true,- },- },- {- id: 'sumi-fude-brush',- category: 'pen',- name: 'Sumi Brush Pen',- badge: 'Pen',- badgeBg: 'bg-indigo-500/15',- badgeText: 'text-indigo-300',- badgeBorder: 'border-indigo-500/30',- desc: 'Expressive Wolf-Hair Fude Brush — Juicy Ink Pools with Organic Dry-Paper Bristle Breakup',- icon: 'pen',- tipGenerator: generateSumiBrushTip,- paperTextureGenerator: generateSketchPaperTexture,- settings: {- size: 18,- minSizeFactor: 0.05,- flow: 0.98,- opacity: 1.0,- hardness: 0.94,- antiAlias: 2,- thickness: 0.82,- customTipAngleDynamics: 'direction',- spacing: 0.045,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- useVelocity: true,- smoothing: true,- sizeSensor: {- usePressure: true,- pressureMin: 0.04,- pressureCurve: [- [0.0, 0.0],- [0.45, 0.36],- [1.0, 1.0],- ],- useTilt: true,- tiltMin: 1.0,- tiltMax: 1.75,- useVelocity: true,- velocityMin: 0.55,- velocityCurve: [- [0.0, 1.0],- [1.0, 0.0],- ],- },- grain: 0.28,- textureDensity: 0.28,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 28,- taper: {- useIn: false,- inLength: 0,- inRatio: 0,- useOut: true,- outLength: 26,- outRatio: 0.24,- inOutType: 2,- endingSharpness: 0.86,- affectSize: true,- minSizeRatio: 0.05,- },- useGpu: true,- },- },- {- id: 'silk-embroidery-ribbon',- category: 'pen',- name: 'Silk Thread Multi-Line',- badge: 'Ribbon',- badgeBg: 'bg-indigo-500/15',- badgeText: 'text-indigo-300',- badgeBorder: 'border-indigo-500/30',- desc: 'Flowing 5-Filament Embroidery Ribbon — Curved Gold Veil Patterns, Filigree & Hair Ribbons',- icon: 'pen',- subTipGenerators: [- () => generateSilkThreadRibbonTip(0),- () => generateSilkThreadRibbonTip(1),- () => generateSilkThreadRibbonTip(2),- ],- subTipDimensions: { width: 64, height: 512 },- settings: {- size: 34,- minSizeFactor: 0.4,- flow: 0.94,- opacity: 0.96,- hardness: 0.96,- antiAlias: 2,- thickness: 1.0,- thicknessVertical: true,- spacing: 0.06,- stabilization: 16,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- isRibbon: true,- subTipOrder: 'random-no-repeat',- flipH: 'none',- flipV: 'none',- opacitySensor: { usePressure: true, pressureMin: 0.24 },- taper: {- useIn: true,- inLength: 42,- inRatio: 0.25,- useOut: true,- outLength: 56,- outRatio: 0.3,- inOutType: 2,- affectSize: true,- affectOpacity: true,- minSizeRatio: 0.35,- },- useGpu: true,- },- },- {- id: 'fine-hair-wisp',- category: 'pen',- name: 'Hair Strand & Lash',- badge: 'Pen',- badgeBg: 'bg-indigo-500/15',- badgeText: 'text-indigo-300',- badgeBorder: 'border-indigo-500/30',- desc: 'Gossamer 3-Filament Hair Liner — Natural Flyaway Strands, Wispy Bangs, Brows & Eyelashes',- icon: 'pen',- tipGenerator: generateHairWispTip,- settings: {- size: 11,- minSizeFactor: 0.08,- flow: 0.94,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- thickness: 0.88,- customTipAngleDynamics: 'direction',- spacing: 0.04,- stabilization: 11,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.88,- densityOfPaint: 0.96,- colorStretch: 0.32,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- taper: {- useIn: true,- inLength: 18,- inRatio: 0.2,- useOut: true,- outLength: 28,- outRatio: 0.26,- inOutType: 2,- startingSharpness: 0.84,- endingSharpness: 0.9,- affectSize: true,- minSizeRatio: 0.05,- },- useGpu: true,- },- },-];--// =============================================================================-// SKETCH SECTION PRO ADDITIONS (+4)-// =============================================================================--export const PRO_SKETCH_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'vine-charcoal-wash',- category: 'sketch',- name: 'Vine Charcoal Wash',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Velvety Soft Willow Charcoal — Sweeping Chiaroscuro Value Washes & Smoky Portrait Grounds',- icon: 'pencil',- tipGenerator: generateVineCharcoalTip,- paperTextureGenerator: generateCharcoalPaperTexture,- settings: {- size: 36,- minSizeFactor: 0.45,- flow: 0.34,- opacity: 0.96,- hardness: 0.26,- antiAlias: 2,- thickness: 0.78,- spacing: 0.14,- stabilization: 4,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 2.3,- smoothing: true,- pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,- opacitySensor: { usePressure: true, pressureMin: 0.12 },- densitySensor: { usePressure: true, pressureMin: 0.22 },- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- grain: 0.72,- textureDensity: 0.72,- paperTextureMode: 'compare',- paperTextureScale: 1.05,- paperTextureContrast: 38,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.08,- angleJitter: 1.0,- flowJitter: 0.14,- },- useGpu: true,- },- },- {- id: 'compressed-charcoal-block',- category: 'sketch',- name: 'Flat Charcoal Block',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Snapped Square Carbon Stick — Razor Chisel Corner for Planes & Broad Matte Tilt Shading',- icon: 'pencil',- tipGenerator: generateCharcoalBlockTip,- paperTextureGenerator: generateCharcoalPaperTexture,- settings: {- size: 26,- minSizeFactor: 0.42,- flow: 0.72,- opacity: 1.0,- hardness: 0.72,- antiAlias: 2,- thickness: 0.44,- customTipAngle: -24,- customTipAngleDynamics: 'none',- spacing: 0.12,- stabilization: 5,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 1.9,- smoothing: true,- opacitySensor: { usePressure: true, pressureMin: 0.2 },- grain: 0.82,- textureDensity: 0.82,- paperTextureMode: 'compare',- paperTextureScale: 1.0,- paperTextureContrast: 46,- paperTextureBrightness: -4,- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.05,- flowJitter: 0.12,- },- useGpu: true,- },- },- {- id: 'conte-sanguine-crayon',- category: 'sketch',- name: 'Conté Crayon',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Old Master Wax-Mineral Crayon — Creamy Life-Drawing Buildup & Crisp Gesso Tooth',- icon: 'pencil',- tipGenerator: generateConteCrayonTip,- paperTextureGenerator: generatePainterlyChalkGrainTexture,- settings: {- size: 18,- minSizeFactor: 0.38,- flow: 0.64,- opacity: 1.0,- hardness: 0.74,- antiAlias: 2,- thickness: 0.76,- customTipAngle: -16,- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.22,- spacing: 0.12,- stabilization: 5,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.65,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.86,- densityOfPaint: 0.92,- colorStretch: 0.28,- grain: 0.68,- textureDensity: 0.68,- paperTextureMode: 'compare',- paperTextureScale: 0.92,- paperTextureContrast: 32,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- useGpu: true,- },- },- {- id: 'col-erase-sketch-pencil',- category: 'sketch',- name: 'Animation Sketch Pencil',- badge: 'Sketch',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: 'Smooth Waxy Col-Erase Rough Pencil — Effortless Gesture Lines, Character Roughs & Clean Tooth',- icon: 'pencil',- tipGenerator: generateColErasePencilTip,- paperTextureGenerator: generateFinePaperTexture,- settings: {- size: 4.5,- minSizeFactor: 0.36,- flow: 0.54,- opacity: 0.96,- hardness: 0.86,- antiAlias: 2,- spacing: 0.09,- stabilization: 7,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 1.35,- smoothing: true,- pressureCurve: [- [0, 0],- [0.28, 0.22],- [0.68, 0.74],- [1, 1],- ],- opacitySensor: { usePressure: true, pressureMin: 0.16 },- densitySensor: { usePressure: true, pressureMin: 0.28 },- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- grain: 0.44,- textureDensity: 0.44,- paperTextureMode: 'compare',- paperTextureScale: 0.75,- paperTextureContrast: 24,- useGpu: true,- },- },-];--// =============================================================================-// BRUSH SECTION PRO PAINTERLY ADDITIONS (+10)-// =============================================================================--export const PRO_PAINT_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'sculptural-hard-square',- category: 'brush',- name: 'Hard Square Block-In',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Architectural Chisel Square — Crisp Facial Planes, Cast Shadows & Faceted Metallic Reflections',- icon: 'paintbrush',- tipGenerator: generateHardSquareTip,- settings: {- size: 36,- minSizeFactor: 0.68,- flow: 0.94,- opacity: 1.0,- hardness: 0.96,- antiAlias: 2,- thickness: 0.62,- customTipAngle: -18,- customTipAngleDynamics: 'none',- flipH: 'none',- flipV: 'none',- spacing: 0.055,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: true,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.84,- densityOfPaint: 0.94,- colorStretch: 0.34,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- useGpu: true,- },- },- {- id: 'opaque-gouache-flat',- category: 'brush',- name: 'Painterly Gouache Flat',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Layered Opaque-Watercolor Flat — Overlapping Translucent Cloth Folds with Subtle Wet-Edge Pooling',- icon: 'paintbrush',- tipGenerator: generatePainterlyGouacheFlatTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),- settings: {- size: 38,- minSizeFactor: 0.36,- flow: 0.84,- opacity: 0.96,- hardness: 0.86,- antiAlias: 2,- thickness: 0.68,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.055,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.72,- densityOfPaint: 0.86,- colorStretch: 0.44,- wetEdge: 0.24,- wetEdgeRadius: 2.0,- wetEdgeAlphaPower: 0.18,- wetEdgeValuePower: 0.14,- surfaceTextureId: 'gesso-board',- paperTextureMode: 'multiply',- grain: 0.22,- textureDensity: 0.22,- paperTextureScale: 0.9,- paperTextureContrast: 14,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- useGpu: true,- },- },- {- id: 'tapered-painterly-oval',- category: 'brush',- name: 'Hard Round Pressure Painter',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Pro Digital Painting Workhorse — Crisp Tapered Oval with Smooth Pressure Opacity & Perceptual Glazing',- icon: 'paintbrush',- tipGenerator: generatePainterlyOvalTip,- settings: {- size: 28,- minSizeFactor: 0.28,- flow: 0.86,- opacity: 1.0,- hardness: 0.86,- antiAlias: 3,- thickness: 0.78,- customTipAngle: -25,- customTipAngleDynamics: 'none',- flipH: 'none',- flipV: 'none',- spacing: 0.05,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- pressureCurve: [- [0, 0],- [0.26, 0.22],- [0.68, 0.78],- [1, 1],- ],- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.76,- densityOfPaint: 0.9,- colorStretch: 0.48,- opacitySensor: { usePressure: true, pressureMin: 0.12 },- useGpu: true,- },- },- {- id: 'silky-hair-locks',- category: 'brush',- name: 'Silky Hair & Fur Locks',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Tapered Multi-Strand Sable Hair Brush — Glossy Layered Bangs, Flowing Locks & Soft Fur',- icon: 'paintbrush',- tipGenerator: generateHairLocksTip,- settings: {- size: 46,- minSizeFactor: 0.2,- flow: 0.9,- opacity: 1.0,- hardness: 0.84,- antiAlias: 2,- thickness: 0.88,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.05,- adjustDensityByGap: false,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'running_color',- amountOfPaint: 0.82,- densityOfPaint: 0.92,- colorStretch: 0.64,- opacitySensor: { usePressure: true, pressureMin: 0.2 },- taper: {- useIn: true,- inLength: 20,- inRatio: 0.2,- useOut: true,- outLength: 32,- outRatio: 0.28,- inOutType: 2,- startingSharpness: 0.76,- endingSharpness: 0.86,- affectSize: true,- minSizeRatio: 0.12,- },- useGpu: true,- },- },- {- id: 'dry-hair-sheen',- category: 'brush',- name: 'Dry-Brush Hair Sheen',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Textured Flat Highlight Bristle + Mineral Dual Brush — Luminous Crown Hair Sheen & Silk Shimmer',- icon: 'paintbrush',- tipGenerator: generateDryHairSheenTip,- dualTipGenerator: generateMineralGrainDualTip,- settings: {- size: 54,- minSizeFactor: 0.36,- flow: 0.88,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- thickness: 0.78,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.058,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.88,- densityOfPaint: 0.94,- colorStretch: 0.36,- opacitySensor: { usePressure: true, pressureMin: 0.14 },- dualBrush: true,- dualBrushCompositeMode: 'multiply',- dualLinkSize: true,- dualScale: 1.1,- dualSpacing: 0.14,- dualDensity: 0.92,- dualAngleDynamics: 'random',- dualFlipH: 'random',- dualFlipV: 'random',- dualBrushConfig: {- enabled: true,- compositeMode: 'multiply',- linkSizeWithMain: true,- sizeRatio: 1.1,- spacing: 0.14,- density: 0.92,- angleDynamics: 'random',- flipH: 'random',- flipV: 'random',- },- useGpu: true,- },- },- {- id: 'rough-concept-bristle',- category: 'brush',- name: 'Expressive Concept Bristle',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: '4-Tip Fractured Hog-Bristle + Dual Tooth — Sweeping Fantasy Cloaks, Moody Skies & Bold Concept Strokes',- icon: 'paintbrush',- subTipGenerators: [- () => generateConceptBristleSubTip(0),- () => generateConceptBristleSubTip(1),- () => generateConceptBristleSubTip(2),- () => generateConceptBristleSubTip(3),- ],- dualTipGenerator: generateMineralGrainDualTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 48,- minSizeFactor: 0.32,- flow: 0.92,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- thickness: 0.64,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'random',- spacing: 0.065,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'running_color',- amountOfPaint: 0.84,- densityOfPaint: 0.94,- colorStretch: 0.68,- surfaceTextureId: 'linen-canvas',- paperTextureMode: 'compare',- grain: 0.34,- textureDensity: 0.34,- paperTextureScale: 0.9,- paperTextureContrast: 22,- opacitySensor: { usePressure: true, pressureMin: 0.2 },- dualBrush: true,- dualBrushCompositeMode: 'multiply',- dualLinkSize: true,- dualScale: 1.12,- dualSpacing: 0.14,- dualDensity: 0.94,- dualAngleDynamics: 'random',- dualFlipH: 'random',- dualFlipV: 'random',- dualBrushConfig: {- enabled: true,- compositeMode: 'multiply',- linkSizeWithMain: true,- sizeRatio: 1.12,- spacing: 0.14,- density: 0.94,- angleDynamics: 'random',- flipH: 'random',- flipV: 'random',- },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.06,- flowJitter: 0.08,- colorJitterEnabled: true,- brightnessJitter: 0.025,- temperatureJitter: 0.025,- },- useGpu: true,- },- },- {- id: 'wedge-chisel-gouache',- category: 'brush',- name: 'Wedge & Chisel Painter',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Asymmetric Diagonal Bevel Wedge — Razor Architectural Leading Corner & Soft Feathered Gouache Heel',- icon: 'paintbrush',- tipGenerator: generateWedgeChiselTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('fine-cotton'),- settings: {- size: 34,- minSizeFactor: 0.32,- flow: 0.9,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- thickness: 0.62,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.05,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.18,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.82,- densityOfPaint: 0.92,- colorStretch: 0.46,- surfaceTextureId: 'fine-cotton',- paperTextureMode: 'multiply',- grain: 0.24,- textureDensity: 0.24,- paperTextureScale: 0.88,- paperTextureContrast: 14,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- useGpu: true,- },- },- {- id: 'translucent-watercolor-wash',- category: 'brush',- name: 'Soft Watercolor Wash',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Organic Translucent Mop Glaze — Wet-Edge Pigment Pooling & Delicate Cold-Press Bloom',- icon: 'paintbrush',- tipGenerator: generateWatercolorWashTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),- settings: {- size: 52,- minSizeFactor: 0.34,- flow: 0.46,- opacity: 0.82,- hardness: 0.56,- antiAlias: 3,- thickness: 0.9,- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- spacing: 0.075,- adjustDensityByGap: true,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.25,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.56,- densityOfPaint: 0.68,- colorStretch: 0.62,- wetEdge: 0.42,- wetEdgeRadius: 2.6,- wetEdgeAlphaPower: 0.22,- wetEdgeValuePower: 0.16,- surfaceTextureId: 'cold-press-watercolor',- paperTextureMode: 'multiply',- grain: 0.36,- textureDensity: 0.36,- paperTextureScale: 0.92,- paperTextureContrast: 18,- opacitySensor: { usePressure: true, pressureMin: 0.12 },- useGpu: true,- },- },- {- id: 'pastel-blush-airbrush',- category: 'brush',- name: 'Silky Blush & Skin Airbrush',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Perceptual Subsurface Skin Airbrush — Luminous Cheek Blush, Nose Warmth & Silky Atmospheric Halos',- icon: 'paintbrush',- settings: {- size: 54,- minSizeFactor: 0.5,- flow: 0.18,- opacity: 0.96,- hardness: 0.0,- antiAlias: 3,- spacing: 0.055,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- adjustDensityByGap: true,- pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.34,- densityOfPaint: 0.52,- colorStretch: 0.45,- opacitySensor: { usePressure: true, pressureMin: 0.04 },- useGpu: true,- },- },- {- id: 'metallic-specular-glint',- category: 'brush',- name: 'Metallic & Gold Impasto',- badge: 'Brush',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Crisp Hammered-Facet Lozenge — Gold Coins, Chrome Chokers, Wet Lip Highlights & Eye Catchlights',- icon: 'paintbrush',- tipGenerator: generateMetallicGlintTip,- settings: {- size: 16,- minSizeFactor: 0.18,- flow: 0.98,- opacity: 1.0,- hardness: 0.94,- antiAlias: 2,- thickness: 0.56,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.04,- adjustDensityByGap: false,- stabilization: 10,- sharpCorners: true,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.94,- densityOfPaint: 0.98,- colorStretch: 0.24,- opacitySensor: { usePressure: true, pressureMin: 0.28 },- useGpu: true,- },- },-];--// =============================================================================-// BLEND SECTION PRO ADDITIONS (+4 — STRICT PURE-SMEAR INVARIANTS)-// =============================================================================--export const PRO_BLEND_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'blend-charcoal-stump',- category: 'blend',- name: 'Charcoal Blending Stump',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Rolled-Paper Tortillon Stump — Rubs Charcoal & Graphite into Velvety Shadows While Keeping Paper Tooth',- icon: 'droplets',- tipGenerator: generateBlendTortillonTip,- paperTextureGenerator: generateCharcoalPaperTexture,- settings: {- size: 38,- minSizeFactor: 0.34,- flow: 0.84,- opacity: 1.0,- hardness: 0.42,- antiAlias: 2,- thickness: 0.74,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.065,- adjustDensityByGap: false,- stabilization: 7,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.45,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.84,- colorStretch: 0.74,- useBlur: true,- blurStrength: 0.26,- grain: 0.48,- textureDensity: 0.48,- paperTextureMode: 'compare',- paperTextureScale: 0.95,- paperTextureContrast: 24,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- useGpu: true,- },- },- {- id: 'blend-gouache-softener',- category: 'blend',- name: 'Painterly Gouache Melter',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Feathered Flat Gouache Blender — Softens Hard Folds & Hair-to-Skin Transitions Without Plastic Blur',- icon: 'droplets',- tipGenerator: generateBlendGouachePadTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),- settings: {- size: 42,- minSizeFactor: 0.34,- flow: 0.84,- opacity: 1.0,- hardness: 0.48,- antiAlias: 3,- thickness: 0.64,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.06,- adjustDensityByGap: false,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.86,- colorStretch: 0.8,- useBlur: true,- blurStrength: 0.2,- surfaceTextureId: 'gesso-board',- paperTextureMode: 'multiply',- grain: 0.16,- textureDensity: 0.16,- paperTextureScale: 0.9,- paperTextureContrast: 10,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- useGpu: true,- },- },- {- id: 'blend-smoke-wisps',- category: 'blend',- name: 'Atmospheric Mist & Smoke Smudge',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Turbulent Cloud-Wisp Smudger — Pulls Paint into Curling Dark Smoke, Magic Vapor & Drifting Fog',- icon: 'droplets',- tipGenerator: generateBlendSmokeWispTip,- settings: {- size: 62,- minSizeFactor: 0.38,- flow: 0.82,- opacity: 1.0,- hardness: 0.3,- antiAlias: 3,- thickness: 0.86,- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.6,- flipH: 'random',- flipV: 'random',- spacing: 0.075,- adjustDensityByGap: false,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.82,- colorStretch: 0.9,- useBlur: true,- blurStrength: 0.3,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.14 },- useGpu: true,- },- },- {- id: 'blend-palette-knife-smear',- category: 'blend',- name: 'Palette Knife Smudge',- badge: 'Blend',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: 'Sharp-Edged Knife Scraper Blender — Pulls Crisp Architectural Paint Planes, Water & Cloth Streaks',- icon: 'droplets',- tipGenerator: generateBlendKnifeSmearTip,- settings: {- size: 40,- minSizeFactor: 0.32,- flow: 0.94,- opacity: 1.0,- hardness: 0.84,- antiAlias: 2,- thickness: 0.36,- customTipAngleDynamics: 'direction',- flipH: 'none',- flipV: 'none',- spacing: 0.04,- adjustDensityByGap: false,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'smear',- amountOfPaint: 0.0,- densityOfPaint: 0.96,- colorStretch: 0.94,- useBlur: false,- grain: 0,- textureDensity: 0,- opacitySensor: { usePressure: true, pressureMin: 0.22 },- useGpu: true,- },- },-];--// =============================================================================-// NATURAL PAINT SECTION PRO ADDITIONS (+4 — PHYSICAL BRISTLE-RIBBON & IMPASTO)-// =============================================================================--export const PRO_NATURAL_PAINT_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'wide-hog-flat-oil',- category: 'natural-paint',- name: 'Wide Hog-Bristle Flat',- badge: 'Oil',- badgeBg: 'bg-rose-500/15',- badgeText: 'text-rose-300',- badgeBorder: 'border-rose-500/30',- desc: 'Broad Chiseled Alla-Prima Hog Flat — Bold Architectural 3D Oil Planes with Crisp Paint Ridges',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('flat'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),- settings: {- size: 56,- minSizeFactor: 0.36,- flow: 0.95,- opacity: 1.0,- hardness: 0.92,- antiAlias: 2,- spacing: 0.048,- stabilization: 10,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'flat',- count: 38,- clumping: 0.44,- stiffness: 0.72,- length: 0.95,- splay: 0.3,- irregularity: 0.36,- edgeRidge: 0.42,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'impasto_mix',- amountOfPaint: 0.84,- densityOfPaint: 0.96,- colorStretch: 0.72,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.92,- paintLoad: 0.84,- depletionRate: 0.24,- wetness: 0.62,- viscosity: 0.64,- autoClean: true,- chargePerPressure: 0.54,- dryBrush: 0.38,- },- impasto: {- enabled: true,- depth: 0.74,- bristleRelief: 0.8,- gloss: 0.44,- reliefContrast: 0.66,- lightAzimuth: 225,- lightElevation: 34,- },- surfaceTextureId: 'linen-canvas',- grainMappingMode: 'canvas-locked',- grain: 0.42,- textureDensity: 0.42,- paperTextureMode: 'compare',- paperTextureScale: 0.86,- paperTextureContrast: 24,- useGpu: true,- },- },- {- id: 'splayed-fan-foliage',- category: 'natural-paint',- name: 'Splayed Bristle Fan',- badge: 'Fan',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Wide Splayed Physical Fan Brush — Organic Foliage, Pine Needles, Grass & Expressive Hair Sweeps',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('fan'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),- settings: {- size: 64,- minSizeFactor: 0.4,- flow: 0.92,- opacity: 1.0,- hardness: 0.9,- antiAlias: 2,- spacing: 0.05,- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.35,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'fan',- count: 36,- clumping: 0.64,- stiffness: 0.78,- length: 1.25,- splay: 0.56,- irregularity: 0.58,- edgeRidge: 0.16,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.82,- densityOfPaint: 0.94,- colorStretch: 0.64,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.88,- paintLoad: 0.82,- depletionRate: 0.3,- wetness: 0.46,- viscosity: 0.58,- autoClean: true,- chargePerPressure: 0.48,- dryBrush: 0.48,- },- impasto: {- enabled: true,- depth: 0.48,- bristleRelief: 0.78,- gloss: 0.28,- reliefContrast: 0.56,- lightAzimuth: 225,- lightElevation: 36,- },- surfaceTextureId: 'coarse-burlap',- grainMappingMode: 'canvas-locked',- grain: 0.46,- textureDensity: 0.46,- paperTextureMode: 'compare',- paperTextureScale: 0.85,- paperTextureContrast: 26,- useGpu: true,- },- },- {- id: 'sumi-ink-wash-natural',- category: 'natural-paint',- name: 'Sumi Ink Wash',- badge: 'Ink',- badgeBg: 'bg-cyan-500/15',- badgeText: 'text-cyan-300',- badgeBorder: 'border-cyan-500/30',- desc: 'Fluid East Asian Sumi Bristle — Rich Wet-Edge Paper Bloom with Dry Flying-White Exhaustion',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('round'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),- settings: {- size: 40,- minSizeFactor: 0.18,- flow: 0.82,- opacity: 0.9,- hardness: 0.76,- antiAlias: 2,- spacing: 0.05,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.4,- smoothing: true,- renderMode: 'bristle-ribbon',- bristle: {- profile: 'round',- count: 26,- clumping: 0.32,- stiffness: 0.42,- length: 1.4,- splay: 0.48,- irregularity: 0.36,- edgeRidge: 0.08,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.78,- densityOfPaint: 0.86,- colorStretch: 0.68,- wetEdge: 0.48,- wetEdgeRadius: 2.5,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.9,- paintLoad: 0.78,- depletionRate: 0.34,- wetness: 0.72,- viscosity: 0.18,- autoClean: true,- chargePerPressure: 0.62,- dryBrush: 0.42,- granulation: 0.58,- },- impasto: {- enabled: false,- depth: 0.0,- bristleRelief: 0.0,- gloss: 0.0,- reliefContrast: 0.0,- lightAzimuth: 225,- lightElevation: 42,- },- surfaceTextureId: 'cold-press-watercolor',- grainMappingMode: 'canvas-locked',- grain: 0.5,- textureDensity: 0.5,- paperTextureMode: 'multiply',- paperTextureScale: 0.92,- paperTextureContrast: 24,- useGpu: true,- },- },- {- id: 'matte-casein-tempera',- category: 'natural-paint',- name: 'Matte Casein & Tempera',- badge: 'Matte',- badgeBg: 'bg-violet-500/15',- badgeText: 'text-violet-300',- badgeBorder: 'border-violet-500/30',- desc: 'Velvety Zero-Gloss Casein Illustration Paint — Opaque Creamy Coverage & Dry Gesso Scumble',- icon: 'palette',- tipGenerator: () => generateNaturalTipByProfile('filbert'),- paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),- settings: {- size: 42,- minSizeFactor: 0.3,- flow: 0.94,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- spacing: 0.05,- stabilization: 9,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.1,- smoothing: true,- renderMode: 'bristle-hybrid',- bristle: {- profile: 'filbert',- count: 30,- clumping: 0.28,- stiffness: 0.62,- length: 0.95,- splay: 0.28,- irregularity: 0.32,- edgeRidge: 0.14,- },- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.86,- densityOfPaint: 0.96,- colorStretch: 0.52,- naturalPaint: {- enabled: true,- spatialMixing: true,- pigmentMixingStrength: 0.92,- paintLoad: 0.86,- depletionRate: 0.22,- wetness: 0.48,- viscosity: 0.52,- autoClean: true,- chargePerPressure: 0.46,- dryBrush: 0.36,- },- impasto: {- enabled: true,- depth: 0.24,- bristleRelief: 0.36,- gloss: 0.02,- reliefContrast: 0.34,- lightAzimuth: 225,- lightElevation: 42,- },- surfaceTextureId: 'gesso-board',- grainMappingMode: 'canvas-locked',- grain: 0.36,- textureDensity: 0.36,- paperTextureMode: 'compare',- paperTextureScale: 0.9,- paperTextureContrast: 20,- useGpu: true,- },- },-];--// =============================================================================-// TEXTURE & FX SECTION (NEW BUILT-IN SECTION — 10 WORLD-CLASS PRO BRUSHES)-// =============================================================================--export const PRO_TEXTURE_FX_BRUSHES: BuiltinBrushDefinition[] = [- {- id: 'painterly-foliage-leaves',- category: 'texture-fx',- name: 'Painterly Canopy Leaves',- badge: 'Foliage',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: '4-Tip Hand-Painted Botanical Leaves — Scattered Forest Canopies with Subtle Sunlight Color Jitter',- icon: 'sparkles',- subTipGenerators: [- () => generatePainterlyLeafSubTip(0),- () => generatePainterlyLeafSubTip(1),- () => generatePainterlyLeafSubTip(2),- () => generatePainterlyLeafSubTip(3),- ],- settings: {- size: 64,- minSizeFactor: 0.35,- flow: 0.94,- opacity: 1.0,- hardness: 0.86,- antiAlias: 2,- spacing: 0.34,- stabilization: 4,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.55,- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.45 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.38,- angleJitter: 0.35,- roundnessJitter: 0.18,- scatter: 0.72,- scatterBothAxes: true,- count: 2,- flowJitter: 0.18,- colorJitterEnabled: true,- hueJitter: 0.05,- saturationJitter: 0.1,- brightnessJitter: 0.14,- temperatureJitter: 0.08,- foregroundBackgroundJitter: 0.12,- },- useGpu: true,- },- },- {- id: 'bokeh-foreground-leaves',- category: 'texture-fx',- name: 'Bokeh Soft Leaves',- badge: 'Foliage',- badgeBg: 'bg-emerald-500/15',- badgeText: 'text-emerald-300',- badgeBorder: 'border-emerald-500/30',- desc: 'Out-of-Focus Depth-of-Field Leaves — Cinematic Foreground Framing & Drifting Wind-Blown Foliage',- icon: 'sparkles',- subTipGenerators: [- () => generateBokehLeafSubTip(0),- () => generateBokehLeafSubTip(1),- () => generateBokehLeafSubTip(2),- ],- settings: {- size: 92,- minSizeFactor: 0.42,- flow: 0.78,- opacity: 0.96,- hardness: 0.25,- antiAlias: 3,- spacing: 0.52,- stabilization: 4,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.35 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.45,- angleJitter: 0.6,- roundnessJitter: 0.14,- scatter: 0.95,- scatterBothAxes: true,- count: 1,- flowJitter: 0.24,- colorJitterEnabled: true,- hueJitter: 0.03,- brightnessJitter: 0.1,- temperatureJitter: 0.05,- },- useGpu: true,- },- },- {- id: 'skin-freckles-pores',- category: 'texture-fx',- name: 'Skin Freckles & Pores',- badge: 'Portrait',- badgeBg: 'bg-rose-500/15',- badgeText: 'text-rose-300',- badgeBorder: 'border-rose-500/30',- desc: '4-Tip Organic Micro-Constellations — Realistic Portrait Freckles, Nose-Bridge Speckle & Skin Pores',- icon: 'sparkles',- subTipGenerators: [- () => generateSkinFrecklesSubTip(0),- () => generateSkinFrecklesSubTip(1),- () => generateSkinFrecklesSubTip(2),- () => generateSkinFrecklesSubTip(3),- ],- settings: {- size: 64,- minSizeFactor: 0.55,- flow: 0.72,- opacity: 0.9,- hardness: 0.68,- antiAlias: 2,- spacing: 0.38,- stabilization: 3,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.22 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.34,- angleJitter: 1.0,- roundnessJitter: 0.16,- scatter: 0.52,- scatterBothAxes: true,- count: 1,- flowJitter: 0.28,- colorJitterEnabled: true,- brightnessJitter: 0.1,- temperatureJitter: 0.04,- },- useGpu: true,- },- },- {- id: 'ethereal-smoke-mist',- category: 'texture-fx',- name: 'Dark Smoke & Vapor',- badge: 'FX',- badgeBg: 'bg-violet-500/15',- badgeText: 'text-violet-300',- badgeBorder: 'border-violet-500/30',- desc: '4-Tip Domain-Warped Turbulent Smoke + Dual Erosion Mask — Necrotic Tendrils, Fog & Magic Mist',- icon: 'sparkles',- subTipGenerators: [- () => generateSmokeTendrilSubTip(0),- () => generateSmokeTendrilSubTip(1),- () => generateSmokeTendrilSubTip(2),- () => generateSmokeTendrilSubTip(3),- ],- dualTipGenerator: generateSmokeDualMaskTip,- settings: {- size: 110,- minSizeFactor: 0.38,- flow: 0.24,- opacity: 0.92,- hardness: 0.2,- antiAlias: 3,- spacing: 0.16,- stabilization: 5,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.72,- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.08 },- dualBrush: true,- dualBrushCompositeMode: 'multiply',- dualLinkSize: true,- dualScale: 1.05,- dualSpacing: 0.18,- dualDensity: 0.9,- dualAngleDynamics: 'random',- dualFlipH: 'random',- dualFlipV: 'random',- dualBrushConfig: {- enabled: true,- compositeMode: 'multiply',- linkSizeWithMain: true,- sizeRatio: 1.05,- spacing: 0.18,- density: 0.9,- angleDynamics: 'random',- flipH: 'random',- flipV: 'random',- },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.28,- angleJitter: 0.55,- roundnessJitter: 0.2,- scatter: 0.24,- scatterBothAxes: true,- count: 1,- flowJitter: 0.22,- },- useGpu: true,- },- },- {- id: 'craggy-rock-bone',- category: 'texture-fx',- name: 'Craggy Rock & Weathered Bone',- badge: 'Texture',- badgeBg: 'bg-amber-500/15',- badgeText: 'text-amber-300',- badgeBorder: 'border-amber-500/30',- desc: '4-Tip Fractured Mineral Shards + Dual Tooth — Jagged Mountains, Skull Pauldrons & Ancient Metal',- icon: 'sparkles',- subTipGenerators: [- () => generateCraggyRockSubTip(0),- () => generateCraggyRockSubTip(1),- () => generateCraggyRockSubTip(2),- () => generateCraggyRockSubTip(3),- ],- dualTipGenerator: generateMineralGrainDualTip,- paperTextureGenerator: generatePainterlyChalkGrainTexture,- settings: {- size: 76,- minSizeFactor: 0.34,- flow: 0.88,- opacity: 1.0,- hardness: 0.84,- antiAlias: 2,- spacing: 0.22,- stabilization: 5,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.2,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- customTipRotationRandomScale: 0.85,- flipH: 'random',- flipV: 'random',- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.84,- densityOfPaint: 0.92,- colorStretch: 0.34,- surfaceTextureId: 'stipple-grain',- paperTextureMode: 'compare',- grain: 0.48,- textureDensity: 0.48,- paperTextureScale: 0.95,- paperTextureContrast: 30,- opacitySensor: { usePressure: true, pressureMin: 0.2 },- dualBrush: true,- dualBrushCompositeMode: 'multiply',- dualLinkSize: true,- dualScale: 1.15,- dualSpacing: 0.16,- dualDensity: 0.92,- dualAngleDynamics: 'random',- dualFlipH: 'random',- dualFlipV: 'random',- dualBrushConfig: {- enabled: true,- compositeMode: 'multiply',- linkSizeWithMain: true,- sizeRatio: 1.15,- spacing: 0.16,- density: 0.92,- angleDynamics: 'random',- flipH: 'random',- flipV: 'random',- },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.26,- angleJitter: 0.85,- roundnessJitter: 0.18,- scatter: 0.14,- scatterBothAxes: true,- flowJitter: 0.16,- colorJitterEnabled: true,- brightnessJitter: 0.06,- temperatureJitter: 0.04,- },- useGpu: true,- },- },- {- id: 'ember-ash-spatter',- category: 'texture-fx',- name: 'Ash, Embers & Ink Spatter',- badge: 'FX',- badgeBg: 'bg-orange-500/15',- badgeText: 'text-orange-300',- badgeBorder: 'border-orange-500/30',- desc: '4-Tip Organic Splatter Constellations — Swirling Fire Embers, Volcanic Ash, Snow & Ink Spray',- icon: 'sparkles',- subTipGenerators: [- () => generateEmberSpatterSubTip(0),- () => generateEmberSpatterSubTip(1),- () => generateEmberSpatterSubTip(2),- () => generateEmberSpatterSubTip(3),- ],- settings: {- size: 76,- minSizeFactor: 0.4,- flow: 0.86,- opacity: 1.0,- hardness: 0.88,- antiAlias: 2,- spacing: 0.42,- stabilization: 3,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.3 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.48,- angleJitter: 1.0,- roundnessJitter: 0.14,- scatter: 0.82,- scatterBothAxes: true,- count: 2,- flowJitter: 0.28,- colorJitterEnabled: true,- hueJitter: 0.03,- brightnessJitter: 0.14,- temperatureJitter: 0.06,- },- useGpu: true,- },- },- {- id: 'painterly-clouds',- category: 'texture-fx',- name: 'Painterly Cumulus Clouds',- badge: 'Sky',- badgeBg: 'bg-sky-500/15',- badgeText: 'text-sky-300',- badgeBorder: 'border-sky-500/30',- desc: '4-Tip Sculpted Sky Puffs — Crisp Sunlit Upper Billows & Soft Atmospheric Bases for Epic Skies',- icon: 'sparkles',- subTipGenerators: [- () => generatePainterlyCloudSubTip(0),- () => generatePainterlyCloudSubTip(1),- () => generatePainterlyCloudSubTip(2),- () => generatePainterlyCloudSubTip(3),- ],- settings: {- size: 98,- minSizeFactor: 0.42,- flow: 0.56,- opacity: 0.96,- hardness: 0.44,- antiAlias: 3,- spacing: 0.19,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- customTipRotationRandomScale: 0.22,- flipH: 'random',- flipV: 'none',- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.66,- densityOfPaint: 0.8,- colorStretch: 0.54,- opacitySensor: { usePressure: true, pressureMin: 0.16 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.24,- angleJitter: 0.12,- roundnessJitter: 0.12,- scatter: 0.24,- scatterBothAxes: true,- count: 1,- flowJitter: 0.16,- },- useGpu: true,- },- },- {- id: 'woven-brocade-fabric',- category: 'texture-fx',- name: 'Woven Cloth & Brocade Grain',- badge: 'Texture',- badgeBg: 'bg-violet-500/15',- badgeText: 'text-violet-300',- badgeBorder: 'border-violet-500/30',- desc: 'Cross-Woven Textile & Twill Pad — Embroidered Sleeves, Medieval Cloaks & Tapestry Weave Highlights',- icon: 'sparkles',- tipGenerator: generateWovenFabricTip,- paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),- settings: {- size: 48,- minSizeFactor: 0.38,- flow: 0.78,- opacity: 1.0,- hardness: 0.68,- antiAlias: 2,- spacing: 0.1,- stabilization: 6,- sharpCorners: false,- usePressure: true,- useTilt: true,- tiltScale: 1.15,- smoothing: true,- customTipAngleDynamics: 'direction-random',- customTipRotationRandomScale: 0.15,- colorMixing: true,- perceptualMixing: true,- mixingMode: 'blend',- amountOfPaint: 0.74,- densityOfPaint: 0.86,- colorStretch: 0.4,- surfaceTextureId: 'coarse-burlap',- paperTextureMode: 'compare',- grain: 0.64,- textureDensity: 0.64,- paperTextureScale: 0.62,- paperTextureContrast: 32,- opacitySensor: { usePressure: true, pressureMin: 0.18 },- useGpu: true,- },- },- {- id: 'luminous-rim-glow',- category: 'texture-fx',- name: 'Luminous Magic & Rim Glow',- badge: 'Glow',- badgeBg: 'bg-fuchsia-500/15',- badgeText: 'text-fuchsia-300',- badgeBorder: 'border-fuchsia-500/30',- desc: 'Optical Add-Glow Point-Spread Bloom — Glowing Magic Lanterns, Backlit Rim Light & Sunbeams',- icon: 'sparkles',- tipGenerator: generateLuminousBloomTip,- settings: {- size: 72,- minSizeFactor: 0.45,- flow: 0.22,- opacity: 0.85,- hardness: 0.0,- antiAlias: 3,- spacing: 0.06,- adjustDensityByGap: true,- brushCombineMode: 'add-glow',- stabilization: 8,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,- opacitySensor: { usePressure: true, pressureMin: 0.05 },- useGpu: true,- },- },- {- id: 'stipple-halftone-grain',- category: 'texture-fx',- name: 'Fine Film & Stipple Dust',- badge: 'Texture',- badgeBg: 'bg-violet-500/15',- badgeText: 'text-violet-300',- badgeBorder: 'border-violet-500/30',- desc: '3-Tip Stochastic Micro-Stipple Dust — Tactile Portrait Film Grain, Dust Motes & Subtle Finish',- icon: 'sparkles',- subTipGenerators: [- () => generateFineStippleSubTip(0),- () => generateFineStippleSubTip(1),- () => generateFineStippleSubTip(2),- ],- settings: {- size: 72,- minSizeFactor: 0.45,- flow: 0.68,- opacity: 0.94,- hardness: 0.55,- antiAlias: 2,- spacing: 0.22,- stabilization: 4,- sharpCorners: false,- usePressure: true,- useTilt: false,- smoothing: true,- subTipOrder: 'random-no-repeat',- customTipAngleDynamics: 'random',- flipH: 'random',- flipV: 'random',- opacitySensor: { usePressure: true, pressureMin: 0.12 },- dynamics: {- ...DEFAULT_BRUSH_DYNAMICS,- sizeJitter: 0.24,- angleJitter: 1.0,- scatter: 0.36,- scatterBothAxes: true,- count: 1,- flowJitter: 0.24,- },- useGpu: true,- },- },-];diff --git a/src/utils/proProceduralBrushTips.ts b/src/utils/proProceduralBrushTips.tsdeleted file mode 100644index b79fe59..0000000--- a/src/utils/proProceduralBrushTips.ts+++ /dev/null@@ -1,1542 +0,0 @@-/**- * proProceduralBrushTips.ts- * High-resolution (256x256 & 64x512 ribbon) procedural brush tips for InkStudio's- * expanded professional artist brush collection:- * - Portrait & anime-realism painting (Hard Square, Painterly Gouache Flat, Hair Locks,- * Dry Hair Sheen, Skin Freckles & Pores, Soft Tapered Liner, Hair Strands)- * - Fantasy & concept illustration (Silk Embroidery Multi-Line Ribbon, Canopy Leaves,- * Bokeh Soft Leaves, Expressive Concept Bristle, Wedge & Chisel, Metallic Impasto)- * - Dark fantasy & atmospheric FX (Turbulent Dark Smoke & Vapor, Craggy Rock & Bone,- * Ash/Ember Spatter, Painterly Cumulus Clouds, Woven Brocade, Optical Luminous Bloom,- * Fine Film Stipple Dust)- * - Traditional sketching & blending (Vine Charcoal, Flat Charcoal Block, Conté Crayon,- * Animation Sketch Pencil, Sumi Brush Pen, Tortillon Stump, Gouache Melter, Smoke Smudge,- * Palette Knife Smudge)- */--import {- HI_TIP_SIZE,- buildCachedPng,- buildCachedRectPng,- clamp01,- createPrng,- makeCellularDomeField,- makePeriodicGrid,- sampleFieldBilinear,- samplePeriodic,- smoothstep,- writeAlphaPixel,-} from './proceduralBrushTips';--// =============================================================================-// 1. PEN SECTION PRO TIPS-// =============================================================================--/**- * Soft Tapered Liner (256x256):- * Silky painted-ink sable nib — dense opaque interior transitioning smoothly- * with ultra-subtle organic micro-tooth on the outer rim for wispy hair strands,- * glasses frames, and painterly anime-realism lineart.- */-export function generateSoftTaperedLinerTip(): string {- return buildCachedPng('pro:soft-tapered-liner-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x21a01);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.42;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const nx = dx / rx;- // Subtle teardrop sable point toward +X- const taper = 1.0 - Math.max(0, nx) * 0.14;- const ny = dy / (ry * taper);- const r = Math.hypot(nx, ny);- if (r >= 1.0) continue;-- let alpha = 1.0 - smoothstep(0.74, 0.995, r);- if (r > 0.68) {- const rim = smoothstep(0.68, 0.98, r);- const tooth = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);- alpha *= 1.0 - rim * 0.14 * (1.0 - tooth);- }- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Sumi Brush Pen / Fude Nib (256x256):- * Pointed wolf-hair sumi-e ink brush oriented along +X: razor-pointed leading tip,- * full juicy belly, and subtly split dry-ink heel bristles for expressive calligraphy & comic ink.- */-export function generateSumiBrushTip(): string {- return buildCachedPng('pro:sumi-fude-brush-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x21b02);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.39;-- // 18 bristle striations concentrating dry splits near the heel (nx < -0.15)- const numStrands = 18;- const sY = new Float32Array(numStrands);- const sW = new Float32Array(numStrands);- const sReach = new Float32Array(numStrands);- for (let i = 0; i < numStrands; i++) {- const u = ((i + 0.5) / numStrands) * 2 - 1;- sY[i] = u * 0.92 + (rand() - 0.5) * 0.06;- sW[i] = 0.065 + rand() * 0.06;- sReach[i] = 0.78 + rand() * 0.24;- }-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const nyBase = dy / ry;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const nx = dx / rx;- if (nx < -1.04 || nx > 1.02) continue;-- // Teardrop sumi brush profile: pointed tip at +X, fuller rounded belly at x = -0.25- const profileHalfH =- nx >= 0- ? Math.pow(Math.max(0, 1.0 - nx), 0.72) * (0.96 + 0.14 * (1.0 - nx))- : Math.sqrt(Math.max(0, 1.0 - Math.pow((nx + 0.15) / 0.92, 2))) * 1.04;- if (profileHalfH <= 0.01) continue;-- const ny = nyBase / profileHalfH;- const absNy = Math.abs(ny);- if (absNy >= 1.08) continue;-- const warp = (samplePeriodic(nMed, 32, x * 0.12, y * 0.22) - 0.5) * 0.09;- const env = 1.0 - smoothstep(0.84 + warp, 1.01 + warp, absNy);-- let alpha = env;- // Split dry bristles softly at the rear heel (nx < -0.2)- if (nx < -0.18) {- const heelFactor = smoothstep(-0.18, -0.88, nx);- let strand = 0;- let reach = 0.85;- for (let i = 0; i < numStrands; i++) {- const d = Math.abs(nyBase - sY[i]) / sW[i];- if (d < 1.0) {- const v = 1.0 - d * d;- if (v > strand) {- strand = v;- reach = sReach[i];- }- }- }- const heelCut = 1.0 - smoothstep(reach * 0.75, reach * 1.02, -nx);- const fine = samplePeriodic(nFine, 64, x * 0.22, y * 0.54);- const splitMask = smoothstep(0.14 + heelFactor * 0.26, 0.56, strand * 0.75 + fine * 0.25);- alpha = env * (1.0 - heelFactor * 0.85 + heelFactor * 0.85 * splitMask * heelCut);- }-- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Silk Thread Multi-Line Ribbon Tip (64x512 seamless vertical strip x 3 variants):- * Inspired by flowing curved parallel gold/silk veil embroidery lines.- * Maps Y strictly along the RibbonBrushEngine path and X across width, with exact- * periodic endpoint matching at v=0 and v=1 for seamless continuous embroidery ribbons.- */-export function generateSilkThreadRibbonTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 3) + 3) % 3;- return buildCachedRectPng(`pro:silk-thread-ribbon-v${vIdx}`, 64, 512, (data, width, height) => {- const rand = createPrng(0x21c03 + vIdx * 0x51a7);- const nMicro = makePeriodicGrid(64, rand);-- // 5 graceful parallel silk filaments across width (1 prominent hero thread + 4 delicate companion threads)- const threads = [- { cx: 0.12, halfW: 0.030, amp: 0.018, freq: 1, phase: 0.4 + vIdx * 1.1, strength: 0.80 },- { cx: 0.29, halfW: 0.042, amp: 0.022, freq: 2, phase: 1.7 + vIdx * 0.9, strength: 0.96 },- { cx: 0.49, halfW: 0.052, amp: 0.016, freq: 1, phase: 2.9 + vIdx * 1.4, strength: 1.0 },- { cx: 0.70, halfW: 0.036, amp: 0.020, freq: 2, phase: 0.9 + vIdx * 1.8, strength: 0.90 },- { cx: 0.88, halfW: 0.028, amp: 0.016, freq: 1, phase: 4.1 + vIdx * 0.7, strength: 0.76 },- ];-- for (let y = 0; y < height; y++) {- const v = y / height;- const tau = v * Math.PI * 2;- const seamEnv = Math.sin(v * Math.PI); // 0 at v=0 & v=1 -> exact alignment across tile boundaries- const row = y * width * 4;-- // Subtle periodic silk-sheen shimmer along thread length- const shimmer = 0.84 + 0.16 * Math.sin(tau * 2 + vIdx * 1.3);-- for (let x = 0; x < width; x++) {- const u = (x + 0.5) / width;- let accum = 0;- for (let t = 0; t < threads.length; t++) {- const th = threads[t];- const center = th.cx + Math.sin(tau * th.freq + th.phase) * th.amp * seamEnv;- const dist = Math.abs(u - center);- const localW = th.halfW * (0.86 + 0.24 * Math.sin(tau * (th.freq + 1) + th.phase * 1.7) * seamEnv);- if (dist < localW * 1.45) {- const a = (1.0 - smoothstep(localW * 0.42, localW * 1.35, dist)) * th.strength;- if (a > accum) accum = a;- }- }- if (accum > 0.006) {- const tooth = 0.88 + 0.12 * samplePeriodic(nMicro, 64, x * 0.5, v * 64);- writeAlphaPixel(data, row + x * 4, clamp01(accum * shimmer * tooth));- }- }- }- });-}--/**- * Hair Strand & Lash Tip (256x256):- * Expressive 3-strand gossamer hair cluster oriented along +X: 1 crisp primary filament- * flanked by 2 staggered delicate flyaway companions for instant natural bangs, eyelashes & wisps.- */-export function generateHairWispTip(): string {- return buildCachedPng('pro:hair-wisp-256', HI_TIP_SIZE, (data, size) => {- const half = size * 0.5;- const strands = [- { cx: half + 4, cy: half - 4, rx: size * 0.45, ry: size * 0.068, strength: 1.0 },- { cx: half - 14, cy: half - 62, rx: size * 0.34, ry: size * 0.036, strength: 0.72 },- { cx: half + 10, cy: half + 68, rx: size * 0.32, ry: size * 0.032, strength: 0.66 },- ];-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let accum = 0;- for (let i = 0; i < strands.length; i++) {- const s = strands[i];- const dy = Math.abs(y - s.cy);- if (dy > s.ry * 1.2) continue;- const dx = Math.abs(x - s.cx);- if (dx > s.rx * 1.05) continue;- const nx = dx / s.rx;- const ny = dy / (s.ry * Math.max(0.2, 1.0 - nx * 0.65));- const d = Math.hypot(nx * 0.85, ny);- if (d < 1.0) {- const v = (1.0 - smoothstep(0.32, 1.0, d)) * s.strength;- if (v > accum) accum = v;- }- }- if (accum > 0.004) writeAlphaPixel(data, row + x * 4, accum);- }- }- });-}--// =============================================================================-// 2. SKETCH SECTION PRO TIPS-// =============================================================================--/**- * Vine Charcoal Wash Tip (256x256):- * Velvety feathered willow charcoal pad for atmospheric shadows, portrait backgrounds,- * and soft chiaroscuro tonal blocking.- */-export function generateVineCharcoalTip(): string {- return buildCachedPng('pro:vine-charcoal-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x31a01);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const domes = makeCellularDomeField(64, 18, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.38;- const invSize = 1 / size;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp =- (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * 0.22 +- (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.10;- const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));- if (r >= 1.0) continue;-- const env = Math.pow(0.5 * (1.0 + Math.cos(r * Math.PI)), 1.18);- const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);- const fine = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);- const dust = dome * 0.44 + fine * 0.38 + rand() * 0.18;- const tooth = smoothstep(0.14 + r * 0.28, 0.62 + r * 0.22, dust);- const alpha = env * (0.34 + 0.66 * tooth);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Flat Charcoal Block Tip (256x256):- * Snapped compressed square charcoal stick — razor-crisp chisel corner for bold shadows- * and brows, fractured matte carbon interior, and loose powder flecks along the trailing edge.- */-export function generateCharcoalBlockTip(): string {- return buildCachedPng('pro:charcoal-block-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x31b02);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const domes = makeCellularDomeField(64, 20, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.34;- const invSize = 1 / size;-- const flecks: Array<{ x: number; y: number; r: number; a: number }> = [];- for (let i = 0; i < 24; i++) {- flecks.push({- x: half + (rand() * 2 - 1) * rx * 0.96,- y: half + ry * (0.88 + rand() * 0.22) * (rand() > 0.25 ? 1 : -1),- r: 1.2 + rand() * 2.4,- a: 0.28 + rand() * 0.48,- });- }-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const ySign = dy / ry;- const trail = clamp01((ySign + 0.2) * 0.75);- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp =- (samplePeriodic(nCoarse, 16, x * 0.075, y * 0.075) - 0.5) * (0.06 + trail * 0.12) +- (samplePeriodic(nMed, 32, x * 0.19, y * 0.19) - 0.5) * 0.06;- const nx = Math.abs(dx) / (rx * (1.0 + warp));- const ny = Math.abs(dy) / (ry * (1.0 + warp));- const d = Math.pow(Math.pow(nx, 6.0) + Math.pow(ny, 6.0), 1 / 6.0);-- let alpha = 0;- if (d < 1.04) {- const env = 1.0 - smoothstep(0.88 - trail * 0.14, 1.015, d);- const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);- const med = samplePeriodic(nMed, 32, x * 0.28, y * 0.28);- const fracture = dome * 0.52 + med * 0.34 + rand() * 0.14;- const cutLow = 0.14 + smoothstep(0.55, 1.0, d) * 0.32 + trail * 0.10;- const body = smoothstep(cutLow, cutLow + 0.22, fracture);- const leadCore = (1.0 - trail) * (1.0 - smoothstep(0.76, 0.98, d)) * 0.88;- alpha = env * Math.max(leadCore, body);- }-- for (let i = 0; i < flecks.length; i++) {- const fl = flecks[i];- const fdx = x - fl.x;- const fdy = y - fl.y;- if (Math.abs(fdx) > 5 || Math.abs(fdy) > 5) continue;- const fd = Math.hypot(fdx, fdy) / fl.r;- if (fd < 1.0) {- const fa = (1.0 - smoothstep(0.3, 1.0, fd)) * fl.a;- if (fa > alpha) alpha = fa;- }- }-- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Conté Crayon Tip (256x256):- * Creamy-dry faceted octagonal wax-mineral drawing crayon with crisp edges and fine chalk grit.- */-export function generateConteCrayonTip(): string {- return buildCachedPng('pro:conte-crayon-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x31c03);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const domes = makeCellularDomeField(64, 24, rand);- const half = size * 0.5;- const rx = size * 0.44;- const ry = size * 0.38;- const invSize = 1 / size;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp = (samplePeriodic(nMed, 32, x * 0.12, y * 0.12) - 0.5) * 0.10;- const nx = Math.abs(dx) / (rx * (1.0 + warp));- const ny = Math.abs(dy) / (ry * (1.0 + warp));- const d = Math.pow(Math.pow(nx, 3.8) + Math.pow(ny, 3.8), 1 / 3.8);- if (d >= 1.03) continue;-- const env = 1.0 - smoothstep(0.78, 1.02, d);- const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);- const fine = samplePeriodic(nFine, 64, x * 0.42, y * 0.42);- const wax = dome * 0.48 + fine * 0.36 + rand() * 0.16;- const core = (1.0 - smoothstep(0.54, 0.92, d)) * 0.88;- const tooth = smoothstep(0.14 + d * 0.28, 0.46 + d * 0.24, wax);- const alpha = env * Math.max(core, tooth);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Animation Sketch Pencil (Col-Erase style, 256x256):- * Honed smooth waxy-graphite cone with crisp gesture clarity and fine light-touch paper tooth.- */-export function generateColErasePencilTip(): string {- return buildCachedPng('pro:col-erase-pencil-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x31d04);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.44;- const ry = size * 0.40;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp = (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.09;- const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));- if (r >= 1.02) continue;-- const env = 1.0 - smoothstep(0.74, 1.01, r);- const fine = samplePeriodic(nFine, 64, x * 0.48, y * 0.48);- const grit = 0.72 + 0.22 * fine + 0.06 * rand();- const rim = r > 0.65 ? smoothstep(0.15, 0.62, fine + (1.0 - r) * 0.9) : 1.0;- const alpha = env * grit * rim;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--// =============================================================================-// 3. BRUSH SECTION PRO PAINTERLY TIPS-// =============================================================================--/**- * Hard Square Block-In Tip (256x256):- * Sculptural architectural flat rectangle (Craig Mullins / Sinix / Ahmed Aldoori style)- * for carving bold portrait planes, crisp cast shadows, and geometric metallic facets.- */-export function generateHardSquareTip(): string {- return buildCachedPng('pro:hard-square-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41a01);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.36;-- for (let y = 0; y < size; y++) {- const dy = Math.abs(y - half + 0.5);- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = Math.abs(x - half + 0.5);- const nx = dx / rx;- const ny = dy / ry;- // Razor-clean superellipse rectangle (p = 9) with softly anti-aliased bevel corners- const d = Math.pow(Math.pow(nx, 9.0) + Math.pow(ny, 9.0), 1 / 9.0);- if (d >= 1.02) continue;-- let alpha = 1.0 - smoothstep(0.935, 1.012, d);- // Subtle organic painterly rim tooth so strokes never feel cold/vector-sterile- if (d > 0.86) {- const micro = samplePeriodic(nFine, 64, x * 0.35, y * 0.35);- alpha *= 0.90 + 0.10 * micro;- }- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Painterly Gouache Flat Tip (256x256):- * Overlapping translucent-to-opaque flat synthetic taklon brush head oriented along +X- * (inspired by Guweiz / Ruan Jia / CSP Opaque Watercolor square painterly fabric folds).- */-export function generatePainterlyGouacheFlatTip(): string {- return buildCachedPng('pro:painterly-gouache-flat-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41b02);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.39;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp =- (samplePeriodic(nCoarse, 16, x * 0.055, y * 0.055) - 0.5) * 0.055 +- (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.03;- const nx = Math.abs(dx) / (rx * (1.0 + warp));- const ny = Math.abs(dy) / (ry * (1.0 + warp));- const d = Math.pow(Math.pow(nx, 4.4) + Math.pow(ny, 4.4), 1 / 4.4);- if (d >= 1.03) continue;-- const env = 1.0 - smoothstep(0.84, 1.015, d);- // Subtle fine synthetic-bristle longitudinal flow + slight gouache edge load- const streak = samplePeriodic(nFine, 64, x * 0.10, y * 0.44);- const edgeLoad = 0.90 + 0.10 * smoothstep(0.50, 0.92, d);- const body = (0.86 + 0.14 * streak) * edgeLoad;- const alpha = clamp01(env * body);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Hard Round Pressure Painter / Tapered Painterly Oval (256x256):- * Classic pro digital-painting workhorse oval with lush solid core, buttery cosine rim,- * and whisper-subtle organic perimeter variation.- */-export function generatePainterlyOvalTip(): string {- return buildCachedPng('pro:painterly-oval-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41c03);- const nMed = makePeriodicGrid(32, rand);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.41;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp = (samplePeriodic(nMed, 32, x * 0.075, y * 0.075) - 0.5) * 0.04;- const r = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));- if (r >= 1.0) continue;-- let alpha = 1.0;- if (r > 0.72) {- const t = (r - 0.72) / 0.28;- alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));- }- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Silky Hair & Fur Locks Tip (256x256):- * Directional multi-strand tapered sable lock head oriented along +X: dense lustrous core- * tufts flanked by delicate separated hair wisps for painting bangs, locks & fur in one sweep.- */-export function generateHairLocksTip(): string {- return buildCachedPng('pro:silky-hair-locks-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41d04);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.41;-- interface LockStrand {- cx: number;- cy: number;- rx: number;- ry: number;- strength: number;- }- const strands: LockStrand[] = [];- // 16 deliberately separated silky lock clumps with crisp airy channels between filaments- const anchors = [- -0.94, -0.82, -0.68, -0.56, -0.42, -0.30, -0.17, -0.05,- 0.07, 0.19, 0.32, 0.44, 0.58, 0.71, 0.84, 0.95,- ];- for (let i = 0; i < anchors.length; i++) {- const u = anchors[i] + (rand() - 0.5) * 0.025;- const absU = Math.abs(u);- const arch = Math.sqrt(Math.max(0.20, 1.0 - absU * absU * 0.68));- const isCore = absU < 0.40;- const isWisp = i === 0 || i === 3 || i === 7 || i === 11 || i === 15;- strands.push({- cx: half + (rand() - 0.5) * rx * 0.22,- cy: half + u * ry * 0.96,- rx: rx * (0.64 + rand() * 0.34) * arch,- ry: isWisp ? 2.2 + rand() * 1.8 : isCore ? 4.4 + rand() * 3.0 : 3.0 + rand() * 2.4,- strength: isWisp ? 0.65 + rand() * 0.30 : 0.86 + rand() * 0.14,- });- }-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let accum = 0;- for (let i = 0; i < strands.length; i++) {- const st = strands[i];- const dy = Math.abs(y - st.cy);- if (dy > st.ry * 1.15) continue;- const dx = Math.abs(x - st.cx);- if (dx > st.rx * 1.05) continue;- const nx = dx / st.rx;- const ny = dy / (st.ry * Math.max(0.28, 1.0 - nx * 0.55));- const crossEnv = 1.0 - smoothstep(0.32, 1.0, ny);- const alongEnv = 1.0 - smoothstep(0.28, 1.0, nx);- const v = crossEnv * alongEnv * st.strength;- if (v > accum) accum = v;- }- if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);- }- }- });-}--/**- * Dry-Brush Hair Sheen Tip (256x256):- * Broad flat dry-bristle highlighter oriented along +X with crisp irregular parallel- * hair-fiber bands and airy gaps — glides across hair crowns & silk for instant specular sheen.- */-export function generateDryHairSheenTip(): string {- return buildCachedPng('pro:dry-hair-sheen-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41e05);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.44;- const ry = size * 0.44;-- interface Band {- cy: number;- ry: number;- rx: number;- cx: number;- str: number;- }- const bands: Band[] = [];- // 11 bold separated dry-sheen hair-fiber bands with clear negative-space channels- const bandAnchors = [-0.90, -0.72, -0.54, -0.35, -0.18, 0.0, 0.19, 0.37, 0.56, 0.74, 0.91];- for (let i = 0; i < bandAnchors.length; i++) {- const posU = bandAnchors[i] + (rand() - 0.5) * 0.04;- const isWide = i === 2 || i === 5 || i === 8;- bands.push({- cx: half + (rand() - 0.5) * 28,- cy: half + posU * ry * 0.96,- rx: rx * (0.66 + rand() * 0.32) * (1.0 - Math.abs(posU) * 0.18),- ry: isWide ? 6.2 + rand() * 3.4 : 2.8 + rand() * 2.6,- str: isWide ? 0.92 + rand() * 0.08 : 0.68 + rand() * 0.28,- });- }-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let accum = 0;- for (let i = 0; i < bands.length; i++) {- const b = bands[i];- const dy = Math.abs(y - b.cy);- if (dy > b.ry * 1.15) continue;- const dx = Math.abs(x - b.cx);- if (dx > b.rx * 1.05) continue;- const nx = dx / b.rx;- const ny = dy / b.ry;- const v = (1.0 - smoothstep(0.25, 1.0, nx)) * (1.0 - smoothstep(0.45, 1.0, ny)) * b.str;- if (v > accum) accum = v;- }- if (accum > 0.008) {- const tooth = 0.72 + 0.28 * samplePeriodic(nFine, 64, x * 0.20, y * 0.62);- writeAlphaPixel(data, row + x * 4, clamp01(accum * tooth));- }- }- }- });-}--/**- * Expressive Concept Bristle Multi-Tip (256x256 x 4 variants):- * Energetic fractured hog-bristle flat daubs oriented along +X (Greg Rutkowski / MTG concept art- * cloak & sky oil brushwork) with bold varied tuft clusters and organic ragged edges.- */-export function generateConceptBristleSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:concept-bristle-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x41f06 + vIdx * 0x62d9);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * (0.43 + (vIdx % 2) * 0.025);- const ry = size * (0.35 + ((vIdx + 1) % 2) * 0.03);-- const numTufts = 26;- const tY = new Float32Array(numTufts);- const tW = new Float32Array(numTufts);- const tStr = new Float32Array(numTufts);- const tReach = new Float32Array(numTufts);- for (let i = 0; i < numTufts; i++) {- const u = ((i + 0.5) / numTufts) * 2 - 1;- tY[i] = half + u * ry * 0.96 + (rand() - 0.5) * 6.5;- tW[i] = 3.8 + rand() * 6.2;- tStr[i] = 0.56 + rand() * 0.44;- tReach[i] = 0.72 + rand() * 0.30;- }-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp =- (samplePeriodic(nCoarse, 16, x * 0.065, y * 0.065) - 0.5) * 0.18 +- (samplePeriodic(nMed, 32, x * 0.16, y * 0.16) - 0.5) * 0.08;- const nx = Math.abs(dx) / (rx * (1.0 + warp));- const ny = Math.abs(dy) / (ry * (1.0 + warp * 0.9));- const d = Math.pow(Math.pow(nx, 3.4) + Math.pow(ny, 3.4), 1 / 3.4);- if (d >= 1.06) continue;-- let tuft = 0;- let reach = 0.88;- for (let i = 0; i < numTufts; i++) {- const distY = Math.abs(y - tY[i]) / tW[i];- if (distY < 1.0) {- const v = (1.0 - distY * distY) * tStr[i];- if (v > tuft) {- tuft = v;- reach = tReach[i];- }- }- }-- const grain = samplePeriodic(nFine, 64, x * 0.18, y * 0.52);- const edgeMask = 1.0 - smoothstep(reach * 0.72, reach * 1.04, d);- const dryPocket = smoothstep(0.18 + d * 0.24, 0.62, tuft * 0.72 + grain * 0.28);- const alpha = edgeMask * (0.28 + 0.72 * dryPocket);- if (alpha > 0.005) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Wedge & Chisel Painter Tip (256x256):- * Asymmetric beveled wedge oriented along +X: razor-crisp architectural edge on top/front- * tapering smoothly into a softly feathered painterly gouache heel on bottom/back for effortless- * lost-and-found edges in a single stroke.- */-export function generateWedgeChiselTip(): string {- return buildCachedPng('pro:wedge-chisel-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x42007);- const nCoarse = makePeriodicGrid(16, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.38;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const yNorm = dy / ry; // -1 = crisp wedge apex, +1 = soft feathered heel- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const xNorm = dx / rx;- // Diagonal sharpness axis: top-front (xNorm - yNorm > 0) is razor crisp, bottom-back fades soft- const softness = clamp01((yNorm - xNorm * 0.45 + 0.65) * 0.58);- const warp = (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * (0.04 + softness * 0.14);-- // Angled bevel wedge silhouette- const widthAtY = 1.0 - Math.max(0, -yNorm) * 0.18;- const nx = Math.abs(dx) / (rx * widthAtY * (1.0 + warp));- const ny = Math.abs(dy) / (ry * (1.0 + warp));- const d = Math.pow(Math.pow(nx, 4.2) + Math.pow(ny, 4.2), 1 / 4.2);- if (d >= 1.04) continue;-- const edgeStart = 0.92 - softness * 0.52;- const edgeEnd = 1.008 + softness * 0.02;- const env = 1.0 - smoothstep(edgeStart, edgeEnd, d);- const fine = samplePeriodic(nFine, 64, x * 0.24, y * 0.34);- const alpha = env * (1.0 - softness * 0.35 * (1.0 - fine));- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Soft Watercolor Wash Mop Tip (256x256):- * Organic translucent watercolor puddle with gentle perimeter undulation and subtly- * richer outer pigment ring (pairs naturally with wetEdge and cold-press watercolor paper).- */-export function generateWatercolorWashTip(): string {- return buildCachedPng('pro:watercolor-wash-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x42108);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const half = size * 0.5;- const rad = size * 0.45;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warp =- (samplePeriodic(nCoarse, 16, x * 0.055, y * 0.055) - 0.5) * 0.22 +- (samplePeriodic(nMed, 32, x * 0.13, y * 0.13) - 0.5) * 0.10;- const r = Math.hypot(dx, dy) / (rad * (1.0 + warp));- if (r >= 1.02) continue;-- const env = 1.0 - smoothstep(0.68, 1.01, r);- // Slightly lighter watery center with subtle pigment settling near rim (0.72..0.92)- const rimPool = 0.78 + 0.22 * Math.exp(-Math.pow((r - 0.78) * 5.2, 2));- const bloom = 0.88 + 0.12 * samplePeriodic(nMed, 32, x * 0.16, y * 0.16);- const alpha = clamp01(env * rimPool * bloom);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Metallic & Gold Impasto Glint Tip (256x256):- * Crisp high-contrast faceted oval-lozenge with hammered micro-facet texture inside- * a clean architectural rim for hammered gold coins, bronze cuffs, chrome & eye catchlights.- */-export function generateMetallicGlintTip(): string {- return buildCachedPng('pro:metallic-glint-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x42209);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.34;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const nx = Math.abs(dx) / rx;- const ny = Math.abs(dy) / ry;- const d = Math.pow(Math.pow(nx, 3.2) + Math.pow(ny, 3.2), 1 / 3.2);- if (d >= 1.02) continue;-- const env = 1.0 - smoothstep(0.90, 1.01, d);- // Subtle anisotropic brushed-metal micro sheen- const brushSheen = 0.86 + 0.14 * samplePeriodic(nFine, 64, x * 0.14, y * 0.55);- const hammer = 0.92 + 0.08 * samplePeriodic(nMed, 32, x * 0.20, y * 0.20);- const alpha = clamp01(env * brushSheen * hammer);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--// =============================================================================-// 4. BLEND SECTION PRO PURE-SMEAR TIPS-// =============================================================================--/**- * Charcoal Blending Stump / Tortillon Tip (256x256):- * Tapered rolled-paper stump pad oriented along +X with soft porous paper-felt fibers- * that rub charcoal & graphite into velvety shadows without destroying tooth.- */-export function generateBlendTortillonTip(): string {- return buildCachedPng('pro:blend-tortillon-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x51a01);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const domes = makeCellularDomeField(64, 22, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.38;- const invSize = 1 / size;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const nx = dx / rx;- const cone = 1.0 - Math.max(0, nx) * 0.28;- const ny = dy / (ry * cone);- const r = Math.hypot(nx, ny);- if (r >= 1.02) continue;-- const env = Math.pow(1.0 - smoothstep(0.20, 1.01, r), 1.15);- const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);- const felt = samplePeriodic(nMed, 32, x * 0.10, y * 0.28) * 0.45 + samplePeriodic(nFine, 64, x * 0.38, y * 0.38) * 0.25 + dome * 0.30;- const alpha = env * (0.52 + 0.48 * smoothstep(0.18, 0.72, felt));- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Painterly Gouache Melter Pad Tip (256x256):- * Feathered flat rectangular gouache softening pad oriented along +X — melts hard edges- * into silky anime-realism & painterly gradients while preserving directional brushwork.- */-export function generateBlendGouachePadTip(): string {- return buildCachedPng('pro:blend-gouache-pad-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x51b02);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.45;- const ry = size * 0.39;-- for (let y = 0; y < size; y++) {- const dy = Math.abs(y - half + 0.5);- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = Math.abs(x - half + 0.5);- const nx = dx / rx;- const ny = dy / ry;- const d = Math.pow(Math.pow(nx, 3.0) + Math.pow(ny, 3.0), 1 / 3.0);- if (d >= 1.02) continue;-- const env = Math.pow(1.0 - smoothstep(0.28, 1.01, d), 1.08);- const streak = 0.82 + 0.18 * samplePeriodic(nFine, 64, x * 0.12, y * 0.42);- const alpha = env * streak;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Atmospheric Mist & Smoke Smudge Tip (256x256):- * Turbulent multi-lobed wispy cloud head that pulls existing paint into ghostly- * drifting smoke tendrils, vapor, and cinematic atmospheric haze.- */-export function generateBlendSmokeWispTip(): string {- return buildCachedPng('pro:blend-smoke-wisp-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x51c03);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rad = size * 0.46;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const r = Math.hypot(dx, dy) / rad;- if (r >= 1.02) continue;-- const env = Math.pow(0.5 * (1.0 + Math.cos(Math.min(1, r) * Math.PI)), 1.35);- // Domain-warped fluid curl for natural wispy smoke eddies- const wx = (samplePeriodic(nCoarse, 16, x * 0.045, y * 0.045) - 0.5) * 44;- const wy = (samplePeriodic(nCoarse, 16, x * 0.045 + 7.2, y * 0.045 + 3.9) - 0.5) * 44;- const curl1 = samplePeriodic(nMed, 32, (x + wx) * 0.09, (y + wy) * 0.09);- const curl2 = samplePeriodic(nFine, 64, (x - wy * 0.5) * 0.18, (y + wx * 0.5) * 0.18);- const wisp = smoothstep(0.24, 0.78, curl1 * 0.65 + curl2 * 0.35);- const alpha = env * (0.18 + 0.82 * wisp);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Palette Knife Smudge Blade Tip (256x256):- * Asymmetric thin painting-knife scraper oriented along +X: crisp straight edge on top- * with smooth feathered trail below for razor-clean sculptural paint pulling.- */-export function generateBlendKnifeSmearTip(): string {- return buildCachedPng('pro:blend-knife-smear-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x51d04);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * 0.46;- const ry = size * 0.34;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const ySigned = dy / ry; // -1 = crisp knife blade edge, +1 = soft feathered smear trail- const trail = clamp01((ySigned + 0.35) / 1.35);- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = Math.abs(x - half + 0.5);- const nx = dx / rx;- const ny = Math.abs(ySigned);- const d = Math.pow(Math.pow(nx, 5.0) + Math.pow(ny, 5.0), 1 / 5.0);- if (d >= 1.02) continue;-- const envX = 1.0 - smoothstep(0.76, 1.01, nx);- const envTop = smoothstep(-1.01, -0.84, ySigned);- const envBot = 1.0 - smoothstep(0.10, 1.01, ySigned);- const micro = 0.90 + 0.10 * samplePeriodic(nFine, 64, x * 0.14, y * 0.48);- const alpha = envX * envTop * envBot * (1.0 - trail * 0.25) * micro;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--// =============================================================================-// 5. TEXTURE & FX SECTION PRO TIPS (FOLIAGE, FRECKLES, SMOKE, ROCK, EMBER, CLOUDS, GLOW)-// =============================================================================--/** Helper: evaluates a single sculpted botanical leaf silhouette in local coords. */-function evalLeafShape(- px: number,- py: number,- cx: number,- cy: number,- len: number,- halfW: number,- angleRad: number,- bend: number,- sharpness: number-): number {- const dx = px - cx;- const dy = py - cy;- const c = Math.cos(-angleRad);- const s = Math.sin(-angleRad);- const lx = (dx * c - dy * s) / len; // [-1, 1] along leaf spine- if (lx < -1.04 || lx > 1.04) return 0;- const bendOffset = bend * (1.0 - lx * lx);- const ly = (dx * s + dy * c) / halfW - bendOffset;-- // Botanical pointed almond contour: fuller near base (-0.25), pointed at tip (+1)- const u = (lx + 1.0) * 0.5; // 0 = base, 1 = tip- const profile = Math.pow(Math.max(0, Math.sin(u * Math.PI)), 0.78) * (1.16 - 0.34 * u);- if (profile <= 0.005) return 0;- const dist = Math.abs(ly) / profile;- if (dist >= 1.08) return 0;-- // Subtle central midrib variation for painted leaf dimensionality- const midrib = 0.92 + 0.08 * Math.exp(-ly * ly * 22);- const edge = 1.0 - smoothstep(sharpness, 1.04, dist);- return edge * midrib;-}--/**- * Painterly Canopy Leaves Multi-Tip (256x256 x 4 botanical variants):- * Hand-painted organic forest leaves & twin/triple sprigs for rich fantasy foliage.- */-export function generatePainterlyLeafSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:painterly-leaf-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61a01 + vIdx * 0x4711);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;-- const specs: Array<Array<{ cx: number; cy: number; len: number; hw: number; ang: number; bend: number; str: number }>> = [- // v0: Sculpted rainforest broadleaf- [{ cx: half, cy: half, len: size * 0.43, hw: size * 0.19, ang: -0.22, bend: 0.18, str: 1.0 }],- // v1: Graceful twin-leaf branchlet- [- { cx: half - 22, cy: half - 26, len: size * 0.34, hw: size * 0.14, ang: -0.62, bend: 0.14, str: 0.96 },- { cx: half + 26, cy: half + 24, len: size * 0.36, hw: size * 0.15, ang: 0.38, bend: -0.16, str: 1.0 },- ],- // v2: Broad angled sunlit diamond leaf- [{ cx: half, cy: half, len: size * 0.41, hw: size * 0.23, ang: 0.18, bend: -0.14, str: 1.0 }],- // v3: Lush triple-leaf canopy cluster- [- { cx: half, cy: half - 40, len: size * 0.28, hw: size * 0.13, ang: -1.25, bend: 0.10, str: 0.94 },- { cx: half - 42, cy: half + 24, len: size * 0.30, hw: size * 0.13, ang: -2.45, bend: -0.12, str: 0.88 },- { cx: half + 40, cy: half + 22, len: size * 0.31, hw: size * 0.14, ang: 0.45, bend: 0.12, str: 1.0 },- ],- ];- const leaves = specs[vIdx];-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const wx = (samplePeriodic(nMed, 32, x * 0.08, y * 0.08) - 0.5) * 4.5;- const wy = (samplePeriodic(nMed, 32, x * 0.08 + 5.1, y * 0.08 + 2.3) - 0.5) * 4.5;- let accum = 0;- for (let i = 0; i < leaves.length; i++) {- const lf = leaves[i];- const v = evalLeafShape(x + wx, y + wy, lf.cx, lf.cy, lf.len, lf.hw, lf.ang, lf.bend, 0.80) * lf.str;- if (v > accum) accum = v;- }- if (accum > 0.006) {- const brushTooth = 0.84 + 0.16 * samplePeriodic(nFine, 64, x * 0.22, y * 0.22);- writeAlphaPixel(data, row + x * 4, clamp01(accum * brushTooth));- }- }- }- });-}--/**- * Bokeh Soft Foreground Leaves Multi-Tip (256x256 x 3 variants):- * Softly defocused optical depth-of-field leaves for cinematic foreground framing & drifting petals.- */-export function generateBokehLeafSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 3) + 3) % 3;- return buildCachedPng(`pro:bokeh-leaf-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const half = size * 0.5;- const cfg = [- { len: size * 0.42, hw: size * 0.22, ang: -0.30, bend: 0.16 },- { len: size * 0.44, hw: size * 0.16, ang: 0.42, bend: -0.20 },- { len: size * 0.38, hw: size * 0.25, ang: 0.05, bend: 0.10 },- ][vIdx];-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- // Wide soft optical defocus (sharpness = 0.18 -> lush dreamy depth-of-field blur)- const v = evalLeafShape(x, y, half, half, cfg.len, cfg.hw, cfg.ang, cfg.bend, 0.16);- if (v > 0.004) {- writeAlphaPixel(data, row + x * 4, Math.pow(v, 1.18));- }- }- }- });-}--/**- * Skin Freckles & Pores Multi-Tip (256x256 x 4 organic micro-constellations):- * Realistic non-repeating irregular freckle clusters & portrait skin pores (zero grid artifacts).- */-export function generateSkinFrecklesSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:skin-freckles-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61c03 + vIdx * 0x893b);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;-- interface Freckle {- x: number;- y: number;- rx: number;- ry: number;- cos: number;- sin: number;- a: number;- }- const spots: Freckle[] = [];- const count = 24 + (vIdx % 2) * 6;- for (let i = 0; i < count; i++) {- const ang = rand() * Math.PI * 2;- // Organic radial spread denser near center, airy sparse edges- const rad = Math.pow(rand(), 0.70) * (size * 0.43);- // Calibrated 4.2..11px at 256px tip so 64px strokes render crisp natural freckles & pores- const baseR = 4.2 + Math.pow(rand(), 1.65) * 6.8;- const rot = rand() * Math.PI;- spots.push({- x: half + Math.cos(ang) * rad,- y: half + Math.sin(ang) * rad,- rx: baseR * (0.78 + rand() * 0.44),- ry: baseR * (0.78 + rand() * 0.44),- cos: Math.cos(rot),- sin: Math.sin(rot),- a: (0.52 + rand() * 0.48) * (1.0 - (rad / (size * 0.48)) * 0.28),- });- }-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let accum = 0;- for (let i = 0; i < spots.length; i++) {- const sp = spots[i];- const dx = x - sp.x;- const dy = y - sp.y;- if (Math.abs(dx) > 16 || Math.abs(dy) > 16) continue;- const lx = (dx * sp.cos + dy * sp.sin) / sp.rx;- const ly = (-dx * sp.sin + dy * sp.cos) / sp.ry;- const d = Math.hypot(lx, ly);- if (d < 1.08) {- const wobble = (samplePeriodic(nFine, 64, x * 0.45, y * 0.45) - 0.5) * 0.22;- const v = (1.0 - smoothstep(0.36 + wobble, 1.02 + wobble, d)) * sp.a;- if (v > accum) accum = v;- }- }- if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);- }- }- });-}--/**- * Dark Smoke & Vapor Tendril Multi-Tip (256x256 x 4 domain-warped turbulent plumes):- * Inspired by MTG dark fantasy swirling necrotic smoke & glowing lantern vapor.- */-export function generateSmokeTendrilSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:smoke-tendril-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61d04 + vIdx * 0x7a1f);- const nWarp = makePeriodicGrid(16, rand);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rx = size * (0.46 - (vIdx % 2) * 0.03);- const ry = size * (0.37 + (vIdx % 2) * 0.05);-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- // Double domain warp produces authentic fluid curling smoke ribbons- const w1x = (samplePeriodic(nWarp, 16, x * 0.038 + vIdx * 2.1, y * 0.038) - 0.5) * 58;- const w1y = (samplePeriodic(nWarp, 16, x * 0.038 + 5.7, y * 0.038 + vIdx * 3.3) - 0.5) * 58;- const px = x + w1x;- const py = y + w1y;-- const r = Math.hypot((dx + w1x * 0.35) / rx, (dy + w1y * 0.35) / ry);- if (r >= 1.05) continue;-- const env = Math.pow(0.5 * (1.0 + Math.cos(Math.min(1, r) * Math.PI)), 1.30);- const f1 = samplePeriodic(nCoarse, 16, px * 0.055, py * 0.055);- const f2 = samplePeriodic(nMed, 32, px * 0.12, py * 0.12);- const f3 = samplePeriodic(nFine, 64, px * 0.25, py * 0.25);- // Ridged billow creates curling translucent smoke tendrils with dark lacy hollows- const fbm = f1 * 0.50 + f2 * 0.32 + f3 * 0.18;- const wisp = smoothstep(0.28 + r * 0.16, 0.78, fbm);- const alpha = env * wisp;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Wispy Smoke Dual Brush Erosion Mask (256x256):- * Secondary modulation tip for Dark Smoke & Vapor — breaks continuous strokes into- * organic billowing eddies and ghost-like tendrils.- */-export function generateSmokeDualMaskTip(): string {- return buildCachedPng('pro:smoke-dual-mask-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61d99);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const half = size * 0.5;- const rad = size * 0.48;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const r = Math.hypot(dx, dy) / rad;- if (r >= 1.0) continue;-- const env = 1.0 - smoothstep(0.58, 1.0, r);- const wx = (samplePeriodic(nCoarse, 16, x * 0.05, y * 0.05) - 0.5) * 32;- const wy = (samplePeriodic(nCoarse, 16, x * 0.05 + 4.3, y * 0.05 + 8.1) - 0.5) * 32;- const cloud = samplePeriodic(nMed, 32, (x + wx) * 0.11, (y + wy) * 0.11);- const mask = 0.25 + 0.75 * smoothstep(0.20, 0.76, cloud);- const alpha = env * mask;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Craggy Rock & Weathered Bone Multi-Tip (256x256 x 4 angular fractured variants):- * Inspired by MTG skull pauldrons, jagged mountain cliffs, ancient stone & hammered rusted metal.- */-export function generateCraggyRockSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:craggy-rock-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61e05 + vIdx * 0x5c3d);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const nFine = makePeriodicGrid(64, rand);- const domes = makeCellularDomeField(64, 16 + vIdx * 3, rand);- const half = size * 0.5;- const rx = size * (0.44 - (vIdx % 2) * 0.03);- const ry = size * (0.37 + ((vIdx + 1) % 2) * 0.04);- const invSize = 1 / size;-- // 5 angular mineral shards composed per variant to eliminate any circular feel- const shards: Array<{ x: number; y: number; rx: number; ry: number; cos: number; sin: number; w: number }> = [];- for (let i = 0; i < 5; i++) {- const th = (i / 5) * Math.PI * 2 + rand() * 0.8;- const dist = (0.08 + rand() * 0.30) * rx;- const rot = rand() * Math.PI;- shards.push({- x: half + Math.cos(th) * dist,- y: half + Math.sin(th) * dist * 0.85,- rx: rx * (0.38 + rand() * 0.30),- ry: ry * (0.32 + rand() * 0.28),- cos: Math.cos(rot),- sin: Math.sin(rot),- w: 0.74 + rand() * 0.26,- });- }-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let shape = 0;- for (let i = 0; i < shards.length; i++) {- const sh = shards[i];- const dx = x - sh.x;- const dy = y - sh.y;- const lx = Math.abs(dx * sh.cos + dy * sh.sin) / sh.rx;- const ly = Math.abs(-dx * sh.sin + dy * sh.cos) / sh.ry;- // Angular faceted diamond-box rock shard (superellipse p = 1.65)- const d = Math.pow(Math.pow(lx, 1.65) + Math.pow(ly, 1.65), 1 / 1.65);- if (d < 1.05) {- const v = (1.0 - smoothstep(0.62, 1.03, d)) * sh.w;- if (v > shape) shape = v;- }- }- if (shape <= 0.01) continue;-- const dome = sampleFieldBilinear(domes, 64, x * invSize, y * invSize);- const ridge = 1.0 - Math.abs(samplePeriodic(nCoarse, 16, x * 0.085, y * 0.085) * 2.0 - 1.0);- const grit = samplePeriodic(nMed, 32, x * 0.22, y * 0.22) * 0.55 + samplePeriodic(nFine, 64, x * 0.45, y * 0.45) * 0.45;- const crag = dome * 0.42 + ridge * 0.32 + grit * 0.26;- const cut = 0.22 + (1.0 - shape) * 0.42;- const alpha = shape * smoothstep(cut, cut + 0.18, crag);- if (alpha > 0.005) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Ash, Embers & Ink Spatter Multi-Tip (256x256 x 4 organic splatter constellations):- * Dynamic teardrop ink drops, glowing fire embers, and crisp irregular ash specks.- */-export function generateEmberSpatterSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:ember-spatter-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x61f06 + vIdx * 0x91e7);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;-- interface Drop {- x: number;- y: number;- rx: number;- ry: number;- cos: number;- sin: number;- a: number;- }- const drops: Drop[] = [];- // 4 primary elongated splash drops + 24 varied ash/ember sparks- for (let i = 0; i < 28; i++) {- const isHero = i < 4;- const th = rand() * Math.PI * 2;- const dist = isHero ? (0.06 + rand() * 0.24) * size : (0.10 + Math.pow(rand(), 0.72) * 0.36) * size;- const r = isHero ? 5.5 + rand() * 7.5 : 1.3 + Math.pow(rand(), 1.7) * 4.2;- const stretch = isHero ? 1.35 + rand() * 0.85 : 0.9 + rand() * 0.65;- const rot = th + (rand() - 0.5) * 0.6;- drops.push({- x: half + Math.cos(th) * dist,- y: half + Math.sin(th) * dist,- rx: r * stretch,- ry: r,- cos: Math.cos(rot),- sin: Math.sin(rot),- a: isHero ? 0.88 + rand() * 0.12 : 0.45 + rand() * 0.55,- });- }-- for (let y = 0; y < size; y++) {- const row = y * size * 4;- for (let x = 0; x < size; x++) {- let accum = 0;- for (let i = 0; i < drops.length; i++) {- const dr = drops[i];- const dx = x - dr.x;- const dy = y - dr.y;- const bound = dr.rx * 1.2 + 2;- if (Math.abs(dx) > bound || Math.abs(dy) > bound) continue;- const lx = (dx * dr.cos + dy * dr.sin) / dr.rx;- const ly = (-dx * dr.sin + dy * dr.cos) / dr.ry;- const d = Math.hypot(lx, ly);- if (d < 1.06) {- const jagged = (samplePeriodic(nFine, 64, x * 0.35, y * 0.35) - 0.5) * 0.20;- const v = (1.0 - smoothstep(0.68 + jagged, 1.02 + jagged, d)) * dr.a;- if (v > accum) accum = v;- }- }- if (accum > 0.005) writeAlphaPixel(data, row + x * 4, accum);- }- }- });-}--/**- * Painterly Cumulus Clouds Multi-Tip (256x256 x 4 asymmetric sculpted sky puffs):- * Crisper sunlit billowing upper domes dissolving into soft misty horizontal bases- * for dramatic fantasy skies & Studio Ghibli / MTG cloudscapes.- */-export function generatePainterlyCloudSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 4) + 4) % 4;- return buildCachedPng(`pro:painterly-cloud-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x62007 + vIdx * 0x4b93);- const nCoarse = makePeriodicGrid(16, rand);- const nMed = makePeriodicGrid(32, rand);- const half = size * 0.5;-- interface Puff {- x: number;- y: number;- rx: number;- ry: number;- w: number;- }- const puffs: Puff[] = [];- const numPuffs = 6;- for (let i = 0; i < numPuffs; i++) {- const u = (i / (numPuffs - 1)) * 2 - 1; // left to right- const arch = 1.0 - u * u * 0.72;- puffs.push({- x: half + u * size * 0.27 + (rand() - 0.5) * 14,- y: half + size * (0.08 - arch * 0.18) + (rand() - 0.5) * 14,- rx: size * (0.16 + arch * 0.11 + rand() * 0.05),- ry: size * (0.14 + arch * 0.11 + rand() * 0.05),- w: 0.78 + arch * 0.22,- });- }-- for (let y = 0; y < size; y++) {- const yFrac = y / size; // 0 = top sunlit billows, 1 = soft misty base- const baseFade = 1.0 - smoothstep(0.56, 0.90, yFrac);- const topCrisp = 1.0 - smoothstep(0.28, 0.65, yFrac); // crisper upper cloud rim- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const wx = (samplePeriodic(nCoarse, 16, x * 0.05, y * 0.05) - 0.5) * 18;- const wy = (samplePeriodic(nCoarse, 16, x * 0.05 + 6.3, y * 0.05 + 2.7) - 0.5) * 16;- let shape = 0;- for (let i = 0; i < puffs.length; i++) {- const pf = puffs[i];- const d = Math.hypot((x + wx - pf.x) / pf.rx, (y + wy - pf.y) / pf.ry);- if (d < 1.05) {- const edgeStart = 0.26 + topCrisp * 0.44;- const v = (1.0 - smoothstep(edgeStart, 1.02, d)) * pf.w;- if (v > shape) shape = v;- }- }- if (shape <= 0.006) continue;- const billow = 0.78 + 0.22 * samplePeriodic(nMed, 32, x * 0.12, y * 0.12);- const alpha = shape * billow * (0.18 + 0.82 * baseFade);- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Woven Cloth & Brocade Grain Tip (256x256):- * Tactile organic textile pad infused with crisp cross-hatched brocade & linen threads- * for painting embroidered medieval sleeves, tunics, scarves & woven fabric highlights.- */-export function generateWovenFabricTip(): string {- return buildCachedPng('pro:woven-fabric-256', HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x62108);- const nCoarse = makePeriodicGrid(16, rand);- const nFine = makePeriodicGrid(64, rand);- const half = size * 0.5;- const rad = size * 0.46;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- const weft = Math.sin(y * 0.58) * 0.5 + 0.5;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const warpNoise = (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * 0.16;- const r = Math.hypot(dx, dy) / (rad * (1.0 + warpNoise));- if (r >= 1.0) continue;-- const env = 1.0 - smoothstep(0.45, 0.99, r);- const warp = Math.sin(x * 0.58) * 0.5 + 0.5;- // Subtle diamond brocade twill weave pattern- const twill = Math.sin((x + y) * 0.29) * Math.cos((x - y) * 0.29) * 0.24;- const weave = clamp01(warp * 0.44 + weft * 0.44 + 0.12 + twill);- const yarn = 0.84 + 0.16 * samplePeriodic(nFine, 64, x * 0.34, y * 0.34);- const alpha = env * (0.28 + 0.72 * smoothstep(0.20, 0.78, weave)) * yarn;- if (alpha > 0.004) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Luminous Magic & Rim Glow Tip (256x256):- * True optical point-spread bloom core: radiant smooth Gaussian center merging seamlessly- * into an exponential inverse-square light halo with zero ring banding.- */-export function generateLuminousBloomTip(): string {- return buildCachedPng('pro:luminous-bloom-256', HI_TIP_SIZE, (data, size) => {- const half = size * 0.5;- const rad = size * 0.49;-- for (let y = 0; y < size; y++) {- const dy = y - half + 0.5;- const row = y * size * 4;- for (let x = 0; x < size; x++) {- const dx = x - half + 0.5;- const r = Math.hypot(dx, dy) / rad;- if (r >= 1.0) continue;-- // Smooth optical lens bloom: bright Gaussian center + wide atmospheric halo tapering to 0- const windowCut = 1.0 - smoothstep(0.84, 1.0, r);- const core = Math.exp(-r * r * 7.2);- const halo = Math.pow(1.0 - r, 2.6);- const alpha = clamp01((core * 0.58 + halo * 0.42) * windowCut);- if (alpha > 0.003) writeAlphaPixel(data, row + x * 4, alpha);- }- }- });-}--/**- * Fine Film & Stipple Dust Multi-Tip (256x256 x 3 organic stochastic micro-grain variants):- * Delicate non-tiling fine stipple dust & photographic film grain for finishing smooth portraits & skies.- */-export function generateFineStippleSubTip(variant: number = 0): string {- const vIdx = ((Math.floor(variant) % 3) + 3) % 3;- return buildCachedPng(`pro:fine-stipple-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {- const rand = createPrng(0x62209 + vIdx * 0x3b71);- const half = size * 0.5;- const maxRad = size * 0.46;-- // Scatter 360 crisp delicate 1.5..3.4px micro-grains directly into buffer (ultra-fast O(360)!)- const grainCount = 360;- for (let i = 0; i < grainCount; i++) {- const th = rand() * Math.PI * 2;- const rNorm = Math.pow(rand(), 0.62);- const cx = half + Math.cos(th) * rNorm * maxRad;- const cy = half + Math.sin(th) * rNorm * maxRad;- const gRad = 1.5 + Math.pow(rand(), 1.8) * 2.0;- const env = 0.5 * (1.0 + Math.cos(rNorm * Math.PI));- const strength = (0.48 + rand() * 0.52) * (0.40 + 0.60 * env);-- const x0 = Math.max(0, Math.floor(cx - gRad - 1));- const x1 = Math.min(size - 1, Math.ceil(cx + gRad + 1));- const y0 = Math.max(0, Math.floor(cy - gRad - 1));- const y1 = Math.min(size - 1, Math.ceil(cy + gRad + 1));- for (let py = y0; py <= y1; py++) {- const dy = py - cy;- const row = py * size * 4;- for (let px = x0; px <= x1; px++) {- const dx = px - cx;- const d = Math.hypot(dx, dy) / gRad;- if (d < 1.0) {- const a = (1.0 - smoothstep(0.25, 1.0, d)) * strength;- const idx = row + px * 4;- const prevA = data[idx + 3] / 255;- if (a > prevA) {- writeAlphaPixel(data, idx, a);- }- }- }- }- }- });-}diff --git a/src/utils/scratchpadRenderer.ts b/src/utils/scratchpadRenderer.tsnew file mode 100644index 0000000..4e01ed2--- /dev/null+++ b/src/utils/scratchpadRenderer.ts@@ -0,0 +1,539 @@+import type { BrushSettings, CspTaperSettings } from '../types/editor';+import { evaluateFastSpline, isNaturalPaintBrush } from './brushMath';+import type { NativeScratchpadStrokeInput } from './nativeEngineBridge';++export interface ScratchpadSamplePoint {+ x: number;+ y: number;+ pressure: number;+ tiltX: number;+ tiltY: number;+ twist: number;+ timestampMs: number;+}++export interface RecordedScratchpadStroke {+ id: number;+ points: ScratchpadSamplePoint[];+ /** Explicit hex color captured at stroke creation (used when `followActiveColor` is false). */+ color: string;+ /** When true (default for strokes drawn with active foreground ink or the reference stroke), follows live color changes. */+ followActiveColor: boolean;+ /** Deterministic PRNG seed so dragging sliders never causes scatter/spray/angle jitter to flicker randomly. */+ seed: number;+}++function clamp(v: number, lo: number, hi: number): number {+ return v < lo ? lo : v > hi ? hi : v;+}++export function hexToRgb01(hex: string | undefined): [number, number, number] {+ if (!hex) return [0.11, 0.31, 0.85];+ const cleaned = hex.trim().replace(/^#/, '');+ if (cleaned.length === 3) {+ const r = parseInt(cleaned[0] + cleaned[0], 16) / 255;+ const g = parseInt(cleaned[1] + cleaned[1], 16) / 255;+ const b = parseInt(cleaned[2] + cleaned[2], 16) / 255;+ if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) return [r, g, b];+ } else if (cleaned.length >= 6) {+ const r = parseInt(cleaned.slice(0, 2), 16) / 255;+ const g = parseInt(cleaned.slice(2, 4), 16) / 255;+ const b = parseInt(cleaned.slice(4, 6), 16) / 255;+ if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) return [r, g, b];+ }+ return [0.11, 0.31, 0.85];+}++/**+ * Generates an expressive pressure-tapered S-curve sample stroke centered inside the scratchpad+ * so Brush Studio immediately shows live parameter edits before the user even draws a stroke.+ */+export function buildDefaultSampleStroke(+ width: number,+ height: number,+ color: string+): RecordedScratchpadStroke {+ const steps = 64;+ const padX = Math.max(44, width * 0.14);+ const spanX = Math.max(60, width - padX * 2);+ const midY = height * 0.5;+ const ampY = Math.max(24, height * 0.24);+ const points: ScratchpadSamplePoint[] = [];++ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const x = padX + spanX * t;+ const y = midY - Math.sin(t * Math.PI * 2) * ampY;+ // Expressive manga/calligraphy pressure bell: delicate entry -> rich belly -> fine exit+ const pressure = clamp(Math.pow(Math.sin(t * Math.PI), 0.72), 0.06, 1.0);+ points.push({+ x,+ y,+ pressure,+ tiltX: 12 * Math.sin(t * Math.PI),+ tiltY: 18 * Math.cos(t * Math.PI * 0.5),+ twist: 0,+ timestampMs: i * 5,+ });+ }++ return {+ id: 0,+ points,+ color,+ followActiveColor: true,+ seed: 0x51a0c0de,+ };+}++export function toNativeScratchpadStrokes(+ strokes: RecordedScratchpadStroke[],+ activeColor: string+): NativeScratchpadStrokeInput[] {+ return strokes.map((s) => ({+ points: s.points.map((p) => ({+ x: p.x,+ y: p.y,+ pressure: p.pressure,+ tiltX: p.tiltX,+ tiltY: p.tiltY,+ twist: p.twist,+ timestampMs: p.timestampMs,+ })),+ color: hexToRgb01(s.followActiveColor ? activeColor : s.color),+ seed: s.seed >>> 0,+ }));+}++function createPrng(seed: number): () => number {+ let state = (seed >>> 0) || 0x2468ace1;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++function evalBrushWidth(bs: BrushSettings, rawPressure: number): number {+ const baseSize = clamp(bs.size || 14, 1, 220);+ if (bs.usePressure === false) return baseSize;+ const p = clamp(rawPressure, 0, 1);+ let mapped = p;+ if (bs.pressureCurve && bs.pressureCurve.length >= 2) {+ mapped = clamp(evaluateFastSpline(p, bs.pressureCurve), 0, 1);+ } else if (bs.pressureCurveGamma && Math.abs(bs.pressureCurveGamma - 1) > 1e-3) {+ mapped = Math.pow(p, clamp(bs.pressureCurveGamma, 0.2, 5));+ }+ const minF = clamp(bs.minSizeFactor ?? 0.1, 0, 1);+ return Math.max(0.6, baseSize * (minF + (1 - minF) * mapped));+}++function shapeTaperRamp(t: number, sharpness: number): number {+ const tc = clamp(t, 0, 1);+ const s = clamp(sharpness, 0, 1);+ const exp = s < 0.5 ? 0.45 + (s / 0.5) * 0.55 : 1.0 + ((s - 0.5) / 0.5) * 1.1;+ const curved = Math.pow(tc, exp);+ const smooth = tc * tc * (3 - 2 * tc);+ return curved * 0.8 + smooth * 0.2;+}++function evalTaperFactors(+ taper: CspTaperSettings | undefined,+ arcDist: number,+ totalLen: number+): { size: number; opacity: number } {+ if (!taper || taper.inOutType === 0 || (!taper.useIn && !taper.useOut)) {+ return { size: 1, opacity: 1 };+ }+ let factor = 1;+ const mode = taper.inOutType ?? 2;+ if (taper.useIn) {+ const inSpan =+ mode === 1 ? totalLen * clamp(taper.inRatio ?? 0.2, 0, 0.95) : Math.max(0, taper.inLength ?? 0);+ if (inSpan > 0.1 && arcDist < inSpan) {+ factor = Math.min(factor, shapeTaperRamp(arcDist / inSpan, taper.startingSharpness ?? 0.5));+ }+ }+ if (taper.useOut) {+ const outSpan =+ mode === 1+ ? totalLen * clamp(taper.outRatio ?? 0.2, 0, 0.95)+ : Math.max(0, taper.outLength ?? 0);+ const distFromEnd = Math.max(0, totalLen - arcDist);+ if (outSpan > 0.1 && distFromEnd < outSpan) {+ factor = Math.min(factor, shapeTaperRamp(distFromEnd / outSpan, taper.endingSharpness ?? 0.5));+ }+ }+ const minSize = clamp(taper.minSizeRatio ?? 0, 0, 1);+ const minDens = clamp(taper.minDensityRatio ?? 0, 0, 1);+ return {+ size: taper.affectSize !== false ? minSize + (1 - minSize) * factor : 1,+ opacity: taper.affectOpacity || mode === 3 ? minDens + (1 - minDens) * factor : 1,+ };+}++/**+ * Lightly smooths recorded polyline points when stabilization or postCorrection > 0+ * so those sliders visibly smooth jittery strokes on the 2D fallback renderer too.+ */+function smoothPolylineForPreview(+ points: ScratchpadSamplePoint[],+ stabilization: number,+ postCorrection: number+): ScratchpadSamplePoint[] {+ if (points.length < 4) return points;+ const passes = Math.min(8, Math.floor((stabilization || 0) / 8) + (postCorrection || 0));+ if (passes <= 0) return points;+ let cur = points.map((p) => ({ ...p }));+ for (let pass = 0; pass < passes; pass++) {+ const next = cur.map((p) => ({ ...p }));+ for (let i = 1; i < cur.length - 1; i++) {+ next[i].x = 0.25 * cur[i - 1].x + 0.5 * cur[i].x + 0.25 * cur[i + 1].x;+ next[i].y = 0.25 * cur[i - 1].y + 0.5 * cur[i].y + 0.25 * cur[i + 1].y;+ }+ cur = next;+ }+ return cur;+}++let cachedTintedTipCanvas: HTMLCanvasElement | null = null;+let cachedTintedTipKey = '';++function getTintedTipCanvas(tipImg: HTMLImageElement, color: string): HTMLCanvasElement | null {+ if (typeof document === 'undefined') return null;+ const w = tipImg.naturalWidth || tipImg.width;+ const h = tipImg.naturalHeight || tipImg.height;+ if (w <= 0 || h <= 0) return null;+ const key = `${tipImg.src.slice(0, 64)}|${color}`;+ if (cachedTintedTipCanvas && cachedTintedTipKey === key) {+ return cachedTintedTipCanvas;+ }+ const c = document.createElement('canvas');+ c.width = Math.min(256, w);+ c.height = Math.min(256, h);+ const ctx = c.getContext('2d');+ if (!ctx) return null;+ ctx.drawImage(tipImg, 0, 0, c.width, c.height);+ ctx.globalCompositeOperation = 'source-in';+ ctx.fillStyle = color;+ ctx.fillRect(0, 0, c.width, c.height);+ cachedTintedTipCanvas = c;+ cachedTintedTipKey = key;+ return c;+}++/**+ * Renders a single stroke onto a 2D context with live BrushSettings fidelity.+ * Used both for real-time 2D replay (Web / tests / fallback) and for live in-progress draft painting.+ */+export function renderSingleScratchpadStroke2D(+ ctx: CanvasRenderingContext2D,+ stroke: RecordedScratchpadStroke,+ bs: BrushSettings,+ activeColor: string+): void {+ const rawPts = stroke.points;+ if (rawPts.length === 0) return;++ const pts = smoothPolylineForPreview(+ rawPts,+ bs.stabilization ?? 0,+ bs.postCorrection ?? 0+ );+ const strokeColor = stroke.followActiveColor ? activeColor : stroke.color;+ const rand = createPrng(stroke.seed);++ const flow = clamp((bs.flow ?? 1.0) * (bs.brushDensity ?? 1.0), 0.04, 1.0);+ const hardness = clamp(bs.hardness ?? 0.9, 0.02, 1.0);+ const spacingRatio = clamp(bs.spacing ?? 0.1, 0.025, 2.5);+ const thickness = clamp(bs.thickness ?? 1.0, 0.1, 1.0);+ const thicknessVertical = Boolean(bs.thicknessVertical);+ const baseAngleRad = ((bs.customTipAngle ?? 0) * Math.PI) / 180;+ const angleMode = bs.customTipAngleDynamics ?? 'none';+ const angleRandScale = bs.customTipRotationRandomScale ?? 1.0;+ const dyn = bs.dynamics;+ const scatter = clamp(dyn?.scatter ?? 0, 0, 5);+ const sizeJitter = clamp(dyn?.sizeJitter ?? 0, 0, 1);+ const angleJitter = clamp(dyn?.angleJitter ?? 0, 0, 1);+ const flowJitter = clamp(dyn?.flowJitter ?? 0, 0, 1);+ const grainAmount = clamp(bs.grain ?? bs.textureDensity ?? 0, 0, 1);+ const wetEdge = clamp(bs.wetEdge ?? 0, 0, 1);+ const isSpray = Boolean(bs.spray?.enabled);+ const naturalMode = isNaturalPaintBrush(bs);+ const tipImg = bs.customTipImage;+ const hasTipImg = Boolean(+ tipImg && tipImg.complete && (tipImg.naturalWidth || tipImg.width) > 0+ );+ const tintedTip =+ hasTipImg && tipImg && !bs.isColorTip ? getTintedTipCanvas(tipImg, strokeColor) : null;++ // Compute total arc length for CSP taper In/Out+ let totalLen = 0;+ for (let i = 1; i < pts.length; i++) {+ totalLen += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);+ }++ let initialAngle = 0;+ for (let i = 1; i < pts.length; i++) {+ const dx = pts[i].x - pts[i - 1].x;+ const dy = pts[i].y - pts[i - 1].y;+ if (Math.hypot(dx, dy) > 0.5) {+ initialAngle = Math.atan2(dy, dx);+ break;+ }+ }++ ctx.save();+ ctx.fillStyle = strokeColor;+ ctx.strokeStyle = strokeColor;+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';++ const drawDab = (+ x: number,+ y: number,+ diam: number,+ angleRad: number,+ alpha: number+ ) => {+ const jSize = sizeJitter > 0.001 ? 1 - rand() * sizeJitter : 1;+ const d = Math.max(0.8, diam * jSize);+ const jFlow = flowJitter > 0.001 ? 1 - rand() * flowJitter : 1;+ const grainAtten = grainAmount > 0.01 ? 1 - grainAmount * 0.45 * rand() : 1;+ const a = clamp(alpha * jFlow * grainAtten, 0.01, 1.0);++ let dx = 0;+ let dy = 0;+ if (scatter > 0.001) {+ const mag = (rand() * 2 - 1) * d * scatter * 0.5;+ const perp = angleRad + Math.PI * 0.5;+ dx = Math.cos(perp) * mag;+ dy = Math.sin(perp) * mag;+ if (dyn?.scatterBothAxes) {+ const along = (rand() * 2 - 1) * d * scatter * 0.5;+ dx += Math.cos(angleRad) * along;+ dy += Math.sin(angleRad) * along;+ }+ }++ const px = x + dx;+ const py = y + dy;++ if (isSpray) {+ const particles = Math.max(3, Math.min(18, Math.round((bs.spray?.density ?? 3) * 2.2)));+ const rad = Math.max(2, d * 0.55);+ const pSizeBase = Math.max(0.75, (bs.spray?.particleSize ?? 3) * 0.42);+ ctx.globalAlpha = a * 0.78;+ for (let j = 0; j < particles; j++) {+ const ang = rand() * Math.PI * 2;+ const r = Math.sqrt(rand()) * rad;+ const pr = Math.max(0.6, pSizeBase * (0.45 + rand() * 0.9));+ ctx.beginPath();+ ctx.arc(px + Math.cos(ang) * r, py + Math.sin(ang) * r, pr, 0, Math.PI * 2);+ ctx.fill();+ }+ return;+ }++ let dynAngle = 0;+ switch (angleMode) {+ case 'direction':+ dynAngle = angleRad;+ break;+ case 'initial-direction':+ dynAngle = initialAngle;+ break;+ case 'random':+ dynAngle = (rand() * 2 - 1) * Math.PI * angleRandScale;+ break;+ case 'direction-random':+ dynAngle = angleRad + (rand() * 2 - 1) * Math.PI * angleRandScale;+ break;+ default:+ dynAngle = 0;+ }+ const rot = baseAngleRad + dynAngle + (rand() * 2 - 1) * Math.PI * angleJitter;++ const rx = Math.max(0.5, (thicknessVertical ? d * thickness : d) * 0.5);+ const ry = Math.max(0.5, (thicknessVertical ? d : d * thickness) * 0.5);++ if (hasTipImg && tipImg) {+ ctx.save();+ ctx.translate(px, py);+ ctx.rotate(rot);+ ctx.globalAlpha = a;+ ctx.drawImage(tintedTip || tipImg, -rx, -ry, rx * 2, ry * 2);+ ctx.restore();+ return;+ }++ if (hardness < 0.85 && rx > 2 && ry > 2 && typeof ctx.createRadialGradient === 'function') {+ ctx.save();+ ctx.translate(px, py);+ ctx.rotate(rot);+ ctx.scale(1, ry / rx);+ const grad = ctx.createRadialGradient(0, 0, rx * hardness * 0.72, 0, 0, rx);+ grad.addColorStop(0, strokeColor);+ grad.addColorStop(1, 'rgba(0,0,0,0)');+ ctx.globalAlpha = a;+ ctx.fillStyle = grad;+ ctx.beginPath();+ ctx.arc(0, 0, rx, 0, Math.PI * 2);+ ctx.fill();+ ctx.restore();+ return;+ }++ ctx.save();+ ctx.translate(px, py);+ ctx.rotate(rot);+ ctx.globalAlpha = a;+ ctx.beginPath();+ if (typeof ctx.ellipse === 'function') {+ ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2);+ } else {+ ctx.arc(0, 0, (rx + ry) * 0.5, 0, Math.PI * 2);+ }+ ctx.fill();+ if (wetEdge > 0.05 && rx > 2.5) {+ ctx.globalAlpha = a * wetEdge * 0.55;+ ctx.lineWidth = Math.max(0.8, (bs.wetEdgeRadius ?? 2) * 0.5);+ ctx.stroke();+ }+ ctx.restore();+ };++ if (naturalMode) {+ const strands = Math.max(6, Math.min(20, Math.round((bs.bristle?.count ?? 20) * 0.5)));+ const splay = clamp(bs.bristle?.splay ?? 0.35, 0, 1);+ let arcAcc = 0;+ for (let i = 1; i < pts.length; i++) {+ const p0 = pts[i - 1];+ const p1 = pts[i];+ const dx = p1.x - p0.x;+ const dy = p1.y - p0.y;+ const segLen = Math.hypot(dx, dy);+ if (segLen < 0.05) continue;+ const taper = evalTaperFactors(bs.taper, arcAcc + segLen * 0.5, totalLen);+ arcAcc += segLen;+ const nx = -dy / segLen;+ const ny = dx / segLen;+ const w0 = evalBrushWidth(bs, p0.pressure) * taper.size;+ const w1 = evalBrushWidth(bs, p1.pressure) * taper.size;+ const avgW = (w0 + w1) * 0.5 * (1 + splay * 0.25);+ for (let b = 0; b < strands; b++) {+ const frac = strands > 1 ? (b / (strands - 1)) * 2 - 1 : 0;+ const off = frac * avgW * 0.45;+ ctx.globalAlpha = clamp(+ flow * taper.opacity * (0.4 + 0.5 * (1 - Math.abs(frac) * 0.4)),+ 0.02,+ 1+ );+ ctx.lineWidth = Math.max(1.0, (avgW / strands) * 1.4);+ ctx.beginPath();+ ctx.moveTo(p0.x + nx * off, p0.y + ny * off);+ ctx.lineTo(p1.x + nx * off, p1.y + ny * off);+ ctx.stroke();+ }+ }+ ctx.restore();+ return;+ }++ // Single-point tap+ if (pts.length === 1 || totalLen < 0.25) {+ const p = pts[0];+ const diam = evalBrushWidth(bs, p.pressure);+ drawDab(p.x, p.y, diam, initialAngle, flow);+ ctx.restore();+ return;+ }++ // Exact arc-length carry-over dab stepping+ let arcAcc = 0;+ let residual = 0;+ const firstTaper = evalTaperFactors(bs.taper, 0, totalLen);+ drawDab(+ pts[0].x,+ pts[0].y,+ evalBrushWidth(bs, pts[0].pressure) * firstTaper.size,+ initialAngle,+ flow * firstTaper.opacity+ );++ for (let i = 1; i < pts.length; i++) {+ const p0 = pts[i - 1];+ const p1 = pts[i];+ const dx = p1.x - p0.x;+ const dy = p1.y - p0.y;+ const segLen = Math.hypot(dx, dy);+ if (segLen < 1e-4) continue;+ const segAngle = Math.atan2(dy, dx);++ let s = residual;+ let guard = 0;+ while (s <= segLen && guard < 1024) {+ guard++;+ const t = s / segLen;+ const x = p0.x + dx * t;+ const y = p0.y + dy * t;+ const pressure = p0.pressure + (p1.pressure - p0.pressure) * t;+ const taper = evalTaperFactors(bs.taper, arcAcc + s, totalLen);+ const diam = evalBrushWidth(bs, pressure) * taper.size;+ const step = Math.max(1.0, diam * spacingRatio);+ if (s > 0 || residual > 0) {+ drawDab(x, y, diam, segAngle, flow * taper.opacity);+ }+ s += step;+ }+ residual = Math.max(0, s - segLen);+ arcAcc += segLen;+ }++ ctx.restore();+}++/**+ * Re-renders all recorded scratchpad strokes cleanly onto `ctx` with stroke-level opacity+ * (matching CSP/DX12 stroke accumulation where opacity applies per stroke, not per dab).+ */+export function renderScratchpadStrokes2D(+ ctx: CanvasRenderingContext2D,+ width: number,+ height: number,+ strokes: RecordedScratchpadStroke[],+ bs: BrushSettings,+ activeColor: string+): void {+ ctx.clearRect(0, 0, width, height);+ if (strokes.length === 0) return;++ const strokeOpacity = clamp(bs.opacity ?? 1.0, 0.01, 1.0);+ const canOffscreen = typeof document !== 'undefined' && strokeOpacity < 0.995;++ if (!canOffscreen) {+ for (const stroke of strokes) {+ renderSingleScratchpadStroke2D(ctx, stroke, bs, activeColor);+ }+ return;+ }++ const off = document.createElement('canvas');+ off.width = width;+ off.height = height;+ const oCtx = off.getContext('2d');+ if (!oCtx) {+ for (const stroke of strokes) {+ renderSingleScratchpadStroke2D(ctx, stroke, bs, activeColor);+ }+ return;+ }++ for (const stroke of strokes) {+ oCtx.clearRect(0, 0, width, height);+ renderSingleScratchpadStroke2D(oCtx, stroke, bs, activeColor);+ ctx.save();+ ctx.globalAlpha = strokeOpacity;+ ctx.drawImage(off, 0, 0);+ ctx.restore();+ }+}