diff --git a/crates/engine/src/eval/masks.rs b/crates/engine/src/eval/masks.rs index 0cccc3e4ce6070a88daee74fee772855884dd97d..5cf784bc2723fa331270250aa40bcbc7d5afcab7 100644 --- a/crates/engine/src/eval/masks.rs +++ b/crates/engine/src/eval/masks.rs @@ -253,24 +253,81 @@ impl Engine { let soft_px = soft * size[0] as f32; let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); - let pixels = rasterize_polyline_mask( - size, - &points, - [center[0] as f32, center[1] as f32], - angle, - if need_post { false } else { invert }, - if need_post { 1.0 } else { level }, - ); - let post = need_post.then_some(MaskPost { - soft_px, - is_box, - clamp_edges, - paint_mode, - invert, - level, - prev: prev_mask.as_ref(), - }); - let tex = self.upload_cpu_mask(enc, size, key, &pixels, post); + let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key }); + + let has_coverage = match polyline_tight_commands(size, &points, [center[0] as f32, center[1] as f32], angle) { + Some(([bx0, by0, bx1, by1], cmds)) if raw_tex.size == size => { + let bw = (bx1 - bx0) as u32; + let bh = (by1 - by0) as u32; + let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)]; + let mut scratch = zeno::Scratch::new(); + let _ = zeno::Mask::with_scratch(&cmds, &mut scratch) + .size(bw, bh) + .origin(zeno::Origin::TopLeft) + .render_into(&mut cov_buf, None); + + let eff_level = if need_post { 1.0 } else { level }; + let mut rgba = vec![0u8; cov_buf.len() * 4]; + if (eff_level - 1.0).abs() <= 1e-6 { + for (dst, &cov) in rgba.chunks_exact_mut(4).zip(cov_buf.iter()) { + dst.fill(cov); + } + } else { + for (dst, &cov) in rgba.chunks_exact_mut(4).zip(cov_buf.iter()) { + let b = (cov as f32 * eff_level).clamp(0.0, 255.0) as u8; + dst.fill(b); + } + } + + if bw == size[0] && bh == size[1] { + self.queue.write_texture( + raw_tex.texture.as_image_copy(), + &rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bw * 4), rows_per_image: Some(bh) }, + wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, + ); + } else { + let small_tex = self.alloc_tex([bw, bh], BitDepth::Int8, 0); + self.queue.write_texture( + small_tex.texture.as_image_copy(), + &rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bw * 4), rows_per_image: Some(bh) }, + wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, + ); + clear_texture_transparent(enc, &raw_tex.view); + enc.copy_texture_to_texture( + small_tex.texture.as_image_copy(), + wgpu::TexelCopyTextureInfo { + texture: &raw_tex.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: bx0 as u32, y: by0 as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, + ); + } + true + } + _ => { + clear_texture_transparent(enc, &raw_tex.view); + false + } + }; + + let tex = if need_post { + let post = MaskPost { + soft_px: if has_coverage { soft_px } else { 0.0 }, + is_box, + clamp_edges, + paint_mode, + invert, + level, + prev: prev_mask.as_ref(), + }; + self.apply_mask_post(enc, size, key, raw_tex, post) + } else { + raw_tex + }; self.cache.insert(key, tex.clone(), node.id, frame_i); tex } @@ -314,20 +371,33 @@ impl Engine { pixels: &[u8], post: Option, ) -> CachedTexture { - let raw_tex = create_texture(&self.device, size, if post.is_some() { 0 } else { key }); + let raw_tex = self.alloc_tex(size, BitDepth::Int8, if post.is_some() { 0 } else { key }); self.queue.write_texture( raw_tex.texture.as_image_copy(), pixels, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size[0] * 4), rows_per_image: Some(size[1]) }, wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, ); - let Some(p) = post else { return raw_tex }; + match post { + Some(p) => self.apply_mask_post(enc, size, key, raw_tex, p), + None => raw_tex, + } + } + + fn apply_mask_post( + &self, + enc: &mut wgpu::CommandEncoder, + size: [u32; 2], + key: u64, + raw_tex: CachedTexture, + p: MaskPost, + ) -> CachedTexture { let blurred = if p.soft_px >= 0.5 { self.blur_mask_texture(enc, &raw_tex, p.soft_px, p.is_box, p.clamp_edges) } else { raw_tex }; - let combined = create_texture(&self.device, size, key); + let combined = self.alloc_tex(size, BitDepth::Int8, key); let mut u = UniformParams::default(); u.p[0] = [p.paint_mode, if p.invert { 1.0 } else { 0.0 }, p.level, if p.prev.is_some() { 1.0 } else { 0.0 }]; let mv = p.prev.map_or(&self.dummy.view, |m| &m.view); @@ -740,6 +810,122 @@ fn wand_flood_fill( out } +fn clear_texture_transparent(enc: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) { + let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("mask-clear"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); +} + +/// Builds `zeno` commands for a `PolylineMask` shifted into its tight pixel bounding box +/// `[bx0, by0, bx1, by1]` clamped to `[0..w, 0..h]`, returning `None` if empty or off-canvas. +fn polyline_tight_commands( + size: [u32; 2], + points: &[model::PolyPoint], + center: [f32; 2], + angle_deg: f32, +) -> Option<([i32; 4], Vec)> { + if points.len() < 2 || size[0] == 0 || size[1] == 0 { + return None; + } + let [w, h] = size; + let aspect = w as f32 / (h as f32).max(1.0); + let (s, c) = angle_deg.to_radians().sin_cos(); + let to_px = |x: f64, y: f64| -> [f32; 2] { + let (x, y) = (x as f32, y as f32 / aspect); + let (rx, ry) = (x * c - y * s, (x * s + y * c) * aspect); + [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] + }; + + let mut min_x = f32::INFINITY; + let mut min_y = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut max_y = f32::NEG_INFINITY; + let mut grow = |p: [f32; 2]| { + if p[0].is_finite() && p[1].is_finite() { + min_x = min_x.min(p[0]); + min_y = min_y.min(p[1]); + max_x = max_x.max(p[0]); + max_y = max_y.max(p[1]); + } + }; + + let mut cmds = Vec::with_capacity(points.len() + 2); + let p0 = to_px(points[0].x, points[0].y); + grow(p0); + cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); + for i in 0..points.len() { + let a = &points[i]; + let b = &points[(i + 1) % points.len()]; + let p = to_px(b.x, b.y); + grow(p); + if a.linear && b.linear { + cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1]))); + } else { + let c1 = to_px(a.x + a.rx, a.y + a.ry); + let c2 = to_px(b.x + b.lx, b.y + b.ly); + grow(c1); + grow(c2); + cmds.push(zeno::Command::CurveTo( + zeno::Vector::new(c1[0], c1[1]), + zeno::Vector::new(c2[0], c2[1]), + zeno::Vector::new(p[0], p[1]), + )); + } + } + cmds.push(zeno::Command::Close); + + if min_x > max_x || min_y > max_y { + return None; + } + let wi = w as i32; + let hi = h as i32; + let bx0 = (min_x.floor() as i32).saturating_sub(2).clamp(0, wi); + let by0 = (min_y.floor() as i32).saturating_sub(2).clamp(0, hi); + let bx1 = (max_x.ceil() as i32).saturating_add(2).clamp(0, wi); + let by1 = (max_y.ceil() as i32).saturating_add(2).clamp(0, hi); + if bx1 <= bx0 || by1 <= by0 { + return None; + } + + if bx0 != 0 || by0 != 0 { + let ox = bx0 as f32; + let oy = by0 as f32; + let shift = |v: &mut zeno::Vector| { + v.x -= ox; + v.y -= oy; + }; + for cmd in &mut cmds { + match cmd { + zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => shift(p), + zeno::Command::QuadTo(c, p) => { + shift(c); + shift(p); + } + zeno::Command::CurveTo(c1, c2, p) => { + shift(c1); + shift(c2); + shift(p); + } + zeno::Command::Close => {} + } + } + } + Some(([bx0, by0, bx1, by1], cmds)) +} + #[cfg(test)] mod tests { use super::*; @@ -974,4 +1160,160 @@ mod tests { let wand_chain = eng.readback_rgba(&t_wc).unwrap(); assert_eq!(wand_chain[3], 255); } + + #[test] + fn polyline_mask_tight_bbox_matches_full_canvas_across_invert_soft_edge_and_oob() { + let comp_src = r#"{ + Tools = ordered() { + PolySmall = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.65, 0.35 }, }, + Angle = Input { Value = 22.0, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -0.1, Y = -0.1 }, + { Linear = true, X = 0.12, Y = -0.05 }, + { Linear = true, X = 0.08, Y = 0.12 }, + { Linear = true, X = -0.08, Y = 0.1 }, + } + }, + }, + }, + }, + PolyInvertLevel = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.5, 0.5 }, }, + Invert = Input { Value = 1, }, + Level = Input { Value = 0.75, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -0.15, Y = -0.15 }, + { Linear = true, X = 0.15, Y = -0.15 }, + { Linear = true, X = 0.15, Y = 0.15 }, + { Linear = true, X = -0.15, Y = 0.15 }, + } + }, + }, + }, + }, + PolySoft = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + SoftEdge = Input { Value = 0.06, }, + ClippingMode = Input { Value = FuID { "None" }, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -0.1, Y = -0.1 }, + { Linear = true, X = 0.1, Y = -0.1 }, + { Linear = true, X = 0.1, Y = 0.1 }, + { Linear = true, X = -0.1, Y = 0.1 }, + } + }, + }, + }, + }, + PolyPartialOob = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -0.8, Y = -0.2 }, + { Linear = true, X = -0.2, Y = -0.2 }, + { Linear = true, X = -0.2, Y = 0.2 }, + { Linear = true, X = -0.8, Y = 0.2 }, + } + }, + }, + }, + }, + PolyAllOob = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = 1.2, Y = 0.0 }, + { Linear = true, X = 1.5, Y = 0.0 }, + { Linear = true, X = 1.5, Y = 0.3 }, + { Linear = true, X = 1.2, Y = 0.3 }, + } + }, + }, + }, + }, + PolyCoverAll = PolylineMask { + Inputs = { + MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -1.0, Y = -1.0 }, + { Linear = true, X = 1.0, Y = -1.0 }, + { Linear = true, X = 1.0, Y = 1.0 }, + { Linear = true, X = -1.0, Y = 1.0 }, + } + }, + }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse polyline comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let check_hard = |eng: &mut Engine, name: &str, center: [f32; 2], angle: f32, invert: bool, level: f32| { + let nid = comp.find_node(name).unwrap(); + let pts = Engine::polyline_points(&comp, comp.node(nid), 0.0); + let expected = rasterize_polyline_mask([96, 64], &pts, center, angle, invert, level); + let (tex, _) = eng.evaluate(&comp, nid, 0.0); + let got = eng.readback_rgba(&tex).unwrap(); + for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { + assert!(g.abs_diff(e) <= 1, "{name} byte {i}: got {g}, expected {e}"); + } + }; + + check_hard(&mut eng, "PolySmall", [0.65, 0.35], 22.0, false, 1.0); + check_hard(&mut eng, "PolyInvertLevel", [0.5, 0.5], 0.0, true, 0.75); + check_hard(&mut eng, "PolyPartialOob", [0.5, 0.5], 0.0, false, 1.0); + check_hard(&mut eng, "PolyAllOob", [0.5, 0.5], 0.0, false, 1.0); + check_hard(&mut eng, "PolyCoverAll", [0.5, 0.5], 0.0, false, 1.0); + + // SoftEdge > 0: compare GPU-blurred tight upload against full-canvas upload_cpu_mask. + let soft_id = comp.find_node("PolySoft").unwrap(); + let soft_pts = Engine::polyline_points(&comp, comp.node(soft_id), 0.0); + let full_raw = rasterize_polyline_mask([96, 64], &soft_pts, [0.5, 0.5], 0.0, false, 1.0); + let mut enc = eng.device.create_command_encoder(&Default::default()); + let ref_tex = eng.upload_cpu_mask( + &mut enc, + [96, 64], + 0, + &full_raw, + Some(MaskPost { + soft_px: 0.06 * 96.0, + is_box: false, + clamp_edges: 0.0, + paint_mode: 0.0, + invert: false, + level: 1.0, + prev: None, + }), + ); + eng.queue.submit(Some(enc.finish())); + let ref_px = eng.readback_rgba(&ref_tex).unwrap(); + let (soft_tex, _) = eng.evaluate(&comp, soft_id, 0.0); + let soft_px = eng.readback_rgba(&soft_tex).unwrap(); + assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel"); + } } diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index a680813bf96aae15edac07945034416ab6217dcf..345db022956e3e7a0562737c939f1e694c32fbcc 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -301,6 +301,61 @@ fn scale_text_chars_x( ([out_w as u32, tex_size[1]], [out_x0, origin[1]], out) } +// Keep `eval::mod`'s re-exported `media` symbols referenced across non-test targets without hitting +// the legacy full-canvas CPU path. +const _: fn([u32; 2], &TextPlusParams<'_>, i32) -> ([u32; 2], [i32; 2], Vec) = rasterize_text_plus; + +fn needs_canvas_aligned_text_output(comp: &Comp, node: &Node) -> bool { + let mut target_names: Vec<&str> = vec![node.name.as_str()]; + let mut seen = HashSet::new(); + seen.insert(node.id); + for _ in 0..4 { + let mut added = false; + for other in &comp.nodes { + if seen.contains(&other.id) { + continue; + } + let reads_target = other + .inputs + .values() + .any(|b| b.source_op.as_deref().is_some_and(|s| target_names.contains(&s))); + if !reads_target { + continue; + } + if other.bypassed || matches!(other.kind.as_str(), "PipeRouter" | "Fuse.Wireless") { + seen.insert(other.id); + target_names.push(other.name.as_str()); + added = true; + continue; + } + if matches!( + other.kind.as_str(), + "Fuse.Outline" + | "ErodeDilate" + | "Blur" + | "Glow" + | "SoftGlow" + | "InvertColor" + | "BrightnessContrast" + | "ColorCorrector" + | "Fuse.Colorize" + | "VariBlur" + | "Filter" + | "ColorCurves" + | "HueCurves" + | "ColorGain" + | "Custom" + ) { + return true; + } + } + if !added { + break; + } + } + false +} + impl Engine { #[allow(clippy::too_many_arguments)] pub(super) fn eval_p_render( @@ -443,7 +498,7 @@ impl Engine { time: f64, frame_i: i64, comp_dims: [u32; 2], - _enc: &mut wgpu::CommandEncoder, + enc: &mut wgpu::CommandEncoder, stats: &mut EvalStats, is_text3d: bool, ) -> CachedTexture { @@ -455,12 +510,15 @@ impl Engine { let ti = resolve_text_inputs(comp, node, time, is_text3d, &self.expr); let is_border_fill = ti.outline_enabled && ti.elem2_shape == 2; + let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); + let need_canvas = is_text3d || has_mask || needs_canvas_aligned_text_output(comp, node); let mut kh = DefaultHasher::new(); self.cache.gpu_salt.hash(&mut kh); self.cache.node_salt(node.id).hash(&mut kh); "TextPlus".hash(&mut kh); is_text3d.hash(&mut kh); + need_canvas.hash(&mut kh); ti.baseline_at_center.hash(&mut kh); size.hash(&mut kh); ti.text_str.hash(&mut kh); @@ -508,39 +566,7 @@ impl Engine { 0 }; let rich = ti.as_rich_params(); - let has_soft = ti.soft_fill != [0.0; 3] || ti.soft_outline != [0.0; 3]; - let (tex_size, origin, pixels) = if !is_text3d && ti.cls_rules.is_empty() && !has_soft { - let is_text_outline = ti.outline_enabled && ti.elem2_shape != 2; - let outline_width_px = if is_text_outline && ti.outline_thickness > 1e-4 { - (ti.outline_thickness * size_px).clamp(2.0, 56.0) - } else { - 0.0 - }; - rasterize_text_plus( - size, - &TextPlusParams { - text: &ti.text_str, - font_family: &ti.font_family, - font_style: &ti.font_style, - size_norm: ti.size_norm, - tracking: ti.tracking, - line_spacing: ti.line_spacing, - center: ti.center, - h_lcr: ti.h_lcr, - v_tcb: ti.v_tcb, - fill_rgba: ti.fill_rgba, - write_on_start: ti.write_start, - write_on_end: ti.write_end, - shear_x: ti.shear_x, - cls: &[], - outline_rgba: rich.outline_rgba, - outline_width_px, - }, - border_pad_px, - ) - } else { - crate::text_engine::rasterize_text_plus_rich(size, &rich, border_pad_px) - }; + let (tex_size, origin, pixels) = crate::text_engine::rasterize_text_plus_rich(size, &rich, border_pad_px); let (tex_size, origin, mut pixels) = if is_text3d && (ti.char_size_x - 1.0).abs() > 1e-4 { scale_text_chars_x(tex_size, origin, size, pixels, ti.char_size_x) } else { @@ -794,6 +820,11 @@ impl Engine { }, ); + let final_tex = if need_canvas && final_tex.has_dod() { + self.crop_to_canvas(enc, final_tex) + } else { + final_tex + }; self.cache.insert(key, final_tex.clone(), node.id, frame_i); final_tex } @@ -1401,4 +1432,66 @@ Composition { let cov = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count(); assert!(cov(&wide) > cov(&base) + 10, "CharacterSizeX=2.5 should increase coverage: {} vs {}", cov(&wide), cov(&base)); } + + #[test] + fn text_plus_tight_dod_merges_and_handles_outline_and_effect_mask() { + let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { + Bg = Background { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1, }, }, }, + Rect = RectangleMask { Inputs = { MaskWidth = Input { Value = 128, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, }, + Txt = TextPlus { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 64, }, + StyledText = Input { Value = "HI", }, + Size = Input { Value = 0.25, }, + }, + }, + TxtEmpty = TextPlus { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 64, }, + StyledText = Input { Value = "", }, + Size = Input { Value = 0.25, }, + }, + }, + TxtMasked = TextPlus { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 64, }, + StyledText = Input { Value = "HI", }, + Size = Input { Value = 0.25, }, + EffectMask = Input { SourceOp = "Rect", Source = "Mask", }, + }, + }, + M = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "Txt", Source = "Output", }, + }, + }, + ED = ErodeDilate { + Inputs = { + XAmount = Input { Value = 0.05, }, + Input = Input { SourceOp = "TxtMasked", Source = "Output", }, + }, + }, + } }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (t_m, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0); + let px_m = eng.readback_rgba(&t_m).unwrap(); + assert!(px_m.chunks_exact(4).any(|c| c[0] > 200 && c[3] == 255), "merged tight TextPlus must render white text"); + let (t_e, _) = eng.evaluate(&comp, comp.find_node("TxtEmpty").unwrap(), 0.0); + assert_eq!(t_e.size, [128, 64]); + let px_e = eng.readback_rgba(&t_e).unwrap(); + assert!(px_e.iter().all(|&b| b == 0), "empty TextPlus must be transparent"); + let (t_ed, _) = eng.evaluate(&comp, comp.find_node("ED").unwrap(), 0.0); + assert_eq!(t_ed.size, [128, 64]); + let px_ed = eng.readback_rgba(&t_ed).unwrap(); + let cov_ed = px_ed.chunks_exact(4).filter(|c| c[3] > 200).count(); + let (t_tm, _) = eng.evaluate(&comp, comp.find_node("TxtMasked").unwrap(), 0.0); + let px_tm = eng.readback_rgba(&t_tm).unwrap(); + let cov_tm = px_tm.chunks_exact(4).filter(|c| c[3] > 200).count(); + assert!(cov_ed > cov_tm + 50, "ErodeDilate downstream of TextPlus must dilate using canvas width: {cov_ed} vs {cov_tm}"); + } } diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index 2038f4642f20c2e67b8d27b23ff36f8a8c108d02..8025cc801c46bb9d276a9fa418a2d63c910e3d4c 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -657,71 +657,118 @@ fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec) { fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32, sigma_y: f32) { let (rx, kx) = gaussian_kernel_1d(sigma_x); - if rx > 0 { - let mut tmp = vec![0.0_f32; w * h]; + let (ry, ky) = gaussian_kernel_1d(sigma_y); + if rx <= 0 && ry <= 0 { + return; + } + let mut tmp = vec![0.0_f32; w * h]; + let src_is_tmp = if rx > 0 { + let r = rx as usize; + let klen = kx.len(); + let mid_end = w.saturating_sub(r); + let left_end = r.min(w); + let right_start = mid_end.max(left_end); for y in 0..h { let row = &plane[y * w..(y + 1) * w]; let dst = &mut tmp[y * w..(y + 1) * w]; - for x in 0..w { + for x in 0..left_end { + let k_start = r - x; + let k_end = (w + r - x).min(klen); + let s_start = x + k_start - r; let mut acc = 0.0_f32; - let xi = x as isize; - for (ki, &kw) in kx.iter().enumerate() { - let sx = xi + (ki as isize - rx); - if sx >= 0 && sx < w as isize { - acc += row[sx as usize] * kw; - } + for (&s, &kw) in row[s_start..s_start + (k_end - k_start)].iter().zip(&kx[k_start..k_end]) { + acc += s * kw; + } + dst[x] = acc; + } + for x in left_end..mid_end { + let win = &row[x - r..x + r + 1]; + let mut acc = 0.0_f32; + for (&s, &kw) in win.iter().zip(kx.iter()) { + acc += s * kw; + } + dst[x] = acc; + } + for x in right_start..w { + let k_end = w + r - x; + let mut acc = 0.0_f32; + for (&s, &kw) in row[x - r..w].iter().zip(&kx[..k_end]) { + acc += s * kw; } dst[x] = acc; } } - plane.copy_from_slice(&tmp); - } - let (ry, ky) = gaussian_kernel_1d(sigma_y); + true + } else { + false + }; + if ry > 0 { - let mut tmp = vec![0.0_f32; w * h]; + let (src_buf, dst_buf): (&[f32], &mut [f32]) = if src_is_tmp { + (&tmp, plane) + } else { + tmp.copy_from_slice(plane); + (&tmp, plane) + }; + dst_buf.fill(0.0); + let klen = ky.len() as isize; for y in 0..h { let yi = y as isize; - for x in 0..w { - let mut acc = 0.0_f32; - for (ki, &kw) in ky.iter().enumerate() { - let sy = yi + (ki as isize - ry); - if sy >= 0 && sy < h as isize { - acc += plane[sy as usize * w + x] * kw; - } + let k_start = (ry - yi).max(0) as usize; + let k_end = ((h as isize + ry - yi).min(klen)).max(0) as usize; + let dst_row = &mut dst_buf[y * w..(y + 1) * w]; + for (ki, &kw) in ky[k_start..k_end].iter().enumerate() { + let sy = (yi + (k_start + ki) as isize - ry) as usize; + let src_row = &src_buf[sy * w..(sy + 1) * w]; + for (d, &s) in dst_row.iter_mut().zip(src_row.iter()) { + *d += s * kw; } - tmp[y * w + x] = acc; } } + } else if src_is_tmp { plane.copy_from_slice(&tmp); } } fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) { - for y in 0..c.height as i32 { - let py = c.top + y - origin[1]; - if py < 0 || py >= th as i32 { - continue; - } - for x in 0..c.width as i32 { - let px = c.left + x - origin[0]; - let a = c.data[(y as u32 * c.width + x as u32) as usize]; - if a > 0 && px >= 0 && px < tw as i32 { - let idx = py as usize * tw + px as usize; - plane[idx] = plane[idx].max(a as f32 / 255.0); + let cw = c.width as i32; + let ch = c.height as i32; + let x0 = (origin[0] - c.left).max(0); + let y0 = (origin[1] - c.top).max(0); + let x1 = (origin[0] + tw as i32 - c.left).min(cw); + let y1 = (origin[1] + th as i32 - c.top).min(ch); + if x0 >= x1 || y0 >= y1 { + return; + } + let span = (x1 - x0) as usize; + let dst_x0 = (c.left + x0 - origin[0]) as usize; + for y in y0..y1 { + let py = (c.top + y - origin[1]) as usize; + let src_start = y as usize * c.width as usize + x0 as usize; + let src_row = &c.data[src_start..src_start + span]; + let dst_start = py * tw + dst_x0; + let dst_row = &mut plane[dst_start..dst_start + span]; + for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) { + if a > 0 { + *d = d.max(a as f32 / 255.0); } } } } /// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and -/// Element 1/2 Softness blur + glow. +/// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer. pub fn rasterize_text_plus_rich( dims: [u32; 2], params: &RichTextPlusParams<'_>, dod_pad: i32, ) -> ([u32; 2], [i32; 2], Vec) { let [w, h] = dims; - let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + let empty = || ([1u32, 1u32], [0i32, 0i32], vec![0u8; 4]); + let has_outline = params.outline_enabled && params.outline_rgba[3] > 0.0; + if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 { + return empty(); + } let Some((glyphs, _)) = layout_glyphs(dims, params) else { return empty(); }; @@ -737,24 +784,25 @@ pub fn rasterize_text_plus_rich( let sx2 = clamp_sigma(params.soft_outline[0]); let sy2 = clamp_sigma(params.soft_outline[1]); let blur_pad = (sx1.max(sy1).max(sx2).max(sy2) * 3.0).ceil().clamp(0.0, 64.0) as i32; - let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad); + // Keep at least a 1px transparent apron around glyphs so GPU bilinear filtering never clamps non-zero edge alpha. + let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); let mut grow = |c: &Coverage, pad: i32| { - min_x = min_x.min(c.left - pad); - min_y = min_y.min(c.top - pad); - max_x = max_x.max(c.left + c.width as i32 + pad); - max_y = max_y.max(c.top + c.height as i32 + pad); + min_x = min_x.min(c.left.saturating_sub(pad)); + min_y = min_y.min(c.top.saturating_sub(pad)); + max_x = max_x.max((c.left + c.width as i32).saturating_add(pad)); + max_y = max_y.max((c.top + c.height as i32).saturating_add(pad)); }; - let has_outline = params.outline_enabled && params.outline_rgba[3] > 0.0; let mut placed = Vec::with_capacity(glyphs.len()); let mut any_outline = false; for g in &glyphs { let f = fill(&g.commands); let l = if has_outline && g.outline_w > 1e-3 { - any_outline = true; - stroke(&g.commands, g.outline_w) + let s = stroke(&g.commands, g.outline_w); + any_outline |= s.is_some(); + s } else { None }; @@ -766,13 +814,19 @@ pub fn rasterize_text_plus_rich( } placed.push((f, l)); } + if min_x > max_x || min_y > max_y { + return empty(); + } let origin_x = min_x.max(-(w as i32)); let origin_y = min_y.max(-(h as i32)); let end_x = max_x.min((w as i32) * 2); let end_y = max_y.min((h as i32) * 2); - let tw = (end_x - origin_x).max(1) as usize; - let th = (end_y - origin_y).max(1) as usize; + if end_x <= origin_x || end_y <= origin_y { + return empty(); + } + let tw = (end_x - origin_x) as usize; + let th = (end_y - origin_y) as usize; let mut fill_plane = vec![0.0_f32; tw * th]; let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }]; @@ -796,22 +850,33 @@ pub fn rasterize_text_plus_rich( let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999)); let (fc, oc) = (params.fill_rgba, params.outline_rgba); let mut out = vec![0u8; tw * th * 4]; - for (i, px) in out.chunks_exact_mut(4).enumerate() { - let fa = (fill_plane[i] * fc[3] * glow1).clamp(0.0, 1.0); - let oa = if any_outline { - (line_plane[i] * oc[3] * glow2).clamp(0.0, 1.0) - } else { - 0.0 - }; - if fa <= 0.0 && oa <= 0.0 { - continue; + if any_outline { + let f_scale = fc[3] * glow1; + let o_scale = oc[3] * glow2; + for (i, px) in out.chunks_exact_mut(4).enumerate() { + let fa = (fill_plane[i] * f_scale).clamp(0.0, 1.0); + let oa = (line_plane[i] * o_scale).clamp(0.0, 1.0); + if fa <= 0.0 && oa <= 0.0 { + continue; + } + let under = 1.0 - fa; + px[0] = ((fc[0] * fa + oc[0] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[1] = ((fc[1] * fa + oc[1] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[2] = ((fc[2] * fa + oc[2] * oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; } - let under = 1.0 - fa; - for k in 0..3 { - let v = fc[k] * fa + oc[k] * oa * under; - px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + } else { + let f_scale = fc[3] * glow1; + for (i, px) in out.chunks_exact_mut(4).enumerate() { + let fa = (fill_plane[i] * f_scale).clamp(0.0, 1.0); + if fa <= 0.0 { + continue; + } + px[0] = (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[1] = (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[2] = (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + px[3] = (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8; } - px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; } ([tw as u32, th as u32], [origin_x, origin_y], out) } @@ -1700,4 +1765,195 @@ mod tests { let resolved = Font::find("FissionRuntimeAliasFont", "Regular").expect("registered alias font"); assert!(resolved.face().glyph_index('A').is_some()); } + + #[test] + fn tight_dod_empty_whitespace_and_zero_alpha_return_1x1_transparent() { + let mut p = RichTextPlusParams { + text: "", + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0; 4], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.0; 4], + outline_thickness_norm: 0.0, + outline_enabled: false, + soft_fill: [0.0; 3], + soft_outline: [0.0; 3], + baseline_at_center: false, + }; + assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0])); + p.text = " "; + assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0])); + p.text = "AB"; + p.write_on_end = 0.0; + assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0])); + p.write_on_end = 1.0; + p.fill_rgba[3] = 0.0; + assert_eq!(rasterize_text_plus_rich([640, 360], &p, 0), ([1, 1], [0, 0], vec![0, 0, 0, 0])); + } + + #[test] + fn tight_dod_text_plus_matches_full_canvas_across_cls_outline_and_softness() { + let dims = [640u32, 360u32]; + let composite_onto_canvas = |sz: [u32; 2], orig: [i32; 2], rgba: &[u8]| -> Vec { + let mut canvas = vec![0u8; (dims[0] * dims[1] * 4) as usize]; + for y in 0..sz[1] as i32 { + let cy = orig[1] + y; + if cy < 0 || cy >= dims[1] as i32 { + continue; + } + for x in 0..sz[0] as i32 { + let cx = orig[0] + x; + if cx < 0 || cx >= dims[0] as i32 { + continue; + } + let si = ((y as u32 * sz[0] + x as u32) * 4) as usize; + let di = ((cy as u32 * dims[0] + cx as u32) * 4) as usize; + canvas[di..di + 4].copy_from_slice(&rgba[si..si + 4]); + } + } + canvas + }; + + // 1. Plain + outline vs legacy full-canvas `rasterize_text_plus`. + let p_legacy = TextPlusParams { + text: "Hello", + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0, 0.9, 0.8, 1.0], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.2, 0.4, 1.0, 0.8], + outline_width_px: (0.04_f32 * 0.08 * 640.0).clamp(1.0, 128.0), + }; + let (lsz, lorig, lrgba) = rasterize_text_plus(dims, &p_legacy, 0); + let p_rich = RichTextPlusParams { + text: "Hello", + font_family: "Liberation Sans", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0, 0.9, 0.8, 1.0], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.2, 0.4, 1.0, 0.8], + outline_thickness_norm: 0.04, + outline_enabled: true, + soft_fill: [0.0; 3], + soft_outline: [0.0; 3], + baseline_at_center: false, + }; + let (tsz, torig, trgba) = rasterize_text_plus_rich(dims, &p_rich, 0); + assert!(tsz[0] < dims[0] && tsz[1] < dims[1], "expected tight DoD, got {tsz:?}"); + assert!(torig[0] > 0 && torig[1] > 0, "expected non-zero tight origin, got {torig:?}"); + let tight_canvas = composite_onto_canvas(tsz, torig, &trgba); + let legacy_canvas = composite_onto_canvas(lsz, lorig, &lrgba); + for (i, (&a, &b)) in tight_canvas.iter().zip(legacy_canvas.iter()).enumerate() { + assert!(a.abs_diff(b) <= 4, "legacy parity diff at byte {i}: {a} vs {b}"); + } + let (psz_plain, porig_plain, prgba_plain) = rasterize_text_plus_rich(dims, &p_rich, 80); + assert_eq!(tight_canvas, composite_onto_canvas(psz_plain, porig_plain, &prgba_plain)); + + // 2. CLS offsets + Softness blur: tight bbox matches full-plane blur pixel-for-pixel. + let cls = [ + StyledClsRule { prop_id: 1350, start: 1, end: 1, value: 0.04, text: String::new() }, + StyledClsRule { prop_id: 1351, start: 2, end: 2, value: -0.03, text: String::new() }, + StyledClsRule { prop_id: 102, start: 3, end: 3, value: 0.12, text: String::new() }, + ]; + let p_soft = RichTextPlusParams { + cls: &cls, + soft_fill: [3.0, 2.5, 0.25], + soft_outline: [4.0, 3.0, 0.4], + ..p_rich + }; + let (ssz, sorig, srgba) = rasterize_text_plus_rich(dims, &p_soft, 0); + assert!(ssz[0] < dims[0] && ssz[1] < dims[1], "expected tight soft DoD, got {ssz:?}"); + // Padded extra 40px must yield identical canvas pixels because blur tail already decays to 0 inside 3*sigma. + let (psz, porig, prgba) = rasterize_text_plus_rich(dims, &p_soft, 40); + assert_eq!( + composite_onto_canvas(ssz, sorig, &srgba), + composite_onto_canvas(psz, porig, &prgba) + ); + } + + #[test] + fn separable_gaussian_fast_path_matches_naive_reference() { + let w = 29usize; + let h = 23usize; + let mut init = vec![0.0_f32; w * h]; + for y in 0..h { + for x in 0..w { + init[y * w + x] = (((x * 7 + y * 13) % 19) as f32) / 18.0; + } + } + let naive = |src: &[f32], sx: f32, sy: f32| -> Vec { + let mut p = src.to_vec(); + let (rx, kx) = gaussian_kernel_1d(sx); + if rx > 0 { + let mut tmp = vec![0.0_f32; w * h]; + for y in 0..h { + for x in 0..w { + let mut acc = 0.0_f32; + for (ki, &kw) in kx.iter().enumerate() { + let ix = x as isize + ki as isize - rx; + if ix >= 0 && ix < w as isize { + acc += p[y * w + ix as usize] * kw; + } + } + tmp[y * w + x] = acc; + } + } + p = tmp; + } + let (ry, ky) = gaussian_kernel_1d(sy); + if ry > 0 { + let mut tmp = vec![0.0_f32; w * h]; + for y in 0..h { + for x in 0..w { + let mut acc = 0.0_f32; + for (ki, &kw) in ky.iter().enumerate() { + let iy = y as isize + ki as isize - ry; + if iy >= 0 && iy < h as isize { + acc += p[iy as usize * w + x] * kw; + } + } + tmp[y * w + x] = acc; + } + } + p = tmp; + } + p + }; + for (sx, sy) in [(2.3, 1.7), (3.1, 0.0), (0.0, 2.8)] { + let mut fast = init.clone(); + apply_separable_gaussian(&mut fast, w, h, sx, sy); + let ref_buf = naive(&init, sx, sy); + for (a, b) in fast.iter().zip(ref_buf.iter()) { + assert!((a - b).abs() < 1e-6, "mismatch for ({sx}, {sy}): {a} vs {b}"); + } + } + } }