From 5418fcbf7b95efd34ffb98b48e1221650cbb33d4 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Sat, 5 Dec 2026 09:09:36 -0800 Subject: [PATCH] Check the GPU's effects analytically instead of against the CPU baking --- .github/workflows/check.yml | 2 + Cargo.lock | 2 + .../raster-kernels/src/value_effects.rs | 17 +- .../libraries/wgpu-executor/src/context.rs | 3 +- node-graph/libraries/wgpu-executor/src/lib.rs | 6 + .../wgpu-executor/src/vello_render/tests.rs | 3552 ++++++++++++----- node-graph/nodes/blending/Cargo.toml | 7 + node-graph/nodes/blending/src/effects.rs | 17 +- node-graph/nodes/blending/src/masks.rs | 32 +- .../nodes/gstd/src/platform_application_io.rs | 2 +- node-graph/nodes/gstd/src/render_cache.rs | 20 +- .../gstd/src/render_node/svg_readback.rs | 8 +- node-graph/nodes/raster/src/adjustments.rs | 12 +- node-graph/nodes/raster/src/channels.rs | 2 +- node-graph/preprocessor/src/readback_tests.rs | 2 +- 15 files changed, 2582 insertions(+), 1102 deletions(-) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 47c5b387e4..6324b3a60f 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -176,6 +176,8 @@ jobs: env: # `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml` RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis" + # GPU tests made through `for_tests()` fail rather than skip when the software Vulkan driver above can't make a device + WGPU_BACKEND: vulkan # The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features` run: >- cargo test --workspace --all-features diff --git a/Cargo.lock b/Cargo.lock index 65d18b2639..479862b08d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -585,6 +585,7 @@ name = "blending-nodes" version = "0.0.0" dependencies = [ "core-types", + "futures", "glam", "graphic-types", "node-macro", @@ -592,6 +593,7 @@ dependencies = [ "serde", "text-nodes", "vector-types", + "wgpu-executor", ] [[package]] diff --git a/node-graph/libraries/raster-kernels/src/value_effects.rs b/node-graph/libraries/raster-kernels/src/value_effects.rs index 27305c88d4..49c0ea8467 100644 --- a/node-graph/libraries/raster-kernels/src/value_effects.rs +++ b/node-graph/libraries/raster-kernels/src/value_effects.rs @@ -480,10 +480,8 @@ mod tests { #[test] fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() { - use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels}; use graphic_types::EffectKind; use graphic_types::blend_if::BlendIfRanges; - use raster_types::{Image, Raster}; // Shown only where the gray is at least half let mut hides_darks = BlendIfRanges::default(); @@ -497,15 +495,8 @@ mod tests { opacity: 100., }); - // Black consumed as a color, which agrees with a raster's pixel of it - let black_through = |name: &str, rows: &[(EffectOperation, f64)]| { - let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element(); - let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows)); - let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT); - let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel)); - assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}"); - color - }; + // Black consumed as a color, which the GPU's render of a raster of it agrees with (`blend_ifs_hide_rasters_through_adjustments_raising_alpha_as_they_hide_values` in wgpu-executor) + let black_through = |rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(Color::BLACK, rows)).element(); // Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either let hidden = [ @@ -514,11 +505,11 @@ mod tests { ("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]), ]; for (name, rows) in hidden { - assert_eq!(black_through(name, &rows).a(), 0., "black {name}"); + assert_eq!(black_through(&rows).a(), 0., "black {name}"); } // In its own run, an overlay still paints within the full-strength black - let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]); + let painted = black_through(&[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]); assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted)); // A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next diff --git a/node-graph/libraries/wgpu-executor/src/context.rs b/node-graph/libraries/wgpu-executor/src/context.rs index 407f6b2225..3189868f33 100644 --- a/node-graph/libraries/wgpu-executor/src/context.rs +++ b/node-graph/libraries/wgpu-executor/src/context.rs @@ -21,8 +21,7 @@ impl Context { } /// The context the GPU tests run on, which wgpu's environment variables can aim at each backend and shader compiler in turn. - #[cfg(test)] - pub(crate) async fn for_tests() -> Option { + pub async fn for_tests() -> Option { let context = ContextBuilder::new().with_environment_overrides().build().await; // A backend asked for by name fails the tests if it can't run them, rather than passing them all as skipped diff --git a/node-graph/libraries/wgpu-executor/src/lib.rs b/node-graph/libraries/wgpu-executor/src/lib.rs index 8db4b0d22e..fb91c2d8e4 100644 --- a/node-graph/libraries/wgpu-executor/src/lib.rs +++ b/node-graph/libraries/wgpu-executor/src/lib.rs @@ -199,6 +199,12 @@ impl WgpuExecutor { Self::with_context(WgpuContext::new().await?) } + /// The executor GPU tests run on, on the context [`WgpuContext::for_tests`] makes, or `None` without a GPU. + #[cfg(not(target_family = "wasm"))] + pub async fn for_tests() -> Option { + Self::with_context(WgpuContext::for_tests().await?) + } + pub fn with_context(context: WgpuContext) -> Option { let vello_renderer = VelloRenderer::new(&context.device, &context.adapter); diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 04f8d0a176..ce8092345c 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -41,6 +41,37 @@ fn render_in_view(size: UVec2, view: DAffine2, mut draw: impl FnMut(&mut VelloSc Some(pixels.as_chunks::<4>().0.to_vec()) } +/// Like [`render_in_view`], into premultiplied colors in the precise format that effects' paints, such as displacement maps, are drawn in. `None` without a GPU. +fn render_precise_in_view(size: UVec2, view: DAffine2, mut draw: impl FnMut(&mut VelloSceneBuilder)) -> Option> { + let executor = executor()?; + let _turn = take_turn(); + + let renderer = &executor.inner.vello_renderer; + let texture = executor.request_texture_with_format(size, renderer.precise_format); + { + let mut canvas = executor.inner.document_canvas.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + canvas.images.render_count += 1; + let mut context = super::RenderContext { + renderer, + canvas: &mut canvas, + device: &executor.context().device, + queue: &executor.context().queue, + failure: None, + }; + context.render_area(&mut draw, Affine::new(view.to_cols_array()), size, &texture, super::TargetAlpha::Premultiplied); + canvas.images.free_unused(); + canvas.effect_textures.finish_render(); + } + + let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the render"); + let channels: Vec = match renderer.precise_format { + wgpu::TextureFormat::Rgba16Unorm => bytes.as_chunks::<2>().0.iter().map(|&bytes| u16::from_le_bytes(bytes) as f32 / 65_535.).collect(), + wgpu::TextureFormat::Rgba16Float => bytes.as_chunks::<2>().0.iter().map(|&bytes| half::f16::from_le_bytes(bytes).to_f32()).collect(), + _ => bytes.iter().map(|&byte| byte as f32 / 255.).collect(), + }; + Some(channels.as_chunks::<4>().0.to_vec()) +} + /// Renders the scene `draw` draws into straight-alpha RGBA8 pixels, with how long the render and its readback took, or `None` without a GPU. fn render_timed(size: UVec2, mut draw: impl FnMut(&mut VelloSceneBuilder)) -> Option<(Vec<[u8; 4]>, std::time::Duration)> { let executor = executor()?; @@ -707,6 +738,24 @@ fn render_square_over_backdrop_in( min: f64, max: f64, size: UVec2, +) -> Option> { + render_square_over_backdrop_in_view(effects, effect_space, DAffine2::IDENTITY, fill, opacity, blend_mode, backdrop, content, min, max, size) +} + +/// Like [`render_square_over_backdrop_in`], rendering through a `view` from the document into the render's pixels. +#[expect(clippy::too_many_arguments)] +fn render_square_over_backdrop_in_view( + effects: Vec, + effect_space: DAffine2, + view: DAffine2, + fill: f32, + opacity: f32, + blend_mode: core_types::blending::BlendMode, + backdrop: Option, + content: Color, + min: f64, + max: f64, + size: UVec2, ) -> Option> { use rendering::{Render, RenderParams}; @@ -722,9 +771,11 @@ fn render_square_over_backdrop_in( let effects = graphic_types::Effects::from_operations(effects); let frame = graphic_types::resampling::frame_of_bounds([glam::DVec2::splat(min), glam::DVec2::splat(max)], DAffine2::IDENTITY); - render(size, |scene| { + let view_bounds = graphic_types::resampling::frame_of_bounds([glam::DVec2::ZERO, size.as_dvec2()], view.inverse()); + render_in_view(size, view, |scene| { if let Some(backdrop) = backdrop { - scene.fill(Fill::NonZero, Affine::IDENTITY, backdrop, None, &Rect::new(0., 0., size.x as f64, size.y as f64)); + let [min, max] = [glam::DVec2::ZERO, glam::DVec2::ONE].map(|corner| view_bounds.transform_point2(corner)); + scene.fill(Fill::NonZero, Affine::IDENTITY, backdrop, None, &Rect::new(min.x, min.y, max.x, max.y)); } scene.draw_effects( &effects, @@ -1069,7 +1120,7 @@ fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() { } #[test] -fn satins_reshape_each_cast_by_the_contour_before_comparing_them_on_the_cpu_gpu_and_svg() { +fn satins_reshape_each_cast_by_the_contour_before_comparing_them_on_the_gpu_and_in_svg() { use core_types::list::{Item, List}; use core_types::transfer_curve::TransferCurve; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; @@ -1110,9 +1161,6 @@ fn satins_reshape_each_cast_by_the_contour_before_comparing_them_on_the_cpu_gpu_ let mut item = Item::new_from_element(Raster::new_cpu(Image { width, height, data: data.clone() })).with_attribute(ATTR_TRANSFORM, placement); stamp_effect(&mut item, Effect::new(&satin)); - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 2, "with invert {invert}, the CPU and GPU differ by up to {worst} levels"); - // Black shading over opaque white leaves 1 minus its strength let Some(gpu) = render_raster(item.clone(), size) else { return }; for (column, strength) in opaque_columns.into_iter().zip(strengths) { @@ -1124,6 +1172,18 @@ fn satins_reshape_each_cast_by_the_contour_before_comparing_them_on_the_cpu_gpu_ ); } + // Shading within the content, it leaves every column's alpha as it is and paints nothing past the content + for (column, &alpha) in alphas.iter().enumerate() { + let shown = pixel(&gpu, size, corner.x + column as u32, corner.y + 1)[3]; + let expected = (alpha * 255.).round() as u8; + assert!(shown.abs_diff(expected) <= 1, "with invert {invert}, column {column} shows an alpha of {shown} rather than {expected}"); + } + let past = (0..size.x * size.y).filter(|index| { + let (x, y) = (index % size.x, index / size.x); + !(corner.x..corner.x + width).contains(&x) || !(corner.y..corner.y + height).contains(&y) + }); + assert!(past.into_iter().all(|index| gpu[index as usize][3] == 0), "with invert {invert}, the satin paints past the content"); + // SVG shades by the GPU's map of the strength, captured in black let mut svg = SvgRender::new(); let export = RenderParams { @@ -1193,20 +1253,18 @@ fn convolution_kernels_filter_endless_gradients_and_colors() { } #[test] -fn random_fields_match_the_cpu_zoomed_out_and_away_from_the_origin() { +fn random_fields_stay_with_the_content_away_from_the_origin_and_average_their_cells_zoomed_out() { use core_types::list::Item; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::filters::{GAUSSIAN_NOISE_LIMIT, RandomField, noise_extent}; use graphic_types::raster_types::{Image, Raster}; use graphic_types::{Effect, EffectOperation, Graphic, NoiseDistribution, stamp_effect}; - use raster_kernels::evaluate_raster_effects; use rendering::{Render, RenderParams}; - let Some(executor) = executor() else { return }; - - // A raster whose pixels each span two document pixels, far out on the negative side of the origin, rendered one texel per pixel, so each takes four samples - let (width, origin) = (32, glam::DVec2::new(-1000., -600.)); - let placement = DAffine2::from_translation(origin) * DAffine2::from_scale(glam::DVec2::splat(2. * width as f64)); - let view = DAffine2::from_scale(glam::DVec2::splat(0.5)) * DAffine2::from_translation(-origin); + // A raster whose pixels each span two document pixels, at the origin or far out on its negative side + let width = 32; + let far = DVec2::new(-1000., -600.); let noise = |amount, distribution, monochromatic| EffectOperation::Speckle { amount, distribution, @@ -1220,35 +1278,97 @@ fn random_fields_match_the_cpu_zoomed_out_and_away_from_the_origin() { ]; for operation in operations { - let image = Image::new(width, width, GraphicColor::from_gamma_srgb_channels(0.4, 0.6, 0.5, 1.)); - let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, placement); - stamp_effect(&mut item, Effect::new(&operation)); + // The raster with its corner at `origin`, rendered from there at `scale` pixels to each document pixel + let draw = |origin: DVec2, scale: f64| { + let image = Image::new(width, width, GraphicColor::from_gamma_srgb_channels(0.4, 0.6, 0.5, 1.)); + let placement = DAffine2::from_translation(origin) * DAffine2::from_scale(DVec2::splat(2. * width as f64)); + let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, placement); + stamp_effect(&mut item, Effect::new(&operation)); - let graphic = Graphic::RasterCPU(Box::new(item.clone())); - let gpu = { - let _turn = take_turn(); - let texture = executor - .render_vello(UVec2::splat(width), view, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) - .expect("the render succeeds"); - executor.read_texture_pixels(&texture).expect("the render reads back") + let graphic = Graphic::RasterCPU(Box::new(item)); + let view = DAffine2::from_scale(DVec2::splat(scale)) * DAffine2::from_translation(-origin); + render_in_view(UVec2::splat((2. * width as f64 * scale) as u32), view, |scene| { + graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()) + }) + }; + let (Some(at_origin), Some(far_away), Some(zoomed_out)) = (draw(DVec2::ZERO, 1.), draw(far, 1.), draw(far, 0.5)) else { + return; }; - // Compared premultiplied, so a nearly transparent pixel's color can't dominate - let evaluated = evaluate_raster_effects(item); - let mut worst = 0; - for (cpu, gpu) in evaluated.element().data.iter().zip(gpu.as_chunks::<4>().0) { - let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels(); - let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); - let gpu_alpha = gpu[3] as f32 / 255.; - for channel in 0..4 { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); + // The field lies on the content, so it's the same wherever the content lies + assert!(at_origin == far_away, "{operation:?} changes as the content moves away from the origin"); + + // Zoomed out to a texel for each pixel, each pixel takes the mean of the four cells the field shows across it at full size, compared premultiplied. + // Noise offsets a color by the mean of its cells' noise, which the colors show only where none of them is clipped to black or white. + let full_size = UVec2::splat(2 * width); + let (mut worst, mut compared) = (0_f32, 0); + for (x, y) in (0..width).flat_map(|y| (0..width).map(move |x| (x, y))) { + let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(right, down)| pixel(&far_away, full_size, 2 * x + right, 2 * y + down)); + let clipped = quad.iter().any(|cell| cell[..3].iter().any(|&channel| channel == 0 || channel == 255)); + if matches!(operation, EffectOperation::Speckle { .. }) && clipped { + continue; } + + let mean: [f32; 4] = std::array::from_fn(|channel| quad.iter().map(|&cell| premultiplied_levels(cell)[channel]).sum::() / 4.); + let shown = premultiplied_levels(pixel(&zoomed_out, UVec2::splat(width), x, y)); + worst = (0..4).map(|channel| (mean[channel] - shown[channel]).abs()).fold(worst, f32::max); + compared += 1; } - assert!(worst <= 2, "{operation:?} differs from the GPU by up to {worst} levels"); + assert!(compared >= 500, "{operation:?} clips the colors of all but {compared} pixels"); + assert!(worst <= 2., "{operation:?} zoomed out differs from the mean of its cells by up to {worst} levels"); + + // At full size, each pixel shows its own cell (a document pixel from the content's corner), whose seeded values give its color by the operation's definition + let content = [0.4_f32, 0.6, 0.5]; + let expected = |cell: glam::IVec2| -> [f32; 4] { + match operation { + EffectOperation::Speckle { + amount, + distribution, + monochromatic, + seed, + } => { + let amount = amount / 100.; + let extent = noise_extent(amount, distribution) as f32; + let offsets = random_field_values(cell, RandomField::NoiseOffsets.seed(seed)); + let noise = match distribution { + NoiseDistribution::Uniform => offsets.map(|offset| 2. * offset - 1.), + // The Box-Muller transform of two uniform values into one with a normal distribution + NoiseDistribution::Gaussian => { + let angles = random_field_values(cell, RandomField::NoiseAngles.seed(seed)); + std::array::from_fn(|channel| { + let normal = (-2. * offsets[channel].ln()).sqrt() * (std::f32::consts::TAU * angles[channel]).cos(); + normal.clamp(-GAUSSIAN_NOISE_LIMIT, GAUSSIAN_NOISE_LIMIT) + }) + } + }; + let noise = if monochromatic { [noise[0]; 3] } else { noise }; + let noisy = |channel: usize| (content[channel] + (noise[channel] * amount as f32).clamp(-extent, extent)).clamp(0., 1.); + [noisy(0), noisy(1), noisy(2), 1.] + } + // The opaque content passes every coverage threshold, so the opacity's threshold alone shows or hides it + EffectOperation::Dissolve { opacity, seed } => match random_field_values(cell, RandomField::Dissolve.seed(seed))[0] < (opacity / 100.) as f32 { + true => [content[0], content[1], content[2], 1.], + false => [0.; 4], + }, + _ => unreachable!(), + } + }; + let mut worst = 0_f32; + for (x, y) in (0..full_size.y).flat_map(|y| (0..full_size.x).map(move |x| (x, y))) { + let [red, green, blue, alpha] = expected(glam::IVec2::new(x as i32, y as i32)); + let wanted = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); + let shown = premultiplied_levels(pixel(&at_origin, full_size, x, y)); + worst = (0..4).map(|channel| (wanted[channel] - shown[channel]).abs()).fold(worst, f32::max); + } + assert!(worst <= 2., "{operation:?} strays from its field's seeded values by up to {worst} levels"); } } +/// The three values the random field of the `seed` holds at a `cell` of the effect space, by its definition: the top 23 bits of each of a PCG3D hash of the two, from 0 to 1. +fn random_field_values(cell: glam::IVec2, seed: u32) -> [f32; 3] { + graphic_types::generator::pcg3d([cell.x as u32, cell.y as u32, seed]).map(|hash| ((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32) +} + #[test] fn random_fields_stay_in_place_far_from_the_origin() { use core_types::list::{ATTR_EFFECTS, Item, List}; @@ -1982,7 +2102,7 @@ fn feathers_fade_the_content_to_nothing_at_its_edges() { } #[test] -fn masked_radius_blur_image_maps_blur_by_their_own_adjustments_and_opacity_on_the_cpu_and_gpu() { +fn masked_radius_blur_image_maps_blur_by_their_own_adjustments_and_opacity() { use core_types::Color as GraphicColor; use core_types::list::Item; use glam::DVec2; @@ -1990,32 +2110,39 @@ fn masked_radius_blur_image_maps_blur_by_their_own_adjustments_and_opacity_on_th use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect}; use rendering::{Render, RenderParams}; - // Image maps placed in the content's own space over it grown by 30 on each side: plain white, black inverted to white, and white at half opacity + // Image maps placed in the content's own space over it grown by 30 on each side: plain white, black inverted to white, white at half opacity, and middle gray let past_content = DAffine2::from_translation(DVec2::splat(-0.6)) * DAffine2::from_scale(DVec2::splat(2.2)); let image = |color| Item::new_from_element(Raster::new_cpu(Image::new(4, 4, color))).with_attribute(core_types::ATTR_TRANSFORM, past_content); let mut inverted = image(GraphicColor::BLACK); stamp_effect(&mut inverted, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert))); let faded = image(GraphicColor::WHITE).with_attribute(core_types::ATTR_OPACITY, 0.5_f64); + let gray = |level: f32| image(GraphicColor::from_gamma_srgb_channels(level, level, level, 1.)); // Each blurs a shadow cast 20 right of the content, so its far edge 20 past the content is soft where the map reaches it let shadow = drop_shadow(GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 1.), DVec2::new(20., 0.), 0., 0.); let size = UVec2::new(160, 160); - for (name, map) in [("plain", image(GraphicColor::WHITE)), ("inverted", inverted), ("faded", faded)] { + let draw = |map: Item>| { let blur = EffectOperation::Blur { radius_mask: Graphic::from(map), radius: 3., box_blur: false, gamma: false, }; - let item = patterned_raster(55., &[shadow.clone(), blur], 1.); - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 3, "the {name} map differs from the GPU by up to {worst} levels"); + let graphic = Graphic::RasterCPU(Box::new(patterned_raster(55., &[shadow.clone(), blur], 1.))); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + let (Some(plain), Some(inverted), Some(faded)) = (draw(image(GraphicColor::WHITE)), draw(inverted), draw(faded)) else { + return; + }; + let Some(middle_gray) = draw(gray(0.5)) else { return }; - let graphic = Graphic::RasterCPU(Box::new(item)); - let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - let soft = (118..132).filter(|&x| (10..245).contains(&pixel(&pixels, size, x, 80)[3])).count(); + // Black inverted to white blurs as white does, and white at half opacity over the black of no map blurs as middle gray does, which blurs less + assert!(largest_difference(&inverted, &plain) <= 1, "the inverted map blurs otherwise than white"); + assert!(largest_difference(&faded, &middle_gray) <= 1, "the faded map blurs otherwise than middle gray"); + assert!(largest_difference(&faded, &plain) > 20, "the faded map blurs as fully as white"); + + for (name, pixels) in [("plain", &plain), ("inverted", &inverted), ("faded", &faded)] { + let soft = (118..132).filter(|&x| (10..245).contains(&pixel(pixels, size, x, 80)[3])).count(); assert!(soft >= 3, "only {soft} pixels soften the shadow's far edge with the {name} map"); } } @@ -2229,13 +2356,23 @@ fn summed_box(channels: &[[f32; 4]], width: usize, height: usize, x: usize, y: u sum.map(|channel| channel / total) } +/// A premultiplied pixel with its straight color carried through a `transfer` function, such as from gamma into linear light. +fn transferred_premultiplied(transfer: fn(f32) -> f32, [red, green, blue, alpha]: [f32; 4]) -> [f32; 4] { + if alpha <= 0. { + return [0.; 4]; + } + let [red, green, blue] = [red, green, blue].map(|channel| transfer((channel / alpha).max(0.)) * alpha); + [red, green, blue, alpha] +} + #[test] -fn gpu_masked_box_blurs_match_the_cpu() { +fn gpu_masked_box_blurs_match_their_definition() { + use core_types::color::{linear_to_srgb, srgb_to_linear}; use graphic_types::masks::{MaskMode, mask_coverage}; use half::f16; - use raster_kernels::effect_kernels::Plane; + use raster_kernels::effect_kernels::{VARIABLE_BOX_MAX_VALUE, variable_box_scale}; - // Colorful content reaching the edges, every fifth pixel transparent and others translucent, which the CPU blurs as the GPU reads it + // Colorful content reaching the edges, every fifth pixel transparent and others translucent, as the GPU reads it let (width, height) = (96, 72); let texels: Vec<[f16; 4]> = (0..width * height) .map(|index| { @@ -2244,11 +2381,7 @@ fn gpu_masked_box_blurs_match_the_cpu() { [x * alpha, y * y * alpha, (1. - x * y) * alpha, alpha].map(f16::from_f32) }) .collect(); - let plane = Plane { - width, - height, - data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(), - }; + let channels: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect(); // Opaque gray maps of each pixel's luminance: one gray, a ramp across, scattered values, and checks of none and all of the radius type CodeAt = fn(usize, usize) -> usize; @@ -2272,12 +2405,29 @@ fn gpu_masked_box_blurs_match_the_cpu() { let Some(gpu) = gpu_effect_texels(&masked_box_blur(radius, gamma), &texels, width, &[&map]) else { return; }; - let cpu = raster_kernels::masks::variable_box_blur(&plane, &luminances, glam::DVec2::splat(radius), !gamma); + + // Each pixel the map lights averages its own box, half as wide as the radius times the map's luminance there, counted in whole steps in light unless in gamma + let steps = variable_box_scale(width * height) as f32; + let counted = |pixel: [f32; 4]| pixel.map(|channel| (channel.clamp(0., VARIABLE_BOX_MAX_VALUE) * steps).round_ties_even() / steps); + let summed: Vec<[f32; 4]> = match gamma { + true => channels.iter().map(|&pixel| counted(pixel)).collect(), + false => channels.iter().map(|&pixel| counted(transferred_premultiplied(srgb_to_linear, pixel))).collect(), + }; + let mut worst = 0_f32; + for (index, actual) in gpu.iter().enumerate() { + let expected = match luminances[index] > 0. { + true => { + let average = summed_box(&summed, width, height, index % width, index / width, radius * luminances[index] as f64).map(|channel| channel as f32); + if gamma { average } else { transferred_premultiplied(linear_to_srgb, average) } + } + false => channels[index], + }; + worst = worst.max((0..4).map(|channel| (actual[channel] - expected[channel]).abs()).fold(0., f32::max)); + } // Within the rounding of the GPU's half floats - let differences = gpu.iter().zip(&cpu.data).flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs())); - let worst = differences.fold(0., f32::max) * 255.; - assert!(worst < 0.3, "a {name} map at {radius} pixels (gamma: {gamma}) differs from the CPU by {worst} levels"); + let worst = worst * 255.; + assert!(worst < 0.3, "a {name} map at {radius} pixels (gamma: {gamma}) strays from its definition by {worst} levels"); } } } @@ -4027,24 +4177,29 @@ fn captured_box_blurs_hold_their_results_for_svg_however_slight() { } } -#[test] -fn cpu_evaluated_effects_match_the_gpu_passes() { +/// The square that [`square_effect_cases`] places its effects' paints around, from (`SQUARE_MIN`, `SQUARE_MIN`) to (`SQUARE_MAX`, `SQUARE_MAX`) in a render 160 across. +const SQUARE_MIN: u32 = 50; +const SQUARE_MAX: u32 = 100; + +/// The content color of the square [`square_effect_cases`] are rendered on, a color of its own so every mode has colors to blend. +const SQUARE_CONTENT: [u8; 4] = [217, 140, 89, 255]; + +/// Effects of every kind on the square from `SQUARE_MIN` to `SQUARE_MAX`, each at settings that exercise its options, with the paints and masks they draw placed around the square. +fn square_effect_cases() -> Vec> { + use core_types::ATTR_TRANSFORM; use core_types::Color as GraphicColor; use core_types::blending::BlendMode; use core_types::list::Item; use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE}; use core_types::transfer_curve::TransferCurve; - use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use glam::DVec2; use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings}; use graphic_types::raster_types::{Image, Raster}; use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop}; use graphic_types::vector_types::vector::style::StrokeAlign; - use graphic_types::{BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, GlowSource, GlowTechnique, Graphic, MaskMode, NoiseDistribution, stamp_effect}; - use raster_kernels::evaluate_raster_effects; + use graphic_types::{BevelDirection, BevelStyle, BevelTechnique, EffectOperation, GlowSource, GlowTechnique, Graphic, MaskMode, NoiseDistribution}; - let size = UVec2::new(160, 160); - let (min, max) = (50, 100); + let (min, max) = (SQUARE_MIN, SQUARE_MAX); let shadow_color = GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75); let blur = |radius, box_blur, gamma| EffectOperation::Blur { radius_mask: Graphic::default(), @@ -4587,12 +4742,6 @@ fn cpu_evaluated_effects_match_the_gpu_passes() { ], ]; - // Content in a color of its own, so every mode has colors to blend - let content = [217, 140, 89]; - let gpu_content = Color::from_rgb8(content[0], content[1], content[2]); - let [red, green, blue] = content.map(|channel| channel as f32 / 255.); - let cpu_content = GraphicColor::from_gamma_srgb_channels(red, green, blue, 1.); - // Filters of the checkerboard's colors, whose sharp edges the kernels pick out let checkered = |filter: EffectOperation| [overlay(&checker, BlendMode::Normal, 100.), vec![filter]].concat(); // Kernels of rows as wide as they are tall, unless their width is given @@ -4731,98 +4880,394 @@ fn cpu_evaluated_effects_match_the_gpu_passes() { vec![EffectOperation::Dissolve { opacity: 100., seed: 9 }], ]); - for effects in cases.into_iter().chain(paint_cases).chain(mask_cases) { - for fill in [1., 0.5] { - let Some(gpu) = render_square_over_backdrop(effects.clone(), fill, 1., BlendMode::Normal, None, gpu_content, min as f64, max as f64, size) else { - return; - }; + cases.into_iter().chain(paint_cases).chain(mask_cases).collect() +} - // The same square as a raster covering the render one pixel to one pixel - let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT); - for y in min..max { - for x in min..max { - image.data[(y * size.x + x) as usize] = cpu_content; - } - } - // Graphics following the content lie in the raster's own space, so they're linked to its placement to match the square drawn without one - let placement = DAffine2::from_scale(size.as_dvec2()); - // A gradient paint keeps its kind, which an outline's drawing depends on, by taking the raster's space into its own transform - let paint_in_raster_space = |paint: Graphic| match paint { - Graphic::Gradient(mut item) => { - let transform = placement.inverse() * item.attribute_cloned_or_default::(ATTR_TRANSFORM); - item.set_attribute(ATTR_TRANSFORM, transform); - Graphic::Gradient(item) - } - paint => graphic_types::linked_to_content(paint, placement), - }; - let linked: Vec = effects - .iter() - .cloned() - .map(|mut operation| { - match &mut operation { - EffectOperation::Mask { mask, .. } => *mask = graphic_types::linked_to_content(std::mem::take(mask), placement), - EffectOperation::Blur { radius_mask, .. } => *radius_mask = graphic_types::linked_to_content(std::mem::take(radius_mask), placement), - EffectOperation::PaintOverlay { paint, .. } | EffectOperation::Outline { paint, .. } => *paint = paint_in_raster_space(std::mem::take(paint)), - EffectOperation::BevelAndEmboss { texture, .. } => *texture = paint_in_raster_space(std::mem::take(texture)), - _ => {} - } - operation - }) - .collect(); - let mut item = Item::new_from_element(Raster::new_cpu(image)) - .with_attribute(ATTR_TRANSFORM, placement) - .with_attribute(ATTR_OPACITY_FILL, fill as f64); - linked.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); - let evaluated = evaluate_raster_effects(item); +/// How a case of [`square_effect_cases`] is checked: by the definition of its effect, or by drawing something that changes the square. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SquareCheck { + /// A blur of the whole square, whose coverage is the square's convolved with the blur's kernel. + Blur, + /// A paint overlay over a color overlay, which blends the paint onto that color by the mode's formula. + PaintOverlay, + /// Masks, then any adjustments, which show the content by each mask's coverage and density and then adjust its colors pixel by pixel. + Masks, + /// A convolution kernel of the checkerboard painted over the content, which sums the weighted colors around each pixel. + Convolution, + /// Adjustments, after any paint overlays, which change each pixel's color alone. + Adjusted, + /// Effects too intricate for a check of their definition, which draw something that changes the square. + Drawn(&'static str), +} - // Reads the evaluated image at the center of each render pixel through its grown placement - let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); +/// How the effects of a case of [`square_effect_cases`] are checked. +fn square_check(effects: &[graphic_types::EffectOperation]) -> SquareCheck { + use graphic_types::{EffectOperation, Graphic}; - let mut worst = 0; - for y in 0..size.y { - for x in 0..size.x { - let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); - let cpu = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize]; - let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels(); - let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); + let plain_blur = |operation: &EffectOperation| matches!(operation, EffectOperation::Blur { radius_mask: Graphic::None(_), .. }); + let unfeathered_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { feather, .. } if *feather == 0.); + let adjustment = |operation: &EffectOperation| matches!(operation, EffectOperation::Adjustment(_)); + let overlays = effects + .iter() + .take_while(|operation| matches!(operation, EffectOperation::PaintOverlay { .. }) || adjustment(operation)) + .count(); - // Compared premultiplied, so a nearly transparent pixel's color can't dominate - let gpu = pixel(&gpu, size, x, y); - let gpu_alpha = gpu[3] as f32 / 255.; - for channel in 0..4 { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); - } - } - } - // A rendered paint rounds to eight bits, which an outline shows unmixed and modes that divide or land near black (where gamma is steepest) amplify - use BlendMode::*; - let tolerance = match effects.last() { - Some(EffectOperation::PaintOverlay { blend_mode: VividLight, .. }) => 16, - Some(EffectOperation::PaintOverlay { - blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | LinearLight | PinLight | Difference, - .. - }) => 8, - Some(operation @ EffectOperation::Outline { .. }) if operation.drawn_paints().next().is_some() => 3, - // A noisy outer glow fades by its raw strength over 0.12, which amplifies eightfold the rounding of that strength where it falls steeply, across a full spread's last pixel - Some(EffectOperation::OuterGlow { noise, spread, .. }) if *noise > 0. && *spread >= 100. => 8, - // A texture's paint rounds to eight bits, which the two renderers can land a level apart, moving the surface by its depth times its span over 255 - Some(EffectOperation::BevelAndEmboss { texture, .. }) if !matches!(texture, Graphic::None(_)) => 6, - // A slope contour steeper than a straight line amplifies the rounding of the GPU's half-float heights - Some(EffectOperation::BevelAndEmboss { slope_contour, .. }) if !slope_contour.is_identity() => 4, - // A rendered map's code apart shifts the interpolation between wide levels of a blur varied by its radius mask, or its box's width - Some(operation @ EffectOperation::Blur { .. }) if operation.varies_blur_radius() => 3, - _ => 2, - }; - assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); - } + match effects { + [blur] if plain_blur(blur) => SquareCheck::Blur, + [EffectOperation::Adjustment(_), EffectOperation::PaintOverlay { .. }] => SquareCheck::PaintOverlay, + [ + EffectOperation::Adjustment(_), + EffectOperation::PaintOverlay { .. }, + EffectOperation::ConvolutionKernel { apply_to_alpha: false, .. }, + ] => SquareCheck::Convolution, + _ if effects.first().is_some_and(unfeathered_mask) && effects.iter().all(|operation| unfeathered_mask(operation) || adjustment(operation)) => SquareCheck::Masks, + _ if overlays == effects.len() => SquareCheck::Adjusted, + [first, ..] => SquareCheck::Drawn(match first { + EffectOperation::Blur { .. } | EffectOperation::Feather { .. } | EffectOperation::Mask { .. } => "effects-masks-feathers-and-blurs", + EffectOperation::DropShadow { .. } | EffectOperation::InnerShadow { .. } | EffectOperation::OuterGlow { .. } | EffectOperation::InnerGlow { .. } => "effects-shadows-and-glows", + EffectOperation::Satin { .. } | EffectOperation::Outline { .. } => "effects-satins-and-outlines", + EffectOperation::BevelAndEmboss { .. } => "effects-bevels", + _ => "effects-filters", + }), + [] => SquareCheck::Adjusted, } } +/// The kinds of the `effects`, numbered by their place in [`square_effect_cases`] and with paint overlays' modes, short enough to read in a failure. +fn square_case_name(index: usize, effects: &[graphic_types::EffectOperation]) -> String { + let kinds = effects.iter().map(|operation| match operation { + graphic_types::EffectOperation::PaintOverlay { blend_mode, .. } => format!("PaintOverlay({blend_mode:?})"), + operation => format!("{:?}", operation.kind()), + }); + format!("case {index} [{}]", kinds.collect::>().join(", ")) +} + +/// A straight-alpha pixel's premultiplied channels, from 0 to 1. +fn premultiplied_unit(pixel: [u8; 4]) -> [f32; 4] { + premultiplied_levels(pixel).map(|level| level / 255.) +} + +/// Renders the square of [`square_effect_cases`] through `effects` with `fill`, at `scale` times its size in a render that much larger than 160 across. +fn render_square_case(effects: Vec, fill: f32, scale: f64) -> Option> { + let [red, green, blue, _] = SQUARE_CONTENT; + let size = (UVec2::splat(160).as_dvec2() * scale).as_uvec2(); + let view = DAffine2::from_scale(glam::DVec2::splat(scale)); + render_square_over_backdrop_in_view( + effects, + DAffine2::IDENTITY, + view, + fill, + 1., + BlendMode::Normal, + None, + Color::from_rgb8(red, green, blue), + SQUARE_MIN as f64, + SQUARE_MAX as f64, + size, + ) +} + #[test] -fn gpu_neighborhood_extremes_match_the_cpu_kernels() { +fn effects_on_a_square_match_their_definitions() { + use core_types::Color as GraphicColor; + use graphic_types::filters::Convolution; + use graphic_types::masks::{mask_coverage, mask_density_line}; + use graphic_types::{EffectOperation, Graphic}; + use raster_kernels::effect_kernels::box_weight; + use raster_kernels::raster_effects::adjust_premultiplied; + use raster_kernels::value_effects::filled_color; + use rendering::{Render, RenderParams}; + + let size = UVec2::splat(160); + let (min, max) = (SQUARE_MIN, SQUARE_MAX); + let inside = |x: u32, y: u32| (min..max).contains(&x) && (min..max).contains(&y); + let content = SQUARE_CONTENT.map(|level| level as f32 / 255.); + let content_color = GraphicColor::from_gamma_srgb_channels(content[0], content[1], content[2], 1.); + + // A paint or mask drawn alone as the effects draw them, in premultiplied channels + let drawn = |graphic: &Graphic| { + let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern()))?; + Some(pixels.into_iter().map(premultiplied_unit).collect::>()) + }; + let at = |pixels: &[[f32; 4]], x: u32, y: u32| pixels[(y * size.x + x) as usize]; + + let mut checked = 0; + for (index, effects) in square_effect_cases().into_iter().enumerate() { + let check = square_check(&effects); + if matches!(check, SquareCheck::Drawn(_)) { + continue; + } + let name = square_case_name(index, &effects); + + for fill in [1., 0.5] { + let Some(gpu) = render_square_case(effects.clone(), fill, 1.) else { return }; + + // What each pixel should show in premultiplied channels, where it's certain, and how many levels the render may stray from it + let expected: Vec> = match check { + // The square's coverage blurred along each axis, in the content's color + SquareCheck::Blur => { + let EffectOperation::Blur { radius, box_blur, .. } = effects[0] else { unreachable!() }; + let coverage = |t: u32| { + let center = t as f64 + 0.5; + if box_blur { + let reach = radius.ceil() as i64; + let weights = (-reach..=reach).map(|offset| (offset, box_weight(radius, offset.unsigned_abs() as usize))); + let (covered, total) = weights.fold((0., 0.), |(covered, total), (offset, weight)| { + let within = (min as i64..max as i64).contains(&(t as i64 + offset)); + (covered + if within { weight } else { 0. }, total + weight) + }); + covered / total + } else { + normal_cdf((center - min as f64) / radius) - normal_cdf((center - max as f64) / radius) + } + }; + (0..size.x * size.y) + .map(|index| { + let alpha = (coverage(index % size.x) * coverage(index / size.x)) as f32 * fill; + Some([content[0] * alpha, content[1] * alpha, content[2] * alpha, alpha]) + }) + .collect() + } + // The content's color overlaid by the color overlay's and then by the paint's color at each pixel, blended by its mode, as a color value takes them + SquareCheck::PaintOverlay => { + let [EffectOperation::Adjustment(backdrop), EffectOperation::PaintOverlay { paint, blend_mode, opacity }] = &effects[..] else { + unreachable!() + }; + let Some(paint) = drawn(paint) else { return }; + + // Darker Color and Lighter Color pick whichever whole color has the lower or higher luma, which rounding can tip either way where they're nearly alike + let picks_by_luma = matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor); + let luma = |[red, green, blue]: [f32; 3]| 0.3 * red + 0.59 * green + 0.11 * blue; + let backdrop_luma = match backdrop { + graphic_types::Adjustment::ColorOverlay { color, .. } => luma(color.to_gamma_srgb_channels()[..3].try_into().unwrap_or_default()), + _ => unreachable!(), + }; + + (0..size.x * size.y) + .map(|index| { + let (x, y) = (index % size.x, index / size.x); + let [red, green, blue, alpha] = at(&paint, x, y); + let color = match alpha > 0. { + true => GraphicColor::from_gamma_srgb_channels(red / alpha, green / alpha, blue / alpha, alpha), + false => GraphicColor::TRANSPARENT, + }; + if picks_by_luma && alpha > 0. && (luma([red / alpha, green / alpha, blue / alpha]) - backdrop_luma).abs() < 2. / 255. { + return None; + } + let overlay = graphic_types::Adjustment::ColorOverlay { + color, + blend_mode: *blend_mode, + opacity: *opacity, + }; + let [red, green, blue, alpha] = filled_color(content_color, &[backdrop.clone(), overlay], fill).to_gamma_srgb_channels(); + inside(x, y).then_some([red * alpha, green * alpha, blue * alpha, alpha]) + }) + .collect() + } + // The content shown by each mask's coverage at its density, then adjusted pixel by pixel + SquareCheck::Masks => { + let mut shown = vec![[0.; 4]; (size.x * size.y) as usize]; + for (index, shown) in shown.iter_mut().enumerate() { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + if inside(x, y) { + *shown = content.map(|channel| channel * fill); + } + } + for operation in &effects { + match operation { + EffectOperation::Mask { mask, mode, density, invert, .. } => { + let Some(mask) = drawn(mask) else { return }; + let (slope, intercept) = mask_density_line(*density, *invert); + for (index, shown) in shown.iter_mut().enumerate() { + let strength = slope * mask_coverage(mask[index], *mode) + intercept; + *shown = shown.map(|channel| channel * strength); + } + } + EffectOperation::Adjustment(adjustment) => adjust_premultiplied(&mut shown, adjustment), + _ => unreachable!(), + } + } + shown.into_iter().map(Some).collect() + } + // The checkerboard painted over the content, with each pixel's colors summing those around it by the kernel's weights. + // Past the square's edge, the colors continue from its nearest pixel, which for a square is the one its edge clamps to. + SquareCheck::Convolution => { + let EffectOperation::ConvolutionKernel { kernel, columns, scale, offset, .. } = &effects[2] else { + unreachable!() + }; + let weights: Vec = kernel.iter_element_values().copied().collect(); + let convolution = Convolution::custom(&weights, *columns as usize, *scale, *offset); + + let Some(painted) = render_square_case(effects[..2].to_vec(), fill, 1.) else { return }; + let straight = |pixel: [u8; 4]| pixel.map(|level| level as f64 / 255.); + let continued = |t: f64| t.clamp(min as f64, (max - 1) as f64) as u32; + (0..size.x * size.y) + .map(|index| { + let (x, y) = (index % size.x, index / size.x); + if !inside(x, y) { + return Some([0.; 4]); + } + + let mut sum = [convolution.offset; 3]; + for &(shift, weight) in &convolution.taps { + let neighbor = straight(pixel(&painted, size, continued(x as f64 + shift.x), continued(y as f64 + shift.y))); + (0..3).for_each(|channel| sum[channel] += weight * neighbor[channel]); + } + let alpha = straight(pixel(&painted, size, x, y))[3] as f32; + let [red, green, blue] = sum.map(|channel| channel.clamp(0., 1.) as f32 * alpha); + Some([red, green, blue, alpha]) + }) + .collect() + } + // The render without the adjustments after the last paint overlay, adjusted pixel by pixel + SquareCheck::Adjusted => { + let painted = effects + .iter() + .rposition(|operation| matches!(operation, EffectOperation::PaintOverlay { .. })) + .map_or(0, |index| index + 1); + let Some(unadjusted) = render_square_case(effects[..painted].to_vec(), fill, 1.) else { return }; + let mut adjusted: Vec<[f32; 4]> = unadjusted.into_iter().map(premultiplied_unit).collect(); + for operation in &effects[painted..] { + let EffectOperation::Adjustment(adjustment) = operation else { unreachable!() }; + adjust_premultiplied(&mut adjusted, adjustment); + } + adjusted.into_iter().map(Some).collect() + } + SquareCheck::Drawn(_) => unreachable!(), + }; + + let (mut worst, mut compared) = (0_f32, 0); + for (index, expected) in expected.iter().enumerate() { + let Some(expected) = expected else { continue }; + let shown = premultiplied_levels(gpu[index]); + let here = (0..4).map(|channel| (expected[channel] * 255. - shown[channel]).abs()).fold(0., f32::max); + worst = worst.max(here); + compared += 1; + } + + // Modes that divide or land near black, where gamma is steepest, amplify the rounding of the passes' half floats + use BlendMode::*; + let tolerance = match effects.last() { + Some(EffectOperation::PaintOverlay { blend_mode: VividLight, .. }) => 16., + Some(EffectOperation::PaintOverlay { + blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | LinearLight | PinLight | Difference | Divide, + .. + }) => 8., + _ => 3., + }; + assert!(compared >= 1000, "{name} at fill {fill} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= tolerance, "{name} at fill {fill} strays from its definition by up to {worst} levels"); + checked += 1; + } + } + assert!(checked >= 100, "only {checked} cases are checked by their definitions"); +} + +/// The cases of [`square_effect_cases`] too intricate for a check of their definitions, each of which draws something its effects change from the plain square. +/// The document corpus's documents named by their [`SquareCheck::Drawn`] pin down their pixels. +#[test] +fn intricate_effects_on_a_square_draw_and_change_it() { + use graphic_types::EffectOperation; + + // Rendered at half size, as their corpus documents draw them, but bevels at full size, since the GPU draws Outer Chisel Hard edges wrong at half zoom (a known bug) + let scale = |document: &str| if document == "effects-bevels" { 1. } else { 0.5 }; + let plain_at = |scale: f64| [1., 0.5].into_iter().map(|fill| render_square_case(Vec::new(), fill, scale)).collect::>>(); + let (Some(plain_at_full_size), Some(plain_at_half_size)) = (plain_at(1.), plain_at(0.5)) else { + return; + }; + + let mut checked = 0; + for (index, effects) in square_effect_cases().into_iter().enumerate() { + let SquareCheck::Drawn(document) = square_check(&effects) else { continue }; + let scale = scale(document); + let plain = if scale == 1. { &plain_at_full_size } else { &plain_at_half_size }; + + // A maximum reaching past the square's middle leaves none of its coverage, and sharpening alone can't sharpen its one color and hard edges further + let name = square_case_name(index, &effects); + let erodes_all = matches!(effects[..], [EffectOperation::MinimumMaximum { radius, mode: MinimumMaximumMode::Maximum }] if radius >= (SQUARE_MAX - SQUARE_MIN) as f64 / 2.); + let may_keep_the_square = match &effects[..] { + [EffectOperation::ConvolutionKernel { kernel, apply_to_alpha: true, .. }] => kernel.iter_element_values().filter(|&&weight| weight > 0.).count() == 1, + [EffectOperation::Sharpen { .. }] => true, + _ => false, + }; + + // The effects change the square at either fill + let mut changes_the_square = false; + for (column, fill) in [1., 0.5].into_iter().enumerate() { + let Some(pixels) = render_square_case(effects.clone(), fill, scale) else { return }; + assert_eq!( + pixels.iter().any(|pixel| pixel[3] > 0), + !erodes_all, + "{name} at fill {fill} renders nothing, or something it should erode" + ); + changes_the_square |= largest_difference(&pixels, &plain[column]) > 8; + } + assert!(changes_the_square || may_keep_the_square, "{name} renders as the square without its effects"); + checked += 1; + } + assert!(checked >= 100, "only {checked} cases are checked by drawing them"); +} + +/// By Minimum and Maximum's definition, the premultiplied `channels` (`width` to a row) at the extreme of each channel over the squares of the whole radii [`graphic_types::filters::neighborhood_radii`] +/// gives, mixed by its fraction: the lightest straight colors and least coverage, or the darkest colors over white and most coverage. O(width × height × radius). +fn neighborhood_extremes(channels: &[[f32; 4]], width: usize, radius: f64, maximum: bool) -> Vec<[f32; 4]> { + let height = channels.len() / width; + + // The channels in the form their extremes are taken of + let prepared: Vec<[f32; 4]> = (channels.iter()) + .map(|&[red, green, blue, alpha]| match maximum { + true if alpha > 0. => [red / alpha, green / alpha, blue / alpha, alpha], + true => [0.; 4], + false => [red + 1. - alpha, green + 1. - alpha, blue + 1. - alpha, alpha], + }) + .collect(); + let extreme = |first: [f32; 4], second: [f32; 4]| -> [f32; 4] { + std::array::from_fn(|channel| match (channel == 3) != maximum { + true => first[channel].max(second[channel]), + false => first[channel].min(second[channel]), + }) + }; + + // Past the edges lies no color, and for the maximum, no coverage + let beyond = if maximum { [0.; 4] } else { [1., 1., 1., 0.] }; + + // The extreme along a line `length` long of the values `read` gives, over those within `reach` of `position`, and what lies past an end if it reaches that far + let line_extreme = |read: &dyn Fn(usize) -> [f32; 4], position: usize, length: usize, reach: usize| { + let within = (position.saturating_sub(reach)..=(position + reach).min(length - 1)).map(read).fold(read(position), extreme); + if reach > position || position + reach >= length { extreme(within, beyond) } else { within } + }; + + // The extreme over each square, along each row and then down each column + let in_squares = |reach: usize| -> Vec<[f32; 4]> { + let rows: Vec<[f32; 4]> = (0..width * height) + .map(|index| line_extreme(&|x| prepared[index / width * width + x], index % width, width, reach)) + .collect(); + (0..width * height) + .map(|index| line_extreme(&|y| rows[y * width + index % width], index / width, height, reach)) + .collect() + }; + + // Back to premultiplied colors, which for the minimum lifts the white back off within the coverage + let premultiplied = |[red, green, blue, alpha]: [f32; 4]| { + let channel = |channel: f32| match maximum { + true => channel * alpha, + false => (channel - (1. - alpha)).max(0.).min(alpha), + }; + [channel(red), channel(green), channel(blue), alpha] + }; + + let ([near, far], fraction) = graphic_types::filters::neighborhood_radii(radius, 1.); + let (near, far) = (in_squares(near as usize), in_squares(far as usize)); + (near.into_iter().zip(far)) + .map(|(near, far)| { + let (near, far) = (premultiplied(near), premultiplied(far)); + std::array::from_fn(|channel| near[channel] + (far[channel] - near[channel]) * fraction as f32) + }) + .collect() +} + +#[test] +fn gpu_neighborhood_extremes_match_their_definition() { use graphic_types::Effects; use half::f16; @@ -4842,11 +5287,7 @@ fn gpu_neighborhood_extremes_match_the_cpu_kernels() { [red, green, blue, alpha].map(f16::from_f32) }) .collect(); - let plane = raster_kernels::effect_kernels::Plane { - width, - height, - data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(), - }; + let channels: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect(); // Radii one pass reads, those doubled several times (some near powers of two), and those reaching across the texture's height or both its sides let mut strays = Vec::new(); @@ -4857,14 +5298,14 @@ fn gpu_neighborhood_extremes_match_the_cpu_kernels() { let Some(gpu) = gpu_effect_texels(&Effects::from_operations([operation.clone()]), &texels, width, &[]) else { return; }; - let cpu = raster_kernels::filter_kernels::neighborhood_extreme(&plane, radius, maximum, glam::DMat2::IDENTITY); + let expected = neighborhood_extremes(&channels, width, radius, maximum); // In 8-bit levels, well below the 0.57 that one texel shifts the gradient across - let levels = (gpu.iter().zip(&cpu.data)) - .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) + let levels = (gpu.iter().zip(&expected)) + .flat_map(|(gpu, expected)| (0..4).map(|channel| (gpu[channel] - expected[channel]).abs() * 255.)) .fold(0_f32, f32::max); if levels > 0.25 { - strays.push(format!("{operation:?} strays from the CPU's kernel by {levels} levels")); + strays.push(format!("{operation:?} strays from its definition by {levels} levels")); } } } @@ -5008,54 +5449,6 @@ fn medians_read_within_an_images_rectangle() { assert_eq!(pixel(&pixels, size, 9, 4)[3], 0); } -#[test] -fn a_median_baked_for_pixel_readers_matches_its_gpu_render() { - use core_types::ATTR_TRANSFORM; - use core_types::list::{Item, List}; - use glam::DVec2; - use graphic_types::raster_types::{CPU, Image, Raster}; - use graphic_types::{Effect, EffectOperation, stamp_effect}; - use rendering::{Render, RenderParams}; - - // Random colors with a fully transparent band, a pixel in from the render's corner, on the content's own grid and on one coarsened past its largest radius - let (width, height) = (40, 30); - let data = (0..width * height) - .map(|index| { - let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.; - let alpha = if (12..16).contains(&(index % width)) { 0. } else { 1. }; - core_types::Color::from_gamma_srgb_channels(random(1), random(2), random(3), alpha) - }) - .collect(); - let placement = DAffine2::from_scale_angle_translation(DVec2::new(width as f64, height as f64), 0., DVec2::ONE); - let image = Item::new_from_element(Raster::new_cpu(Image { - width: width as u32, - height: height as u32, - data, - })) - .with_attribute(ATTR_TRANSFORM, placement); - - let size = UVec2::new(width as u32 + 2, height as u32 + 2); - let draw = |item: Item>| { - let list = List::new_from_item(item); - render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) - }; - for radius in [2., 20.] { - let mut item = image.clone(); - stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius })); - - // A reader bakes the effect into the image's pixels, which must draw as the GPU draws the effect - let baked = raster_kernels::evaluate_raster_effects(item.clone()); - let (Some(gpu), Some(baked)) = (draw(item), draw(baked)) else { return }; - // Compared premultiplied, since the straight colors of nearly transparent pixels read back in steps as coarse as their alpha, within the rounding of half floats and 8 bits - let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]); - let stray = (gpu.iter().zip(&baked)) - .flat_map(|(gpu, baked)| premultiplied(*gpu).zip(premultiplied(*baked)).map(|(gpu, baked)| (gpu - baked).abs())) - .fold(0_f32, f32::max); - assert!(stray <= 3., "a median of radius {radius} baked strays from its GPU render by {stray} levels"); - assert_ne!(baked, draw(image.clone()).unwrap_or_default(), "the median changes the pixels"); - } -} - /// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent. fn adjustment_test_colors() -> Vec { const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.]; @@ -6376,16 +6769,13 @@ fn adjustments_leave_the_empty_space_around_content_empty() { } #[test] -fn grained_glows_match_the_cpu_zoomed_in_and_out() { - use core_types::ATTR_TRANSFORM; +fn grained_glows_stay_on_the_content_and_average_their_cells_zoomed_in_and_out() { use core_types::Color as GraphicColor; - use core_types::list::Item; use core_types::transfer_curve::TransferCurve; use glam::DVec2; - use graphic_types::raster_types::{Image, Raster}; + use graphic_types::filters::RandomField; use graphic_types::vector_types::gradient::{Gradient, GradientStop}; use graphic_types::{EffectOperation, Effects, GlowSource, GlowTechnique, Graphic}; - use raster_kernels::evaluate_raster_effects; let (min, max) = (24., 56.); let stop = |position, color| GradientStop { position, midpoint: 0.5, color }; @@ -6451,85 +6841,113 @@ fn grained_glows_match_the_cpu_zoomed_in_and_out() { }, ]; - let zooms = [ - // Twice and half as many pixels as document pixels, with the render's corner at negative document pixels so the grain's cells there are negative too - (2., DVec2::new(10., 6.), 160), - (0.5, DVec2::new(4., 2.), 48), - // An eighth as many, where each pixel spans more grain than it samples - (0.125, DVec2::new(3., 2.), 16), - // The render cutting off the content's upper left, so it starts partway into the grain - (2., DVec2::new(-70., -60.), 160), - ]; - for (scale, offset, side) in zooms { - for glow in glows.clone() { - let effects = Effects::from_operations([glow.clone()]); - let size = UVec2::splat(side); - let square = Rect::new(min, min, max, max); - // The grain lies in the effect space, which has its origin at the content's, the square's corner - let effect_space = DAffine2::from_translation(DVec2::splat(min)); - let Some(gpu) = render(size, |scene| { - scene.draw_placed(Affine::translate((offset.x, offset.y)) * Affine::scale(scale), |scene| { - scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| { - scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) - }); + // A band of grain alone: a precise glow at full spread is flat across its size but for its noise + let flat_band = EffectOperation::OuterGlow { + color: GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75).into(), + blend_mode: BlendMode::Normal, + technique: GlowTechnique::Precise, + spread: 100., + size: 8., + range: 100., + contour: TransferCurve::default(), + noise: 60., + jitter: 0., + seed: 2, + }; + + // The square at `scale` pixels per document pixel, with the render's corner at `offset` pixels from the document's origin + let draw = |glow: &EffectOperation, scale: f64, offset: DVec2, side: u32| { + let effects = Effects::from_operations([glow.clone()]); + let square = Rect::new(min, min, max, max); + // The grain lies in the effect space, which has its origin at the content's, the square's corner + let effect_space = DAffine2::from_translation(DVec2::splat(min)); + render(UVec2::splat(side), |scene| { + scene.draw_placed(Affine::translate((offset.x, offset.y)) * Affine::scale(scale), |scene| { + scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square) }); - }) else { + }); + }) + }; + let difference = |first: [u8; 4], second: [u8; 4]| { + let (first, second) = (premultiplied_levels(first), premultiplied_levels(second)); + (0..4).map(|channel| (first[channel] - second[channel]).abs()).fold(0., f32::max) + }; + + // Moved by whole pixels at twice, half, and an eighth as many pixels as document pixels, the grain moves with the content. + // The first render's corner lies at negative document pixels, so the grain's cells there are negative too, and the second cuts off the content's upper left, so it starts partway into the grain. + for (scale, offset, side, shift) in [ + (2., DVec2::new(10., 6.), 160, UVec2::new(80, 66)), + (0.5, DVec2::new(4., 2.), 48, UVec2::new(9, 7)), + (0.125, DVec2::new(3., 2.), 16, UVec2::new(3, 2)), + ] { + for glow in glows.iter().chain([&flat_band]) { + let (Some(placed), Some(moved)) = (draw(glow, scale, offset, side), draw(glow, scale, offset - shift.as_dvec2(), side)) else { return; }; - - // The same square as a raster at the same pixels per document pixel - let pixels = ((max - min) * scale) as u32; - let mut item = Item::new_from_element(Raster::new_cpu(Image::new(pixels, pixels, GraphicColor::WHITE))) - .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(min)) * DAffine2::from_scale(DVec2::splat(max - min))); - graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(&glow)); - let evaluated = evaluate_raster_effects(item); - let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); - - let mut worst = 0; - for y in 0..size.y { - for x in 0..size.x { - let document = (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - offset) / scale; - let point = document_to_pixels.transform_point2(document).floor(); - let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64; - let cpu = match inside { - true => { - let [red, green, blue, alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels(); - [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.) - } - false => [0.; 4], - }; - - let gpu = pixel(&gpu, size, x, y); - let gpu_alpha = gpu[3] as f32 / 255.; - for channel in 0..4 { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); - } - } + for (x, y) in (0..side - shift.y).flat_map(|y| (0..side - shift.x).map(move |x| (x, y))) { + let (expected, actual) = (pixel(&placed, UVec2::splat(side), x + shift.x, y + shift.y), pixel(&moved, UVec2::splat(side), x, y)); + assert!( + difference(expected, actual) <= 1., + "{glow:?} at {scale} pixels per document pixel shows {actual:?} at ({x}, {y}) once moved, rather than {expected:?}" + ); } - assert!(worst <= 2, "{effects:?} at {scale} pixels per document pixel differs from the GPU by up to {worst} levels"); } } + + // The band from 56 to 64 right of the square at one pixel to each cell of grain, away from its corners and its antialiased outer edge + let Some(full_size) = draw(&flat_band, 1., DVec2::ZERO, 80) else { return }; + let cell = |x: u32, y: u32| pixel(&full_size, UVec2::splat(80), x, y); + let (columns, rows) = (57..63, 30..50); + assert!(rows.clone().any(|y| columns.clone().any(|x| cell(x, y)[3] != cell(57, 30)[3])), "the band shows no grain"); + + // Each pixel shows its cell's grain from -1 to 1 (a document pixel from the content's corner), which offsets the glow's full strength by the noise before it's held under 1 + let grain = |x: u32, y: u32| 2. * random_field_values(glam::IVec2::new(x as i32 - min as i32, y as i32 - min as i32), RandomField::GlowGrain.seed(2))[0] - 1.; + for (x, y) in rows.clone().flat_map(|y| columns.clone().map(move |x| (x, y))) { + let expected = 0.75 * (1. + 0.6 * grain(x, y)).clamp(0., 1.) * 255.; + let shown = cell(x, y)[3] as f32; + assert!((shown - expected).abs() <= 1., "({x}, {y}) shows an alpha of {shown} rather than its grain's {expected}"); + } + + // At two pixels to each cell, each pixel shows the cell under its middle + let Some(zoomed_in) = draw(&flat_band, 2., DVec2::ZERO, 160) else { return }; + for (x, y) in rows.clone().flat_map(|y| columns.clone().map(move |x| (x, y))) { + for (right, down) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let shown = pixel(&zoomed_in, UVec2::splat(160), 2 * x + right, 2 * y + down); + assert!(difference(shown, cell(x, y)) <= 1., "zoomed in, ({x}, {y}) shows {shown:?} rather than its cell's {:?}", cell(x, y)); + } + } + + // At half as many pixels, each pixel takes the mean of the four cells across it + let Some(zoomed_out) = draw(&flat_band, 0.5, DVec2::ZERO, 40) else { return }; + for (x, y) in (rows.start / 2..rows.end / 2).flat_map(|y| (29..31).map(move |x| (x, y))) { + let cells = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(right, down)| premultiplied_levels(cell(2 * x + right, 2 * y + down))); + let mean: [f32; 4] = std::array::from_fn(|channel| cells.iter().map(|levels| levels[channel]).sum::() / 4.); + let shown = premultiplied_levels(pixel(&zoomed_out, UVec2::splat(40), x, y)); + let worst = (0..4).map(|channel| (mean[channel] - shown[channel]).abs()).fold(0., f32::max); + assert!(worst <= 2., "zoomed out, ({x}, {y}) strays from the mean of its cells by {worst} levels"); + } } +/// Soft chisels on translucent content each draw something the bevel changes from the plain square, which the document corpus's `effects-soft-chisels` pins down. #[test] -fn soft_chisels_on_translucent_content_match_the_cpu() { - use core_types::ATTR_TRANSFORM; +fn soft_chisels_on_translucent_content_draw_and_change_it() { use core_types::Color as GraphicColor; - use core_types::list::Item; - use glam::DVec2; - use graphic_types::raster_types::{Image, Raster}; - use graphic_types::{BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, stamp_effect}; - use raster_kernels::evaluate_raster_effects; + use graphic_types::{BevelStyle, BevelTechnique, EffectKind, EffectOperation, Effects}; let size = UVec2::new(160, 160); let (min, max) = (50, 110); // Partial coverage gives every pixel inside a head start short of the whole slope, so seeds of differing values meet let alpha = 140. / 255.; - for (style, bevel_size) in [(BevelStyle::InnerBevel, 10.), (BevelStyle::Emboss, 12.), (BevelStyle::OuterBevel, 8.), (BevelStyle::InnerBevel, 40.)] { + // The square without a bevel, which each bevel's render has to change + let square = Rect::new(min as f64, min as f64, max as f64, max as f64); + let Some(plain) = render(size, |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE.with_alpha(alpha), None, &square)) else { + return; + }; + + let bevels = [(BevelStyle::InnerBevel, 10.), (BevelStyle::Emboss, 12.), (BevelStyle::OuterBevel, 8.), (BevelStyle::InnerBevel, 40.)]; + for (style, bevel_size) in bevels { let mut bevel = EffectOperation::default_for(EffectKind::BevelAndEmboss); if let EffectOperation::BevelAndEmboss { style: bevel_style, @@ -6545,7 +6963,6 @@ fn soft_chisels_on_translucent_content_match_the_cpu() { } let effects = Effects::from_operations([bevel.clone()]); - let square = Rect::new(min as f64, min as f64, max as f64, max as f64); let Some(gpu) = render(size, |scene| { scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE.with_alpha(alpha), None, &square) @@ -6553,37 +6970,8 @@ fn soft_chisels_on_translucent_content_match_the_cpu() { }) else { return; }; - - // The same square as a raster covering the render one pixel to one pixel - let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT); - for y in min..max { - for x in min..max { - image.data[(y * size.x + x) as usize] = GraphicColor::WHITE.with_alpha(alpha); - } - } - let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())); - stamp_effect(&mut item, Effect::new(&bevel)); - let evaluated = evaluate_raster_effects(item); - let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); - - let mut worst = 0; - for y in 0..size.y { - for x in 0..size.x { - let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); - let [red, green, blue, cpu_alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels(); - let cpu = [red * cpu_alpha, green * cpu_alpha, blue * cpu_alpha, cpu_alpha].map(|channel| channel * 255.); - - let gpu = pixel(&gpu, size, x, y); - let gpu_alpha = gpu[3] as f32 / 255.; - for channel in 0..4 { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); - } - } - } - assert!(worst <= 2, "a soft {style:?} of {bevel_size} on translucent content differs from the GPU by up to {worst} levels"); + assert!(gpu.iter().any(|pixel| pixel[3] > 0), "{style:?} of {bevel_size} renders nothing"); + assert!(largest_difference(&gpu, &plain) > 8, "{style:?} of {bevel_size} renders as the square without its bevel"); } } @@ -6979,9 +7367,15 @@ fn drawing_differences(pattern: &graphic_types::generator::GeneratorPattern, pix assert_eq!(pixel(&pixels, size, 2, 2)[3], 255); assert_eq!(pixel(&pixels, size, 76, 76)[3], 255); - let (expected, _, _) = raster_kernels::generators::render_pattern(pattern, [origin, origin + 64. / pixels_per_unit], 64, 64) - .unwrap() - .to_flat_u8(); + // The generator's own point function sampled at each pixel's center + let sample = raster_kernels::generators::pattern_sampler(pattern); + let samples = (0..64 * 64).map(|index| sample(origin + (glam::DVec2::new((index % 64) as f64, (index / 64) as f64) + 0.5) / pixels_per_unit)); + let image = graphic_types::raster_types::Image { + width: 64, + height: 64, + data: samples.collect(), + }; + let (expected, _, _) = image.to_flat_u8(); let differences: Vec = (0..64 * 64) .map(|index| { let drawn = pixel(&pixels, size, index % 64 + 8, index / 64 + 8); @@ -7084,7 +7478,7 @@ fn every_mandelbrot_setting_renders_on_the_gpu_like_on_the_cpu() { })) .chain([MandelbrotExterior::Tendrils, MandelbrotExterior::Rays].map(|exterior| MandelbrotSettings { exterior, frequency: 2, ..base() })); - // The plane from -2 to 2 across the pixels compared, where 32-bit rounding, and the CPU and each GPU tile following reference orbits of their own, may tip points + // The plane from -2 to 2 across the pixels compared, where 32-bit rounding, and each GPU tile following a reference orbit of its own, may tip points // on the set's ragged edge into escaping at another iteration for settings in variations { let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Mandelbrot(settings.clone()), 64. / (4. * scale), glam::DVec2::splat(-2. * scale)) else { @@ -7340,23 +7734,749 @@ fn filters_8_bit_images_to_whole_levels() -> bool { executor().is_some_and(|executor| executor.context().adapter.get_info().device_type == wgpu::DeviceType::Cpu) } -/// The most that the GPU's render of `item` and its CPU evaluation differ by at any of the render's pixels, in levels of their premultiplied channels, or `None` without a GPU. -fn gpu_and_cpu_difference(item: core_types::list::Item>, size: UVec2) -> Option { - gpu_and_cpu_difference_in_view(item, size, DAffine2::IDENTITY) +/// Where a pixel's color comes from under a resampling effect, by the effect's definition: a point of the render the content is read at, or an average of such points. +enum Reads { + Point(glam::DVec2), + /// The mean of the points, in light rather than gamma if `in_light`. + Mean { + points: Vec, + in_light: bool, + }, + /// The points painted over each other, topmost first. + Layers(Vec), + Nothing, } -/// Like [`gpu_and_cpu_difference`], with the GPU rendering through a `view` (a zoom, say), which should keep the evaluated raster's pixels on the render's. -fn gpu_and_cpu_difference_in_view(item: core_types::list::Item>, size: UVec2, view: DAffine2) -> Option { - Some(gpu_and_cpu_differences_in_view(item, size, view)?.into_iter().max().unwrap_or_default()) +/// Where a displacement confined to a frame (`half` its size) reads from a `source` in its local space for a pixel past the frame, kept out of it: +/// a source within a pixel's `extent` of the frame (see [`graphic_types::resampling::EffectFrame::pixel_extent`]) moves out past its nearest side, that far beyond. +fn pushed_out_of_frame(source: glam::DVec2, half: glam::DVec2, extent: glam::DVec2) -> glam::DVec2 { + let gap = half + extent - source.abs(); + if gap.cmple(glam::DVec2::ZERO).any() { + return source; + } + match gap.x < gap.y { + true => glam::DVec2::new((half.x + extent.x).copysign(source.x), source.y), + false => glam::DVec2::new(source.x, (half.y + extent.y).copysign(source.y)), + } } -/// How much the GPU's render of `item` through a `view` and its CPU evaluation differ by at each of the render's pixels, row by row, as [`gpu_and_cpu_difference_in_view`] measures it. -fn gpu_and_cpu_differences_in_view(item: core_types::list::Item>, size: UVec2, view: DAffine2) -> Option> { +/// The Keys cubic convolution kernel with a = -0.75, which PSD's motion blur shears interpolate with. +fn keys_cubic(x: f64) -> f64 { + const A: f64 = -0.75; + let x = x.abs(); + match x { + _ if x < 1. => (A + 2.) * x * x * x - (A + 3.) * x * x + 1., + _ if x < 2. => A * x * x * x - 5. * A * x * x + 8. * A * x - 4. * A, + _ => 0., + } +} + +/// By PSD's definition, the premultiplied `texels` (`width` to a row, clear past their edges) motion blurred along a line `distance` long at `angle` degrees, counterclockwise from the right in the effect space `effect_to_pixels` places on them. +/// The texels shear across the axis the line lies nearer by the Keys cubic (measured from the effect space's origin) until the line runs along it, average over a box one pixel longer than the line, and shear back. +/// O(texels × the line's length). +fn sheared_box_blurred(texels: &[[f32; 4]], width: usize, angle: f64, distance: f64, effect_to_pixels: DAffine2) -> Vec<[f32; 4]> { + use glam::DVec2; + + let height = texels.len() / width; + let line = DVec2::new(angle.to_radians().cos(), -angle.to_radians().sin()) * distance.abs(); + let end = effect_to_pixels.matrix2 * line; + + // A diagonal runs along the effect space's x axis, and in the texels, along whichever axis that one lies nearer + let nearer_y_axis = |vector: DVec2| { + let (x, y) = (vector.x.abs(), vector.y.abs()); + ((x - y).abs() > x.max(y) * 1e-9).then_some(y > x) + }; + let own_axis_vertical = nearer_y_axis(line).unwrap_or(false); + let own_axis = if own_axis_vertical { DVec2::Y } else { DVec2::X }; + let vertical = nearer_y_axis(end).or_else(|| nearer_y_axis(effect_to_pixels.matrix2 * own_axis)).unwrap_or(false); + let along_major = |vector: DVec2| if vertical { [vector.y, vector.x] } else { [vector.x, vector.y] }; + let ([major, minor], [anchor, _]) = (along_major(end), along_major(effect_to_pixels.translation)); + if major.abs() < 0.01 { + return texels.to_vec(); + } + + // Each column (or row) shears across by the line's slope from the anchor, which slants in only as a line shorter than a pixel lengthens, as whole pixels and the fraction left over + let slope = minor / major * major.abs().min(1.); + let phase = (slope * anchor).rem_euclid(1.); + let shift = |major: i64| { + let shift = slope * (major as f64 + 0.5) - phase; + (shift.floor() as i64, shift - shift.floor()) + }; + + // The box leans half a pixel at odd lengths toward the line's end farther along the effect space's axis nearest it, and spreads its samples to take at most 1024 + let length = major.abs(); + let lean = if (major > 0.) == ((if own_axis_vertical { line.y } else { line.x }) > 0.) { 1. } else { -1. }; + let middle = lean * (0.5 - (0.5 - (length / 2.).fract()).abs()); + let [box_start, box_end] = [middle - (length + 1.) / 2., middle + (length + 1.) / 2.]; + let stride = ((length + 2.) / 1024.).ceil().max(1.); + let samples: Vec<(i64, f64)> = (((box_start + stride / 2.) / stride).floor() as i64..=((box_end - stride / 2.) / stride).ceil() as i64) + .filter_map(|index| { + let offset = index as f64 * stride; + let weight = box_end.min(offset + stride / 2.) - box_start.max(offset - stride / 2.); + (weight > 0.).then_some((offset as i64, weight)) + }) + .collect(); + let total: f64 = samples.iter().map(|(_, weight)| weight).sum(); + + // Texels by their place along the major axis and across it + let (majors, minors) = if vertical { (height as i64, width as i64) } else { (width as i64, height as i64) }; + let at = |plane: &[[f32; 4]], major: i64, minor: i64| match (0..majors).contains(&major) && (0..minors).contains(&minor) { + true if vertical => plane[(major * width as i64 + minor) as usize], + true => plane[(minor * width as i64 + major) as usize], + false => [0.; 4], + }; + let each_texel = |value: &dyn Fn(i64, i64) -> [f32; 4]| -> Vec<[f32; 4]> { + (0..texels.len()) + .map(|index| { + let (x, y) = ((index % width) as i64, (index / width) as i64); + if vertical { value(y, x) } else { value(x, y) } + }) + .collect() + }; + let weighted_sum = + |samples: &mut dyn Iterator| samples.fold([0.; 4], |sum, (sample, weight)| std::array::from_fn(|channel| sum[channel] + sample[channel] * weight as f32)); + let clipped = |[red, green, blue, alpha]: [f32; 4]| { + let alpha = alpha.clamp(0., 1.); + [red.clamp(0., alpha), green.clamp(0., alpha), blue.clamp(0., alpha), alpha] + }; + + // Sheared by each column's fraction, averaged along the box stepping across by the whole pixels of each column's shift, and sheared back by the fraction + let sheared = each_texel(&|major, minor| { + clipped(weighted_sum( + &mut (-1..=2).map(|offset| (at(texels, major, minor + offset), keys_cubic(offset as f64 - shift(major).1))), + )) + }); + let boxed = each_texel(&|major, minor| { + let whole = shift(major).0; + let sum = weighted_sum(&mut samples.iter().map(|&(offset, weight)| (at(&sheared, major + offset, minor + shift(major + offset).0 - whole), weight))); + sum.map(|channel| channel / total as f32) + }); + each_texel(&|major, minor| { + clipped(weighted_sum( + &mut (-2..=1).map(|offset| (at(&boxed, major, minor + offset), keys_cubic(offset as f64 + shift(major).1))), + )) + }) +} + +/// What the raster `item`, ending with a resampling effect (a warp, displacement, radial or motion blur, or pixelation), shows at each pixel of a render `size` across through a `view`, by that effect's definition. +/// Each pixel reads what the effects before it leave, as the GPU renders them, bilinearly at the points the effect reads for the pixel's middle, or as [`pixelated_reference`], +/// [`sheared_box_blurred`], or [`warp_layers`] find for a pixelation, motion blur, or Warp. Pixels reading within two pixels of sides that pixels straddle, where each edge mode has rules of its own, are `None`. The whole reference is `None` without a GPU. +fn resampled_reference(item: &core_types::list::Item>, view: DAffine2, size: UVec2) -> Option>> { + use core_types::list::{ATTR_EFFECTS, Item}; + use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; + use glam::DVec2; + use graphic_types::effects::effect_space; + use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, confines_to_frame, map_displacement, source_within_frame, warp_frame, warp_of}; + use graphic_types::vector_types::GradientSpread; + use graphic_types::{EffectOperation, Effects, Graphic}; + use rendering::{Render, RenderParams}; + + let content_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let effects = item.attribute::(ATTR_EFFECTS).expect("the item carries an effect"); + let last = effects.len() - 1; + let operation = &effects.operations().last().expect("the item carries an effect"); + let (stamped_transform, _) = effects.runs().into_iter().find(|(_, rows)| rows.contains(&last)).expect("the last effect lies in a run"); + let effect_space = effect_space(content_transform, stamped_transform); + let effect_to_pixels = view * effect_space; + + // Premultiplied gamma-encoded channels carried into light and back, for averages taken in light + let into_light = |[red, green, blue, alpha]: [f32; 4]| { + let linear = |channel: f32| if alpha > 0. { core_types::color::srgb_to_linear(channel / alpha) * alpha } else { 0. }; + [linear(red), linear(green), linear(blue), alpha] + }; + let out_of_light = |[red, green, blue, alpha]: [f32; 4]| { + let gamma = |channel: f32| if alpha > 0. { core_types::color::linear_to_srgb(channel / alpha) * alpha } else { 0. }; + [gamma(red), gamma(green), gamma(blue), alpha] + }; + + // What the effects before it leave, as the GPU renders them (as far as the render's size past each of its sides) into 8-bit or precise colors + let padded_view = DAffine2::from_translation(size.as_dvec2()) * view; + let before = item.clone().with_attribute(ATTR_EFFECTS, effects.run(0..last).into_owned()); + let render_padded = |item: Item>, precise: bool| -> Option> { + let graphic = Graphic::RasterCPU(Box::new(item)); + let draw = |scene: &mut VelloSceneBuilder| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()); + match precise { + true => render_precise_in_view(size * 3, padded_view, draw), + false => Some(render_in_view(size * 3, padded_view, draw)?.into_iter().map(premultiplied_unit).collect()), + } + }; + + // Pixelations average whole cells and dot boxes, read in precise colors since a dot's edge moves far for a small change in its ink + if matches!(operation, EffectOperation::Pixelate { .. } | EffectOperation::ColorHalftone { .. }) { + let padded_frame = EffectFrame::new(effect_space.inverse() * content_transform, padded_view * effect_space).expect("the content has a frame"); + let before = render_padded(before, true)?; + + // A halftone inks from the colors the fill and Blend Ifs leave at the full-strength content's coverage, so they fade its print rather than shrink its dots + let mut ink_from = before.clone(); + if matches!(operation, EffectOperation::ColorHalftone { .. }) { + let unfaded = effects.run(0..last).keeping(|operation| !matches!(operation, EffectOperation::BlendIf(_))); + let full = render_padded(item.clone().with_attribute(ATTR_OPACITY_FILL, 1.).with_attribute(ATTR_EFFECTS, unfaded), true)?; + for (texel, full) in ink_from.iter_mut().zip(full) { + *texel = if texel[3] > 0. { texel.map(|channel| channel / texel[3] * full[3]) } else { full }; + } + } + return Some(pixelated_reference(operation, &before, &ink_from, size.x * 3, &padded_frame, [size, size])); + } + + // And that in light, where blurs averaging in light filter it + let before = render_padded(before, false)?; + let before_in_light: Vec<[f32; 4]> = before.iter().map(|&texel| into_light(texel)).collect(); + + // A motion blur smears the whole render by PSD's sheared box + if let EffectOperation::MotionBlur { angle, distance, gamma } = *operation { + let padded_width = 3 * size.x as usize; + let blurred = sheared_box_blurred(if gamma { &before } else { &before_in_light }, padded_width, angle, distance, padded_view * effect_space); + let shown = (0..size.x * size.y).map(|index| { + let texel = blurred[(index / size.x + size.y) as usize * padded_width + (index % size.x + size.x) as usize]; + Some(if gamma { texel } else { out_of_light(texel) }) + }); + return Some(shown.collect()); + } + + // Either sampled bilinearly at points of the render + let (width, height) = (size.x as i64, size.y as i64); + let texel = |texels: &[[f32; 4]], x: i64, y: i64| -> [f32; 4] { + let (x, y) = (x + width, y + height); + if x < 0 || y < 0 || x >= 3 * width || y >= 3 * height { + return [0.; 4]; + } + texels[(y * 3 * width + x) as usize] + }; + let sample_from = |texels: &[[f32; 4]], point: DVec2| -> [f32; 4] { + let position = point - 0.5; + let (corner, fraction) = (position.floor(), (position - position.floor()).as_vec2()); + let (x, y) = (corner.x as i64, corner.y as i64); + let [top_left, top_right, bottom_left, bottom_right] = [texel(texels, x, y), texel(texels, x + 1, y), texel(texels, x, y + 1), texel(texels, x + 1, y + 1)]; + std::array::from_fn(|channel| { + let top = top_left[channel] + (top_right[channel] - top_left[channel]) * fraction.x; + let bottom = bottom_left[channel] + (bottom_right[channel] - bottom_left[channel]) * fraction.x; + top + (bottom - top) * fraction.y + }) + }; + let sample = |point: DVec2| sample_from(&before, point); + + // The frame of the content, and whether a point in some frame's local space lies within two pixels of its sides or past them + let frame = EffectFrame::new(effect_space.inverse() * content_transform, effect_to_pixels).expect("the content has a frame"); + let near_sides = |frame: &EffectFrame, local: DVec2| (local.abs() - (frame.size / 2. - 4. * frame.pixel_extent())).max_element() > 0.; + let past_sides = |frame: &EffectFrame, local: DVec2| (local.abs() - (frame.size / 2. + 4. * frame.pixel_extent())).max_element() > 0.; + + // Whether the frame's sides lie on the pixels' boundaries, so no pixel straddles them + let on_pixel_boundaries = { + let corners = [DVec2::ZERO, DVec2::ONE].map(|corner| frame.to_pixels.transform_point2(corner)); + let upright = frame.to_pixels.matrix2.x_axis.y.abs() < 1e-9 && frame.to_pixels.matrix2.y_axis.x.abs() < 1e-9; + upright && corners.iter().all(|corner| (*corner - corner.round()).abs().max_element() < 1e-9) + }; + + // The maps' colors where the GPU draws them, as a displacement reads them, at each pixel's middle + let maps: Vec<(Vec<[f32; 4]>, DVec2)> = (operation.displacement_maps().into_iter().flatten()) + .map(|(map, movement)| { + let placed = Graphic::Graphic(Box::new(Item::new_from_element(map.clone()).with_attribute(ATTR_TRANSFORM, content_transform))); + let colors = render_precise_in_view(size, view, |scene| placed.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern()))?; + Some((colors, movement)) + }) + .collect::>()?; + + // The layers a Warp paints at each pixel, none where its square collapses + let warp_layers = warp_of(operation).map(|(warp, transform)| match warp_frame(transform, effect_to_pixels) { + Some(square) => warp_layers(&warp.mesh(square.size), &square, size), + None => vec![Some(Vec::new()); (size.x * size.y) as usize], + }); + + // A displacement within the content's frame, reading from where its edge mode sends each pixel's displaced point. + // Those confined to the frame keep what lies past it there, moved alike but kept out of the frame, and read its edge pixels exactly unless pixels straddle its sides. + let displaced = |point: DVec2, displacement: &dyn Fn(DVec2) -> DVec2, edge_mode: GradientSpread| { + let local = frame.pixels_to_local().transform_point2(point); + if confines_to_frame(edge_mode) && past_sides(&frame, local) { + let source = pushed_out_of_frame(local + displacement(local), frame.size / 2., frame.pixel_extent()); + return past_sides(&frame, source).then(|| Reads::Point(frame.local_to_pixels().transform_point2(source))); + } + if confines_to_frame(edge_mode) && near_sides(&frame, local) && !(on_pixel_boundaries && frame.contains(local)) { + return None; + } + + let source = source_within_frame(edge_mode, local + displacement(local), frame.size, frame.pixel_extent()); + let within_edge_pixels = (source.abs() - (frame.size / 2. - frame.pixel_extent())).max_element() <= 1e-9; + if edge_mode != GradientSpread::Clear && near_sides(&frame, source) && !(on_pixel_boundaries && within_edge_pixels) { + return None; + } + Some(Reads::Point(frame.local_to_pixels().transform_point2(source))) + }; + + let reads = |point: DVec2, index: usize| -> Option { + match operation { + _ if let Some((warp, transform)) = FrameWarp::of(operation) => { + let polar = matches!(warp, FrameWarp::Polar { .. }); + let Some(square) = warp_frame(transform, effect_to_pixels) else { + return Some(if polar { Reads::Nothing } else { Reads::Point(point) }); + }; + + // Polar Coordinates clears all outside its square, and both it and the side it reads near have rules of their own + let local = square.pixels_to_local().transform_point2(point); + if polar && past_sides(&square, local) { + return Some(Reads::Nothing); + } + let source = warp.source(local, square.size); + if polar && (near_sides(&square, local) || near_sides(&square, source)) { + return None; + } + Some(Reads::Point(square.local_to_pixels().transform_point2(source))) + } + EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } => { + let (field, edge_mode) = DisplacementField::of(operation)?; + let displacer = field.displacer(frame.origin); + displaced(point, &displacer, edge_mode) + } + EffectOperation::Displace { edge_mode, .. } => { + let displacement = maps + .iter() + .map(|(colors, movement)| map_displacement(colors[index].map(|channel| channel.clamp(0., 1.)), *movement)) + .sum::(); + displaced(point, &|_| displacement, *edge_mode) + } + EffectOperation::RadialBlur { method, amount, transform, gamma } => { + let blur = RadialBlur::new(*method, *amount, *transform); + let at = effect_to_pixels.inverse().transform_point2(point); + let count = blur.sample_count(at, effect_to_pixels.matrix2.determinant().abs().sqrt()); + let points = (0..count).map(|sample| effect_to_pixels.transform_point2(blur.sample(at, sample, count))).collect(); + Some(Reads::Mean { points, in_light: !gamma }) + } + EffectOperation::Warp { .. } => warp_layers.as_ref()?[index].clone().map(Reads::Layers), + _ => None, + } + }; + + let reference = (0..size.x * size.y).map(|index| { + let point = DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5); + let shown = match reads(point, index as usize)? { + Reads::Point(source) => sample(source), + Reads::Nothing => [0.; 4], + Reads::Layers(points) => points.iter().rev().fold([0.; 4], |beneath, &point| { + let layer = sample(point); + std::array::from_fn(|channel| layer[channel] + beneath[channel] * (1. - layer[3])) + }), + Reads::Mean { points, in_light } => { + let samples = points.iter().map(|&source| sample_from(if in_light { &before_in_light } else { &before }, source)); + let sum = samples.fold([0.; 4], |sum, sample| std::array::from_fn(|channel| sum[channel] + sample[channel])); + let mean = sum.map(|channel| channel / points.len().max(1) as f32); + if in_light { out_of_light(mean) } else { mean } + } + }; + Some(shown) + }); + Some(reference.collect()) +} + +/// What each pixel of a render `size` across shows under a Warp of the `mesh` (as fractions of its `square` in the render's pixels), by its definition: +/// the points it reads the content at, topmost first, one for each point of the square the patch carries onto the pixel's middle, with the sheet turned over on top. +/// `None` within three pixels of where the patch carries the square's sides or turns over, or reading near the square's sides, or under two layers of one winding. O(pixels the patch spans). +fn warp_layers(mesh: &graphic_types::warp::WarpMesh, square: &graphic_types::resampling::EffectFrame, size: UVec2) -> Vec>> { + use glam::DVec2; + + let patch = mesh.transformed(square.to_pixels); + let orientation = square.to_pixels.matrix2.determinant().signum(); + let turned_over = |parameters: DVec2| { + let [_, along_s, along_t] = patch.point_and_tangents(parameters); + along_s.perp_dot(along_t) * orientation < 0. + }; + + // Each pixel's points of the square, and whether it lies within three pixels of a side or a crease + let pixel_index = |pixel: DVec2| (pixel.cmpge(DVec2::ZERO).all() && pixel.cmplt(size.as_dvec2()).all()).then(|| (pixel.y as u32 * size.x + pixel.x as u32) as usize); + let mut found: Vec> = vec![Vec::new(); (size.x * size.y) as usize]; + let mut near = vec![false; found.len()]; + let mark_near = |near: &mut [bool], point: DVec2| { + for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) { + let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64); + if (pixel + 0.5).distance(point) <= 3. + && let Some(index) = pixel_index(pixel) + { + near[index] = true; + } + } + }; + + // Newton's method from a seed onto the parameters the patch carries onto `target` + let polished = |seed: DVec2, target: DVec2| { + let mut parameters = seed; + for _ in 0..4 { + let [point, along_s, along_t] = patch.point_and_tangents(parameters); + let determinant = along_s.perp_dot(along_t); + if determinant.abs() < 1e-12 { + break; + } + let residual = point - target; + parameters -= DVec2::new(residual.perp_dot(along_t), along_s.perp_dot(residual)) / determinant; + } + ((patch.point(parameters) - target).length() < 1e-6).then_some(parameters) + }; + + // Each pixel middle within a triangle of the grid, polished from the parameters the triangle interpolates there, and a triangle of both windings marking a crease + let rasterize = |found: &mut [Vec], near: &mut [bool], corners: [(DVec2, DVec2, bool); 3]| { + if corners.iter().any(|corner| corner.2 != corners[0].2) { + corners.iter().for_each(|corner| mark_near(near, corner.1)); + } + + let [(first_parameters, a, _), (second_parameters, b, _), (third_parameters, c, _)] = corners; + let area = (b - a).perp_dot(c - a); + if area.abs() < 1e-18 { + return; + } + let first = (a.min(b).min(c) - 0.5).ceil().max(DVec2::ZERO); + let last = (a.max(b).max(c) - 0.5).floor().min(size.as_dvec2() - 1.); + for pixel in (first.y as i64..=last.y as i64).flat_map(|y| (first.x as i64..=last.x as i64).map(move |x| DVec2::new(x as f64, y as f64))) { + let target = pixel + 0.5; + let weights = [(c - b).perp_dot(target - b), (a - c).perp_dot(target - c), (b - a).perp_dot(target - a)].map(|weight| weight / area); + if weights.iter().any(|&weight| weight < -1e-9) { + continue; + } + + let seed = first_parameters * weights[0] + second_parameters * weights[1] + third_parameters * weights[2]; + let (Some(parameters), Some(index)) = (polished(seed, target), pixel_index(pixel)) else { + continue; + }; + if found[index].iter().all(|other| other.distance(parameters) > 1e-7) { + found[index].push(parameters); + } + } + }; + + // A grid over the square with cells spanning under half a pixel, row by row, its points carried by the patch with their winding, and those along its sides marking them + let tangents = patch.tangent_bounds(); + if !tangents.is_finite() { + return vec![None; found.len()]; + } + let cells = (tangents * 2.).ceil().clamp(DVec2::ONE, DVec2::splat(4096.)).as_uvec2(); + let grid_row = |row: u32| -> Vec<(DVec2, DVec2, bool)> { + (0..=cells.x) + .map(|column| { + let parameters = DVec2::new(column as f64 / cells.x as f64, row as f64 / cells.y as f64); + (parameters, patch.point(parameters), turned_over(parameters)) + }) + .collect() + }; + let mut previous = grid_row(0); + previous.iter().for_each(|corner| mark_near(&mut near, corner.1)); + for row in 1..=cells.y { + let current = grid_row(row); + let sides = if row == cells.y { current.clone() } else { vec![current[0], current[cells.x as usize]] }; + sides.iter().for_each(|corner| mark_near(&mut near, corner.1)); + + for column in 0..cells.x as usize { + let [top_left, top_right, bottom_left, bottom_right] = [previous[column], previous[column + 1], current[column], current[column + 1]]; + rasterize(&mut found, &mut near, [top_left, top_right, bottom_right]); + rasterize(&mut found, &mut near, [top_left, bottom_right, bottom_left]); + } + previous = current; + } + + // The content where each point lies within the square, the turned sheet over the other where two layers wind each way + let pixels_to_local = square.pixels_to_local(); + let reads_near_sides = |source: DVec2| (pixels_to_local.transform_point2(source).abs() - (square.size / 2. - 4. * square.pixel_extent())).max_element() > 0.; + found + .into_iter() + .zip(near) + .map(|(found, near)| { + let layers: Vec<(DVec2, bool)> = found.iter().map(|¶meters| (square.to_pixels.transform_point2(parameters), turned_over(parameters))).collect(); + if near || layers.iter().any(|&(source, _)| reads_near_sides(source)) { + return None; + } + match layers.as_slice() { + [] => Some(Vec::new()), + &[(source, _)] => Some(vec![source]), + &[(first, first_turned), (second, second_turned)] if first_turned != second_turned => Some(if first_turned { vec![first, second] } else { vec![second, first] }), + _ => None, + } + }) + .collect() +} + +/// What a Pixelate or Color Halftone `operation` in the `frame` shows by its definition at each texel of `before` from `corner`, `extent` across, row by row. +/// `before` is a premultiplied render `width` texels across of what the effects before it leave, and `ink_from` the colors a halftone's dots take their ink from. +/// Texels the frame's sides cut through are `None`, as are those of cells reaching past `before` or holding texels on their boundaries, and a halftone's channels near such dots are NaN. +fn pixelated_reference( + operation: &graphic_types::EffectOperation, + before: &[[f32; 4]], + ink_from: &[[f32; 4]], + width: u32, + frame: &graphic_types::resampling::EffectFrame, + [corner, extent]: [UVec2; 2], +) -> Vec> { + use glam::DVec2; + use graphic_types::EffectOperation; + use graphic_types::resampling::{HALFTONE_BOX_NUDGE, HALFTONE_SUBSAMPLES, HalftoneScreen, PIXELATE_TIE_NUDGE, halftone_dot_radius, tie_nudge}; + use std::collections::HashMap; + use std::f64::consts::{PI, SQRT_2}; + + let height = before.len() as u32 / width; + let (to_local, to_pixels, half) = (frame.pixels_to_local(), frame.local_to_pixels(), frame.size / 2.); + let local_at = |x: u32, y: u32| to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + let texel_at = |x: u32, y: u32| before[(y * width + x) as usize]; + + // A thousandth of a texel along each of the frame's sides, within which rounding puts a texel center on either side of a boundary. + // A cell or box is uncertain if more of its texels lie that near its boundary than could move its average by a 4096th. + let hair = 0.002 * frame.half_pixel(); + let uncertain = |near_boundary: u32, counted: u32| counted == 0 || near_boundary * 4096 > counted; + + // The first and last texels with centers that a rectangle from `low` to `high` in the local space may hold + let texels_within = |[low, high]: [DVec2; 2]| { + let corners = [low, DVec2::new(high.x, low.y), DVec2::new(low.x, high.y), high].map(|corner| to_pixels.transform_point2(corner)); + let (min, max) = (corners.into_iter().fold(DVec2::INFINITY, DVec2::min), corners.into_iter().fold(DVec2::NEG_INFINITY, DVec2::max)); + [(min - 0.5).ceil() - 1., (max - 0.5).floor() + 1.] + }; + // Those texels, if `before` holds them all + let texels_held = |rectangle| { + let [first, last] = texels_within(rectangle); + let held = first.cmpge(DVec2::ZERO).all() && last.cmplt(DVec2::new(width as f64, height as f64)).all(); + held.then(|| [first.as_uvec2(), last.as_uvec2()]) + }; + + // How much of a texel centered at `local` the frame covers, ramping from all to none across `reach` within and past each side + let coverage = |local: DVec2, reach: DVec2| (0.5 + (half - local.abs()) / (2. * reach)).clamp(DVec2::ZERO, DVec2::ONE).element_product(); + + // Averages count only the texels wholly within the frame or wholly past it, ignoring the slivers that single precision can round coverage to + const SLIVER: f64 = 1. / 256.; + let counted = |local: DVec2| { + let covered = coverage(local, frame.pixel_extent()); + covered < SLIVER || covered > 1. - SLIVER + }; + + // The texels shown, each wholly within the frame (`Some(true)`) or past it, rather than mixing what both sides show + let shown: Vec<(u32, u32)> = (corner.y..corner.y + extent.y).flat_map(|y| (corner.x..corner.x + extent.x).map(move |x| (x, y))).collect(); + let shown_within = |local: DVec2| { + let covered = coverage(local, frame.half_pixel()); + (covered < 1e-6 || covered > 1. - 1e-6).then_some(covered > 0.5) + }; + + if let &EffectOperation::Pixelate { cell_size, offset } = operation { + // Cells along the frame's sides from a corner at `offset` from the content's origin, each holding the texels with centers, nudged toward the frame's far corner, within it. + // The frame's sides cut those they cross in two, so the content's own cells average only the content. + let start = -half - (-half - (frame.origin + offset)).rem_euclid(DVec2::splat(cell_size)); + let nudge = tie_nudge(cell_size, PIXELATE_TIE_NUDGE, frame); + let cell_at = |local: DVec2, shift: DVec2| { + let index = ((local - start + nudge + shift) / cell_size).floor(); + let side = |axis: usize| (local[axis] > half[axis]) as i64 - (local[axis] < -half[axis]) as i64; + [(index.x as i64, side(0)), (index.y as i64, side(1))] + }; + // The cells a hair either way of a texel center, which differ near a boundary + let cells_near = |local| [cell_at(local, -hair), cell_at(local, hair)]; + + // Each cell's sum and count of the texels it averages, and how many more lie near its boundary + type CellSums = HashMap<[(i64, i64); 2], ([f64; 4], u32, u32)>; + let mut sums = CellSums::new(); + for (x, y) in (0..height).flat_map(|y| (0..width).map(move |x| (x, y))) { + let local = local_at(x, y); + if !counted(local) { + continue; + } + + let [cell, other] = cells_near(local); + if cell != other { + [cell, other].into_iter().for_each(|cell| sums.entry(cell).or_default().2 += 1); + continue; + } + let (sum, count, _) = sums.entry(cell).or_default(); + let texel = texel_at(x, y); + *sum = std::array::from_fn(|channel| sum[channel] + texel[channel] as f64); + *count += 1; + } + + // Whether a cell, the part of it on its side of the frame's edge, reaches past `before` + let reaches_past = |cell: [(i64, i64); 2]| { + let [across, down] = [0, 1].map(|axis| { + let (index, side) = cell[axis]; + let low = start[axis] + index as f64 * cell_size; + let high = low + cell_size; + match side { + -1 => [low, high.min(-half[axis])], + 0 => [low.max(-half[axis]), high.min(half[axis])], + _ => [low.max(half[axis]), high], + } + }); + texels_held([DVec2::new(across[0], down[0]), DVec2::new(across[1], down[1])]).is_none() + }; + + return shown + .iter() + .map(|&(x, y)| { + let local = local_at(x, y); + shown_within(local)?; + let [cell, other] = cells_near(local); + let (sum, count, near_boundary) = sums.get(&cell).copied()?; + if cell != other || reaches_past(cell) || uncertain(near_boundary, count) { + return None; + } + Some(sum.map(|channel| (channel / count as f64) as f32)) + }) + .collect(); + } + + let Some(screens) = HalftoneScreen::of(operation, frame) else { + panic!("{operation:?} isn't a pixelation") + }; + + // Dots too close together to print give way to the tone they'd average to, each channel over white at the texel's alpha (as do far more dots than texels, which this leaves out) + if !screens.iter().all(|screen| screen.prints_dots(frame)) { + let tone = |&(x, y): &(u32, u32)| { + let ([red, green, blue, ink_alpha], alpha) = (ink_from[(y * width + x) as usize], texel_at(x, y)[3]); + let over_white = |channel: f32| (channel + 1. - ink_alpha) * alpha; + Some([over_white(red), over_white(green), over_white(blue), alpha]) + }; + return shown.iter().map(tone).collect(); + } + + // A grid of subsamples across each texel in the local space, how wide each is, and how far the texel reaches from its center + let texel_to_local = to_local.matrix2; + let subsample_step = texel_to_local / HALFTONE_SUBSAMPLES as f64; + let subsample_width = (subsample_step.x_axis.length() + subsample_step.y_axis.length()) / 2.; + let texel_reach = (texel_to_local.x_axis.length() + texel_to_local.y_axis.length()) / 2.; + + // The share of a texel centered at `local` that a dot of `dot_radius` at `center` covers, each subsample ramping across its width at the dot's edge. + // A dot smaller than a subsample covers no more of each than its own area. + let dot_coverage = |center: DVec2, dot_radius: f64, local: DVec2| { + let most = PI * dot_radius * dot_radius / (subsample_width * subsample_width); + let texel_corner = local - texel_to_local * DVec2::splat(0.5); + let subsamples = (0..HALFTONE_SUBSAMPLES).flat_map(|down| (0..HALFTONE_SUBSAMPLES).map(move |across| DVec2::new(across as f64 + 0.5, down as f64 + 0.5))); + let covered: f64 = subsamples + .map(|subsample| { + ((dot_radius - center.distance(texel_corner + subsample_step * subsample)) / subsample_width + 0.5) + .clamp(0., 1.) + .min(most) + }) + .sum(); + covered / (HALFTONE_SUBSAMPLES * HALFTONE_SUBSAMPLES) as f64 + }; + + // Each texel's white ground in each channel, which each dot reaching it darkens by its share, so overlapping dots' shares multiply (NaN near a dot of uncertain size) + let mut white = vec![[1_f64; 3]; shown.len()]; + + for (channel, screen) in screens.iter().enumerate() { + // Each dot's box reaches the radius each way from its center + let radius = screen.side / SQRT_2; + let nudge = tie_nudge(2. * radius, HALFTONE_BOX_NUDGE, frame); + + // How many dots sit on each whole unit that may reach the texels shown, snapped from lattice points up to a unit and a half away along each axis + let shown_corners = [corner, corner + UVec2::new(extent.x, 0), corner + UVec2::new(0, extent.y), corner + extent]; + let cells = shown_corners.map(|point| screen.cell_at(to_local.transform_point2(point.as_dvec2()) - frame.origin)); + let margin = ((1.5 * SQRT_2 + radius + texel_reach) / screen.side).ceil() as i64 + 1; + let first = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).min().unwrap_or_default() - margin); + let last = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).max().unwrap_or_default() + margin); + let mut stacked: HashMap<[i64; 2], i32> = HashMap::new(); + for cell in (first[1]..=last[1]).flat_map(|row| (first[0]..=last[0]).map(move |column| [column, row])) { + *stacked.entry(screen.dot_center(cell).to_array().map(|unit| unit as i64)).or_default() += 1; + } + + // A dot's radii within the frame and past it, covering the share of its cell that the channel's ink over white averages to across its box on that side of the frame's edge + let dot_radii = |center: DVec2| -> Option<[f64; 2]> { + let [first, last] = texels_held([center - radius, center + radius])?; + let (mut sums, mut counts, mut near_boundary, mut cut_within) = ([[0_f64; 4]; 2], [0; 2], 0, false); + for (x, y) in (first.y..=last.y).flat_map(|y| (first.x..=last.x).map(move |x| (x, y))) { + let local = local_at(x, y); + let from_center = local - center + nudge; + if from_center.abs().cmple(radius + hair).all() && (from_center.abs() - radius).abs().cmplt(hair).any() { + near_boundary += 1; + continue; + } + if !(from_center.cmpge(DVec2::splat(-radius)).all() && from_center.cmplt(DVec2::splat(radius)).all()) { + continue; + } + if !counted(local) { + cut_within |= frame.contains(local); + continue; + } + + let side = if frame.contains(local) { 0 } else { 1 }; + let texel = ink_from[(y * width + x) as usize]; + sums[side] = std::array::from_fn(|index| sums[side][index] + texel[index] as f64); + counts[side] += 1; + } + + // Without a texel wholly within the frame, those its edge cuts through count by their coverage, which this leaves out + if uncertain(near_boundary, counts[0] + counts[1]) || (counts[0] == 0 && cut_within) { + return None; + } + Some([0, 1].map(|side| { + let ink = if counts[side] == 0 { 0. } else { (sums[side][3] - sums[side][channel]) / counts[side] as f64 }; + halftone_dot_radius(ink, screen.side) + })) + }; + + for (unit, stacked) in stacked { + let center = DVec2::new(unit[0] as f64, unit[1] as f64) + frame.origin; + let radii = dot_radii(center); + + // The shown texels within reach of the dot, on the side of the frame's edge each lies on + let reach = radii.map_or(radius, |radii| radii[0].max(radii[1])) + texel_reach; + let [first, last] = texels_within([center - reach, center + reach]); + let (first, last) = (first.max(corner.as_dvec2()).as_uvec2(), last.min((corner + extent).as_dvec2() - 1.).as_uvec2()); + for (x, y) in (first.y..=last.y).flat_map(|y| (first.x..=last.x).map(move |x| (x, y))) { + let local = local_at(x, y); + let Some(within) = shown_within(local) else { continue }; + if center.distance(local) >= reach { + continue; + } + + let white = &mut white[((y - corner.y) * extent.x + x - corner.x) as usize][channel]; + match radii.map(|radii| radii[if within { 0 } else { 1 }]) { + None => *white = f64::NAN, + Some(dot_radius) if dot_radius > 0. => *white *= (1. - dot_coverage(center, dot_radius, local)).powi(stacked), + Some(_) => {} + } + } + } + } + + // Each channel's white ground at the texel's alpha + let printed = |(&(x, y), white): (&(u32, u32), [f64; 3])| { + shown_within(local_at(x, y))?; + let alpha = texel_at(x, y)[3]; + Some([white[0] as f32 * alpha, white[1] as f32 * alpha, white[2] as f32 * alpha, alpha]) + }; + shown.iter().zip(white).map(printed).collect() +} + +/// The most that a render `size` across differs from a `reference` of what each pixel should show where it's certain, in levels of their premultiplied channels, and how many pixels it compares. +/// Channels the reference leaves NaN aren't compared. +fn reference_difference(render: &[[u8; 4]], reference: &[Option<[f32; 4]>]) -> (f32, usize) { + let compared = render.iter().zip(reference).filter_map(|(&shown, expected)| Some((premultiplied_levels(shown), (*expected)?))); + compared.fold((0., 0), |(worst, count), (shown, expected)| { + let difference = (0..4).map(|channel| (shown[channel] - expected[channel] * 255.).abs()).fold(0., f32::max); + (worst.max(difference), count + 1) + }) +} + +/// The GPU's render of the raster `item` through a `view`, and the most it differs from [`resampled_reference`] with how many pixels that compares, or `None` without a GPU. +fn resampled_difference(item: &core_types::list::Item>, size: UVec2, view: DAffine2) -> Option<(f32, usize)> { use rendering::{Render, RenderParams}; let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); let gpu = render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; - Some(cpu_differences(&gpu, size, item, view, UVec2::ZERO, size)) + Some(reference_difference(&gpu, &resampled_reference(item, view, size)?)) +} + +/// Like [`resampled_difference`], counting only the pixels it compares where the reference shows content. +fn resampled_difference_over_content(item: &core_types::list::Item>, size: UVec2, view: DAffine2) -> Option<(f32, usize)> { + use rendering::{Render, RenderParams}; + + let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); + let gpu = render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; + let reference = resampled_reference(item, view, size)?; + Some((reference_difference(&gpu, &reference).0, reference.iter().flatten().filter(|color| color[3] > 0.).count())) +} + +/// Like [`resampled_difference_over_content`] for each of the raster `items` (as if each were drawn alone in a render `tile` pixels across), drawn together as [`gpu_tiles`] draws them. +fn gpu_tiles_and_reference_differences( + items: &[core_types::list::Item>], + tile: UVec2, + columns: u32, +) -> Option> { + let tiles = gpu_tiles(items, tile, columns)?; + items + .iter() + .zip(&tiles) + .map(|(item, pixels)| { + let reference = resampled_reference(item, DAffine2::IDENTITY, tile)?; + Some((reference_difference(pixels, &reference).0, reference.iter().flatten().filter(|color| color[3] > 0.).count())) + }) + .collect() } /// The GPU's renders of the `items` (as if each were drawn alone in a render `tile` pixels across), drawn side by side in one render in rows of `columns`, each cut from it. `None` without a GPU. @@ -7386,63 +8506,6 @@ fn gpu_tiles(items: &[core_types::list::Item>>, - tile: UVec2, - columns: u32, -) -> Option, Vec)>> { - let tiles = gpu_tiles(&items, tile, columns)?; - let differences = items - .into_iter() - .zip(&tiles) - .map(|(item, pixels)| cpu_differences(pixels, tile, item, DAffine2::IDENTITY, UVec2::ZERO, tile)); - Some(tiles.iter().cloned().zip(differences).collect()) -} - -/// How much the CPU evaluation of `item` through a `view` differs from the `gpu` render of it, `size` pixels across, at each pixel of the part `extent` across from `origin`, row by row, -/// in levels of their premultiplied channels. -fn cpu_differences( - gpu: &[[u8; 4]], - size: UVec2, - item: core_types::list::Item>, - view: DAffine2, - origin: UVec2, - extent: UVec2, -) -> Vec { - use core_types::ATTR_TRANSFORM; - - let evaluated = raster_kernels::evaluate_raster_effects(item); - let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(glam::DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse() * view.inverse(); - - let mut differences = Vec::with_capacity((extent.x * extent.y) as usize); - for y in origin.y..origin.y + extent.y { - for x in origin.x..origin.x + extent.x { - let point = document_to_pixels.transform_point2(glam::DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); - let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64; - let cpu = if inside { - raster.data[(point.y as u32 * raster.width + point.x as u32) as usize] - } else { - core_types::Color::TRANSPARENT - }; - let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels(); - let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); - - let gpu = pixel(gpu, size, x, y); - let gpu_alpha = gpu[3] as f32 / 255.; - let difference = (0..4).map(|channel| { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - (cpu[channel] - gpu_channel).abs().round() as u32 - }); - differences.push(difference.max().unwrap_or_default()); - } - } - differences -} - /// A straight-alpha pixel's levels with its color multiplied by its alpha, which compare meaningfully even where it's nearly transparent. fn premultiplied_levels(pixel: [u8; 4]) -> [f32; 4] { let alpha = pixel[3] as f32 / 255.; @@ -7450,11 +8513,12 @@ fn premultiplied_levels(pixel: [u8; 4]) -> [f32; 4] { } #[test] -fn motion_blurs_lean_alike_on_flipped_and_turned_content_on_the_cpu_gpu_and_svg() { +fn motion_blurs_lean_alike_on_flipped_and_turned_content_and_in_svg() { use core_types::ATTR_TRANSFORM; - use core_types::list::List; + use core_types::list::{Item, List}; use core_types::transform::Footprint; use glam::{DMat2, DVec2}; + use graphic_types::raster_types::{CPU, Raster}; use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; use rendering::{Render, RenderParams, SvgRender}; @@ -7475,27 +8539,45 @@ fn motion_blurs_lean_alike_on_flipped_and_turned_content_on_the_cpu_gpu_and_svg( ]; let size = UVec2::splat(160); + let draw = |item: &Item>| { + let graphic = Graphic::RasterCPU(Box::new(item.clone())); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + for blur in &blurs { for (name, linear) in placements { + let about = about_middle(linear); + // Blurred where it lies once placed, or blurred upright and then placed, which carries the blur along with it for blurred_once_placed in [true, false] { let mut item = patterned_raster(55., &[], 1.); - let placed = about_middle(linear) * item.attribute_cloned_or_default::(ATTR_TRANSFORM); + let upright = item.attribute_cloned_or_default::(ATTR_TRANSFORM); if blurred_once_placed { - item.set_attribute(ATTR_TRANSFORM, placed); + item.set_attribute(ATTR_TRANSFORM, about * upright); } stamp_effect(&mut item, Effect::new(blur)); - item.set_attribute(ATTR_TRANSFORM, placed); + item.set_attribute(ATTR_TRANSFORM, about * upright); let case = format!("{blur:?} on content {name}, blurred {}", if blurred_once_placed { "once placed" } else { "before it's placed" }); - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 3, "{case} differs between the CPU and GPU by up to {worst} levels"); + // The box leans toward the end of the line along the effect space's axis, whichever way the content lies in that space + let Some((worst, compared)) = resampled_difference(&item, size, DAffine2::IDENTITY) else { return }; + assert!(compared >= 1000, "{case} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{case} strays from its definition by up to {worst} levels"); + + // Moved back upright, the content carries its blur along, so the flip or turn takes the render's pixels onto those of the render moved back + let moved_back = item.clone().with_attribute(ATTR_TRANSFORM, upright); + let (Some(gpu), Some(moved_back)) = (draw(&item), draw(&moved_back)) else { return }; + let mut worst = 0_f32; + for (index, &moved_back_pixel) in moved_back.iter().enumerate() { + let middle = DVec2::new((index as u32 % size.x) as f64 + 0.5, (index as u32 / size.x) as f64 + 0.5); + let position = about.transform_point2(middle).floor(); + + let (expected, actual) = (premultiplied_levels(moved_back_pixel), premultiplied_levels(pixel(&gpu, size, position.x as u32, position.y as u32))); + worst = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(worst, f32::max); + } + assert!(worst <= 3., "{case} differs from its render moved back upright by up to {worst} levels"); // SVG draws the item as an image the GPU renders of it, which has to show what the GPU draws in the view - let graphic = Graphic::RasterCPU(Box::new(item.clone())); - let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; let mut svg = SvgRender::new(); List::new_from_item(item).render_svg( &mut svg, @@ -7541,11 +8623,9 @@ fn motion_blurs_lean_alike_on_flipped_and_turned_content_on_the_cpu_gpu_and_svg( } #[test] -fn long_motion_blurs_spread_their_samples_alike_on_the_cpu_and_gpu() { - use glam::{DMat2, DVec2}; +fn long_motion_blurs_average_only_the_pixels_their_spread_samples_land_on() { use graphic_types::{EffectOperation, Effects}; use half::f16; - use raster_kernels::resample_kernels::{MAX_MOTION_BLUR_SAMPLES, MotionBlurShear, motion_blurred}; // Stripes repeating every two and three pixels along a strip, which a box sampling the wrong pixels of would average far off let (width, height) = (1400, 48); @@ -7558,27 +8638,51 @@ fn long_motion_blurs_spread_their_samples_alike_on_the_cpu_and_gpu() { [red, green, blue, alpha].map(f16::from_f32) }) .collect(); - let plane = raster_kernels::effect_kernels::Plane { - width, - height, - data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(), - }; - - // Lines past the most samples a box takes, so its samples lie two or three pixels apart, along the strip and slanting across it - for (angle, distance) in [(0., 1100.), (0., 2501.5), (4., 1300.)] { - let Some(shear) = MotionBlurShear::new(angle, distance, DMat2::IDENTITY, DVec2::ZERO) else { - panic!("a line {distance} long has shears") - }; - assert!(shear.stride() > 1. && shear.length > MAX_MOTION_BLUR_SAMPLES, "the box of a line {distance} long takes every pixel"); + // Lines past the 1024 samples a box takes at most, so its samples lie two or three whole pixels apart along the strip, along it and slanting across it + for (angle, distance, stride) in [(0., 1100., 2), (0., 2501.5, 3), (4., 1300., 2)] { let effects = Effects::from_operations([EffectOperation::MotionBlur { angle, distance, gamma: true }]); let Some(gpu) = gpu_effect_texels(&effects, &texels, width, &[]) else { return }; - let cpu = motion_blurred(&plane, &shear); - let levels = (gpu.iter().zip(&cpu.data)) - .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) - .fold(0_f32, f32::max); - assert!(levels <= 1., "a line {distance} long at {angle} degrees strays from the CPU's kernel by {levels} levels"); + // Samples a stride apart all land on one phase of the stripes repeating every stride, keeping its color, and spread evenly over the other's phases, averaging them. + // Where the line runs past the strip or across its hole, a phase may take a few samples more than another, skewing that mean by their share of what the line covers. + let line = distance * angle.to_radians().cos() + 1.; + let mut compared = 0; + for (index, &[red, green, _, alpha]) in gpu.iter().enumerate() { + if alpha < 0.25 { + continue; + } + let x = index % width; + let (expected, averaged) = match stride { + 2 => ([(x % 2) as f32, 0.5], [false, true]), + _ => ([0.5, (x % 3) as f32 / 2.], [true, false]), + }; + let skew = 3. * stride as f32 / 2. / (alpha * line as f32); + + for (channel, ((shown, expected), averaged)) in [red / alpha, green / alpha].into_iter().zip(expected).zip(averaged).enumerate() { + let tolerance = (1. + if averaged { skew * 255. } else { 0. }) / 255.; + assert!( + (shown - expected).abs() <= tolerance, + "a line {distance} long at {angle} degrees shows channel {channel} at {shown} rather than {expected} at ({x}, {})", + index / width + ); + } + compared += 1; + } + assert!( + compared >= width * height / 4, + "a line {distance} long at {angle} degrees leaves only {compared} pixels opaque enough to compare" + ); + + // Every channel follows PSD's sheared box, including the blue ramp a slanted line mixes across rows and the coverage the strip's edges and hole leave + let unblurred: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect(); + let reference = sheared_box_blurred(&unblurred, width, angle, distance, DAffine2::IDENTITY); + let differences = gpu + .iter() + .zip(&reference) + .flat_map(|(shown, expected)| (0..4).map(move |channel| (shown[channel] - expected[channel]).abs())); + let worst = differences.fold(0., f32::max) * 255.; + assert!(worst <= 1., "a line {distance} long at {angle} degrees strays from PSD's sheared box by up to {worst} levels"); } } @@ -7687,7 +8791,7 @@ fn radial_blurs_reach_as_far_inside_faded_groups_and_from_out_of_view() { } #[test] -fn resampling_effects_match_on_the_cpu_and_gpu() { +fn resampling_effects_match_their_definitions() { use glam::DVec2; use graphic_types::vector_types::GradientSpread; use graphic_types::{EffectOperation, RadialBlurMethod, WaveType}; @@ -7865,10 +8969,11 @@ fn resampling_effects_match_on_the_cpu_and_gpu() { for effects in cases.into_iter().chain(displacements).chain(fields) { for fill in [1., 0.5] { - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., &effects, fill), UVec2::new(160, 160)) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., &effects, fill), UVec2::new(160, 160), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{effects:?} at fill {fill} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{effects:?} at fill {fill} strays from its definition by up to {worst} levels"); } } } @@ -7878,9 +8983,10 @@ fn resampling_effects_match_on_turned_zoomed_and_oblong_content() { use core_types::list::Item; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use glam::DVec2; - use graphic_types::raster_types::{Image, Raster}; + use graphic_types::raster_types::{CPU, Image, Raster}; use graphic_types::vector_types::GradientSpread; - use graphic_types::{EffectOperation, RadialBlurMethod, WaveType, stamp_effect}; + use graphic_types::{EffectOperation, Graphic, RadialBlurMethod, WaveType, stamp_effect}; + use rendering::{Render, RenderParams}; // An oblong raster of 60 by 36 pixels, two to each document unit, upright or turned a quarter and viewed at twice the size, so its pixels land on the render's let level = |channel: f32| (channel * 255.).round() / 255.; @@ -7974,19 +9080,58 @@ fn resampling_effects_match_on_turned_zoomed_and_oblong_content() { halftone(3., DVec2::new(7.4, 2.9), 65.), halftone(0.75, DVec2::ZERO, 0.), ]; - let cases = cases.into_iter().chain(pixelations).collect::>(); + + let size = UVec2::new(160, 160); + let view = DAffine2::from_scale(DVec2::splat(2.)); + let draw = |item: &Item>| { + let graphic = Graphic::RasterCPU(Box::new(item.clone())); + render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + + // Stamped on each placement where it lies, each effect but the pixelations shows what its definition reads for each pixel for placement in [upright, turned] { let displacements = [across_and_down(placement), angled(placement)]; for effect in displacements.iter().chain(&warps(placement)).chain(&cases) { - let Some(worst) = gpu_and_cpu_difference_in_view(content(placement, std::slice::from_ref(effect)), UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else { - return; - }; if matches!(effect, EffectOperation::Displace { .. }) && filters_8_bit_images_to_whole_levels() { continue; } - assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels"); + let Some((worst, compared)) = resampled_difference(&content(placement, std::slice::from_ref(effect)), size, view) else { + return; + }; + assert!(compared >= 1000, "{effect:?} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{effect:?} strays from its definition by up to {worst} levels"); } } + + // Stamped upright and then turned onto the turned one's place, each effect turns along with it, so the render turns pixel for pixel + let turn = view * turned * upright.inverse() * view.inverse(); + let displacements = [across_and_down(upright), angled(upright)]; + for effect in displacements.iter().chain(&warps(upright)).chain(&cases).chain(&pixelations) { + if matches!(effect, EffectOperation::Displace { .. }) && filters_8_bit_images_to_whole_levels() { + continue; + } + let upright_item = content(upright, std::slice::from_ref(effect)); + let turned_item = upright_item.clone().with_attribute(ATTR_TRANSFORM, turned); + let (Some(upright_render), Some(turned_render)) = (draw(&upright_item), draw(&turned_item)) else { + return; + }; + + let mut worst = 0_f32; + for (index, &upright_pixel) in upright_render.iter().enumerate() { + let middle = DVec2::new((index as u32 % size.x) as f64 + 0.5, (index as u32 / size.x) as f64 + 0.5); + let turned_position = turn.transform_point2(middle).floor(); + if turned_position.cmplt(DVec2::ZERO).any() || turned_position.cmpge(size.as_dvec2()).any() { + continue; + } + + let (expected, actual) = ( + premultiplied_levels(upright_pixel), + premultiplied_levels(pixel(&turned_render, size, turned_position.x as u32, turned_position.y as u32)), + ); + worst = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(worst, f32::max); + } + assert!(worst <= 3., "{effect:?} turned along with its content differs from the upright render turned by up to {worst} levels"); + } } /// Each warp, acting within the frame the `transform` places. @@ -8013,7 +9158,7 @@ fn warps_within(transform: DAffine2) -> [graphic_types::EffectOperation; 7] { } #[test] -fn warps_match_on_the_cpu_and_gpu_within_small_offset_and_turned_slanted_frames() { +fn warps_match_their_definitions_within_small_offset_and_turned_slanted_frames() { use glam::DVec2; // Within the image 50 pixels across, measured from its corner: a circle about a third its size toward its bottom right, and an oblong one turned and slanted about its middle @@ -8021,10 +9166,11 @@ fn warps_match_on_the_cpu_and_gpu_within_small_offset_and_turned_slanted_frames( let slanted = DAffine2::from_translation(DVec2::new(24., 26.)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[40., 0., 12., 24., 0., 0.]); for warp in [small, slanted].into_iter().flat_map(warps_within) { for fill in [1., 0.5] { - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160)) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{warp:?} at fill {fill} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{warp:?} at fill {fill} strays from its definition by up to {worst} levels"); } } } @@ -8039,8 +9185,15 @@ fn warps_paint_as_far_as_their_ellipse_or_square_reaches_past_the_content() { let size = UVec2::new(160, 160); for warp in warps_within(transform) { let item = patterned_raster(55., std::slice::from_ref(&warp), 1.); - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels"); + let Some((worst, compared)) = resampled_difference(&item, size, DAffine2::IDENTITY) else { return }; + assert!(compared >= 1000, "{warp:?} leaves only {compared} pixels certain enough to compare"); + + // Mesa's asin errs by up to 5e-5, moving the reads of an outward Spherize in this frame 75 texels in radius by 0.0024 texels, or 0.6 levels across a hard edge + let tolerance = match warp { + graphic_types::EffectOperation::Spherize { amount, .. } if amount > 0. => 3.6, + _ => 3., + }; + assert!(worst <= tolerance, "{warp:?} strays from its definition by up to {worst} levels"); // All but pinching inward and wrapping, which gather the content toward the middle, paint more than 5 past the content from (55, 55) to (105, 105) rather than being cut off at its bounds let graphic = graphic_types::Graphic::RasterCPU(Box::new(item)); @@ -8096,16 +9249,17 @@ fn warps_within_the_identity_or_a_collapsed_transform_change_nothing_else_unless assert!(difference <= 2., "{warp:?} shows {actual:?} at ({x}, {y}) rather than {expected:?}"); } - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), 1.), size) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., std::slice::from_ref(&warp), 1.), size, view) else { return; }; - assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{warp:?} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{warp:?} strays from its definition by up to {worst} levels"); } } } #[test] -fn warps_past_full_strength_fold_alike_on_the_cpu_and_gpu_reading_from_past_their_ellipse_and_the_view() { +fn warps_past_full_strength_fold_as_defined_reading_from_past_their_ellipse_and_the_view() { use glam::DVec2; use graphic_types::EffectOperation; @@ -8126,11 +9280,12 @@ fn warps_past_full_strength_fold_alike_on_the_cpu_and_gpu_reading_from_past_thei for warp in warps { for (view, fill) in [(DAffine2::IDENTITY, 1.), (DAffine2::IDENTITY, 0.5), (cropped, 1.)] { - let Some(worst) = gpu_and_cpu_difference_in_view(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160), view) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160), view) else { return; }; // Folds this strong magnify where they read, so the GPU's 32-bit rounding of each read shows as a level or two more - assert!(worst <= 5, "{warp:?} at fill {fill} in the view {view} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{warp:?} at fill {fill} in the view {view} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 5., "{warp:?} at fill {fill} in the view {view} strays from its definition by up to {worst} levels"); } } } @@ -8191,11 +9346,11 @@ fn polar_coordinates_read_nothing_past_a_square_too_small_to_cover_a_texel_on_th } #[test] -fn polar_coordinates_match_the_cpu_within_slanted_and_turned_squares() { +fn polar_coordinates_match_their_definition_within_slanted_and_turned_squares() { + use glam::DVec2; use graphic_types::resampling::{FrameWarp, warp_frame}; use graphic_types::{EffectOperation, Effects}; use half::f16; - use raster_kernels::resample_kernels::frame_warped; // Colors varying across a texture 180 texels square, around a hole and through a translucent band, so the squares' sides cut through edges and translucency let size = 180; @@ -8214,10 +9369,23 @@ fn polar_coordinates_match_the_cpu_within_slanted_and_turned_squares() { [red, green, blue, alpha].map(f16::from_f32) }) .collect(); - let plane = raster_kernels::effect_kernels::Plane { - width: size, - height: size, - data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(), + + // The content between the four texels around a point, clear past the texture + let content: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect(); + let texel_at = |x: i64, y: i64| match (0..size as i64).contains(&x) && (0..size as i64).contains(&y) { + true => content[y as usize * size + x as usize], + false => [0.; 4], + }; + let sample = |point: DVec2| -> [f32; 4] { + let position = point - 0.5; + let (corner, fraction) = (position.floor(), (position - position.floor()).as_vec2()); + let (x, y) = (corner.x as i64, corner.y as i64); + let [top_left, top_right, bottom_left, bottom_right] = [texel_at(x, y), texel_at(x + 1, y), texel_at(x, y + 1), texel_at(x + 1, y + 1)]; + std::array::from_fn(|channel| { + let top = top_left[channel] + (top_right[channel] - top_left[channel]) * fraction.x; + let bottom = bottom_left[channel] + (bottom_right[channel] - bottom_left[channel]) * fraction.x; + top + (bottom - top) * fraction.y + }) }; for transform in slanted_and_turned_squares() { @@ -8229,12 +9397,24 @@ fn polar_coordinates_match_the_cpu_within_slanted_and_turned_squares() { let (Some((warp, _)), Some(square)) = (FrameWarp::of(&operation), warp_frame(transform, DAffine2::IDENTITY)) else { panic!("{operation:?} has no square") }; - let cpu = frame_warped(&plane, &warp, &square); - let levels = (gpu.iter().zip(&cpu.data)) - .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) - .fold(0_f32, f32::max); - assert!(levels <= 1., "{operation:?} strays from the CPU's kernel by {levels} levels"); + // Each texel shows the content where the warp reads it, and past the square nothing, except within two texels of the square's sides there or where it reads, which have rules of their own + let (to_local, to_pixels, reach) = (square.pixels_to_local(), square.local_to_pixels(), 4. * square.pixel_extent()); + let past_sides_by = |local: DVec2, margin: DVec2| (local.abs() - (square.size / 2. + margin)).max_element() > 0.; + let (mut worst, mut compared) = (0_f32, 0); + for (index, texel) in gpu.iter().enumerate() { + let local = to_local.transform_point2(DVec2::new((index % size) as f64 + 0.5, (index / size) as f64 + 0.5)); + let source = warp.source(local, square.size); + let expected = match () { + _ if past_sides_by(local, reach) => [0.; 4], + _ if past_sides_by(local, -reach) || past_sides_by(source, -reach) => continue, + _ => sample(to_pixels.transform_point2(source)), + }; + worst = (0..4).map(|channel| (texel[channel] - expected[channel]).abs() * 255.).fold(worst, f32::max); + compared += 1; + } + assert!(compared >= 10_000, "{operation:?} leaves only {compared} texels certain enough to compare"); + assert!(worst <= 1., "{operation:?} strays from its definition by up to {worst} levels"); } } } @@ -8254,85 +9434,54 @@ fn polar_seam_squares() -> [DAffine2; 4] { ] } -/// A texture 160 texels square of opaque blue, as half floats and as the CPU's plane. -fn opaque_polar_content() -> (Vec<[half::f16; 4]>, raster_kernels::effect_kernels::Plane<[f32; 4]>) { - let texels = vec![[0.2, 0.6, 0.9, 1.].map(half::f16::from_f32); 160 * 160]; - let plane = raster_kernels::effect_kernels::Plane { - width: 160, - height: 160, - data: texels.iter().map(|texel| texel.map(half::f16::to_f32)).collect(), - }; - (texels, plane) -} - -/// The `plane` unwrapped within the square the `transform` places, then wrapped back within it, on the CPU. -fn polar_round_trip_on_the_cpu(plane: &raster_kernels::effect_kernels::Plane<[f32; 4]>, transform: DAffine2) -> raster_kernels::effect_kernels::Plane<[f32; 4]> { - use graphic_types::resampling::{FrameWarp, warp_frame}; - use raster_kernels::resample_kernels::frame_warped; - - let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else { - panic!("{transform} has no square") - }; - let unwrapped = frame_warped(plane, &FrameWarp::Polar { inverse: true }, &square); - frame_warped(&unwrapped, &FrameWarp::Polar { inverse: false }, &square) -} - #[test] fn polar_coordinates_round_trip_opaque_content_without_a_seam() { use glam::DVec2; use graphic_types::resampling::warp_frame; - - let (_, plane) = opaque_polar_content(); - for transform in polar_seam_squares() { - let round_trip = polar_round_trip_on_the_cpu(&plane, transform); - let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else { - panic!("{transform} has no square") - }; - let (to_local, half) = (square.pixels_to_local(), square.size / 2.); - - // Around the center and along the seam straight up from it, away from the rim, each texel shows the opaque content as those beside it do - for (index, texel) in round_trip.data.iter().enumerate() { - let (x, y) = (index % 160, index / 160); - let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); - if local.x.abs() > 1.5 || !(-half.y + 2. ..1.5).contains(&local.y) { - continue; - } - - let difference = texel.iter().zip(&plane.data[index]).map(|(actual, expected)| (actual - expected).abs()).fold(0., f32::max); - assert!(difference < 0.01, "({x}, {y}) on the seam within {transform} shows {texel:?}"); - } - } -} - -#[test] -fn polar_coordinates_round_trip_without_a_seam_on_the_gpu_as_on_the_cpu() { use graphic_types::{EffectOperation, Effects}; - let (texels, plane) = opaque_polar_content(); + // A texture 160 texels square of opaque blue + let blue = [0.2, 0.6, 0.9, 1.].map(half::f16::from_f32); + let texels = vec![blue; 160 * 160]; + for transform in polar_seam_squares() { let [unwrap, wrap] = [true, false].map(|inverse| EffectOperation::PolarCoordinates { inverse, transform }); let Some(gpu) = gpu_effect_texels(&Effects::from_operations([unwrap, wrap]), &texels, 160, &[]) else { return; }; - let cpu = polar_round_trip_on_the_cpu(&plane, transform); + let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else { + panic!("{transform} has no square") + }; - let levels = (gpu.iter().zip(&cpu.data)) - .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) - .fold(0_f32, f32::max); - assert!(levels <= 1., "the round trip within {transform} strays from the CPU's kernel by {levels} levels"); + // Within the square's ellipse, its center and the seam straight up from it included, each texel shows the opaque content, and past the square nothing, away from the rim and the sides + let (to_local, reach) = (square.pixels_to_local(), 4. * square.pixel_extent()); + let past_sides_by = |local: DVec2, margin: DVec2| (local.abs() - (square.size / 2. + margin)).max_element() > 0.; + let mut compared = 0; + for (index, texel) in gpu.iter().enumerate() { + let (x, y) = (index % 160, index / 160); + let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + let expected = match () { + _ if past_sides_by(local, reach) => [0.; 4], + _ if (local / (square.size / 2. - reach)).length() > 1. => continue, + _ => blue.map(half::f16::to_f32), + }; + + let levels = (0..4).map(|channel| (texel[channel] - expected[channel]).abs() * 255.).fold(0., f32::max); + assert!(levels <= 1., "({x}, {y}) within {transform} shows {texel:?} rather than {expected:?}"); + compared += 1; + } + assert!(compared >= 20_000, "the round trip within {transform} leaves only {compared} texels certain enough to compare"); } } #[test] -fn motion_blurs_of_negative_distances_smear_as_positive_ones_do_on_the_cpu_and_gpu() { +fn motion_blurs_of_negative_distances_smear_as_positive_ones_do() { use graphic_types::EffectOperation; use rendering::{Render, RenderParams}; let size = UVec2::new(160, 160); for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] { let [positive, negative] = [distance, -distance].map(|distance| patterned_raster(55., &[EffectOperation::MotionBlur { angle, distance, gamma: false }], 1.)); - let Some(worst) = gpu_and_cpu_difference(negative.clone(), size) else { return }; - assert!(worst <= 3, "a line {distance} long backward at {angle} degrees differs from the GPU by up to {worst} levels"); let draw = |item: &core_types::list::Item<_>| { let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); @@ -8344,7 +9493,7 @@ fn motion_blurs_of_negative_distances_smear_as_positive_ones_do_on_the_cpu_and_g } #[test] -fn elliptical_radial_blurs_match_on_the_cpu_and_gpu_whatever_their_transforms_size() { +fn elliptical_radial_blurs_match_their_definition_whatever_their_transforms_size() { use glam::DVec2; use graphic_types::{EffectOperation, RadialBlurMethod}; use rendering::{Render, RenderParams}; @@ -8379,10 +9528,11 @@ fn elliptical_radial_blurs_match_on_the_cpu_and_gpu_whatever_their_transforms_si for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] { for (center, shape) in centers.into_iter().flat_map(|center| shapes.map(|shape| (center, shape))) { let blur = radial(method, center * shape); - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&blur), 1.), size) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., std::slice::from_ref(&blur), 1.), size, DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{blur:?} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{blur:?} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{blur:?} strays from its definition by up to {worst} levels"); // Scaling the transform evenly changes nothing but rounding let (Some(blurred), Some(scaled)) = (draw(&blur), draw(&radial(method, center * shape * DAffine2::from_scale(DVec2::splat(6.))))) else { @@ -8558,7 +9708,7 @@ fn warps_bend_endless_gradients_within_their_circle() { } #[test] -fn frame_relative_effects_carry_what_earlier_effects_paint_past_the_frame_on_the_cpu_and_gpu() { +fn frame_relative_effects_carry_what_earlier_effects_paint_past_the_frame() { use glam::DVec2; use graphic_types::vector_types::GradientSpread; use graphic_types::{EffectKind, EffectOperation, WaveType}; @@ -8642,10 +9792,11 @@ fn frame_relative_effects_carry_what_earlier_effects_paint_past_the_frame_on_the for (earlier, effect) in [&shadow, &glow].into_iter().flat_map(|earlier| effects.iter().map(move |effect| (earlier, effect))) { for fill in [1., 0.5] { let chain = [earlier.clone(), effect.clone()]; - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., &chain, fill), UVec2::new(160, 160)) else { + let Some((worst, compared)) = resampled_difference(&patterned_raster(55., &chain, fill), UVec2::new(160, 160), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{chain:?} at fill {fill} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "{chain:?} at fill {fill} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "{chain:?} at fill {fill} strays from its definition by up to {worst} levels"); } } } @@ -8838,14 +9989,12 @@ fn frame_relative_effects_carry_a_shadow_past_a_turned_frame_without_holes_or_fa } #[test] -fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs_as_they_are_on_the_cpu_and_gpu() { +fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs_as_they_are() { use core_types::Color as GraphicColor; use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, List}; - use glam::DVec2; - use graphic_types::resampling::{DISPLACEMENT_NEUTRAL_LEVEL, EffectFrame, frame_of_bounds}; + use graphic_types::resampling::DISPLACEMENT_NEUTRAL_LEVEL; use graphic_types::vector_types::GradientSpread; use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector}; - use raster_kernels::effect_kernels::Plane; use rendering::{Render, RenderParams}; use vello_gpu::kurbo::Shape; @@ -8869,18 +10018,12 @@ fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))), ); - let frame = EffectFrame::new(frame_of_bounds([DVec2::new(left, 6.), DVec2::new(right, 26.)], DAffine2::IDENTITY), DAffine2::IDENTITY).unwrap(); for before in [None, Some(box_blur.clone())] { let plain = Graphic::Vector(Box::new(strip.clone().with_attribute(ATTR_EFFECTS, Effects::from_operations(before.clone())))); let Some(plain) = render(size, |scene| plain.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { return; }; - let plane = Plane { - width: size.x as usize, - height: size.y as usize, - data: plain.iter().map(|pixel| [pixel[3] as f32 / 255.; 4]).collect(), - }; let blurred = if before.is_some() { "blurred " } else { "" }; for edge_mode in [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect] { @@ -8894,14 +10037,12 @@ fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs let Some(gpu) = render(size, |scene| displaced.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { return; }; - let cpu = raster_kernels::resample_kernels::displaced(&plane, |_, _| DVec2::ZERO, &frame, edge_mode); - // Moved nowhere, each texel keeps the coverage it had, as the CPU's kernel keeps it - for (index, ((plain, gpu), cpu)) in plain.iter().zip(&gpu).zip(&cpu.data).enumerate() { - let cpu = (cpu[3] * 255.).round() as u8; + // Moved nowhere, each texel keeps the coverage it had + for (index, (plain, gpu)) in plain.iter().zip(&gpu).enumerate() { assert!( - plain[3].abs_diff(gpu[3]) <= 1 && cpu.abs_diff(gpu[3]) <= 1, - "texel {index} of the {blurred}strip from {left} to {right} draws {} rather than {} (the CPU's {cpu}) with {edge_mode:?}", + plain[3].abs_diff(gpu[3]) <= 1, + "texel {index} of the {blurred}strip from {left} to {right} draws {} rather than {} with {edge_mode:?}", gpu[3], plain[3] ); @@ -8912,7 +10053,64 @@ fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs } #[test] -fn displacement_maps_match_on_the_cpu_and_gpu() { +fn displacements_read_past_the_frame_as_each_edge_mode_defines() { + use core_types::list::Item; + use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Graphic, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Content of 8 by 8 pixels colored by their column and row, one to each of the render's, its frame's sides on the render's pixel boundaries + let size = UVec2::splat(24); + let placement = DAffine2::from_translation(DVec2::splat(8.)) * DAffine2::from_scale(DVec2::splat(8.)); + let color = |column: i32, row: i32| GraphicColor::from_gamma_srgb_channels(column as f32 / 7., row as f32 / 7., 0.5, 1.); + let data = (0..64).map(|index| color(index % 8, index / 8)).collect(); + let content = Item::new_from_element(Raster::new_cpu(Image { width: 8, height: 8, data })).with_attribute(ATTR_TRANSFORM, placement); + + // A black map moves the content its whole distance away from the angle, so each pixel reads the one 3 columns toward it + let black = gray_map(8, 8, placement, |_, _| 0.); + for (angle, step) in [(0., 3), (180., -3)] { + for edge_mode in [GradientSpread::Clear, GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect] { + let mut item = content.clone(); + stamp_effect(&mut item, stamped_at(&angle_displacement(black.clone(), angle, 3., edge_mode), placement)); + let graphic = Graphic::RasterCPU(Box::new(item)); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let (column, row) = (x as i32 - 8, y as i32 - 8); + let source = column + step; + let read = match edge_mode { + // The map lies only on the content, leaving nothing past its frame to move + _ if !(0..8).contains(&row) || !(0..8).contains(&column) => None, + GradientSpread::Clear => (0..8).contains(&source).then_some(source), + GradientSpread::Pad => Some(source.clamp(0, 7)), + GradientSpread::Repeat => Some(source.rem_euclid(8)), + // Folded back across each side, which reads its edge pixel twice + GradientSpread::Reflect => Some(match source { + ..0 => -1 - source, + 8.. => 15 - source, + _ => source, + }), + }; + + let shown = pixel(&pixels, size, x, y); + let context = format!("{edge_mode:?} along {angle} degrees shows {shown:?} at ({x}, {y})"); + let Some(source) = read else { + assert_eq!(shown[3], 0, "{context} rather than nothing"); + continue; + }; + let expected = color(source, row).to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as u8); + assert!(shown.iter().zip(expected).all(|(shown, expected)| shown.abs_diff(expected) <= 2), "{context} rather than {expected:?}"); + } + } + } +} + +#[test] +fn displacement_maps_match_their_definition() { use core_types::list::Item; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use glam::DVec2; @@ -8956,10 +10154,11 @@ fn displacement_maps_match_on_the_cpu_and_gpu() { ), ]; for (name, displace) in displacements { - let Some(worst) = gpu_and_cpu_difference(content(&[displace]), UVec2::new(160, 160)) else { + let Some((worst, compared)) = resampled_difference(&content(&[displace]), UVec2::new(160, 160), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "the {name} with {edge_mode:?} differs from the GPU by up to {worst} levels"); + assert!(compared >= 1000, "the {name} with {edge_mode:?} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "the {name} with {edge_mode:?} strays from its definition by up to {worst} levels"); } } } @@ -8990,25 +10189,28 @@ fn image_displacement_maps_take_their_own_adjustments_and_opacity() { stamp_effect(&mut item, stamped_at(&displace, on_content)); item }; - let data = (0..13 * 9) - .map(|index| { - let (x, y) = ((index % 13) as f32, (index / 13) as f32); - GraphicColor::from_gamma_srgb_channels((90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5, 1.) - }) - .collect(); - let plain = Raster::new_cpu(Image { width: 13, height: 9, data }); + let map_image = |inverted: bool| { + let data = (0..13 * 9) + .map(|index| { + let (x, y) = ((index % 13) as f32, (index / 13) as f32); + let [red, green, blue] = [(90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5].map(|channel| if inverted { 1. - channel } else { channel }); + GraphicColor::from_gamma_srgb_channels(red, green, blue, 1.) + }) + .collect(); + Item::new_from_element(Raster::new_cpu(Image { width: 13, height: 9, data })) + }; // An inverted map at half opacity moves the content half as far as its inverted pixels do - let mut adjusted = Item::new_from_element(plain.clone()).with_attribute(ATTR_OPACITY, 0.5); + let mut adjusted = map_image(false).with_attribute(ATTR_OPACITY, 0.5); stamp_effect(&mut adjusted, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert))); - let inverted = Item::new_from_element(raster_kernels::raster_effects::adjusted_raster(&plain, &[Adjustment::Invert])); + let inverted = map_image(true); let size = UVec2::new(160, 160); let rendered = |item: Item>| { let graphic = Graphic::RasterCPU(Box::new(item)); render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) }; - let Some(actual) = rendered(content(adjusted.clone(), 1.)) else { return }; + let Some(actual) = rendered(content(adjusted, 1.)) else { return }; let Some(expected) = rendered(content(inverted, 0.5)) else { return }; let worst = actual @@ -9018,11 +10220,6 @@ fn image_displacement_maps_take_their_own_adjustments_and_opacity() { .map(|(actual, expected)| actual.abs_diff(*expected)); let worst = worst.max().unwrap_or_default(); assert!(worst <= 3, "the map with its own adjustment and opacity differs by up to {worst} levels"); - - let Some(worst) = gpu_and_cpu_difference(content(adjusted, 1.), size) else { - return; - }; - assert!(worst <= 3, "the map with its own adjustment and opacity differs from the GPU by up to {worst} levels"); } /// A 50 by 50 opaque checkerboard of 5 pixel squares at (55, 55), one pixel per document unit, carrying `effects`. Its hard edges show a move by a fraction of a pixel as that fraction of their contrast. @@ -9046,7 +10243,7 @@ fn checkered_raster(effects: &[graphic_types::EffectOperation]) -> core_types::l } #[test] -fn displacement_maps_between_whole_levels_move_hard_edges_alike_on_the_cpu_and_gpu() { +fn displacement_maps_between_whole_levels_move_hard_edges_as_defined() { use core_types::list::Item; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use graphic_types::Graphic; @@ -9079,7 +10276,7 @@ fn displacement_maps_between_whole_levels_move_hard_edges_alike_on_the_cpu_and_g let color = Graphic::from(GraphicColor::from_gamma_srgb_channels(141.25 / 255., 113.75 / 255., 0.5, 1.)); // At these distances a level of a map's luminance moves the content about a pixel each way, so a level's fraction apart shows at every edge. - // The maps' colors of whole levels mix into luminances between them, which both renderers take from the same rounded colors. + // The maps' colors of whole levels mix into luminances between them, which the GPU and the reference take from the same rounded colors. let maps = [ ("gradient", gradient), ("stretched image", image(|_, _| 1.)), @@ -9092,19 +10289,20 @@ fn displacement_maps_between_whole_levels_move_hard_edges_alike_on_the_cpu_and_g GradientSpread::Pad => angle_displacement(map.clone(), 135., 181., edge_mode), _ => x_and_y_displacement((map.clone(), 128.), (map.clone(), -102.4), edge_mode), }; - let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[displace]), UVec2::new(160, 160)) else { - return; - }; if matches!(map, Graphic::RasterCPU(_)) && filters_8_bit_images_to_whole_levels() { continue; } - assert!(worst <= 3, "the {name} map with {edge_mode:?} differs from the GPU by up to {worst} levels"); + let Some((worst, compared)) = resampled_difference(&checkered_raster(&[displace]), UVec2::new(160, 160), DAffine2::IDENTITY) else { + return; + }; + assert!(compared >= 1000, "the {name} map with {edge_mode:?} leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "the {name} map with {edge_mode:?} strays from its definition by up to {worst} levels"); } } } #[test] -fn displacement_maps_draw_with_their_own_opacity_and_effects_on_the_cpu_and_gpu() { +fn displacement_maps_draw_with_their_own_opacity_and_effects() { use core_types::list::{Item, List}; use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor}; use graphic_types::raster_types::{CPU, Image, Raster}; @@ -9128,21 +10326,24 @@ fn displacement_maps_draw_with_their_own_opacity_and_effects_on_the_cpu_and_gpu( }; // An image at half opacity under a paint overlay, an effect it can't take into its pixels - let data = (0..13 * 9) - .map(|index| { - let (x, y) = ((index % 13) as f32, (index / 13) as f32); - GraphicColor::from_gamma_srgb_channels((90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5, 1.) - }) - .collect(); - let plain = Raster::new_cpu(Image { width: 13, height: 9, data }); + let map_image = |inverted: bool| { + let data = (0..13 * 9) + .map(|index| { + let (x, y) = ((index % 13) as f32, (index / 13) as f32); + let [red, green, blue] = [(90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5].map(|channel| if inverted { 1. - channel } else { channel }); + GraphicColor::from_gamma_srgb_channels(red, green, blue, 1.) + }) + .collect(); + Raster::new_cpu(Image { width: 13, height: 9, data }) + }; + let plain = map_image(false); let mut image = Item::new_from_element(plain.clone()).with_attribute(ATTR_OPACITY, 0.5_f64).with_attribute(ATTR_TRANSFORM, on_content); stamp_effect(&mut image, Effect::new(&color_overlay([0.2, 0.9, 0.5], BlendMode::Normal, 0.5))); // The plain image at half opacity in a group, and in a list at half opacity over itself inverted let placed = |raster: Raster| Item::new_from_element(Graphic::from(Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, on_content))); let group = Graphic::Graphic(Box::new(placed(plain.clone()).with_attribute(ATTR_OPACITY, 0.5_f64))); - let inverted = raster_kernels::raster_effects::adjusted_raster(&plain, &[Adjustment::Invert]); - let list = Graphic::GraphicList([placed(inverted), placed(plain).with_attribute(ATTR_OPACITY, 0.5_f64)].into_iter().collect::>()); + let list = Graphic::GraphicList([placed(map_image(true)), placed(plain).with_attribute(ATTR_OPACITY, 0.5_f64)].into_iter().collect::>()); let displace = |map: Graphic| angle_displacement(map, 140., 64., GradientSpread::Repeat); // Each with whether it draws a plain image straight from its 8-bit texture @@ -9155,13 +10356,14 @@ fn displacement_maps_draw_with_their_own_opacity_and_effects_on_the_cpu_and_gpu( ]; let size = UVec2::new(160, 160); for (name, map, plain_image) in maps { - let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[displace(map)]), size) else { - return; - }; if plain_image && filters_8_bit_images_to_whole_levels() { continue; } - assert!(worst <= 3, "the {name} map differs from the GPU by up to {worst} levels"); + let Some((worst, compared)) = resampled_difference(&checkered_raster(&[displace(map)]), size, DAffine2::IDENTITY) else { + return; + }; + assert!(compared >= 1000, "the {name} map leaves only {compared} pixels certain enough to compare"); + assert!(worst <= 3., "the {name} map strays from its definition by up to {worst} levels"); } } @@ -9260,29 +10462,22 @@ fn angled_displacements_match_those_across_and_down_by_the_angles_components() { let pairs = pairs.into_iter().chain([(angle_displacement(map.clone(), 0., 25., GradientSpread::Repeat), across_alone)]); let size = UVec2::new(160, 160); - let gpu = |displace: &EffectOperation| { + let draw = |displace: &EffectOperation| { let graphic = Graphic::RasterCPU(Box::new(checkered_raster(std::slice::from_ref(displace)))); render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) }; - let cpu = |displace: &EffectOperation| raster_kernels::evaluate_raster_effects(checkered_raster(std::slice::from_ref(displace))).element().data.clone(); for (angled, components) in pairs { - let levels = |color: &core_types::Color| color.to_gamma_srgb_channels().map(|channel| channel * 255.); - let cpu_worst = (cpu(&angled).iter().zip(&cpu(&components))) - .flat_map(|(angled, components)| levels(angled).into_iter().zip(levels(components)).map(|(angled, components)| (angled - components).abs())) - .fold(0., f32::max); - assert!(cpu_worst <= 1., "{angled:?} differs on the CPU from {components:?} by up to {cpu_worst} levels"); - - let (Some(angled_render), Some(components_render)) = (gpu(&angled), gpu(&components)) else { + let (Some(angled_render), Some(components_render)) = (draw(&angled), draw(&components)) else { return; }; - let gpu_worst = largest_difference(&angled_render, &components_render); - assert!(gpu_worst <= 1, "{angled:?} differs on the GPU from {components:?} by up to {gpu_worst} levels"); + let worst = largest_difference(&angled_render, &components_render); + assert!(worst <= 1, "{angled:?} differs from {components:?} by up to {worst} levels"); } } #[test] -fn unwired_displacement_maps_move_nothing_in_either_mode_on_the_cpu_and_gpu() { +fn unwired_displacement_maps_move_nothing_in_either_mode() { use graphic_types::vector_types::GradientSpread; use graphic_types::{EffectOperation, Graphic}; use rendering::{Render, RenderParams}; @@ -9303,10 +10498,7 @@ fn unwired_displacement_maps_move_nothing_in_either_mode_on_the_cpu_and_gpu() { let effects = [displace]; let Some(displaced) = rendered(&effects) else { return }; let worst = largest_difference(&displaced, &unmoved); - assert!(worst <= 1, "{effects:?} moves the content by up to {worst} levels on the GPU"); - - let Some(worst) = gpu_and_cpu_difference(checkered_raster(&effects), size) else { return }; - assert!(worst <= 1, "{effects:?} differs from the GPU by up to {worst} levels"); + assert!(worst <= 1, "{effects:?} moves the content by up to {worst} levels"); } } @@ -9388,7 +10580,7 @@ fn leveled_raster( } #[test] -fn color_halftones_with_large_dots_match_on_the_cpu_and_gpu() { +fn color_halftones_with_large_dots_print_as_defined() { use graphic_types::EffectOperation; // Dark content prints dots nearly filling their cells, up to the largest radius PSD interop brings. @@ -9405,20 +10597,21 @@ fn color_halftones_with_large_dots_match_on_the_cpu_and_gpu() { phase: 0., }; for (tone, color) in [("dark", &dark as &dyn Fn(u32, u32) -> [f32; 3]), ("light", &light)] { - let Some(worst) = gpu_and_cpu_difference(leveled_raster(28., UVec2::splat(200), 1., color, std::slice::from_ref(&halftone)), UVec2::splat(256)) else { + let raster = leveled_raster(28., UVec2::splat(200), 1., color, std::slice::from_ref(&halftone)); + let Some((worst, _)) = resampled_difference(&raster, UVec2::splat(256), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{tone} dots of radius {radius} differ from the GPU by up to {worst} levels"); + assert!(worst <= 3., "{tone} dots of radius {radius} stray from their definition by up to {worst} levels"); } } } #[test] -fn pixelations_averaging_sparsely_match_on_the_cpu_and_gpu() { +fn pixelations_summing_rows_of_texels_at_once_count_every_row_and_column() { use graphic_types::EffectOperation; - // A cell and a dot's square each hold more pixels than an average takes, so they're sampled every other one across and down. - // Red alternates by column and green by row, in levels just past steps of a half float, so sampling other columns or rows than the CPU's would change the colors. + // A cell and a dot's square each hold more texels than an average tests one by one, so it sums each row's run of them at once. + // Red alternates by column and green by row, in levels just past steps of a half float, so leaving out columns or rows would change the colors. let level = |odd: u32| (64 + 128 * odd) as f32 / 255.; let stripes = |x: u32, y: u32| [level(x % 2), level(y % 2), 128. / 255.]; let pixelate = EffectOperation::Pixelate { @@ -9434,10 +10627,11 @@ fn pixelations_averaging_sparsely_match_on_the_cpu_and_gpu() { phase: 0., }; for effect in [pixelate, halftone] { - let Some(worst) = gpu_and_cpu_difference(leveled_raster(10., UVec2::splat(300), 1., stripes, std::slice::from_ref(&effect)), UVec2::splat(320)) else { + let raster = leveled_raster(10., UVec2::splat(300), 1., stripes, std::slice::from_ref(&effect)); + let Some((worst, _)) = resampled_difference(&raster, UVec2::splat(320), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels"); + assert!(worst <= 3., "{effect:?} strays from its definition by up to {worst} levels"); } } @@ -9573,7 +10767,7 @@ fn pixelation_tables_wider_than_a_texture_allows_wrap_their_rows_rather_than_cha } #[test] -fn color_halftones_with_dots_under_a_unit_across_match_on_the_cpu_and_gpu() { +fn color_halftones_with_dots_under_a_unit_across_print_as_defined() { use graphic_types::EffectOperation; // Dark content of four pixels to each unit, viewed at four times the size so its pixels land on the render's. @@ -9588,17 +10782,15 @@ fn color_halftones_with_dots_under_a_unit_across_match_on_the_cpu_and_gpu() { phase: 0., }; let view = DAffine2::from_scale(glam::DVec2::splat(4.)); - let Some(worst) = gpu_and_cpu_difference_in_view(leveled_raster(4., UVec2::splat(128), 4., dark, &[halftone]), UVec2::splat(160), view) else { + let Some((worst, _)) = resampled_difference(&leveled_raster(4., UVec2::splat(128), 4., dark, &[halftone]), UVec2::splat(160), view) else { return; }; - assert!(worst <= 3, "the dots differ from the GPU by up to {worst} levels"); + assert!(worst <= 3., "the dots stray from their definition by up to {worst} levels"); } #[test] -fn color_halftones_of_dots_far_under_a_unit_apart_ink_each_texel_they_snap_together_to_reach_on_the_cpu_and_gpu() { +fn color_halftones_of_dots_far_under_a_unit_apart_ink_each_texel_they_snap_together_to_reach() { use glam::DVec2; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // Opaque black over a frame 4 units across and 2 units past each side, at 40 pixels to each unit, with dots of radius 0.05 on upright screens placed as PSD places them. // Lattice points up to a unit and a half away snap together onto each whole unit, where the 98 at (-1, 1) from the frame's corner fill their dot. @@ -9608,30 +10800,22 @@ fn color_halftones_of_dots_far_under_a_unit_apart_ink_each_texel_they_snap_toget DAffine2::from_scale(DVec2::splat(40.)) * DAffine2::from_translation(DVec2::splat(2.)), ); let halftone = psd_color_halftone(0.05, [0.; 3], DVec2::splat(4.)); - let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| { + let Some((pixels, differences)) = pixelated_in_frame(&halftone, frame, effect_space, bounds, size, 40, |scene| { scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &bounds); }) else { return; }; assert_eq!(pixel(&pixels, size, 40, 120), [0, 0, 0, 255], "the texel past the frame's side nearest the unit at (-1, 1) isn't inked"); - // The CPU's halftone of the same texels and frame - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = vec![[0., 0., 0., 1.]; (size.x * size.y) as usize]; - let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else { - panic!("the frame doesn't collapse") - }; - let expected = cpu_pixelated(&halftone, &plane, &frame); - for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}"); + for (index, difference) in differences.into_iter().enumerate() { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + let difference = difference.unwrap_or_else(|| panic!("({x}, {y}) is uncertain")); + assert!(difference <= 3., "({x}, {y}) shows {:?}, {difference} levels from its definition", pixel(&pixels, size, x, y)); } } #[test] -fn color_halftones_under_a_fill_print_what_lies_beneath_the_content_alike_on_the_cpu_and_gpu() { +fn color_halftones_under_a_fill_print_what_lies_beneath_the_content() { use core_types::list::Item; use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use glam::DVec2; @@ -9667,8 +10851,10 @@ fn color_halftones_under_a_fill_print_what_lies_beneath_the_content_alike_on_the .with_attribute(ATTR_OPACITY_FILL, fill); shadows.iter().chain([&halftone]).for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); - let Some(worst) = gpu_and_cpu_difference(item, UVec2::splat(48)) else { return }; - assert!(worst <= 3, "at fill {fill} and radius {radius}, the halftone differs from the GPU by up to {worst} levels"); + let Some((worst, _)) = resampled_difference(&item, UVec2::splat(48), DAffine2::IDENTITY) else { + return; + }; + assert!(worst <= 3., "at fill {fill} and radius {radius}, the halftone strays from its definition by up to {worst} levels"); } } @@ -9676,39 +10862,36 @@ fn color_halftones_under_a_fill_print_what_lies_beneath_the_content_alike_on_the fn color_halftones_ink_nothing_of_the_contents_edge_at_a_frame_cutting_through_texels() { use glam::DVec2; use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // A black square from 10.3 to 30.3 amid its hard white shadow, so the frame's sides cut through texels holding the content's antialiased edge, with its origin at its corner and its dots placed as PSD places them let shadow = drop_shadow(core_types::Color::WHITE, DVec2::ZERO, 12., 100.); let halftone = psd_color_halftone(4. * std::f64::consts::SQRT_2, [0., 90., 180.], DVec2::splat(20.)); let (size, effect_space) = (UVec2::splat(48), DAffine2::from_translation(DVec2::splat(10.3))); - let Some(pixels) = render_square_over_backdrop_in(vec![shadow, halftone.clone()], effect_space, 1., 1., BlendMode::Normal, None, Color::BLACK, 10.3, 30.3, size) else { + let Some(pixels) = render_square_over_backdrop_in(vec![shadow.clone(), halftone.clone()], effect_space, 1., 1., BlendMode::Normal, None, Color::BLACK, 10.3, 30.3, size) else { return; }; - // The CPU's halftone of the square as its dots should read it, black wherever a texel's center lies within the frame and white past it - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y) - .map(|index| { - if (10..30).contains(&(index % size.x)) && (10..30).contains(&(index / size.x)) { - [0., 0., 0., 1.] - } else { - [1.; 4] - } - }) - .collect(); - let Some(frame) = EffectFrame::new(DAffine2::from_scale(DVec2::splat(20.)), effect_space) else { + // The halftone's definition over the square and its shadow, read as far as 16 pixels past each side of the render + let (margin, padding) = (16, DAffine2::from_translation(DVec2::splat(16.))); + let Some(before) = render_square_over_backdrop_in_view(vec![shadow], effect_space, padding, 1., 1., BlendMode::Normal, None, Color::BLACK, 10.3, 30.3, size + 2 * margin) else { + return; + }; + let before: Vec<[f32; 4]> = before.into_iter().map(premultiplied_unit).collect(); + let Some(frame) = EffectFrame::new(DAffine2::from_scale(DVec2::splat(20.)), padding * effect_space) else { panic!("the square has a frame") }; - let expected = cpu_pixelated(&halftone, &plane, &frame); + let expected = pixelated_reference(&halftone, &before, &before, size.x + 2 * margin, &frame, [UVec2::splat(margin), size]); // Within the shadow, the dots take their ink only from texels the frame covers wholly or not at all, so the edge's gray changes none of them + let mut compared = 0; for (x, y) in (4..=36).flat_map(|y| (4..=36).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}"); + let Some(expected) = expected[(y * size.x + x) as usize] else { continue }; + let (expected, shown) = (expected.map(|channel| channel * 255.), premultiplied_levels(pixel(&pixels, size, x, y))); + let worst = (0..4).map(|channel| (expected[channel] - shown[channel]).abs()).fold(0., f32::max); + assert!(worst <= 3., "({x}, {y}) shows {shown:?} rather than {expected:?}"); + compared += 1; } + assert!(compared >= 900, "only {compared} texels lie wholly within the frame or past it"); } /// Renders `draw` through the `effect` placed in the `frame`, with the content within `bounds`, in an `effect_space` placed in the document. @@ -9726,21 +10909,35 @@ fn render_with_effect_in_frame( }) } -/// The CPU's Pixelate or Color Halftone of a premultiplied `plane` in the `frame`, as the `effect` makes it. -fn cpu_pixelated( - effect: &graphic_types::EffectOperation, - plane: &raster_kernels::effect_kernels::Plane<[f32; 4]>, - frame: &graphic_types::resampling::EffectFrame, -) -> raster_kernels::effect_kernels::Plane<[f32; 4]> { - use graphic_types::EffectOperation; - use graphic_types::resampling::HalftoneScreen; - use raster_kernels::resample_kernels::{halftoned, pixelated}; +/// A render's pixels, with how many levels each strays from its reference (`None` where that's uncertain). +type PixelsAndDifferences = (Vec<[u8; 4]>, Vec>); - match (effect, HalftoneScreen::of(effect, frame)) { - (&EffectOperation::Pixelate { cell_size, offset }, _) => pixelated(plane, cell_size, offset, frame), - (_, Some(screens)) => halftoned(plane, &screens, frame), - _ => panic!("{effect:?} isn't a pixelation"), - } +/// Renders `draw` through the pixelation `effect` as [`render_with_effect_in_frame`] does, with how many levels each pixel strays from [`pixelated_reference`] (`None` where that's uncertain). +/// The reference reads what `draw` draws as far as `margin` pixels past each side of the render. `None` without a GPU. +fn pixelated_in_frame( + effect: &graphic_types::EffectOperation, + frame: DAffine2, + effect_space: DAffine2, + bounds: Rect, + size: UVec2, + margin: u32, + mut draw: impl FnMut(&mut VelloSceneBuilder), +) -> Option { + let pixels = render_with_effect_in_frame(effect.clone(), frame, effect_space, bounds, size, &mut draw)?; + + let padding = DAffine2::from_translation(glam::DVec2::splat(margin as f64)); + let before = render_precise_in_view(size + 2 * margin, padding, &mut draw)?; + let Some(padded_frame) = graphic_types::resampling::EffectFrame::new(effect_space.inverse() * frame, padding * effect_space) else { + panic!("the frame collapses") + }; + let reference = pixelated_reference(effect, &before, &before, size.x + 2 * margin, &padded_frame, [UVec2::splat(margin), size]); + + let differences = pixels.iter().zip(reference).map(|(&shown, expected)| { + let (shown, expected) = (premultiplied_levels(shown), expected?); + Some((0..4).map(|channel| (shown[channel] - expected[channel] * 255.).abs()).fold(0., f32::max)) + }); + let differences = differences.collect(); + Some((pixels, differences)) } /// For PSD interop, a color halftone of dots up to `radius` across on screens at `angles`, placed as PSD places them on content `size` across with its origin at its frame's corner. @@ -9756,12 +10953,10 @@ fn psd_color_halftone(radius: f64, [red_angle, green_angle, blue_angle]: [f64; 3 } } -/// Asserts that the `effect`, placed in a frame leaning `lean` radians from flat, leaves a square from (12, 12) to (52, 52) of black and white columns a pixel wide as it is, on the CPU and GPU alike. +/// Asserts that the `effect`, placed in a frame leaning `lean` radians from flat, leaves a square from (12, 12) to (52, 52) of black and white columns a pixel wide as it is. /// Each row of texels lies in a row of the frame's cells of its own, and runs across cells or dots holding a few texels each. fn assert_stripes_stay_in_a_frame_leaning_nearly_flat(effect: graphic_types::EffectOperation, lean: f64) { use glam::DVec2; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; let frame = DAffine2::from_cols(DVec2::new(40., 0.), DVec2::new(lean.cos(), lean.sin()) * 40., DVec2::splat(12.)); let square = Rect::new(12., 12., 52., 52.); @@ -9781,34 +10976,12 @@ fn assert_stripes_stay_in_a_frame_leaning_nearly_flat(effect: graphic_types::Eff let worst = (0..4).map(|channel| actual[channel].abs_diff(expected[channel])).max().unwrap_or_default(); assert!(worst <= 1, "{effect:?} leaning {lean} shows {actual:?} at ({}, {}) rather than {expected:?}", index % 64, index / 64); } - - // The CPU's result on the same texels and frame - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y) - .map(|index| match ((12..52).contains(&(index % size.x)) && (12..52).contains(&(index / size.x)), index % 2 == 0) { - (true, true) => [0., 0., 0., 1.], - (true, false) => [1.; 4], - (false, _) => [0.; 4], - }) - .collect(); - let Some(frame) = EffectFrame::new(frame, DAffine2::IDENTITY) else { - panic!("the frame doesn't collapse") - }; - let expected = cpu_pixelated(&effect, &plane, &frame); - for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&with_effect, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 1., "{effect:?} leaning {lean} shows {gpu:?} at ({x}, {y}) on the GPU rather than {cpu:?} as on the CPU"); - } } #[test] -fn pixelations_of_more_texels_than_an_average_tests_one_by_one_match_on_the_cpu_and_gpu_in_a_skewed_frame() { +fn pixelations_of_more_texels_than_an_average_tests_one_by_one_match_their_definitions_in_a_skewed_frame() { use glam::DVec2; use graphic_types::EffectOperation; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // Black and white columns a texel wide over a square from 16 to 496, under a frame turned and skewed off the texels, so its sides cut through them let (size, square) = (UVec2::splat(512), Rect::new(16., 16., 496., 496.)); @@ -9819,20 +10992,6 @@ fn pixelations_of_more_texels_than_an_average_tests_one_by_one_match_on_the_cpu_ scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(x as f64, 16., x as f64 + 1., 496.)); } }; - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y) - .map(|index| { - let (x, y) = (index % size.x, index / size.x); - match ((16..496).contains(&x) && (16..496).contains(&y), x % 2 == 0) { - (true, true) => [0., 0., 0., 1.], - (true, false) => [1.; 4], - (false, _) => [0.; 4], - } - }) - .collect(); - let Some(frame) = EffectFrame::new(placement, DAffine2::IDENTITY) else { - panic!("the frame doesn't collapse") - }; // Cells and dot squares wider than an average tests one by one, within the frame, past its sides, and cut by them let pixelate = EffectOperation::Pixelate { @@ -9850,16 +11009,20 @@ fn pixelations_of_more_texels_than_an_average_tests_one_by_one_match_on_the_cpu_ // Within the square, since the render draws a frame-relative effect no farther than the content's bounds and what earlier effects paint past them for effect in [pixelate, halftone] { - let expected = cpu_pixelated(&effect, &plane, &frame); - let Some(pixels) = render_with_effect_in_frame(effect.clone(), placement, DAffine2::IDENTITY, square, size, draw_stripes) else { + let Some((pixels, differences)) = pixelated_in_frame(&effect, placement, DAffine2::IDENTITY, square, size, 480, draw_stripes) else { return; }; + let mut compared = 0; for (x, y) in (16..496).flat_map(|y| (16..496).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "{effect:?} shows {gpu:?} at ({x}, {y}) rather than {cpu:?}"); + let Some(difference) = differences[(y * size.x + x) as usize] else { continue }; + assert!( + difference <= 3., + "{effect:?} shows {:?} at ({x}, {y}), {difference} levels from its definition", + pixel(&pixels, size, x, y) + ); + compared += 1; } + assert!(compared >= 200_000, "{effect:?} leaves only {compared} texels certain enough to compare"); } } @@ -9892,7 +11055,7 @@ fn color_halftones_with_far_more_dots_than_texels_print_their_tone() { } #[test] -fn color_halftones_over_regions_far_wider_than_tall_match_on_the_cpu_and_gpu() { +fn color_halftones_over_regions_far_wider_than_tall_print_as_defined() { use graphic_types::EffectOperation; // A strip 1024 by 64 texels, with dots 2.8 texels apart on screens turned from its axes. @@ -9907,10 +11070,10 @@ fn color_halftones_over_regions_far_wider_than_tall_match_on_the_cpu_and_gpu() { phase: 0., }; let size = UVec2::new(1024, 64); - let Some(worst) = gpu_and_cpu_difference(leveled_raster(0., size, 1., gradient, &[halftone]), size) else { + let Some((worst, _)) = resampled_difference(&leveled_raster(0., size, 1., gradient, &[halftone]), size, DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "the dots differ from the GPU by up to {worst} levels"); + assert!(worst <= 3., "the dots stray from their definition by up to {worst} levels"); } #[test] @@ -9938,10 +11101,9 @@ fn pixelate_cells_hundreds_of_texels_wide_hold_the_texels_up_to_their_boundaries } #[test] -fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_same_texels_on_the_cpu_and_gpu() { +fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_texels_they_are_defined_to() { use glam::DVec2; use graphic_types::resampling::{EffectFrame, HalftoneScreen}; - use raster_kernels::effect_kernels::Plane; // Dots of radius 256 square to a frame 1024 across, placed as PSD places them, seen through a window holding the dot at the frame's center and the column of texels just before its box's near side let frame_size = DVec2::splat(1024.); @@ -9956,34 +11118,23 @@ fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_same_texels_on_the_ // White but for that column, which only the box of the dot before it holds, and that dot lies outside the window let (size, bounds) = (UVec2::new(264, 6), Rect::new(0., 0., 264., 6.)); let column = (center.x - 257. - window.x) as u32; - let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| { + let Some((pixels, differences)) = pixelated_in_frame(&halftone, frame, effect_space, bounds, size, 640, |scene| { scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &bounds); scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(column as f64, 0., column as f64 + 1., 6.)); }) else { return; }; - // The CPU's halftone of the same window - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y).map(|index| if index % size.x == column { [0., 0., 0., 1.] } else { [1.; 4] }).collect(); - let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else { - panic!("the window has a frame") - }; - let expected = cpu_pixelated(&halftone, &plane, &frame); - - for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 1., "({x}, {y}) shows {gpu:?} rather than {cpu:?}"); + for (index, difference) in differences.into_iter().enumerate() { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + let difference = difference.unwrap_or_else(|| panic!("({x}, {y}) is uncertain")); + assert!(difference <= 1., "({x}, {y}) shows {:?}, {difference} levels from its definition", pixel(&pixels, size, x, y)); } } #[test] -fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_row_a_tie_nudge_brings_into_them_on_the_cpu_and_gpu() { +fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_row_a_tie_nudge_brings_into_them() { use glam::DVec2; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // A frame 1000 units across at 2 texels to each unit from (10.53125, 10.53125), with its origin there, seen through a window from texel 770. // The box of the dot of radius 127 nearest its center, placed as PSD places it, starts at 8.53125, a 32nd of a texel past row 8's centers, which a tie's nudge of a 16th of a texel brings within it. @@ -9995,7 +11146,7 @@ fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_row_a_tie_nudge_bri let halftone = psd_color_halftone(127., [0.; 3], DVec2::splat(1000.)); // White but for that row, which inks the dot at (262.5, 262.5) about 13 texels across - let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| { + let Some((pixels, differences)) = pixelated_in_frame(&halftone, frame, effect_space, bounds, size, 560, |scene| { scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &bounds); scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(0., 8., 280., 9.)); }) else { @@ -10003,19 +11154,10 @@ fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_row_a_tie_nudge_bri }; assert_eq!(pixel(&pixels, size, 262, 262), [0, 0, 0, 255], "the dot's center isn't inked"); - // The CPU's halftone of the same window - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y).map(|index| if index / size.x == 8 { [0., 0., 0., 1.] } else { [1.; 4] }).collect(); - let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else { - panic!("the window has a frame") - }; - let expected = cpu_pixelated(&halftone, &plane, &frame); - - for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}"); + for (index, difference) in differences.into_iter().enumerate() { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + let difference = difference.unwrap_or_else(|| panic!("({x}, {y}) is uncertain")); + assert!(difference <= 3., "({x}, {y}) shows {:?}, {difference} levels from its definition", pixel(&pixels, size, x, y)); } } @@ -10043,18 +11185,13 @@ fn pixelate_cells_cut_by_the_frames_far_sides_keep_the_contents_edge() { } #[test] -fn color_halftone_dots_snap_alike_on_the_cpu_and_gpu_across_a_vast_frame() { +fn color_halftone_dots_snap_as_defined_across_a_vast_frame() { use glam::DVec2; - use graphic_types::Effects; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // A gray square 8001 across with its origin at its corner, viewed where dots of its red screen, placed as PSD places them, lie within a ten-thousandth of a unit of a tie between two whole units from its corner. // Single precision can't tell those apart there. let halftone = psd_color_halftone(8., [108., 162., 90.], DVec2::splat(8001.)); - let effects = Effects::from_operations([halftone.clone()]); - let gray = 128. / 255.; - let (size, margin) = (UVec2::splat(64), 32); + let size = UVec2::splat(64); for near_tie in [ DVec2::new(370., 7376.), @@ -10066,45 +11203,28 @@ fn color_halftone_dots_snap_alike_on_the_cpu_and_gpu_across_a_vast_frame() { let corner = DVec2::splat(32.) - near_tie; let placement = DAffine2::from_translation(corner) * DAffine2::from_scale(DVec2::splat(8001.)); let square = Rect::new(corner.x, corner.y, corner.x + 8001., corner.y + 8001.); - let pixels = render(size, |scene| { - scene.draw_effects( - &effects, - 1., - 1., - BlendMode::Normal, - true, - Some(square), - DAffine2::from_translation(corner), - Some((placement, 0.)), - &mut |_, _| {}, - &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(128, 128, 128), None, &square), - ) - }); - let Some(pixels) = pixels else { return }; - - // The CPU's halftone of the same part of the square, with a margin holding all that the dots in view average - let mut plane = Plane::<[f32; 4]>::new((size.x + 2 * margin) as usize, (size.y + 2 * margin) as usize); - plane.data.fill([gray, gray, gray, 1.]); - let Some(frame) = EffectFrame::new(DAffine2::from_scale(DVec2::splat(8001.)), DAffine2::from_translation(DVec2::splat(margin as f64) + corner)) else { - panic!("the square has a frame") + let Some((pixels, differences)) = pixelated_in_frame(&halftone, placement, DAffine2::from_translation(corner), square, size, 32, |scene| { + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(128, 128, 128), None, &square); + }) else { + return; }; - let expected = cpu_pixelated(&halftone, &plane, &frame); - for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let cpu = expected.data[((y + margin) * (size.x + 2 * margin) + x + margin) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "near {near_tie}, ({x}, {y}) shows {gpu:?} rather than {cpu:?}"); + for (index, difference) in differences.into_iter().enumerate() { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + let difference = difference.unwrap_or_else(|| panic!("near {near_tie}, ({x}, {y}) is uncertain")); + assert!( + difference <= 3., + "near {near_tie}, ({x}, {y}) shows {:?}, {difference} levels from its definition", + pixel(&pixels, size, x, y) + ); } } } #[test] -fn pixelations_far_from_the_contents_origin_match_on_the_cpu_and_gpu() { +fn pixelations_far_from_the_contents_origin_match_their_definitions() { use glam::DVec2; use graphic_types::EffectOperation; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // A square of four colors from 8 to 56 with its origin 100,000 units away, under cells and dots placed back on it, which single precision can't place from that origin let (size, square) = (UVec2::splat(64), Rect::new(8., 8., 56., 56.)); @@ -10125,21 +11245,6 @@ fn pixelations_far_from_the_contents_origin_match_on_the_cpu_and_gpu() { } }; - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y) - .map(|index| { - let (x, y) = (index % size.x, index / size.x); - if !(8..56).contains(&x) || !(8..56).contains(&y) { - return [0.; 4]; - } - let [red, green, blue] = quadrant_color(x, y).map(|level| level as f32 / 255.); - [red, green, blue, 1.] - }) - .collect(); - let Some(cpu_frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else { - panic!("the square has a frame") - }; - // Then cells and screens placed far away themselves, with boundaries and dots hundreds of millions of cells from where they're placed let pixelate = |cell_size, offset| EffectOperation::Pixelate { cell_size, offset }; let halftone = |offset, phase| EffectOperation::ColorHalftone { @@ -10152,25 +11257,24 @@ fn pixelations_far_from_the_contents_origin_match_on_the_cpu_and_gpu() { }; let effects = [pixelate(5.3, on_square), halftone(on_square, 40.), pixelate(1e9, on_square), halftone(DVec2::splat(-1e9), 0.)]; for effect in effects { - let Some(pixels) = render_with_effect_in_frame(effect.clone(), frame, effect_space, square, size, draw_quadrants) else { + let Some((pixels, differences)) = pixelated_in_frame(&effect, frame, effect_space, square, size, 16, draw_quadrants) else { return; }; - let expected = cpu_pixelated(&effect, &plane, &cpu_frame); for (x, y) in (8..56).flat_map(|y| (8..56).map(move |x| (x, y))) { - let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.); - let gpu = premultiplied_levels(pixel(&pixels, size, x, y)); - let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max); - assert!(worst <= 3., "{effect:?} shows {gpu:?} at ({x}, {y}) rather than {cpu:?}"); + let difference = differences[(y * size.x + x) as usize].unwrap_or_else(|| panic!("{effect:?} leaves ({x}, {y}) uncertain")); + assert!( + difference <= 3., + "{effect:?} shows {:?} at ({x}, {y}), {difference} levels from its definition", + pixel(&pixels, size, x, y) + ); } } } #[test] -fn pixelate_cells_far_wider_than_the_frame_meet_where_they_lie_within_it_on_the_gpu() { +fn pixelate_cells_far_wider_than_the_frame_meet_where_they_lie_within_it() { use glam::DVec2; use graphic_types::EffectOperation; - use graphic_types::resampling::EffectFrame; - use raster_kernels::effect_kernels::Plane; // An opaque square 64 across with its origin at its corner, black on its left half and white on its right, in cells 10^9 across meeting at its middle let (size, square) = (UVec2::splat(64), Rect::new(0., 0., 64., 64.)); @@ -10179,25 +11283,17 @@ fn pixelate_cells_far_wider_than_the_frame_meet_where_they_lie_within_it_on_the_ cell_size: 1e9, offset: DVec2::splat(32.), }; - let Some(pixels) = render_with_effect_in_frame(pixelate.clone(), frame, DAffine2::IDENTITY, square, size, |scene| { + let Some(pixels) = render_with_effect_in_frame(pixelate, frame, DAffine2::IDENTITY, square, size, |scene| { scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(0., 0., 32., 64.)); scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &Rect::new(32., 0., 64., 64.)); }) else { return; }; - // Each cell holds one half, which keeps its color, as on the CPU - let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); - plane.data = (0..size.x * size.y).map(|index| if index % size.x < 32 { [0., 0., 0., 1.] } else { [1.; 4] }).collect(); - let Some(cpu_frame) = EffectFrame::new(frame, DAffine2::IDENTITY) else { - panic!("the square has a frame") - }; - let expected = cpu_pixelated(&pixelate, &plane, &cpu_frame); + // Each cell holds one half, which keeps its color for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { - let index = (y * size.x + x) as usize; - assert_eq!(expected.data[index], plane.data[index], "({x}, {y}) shows another half on the CPU"); let shown = if x < 32 { [0, 0, 0, 255] } else { [255; 4] }; - assert_eq!(pixel(&pixels, size, x, y), shown, "({x}, {y}) shows another half on the GPU"); + assert_eq!(pixel(&pixels, size, x, y), shown, "({x}, {y}) shows another half"); } } @@ -10256,11 +11352,11 @@ fn square_on(placement: DAffine2) -> DAffine2 { #[test] fn warp_effects_on_a_tilted_canvas_keep_all_they_paint() { use glam::DVec2; - use graphic_types::{EffectOperation, Graphic, WarpStyle}; - use rendering::{Render, RenderParams}; + use graphic_types::{EffectOperation, WarpStyle}; // Within a square on a raster 200 by 100 at the origin let on_raster = square_on(DAffine2::from_scale(DVec2::new(200., 100.))); + let arch = warp_effect(WarpStyle::Arch, 80., on_raster); let chains = [ // A rise with both distortions reaches far past one corner of its square, past both sides there, on a canvas tilted off the document's axes vec![EffectOperation::Warp { @@ -10272,7 +11368,8 @@ fn warp_effects_on_a_tilted_canvas_keep_all_they_paint() { transform: on_raster, }], // An arch bends far above its square yet within its tilted bounds, where a twist after it clears it, bending what remains within the square - vec![warp_effect(WarpStyle::Arch, 80., on_raster), warp_effect(WarpStyle::Twist, -50., on_raster)], + vec![arch.clone()], + vec![arch, warp_effect(WarpStyle::Twist, -50., on_raster)], ]; let size = UVec2::splat(480); @@ -10282,28 +11379,22 @@ fn warp_effects_on_a_tilted_canvas_keep_all_they_paint() { for degrees in [30_f64, 45.] { let view = DAffine2::from_translation(DVec2::splat(240.)) * DAffine2::from_angle(degrees.to_radians()) * DAffine2::from_translation(-DVec2::new(100., 50.)); - // The GPU's warp, beside the CPU's warped image drawn plainly through the same view - let warped = Graphic::RasterCPU(Box::new(item.clone())); - let Some(gpu) = render_in_view(size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item.clone()))); - let Some(cpu) = render_in_view(size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - - // Where the CPU's image shows the content, so does the GPU's - let missing = (0..size.x * size.y).filter(|index| pixel(&cpu, size, index % size.x, index / size.x)[3] > 192 && pixel(&gpu, size, index % size.x, index / size.x)[3] < 64); - let missing = missing.count(); - assert!(missing <= 2, "{effects:?} tilted {degrees} degrees, {missing} pixels of the content are missing on the GPU"); + // The GPU shows what the last warp's definition makes of what the GPU shows before it, all that it paints included + let Some((worst, showing)) = resampled_difference_over_content(&item, size, view) else { return }; + assert!( + showing >= 5000, + "{effects:?} tilted {degrees} degrees leaves only {showing} pixels of content certain enough to compare" + ); + assert!(worst <= 3., "{effects:?} tilted {degrees} degrees strays from its definition by up to {worst} levels"); } } } #[test] -fn warp_effects_match_on_the_cpu_and_gpu() { +fn warp_effects_match_their_definition() { use core_types::ATTR_TRANSFORM; use glam::DVec2; + use graphic_types::resampling::{warp_frame, warp_of}; use graphic_types::{EffectOperation, WarpStyle}; let warp = |style, bend, horizontal_distortion, vertical_distortion, vertical, transform| EffectOperation::Warp { @@ -10327,19 +11418,19 @@ fn warp_effects_match_on_the_cpu_and_gpu() { vec![warp(Arc, 30., 25., -20., false, on_image)], vec![warp(Flag, 35., 0., 0., true, on_image)], vec![warp(Bulge, -25., -30., 15., true, on_image)], - // What a shadow paints past the square clears, as on the CPU + // What a shadow paints past the square clears vec![shadow.clone(), warp(Arc, 45., 0., 0., false, on_image)], vec![shadow.clone(), warp(Wave, 50., 0., 0., false, on_image)], ]); // All of them side by side in one render let filled_cases: Vec<_> = cases.iter().flat_map(|effects| [1., 0.5].map(|fill| (effects, fill))).collect(); - let items = filled_cases.iter().map(|&(effects, fill)| patterned_raster(55., effects, fill)).collect(); - let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 10) else { + let items: Vec<_> = filled_cases.iter().map(|&(effects, fill)| patterned_raster(55., effects, fill)).collect(); + let Some(differences) = gpu_tiles_and_reference_differences(&items, UVec2::new(160, 160), 10) else { return; }; - for (&(effects, fill), (_, differences)) in filled_cases.iter().zip(tiles) { - let worst = differences.into_iter().max().unwrap_or_default(); - assert!(worst <= 3, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); + for (&(effects, fill), (worst, showing)) in filled_cases.iter().zip(differences) { + assert!(showing >= 1000, "{effects:?} at fill {fill} leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{effects:?} at fill {fill} strays from its definition by up to {worst} levels"); } // A square wider than it's tall, bending into arcs that are circles in its own units @@ -10349,26 +11440,43 @@ fn warp_effects_match_on_the_cpu_and_gpu() { warp(Bulge, 35., 0., 0., true, on_oblong), warp(Twist, 40., 0., 0., false, on_oblong), ] { - let Some(worst) = gpu_and_cpu_difference(patterned_raster_sized(55., UVec2::new(50, 30), std::slice::from_ref(&effect), 1.), UVec2::new(160, 160)) else { + let item = patterned_raster_sized(55., UVec2::new(50, 30), std::slice::from_ref(&effect), 1.); + let Some((worst, showing)) = resampled_difference_over_content(&item, UVec2::new(160, 160), DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{effect:?} on a raster 50 by 30 differs from the GPU by up to {worst} levels"); + assert!(showing >= 500, "{effect:?} on a raster 50 by 30 leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{effect:?} on a raster 50 by 30 strays from its definition by up to {worst} levels"); } - // Where the patch folds over itself, the GPU shows the sheet turned over on top as the CPU does, so only the texels along its creases differ. + // Where the patch folds over itself, the sheet turned over shows on top, which all but the texels along its creases hold to. // The wave's square is nudged off the texel grid, since the side its turned-over part ends at, which fades only outward, otherwise runs exactly through texel centers that roundoff splits between layers. let nudged = DAffine2::from_translation(DVec2::new(0.3, 0.18)) * on_image; - for effect in [ - warp(Wave, 100., 100., 100., false, nudged), - warp(Fisheye, 100., 0., 0., false, on_image), - warp(ShellLower, -100., 0., 0., false, on_image), - ] { - let Some(differences) = gpu_and_cpu_differences_in_view(patterned_raster(55., std::slice::from_ref(&effect), 1.), UVec2::new(160, 160), DAffine2::IDENTITY) else { - return; + let folds = [ + vec![warp(Wave, 100., 100., 100., false, nudged)], + vec![warp(Fisheye, 100., 0., 0., false, on_image)], + vec![warp(ShellLower, -100., 0., 0., false, on_image)], + ]; + let items: Vec<_> = folds.iter().map(|effects| patterned_raster(55., effects, 1.)).collect(); + let Some(differences) = gpu_tiles_and_reference_differences(&items, UVec2::new(160, 160), 3) else { + return; + }; + let mut doubled = 0; + for (effects, (worst, showing)) in folds.iter().zip(differences) { + assert!(showing >= 500, "{effects:?} leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{effects:?} strays from its definition by up to {worst} levels"); + + // The pixels compared under both windings, where the turned sheet shows on top + let Some((style, transform)) = warp_of(&effects[0]) else { continue }; + let Some(square) = warp_frame(transform, DAffine2::from_translation(DVec2::splat(55.))) else { + continue; }; - let differing = differences.iter().filter(|&&difference| difference > 3).count(); - assert!(differing <= 8, "{effect:?} differs from the GPU by over 3 levels at {differing} texels"); + doubled += warp_layers(&style.mesh(square.size), &square, UVec2::new(160, 160)) + .iter() + .flatten() + .filter(|layers| layers.len() == 2) + .count(); } + assert!(doubled >= 50, "the folds leave only {doubled} pixels under two layers certain enough to compare"); // Only the right part of the warped content in view reads the part of the content left of the view, which the patch carries there. // Premultiplied, so a faint pixel's colors don't magnify roundoff. @@ -10404,16 +11512,17 @@ fn warp_effects_match_on_the_cpu_and_gpu() { for placement in [upright, turned] { for effect in [warp(Arc, 40., 0., 0., false, on_image), warp(Rise, -35., 10., 0., true, on_image)] { let item = patterned_raster(0., std::slice::from_ref(&effect), 1.).with_attribute(ATTR_TRANSFORM, placement); - let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else { + let Some((worst, showing)) = resampled_difference_over_content(&item, UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else { return; }; - assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels"); + assert!(showing >= 1500, "{effect:?} placed at {placement} leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{effect:?} placed at {placement} strays from its definition by up to {worst} levels"); } } } #[test] -fn warp_effects_match_on_the_cpu_and_gpu_within_offset_turned_and_slanted_squares() { +fn warp_effects_match_their_definition_within_offset_turned_and_slanted_squares() { use glam::DVec2; use graphic_types::{EffectOperation, WarpStyle}; @@ -10443,13 +11552,13 @@ fn warp_effects_match_on_the_cpu_and_gpu_within_offset_turned_and_slanted_square .flat_map(warps) .flat_map(|warp| [1., 0.5].map(|fill| (warp.clone(), fill))) .collect(); - let items = cases.iter().map(|(warp, fill)| patterned_raster(55., std::slice::from_ref(warp), *fill)).collect(); - let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 6) else { + let items: Vec<_> = cases.iter().map(|(warp, fill)| patterned_raster(55., std::slice::from_ref(warp), *fill)).collect(); + let Some(differences) = gpu_tiles_and_reference_differences(&items, UVec2::new(160, 160), 6) else { return; }; - for ((warp, fill), (_, differences)) in cases.iter().zip(tiles) { - let worst = differences.into_iter().max().unwrap_or_default(); - assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels"); + for ((warp, fill), (worst, showing)) in cases.iter().zip(differences) { + assert!(showing >= 150, "{warp:?} at fill {fill} leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{warp:?} at fill {fill} strays from its definition by up to {worst} levels"); } } @@ -10479,10 +11588,134 @@ fn warp_square_coverage(placement: DAffine2, pixel: glam::DVec2) -> f64 { (0.5 + (half - local.abs()) / (2. * half_fade)).clamp(glam::DVec2::ZERO, glam::DVec2::ONE).element_product() } +/// How many points of the unit square the patch of `mesh` (in pixels) carries onto `point`, found by splitting the square until its parts are small, then polishing each part's middle onto it. +/// A part whose polish settles outside it, or nowhere, splits further, as beside a fold's crease, and the points found from several parts count once. +fn warp_preimages(mesh: &graphic_types::warp::WarpMesh, point: glam::DVec2) -> usize { + use glam::DVec2; + + let mut found: Vec = Vec::new(); + let mut parts = vec![(DVec2::ZERO, DVec2::ONE)]; + while let Some((start, end)) = parts.pop() { + let [min, max] = mesh.over(start, end).hull_bounds(); + if point.cmplt(min).any() || point.cmpgt(max).any() { + continue; + } + let middle = (start + end) / 2.; + let split = [ + (start, middle), + (DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)), + (DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)), + (middle, end), + ]; + let size = (end - start).max_element(); + if size > 1. / 64. { + parts.extend(split); + continue; + } + + let mut uv = middle; + for _ in 0..16 { + let [landed, along_u, along_v] = mesh.point_and_tangents(uv); + let (residual, determinant) = (landed - point, along_u.perp_dot(along_v)); + if determinant.abs() < 1e-12 { + break; + } + uv -= DVec2::new(residual.perp_dot(along_v), along_u.perp_dot(residual)) / determinant; + } + + let settled = (mesh.point(uv) - point).length() < 1e-6; + if settled && uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all() && found.iter().all(|other| other.distance(uv) > 1e-7) { + found.push(uv); + } + let within_part = uv.cmpge(start - 1e-9).all() && uv.cmple(end + 1e-9).all(); + if !(settled && within_part) && size > 1. / 4096. { + parts.extend(split); + } + } + found.len() +} + +/// How many layers of content show at each of 8 by 8 samples across `pixel` (its corner) after the Warp of the `mesh` (as fractions of the `square`): +/// one for each point of the square the patch carries onto it. +fn supersampled_warp_layers(mesh: &graphic_types::warp::WarpMesh, square: &graphic_types::resampling::EffectFrame, pixel: glam::DVec2) -> [usize; 64] { + let in_pixels = mesh.transformed(square.to_pixels); + std::array::from_fn(|index| warp_preimages(&in_pixels, pixel + (glam::DVec2::new((index % 8) as f64, (index / 8) as f64) + 0.5) / 8.)) +} + +/// The least and most coverage a Warp's `tessellation` paints of content of one `alpha` within a 32nd of a pixel of each pixel's middle in a render `size` across, by its definition: +/// each of its triangles (the fringe's past each side and corner, and each cell's two) shades the points it covers as [`WarpTessellation::shade`] says, from the parameters it interpolates there +/// (polished within the square), each over the rest. `None` where those points stack other layers, as on a triangle's edge or a crease, which the GPU's rounding could settle either way. +fn warp_tessellation_alphas(tessellation: &graphic_types::resampling::WarpTessellation, size: UVec2, alpha: f32) -> Vec> { + use glam::DVec2; + use graphic_types::resampling::WarpFragment; + + // Each quad of the fringe splits into two triangles, as each cell does + let [columns, rows] = tessellation.cells; + let mut triangles: Vec<([(DVec2, DVec2); 3], WarpFragment)> = Vec::new(); + let quad = |[first, second, third, fourth]: [(DVec2, DVec2); 4], fragment| [([first, second, third], fragment), ([first, third, fourth], fragment)]; + for side in (0..4).filter(|&side| tessellation.sides[side]) { + let segments = if side < 2 { rows } else { columns }; + for along in 0..segments { + let corners = [(along, false), (along + 1, false), (along + 1, true), (along, true)].map(|(along, outer)| tessellation.fringe_vertex(side, along, outer)); + triangles.extend(quad(corners, WarpFragment::PastSide(side))); + } + } + for corner in (0..4).filter(|&corner| tessellation.sides[corner % 2] && tessellation.sides[2 + corner / 2]) { + let corners = [[false, false], [true, false], [true, true], [false, true]].map(|outer| tessellation.corner_vertex(corner, outer)); + triangles.extend(quad(corners, WarpFragment::PastCorner(corner))); + } + for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) { + let [top_left, top_right, bottom_left, bottom_right] = [[column, row], [column + 1, row], [column, row + 1], [column + 1, row + 1]].map(|index| tessellation.vertex(index)); + triangles.extend([ + ([top_left, top_right, bottom_right], WarpFragment::Within), + ([top_left, bottom_right, bottom_left], WarpFragment::Within), + ]); + } + + // The alphas of those covering each pixel's point `nudge` from its middle stack whatever order they're painted in + let stacked = |nudge: DVec2| { + let mut clear = vec![1_f32; (size.x * size.y) as usize]; + for ([(first_parameters, a), (second_parameters, b), (third_parameters, c)], fragment) in &triangles { + let area = (*b - *a).perp_dot(*c - *a); + let (first, last) = ( + (a.min(*b).min(*c) - 0.5 - nudge).ceil().max(DVec2::ZERO), + (a.max(*b).max(*c) - 0.5 - nudge).floor().min(size.as_dvec2() - 1.), + ); + if area.abs() < 1e-12 || first.cmpgt(last).any() { + continue; + } + + for (x, y) in (first.y as u32..=last.y as u32).flat_map(|y| (first.x as u32..=last.x as u32).map(move |x| (x, y))) { + let target = DVec2::new(x as f64 + 0.5, y as f64 + 0.5) + nudge; + let weights = [(*c - *b).perp_dot(target - *b), (*a - *c).perp_dot(target - *c), (*b - *a).perp_dot(target - *a)].map(|weight| weight / area); + if weights.iter().any(|&weight| weight < 0.) { + continue; + } + + let seed = *first_parameters * weights[0] + *second_parameters * weights[1] + *third_parameters * weights[2]; + let parameters = if *fragment == WarpFragment::Within { tessellation.polished(seed, target) } else { seed }; + clear[(y * size.x + x) as usize] *= 1. - alpha * tessellation.shade(*fragment, parameters, target).coverage.clamp(0., 1.) as f32; + } + } + clear.into_iter().map(|clear| 1. - clear).collect::>() + }; + + // The range a fade's slope moves them over, where nudging leaves the layers as they are + let nudged = [DVec2::ZERO, DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y].map(|direction| stacked(direction / 32.)); + (0..(size.x * size.y) as usize) + .map(|index| { + let alphas = nudged.iter().map(|alphas| alphas[index]); + let (low, high) = alphas.fold((f32::INFINITY, f32::NEG_INFINITY), |(low, high), alpha| (low.min(alpha), high.max(alpha))); + (high - low <= 0.1).then_some((low, high)) + }) + .collect() +} + #[test] fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any_squeeze_and_offset() { use glam::DVec2; use graphic_types::WarpStyle; + use graphic_types::resampling::{WarpTessellation, warp_frame}; use graphic_types::warp::Warp; // Content of one color within a square 39 by 19 at two offsets and at a scale between pixels, and within squares slanted and turned off the pixel grid, which fisheyes, waves, and twists bend @@ -10501,15 +11734,11 @@ fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any .flat_map(|style| bends.into_iter().flat_map(move |bend| placements.map(|placement| (style, bend, placement)))) .collect(); - // All the cases side by side in one render for each color - for color in [core_types::Color::WHITE, core_types::Color::from_rgbaf32_unchecked(1., 1., 1., 0.5)] { - let items = cases.iter().map(|&(style, bend, placement)| one_color_raster(color, Some((style, bend, placement)))).collect(); - let Some(tiles) = gpu_tiles_and_cpu_differences(items, size, 15) else { return }; - - for (&(style, bend, placement), (warped, differences)) in cases.iter().zip(tiles) { - let offset = placement.translation; - - // Whether the patch turns over anywhere + // Whether each case's patch turns over anywhere, and if so, its tessellation and the layers a supersampled reference counts across the 3 by 3 pixels around each corner of its square + type FoldingCorners = (WarpTessellation, Vec<(DVec2, [usize; 64])>); + let folding_corners: Vec> = cases + .iter() + .map(|&(style, bend, placement)| { let warp = Warp { style, bend: bend / 100., @@ -10517,18 +11746,39 @@ fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any vertical_distortion: 0., vertical: false, }; - let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())); + let square = warp_frame(placement, DAffine2::IDENTITY)?; + let mesh = warp.mesh(square.size); let folds = (0..65 * 65).any(|index| { let [_, along_s, along_t] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.); along_s.perp_dot(along_t) <= 1e-9 }); + if !folds { + return None; + } + + let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner)); + let around_corners = corners + .into_iter() + .flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64))); + let tessellation = WarpTessellation::new(&mesh, &square, size.as_dvec2()).expect("the square has a tessellation"); + Some((tessellation, around_corners.map(|pixel| (pixel, supersampled_warp_layers(&mesh, &square, pixel))).collect())) + }) + .collect(); + + // All the cases side by side in one render for each color + for color in [core_types::Color::WHITE, core_types::Color::from_rgbaf32_unchecked(1., 1., 1., 0.5)] { + let items: Vec<_> = cases.iter().map(|&(style, bend, placement)| one_color_raster(color, Some((style, bend, placement)))).collect(); + let Some(tiles) = gpu_tiles(&items, size, 15) else { return }; + + for ((&(style, bend, placement), warped), folding_corners) in cases.iter().zip(tiles).zip(&folding_corners) { + let offset = placement.translation; // Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides. // Where it folds, the layers of opaque content cover at least that much. for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { let expected = warp_square_coverage(placement, DVec2::new(x as f64, y as f64)) as f32 * color.a() * 255.; let alpha = pixel(&warped, size, x, y)[3] as f32; - if !folds { + if folding_corners.is_none() { assert!( (alpha - expected).abs() <= 1., "{style:?} at {bend} placed at {offset}, {color:?}, shows alpha {alpha} rather than {expected} at ({x}, {y})" @@ -10538,18 +11788,38 @@ fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any } } - // Around each corner, it matches the CPU, which matches a supersampled reference there - let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner)); - for pixel in corners - .into_iter() - .flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64))) - { - let difference = differences[(pixel.y as u32 * size.x + pixel.x as u32) as usize]; + // Around each corner of an upright square, where its coverage is its area, the layers stack their alphas across the supersamples. + // A slanted square's edge fades by its coverage along its axes instead, which holds around a corner no fold reaches. + let upright = placement.matrix2.x_axis.y == 0. && placement.matrix2.y_axis.x == 0.; + let Some((tessellation, corners)) = folding_corners else { continue }; + for (position, layers) in corners { + let expected = match upright { + true => layers.iter().map(|&layers| 1. - (1. - color.a()).powi(layers as i32)).sum::() / 64. * 255., + false if layers.iter().all(|&layers| layers <= 1) => warp_square_coverage(placement, *position) as f32 * color.a() * 255., + false => continue, + }; + let alpha = pixel(&warped, size, position.x as u32, position.y as u32)[3] as f32; assert!( - difference <= 2, - "{style:?} at {bend} placed at {offset}, {color:?}, differs from the CPU by {difference} levels at {pixel}" + (alpha - expected).abs() <= 2., + "{style:?} at {bend} placed at {offset}, {color:?}, shows alpha {alpha} rather than {expected} at {position}" ); } + + // Wherever it folds, slanted or not, each pixel shows the alphas its tessellation's triangles stack around its middle + let mut compared = 0; + for (index, range) in warp_tessellation_alphas(tessellation, size, color.a()).into_iter().enumerate() { + let Some((least, most)) = range else { continue }; + let position = UVec2::new(index as u32 % size.x, index as u32 / size.x); + let alpha = pixel(&warped, size, position.x, position.y)[3] as f32; + assert!( + ((least * 255. - 2.)..=(most * 255. + 2.)).contains(&alpha), + "{style:?} at {bend} placed at {offset}, {color:?}, shows alpha {alpha} rather than {} to {} at {position}", + least * 255., + most * 255. + ); + compared += 1; + } + assert!(compared >= 2000, "{style:?} at {bend} placed at {offset} leaves only {compared} pixels certain enough to compare"); } } } @@ -10847,21 +12117,29 @@ fn warp_effects_carry_nothing_wholly_outside_a_slanted_or_turned_square() { } #[test] -fn warp_effects_within_squares_far_smaller_than_a_pixel_match_on_the_cpu_and_gpu() { +fn warp_effects_within_squares_far_smaller_than_a_pixel_clear_every_pixel() { use core_types::ATTR_TRANSFORM; use core_types::list::Item; use glam::DVec2; use graphic_types::raster_types::{Image, Raster}; - use graphic_types::{Effect, WarpStyle, stamp_effect}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; // Opaque white 25 pixels across stretched to 2500 units and viewed at a hundredth of that, twisted within a square one unit across at its middle let mut item = Item::new_from_element(Raster::new_cpu(Image::new(25, 25, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2500.))); stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Twist, 80., DAffine2::from_translation(DVec2::splat(1275.))))); + let graphic = Graphic::RasterCPU(Box::new(item)); - let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::splat(64), DAffine2::from_scale(DVec2::splat(0.01))) else { + // The square and the unit its edge fades across lie a quarter of a pixel from the nearest pixel's middle, so it covers none, and the warp clears all the content past it + let size = UVec2::splat(64); + let Some(pixels) = render_in_view(size, DAffine2::from_scale(DVec2::splat(0.01)), |scene| { + graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()) + }) else { return; }; - assert!(worst <= 3, "the GPU differs from the CPU by up to {worst} levels"); + for (index, color) in pixels.iter().enumerate() { + assert!(color[3] <= 1, "({}, {}) shows {color:?}", index as u32 % size.x, index as u32 / size.x); + } } #[test] @@ -10889,16 +12167,16 @@ fn warp_effects_within_the_identity_or_a_collapsed_transform_clear_all_but_a_pix assert!(alpha == 0, "{warp:?} shows alpha {alpha} at ({x}, {y})"); } - let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), 1.), size) else { + let Some((worst, _)) = resampled_difference(&patterned_raster(55., std::slice::from_ref(&warp), 1.), size, DAffine2::IDENTITY) else { return; }; - assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels"); + assert!(worst <= 3., "{warp:?} strays from its definition by up to {worst} levels"); } } } #[test] -fn warp_effects_on_squares_turned_since_an_earlier_warp_match_on_the_cpu_and_gpu() { +fn warp_effects_on_squares_turned_since_an_earlier_warp_match_their_definition() { use core_types::ATTR_TRANSFORM; use core_types::list::Item; use glam::DVec2; @@ -10926,15 +12204,22 @@ fn warp_effects_on_squares_turned_since_an_earlier_warp_match_on_the_cpu_and_gpu let stamped = DAffine2::from_scale(banner.as_dvec2()); let mut item = Item::new_from_element(Raster::new_cpu(image.clone())).with_attribute(ATTR_TRANSFORM, stamped); stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 50., square_on(stamped)))); - let mut item = item.with_attribute(ATTR_TRANSFORM, turn * stamped); - stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Flag, 30., square_on(turn * stamped)))); + let arced = item.with_attribute(ATTR_TRANSFORM, turn * stamped); + let mut flagged = arced.clone(); + stamp_effect(&mut flagged, Effect::new(&warp_effect(WarpStyle::Flag, 30., square_on(turn * stamped)))); - // Viewed turned back, so the content's pixels land on the render's + // Viewed turned back, so the content's pixels land on the render's, the arc and the flag after it each show what its definition makes of what's before it let view = DAffine2::from_translation(DVec2::new(48., 64.)) * turn.inverse(); - let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::new(256, 136), view) else { - return; - }; - assert!(worst <= 3, "turned {degrees} degrees, the flag differs from the GPU by up to {worst} levels"); + for (name, item) in [("arc", arced), ("flag", flagged)] { + let Some((worst, showing)) = resampled_difference_over_content(&item, UVec2::new(256, 136), view) else { + return; + }; + assert!( + showing >= 2000, + "turned {degrees} degrees, the {name} leaves only {showing} pixels of content certain enough to compare" + ); + assert!(worst <= 3., "turned {degrees} degrees, the {name} strays from its definition by up to {worst} levels"); + } } } @@ -10944,8 +12229,7 @@ fn radial_blurs_spin_all_that_earlier_warps_bent_past_a_frame_turned_or_scaled_s use core_types::list::Item; use glam::DVec2; use graphic_types::raster_types::{Image, Raster}; - use graphic_types::{Effect, EffectOperation, Graphic, RadialBlurMethod, WarpStyle, stamp_effect}; - use rendering::{Render, RenderParams}; + use graphic_types::{Effect, EffectOperation, RadialBlurMethod, WarpStyle, stamp_effect}; // A banner of 300 by 30 pixels, one to each document unit once placed, of colors varying across it let banner = UVec2::new(300, 30); @@ -10965,9 +12249,10 @@ fn radial_blurs_spin_all_that_earlier_warps_bent_past_a_frame_turned_or_scaled_s }; let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(stamped_size)); stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 100., square_on(DAffine2::from_scale(stamped_size))))); - let mut item = item.with_attribute(ATTR_TRANSFORM, placement); + let bent = item.with_attribute(ATTR_TRANSFORM, placement); + let mut spun = bent.clone(); stamp_effect( - &mut item, + &mut spun, Effect::new(&EffectOperation::RadialBlur { method: RadialBlurMethod::Spin, amount: 45., @@ -10975,31 +12260,26 @@ fn radial_blurs_spin_all_that_earlier_warps_bent_past_a_frame_turned_or_scaled_s gamma: false, }), ); - item + [("bent", bent), ("spun", spun)] }; let size = banner.as_dvec2(); - // Scaled twice as large and turned a half since, its pixels still land on the render's, so the CPU and GPU match throughout - let scaled = bent_and_spun(size / 2., DAffine2::from_angle(std::f64::consts::PI) * DAffine2::from_scale(size)); - let Some(worst) = gpu_and_cpu_difference_in_view(scaled, UVec2::new(440, 520), DAffine2::from_translation(DVec2::new(380., 240.))) else { - return; - }; - assert!(worst <= 3, "scaled and turned a half, the spin differs from the GPU by up to {worst} levels"); - - // Turned 60 degrees since, the GPU shows the smear wherever the CPU's image drawn plainly does - let turned = bent_and_spun(size, DAffine2::from_angle(60_f64.to_radians()) * DAffine2::from_scale(size)); - let (render_size, view) = (UVec2::new(560, 460), DAffine2::from_translation(DVec2::new(200., 100.))); - let warped = Graphic::RasterCPU(Box::new(turned.clone())); - let Some(gpu) = render_in_view(render_size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(turned))); - let Some(cpu) = render_in_view(render_size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, render_size, index % render_size.x, index / render_size.x)[3]; - let missing = (0..render_size.x * render_size.y).filter(|&index| alpha(&cpu, index) >= 8 && alpha(&gpu, index) == 0).count(); - assert!(missing <= 2, "turned 60 degrees, {missing} pixels of the smear are missing on the GPU"); + // Scaled twice as large and turned a half since, or turned 60 degrees since, the arc and the spin after it each show what its definition makes of what's before it, all of the bent ring included + let scaled = DAffine2::from_angle(std::f64::consts::PI) * DAffine2::from_scale(size); + let turned = DAffine2::from_angle(60_f64.to_radians()) * DAffine2::from_scale(size); + let cases = [ + ("scaled and turned a half", size / 2., scaled, UVec2::new(440, 520), DVec2::new(380., 240.)), + ("turned 60 degrees", size, turned, UVec2::new(560, 460), DVec2::new(200., 100.)), + ]; + for (description, stamped_size, placement, render_size, offset) in cases { + for (name, item) in bent_and_spun(stamped_size, placement) { + let Some((worst, showing)) = resampled_difference_over_content(&item, render_size, DAffine2::from_translation(offset)) else { + return; + }; + assert!(showing >= 10_000, "{description}, the {name} banner leaves only {showing} pixels of content certain enough to compare"); + assert!(worst <= 3., "{description}, the {name} banner strays from its definition by up to {worst} levels"); + } + } } #[test] @@ -11108,36 +12388,62 @@ fn warp_effects_clear_what_a_minimum_grows_past_a_turned_square() { } #[test] -fn warp_effects_leave_what_earlier_warps_bent_before_a_stretch_alike_on_the_cpu_and_gpu() { +fn warp_effects_leave_what_earlier_warps_bent_before_a_stretch_as_defined() { use core_types::ATTR_TRANSFORM; use glam::DVec2; + use graphic_types::effects::effect_space; + use graphic_types::resampling::{warp_frame, warp_of}; use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; use rendering::{Render, RenderParams}; let size = UVec2::new(560, 200); // A square bent into an arc within a square on it, then stretched four times as wide, its ends then far past its sides, past the square of a warp stamped after the stretch + let upright = DAffine2::from_scale(DVec2::splat(50.)); let stretched = DAffine2::from_translation(DVec2::new(180., 70.)) * DAffine2::from_scale(DVec2::new(200., 50.)); - let arc = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(50.)))); + let arc = warp_effect(WarpStyle::Arc, 50., square_on(upright)); + let arced = patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched); + + // The arc alone, which the warps after it read, covers what the content does where the patch carries each pixel's middle from: all but its hole. + // The GPU carries it out along the stretched axes at four times the render's density, so the hole's edge, which that blurs differently, isn't compared. + let Some(arc_alone) = render(size, |scene| { + Graphic::RasterCPU(Box::new(arced.clone())).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()) + }) else { + return; + }; + let (warp, transform) = warp_of(&arc).expect("the arc is a Warp"); + let square = warp_frame(transform, effect_space(stretched, upright)).expect("the arc's square has an area"); + let pixels_to_content = upright * stretched.inverse(); + let coverage = |source: DVec2| { + let from_hole = pixels_to_content.transform_point2(source).distance(DVec2::new(32., 20.)) - 7.; + (from_hole.abs() > 2.).then_some(if from_hole > 0. { 1. } else { 0. }) + }; + let mut compared = 0; + for (index, layers) in warp_layers(&warp.mesh(square.size), &square, size).into_iter().enumerate() { + let Some(coverages) = layers.and_then(|layers| layers.into_iter().map(coverage).collect::>>()) else { + continue; + }; + let expected = 255. * (1. - coverages.iter().fold(1., |clear, coverage| clear * (1. - coverage))); + let shown = arc_alone[index][3] as f32; + assert!( + (shown - expected).abs() <= 3., + "the arc alone shows alpha {shown} rather than {expected} at {}", + UVec2::new(index as u32 % size.x, index as u32 / size.x) + ); + compared += 1; + } + assert!(compared >= 20_000, "the arc alone leaves only {compared} pixels certain enough to compare"); + for second in [WarpStyle::Flag, WarpStyle::Twist] { - let mut item = patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched); + let mut item = arced.clone(); stamp_effect(&mut item, Effect::new(&warp_effect(second, 30., square_on(DAffine2::from_mat2(stretched.matrix2))))); - // The GPU's warps, beside the CPU's warped image drawn plainly, with pixels four times as wide as the render's - let warped = Graphic::RasterCPU(Box::new(item.clone())); - let Some(gpu) = render(size, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + // With pixels four times as wide as the render's, the warp after the stretch shows what its definition makes of the arc the GPU shows before it + let Some((worst, showing)) = resampled_difference_over_content(&item, size, DAffine2::IDENTITY) else { return; }; - let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item))); - let Some(cpu) = render(size, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - - // Each shows the content wherever the other does - let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3]; - let shown_by_one = |index: &u32| (alpha(&gpu, *index) > 192 && alpha(&cpu, *index) < 64) || (alpha(&cpu, *index) > 192 && alpha(&gpu, *index) < 64); - let differing = (0..size.x * size.y).filter(shown_by_one).count(); - assert!(differing <= 2, "after {second:?}, {differing} pixels of the content show on only one of the CPU and GPU"); + assert!(showing >= 3000, "after {second:?}, only {showing} pixels of content are certain enough to compare"); + assert!(worst <= 3., "after {second:?}, the warps stray from their definition by up to {worst} levels"); } } @@ -11177,16 +12483,46 @@ fn blend_range([falloff_start, range_start, range_end, falloff_end]: [f64; 4]) - } } +/// The premultiplied gamma-encoded `pixels`, `size` across, blurred in linear light by a Gaussian of `radius`, each pixel weighing those around it by the normal distribution's share over each. +/// Nothing lies past the edges. O(width × height × radius). +fn gaussian_blurred_in_light(pixels: &[[f32; 4]], size: UVec2, radius: f64) -> Vec<[f32; 4]> { + use core_types::color::{linear_to_srgb, srgb_to_linear}; + + let (width, height) = (size.x as i64, size.y as i64); + let reach = (4. * radius).ceil() as i64; + let weights: Vec = (-reach..=reach) + .map(|offset| normal_cdf((offset as f64 + 0.5) / radius) - normal_cdf((offset as f64 - 0.5) / radius)) + .collect(); + + // Along each row, then down each column + let along = |values: &[[f32; 4]], [step_x, step_y]: [i64; 2]| -> Vec<[f32; 4]> { + (0..width * height) + .map(|index| { + let mut sum = [0_f64; 4]; + for (offset, weight) in (-reach..=reach).zip(&weights) { + let (x, y) = (index % width + offset * step_x, index / width + offset * step_y); + if (0..width).contains(&x) && (0..height).contains(&y) { + let value = values[(y * width + x) as usize]; + (0..4).for_each(|channel| sum[channel] += weight * value[channel] as f64); + } + } + sum.map(|channel| channel as f32) + }) + .collect() + }; + + let light: Vec<[f32; 4]> = pixels.iter().map(|&pixel| transferred_premultiplied(srgb_to_linear, pixel)).collect(); + let blurred = along(&along(&light, [1, 0]), [0, 1]); + blurred.into_iter().map(|pixel| transferred_premultiplied(linear_to_srgb, pixel)).collect() +} + #[test] -fn blend_ifs_fade_the_content_by_its_tones_on_the_gpu_like_on_the_cpu() { +fn blend_ifs_fade_the_content_by_its_tones() { use core_types::Color as GraphicColor; - use core_types::list::Item; - use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use glam::DVec2; use graphic_types::blend_if::BlendIfRanges; - use graphic_types::raster_types::{Image, Raster}; use graphic_types::{EffectOperation, Effects}; - use raster_kernels::evaluate_raster_effects; + use raster_kernels::value_effects::{adjustments, content_blend_ifs, filled_color_with_blend_ifs}; let size = UVec2::new(160, 160); let (min, max) = (30_u32, 130_u32); @@ -11236,7 +12572,7 @@ fn blend_ifs_fade_the_content_by_its_tones_on_the_gpu_like_on_the_cpu() { vec![with_content(soft)], vec![with_content(hard)], vec![with_content(colored)], - // The shadow is knocked out by the content as Blend If leaves it, wherever it lies in the order + // The content knocks out the shadow however the Blend If fades it, as at any fill, wherever it lies in the order vec![shadow.clone(), with_content(soft)], vec![with_content(hard), shadow.clone()], // Blend If reads the content as a blur before it leaves it, and a blur after it softens what it hides @@ -11250,63 +12586,85 @@ fn blend_ifs_fade_the_content_by_its_tones_on_the_gpu_like_on_the_cpu() { vec![inner_shadow, with_content(soft)], ]; - for effects in cases { - for fill in [1., 0.5] { - let effects_list = Effects::from_operations(effects.clone()); - let draw_columns = |scene: &mut VelloSceneBuilder| { - for y in [min, 80] { - for x in min..max { - let [red, green, blue] = column_color(x, y); - let column = Rect::new(x as f64, y as f64, (x + 1) as f64, (y + 50) as f64); - scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(red, green, blue), None, &column); - } - } - }; - let bounds = Rect::new(min as f64, min as f64, max as f64, max as f64); - let Some(gpu) = render(size, |scene| { - scene.draw_effects(&effects_list, fill, 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { - draw_columns(scene) - }) - }) else { - return; - }; - - // The same columns as a raster covering the render one pixel to one pixel - let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT); - for y in min..max { + // The columns drawn through `effects` at `fill` + let bounds = Rect::new(min as f64, min as f64, max as f64, max as f64); + let draw = |scene: &mut VelloSceneBuilder, effects: &[EffectOperation], fill: f32| { + let effects = Effects::from_operations(effects.to_vec()); + scene.draw_effects(&effects, fill, 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| { + for y in [min, 80] { for x in min..max { - let [red, green, blue] = column_color(x, if y < 80 { min } else { 80 }); - image.data[(y * size.x + x) as usize] = GraphicColor::from(core_types::color::SRGBA8::new(red, green, blue, 255)); + let [red, green, blue] = column_color(x, y); + let column = Rect::new(x as f64, y as f64, (x + 1) as f64, (y + 50) as f64); + scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(red, green, blue), None, &column); } } - let mut item = Item::new_from_element(Raster::new_cpu(image)) - .with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())) - .with_attribute(ATTR_OPACITY_FILL, fill as f64); - effects.iter().for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation))); - let evaluated = evaluate_raster_effects(item); - let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); - let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); + }) + }; + let render_through = |effects: &[EffectOperation], fill: f32| Some(render(size, |scene| draw(scene, effects, fill))?.into_iter().map(premultiplied_unit).collect::>()); - let mut worst = 0; - for y in 0..size.y { - for x in 0..size.x { - let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); - let [red, green, blue, alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels(); - let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.); + // The content's opaque color at each pixel it covers + let pixels = (size.x * size.y) as usize; + let content_at = |index: usize| { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + let inside = (min..max).contains(&x) && (min..max).contains(&y); + inside.then(|| { + let [red, green, blue] = column_color(x, if y < 80 { min } else { 80 }).map(|level| level as f32 / 255.); + GraphicColor::from_gamma_srgb_channels(red, green, blue, 1.) + }) + }; + let premultiplied = |color: GraphicColor| { + let [red, green, blue, alpha] = color.to_gamma_srgb_channels(); + [red * alpha, green * alpha, blue * alpha, alpha] + }; - // Compared premultiplied, so a nearly transparent pixel's color can't dominate - let gpu = pixel(&gpu, size, x, y); - let gpu_alpha = gpu[3] as f32 / 255.; - for channel in 0..4 { - let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha }; - worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32); - } + for effects in cases { + // What the Blend Ifs leave of a color at a fill, with the adjustments carried out, by the value path + let effects_list = Effects::from_operations(effects.clone()); + let (adjustments, steps) = (adjustments(&effects_list), content_blend_ifs(&effects_list)); + let faded = |color: GraphicColor, fill: f32| filled_color_with_blend_ifs(color, &adjustments, &steps, fill); + + for fill in [1., 0.5] { + let Some(gpu) = render(size, |scene| draw(scene, &effects, fill)) else { return }; + + // The content faded pixel by pixel + let pointwise: Vec<[f32; 4]> = (0..pixels).map(|index| content_at(index).map_or([0.; 4], |color| premultiplied(faded(color, fill)))).collect(); + + let shadow = effects.iter().find(|operation| matches!(operation, EffectOperation::DropShadow { .. })); + let interior = effects.iter().find(|operation| matches!(operation, EffectOperation::InnerShadow { .. })); + let expected: Vec<[f32; 4]> = match (&effects[..], shadow, interior) { + // Blend If reads the colors of the blur before it as the GPU renders the blur alone + ([blur @ EffectOperation::Blur { .. }, ..], _, _) => { + let Some(blurred) = render_precise_in_view(size, DAffine2::IDENTITY, |scene| draw(scene, std::slice::from_ref(blur), fill)) else { + return; + }; + let weighed = |[red, green, blue, alpha]: [f32; 4]| premultiplied(faded(GraphicColor::from_gamma_srgb_channels(red / alpha, green / alpha, blue / alpha, alpha), 1.)); + blurred.into_iter().map(|pixel| if pixel[3] > 0. { weighed(pixel) } else { [0.; 4] }).collect() } - } - // A blur leaves colors between levels, where the GPU's and the CPU's precisions can round to neighboring levels, which a falloff amplifies - let tolerance = if matches!(effects[0], EffectOperation::Blur { .. }) { 8 } else { 2 }; - assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); + // A blur after it blurs the faded content + ([.., EffectOperation::Blur { radius, .. }], _, _) => gaussian_blurred_in_light(&pointwise, size, *radius), + // The shadow as it renders alone past the content, and none within it, since the content knocks it out however the Blend Ifs fade it + (_, Some(shadow), _) => { + let Some(shadow) = render_through(std::slice::from_ref(shadow), 0.) else { return }; + (0..pixels).map(|index| if content_at(index).is_some() { pointwise[index] } else { shadow[index] }).collect() + } + // The interior piece shows as through the fill times the Blend Ifs' weight, mixing linearly between how it shows at no fill and a full one + (_, _, Some(interior)) => { + let (Some(unfilled), Some(filled)) = (render_through(std::slice::from_ref(interior), 0.), render_through(std::slice::from_ref(interior), 1.)) else { + return; + }; + let weight = |index: usize| content_at(index).map_or(0., |color| faded(color, 1.).a()); + let mix = |index: usize, channel: usize| unfilled[index][channel] + (filled[index][channel] - unfilled[index][channel]) * fill * weight(index); + (0..pixels).map(|index| std::array::from_fn(|channel| mix(index, channel))).collect() + } + _ => pointwise, + }; + + let (worst, _) = reference_difference(&gpu, &expected.into_iter().map(Some).collect::>()); + + // Blend If reads each blurred color at its nearest level, which the GPU's precision can tip to the next across a falloff, by up to 5 levels here + let tolerance = if matches!(effects[0], EffectOperation::Blur { .. }) { 6. } else { 3. }; + let kinds: Vec<_> = effects.iter().map(|operation| operation.kind()).collect(); + assert!(worst <= tolerance, "{kinds:?} at fill {fill} strays from its definition by up to {worst} levels"); } } } @@ -11584,8 +12942,7 @@ fn flattened_glows_before_a_mask_hide_where_a_blend_if_after_it_hides_the_conten use core_types::list::Item; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use graphic_types::raster_types::{Image, Raster}; - use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; - use rendering::{Render, RenderParams}; + use graphic_types::{Effect, EffectOperation, stamp_effect}; // A glow in a mode CSS lacks, which flattens it into the content's image let glow = EffectOperation::OuterGlow { @@ -11619,18 +12976,28 @@ fn flattened_glows_before_a_mask_hide_where_a_blend_if_after_it_hides_the_conten let size = UVec2::splat(160); for operations in [[glow.clone(), mask.clone(), blend_if.clone()], [glow.clone(), blend_if.clone(), mask.clone()]] { let kinds: Vec<_> = operations.iter().map(|operation| operation.kind()).collect(); - let item = raster(&operations); - - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 2, "{kinds:?} differs between the CPU and GPU by up to {worst} levels"); - - let graphic = Graphic::RasterCPU(Box::new(item)); - let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + let without_blend_if: Vec = operations.iter().filter(|operation| !matches!(operation, EffectOperation::BlendIf(_))).cloned().collect(); + let (Some(pixels), Some(unfaded)) = (render_raster(raster(&operations), size), render_raster(raster(&without_blend_if), size)) else { return; }; assert_eq!(pixel(&pixels, size, 65, 70)[3], 0, "{kinds:?}: the glow hides with the dark half: {:?}", pixel(&pixels, size, 65, 70)); assert_eq!(pixel(&pixels, size, 95, 70), [light, light, light, 255], "{kinds:?}: the light half shows"); assert_eq!(pixel(&pixels, size, 95, 100)[3], 0, "{kinds:?}: the mask hides the bottom"); + + // Within the raster, only the light half above the mask's cut shows, and past it the Blend If reads the glow's light colors, which it leaves as they are + let expected: Vec> = (0..size.x * size.y) + .map(|index| { + let (x, y) = (index % size.x, index / size.x); + let within = (55..105).contains(&x) && (55..105).contains(&y); + Some(match (within, x >= 80 && y < 95) { + (true, true) => [light as f32 / 255., light as f32 / 255., light as f32 / 255., 1.], + (true, false) => [0.; 4], + (false, _) => premultiplied_unit(pixel(&unfaded, size, x, y)), + }) + }) + .collect(); + let (worst, _) = reference_difference(&pixels, &expected); + assert!(worst <= 2., "{kinds:?} strays from the light half alone and the glow left as it is by up to {worst} levels"); } } @@ -11647,12 +13014,10 @@ fn color_overlays_before_a_mask_paint_the_colors_a_blend_if_after_it_reads_on_ev let operations = [color_overlay([0., 0., 1.], BlendMode::Normal, 1.), mask_hiding_the_bottom_fifth(), blend_if_hiding_darks()]; let size = UVec2::splat(160); - // A 50 by 50 white raster at (55, 55), compared with its CPU evaluation + // A 50 by 50 white raster at (55, 55) let placement = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.)); let mut raster = Item::new_from_element(Raster::new_cpu(Image::new(50, 50, GraphicColor::WHITE))).with_attribute(ATTR_TRANSFORM, placement); operations.iter().for_each(|operation| stamp_effect(&mut raster, Effect::new(operation))); - let Some(worst) = gpu_and_cpu_difference(raster.clone(), size) else { return }; - assert!(worst <= 2, "the raster differs between the CPU and GPU by up to {worst} levels"); // The same square as a vector with a solid fill, which takes the overlay into its paint, and in a group carrying the effects, which takes it as a piece let mut vector = Vector::item_from_bezpath(&Rect::new(55., 55., 105., 105.).to_path(0.1)); @@ -11668,12 +13033,14 @@ fn color_overlays_before_a_mask_paint_the_colors_a_blend_if_after_it_reads_on_ev ("group", Graphic::Graphic(Box::new(group))), ]; + // Painted blue all over, each is hidden everywhere for (name, graphic) in contents { let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { return; }; - for (x, y) in [(60, 60), (80, 80), (100, 90)] { - assert_eq!(pixel(&pixels, size, x, y)[3], 0, "the {name} painted blue is hidden at ({x}, {y}): {:?}", pixel(&pixels, size, x, y)); + if let Some(index) = pixels.iter().position(|pixel| pixel[3] > 0) { + let (x, y) = (index as u32 % size.x, index as u32 / size.x); + panic!("the {name} painted blue shows at ({x}, {y}): {:?}", pixels[index]); } } } @@ -11947,7 +13314,7 @@ fn black_to_white_gradient(effects: &[graphic_types::EffectOperation]) -> core_t } #[test] -fn masked_radius_blurs_after_a_blend_if_blur_the_full_strength_content_alike_on_the_cpu_gpu_and_svg() { +fn masked_radius_blurs_after_a_blend_if_blur_the_full_strength_content_alike_on_the_gpu_and_in_svg() { use core_types::list::{Item, List}; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use glam::DVec2; @@ -11972,18 +13339,22 @@ fn masked_radius_blurs_after_a_blend_if_blur_the_full_strength_content_alike_on_ opacity: 100., }), ]; - let mut item = Item::new_from_element(Raster::new_cpu(Image::new(40, 40, GraphicColor::BLACK))) - .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(24.)) * DAffine2::from_scale(DVec2::splat(40.))); - operations.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + let raster = |operations: &[EffectOperation]| { + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(40, 40, GraphicColor::BLACK))) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(24.)) * DAffine2::from_scale(DVec2::splat(40.))); + operations.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + item + }; + let item = raster(&operations); + // On the GPU, the square shows red as far as the blur spreads it without the Blend If let size = UVec2::new(88, 88); - let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; - assert!(worst <= 3, "the CPU and GPU differ by up to {worst} levels"); - let graphic = Graphic::RasterCPU(Box::new(item.clone())); - let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + let (Some(gpu), Some(unfaded)) = (render_raster(item.clone(), size), render_raster(raster(&operations[1..]), size)) else { return; }; assert_eq!(pixel(&gpu, size, 44, 44), [255, 0, 0, 255], "the GPU paints the hidden square red"); + let (worst, _) = reference_difference(&gpu, &unfaded.into_iter().map(|pixel| Some(premultiplied_unit(pixel))).collect::>()); + assert!(worst <= 1., "the hidden square painted red strays from the unfaded one by up to {worst} levels"); // SVG takes both of the blur's results from the GPU as maps, rather than starting a fresh filter from the faded content alone let mut svg = SvgRender::new(); @@ -12055,49 +13426,68 @@ fn color_and_gradient_paints_fade_by_their_own_blend_ifs_on_the_gpu() { } #[test] -fn effect_paints_and_maps_fade_by_their_own_blend_ifs_on_the_cpu_like_on_the_gpu() { +fn effect_paints_and_maps_fade_by_their_own_blend_ifs() { use core_types::Color as GraphicColor; use core_types::list::Item; use graphic_types::vector_types::GradientSpread; use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect}; + use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects}; - // A dark gray hidden by the Blend If, and a ramp hidden up to its middle gray - let mut hidden_gray = Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.3, 0.3, 0.3, 1.)); - stamp_effect(&mut hidden_gray, Effect::new(&blend_if_hiding_below_half())); - let hidden_gray = Graphic::from(hidden_gray); - let ramp = Graphic::from(black_to_white_gradient(&[blend_if_hiding_below_half()])); - // Paints and maps that don't follow the content lie where they're placed, so this ramp is placed across it - let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.)); - let placed_ramp = Graphic::from(black_to_white_gradient(&[blend_if_hiding_below_half()]).with_attribute(core_types::ATTR_TRANSFORM, on_content)); + // The paint with its effects carried out and consumed by the value path, as the nodes reading its colors take it + fn consumed(paint: Graphic) -> Graphic { + match paint { + Graphic::Color(color) => Graphic::Color(evaluate_color_effects(color)), + Graphic::Gradient(gradient) => Graphic::Gradient(evaluate_gradient_effects(gradient)), + paint => paint, + } + } - let mask = |mask: Graphic, mode: MaskMode| EffectOperation::Mask { - mask, - mode, - density: 100., - feather: 0., - invert: false, + // Each case's paints and maps given to `prepare` before they're stamped + let cases = |prepare: fn(Graphic) -> Graphic| { + // A dark gray hidden by the Blend If, and a ramp hidden up to its middle gray + let mut hidden_gray = Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.3, 0.3, 0.3, 1.)); + stamp_effect(&mut hidden_gray, Effect::new(&blend_if_hiding_below_half())); + let hidden_gray = prepare(Graphic::from(hidden_gray)); + let ramp = prepare(Graphic::from(black_to_white_gradient(&[blend_if_hiding_below_half()]))); + // Paints and maps that don't follow the content lie where they're placed, so this ramp is placed across it + let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.)); + let placed_ramp = prepare(Graphic::from( + black_to_white_gradient(&[blend_if_hiding_below_half()]).with_attribute(core_types::ATTR_TRANSFORM, on_content), + )); + + let mask = |mask: Graphic, mode: MaskMode| EffectOperation::Mask { + mask, + mode, + density: 100., + feather: 0., + invert: false, + }; + // The map moves the content across and down by its luminance + let displace = |map: Graphic| x_and_y_displacement((map.clone(), 25.6), (map, 12.8), GradientSpread::Repeat); + [ + ("color mask", mask(hidden_gray.clone(), MaskMode::Alpha)), + ("gradient mask", mask(ramp, MaskMode::Alpha)), + ( + "gradient paint overlay", + EffectOperation::PaintOverlay { + paint: placed_ramp.clone(), + blend_mode: BlendMode::Normal, + opacity: 100., + }, + ), + ("color displacement map", displace(hidden_gray)), + ("gradient displacement map", displace(placed_ramp)), + ] }; - // The map moves the content across and down by its luminance - let displace = |map: Graphic| x_and_y_displacement((map.clone(), 25.6), (map, 12.8), GradientSpread::Repeat); - let cases = [ - ("color mask", mask(hidden_gray.clone(), MaskMode::Alpha)), - ("gradient mask", mask(ramp, MaskMode::Alpha)), - ( - "gradient paint overlay", - EffectOperation::PaintOverlay { - paint: placed_ramp.clone(), - blend_mode: BlendMode::Normal, - opacity: 100., - }, - ), - ("color displacement map", displace(hidden_gray)), - ("gradient displacement map", displace(placed_ramp)), - ]; + // Each draws as the paint the value path leaves of it let size = UVec2::new(160, 160); - for (name, operation) in cases { - let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[operation]), size) else { return }; - assert!(worst <= 3, "the {name} differs between the CPU and GPU by up to {worst} levels"); + for ((name, operation), (_, consumed_operation)) in cases(|paint| paint).into_iter().zip(cases(consumed)) { + let (Some(drawn), Some(consumed)) = (render_raster(checkered_raster(&[operation]), size), render_raster(checkered_raster(&[consumed_operation]), size)) else { + return; + }; + let (worst, _) = reference_difference(&drawn, &consumed.into_iter().map(|pixel| Some(premultiplied_unit(pixel))).collect::>()); + assert!(worst <= 1., "the {name} strays from its paint with its effects consumed by up to {worst} levels"); } } @@ -12186,14 +13576,24 @@ fn endless_layers_given_edges_by_a_mask_read_nothing_beneath_them_on_the_gpu_or_ } } +/// The `item` with each of the `rows` stamped on it while it's scaled from its `placement` by the row's scale, so a row stamped at a new scale starts a run of its own. +fn stamped_while_scaled(mut item: core_types::list::Item, placement: DAffine2, rows: &[(&graphic_types::EffectOperation, f64)]) -> core_types::list::Item { + for (operation, scale) in rows { + item.set_attribute(core_types::ATTR_TRANSFORM, placement * DAffine2::from_scale(glam::DVec2::splat(*scale))); + graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)); + } + item +} + #[test] -fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_them_on_the_gpu_like_on_the_cpu() { - use core_types::list::{Item, List}; +fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_them() { + use core_types::list::{ATTR_EFFECTS, Item, List}; use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; use glam::DVec2; use graphic_types::adjustment::Adjustment; use graphic_types::raster_types::{Image, Raster}; - use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use graphic_types::{EffectOperation, Effects, Graphic}; + use raster_kernels::value_effects::{adjustments, content_blend_ifs, filled_color_with_blend_ifs}; use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; // White, or a ramp from black to white, painted blue and then scaled up, where a Blend If hiding grays below half reads the blue and hides it @@ -12203,21 +13603,14 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i opacity: 100., }); - // Each row is stamped while the item is scaled from its `placement` by the row's scale, so the ramp lies across the render - fn stamped(mut item: Item, placement: DAffine2, rows: &[(&EffectOperation, f64)]) -> Item { - for (operation, scale) in rows { - item.set_attribute(ATTR_TRANSFORM, placement * DAffine2::from_scale(DVec2::splat(*scale))); - stamp_effect(&mut item, Effect::new(operation)); - } - item - } + // The rows stamped so the ramp lies across the render let blend_if = blend_if_hiding_below_half(); let layers = |scale: f64| { let rows = [(&blue, 1.), (&blend_if, scale)]; let across = DAffine2::from_scale(DVec2::splat(32.)); [ - ("color", Graphic::from(stamped(Item::new_from_element(GraphicColor::WHITE), across, &rows))), - ("gradient", Graphic::from(stamped(black_to_white_gradient(&[]), across, &rows))), + ("color", Graphic::from(stamped_while_scaled(Item::new_from_element(GraphicColor::WHITE), across, &rows))), + ("gradient", Graphic::from(stamped_while_scaled(black_to_white_gradient(&[]), across, &rows))), ] }; @@ -12255,7 +13648,7 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i assert_eq!(pixel(&unscaled_pixels, size, 16, 16), [0, 0, 255, 255], "the {name} in one run is painted blue"); } - // As a mask, it hides everything, and as a paint overlay's paint, it paints nothing, which the CPU reads alike + // As a mask, it hides everything, and as a paint overlay's paint, it paints nothing let [(_, color), (_, gradient)] = layers(2.); let mask = |mask: Graphic| EffectOperation::Mask { mask, @@ -12265,8 +13658,8 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i invert: false, }; let cases = [ - ("color mask", mask(color), 0), - ("gradient mask", mask(gradient.clone()), 0), + ("color mask", mask(color), 0.), + ("gradient mask", mask(gradient.clone()), 0.), ( "gradient paint overlay", EffectOperation::PaintOverlay { @@ -12274,24 +13667,19 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i blend_mode: BlendMode::Normal, opacity: 100., }, - 255, + 1., ), ]; let size = UVec2::new(160, 160); - for (name, operation, alpha) in cases { - let raster = checkered_raster(&[operation]); - let Some(worst) = gpu_and_cpu_difference(raster.clone(), size) else { return }; - assert!(worst <= 3, "the {name} differs between the CPU and GPU by up to {worst} levels"); - - let graphic = Graphic::RasterCPU(Box::new(raster)); - let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { - return; - }; - let [_, _, blue, shown] = pixel(&pixels, size, 80, 80); - assert!(shown == alpha && blue < 255, "the {name} paints blue or doesn't hide: {:?}", pixel(&pixels, size, 80, 80)); + let Some(plain) = render_raster(checkered_raster(&[]), size) else { return }; + let content_shown = |shown: f32| plain.iter().map(|&pixel| Some(premultiplied_unit(pixel).map(|channel| channel * shown))).collect::>(); + for (name, operation, shown) in cases { + let Some(pixels) = render_raster(checkered_raster(&[operation]), size) else { return }; + let (worst, _) = reference_difference(&pixels, &content_shown(shown)); + assert!(worst <= 1., "the {name} strays from showing {shown} of the content by up to {worst} levels"); } - // At half fill, half of the overlay paints over the faded white, and the next run's softer Blend If reads that mix, which shows about a third of it + // At half fill, half of the overlay paints over the faded white, and the next run's softer Blend If reads that mix, which shows about a third of it, as the value path takes it let mut soft = graphic_types::blend_if::BlendIfRanges::default(); soft.content.gray = blend_range([63.75, 191.25, 255., 255.]); let half_blue = EffectOperation::Adjustment(Adjustment::ColorOverlay { @@ -12300,11 +13688,57 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i opacity: 50., }); let rows = [(&half_blue, 1.), (&EffectOperation::BlendIf(Box::new(soft)), 2.)]; - let half_filled = stamped(Item::new_from_element(GraphicColor::WHITE), DAffine2::IDENTITY, &rows).with_attribute(core_types::ATTR_OPACITY_FILL, 0.5); - let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[mask(Graphic::from(half_filled))]), size) else { + let half_filled = stamped_while_scaled(Item::new_from_element(GraphicColor::WHITE), DAffine2::IDENTITY, &rows).with_attribute(core_types::ATTR_OPACITY_FILL, 0.5); + let effects: Effects = half_filled.attribute_cloned_or_default(ATTR_EFFECTS); + let shown = filled_color_with_blend_ifs(GraphicColor::WHITE, &adjustments(&effects), &content_blend_ifs(&effects), 0.5).a(); + + let Some(pixels) = render_raster(checkered_raster(&[mask(Graphic::from(half_filled))]), size) else { return; }; - assert!(worst <= 3, "the half-filled color mask differs between the CPU and GPU by up to {worst} levels"); + let (worst, _) = reference_difference(&pixels, &content_shown(shown)); + assert!(worst <= 1., "the half-filled color mask strays from showing {shown} of the content by up to {worst} levels"); +} + +#[test] +fn blend_ifs_hide_rasters_through_adjustments_raising_alpha_as_they_hide_values() { + use core_types::Color as GraphicColor; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{EffectKind, EffectOperation}; + use raster_kernels::evaluate_color_effects; + + // Black hidden by a Blend If, then made opaque in its run or the next and painted red in either, the rows raster-kernels' value test takes a color through + let (blend_if, make_opaque) = (blend_if_hiding_below_half(), EffectOperation::default_for(EffectKind::MakeOpaque)); + let red_overlay = color_overlay([1., 0., 0.], BlendMode::Normal, 1.); + let cases = [ + ("made opaque", vec![(&blend_if, 1.), (&make_opaque, 1.)]), + ("made opaque in the next run", vec![(&blend_if, 1.), (&make_opaque, 2.)]), + ("made opaque and painted in the next run", vec![(&blend_if, 1.), (&make_opaque, 2.), (&red_overlay, 2.)]), + ("made opaque and painted", vec![(&blend_if, 1.), (&make_opaque, 1.), (&red_overlay, 1.)]), + ]; + + // A black raster stamped while scaled from a square 16 across at (16, 16), which ends at the last row's scale + let placement = DAffine2::from_translation(DVec2::splat(16.)) * DAffine2::from_scale(DVec2::splat(16.)); + let size = UVec2::splat(64); + for (name, rows) in cases { + let raster = stamped_while_scaled(Item::new_from_element(Raster::new_cpu(Image::new(16, 16, GraphicColor::BLACK))), placement, &rows); + let Some(pixels) = render_raster(raster, size) else { return }; + + // Within the raster, the color the value path leaves of black, and clear past it + let value = evaluate_color_effects(stamped_while_scaled(Item::new_from_element(GraphicColor::BLACK), placement, &rows)).into_element(); + let [red, green, blue, alpha] = value.to_gamma_srgb_channels(); + let end = 16. + 16. * rows.last().map_or(1., |(_, scale)| *scale); + let expected: Vec> = (0..size.x * size.y) + .map(|index| { + let middle = DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5); + let within = middle.cmpgt(DVec2::splat(16.)).all() && middle.cmplt(DVec2::splat(end)).all(); + Some(if within { [red * alpha, green * alpha, blue * alpha, alpha] } else { [0.; 4] }) + }) + .collect(); + let (worst, _) = reference_difference(&pixels, &expected); + assert!(worst <= 1., "black {name} strays from the value's {:?} by up to {worst} levels", value.to_gamma_srgb_channels()); + } } /// A raster of `size` texels placed a texel to each of the render's pixels from `corner`, each of the straight 8-bit color `level` gives at its column and row. diff --git a/node-graph/nodes/blending/Cargo.toml b/node-graph/nodes/blending/Cargo.toml index 92758ea709..47e29d41b2 100644 --- a/node-graph/nodes/blending/Cargo.toml +++ b/node-graph/nodes/blending/Cargo.toml @@ -31,3 +31,10 @@ glam = { workspace = true } # Optional workspace dependencies serde = { workspace = true, optional = true } + +[dev-dependencies] +# Local dependencies +wgpu-executor = { workspace = true } + +# Workspace dependencies +futures = { workspace = true } diff --git a/node-graph/nodes/blending/src/effects.rs b/node-graph/nodes/blending/src/effects.rs index 5f4390d356..20ed1017e7 100644 --- a/node-graph/nodes/blending/src/effects.rs +++ b/node-graph/nodes/blending/src/effects.rs @@ -683,7 +683,7 @@ mod test { use core_types::list::{ATTR_EFFECTS, Item}; use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color}; use glam::{DAffine2, DVec2}; - use graphic_types::raster_types::{Image, Raster}; + use graphic_types::raster_types::{CPU, Image, Raster}; use graphic_types::{Effects, Graphic}; use vector_types::{Gradient, GradientForm}; @@ -731,6 +731,13 @@ mod test { ); } + /// The single pixel of the raster `item` with its effects carried out on the GPU and read back, or `None` without a GPU. + fn rendered_pixel(item: Item>) -> Option { + let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?; + let rendered = futures::executor::block_on(executor.read_back(item)).expect("the effects render"); + Some(rendered.element().data[0]) + } + #[test] fn paint_overlay_multiplies_a_color_into_the_content() { let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4); @@ -745,11 +752,11 @@ mod test { false.into(), DAffine2::IDENTITY.into(), ); - let result = raster_kernels::evaluate_raster_effects(result).into_element(); + let Some(color) = rendered_pixel(result) else { return }; // Multiplying by green keeps only the green channel. It blends within the content's share, so the translucent content keeps its own alpha. let expected = Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()); - assert!((result.data[0].to_vec4() - expected.to_vec4()).abs().max_element() < 1e-4, "{:?} against {expected:?}", result.data[0]); + assert!((color.to_vec4() - expected.to_vec4()).abs().max_element() < 0.01, "{color:?} against {expected:?}"); } #[test] @@ -766,7 +773,7 @@ mod test { false.into(), DAffine2::IDENTITY.into(), ); - let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0]; + let Some(color) = rendered_pixel(result) else { return }; assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}"); } @@ -1019,7 +1026,7 @@ mod test { false.into(), DAffine2::IDENTITY.into(), ); - let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0]; + let Some(color) = rendered_pixel(result) else { return }; assert!(color.r() > 0.99, "the hidden black paint leaves {color:?}"); } diff --git a/node-graph/nodes/blending/src/masks.rs b/node-graph/nodes/blending/src/masks.rs index 927cdb7984..200174eb48 100644 --- a/node-graph/nodes/blending/src/masks.rs +++ b/node-graph/nodes/blending/src/masks.rs @@ -97,9 +97,15 @@ fn feather( mod test { use core_types::Color; use core_types::list::{Item, List}; - use graphic_types::raster_types::{Image, Raster}; + use graphic_types::raster_types::{CPU, Image, Pixels, Raster}; use graphic_types::{Graphic, MaskMode}; + /// The GPU's render of the raster `item` with its effects carried out, read back, or `None` without a GPU. + fn rendered(item: Item>) -> Option> { + let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?; + Some(futures::executor::block_on(executor.read_back(item)).expect("the effects render")) + } + #[test] fn a_gray_luminance_mask_shows_the_content_at_its_gray_level() { let content = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))); @@ -115,15 +121,24 @@ mod test { 0_f64.into(), invert.into(), ); - raster_kernels::evaluate_raster_effects(result).into_element().data[0].a() + rendered(result).map(|rendered| rendered.element().data[0].a()) }; // Luminance is taken on gamma-encoded channels, so a middle gray shows half the content, as a PSD mask's gray level does - assert!((masked(MaskMode::Luminance, 100., false) - 0.5).abs() < 1e-3); - assert!((masked(MaskMode::Luminance, 100., true) - 0.5).abs() < 1e-3); - assert!((masked(MaskMode::Luminance, 50., false) - 0.75).abs() < 1e-3, "half the density hides half as much"); - assert!((masked(MaskMode::Alpha, 100., false) - 1.).abs() < 1e-6, "an opaque mask shows everything by its alpha"); - assert!(masked(MaskMode::Alpha, 100., true) < 1e-6); + let cases = [ + (MaskMode::Luminance, 100., false, 0.5), + (MaskMode::Luminance, 100., true, 0.5), + (MaskMode::Luminance, 50., false, 0.75), + (MaskMode::Alpha, 100., false, 1.), + (MaskMode::Alpha, 100., true, 0.), + ]; + for (mode, density, invert, expected) in cases { + let Some(alpha) = masked(mode, density, invert) else { return }; + assert!( + (alpha - expected).abs() < 0.005, + "{mode:?} at a density of {density} (inverted: {invert}) shows {alpha} rather than {expected}" + ); + } } #[test] @@ -156,7 +171,8 @@ mod test { let mirror = DAffine2::from_translation(DVec2::new(4., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.)); masked.set_attribute(ATTR_TRANSFORM, mirror * placement); - let alphas: Vec = raster_kernels::evaluate_raster_effects(masked).into_element().data.iter().map(|color| color.a().round()).collect(); + let Some(rendered) = rendered(masked) else { return }; + let alphas: Vec = rendered.element().data.iter().map(|color| color.a().round()).collect(); assert_eq!(alphas, [0., 0., 1., 1.], "the mask hides the half of the image it covered before the transform"); } } diff --git a/node-graph/nodes/gstd/src/platform_application_io.rs b/node-graph/nodes/gstd/src/platform_application_io.rs index b72ede6f1a..2ff09c5bb8 100644 --- a/node-graph/nodes/gstd/src/platform_application_io.rs +++ b/node-graph/nodes/gstd/src/platform_application_io.rs @@ -332,7 +332,7 @@ mod tests { #[tokio::test] async fn rasterize_renders_the_footprint_area_at_its_resolution() { - let Some(executor) = ::wgpu_executor::WgpuExecutor::new().await else { return }; + let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return }; let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.))); let data = List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red)))); diff --git a/node-graph/nodes/gstd/src/render_cache.rs b/node-graph/nodes/gstd/src/render_cache.rs index 4ee8a2ebae..5f5d1ab63c 100644 --- a/node-graph/nodes/gstd/src/render_cache.rs +++ b/node-graph/nodes/gstd/src/render_cache.rs @@ -793,7 +793,9 @@ mod tests { #[test] fn regions_out_of_view_are_held_weakly_and_those_in_view_strongly() { - let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return }; + let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else { + return; + }; let cache = TileCache::default(); let mut pool = Vec::new(); @@ -808,7 +810,9 @@ mod tests { #[test] fn a_parked_region_back_in_view_is_reused() { - let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return }; + let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else { + return; + }; let cache = TileCache::default(); let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1)); @@ -819,7 +823,9 @@ mod tests { #[test] fn a_parked_region_the_pool_evicted_is_rendered_again() { - let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return }; + let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else { + return; + }; let cache = TileCache::default(); let (_, evicted) = show(&cache, &context.device, &view(0), &zoom(1)); @@ -833,7 +839,9 @@ mod tests { #[test] fn the_regions_of_an_earlier_cache_key_are_reused_on_returning_to_it() { - let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return }; + let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else { + return; + }; let cache = TileCache::default(); let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1)); @@ -844,7 +852,9 @@ mod tests { #[test] fn the_regions_of_cache_keys_older_than_the_most_recent_ones_are_released() { - let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return }; + let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else { + return; + }; let cache = TileCache::default(); let (_, oldest) = show(&cache, &context.device, &view(0), &zoom(0)); diff --git a/node-graph/nodes/gstd/src/render_node/svg_readback.rs b/node-graph/nodes/gstd/src/render_node/svg_readback.rs index 0cb0063f65..8d73d77e4f 100644 --- a/node-graph/nodes/gstd/src/render_node/svg_readback.rs +++ b/node-graph/nodes/gstd/src/render_node/svg_readback.rs @@ -250,7 +250,7 @@ mod tests { #[test] fn an_svg_render_is_partial_until_its_readback_lands() { - let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return }; let tasks = Arc::new(HeldTasks::default()); let runtime = AsyncRuntime::new(tasks.clone()); let slot = SvgReadbackSlot::default(); @@ -301,7 +301,7 @@ mod tests { #[test] fn evaluations_of_content_in_view_draw_the_same_placeholders_so_its_readback_finishes_them() { - let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return }; let tasks = Arc::new(HeldTasks::default()); let runtime = AsyncRuntime::new(tasks.clone()); let (slot, in_view) = (SvgReadbackSlot::default(), SvgInViewSlot::default()); @@ -330,7 +330,7 @@ mod tests { #[test] fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() { - let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return }; let tasks = Arc::new(HeldTasks::default()); let runtime = AsyncRuntime::new(tasks.clone()); let slot = SvgReadbackSlot::default(); @@ -355,7 +355,7 @@ mod tests { #[test] fn a_readback_underway_is_cancelled_once_its_slot_is_dropped() { - let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return }; let tasks = Arc::new(HeldTasks::default()); let runtime = AsyncRuntime::new(tasks.clone()); let slot = SvgReadbackSlot::default(); diff --git a/node-graph/nodes/raster/src/adjustments.rs b/node-graph/nodes/raster/src/adjustments.rs index cd95c077a6..808c3e8b23 100644 --- a/node-graph/nodes/raster/src/adjustments.rs +++ b/node-graph/nodes/raster/src/adjustments.rs @@ -1460,7 +1460,10 @@ mod tests { let mut square = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.))); stamp_effect(&mut square, Effect::new(&shadow)); - let desaturated = raster_kernels::evaluate_raster_effects(desaturate((), square, DesaturateMethod::default().into())); + let Some(executor) = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests()) else { + return; + }; + let desaturated = futures::executor::block_on(executor.read_back(desaturate((), square, DesaturateMethod::default().into()))).expect("the effects render"); let shaded = desaturated.element().data.iter().filter(|pixel| pixel.a() > 0.5 && pixel.r() < 0.99).collect::>(); assert!(!shaded.is_empty(), "the shadow was carried out"); @@ -2141,7 +2144,10 @@ mod tests { use core_types::ATTR_TRANSFORM; use glam::DAffine2; use graphic_types::{Effect, EffectOperation, stamp_effect}; - use raster_kernels::evaluate_raster_effects; + + let Some(executor) = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests()) else { + return; + }; // A white square in the middle of a transparent image, placed one pixel per document unit, then blurred let mut image = Image::new(20, 20, Color::TRANSPARENT); @@ -2160,7 +2166,7 @@ mod tests { gamma: false, }), ); - let result = evaluate_raster_effects(super::make_opaque((), item, Item::new_from_element(100.))); + let result = futures::executor::block_on(executor.read_back(super::make_opaque((), item, Item::new_from_element(100.)))).expect("the effects render"); // Just outside the square, the blur's faint white becomes opaque white, where making it opaque first would have blurred in black let transform: DAffine2 = result.attribute_cloned_or_default(ATTR_TRANSFORM); diff --git a/node-graph/nodes/raster/src/channels.rs b/node-graph/nodes/raster/src/channels.rs index 5af2ce80e8..2111ff4df0 100644 --- a/node-graph/nodes/raster/src/channels.rs +++ b/node-graph/nodes/raster/src/channels.rs @@ -223,7 +223,7 @@ mod tests { fn rendered(graphic: &Item, size: UVec2) -> Option> { use rendering::{Render, RenderParams}; - let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?; + let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?; let list = core_types::list::List::new_from_item(graphic.clone()); let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()); let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render"); diff --git a/node-graph/preprocessor/src/readback_tests.rs b/node-graph/preprocessor/src/readback_tests.rs index 2fba4fec3b..25a5090ae1 100644 --- a/node-graph/preprocessor/src/readback_tests.rs +++ b/node-graph/preprocessor/src/readback_tests.rs @@ -140,7 +140,7 @@ struct Compiled { impl Compiled { /// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU. fn new(network: NodeNetwork) -> Option { - let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?; + let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?; let application_io = PlatformApplicationIo::new_with_executor(gpu); Some(Self::with_application_io(network, application_io)) }