use emblema::{
Affine2, Atlas, BackendPreference, BlendMode, Canvas, Color, ColorFilter, Context, Coverage,
Dash, Error, Extent2D, GlyphKey, GradientStop, ImageFilter, Layer, LineCap, LineJoin,
MaskBlurStyle, Morphology, Paint, Path, PathBuilder, PixelFormat, PointMode, PositionedGlyph,
Rect, Result, RoundingRadii, Sampling, Shader, SourceRect, Sprite, StrokeStyle, Style,
TileMode, Transform2D, Vec2, VertexMode, Vertices, MAX_STOPS, MORPHOLOGY_TAPS, RUNTIME_FLOATS,
};
use googletest::prelude::*;
use std::f32::consts::PI;
const SIZE: Extent2D = Extent2D {
width: 128,
height: 128,
};
fn context() -> Option<Context> {
match Context::new(BackendPreference::Auto) {
Ok(ctx) => Some(ctx),
Err(e) => {
eprintln!("skipping: no usable backend ({e})");
None
}
}
}
fn render(ctx: &mut Context, canvas: Canvas) -> Vec<u8> {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
}
fn render_recording(ctx: &mut Context, recording: &emblema::Recording) -> Vec<u8> {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
}
fn pixel(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
let i = ((y * SIZE.width + x) * 4) as usize;
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
}
fn square_path(rect: Rect) -> Path {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(rect.left, rect.top))
.line_to(Vec2::new(rect.right, rect.top))
.line_to(Vec2::new(rect.right, rect.bottom))
.line_to(Vec2::new(rect.left, rect.bottom))
.close();
b.build()
}
fn concave_path(rect: Rect) -> Path {
let (mx, my) = (
(rect.left + rect.right) / 2.0,
(rect.top + rect.bottom) / 2.0,
);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(rect.left, rect.top))
.line_to(Vec2::new(rect.right, rect.top))
.line_to(Vec2::new(rect.right, my))
.line_to(Vec2::new(mx, my))
.line_to(Vec2::new(mx, rect.bottom))
.line_to(Vec2::new(rect.left, rect.bottom))
.close();
b.build()
}
#[track_caller]
fn close_enough(got: [u8; 4], want: [u8; 4], within: u8, what: &str) {
let off = (0..4).find(|&i| got[i].abs_diff(want[i]) > within);
assert!(
off.is_none(),
"{what}: got {got:?}, wanted {want:?} within {within} \
(channel {} differs by {})",
off.unwrap_or(0),
got[off.unwrap_or(0)].abs_diff(want[off.unwrap_or(0)])
);
}
#[test]
fn a_context_reports_which_backend_it_chose() {
let Some(ctx) = context() else { return };
eprintln!(
"backend: {} on {}",
ctx.backend(),
ctx.capabilities().device_name
);
assert!(ctx.capabilities().max_texture_size >= 2048);
}
#[test]
fn a_rectangle_lands_where_it_was_asked_to() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 96.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 64, 64), [255, 255, 255, 255], "inside");
assert_eq!(pixel(&pixels, 8, 8), [0, 0, 0, 255], "outside");
assert_eq!(pixel(&pixels, 64, 16), [0, 0, 0, 255], "above the rect");
}
#[test]
fn colors_are_specified_in_srgb_and_stored_in_srgb() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::rgba8(128, 128, 128, 255));
let pixels = render(&mut ctx, canvas);
let stored = pixel(&pixels, 4, 4)[0];
assert_eq!(stored, 128, "sRGB 128 should store as 128, got {stored}");
}
#[test]
fn the_transform_stack_places_shapes_independently() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::fill(Color::WHITE).with_anti_alias(false);
canvas.save();
canvas.translate(16.0, 16.0);
canvas
.draw_rect(Rect::from_size(16.0, 16.0), &paint)
.unwrap();
canvas.restore();
canvas
.draw_rect(Rect::from_size(16.0, 16.0), &paint)
.unwrap();
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 24, 24), [255, 255, 255, 255], "translated");
assert_eq!(pixel(&pixels, 8, 8), [255, 255, 255, 255], "restored");
assert_eq!(pixel(&pixels, 60, 60), [0, 0, 0, 255], "neither");
}
#[test]
fn a_stroke_traces_an_outline_rather_than_filling_it() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 96.0),
&Paint::stroke(Color::WHITE, 8.0).with_anti_alias(false),
)
.expect("stroke");
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 64, 32), [255, 255, 255, 255], "on the edge");
assert_eq!(pixel(&pixels, 64, 64), [0, 0, 0, 255], "interior");
}
#[test]
fn translucent_paint_blends_with_what_is_underneath() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 1.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 0.5)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
for (channel, want) in got.iter().zip([128u8, 0, 128, 255]) {
assert!(
(*channel as i32 - want as i32).abs() <= 2,
"got {got:?}, expected about [128, 0, 128, 255]"
);
}
}
#[test]
fn a_shadows_softness_is_fixed_in_device_pixels() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(256, 256);
let measure = |ctx: &mut Context, scale: f32| -> (usize, usize) {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas.save();
canvas.scale(scale, scale);
let center = 128.0 / scale;
let mut b = PathBuilder::new();
b.move_to(Vec2::new(center - 20.0, center - 20.0))
.line_to(Vec2::new(center + 20.0, center - 20.0))
.line_to(Vec2::new(center + 20.0, center + 20.0))
.line_to(Vec2::new(center - 20.0, center + 20.0))
.close();
canvas
.draw_shadow(&b.build(), Color::WHITE, 6.0, false)
.expect("a shadow");
canvas.restore();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let value = |x: usize| pixels[(128 * extent.width as usize + x) * 4];
let peak = (0..extent.width as usize).map(value).max().unwrap_or(0) as u32;
let solid = (0..128).filter(|x| value(*x) as u32 * 2 > peak).count();
let lit = (0..128).filter(|x| value(*x) > 6).count();
(solid, lit - solid)
};
let (solid_at_one, tail_at_one) = measure(&mut ctx, 1.0);
let (solid_at_two, tail_at_two) = measure(&mut ctx, 2.0);
assert!(
solid_at_two > solid_at_one + 8,
"doubling the scale did not grow the caster: {solid_at_one} then {solid_at_two}"
);
assert!(
(tail_at_one as i32 - tail_at_two as i32).abs() <= 2,
"the shadow's softness moved with the transform: {tail_at_one} then \
{tail_at_two} device pixels. Upstream's does not, and the division in \
`draw_shadow` is what holds it still now that a blur's sigma scales"
);
}
#[test]
fn a_colored_blurred_rounded_rect_is_premultiplied() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::fill(Color::srgb(0.0, 0.0, 1.0, 0.5)).with_mask_blur(4.0);
canvas
.draw_path(
&Rect::new(16.0, 16.0, 112.0, 112.0).to_rounded_path(12.0),
&paint,
)
.expect("a blurred rounded rect");
let recording = canvas.finish();
assert_eq!(recording.passes.len(), 1, "not the analytic route");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let center = pixel(&pixels, 64, 64);
assert!(
(center[2] as i32 - 128).abs() <= 2 && center[0] == 0 && center[1] == 0,
"half-transparent blue over black should be half blue, got {center:?}"
);
let brightest = pixels.chunks_exact(4).map(|p| p[2]).max().unwrap_or(0);
assert!(
brightest <= 130,
"a channel above its alpha: blue reaches {brightest}"
);
}
#[test]
fn a_shadows_offset_is_fixed_in_device_pixels() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(256, 256);
let elevation = 12.0;
let centroid = |ctx: &mut Context, scale: f32, radians: f32| -> (f32, f32) {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas.save();
canvas.translate(128.0, 128.0);
canvas.rotate(radians);
canvas.scale(scale, scale);
let half = 16.0 / scale;
let mut b = PathBuilder::new();
b.move_to(Vec2::new(-half, -half))
.line_to(Vec2::new(half, -half))
.line_to(Vec2::new(half, half))
.line_to(Vec2::new(-half, half))
.close();
canvas
.draw_shadow(&b.build(), Color::WHITE, elevation, false)
.expect("a shadow");
canvas.restore();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let (mut sum, mut sx, mut sy) = (0.0f64, 0.0f64, 0.0f64);
for y in 0..extent.height as usize {
for x in 0..extent.width as usize {
let v = f64::from(pixels[(y * extent.width as usize + x) * 4]);
sum += v;
sx += v * x as f64;
sy += v * y as f64;
}
}
assert!(sum > 0.0, "no shadow drawn");
((sx / sum) as f32 + 0.5, (sy / sum) as f32 + 0.5)
};
for (scale, radians, what) in [
(1.0, 0.0, "unit"),
(2.0, 0.0, "scaled by two"),
(0.5, 0.0, "scaled by a half"),
(1.0, std::f32::consts::FRAC_PI_2, "turned a quarter"),
(2.0, 0.6, "scaled and turned"),
] {
let (x, y) = centroid(&mut ctx, scale, radians);
assert!(
(x - 128.0).abs() < 0.5 && (y - (128.0 + elevation)).abs() < 0.5,
"{what}: the shadow's centroid is at {x}, {y}; it falls {elevation} \
device pixels below the caster's center at 128, 128 upstream"
);
}
}
#[test]
fn a_blur_past_the_tap_budget_shrinks_what_it_blurs() {
let extent = Extent2D::new(256, 256);
let passes_for = |sigma: f32| -> usize {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::opacity(1.0).with_blur(sigma));
canvas
.draw_rect(
Rect::new(96.0, 96.0, 160.0, 160.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("square");
canvas.restore();
canvas.finish().passes.len()
};
assert_eq!(passes_for(8.0), 4, "a narrow blur should not be reduced");
assert_eq!(
passes_for(18.0),
4,
"a blur inside the budget should not be reduced"
);
assert_eq!(
passes_for(20.0),
5,
"a blur past the budget should be halved once"
);
assert_eq!(
passes_for(40.0),
6,
"twice the deviation should halve once more"
);
assert_eq!(passes_for(80.0), 7, "and again");
assert!(
passes_for(100_000.0) <= 12,
"an enormous deviation should not keep adding passes: {}",
passes_for(100_000.0)
);
}
#[test]
fn a_blur_far_wider_than_its_subject_still_draws() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(128, 128);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
for case in 0..4 {
let name = match case {
0 => "a layer bounded to eight pixels",
1 => "a layer bounded to one pixel",
2 => "a mask blur wider than the frame",
_ => "a shadow at an absurd elevation",
};
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
match case {
0 | 1 => {
let (bounds, sigma) = if case == 0 {
(Rect::new(60.0, 60.0, 68.0, 68.0), 400.0)
} else {
(Rect::new(63.0, 63.0, 64.0, 64.0), 200.0)
};
canvas.save_layer_bounds(Layer::opacity(1.0).with_blur(sigma), bounds);
canvas
.draw_rect(square, &Paint::fill(Color::WHITE).with_anti_alias(false))
.expect("square");
canvas.restore();
}
2 => {
canvas
.draw_rect(square, &Paint::fill(Color::WHITE).with_mask_blur(60.0))
.expect("mask blur");
}
_ => {
canvas
.draw_shadow(&square.to_rounded_path(4.0), Color::BLACK, 300.0, false)
.expect("shadow");
}
}
let recording = canvas.finish();
for (index, pass) in recording.passes.iter().enumerate() {
assert!(
pass.extent.width >= 1 && pass.extent.height >= 1,
"{name}: pass {index} has no pixels: {:?}",
pass.extent
);
}
assert!(
recording.passes.len() <= 12,
"{name}: {} passes, which is more than a reduction should need",
recording.passes.len()
);
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording)
.unwrap_or_else(|e| panic!("{name}: {e}"));
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
assert!(
!pixels
.chunks_exact(4)
.any(|texel| texel[3] == 0 && texel[0] > 0),
"{name}: a pixel came back with color and no alpha"
);
}
}
#[test]
fn a_deviation_is_clamped_and_a_nan_is_not_clamped_into_one() {
let extent = Extent2D::new(64, 64);
let passes_for = |sigma: f32| -> usize {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::opacity(1.0).with_blur(sigma));
canvas
.draw_rect(
Rect::new(16.0, 16.0, 48.0, 48.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("square");
canvas.restore();
canvas.finish().passes.len()
};
assert_eq!(
passes_for(500.0),
passes_for(50_000.0),
"a deviation past the clamp should draw the same as one at it"
);
assert_eq!(
passes_for(f32::NAN),
passes_for(0.0),
"a NaN deviation should draw the same as no blur at all"
);
assert!(
passes_for(8.0) > passes_for(0.0),
"this comparison says nothing unless a blur costs passes"
);
}
#[test]
fn a_blur_preserves_the_total_light_in_the_frame() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().float_render_targets {
eprintln!("skipping: no float render targets");
return;
}
let extent = Extent2D::new(256, 256);
let total = |ctx: &mut Context, sigma: f32| -> (f64, u32) {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
if sigma > 0.0 {
canvas.save_layer(Layer::opacity(1.0).with_blur(sigma));
}
canvas
.draw_rect(
Rect::new(96.0, 96.0, 160.0, 160.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
if sigma > 0.0 {
canvas.restore();
}
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba16Float)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let (mut sum, mut lit_edge) = (0.0f64, 0u32);
for y in 0..extent.height as usize {
for x in 0..extent.width as usize {
let at = (y * extent.width as usize + x) * 8;
let value = half::f16::from_le_bytes([pixels[at], pixels[at + 1]]).to_f32() as f64;
sum += value;
let border = x == 0
|| y == 0
|| x + 1 == extent.width as usize
|| y + 1 == extent.height as usize;
if border && value > 1e-4 {
lit_edge += 1;
}
}
}
(sum, lit_edge)
};
let (unblurred, _) = total(&mut ctx, 0.0);
assert!(unblurred > 0.0, "the unblurred square drew nothing");
for sigma in [2.0f32, 8.0, 24.0] {
let (blurred, lit_edge) = total(&mut ctx, sigma);
assert_eq!(
lit_edge, 0,
"at sigma {sigma} the blur reached the frame edge, so light leaving \
cannot be told from light lost and this measurement says nothing"
);
let ratio = blurred / unblurred;
assert!(
(ratio - 1.0).abs() < 0.01,
"at sigma {sigma} the blur changed the total light by {:.2}%: \
{blurred:.1} against {unblurred:.1}",
(ratio - 1.0) * 100.0
);
}
}
#[test]
fn dithering_tracks_a_gradient_better_than_rounding_does() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(256, 64);
let render =
|ctx: &mut Context, format: PixelFormat, lo: f32, hi: f32, interpolated: bool| -> Vec<u8> {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
let paint = Paint::default()
.with_shader(Shader::LinearGradient {
start: Vec2::ZERO,
end: Vec2::new(256.0, 0.0),
stops: vec![
GradientStop {
offset: 0.0,
color: Color::srgb(lo, lo, lo, 1.0),
},
GradientStop {
offset: 1.0,
color: Color::srgb(hi, hi, hi, 1.0),
},
],
tile: TileMode::Clamp,
})
.with_anti_alias(false);
if interpolated {
canvas
.draw_rect(Rect::new(0.0, 0.0, 256.0, 64.0), &paint)
.expect("gradient");
} else {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(0.0, 0.0))
.line_to(Vec2::new(256.0, 0.0))
.line_to(Vec2::new(256.0, 64.0))
.line_to(Vec2::new(0.0, 64.0))
.close();
canvas.draw_path(&b.build(), &paint).expect("gradient");
}
let mut surface = ctx.create_surface(extent, format).expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
for (route, interpolated) in [("interpolated", true), ("per fragment", false)] {
for (band, lo, hi) in [("dark", 0.10f32, 0.16f32), ("bright", 0.60, 0.66)] {
let stored = render(&mut ctx, PixelFormat::Rgba8Unorm, lo, hi, interpolated);
let ideal = |x: usize| {
let t = (x as f64 + 0.5) / extent.width as f64;
lo as f64 + (hi - lo) as f64 * t
};
let mut bias = 0.0f64;
for y in 0..extent.height as usize {
for x in 0..extent.width as usize {
let at = (y * extent.width as usize + x) * 4;
bias += stored[at] as f64 / 255.0 - ideal(x);
}
}
let bias = bias / (extent.width as usize * extent.height as usize) as f64;
let (mut dithered_error, mut rounded_error, mut blocks) = (0.0f64, 0.0f64, 0usize);
for top in (0..extent.height as usize - 7).step_by(8) {
for left in (0..extent.width as usize - 7).step_by(8) {
let (mut want, mut got, mut rounded) = (0.0f64, 0.0f64, 0.0f64);
for y in top..top + 8 {
for x in left..left + 8 {
let at = (y * extent.width as usize + x) * 4;
let value = ideal(x);
want += value;
got += stored[at] as f64 / 255.0;
rounded += (value * 255.0).round() / 255.0;
}
}
dithered_error += (got - want - bias * 64.0).abs() / 64.0;
rounded_error += (rounded - want).abs() / 64.0;
blocks += 1;
}
}
let (dithered_error, rounded_error) = (
dithered_error / blocks as f64,
rounded_error / blocks as f64,
);
assert!(
dithered_error <= rounded_error,
"{band}, {route}: dithering tracks worse than rounding, \
{dithered_error:.6} against {rounded_error:.6}"
);
assert!(
rounded_error / dithered_error > 3.0,
"{band}, {route}: dithering barely helped, \
{dithered_error:.6} against {rounded_error:.6}"
);
}
}
}
#[test]
fn the_two_gradient_routes_agree() {
let Some(mut ctx) = context() else { return };
let stops = || {
vec![
GradientStop::new(Color::srgb(0.9, 0.1, 0.2, 1.0), 0.0),
GradientStop::new(Color::srgb(0.1, 0.3, 0.9, 1.0), 0.45),
GradientStop::new(Color::srgb(0.2, 0.8, 0.3, 1.0), 1.0),
]
};
let shader = || Shader::LinearGradient {
start: Vec2::new(0.0, 0.0),
end: Vec2::new(128.0, 0.0),
stops: stops(),
tile: TileMode::Clamp,
};
let mut fast = Canvas::new(SIZE);
fast.clear(Color::BLACK);
fast.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::WHITE).with_shader(shader()),
)
.expect("the interpolated route");
let interpolated = fast.finish();
let mut slow = Canvas::new(SIZE);
slow.clear(Color::BLACK);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(0.0, 0.0))
.line_to(Vec2::new(128.0, 0.0))
.line_to(Vec2::new(128.0, 128.0))
.line_to(Vec2::new(0.0, 128.0))
.close();
slow.draw_path(&b.build(), &Paint::fill(Color::WHITE).with_shader(shader()))
.expect("the per-fragment route");
let per_fragment = slow.finish();
let materials = |r: &emblema::Recording| -> Vec<emblema_hal::Material> {
r.passes
.iter()
.flat_map(|p| p.batch.draws())
.map(|d| d.material.clone())
.collect()
};
assert!(
materials(&interpolated)
.iter()
.any(|m| matches!(m, emblema_hal::Material::VertexGradient)),
"the rectangle did not take the interpolated route"
);
assert!(
materials(&per_fragment)
.iter()
.any(|m| matches!(m, emblema_hal::Material::LinearGradient { .. })),
"the traced path did not take the per-fragment route"
);
let a = render_recording(&mut ctx, &interpolated);
let b2 = render_recording(&mut ctx, &per_fragment);
assert_eq!(a.len(), b2.len());
let mut worst = 0i32;
for (x, y) in a.iter().zip(b2.iter()) {
worst = worst.max((*x as i32 - *y as i32).abs());
}
assert!(
worst <= 1,
"the two gradient routes disagree by {worst} levels"
);
}
#[test]
fn the_interpolated_route_refuses_what_it_cannot_draw() {
let axis_aligned = |start: Vec2, end: Vec2, stops: Vec<GradientStop>| Shader::LinearGradient {
start,
end,
stops,
tile: TileMode::Clamp,
};
let two = || {
vec![
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.0, 0.0, 1.0, 1.0), 1.0),
]
};
let rect = Rect::new(0.0, 0.0, 128.0, 128.0);
let took_it = |shader: Shader, build: &dyn Fn(&mut Canvas, &Paint)| -> bool {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::fill(Color::WHITE).with_shader(shader);
build(&mut canvas, &paint);
canvas
.finish()
.passes
.iter()
.flat_map(|p| p.batch.draws())
.any(|d| matches!(d.material, emblema_hal::Material::VertexGradient))
};
let as_rect = |canvas: &mut Canvas, paint: &Paint| {
canvas.draw_rect(rect, paint).expect("rect");
};
assert!(
took_it(
axis_aligned(Vec2::ZERO, Vec2::new(128.0, 0.0), two()),
&as_rect
),
"a horizontal wash on the rectangle's edges is the case this exists for"
);
assert!(
took_it(
axis_aligned(Vec2::ZERO, Vec2::new(0.0, 128.0), two()),
&as_rect
),
"upstream's predicate takes a vertical wash as readily as a horizontal one"
);
assert!(
took_it(
axis_aligned(Vec2::new(128.0, 0.0), Vec2::ZERO, two()),
&as_rect
),
"the endpoints may arrive in either order"
);
assert!(
!took_it(
axis_aligned(Vec2::ZERO, Vec2::new(128.0, 128.0), two()),
&as_rect
),
"a diagonal gradient is not axis-aligned and the sections would be wrong"
);
assert!(
!took_it(
axis_aligned(Vec2::new(16.0, 0.0), Vec2::new(112.0, 0.0), two()),
&as_rect
),
"endpoints inside the rectangle leave a region no section covers"
);
assert!(
!took_it(
axis_aligned(Vec2::ZERO, Vec2::new(256.0, 0.0), two()),
&as_rect
),
"endpoints past the rectangle put the whole ramp in part of the shape"
);
let as_path = |canvas: &mut Canvas, paint: &Paint| {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(0.0, 0.0))
.line_to(Vec2::new(128.0, 0.0))
.line_to(Vec2::new(128.0, 128.0))
.line_to(Vec2::new(0.0, 128.0))
.close();
canvas.draw_path(&b.build(), paint).expect("path");
};
assert!(
!took_it(
axis_aligned(Vec2::ZERO, Vec2::new(128.0, 0.0), two()),
&as_path
),
"a traced rectangle is not a recorded one"
);
let stroked = |canvas: &mut Canvas, paint: &Paint| {
canvas
.draw_rect(
rect,
&paint
.clone()
.with_style(Style::Stroke(StrokeStyle::new(8.0))),
)
.expect("stroke");
};
assert!(
!took_it(
axis_aligned(Vec2::ZERO, Vec2::new(128.0, 0.0), two()),
&stroked
),
"a stroked rectangle covers its border, not its area"
);
let blurred = |canvas: &mut Canvas, paint: &Paint| {
canvas
.draw_rect(rect, &paint.clone().with_mask_blur(4.0))
.expect("mask blur");
};
assert!(
!took_it(
axis_aligned(Vec2::ZERO, Vec2::new(128.0, 0.0), two()),
&blurred
),
"a mask blur must reach the masked route, not this one"
);
for mode in [TileMode::Repeat, TileMode::Mirror, TileMode::Decal] {
let shader = Shader::LinearGradient {
start: Vec2::ZERO,
end: Vec2::new(128.0, 0.0),
stops: two(),
tile: mode,
};
assert!(
!took_it(shader, &as_rect),
"{mode:?} decides what happens outside the span, which sections cannot express"
);
}
}
#[test]
fn dithering_leaves_flat_color_and_float_targets_alone() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(32, 32);
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 32.0, 32.0),
&Paint::fill(Color::srgb(0.35, 0.35, 0.35, 1.0)).with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let distinct: std::collections::BTreeSet<u8> =
pixels.chunks_exact(4).map(|texel| texel[0]).collect();
assert_eq!(
distinct.len(),
1,
"a solid fill came back with more than one value: {distinct:?}"
);
if !ctx.capabilities().float_render_targets {
eprintln!("skipping the float half: no float render targets");
return;
}
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 32.0, 32.0),
&Paint::default()
.with_shader(Shader::LinearGradient {
start: Vec2::ZERO,
end: Vec2::new(32.0, 0.0),
stops: vec![
GradientStop {
offset: 0.0,
color: Color::srgb(0.20, 0.20, 0.20, 1.0),
},
GradientStop {
offset: 1.0,
color: Color::srgb(0.22, 0.22, 0.22, 1.0),
},
],
tile: TileMode::Clamp,
})
.with_anti_alias(false),
)
.expect("gradient");
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba16Float)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let value_at = |x: usize, y: usize| -> f32 {
let at = (y * extent.width as usize + x) * 8;
half::f16::from_le_bytes([pixels[at], pixels[at + 1]]).to_f32()
};
let first = value_at(16, 0);
for y in 1..extent.height as usize {
assert_eq!(
value_at(16, y),
first,
"a float target was dithered at row {y}"
);
}
}
#[test]
fn a_layers_antialiasing_does_not_multisample_the_frame() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().sample_counts.supports(4) {
eprintln!("skipping: 4x not supported");
return;
}
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::opacity(1.0));
canvas
.draw_line(
Vec2::new(8.0, 8.0),
Vec2::new(120.0, 96.0),
&Paint::stroke(Color::WHITE, 6.0),
)
.expect("line");
canvas.restore();
let recording = canvas.finish();
let root = recording.passes.len() - 1;
assert_eq!(
recording.passes[root].descriptor.samples, 1,
"the root only composites a quad and should not be multisampled"
);
assert!(
recording.passes[..root]
.iter()
.any(|p| p.descriptor.samples == 4),
"the layer holding the line still has to be multisampled"
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let partial = pixels
.chunks_exact(4)
.filter(|p| p[0] > 0 && p[0] < 255)
.count();
assert!(
partial > 32,
"the line inside the layer is not antialiased: {partial} partial pixels"
);
}
#[test]
fn a_layer_does_not_inherit_the_frames_antialiasing() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().sample_counts.supports(4) {
eprintln!("skipping: 4x not supported");
return;
}
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_line(
Vec2::new(8.0, 8.0),
Vec2::new(120.0, 96.0),
&Paint::stroke(Color::WHITE, 6.0),
)
.expect("line");
canvas.save_layer(Layer::opacity(0.5));
canvas
.draw_rrect(
Rect::new(16.0, 16.0, 64.0, 64.0),
8.0,
&Paint::fill(Color::WHITE),
)
.expect("rrect");
canvas.restore();
let recording = canvas.finish();
let root = recording.passes.len() - 1;
assert_eq!(
recording.passes[root].descriptor.samples, 4,
"the frame's own line still needs multisampling"
);
for pass in &recording.passes[..root] {
assert_eq!(
pass.descriptor.samples, 1,
"a layer of analytic shapes should not be multisampled"
);
}
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
ctx.destroy_surface(surface);
}
#[test]
fn a_shadow_needs_no_background() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().sample_counts.supports(4) {
eprintln!("skipping: 4x not supported");
return;
}
let mut canvas = Canvas::new(SIZE);
canvas
.draw_shadow(
&Rect::new(24.0, 24.0, 104.0, 104.0).to_rounded_path(8.0),
Color::BLACK,
6.0,
false,
)
.expect("shadow");
let recording = canvas.finish();
assert_eq!(
recording.passes[recording.passes.len() - 1]
.descriptor
.samples,
1,
"the root composites the blurred layer and nothing else"
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording)
.expect("a shadow onto an uncleared canvas");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
assert!(
pixels.chunks_exact(4).any(|p| p[3] > 0),
"the shadow drew nothing"
);
}
#[test]
fn a_multisampled_frame_needs_a_background_and_says_so() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().sample_counts.supports(4) {
eprintln!("skipping: 4x not supported");
return;
}
let draw = |ctx: &mut Context, background: bool, anti_alias: bool| -> Result<()> {
let mut canvas = Canvas::new(SIZE);
if background {
canvas.clear(Color::BLACK);
}
canvas
.draw_line(
Vec2::new(8.0, 8.0),
Vec2::new(120.0, 120.0),
&Paint::stroke(Color::WHITE, 4.0).with_anti_alias(anti_alias),
)
.expect("record");
let mut surface = ctx.create_surface(SIZE, PixelFormat::Rgba8Unorm)?;
let outcome = ctx.draw(&mut surface, &canvas.finish()).map(|_| ());
ctx.destroy_surface(surface);
outcome
};
let refused = draw(&mut ctx, false, true).expect_err("a cleared-less multisampled frame");
let Error::Unsupported(message) = refused else {
panic!("expected a refusal, got {refused:?}");
};
assert!(
message.contains("clear color") && message.contains("one sample"),
"the refusal names neither remedy: {message}"
);
draw(&mut ctx, true, true).expect("a background makes it drawable");
draw(&mut ctx, false, false).expect("dropping antialiasing makes it drawable");
let mut canvas = Canvas::new(SIZE);
canvas
.draw_rrect(
Rect::new(8.0, 8.0, 120.0, 120.0),
12.0,
&Paint::fill(Color::WHITE),
)
.expect("record");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish())
.expect("an analytic shape antialiases with no background");
ctx.destroy_surface(surface);
}
#[test]
fn antialiasing_is_requested_through_the_paint() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().sample_counts.supports(4) {
eprintln!("skipping: 4x not supported");
return;
}
let draw = |ctx: &mut Context, anti_alias: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
48.0,
&Paint::fill(Color::WHITE).with_anti_alias(anti_alias),
)
.expect("circle");
render(ctx, canvas)
};
let partial = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.filter(|p| p[0] > 0 && p[0] < 255)
.count()
};
assert_eq!(partial(&draw(&mut ctx, false)), 0, "aliased");
assert!(partial(&draw(&mut ctx, true)) > 32, "antialiased");
}
#[test]
fn an_empty_frame_still_clears() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::rgba8(255, 255, 255, 255));
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 0, 0), [255, 255, 255, 255]);
}
fn every_backend() -> Vec<Context> {
[BackendPreference::Vulkan, BackendPreference::Gles]
.into_iter()
.filter_map(|preference| Context::new(preference).ok())
.collect()
}
#[test]
fn an_intermediate_is_never_given_an_srgb_format() {
for root in [
PixelFormat::Rgba8Unorm,
PixelFormat::Bgra8Unorm,
PixelFormat::Rgba8UnormSrgb,
PixelFormat::Bgra8UnormSrgb,
PixelFormat::Rgb10A2Unorm,
PixelFormat::Rgba16Float,
PixelFormat::R8Unorm,
] {
let intermediate = root.intermediate();
assert!(
intermediate.is_drawable(),
"a root of {root:?} gave an intermediate of {intermediate:?}, \
which would encode what the pipeline already encoded"
);
}
assert_eq!(
PixelFormat::Rgba16Float.intermediate(),
PixelFormat::Rgba16Float
);
}
#[test]
fn both_backends_refuse_an_srgb_surface() {
let mut contexts = every_backend();
if contexts.len() < 2 {
eprintln!("skipping: both backends are needed");
return;
}
for ctx in &mut contexts {
let backend = ctx.backend();
let outcome = ctx.create_surface(SIZE, PixelFormat::Rgba8UnormSrgb);
match outcome {
Ok(surface) => {
ctx.destroy_surface(surface);
panic!("{backend} allowed an sRGB surface, which would encode twice");
}
Err(Error::Unsupported(message)) => {
assert!(
message.contains("encode"),
"{backend} refused for a reason that is not this one: {message}"
);
}
Err(e) => panic!("{backend} refused an sRGB surface wrongly: {e}"),
}
}
for ctx in &mut contexts {
let backend = ctx.backend();
let surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.unwrap_or_else(|e| panic!("{backend} refused a plain surface: {e}"));
ctx.destroy_surface(surface);
}
}
fn deeply_clipped(ctx: &mut Context, count: usize, last: Option<&Path>) -> Result<Vec<u8>> {
let extent = Extent2D::new(64, 64);
let corner = |size: f32| {
let mut b = PathBuilder::new();
b.move_to(Vec2::ZERO)
.line_to(Vec2::new(size, 0.0))
.line_to(Vec2::new(0.0, size))
.close();
b.build()
};
let big = corner(64.0);
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
for _ in 0..count {
canvas.save();
canvas.clip_path(&big).expect("clip");
}
if let Some(path) = last {
canvas.save();
canvas.clip_path(path).expect("clip");
}
canvas
.draw_rect(
Rect::from_size(64.0, 64.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("fill");
for _ in 0..count + usize::from(last.is_some()) {
canvas.restore();
}
let mut surface = ctx.create_surface(extent, PixelFormat::Rgba8Unorm)?;
let outcome = ctx
.draw(&mut surface, &canvas.finish())
.and_then(|()| ctx.read(&mut surface));
ctx.destroy_surface(surface);
outcome
}
#[test]
fn a_clip_stack_deeper_than_the_stencil_is_refused_by_every_backend() {
let mut contexts = every_backend();
assert!(!contexts.is_empty(), "no backend, so nothing here ran");
for ctx in &mut contexts {
let backend = ctx.backend();
let error = deeply_clipped(ctx, 300, None)
.err()
.unwrap_or_else(|| panic!("{backend} accepted a clip stack of 300"));
let text = error.to_string();
assert!(
text.contains("clip nesting depth") && text.contains("255"),
"{backend} refused for the wrong reason: {text}"
);
}
}
#[test]
fn nesting_up_to_the_limit_still_works() {
let mut contexts = every_backend();
assert!(!contexts.is_empty(), "no backend, so nothing here ran");
for ctx in &mut contexts {
let backend = ctx.backend();
let pixels = deeply_clipped(ctx, 255, None)
.unwrap_or_else(|e| panic!("{backend} refused a legal clip stack of 255: {e}"));
let at = |x: u32, y: u32| pixels[((y * 64 + x) * 4) as usize];
assert_eq!(at(4, 4), 255, "{backend}: inside the clip should be drawn");
assert_eq!(at(60, 60), 0, "{backend}: outside the clip should not be");
}
}
#[test]
fn the_innermost_clip_still_applies_at_the_limit() {
let mut contexts = every_backend();
assert!(!contexts.is_empty(), "no backend, so nothing here ran");
let mut small = PathBuilder::new();
small
.move_to(Vec2::ZERO)
.line_to(Vec2::new(16.0, 0.0))
.line_to(Vec2::new(0.0, 16.0))
.close();
let small = small.build();
for ctx in &mut contexts {
let backend = ctx.backend();
let pixels = deeply_clipped(ctx, 254, Some(&small))
.unwrap_or_else(|e| panic!("{backend} refused a legal clip stack: {e}"));
let at = |x: u32, y: u32| pixels[((y * 64 + x) * 4) as usize];
assert_eq!(
at(3, 3),
255,
"{backend}: inside every clip should be drawn"
);
assert_eq!(
at(30, 10),
0,
"{backend}: the innermost clip stopped excluding anything"
);
}
}
#[test]
fn a_surface_from_one_context_is_refused_by_another() {
let (Ok(mut first), Ok(mut second)) = (
Context::new(BackendPreference::Vulkan),
Context::new(BackendPreference::Gles),
) else {
eprintln!("skipping: both backends are needed");
return;
};
let mut surface = first
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
let canvas = Canvas::new(SIZE);
assert_ne!(first.backend(), second.backend());
assert!(second.draw(&mut surface, &canvas.finish()).is_err());
first.destroy_surface(surface);
}
#[test]
fn a_rounded_rectangle_cuts_its_corners_and_keeps_its_edges() {
let Some(mut ctx) = context() else { return };
let region = Rect::new(16.0, 32.0, 112.0, 96.0);
let render = |ctx: &mut Context, radius: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(
region,
radius,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rrect");
render(ctx, canvas)
};
let square = render(&mut ctx, 0.0);
let rounded = render(&mut ctx, 16.0);
let lit = |pixels: &[u8], x: u32, y: u32| pixels[((y * SIZE.width + x) * 4) as usize] > 128;
for (x, y) in [(17, 33), (110, 33), (17, 94), (110, 94)] {
assert!(
lit(&square, x, y),
"square corner ({x},{y}) should be filled"
);
assert!(
!lit(&rounded, x, y),
"rounded corner ({x},{y}) should be cut away"
);
}
for (x, y) in [(64, 33), (64, 94), (17, 64), (110, 64)] {
assert!(
lit(&rounded, x, y),
"edge ({x},{y}) should survive rounding"
);
}
assert!(lit(&rounded, 64, 64), "the middle should be filled");
}
#[test]
fn an_antialiased_rounded_rectangle_is_two_triangles() {
let region = Rect::new(16.0, 32.0, 112.0, 96.0);
let vertices = |paint: &Paint| {
let mut canvas = Canvas::new(SIZE);
canvas.draw_rrect(region, 16.0, paint).expect("rrect");
canvas
.finish()
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum::<usize>()
};
let analytic = vertices(&Paint::fill(Color::WHITE));
assert_eq!(analytic, 4, "an antialiased fill should be one quad");
let tessellated = vertices(&Paint::fill(Color::WHITE).with_anti_alias(false));
assert!(
tessellated > analytic * 4,
"the tessellated path should cost many more vertices, got {tessellated}"
);
}
#[test]
fn only_an_antialiased_solid_paint_takes_the_analytic_path() {
let region = Rect::new(16.0, 32.0, 112.0, 96.0);
let vertices = |paint: &Paint, radius: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.draw_rrect(region, radius, paint).expect("rrect");
canvas
.finish()
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum::<usize>()
};
assert_eq!(
vertices(&Paint::fill(Color::WHITE), 16.0),
4,
"the fast path"
);
for (name, paint, radius) in [
(
"aliased",
Paint::fill(Color::WHITE).with_anti_alias(false),
16.0,
),
(
"gradient",
Paint::linear_gradient(
Vec2::ZERO,
Vec2::new(64.0, 0.0),
vec![
GradientStop::new(Color::WHITE, 0.0),
GradientStop::new(Color::BLACK, 1.0),
],
),
16.0,
),
] {
assert!(
vertices(&paint, radius) > 4,
"{name} should have fallen back to tessellation"
);
}
}
#[test]
fn an_antialiased_rectangle_antialiases_by_multisampling() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, anti_alias: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save();
canvas.translate(64.0, 64.0);
canvas.rotate(0.35);
canvas.translate(-64.0, -64.0);
canvas
.draw_rect(
Rect::new(30.5, 30.5, 97.5, 97.5),
&Paint::fill(Color::WHITE).with_anti_alias(anti_alias),
)
.expect("rect");
canvas.restore();
let recording = canvas.finish();
let samples = recording.root().descriptor.samples;
let pixels = render_recording(ctx, &recording);
let partial = pixels
.chunks_exact(4)
.filter(|texel| texel[0] > 8 && texel[0] < 247)
.count();
let coverage: u64 = pixels.chunks_exact(4).map(|texel| texel[0] as u64).sum();
(samples, partial, coverage as f64)
};
let (samples, partial, coverage) = draw(&mut ctx, true);
assert_eq!(
samples, 4,
"a tessellated rectangle takes its edge from the rasterizer"
);
assert!(
partial > 100,
"a rotated antialiased rectangle should have partly covered pixels, found {partial}"
);
let side = 97.5 - 30.5;
let exact = side * side * 255.0;
assert!(
(coverage - exact).abs() / exact < 0.01,
"the rotated rectangle covers {coverage} against an exact {exact}"
);
let (_, aliased_partial, _) = draw(&mut ctx, false);
assert_eq!(
aliased_partial, 0,
"an aliased rectangle should have no partly covered pixels"
);
}
fn analytic_shapes(canvas: &mut Canvas) {
canvas
.draw_rrect(
Rect::new(48.0, 38.0, 112.0, 70.0),
12.0,
&Paint::fill(Color::WHITE),
)
.expect("rrect");
canvas
.draw_circle(
Vec2::new(64.0, 80.0),
9.0,
&Paint::fill(Color::linear(1.0, 0.3, 0.2, 1.0)),
)
.expect("circle");
}
#[test]
fn an_analytic_shape_lands_the_same_in_a_bounded_layer() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(160, 120);
let region = Rect::new(48.0, 38.0, 112.0, 89.0);
let mut render_layered = |bounded: bool| {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
let layer = Layer::opacity(0.8);
match bounded {
true => canvas.save_layer_bounds(layer, region),
false => canvas.save_layer(layer),
};
analytic_shapes(&mut canvas);
canvas.restore();
let recording = canvas.finish();
let first = recording.passes[0].extent;
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
(pixels, first)
};
let (full, full_extent) = render_layered(false);
let (bounded, bounded_extent) = render_layered(true);
assert!(
full_extent != bounded_extent,
"both layers got the same target ({full_extent:?}), so this compares nothing"
);
assert!(
full_extent.width < extent.width && bounded_extent.width < extent.width,
"a layer holding two small shapes should not have taken the whole frame"
);
let worst = full
.iter()
.zip(&bounded)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(
worst <= 8,
"the shape moved when the layer was bounded: {worst}"
);
assert!(full.iter().any(|&b| b > 64), "the shapes rendered nothing");
}
#[test]
fn a_clip_confines_an_analytic_shape_exactly() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(160, 120);
let clip = Rect::new(30.0, 30.0, 100.0, 100.0);
let mut render_clipped = |clipped: bool| {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
if clipped {
canvas.save();
canvas.clip_rect(clip).expect("clip");
}
analytic_shapes(&mut canvas);
if clipped {
canvas.restore();
}
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let open = render_clipped(false);
let confined = render_clipped(true);
let mut inside = 0;
let mut outside = 0;
for y in 0..extent.height {
for x in 0..extent.width {
let at = ((y * extent.width + x) * 4) as usize;
let within = (x as f32) >= clip.left
&& (x as f32) < clip.right
&& (y as f32) >= clip.top
&& (y as f32) < clip.bottom;
if within {
assert_eq!(
&confined[at..at + 4],
&open[at..at + 4],
"({x}, {y}) is inside the clip and should be untouched by it"
);
if open[at] > 64 {
inside += 1;
}
} else {
assert_eq!(
&confined[at..at + 4],
&[0, 0, 0, 255],
"({x}, {y}) is outside the clip and should not have been drawn"
);
if open[at] > 64 {
outside += 1;
}
}
}
}
assert!(
inside > 0 && outside > 0,
"the clip removed nothing: {inside} in, {outside} out"
);
}
#[test]
fn an_outline_costs_the_distance_field_nothing() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(200, 160);
let mut stroked = |analytic: bool, kind: &str| {
let mut canvas = Canvas::new(extent).with_samples(4);
canvas.clear(Color::BLACK);
let paint = Paint::stroke(Color::WHITE, 10.0).with_anti_alias(analytic);
match kind {
"rrect" => canvas
.draw_rrect(Rect::new(30.0, 30.0, 170.0, 130.0), 24.0, &paint)
.expect("rrect"),
"circle" => canvas
.draw_circle(Vec2::new(100.0, 80.0), 55.0, &paint)
.expect("circle"),
_ => canvas
.draw_oval(Rect::new(20.0, 45.0, 180.0, 115.0), &paint)
.expect("oval"),
};
let recording = canvas.finish();
let vertices: usize = recording
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
(pixels, vertices)
};
for kind in ["rrect", "circle", "oval"] {
let (analytic, analytic_vertices) = stroked(true, kind);
let (tessellated, tessellated_vertices) = stroked(false, kind);
assert_eq!(analytic_vertices, 4, "{kind}: an outline should be a quad");
assert!(
tessellated_vertices > 32,
"{kind}: the tessellated outline should cost far more, got {tessellated_vertices}"
);
let area = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>() as f64
};
let difference = (area(&analytic) - area(&tessellated)).abs() / area(&tessellated);
assert!(
difference < 0.01,
"{kind}: the two outlines cover different amounts, {:.2}% apart",
difference * 100.0
);
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * extent.width + x) * 4) as usize];
assert_eq!(
at(&analytic, 100, 80),
0,
"{kind}: the middle should be empty"
);
assert_eq!(
at(&tessellated, 100, 80),
0,
"{kind}: the middle should be empty"
);
}
let (analytic, _) = stroked(true, "circle");
let (tessellated, _) = stroked(false, "circle");
let area = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>() as f64
};
let exact = std::f64::consts::PI * (60.0f64 * 60.0 - 50.0 * 50.0) * 255.0;
let analytic_error = (area(&analytic) - exact).abs() / exact;
let tessellated_error = (area(&tessellated) - exact).abs() / exact;
assert!(
analytic_error < 0.001,
"the analytic ring is {:.3}% off the exact annulus",
analytic_error * 100.0
);
assert!(
analytic_error < tessellated_error,
"the analytic ring should be nearer the exact annulus: {:.3}% against {:.3}%",
analytic_error * 100.0,
tessellated_error * 100.0
);
}
#[test]
fn an_analytic_stroke_deforms_with_the_transform() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(220, 160);
let mut ring = |analytic: bool, sx: f32, sy: f32| {
let mut canvas = Canvas::new(extent).with_samples(4);
canvas.clear(Color::BLACK);
canvas.save();
canvas.translate(110.0, 80.0);
canvas.scale(sx, sy);
canvas.translate(-110.0, -80.0);
canvas
.draw_circle(
Vec2::new(110.0, 80.0),
50.0,
&Paint::stroke(Color::WHITE, 12.0).with_anti_alias(analytic),
)
.expect("ring");
canvas.restore();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let across = |pixels: &[u8]| {
(0..extent.width)
.filter(|x| pixels[((80 * extent.width + x) * 4) as usize] > 128)
.count()
};
let coverage = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>() as f64
};
let (round, round_tessellated) = (ring(true, 1.0, 1.0), ring(false, 1.0, 1.0));
let (wide, wide_tessellated) = (ring(true, 2.0, 1.0), ring(false, 2.0, 1.0));
assert!(
across(&wide) > across(&round) + 12,
"the stroke did not stretch: {} against {}",
across(&wide),
across(&round)
);
for (name, analytic, tessellated) in [
("unscaled", &round, &round_tessellated),
("stretched", &wide, &wide_tessellated),
] {
assert_eq!(
across(analytic),
across(tessellated),
"{name}: the two strokes differ in thickness"
);
let apart = (coverage(analytic) - coverage(tessellated)).abs() / coverage(tessellated);
assert!(
apart < 0.01,
"{name}: the two strokes cover different amounts, {:.2}% apart",
apart * 100.0
);
}
}
#[test]
fn an_analytic_shape_does_not_erase_what_is_behind_it() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(128, 128);
let shape = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut over_a_backdrop = |blend: BlendMode, anti_alias: bool| {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.0, 0.4, 0.0, 1.0)).with_anti_alias(false),
)
.expect("backdrop");
canvas
.draw_rrect(
shape,
10.0,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0))
.with_blend(blend)
.with_anti_alias(anti_alias),
)
.expect("shape");
let recording = canvas.finish();
let vertices: usize = recording
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum();
let pixels = render_recording(&mut ctx, &recording);
(pixels, vertices)
};
let at = |pixels: &[u8], x: u32, y: u32| {
let i = ((y * extent.width + x) * 4) as usize;
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
};
let gaps = [(41, 41), (39, 64)];
let (replaced, replaced_vertices) = over_a_backdrop(BlendMode::Src, true);
let (tessellated, _) = over_a_backdrop(BlendMode::Src, false);
let (_, composited_vertices) = over_a_backdrop(BlendMode::SrcOver, true);
assert!(
replaced_vertices > composited_vertices,
"a destination-discarding mode should have fallen back to tessellation: \
{replaced_vertices} against {composited_vertices}"
);
for (x, y) in gaps {
assert_eq!(
at(&replaced, x, y),
at(&tessellated, x, y),
"({x}, {y}) differs between the two routes"
);
assert_ne!(
at(&replaced, x, y),
[0, 0, 0, 0],
"({x}, {y}) was erased rather than left alone"
);
}
let (composited, _) = over_a_backdrop(BlendMode::SrcOver, true);
for (x, y) in gaps {
assert_ne!(
at(&composited, x, y),
[0, 0, 0, 0],
"({x}, {y}) was erased by a mode that composites"
);
}
}
#[test]
fn an_oval_is_an_ellipse_rather_than_a_stadium() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(200, 140);
let bounds = Rect::new(20.0, 34.0, 180.0, 106.0);
let mut oval = |anti_alias: bool| {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_oval(
bounds,
&Paint::fill(Color::WHITE).with_anti_alias(anti_alias),
)
.expect("oval");
let recording = canvas.finish();
let vertices: usize = recording
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
(pixels, vertices)
};
let (analytic, analytic_vertices) = oval(true);
let (tessellated, tessellated_vertices) = oval(false);
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * extent.width + x) * 4) as usize];
assert_eq!(analytic_vertices, 4, "an antialiased oval should be a quad");
assert!(
tessellated_vertices > 16,
"the tessellated oval should cost many more vertices, got {tessellated_vertices}"
);
for (name, pixels) in [("analytic", &analytic), ("tessellated", &tessellated)] {
assert_eq!(
at(pixels, 140, 103),
0,
"{name}: this shape is a stadium, not an ellipse"
);
assert_eq!(at(pixels, 140, 98), 255, "{name}: inside the curve");
assert_eq!(at(pixels, 100, 70), 255, "{name}: center");
assert_eq!(at(pixels, 22, 70), 255, "{name}: the end of the major axis");
assert_eq!(
at(pixels, 100, 36),
255,
"{name}: the end of the minor axis"
);
assert_eq!(at(pixels, 25, 38), 0, "{name}: the corner is outside");
}
let exact = std::f64::consts::PI * 80.0 * 36.0 * 255.0;
let area = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>() as f64
};
let analytic_error = (area(&analytic) - exact).abs() / exact;
let tessellated_error = (area(&tessellated) - exact).abs() / exact;
assert!(
analytic_error < 0.001,
"the analytic oval is {:.3}% off the exact area",
analytic_error * 100.0
);
assert!(
analytic_error < tessellated_error,
"the analytic oval should be nearer the exact area: {:.3}% against {:.3}%",
analytic_error * 100.0,
tessellated_error * 100.0
);
}
#[test]
fn an_antialiased_circle_uses_the_same_distance_field() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(160, 120);
let radius = 40.0f32;
let mut draw = |analytic: bool| {
let mut canvas = Canvas::new(extent).with_samples(4);
canvas.clear(Color::BLACK);
if analytic {
canvas
.draw_circle(Vec2::new(80.0, 60.0), radius, &Paint::fill(Color::WHITE))
.expect("circle");
} else {
canvas
.draw_circle(
Vec2::new(80.0, 60.0),
radius,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("circle");
}
let recording = canvas.finish();
let vertices: usize = recording
.passes
.iter()
.map(|pass| pass.batch.vertices().len())
.sum();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let coverage: u64 = pixels.chunks_exact(4).map(|texel| texel[0] as u64).sum();
(vertices, coverage as f64)
};
let (analytic_vertices, analytic_coverage) = draw(true);
let (tessellated_vertices, tessellated_coverage) = draw(false);
assert_eq!(
analytic_vertices, 4,
"an antialiased circle should be a quad"
);
assert!(
tessellated_vertices > 16,
"the tessellated circle should cost many more vertices, got {tessellated_vertices}"
);
let exact = std::f64::consts::PI * (radius as f64) * (radius as f64) * 255.0;
let analytic_error = (analytic_coverage - exact).abs() / exact;
let tessellated_error = (tessellated_coverage - exact).abs() / exact;
assert!(
analytic_error < 0.002,
"the analytic circle is {:.3}% off the exact area",
analytic_error * 100.0
);
assert!(
analytic_error < tessellated_error,
"the analytic circle should be nearer the exact area than the \
tessellated one: {:.3}% against {:.3}%",
analytic_error * 100.0,
tessellated_error * 100.0
);
}
#[test]
fn the_two_shapes_still_agree_under_perspective() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(160, 120);
let region = Rect::new(40.0, 30.0, 120.0, 90.0);
let mut coverage = |analytic: bool, matrix: &[f32; 16], radius: f32| -> u64 {
let mut canvas = Canvas::new(extent).with_samples(4);
canvas.clear(Color::BLACK);
canvas.concat_4x4(matrix);
if analytic {
canvas
.draw_rrect(region, radius, &Paint::fill(Color::WHITE))
.expect("rrect");
} else {
canvas
.draw_path(®ion.to_rounded_path(radius), &Paint::fill(Color::WHITE))
.expect("path");
}
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>()
};
for (along_x, along_y) in [
(0.0, 0.002),
(0.0, 0.004),
(0.003, 0.0),
(0.002, 0.002),
(0.0, -0.003),
] {
let matrix = receding(along_x, along_y);
for radius in [20.0, 0.0] {
let analytic = coverage(true, &matrix, radius) as f64;
let tessellated = coverage(false, &matrix, radius) as f64;
let error = (analytic - tessellated).abs() / tessellated;
assert!(
error < 0.01,
"under ({along_x}, {along_y}) with radius {radius} the two paths \
cover different areas: {analytic} against {tessellated}, \
{:.2}% apart",
error * 100.0
);
}
}
let flat = coverage(true, &receding(0.0, 0.0), 20.0);
let deep = coverage(true, &receding(0.0, 0.004), 20.0);
assert!(
(flat as f64 - deep as f64).abs() / flat as f64 > 0.2,
"the perspective barely changed the shape: {flat} against {deep}"
);
}
#[test]
fn the_analytic_shape_matches_the_tessellated_one() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(160, 120);
let region = Rect::new(40.0, 30.0, 120.0, 90.0);
let mut coverage = |analytic: bool, sx: f32, sy: f32| {
let mut canvas = Canvas::new(extent).with_samples(4);
canvas.clear(Color::BLACK);
canvas.save();
canvas.translate(80.0, 60.0);
canvas.scale(sx, sy);
canvas.translate(-80.0, -60.0);
if analytic {
canvas
.draw_rrect(region, 20.0, &Paint::fill(Color::WHITE))
.expect("rrect");
} else {
canvas
.draw_path(®ion.to_rounded_path(20.0), &Paint::fill(Color::WHITE))
.expect("path");
}
canvas.restore();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
.chunks_exact(4)
.map(|texel| texel[0] as u64)
.sum::<u64>()
};
for (sx, sy) in [(1.0, 1.0), (1.4, 0.8), (0.6, 1.3)] {
let analytic = coverage(true, sx, sy) as f64;
let tessellated = coverage(false, sx, sy) as f64;
let error = (analytic - tessellated).abs() / tessellated;
assert!(
error < 0.01,
"at scale ({sx}, {sy}) the two paths cover different areas: \
{analytic} against {tessellated}, {:.2}% apart",
error * 100.0
);
}
}
#[test]
fn the_analytic_shape_antialiases_without_multisampling() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(
Rect::new(16.0, 32.0, 112.0, 96.0),
16.0,
&Paint::fill(Color::WHITE),
)
.expect("rrect");
let recording = canvas.finish();
assert_eq!(
recording.root().descriptor.samples,
1,
"the analytic path should not need a multisampled pass"
);
let pixels = render_recording(&mut ctx, &recording);
let partial = pixels
.chunks_exact(4)
.filter(|texel| texel[0] > 8 && texel[0] < 247)
.count();
assert!(
partial > 40,
"an analytic edge should have partly covered pixels, found {partial}"
);
}
#[test]
fn each_corner_of_a_rounded_rectangle_can_have_its_own_radii() {
let Some(mut ctx) = context() else { return };
let region = Rect::new(20.0, 20.0, 108.0, 108.0);
let shot = |ctx: &mut Context, draw: &dyn Fn(&mut Canvas)| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
draw(&mut canvas);
render(ctx, canvas)
};
let paint = || Paint::fill(Color::WHITE).with_anti_alias(false);
let uniform = shot(&mut ctx, &|c| {
c.draw_rrect(region, 16.0, &paint()).expect("uniform");
});
let spelled_out = shot(&mut ctx, &|c| {
c.draw_rrect_with_radii(region, [[16.0, 16.0]; 4], &paint())
.expect("uniform, spelled out");
});
assert_eq!(
uniform, spelled_out,
"a uniform shape asked for the general way should be the uniform shape"
);
let mixed = shot(&mut ctx, &|c| {
c.draw_rrect_with_radii(
region,
[[0.0, 0.0], [16.0, 16.0], [16.0, 16.0], [40.0, 40.0]],
&paint(),
)
.expect("mixed");
});
assert_ne!(
uniform, mixed,
"corners that differ should not draw the uniform shape"
);
let at = |p: &[u8], x: u32, y: u32| pixel(p, x, y)[0];
assert!(
at(&mixed, 22, 22) > 200,
"the square corner should be filled to its point"
);
assert_eq!(
at(&mixed, 106, 106),
0,
"the corner given the largest radii should be cut back furthest"
);
assert_eq!(
at(&uniform, 22, 22),
at(&uniform, 106, 106),
"a uniform shape is symmetric about its diagonal"
);
}
#[test]
fn radii_that_overrun_a_side_are_scaled_together_rather_than_singly() {
let Some(mut ctx) = context() else { return };
let region = Rect::new(20.0, 40.0, 108.0, 88.0);
let shot = |ctx: &mut Context, radii: RoundingRadii| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect_with_radii(
region,
radii,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rrect");
render(ctx, canvas)
};
let overrun = shot(&mut ctx, [[48.0, 48.0]; 4]);
let fitted = shot(&mut ctx, [[24.0, 24.0]; 4]);
assert_eq!(
overrun, fitted,
"radii twice too large should scale to the ones that fit"
);
let one_edge = shot(
&mut ctx,
[[48.0, 48.0], [48.0, 48.0], [12.0, 12.0], [12.0, 12.0]],
);
let scaled_all = shot(
&mut ctx,
[[44.0, 44.0], [44.0, 44.0], [11.0, 11.0], [11.0, 11.0]],
);
assert_eq!(
one_edge, scaled_all,
"one overrunning edge should scale every corner, not just its own two"
);
}
#[test]
fn a_radius_larger_than_the_rectangle_is_clamped() {
let Some(mut ctx) = context() else { return };
let region = Rect::new(16.0, 32.0, 112.0, 96.0);
let render = |ctx: &mut Context, radius: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(
region,
radius,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rrect");
render(ctx, canvas)
};
let exact = render(&mut ctx, 32.0);
let enormous = render(&mut ctx, 10_000.0);
assert_eq!(exact, enormous, "a huge radius should clamp to the stadium");
assert_eq!(
exact,
render(&mut ctx, f32::INFINITY),
"an infinite radius should clamp like any other large one"
);
let lit = |pixels: &[u8], x: u32, y: u32| pixels[((y * SIZE.width + x) * 4) as usize] > 128;
assert!(lit(&exact, 64, 64), "the middle should be filled");
assert!(!lit(&exact, 17, 33), "the corner should be gone");
assert!(lit(&exact, 17, 64), "the left end should reach its extreme");
}
#[test]
fn a_radius_of_zero_is_the_plain_rectangle() {
let region = Rect::new(16.0, 32.0, 112.0, 96.0);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(region, 0.0, &Paint::fill(Color::WHITE))
.expect("rrect");
let rounded = canvas.finish();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(region, &Paint::fill(Color::WHITE))
.expect("rect");
let square = canvas.finish();
assert_eq!(
rounded.draw_count(),
square.draw_count(),
"a zero radius should record the same drawing as a plain rectangle"
);
for radius in [-4.0, f32::NAN] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(region, radius, &Paint::fill(Color::WHITE))
.expect("rrect");
let recorded = canvas.finish();
assert_eq!(
recorded.draw_count(),
square.draw_count(),
"a radius of {radius} should record the same drawing as a plain rectangle"
);
}
}
#[test]
fn an_empty_rounded_rectangle_draws_nothing() {
let mut canvas = Canvas::new(SIZE);
canvas
.draw_rrect(
Rect::new(50.0, 50.0, 50.0, 20.0),
8.0,
&Paint::fill(Color::WHITE),
)
.expect("rrect");
assert!(
canvas.finish().is_empty(),
"a rectangle with no area should record no drawing"
);
}
#[test]
fn a_linear_gradient_runs_between_its_stops() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
let left = pixel(&pixels, 1, 64);
let middle = pixel(&pixels, 64, 64);
let right = pixel(&pixels, 126, 64);
assert!(left[0] > 240 && left[2] < 16, "left end: {left:?}");
assert!(right[2] > 240 && right[0] < 16, "right end: {right:?}");
assert!(
middle[0] > 80 && middle[0] < 180 && middle[2] > 80 && middle[2] < 180,
"midpoint should be a mix, got {middle:?}"
);
}
#[test]
fn a_linear_gradient_runs_the_same_way_on_a_target_that_is_not_square() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D {
width: 128,
height: 64,
};
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 64.0),
&Paint::linear_gradient(
Vec2::ZERO,
Vec2::new(64.0, 64.0),
vec![
GradientStop::new(Color::linear(0.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(1.0, 1.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let at = |x: u32, y: u32| pixels[((y * extent.width + x) * 4) as usize];
let (a, b, c) = (at(32, 0), at(0, 32), at(16, 16));
let spread = a.abs_diff(b).max(b.abs_diff(c)).max(a.abs_diff(c));
assert!(
spread <= 2,
"equidistant points along the axis differ: {a}, {b}, {c}"
);
assert!(at(32, 32) > a + 40, "{} should exceed {a}", at(32, 32));
assert!(at(1, 1) < 16, "the origin corner should be dark");
}
#[test]
fn a_gradient_runs_along_the_axis_it_was_given() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 128.0),
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
assert!(
pixel(&pixels, 64, 1)[0] > 240,
"top should be the first stop"
);
assert!(
pixel(&pixels, 64, 126)[2] > 240,
"bottom should be the last stop"
);
let a = pixel(&pixels, 4, 64);
let b = pixel(&pixels, 124, 64);
assert_eq!(a, b, "a vertical gradient should not vary horizontally");
}
#[test]
fn a_gradient_travels_with_the_canvas_transform() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, rotate: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if rotate {
canvas.translate(64.0, 64.0);
canvas.rotate(std::f32::consts::FRAC_PI_2);
canvas.translate(-64.0, -64.0);
}
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
render(ctx, canvas)
};
let plain = draw(&mut ctx, false);
let rotated = draw(&mut ctx, true);
assert!(
pixel(&plain, 1, 64)[0] > 240,
"unrotated starts red at left"
);
assert!(
pixel(&rotated, 64, 1)[0] > 240,
"rotated should start red at the top, got {:?}",
pixel(&rotated, 64, 1)
);
}
#[test]
fn a_gradient_with_more_than_two_stops_passes_through_each() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 1.0, 0.0, 1.0), 0.5),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
let middle = pixel(&pixels, 64, 64);
assert!(
middle[1] > 200 && middle[0] < 60 && middle[2] < 60,
"the middle stop should dominate at the midpoint, got {middle:?}"
);
}
#[test]
fn a_radial_gradient_runs_outward_from_its_center() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::radial_gradient(
Vec2::new(64.0, 64.0),
60.0,
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("radial");
let pixels = render(&mut ctx, canvas);
let center = pixel(&pixels, 64, 64);
assert!(center[0] > 240 && center[2] < 16, "center: {center:?}");
let right = pixel(&pixels, 64 + 40, 64);
let below = pixel(&pixels, 64, 64 + 40);
for channel in 0..4 {
assert!(
(right[channel] as i32 - below[channel] as i32).abs() <= 2,
"the gradient is not circular: right {right:?}, below {below:?}"
);
}
assert!(right[2] > center[2] + 40, "no falloff toward the edge");
}
#[test]
fn a_radial_gradient_stays_circular_on_a_non_square_target() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(192, 96);
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(192.0, 96.0),
&Paint::radial_gradient(
Vec2::new(96.0, 48.0),
40.0,
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("radial");
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let at = |x: u32, y: u32| {
let i = ((y * extent.width + x) * 4) as usize;
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
};
let right = at(96 + 30, 48);
let below = at(96, 48 + 30);
for channel in 0..4 {
assert!(
(right[channel] as i32 - below[channel] as i32).abs() <= 2,
"stretched by the aspect ratio: right {right:?}, below {below:?}"
);
}
}
fn tiled_ramp(ctx: &mut Context, tile: TileMode) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("ground");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(32.0, 0.0),
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_tile_mode(tile)
.with_blend(BlendMode::SrcOver)
.with_anti_alias(false),
)
.expect("gradient");
render(ctx, canvas)
}
#[test]
fn no_number_a_caller_can_write_takes_the_process_down() {
let Some(mut ctx) = context() else { return };
let poisons = [
("nan", f32::NAN),
("inf", f32::INFINITY),
("-inf", f32::NEG_INFINITY),
("huge", 1e30),
("-huge", -1e30),
("tiny", 1e-30),
("zero", 0.0),
("negative", -8.0),
];
for (name, v) in poisons {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let white = Paint::fill(Color::WHITE);
let stroked = Paint::stroke(Color::WHITE, v);
let _ = canvas.draw_rect(Rect::new(v, v, v + 32.0, v + 32.0), &white);
let _ = canvas.draw_rrect(Rect::from_size(64.0, 64.0), v, &white);
let _ = canvas.draw_circle(Vec2::new(64.0, 64.0), v, &white);
let _ = canvas.draw_oval(Rect::new(0.0, 0.0, v, v), &white);
let _ = canvas.draw_line(Vec2::ZERO, Vec2::new(v, v), &stroked);
let _ = canvas.draw_rect(Rect::from_size(32.0, 32.0), &stroked);
let mut builder = PathBuilder::new();
builder.move_to(Vec2::new(8.0, 8.0));
builder.quad_to(Vec2::new(v, 64.0), Vec2::new(96.0, 96.0));
builder.cubic_to(Vec2::new(v, v), Vec2::new(16.0, v), Vec2::new(8.0, 8.0));
builder.close();
let _ = canvas.draw_path(&builder.build(), &white);
let _ = canvas.draw_rect(
Rect::from_size(64.0, 64.0),
&Paint::radial_gradient(
Vec2::new(64.0, 64.0),
v,
vec![
GradientStop::new(Color::WHITE, v),
GradientStop::new(Color::BLACK, 1.0),
],
),
);
let _ = canvas.draw_rect(
Rect::from_size(64.0, 64.0),
&Paint::sweep_gradient(
Vec2::new(64.0, 64.0),
v,
v,
vec![
GradientStop::new(Color::WHITE, 0.0),
GradientStop::new(Color::BLACK, 1.0),
],
),
);
canvas.save();
let _ = canvas.clip_rect(Rect::new(v, v, v, v));
canvas.translate(v, v);
canvas.scale(v, v);
canvas.rotate(v);
let _ = canvas.draw_rect(Rect::from_size(16.0, 16.0), &white);
canvas.restore();
canvas.save_layer(Layer::opacity(v).with_blur(v));
let _ = canvas.draw_rect(Rect::from_size(48.0, 48.0), &white);
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixels.len(),
(SIZE.width * SIZE.height * 4) as usize,
"{name} did not produce a full frame"
);
}
}
#[test]
fn a_glyph_placed_by_arithmetic_that_went_wrong_still_renders_a_frame() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, _) = two_glyph_atlas();
let rect = atlas.get(solid).unwrap();
for (name, v) in [
("nan", f32::NAN),
("inf", f32::INFINITY),
("-inf", f32::NEG_INFINITY),
("huge", 1e30),
] {
let image = upload_atlas(&mut ctx, &atlas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let _ = canvas.draw_glyphs(
&[
PositionedGlyph::new(solid, [16.0, 16.0], rect),
PositionedGlyph::new(solid, [v, 40.0], rect),
PositionedGlyph::new(solid, [40.0, v], rect),
],
&atlas,
0,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)),
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(
pixel(&pixels, 20, 20),
[255, 0, 0, 255],
"{name}: the well-placed glyph in the same run did not survive"
);
}
}
type PoisonedDraw = Box<dyn Fn(&mut Canvas)>;
#[gtest]
fn a_draw_placed_at_nan_contributes_nothing() {
let Some(mut ctx) = context() else { return };
let reference = |ctx: &mut Context| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::linear(0.0, 1.0, 0.0, 1.0)),
)
.expect("reference");
render(ctx, canvas)
};
let expected = reference(&mut ctx);
let n = f32::NAN;
let cases: Vec<(&str, PoisonedDraw)> = vec![
(
"rect",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_rect(Rect::new(n, n, n, n), &Paint::fill(Color::WHITE));
}),
),
(
"rect with a nan edge",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_rect(Rect::new(0.0, 0.0, n, 64.0), &Paint::fill(Color::WHITE));
}),
),
(
"rounded rect",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_rrect(
Rect::new(n, 0.0, 64.0, 64.0),
8.0,
&Paint::fill(Color::WHITE),
);
}),
),
(
"circle",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_circle(Vec2::new(n, 64.0), 32.0, &Paint::fill(Color::WHITE));
}),
),
(
"oval",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_oval(Rect::new(0.0, n, 64.0, 64.0), &Paint::fill(Color::WHITE));
}),
),
(
"line",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_line(
Vec2::new(n, 0.0),
Vec2::new(128.0, 128.0),
&Paint::stroke(Color::WHITE, 4.0),
);
}),
),
(
"line of nan width",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_line(
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 128.0),
&Paint::stroke(Color::WHITE, n),
);
}),
),
(
"path",
Box::new(move |c: &mut Canvas| {
let mut builder = PathBuilder::new();
builder.move_to(Vec2::new(0.0, 0.0));
builder.line_to(Vec2::new(n, 64.0));
builder.line_to(Vec2::new(64.0, 64.0));
builder.close();
let _ = c.draw_path(&builder.build(), &Paint::fill(Color::WHITE));
}),
),
(
"translate",
Box::new(move |c: &mut Canvas| {
c.save();
c.translate(n, 0.0);
let _ = c.draw_rect(Rect::from_size(64.0, 64.0), &Paint::fill(Color::WHITE));
c.restore();
}),
),
(
"scale",
Box::new(move |c: &mut Canvas| {
c.save();
c.scale(n, 1.0);
let _ = c.draw_rect(Rect::from_size(64.0, 64.0), &Paint::fill(Color::WHITE));
c.restore();
}),
),
(
"rotate",
Box::new(move |c: &mut Canvas| {
c.save();
c.rotate(n);
let _ = c.draw_rect(Rect::from_size(64.0, 64.0), &Paint::fill(Color::WHITE));
c.restore();
}),
),
(
"gradient endpoints",
Box::new(move |c: &mut Canvas| {
let _ = c.draw_rect(
Rect::from_size(64.0, 64.0),
&Paint::linear_gradient(
Vec2::new(n, n),
Vec2::new(n, n),
vec![
GradientStop::new(Color::WHITE, 0.0),
GradientStop::new(Color::BLACK, 1.0),
],
),
);
}),
),
];
for (name, poison) in &cases {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::linear(0.0, 1.0, 0.0, 1.0)),
)
.expect("reference");
poison(&mut canvas);
let got = render(&mut ctx, canvas);
let differing = got
.chunks_exact(4)
.zip(expected.chunks_exact(4))
.filter(|(a, b)| a != b)
.count();
expect_that!(
differing,
eq(0),
"{name} at NaN changed {differing} pixel(s); such a draw should contribute nothing"
);
}
}
#[test]
fn a_gradient_with_many_stops_agrees_with_one_that_fits() {
let Some(mut ctx) = context() else { return };
let ends = vec![
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.5, 0.0, 0.5, 1.0), 0.5),
GradientStop::new(Color::srgb(0.0, 0.0, 1.0, 1.0), 1.0),
];
let mut many = ends.clone();
for (offset, t) in [(0.25, 0.25f32), (0.75, 0.75)] {
let c = if t < 0.5 { t * 2.0 } else { (t - 0.5) * 2.0 };
let color = if t < 0.5 {
Color::srgb(1.0 - c * 0.5, 0.0, c * 0.5, 1.0)
} else {
Color::srgb(0.5 - c * 0.5, 0.0, 0.5 + c * 0.5, 1.0)
};
many.push(GradientStop::new(color, offset));
}
many.sort_by(|a, b| a.offset.partial_cmp(&b.offset).unwrap());
assert!(
ends.len() <= MAX_STOPS,
"the control must take the walked path"
);
assert!(
many.len() > MAX_STOPS,
"the subject must take the ramp path"
);
let render_with = |ctx: &mut Context, stops: Vec<GradientStop>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), stops)
.with_anti_alias(false),
)
.expect("gradient");
render(ctx, canvas)
};
let walked = render_with(&mut ctx, ends);
let sampled = render_with(&mut ctx, many);
let mut worst = 0i32;
for x in 0..128u32 {
let a = pixel(&walked, x, 64);
let b = pixel(&sampled, x, 64);
for channel in 0..4 {
worst = worst.max((a[channel] as i32 - b[channel] as i32).abs());
}
}
assert!(
worst <= 1,
"the two paths disagree by {worst}, which is more than rounding"
);
let left = pixel(&sampled, 4, 64);
let right = pixel(&sampled, 124, 64);
assert!(left[0] > 200 && left[2] < 60, "left end {left:?}");
assert!(right[2] > 200 && right[0] < 60, "right end {right:?}");
}
#[gtest]
fn a_mask_blur_softens_a_shape_and_matches_a_blurred_layer() {
let Some(mut ctx) = context() else { return };
let sigma = 6.0;
let shape = Rect::new(40.0, 40.0, 88.0, 88.0);
let color = Color::linear(1.0, 0.4, 0.1, 1.0);
let mut masked = Canvas::new(SIZE);
masked.clear(Color::BLACK);
masked
.draw_path(
&concave_path(shape),
&Paint::fill(color).with_mask_blur(sigma),
)
.expect("mask blur");
let masked = render(&mut ctx, masked);
let mut layered = Canvas::new(SIZE);
layered.clear(Color::BLACK);
let reach = ((sigma - 0.5) * 1.7320508).max(0.0).ceil();
layered.save_layer_bounds(
Layer::opacity(1.0).with_blur(sigma),
Rect::new(
shape.left - reach,
shape.top - reach,
shape.right + reach,
shape.bottom + reach,
),
);
layered
.draw_path(&concave_path(shape), &Paint::fill(color))
.expect("shape");
layered.restore();
let layered = render(&mut ctx, layered);
let worst = masked
.iter()
.zip(&layered)
.map(|(a, b)| (*a as i32 - *b as i32).abs())
.max()
.unwrap_or(0);
expect_that!(
worst,
le(1),
"a mask blur and a blurred layer of the same shape differ by {worst}"
);
let edge = pixel(&masked, 88, 64);
expect_true!(
edge[0] > 8 && edge[0] < 247,
"the edge is not soft: {edge:?}"
);
let mut sharp = Canvas::new(SIZE);
sharp.clear(Color::BLACK);
sharp
.draw_rect(shape, &Paint::fill(color).with_anti_alias(false))
.expect("sharp");
let sharp = render(&mut ctx, sharp);
let (beyond, control) = (pixel(&masked, 94, 64), pixel(&sharp, 94, 64));
expect_that!(
control[0],
eq(0),
"the control should not reach here at all"
);
expect_true!(
beyond[0] > control[0],
"nothing reached past the shape: {beyond:?} against {control:?}"
);
}
#[gtest]
fn a_mask_blur_takes_a_gradient_in_every_style_but_not_over_a_glyph_run() {
let Some(mut ctx) = context() else { return };
let _ = &mut ctx;
let gradient = || {
Paint::linear_gradient(
Vec2::ZERO,
Vec2::new(128.0, 0.0),
vec![
GradientStop::new(Color::WHITE, 0.0),
GradientStop::new(Color::BLACK, 1.0),
],
)
.with_mask_blur(4.0)
};
let square = Rect::new(16.0, 16.0, 112.0, 112.0);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
expect_true!(
canvas.draw_rect(square, &gradient()).is_ok(),
"a mask blur over a gradient states the mask blurred and the paint \
applied through it, which is defined for any fill"
);
expect_true!(
canvas
.draw_rect(square, &Paint::fill(Color::WHITE).with_mask_blur(4.0))
.is_ok(),
"a solid mask blur should be accepted"
);
for style in [
MaskBlurStyle::Solid,
MaskBlurStyle::Outer,
MaskBlurStyle::Inner,
] {
expect_true!(
canvas
.draw_rect(square, &gradient().with_mask_blur_style(style))
.is_ok(),
"{style:?} over a gradient should be drawn, not refused"
);
}
let (atlas, solid, _) = two_glyph_atlas();
expect_true!(
canvas
.draw_glyphs(
&[PositionedGlyph::new(
solid,
[32.0, 80.0],
atlas.get(solid).unwrap()
)],
&atlas,
0,
&gradient(),
)
.is_err(),
"a gradient over a glyph run should be refused, blurred or not"
);
}
#[test]
fn a_group_can_be_filtered_by_a_composition_in_either_order() {
let Some(mut ctx) = context() else { return };
let content = |canvas: &mut Canvas| {
for rect in [
Rect::new(30.0, 48.0, 60.0, 80.0),
Rect::new(68.0, 48.0, 98.0, 80.0),
] {
canvas
.draw_rect(
rect,
&Paint::fill(Color::srgb(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_blend(BlendMode::SrcOver),
)
.expect("rect");
}
};
let shot = |ctx: &mut Context, filter: Option<ImageFilter>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
match filter {
Some(filter) => {
canvas
.save_layer_filtered(Layer::opacity(1.0), None, &filter)
.expect("filtered group");
}
None => {
canvas.save_layer(Layer::opacity(1.0));
}
}
content(&mut canvas);
canvas.restore();
render(ctx, canvas)
};
let dilate = || ImageFilter::Dilate {
radius_x: 6.0,
radius_y: 6.0,
};
let erode = || ImageFilter::Erode {
radius_x: 6.0,
radius_y: 6.0,
};
let closed = shot(&mut ctx, Some(ImageFilter::compose(erode(), dilate())));
let opened = shot(&mut ctx, Some(ImageFilter::compose(dilate(), erode())));
let difference = closed
.chunks_exact(4)
.zip(opened.chunks_exact(4))
.filter(|(a, b)| a != b)
.count();
assert!(
difference > 200,
"the two orders of one composition gave nearly the same picture, so the \
order was not carried: {difference} pixels differ"
);
let plain = shot(&mut ctx, None);
let worst = |a: &[u8], b: &[u8]| -> u8 {
a.iter()
.zip(b.iter())
.map(|(x, y)| x.abs_diff(*y))
.max()
.unwrap_or(0)
};
let bridged = plain
.chunks_exact(4)
.zip(closed.chunks_exact(4))
.filter(|(a, b)| worst(a, b) >= 128)
.count();
assert!(
bridged >= 200,
"closing should have bridged the gap between the rectangles, which is \
about two hundred and fifty pixels going from background to shape: \
{bridged} pixels changed by half or more"
);
let slack = worst(&plain, &opened);
assert!(
slack <= 16,
"opening a pair of rectangles by a rectangle returns them unchanged, so \
this order should give the group back as it was, up to where the \
resampling lands: worst channel differs by {slack}"
);
let between = |p: &[u8]| pixel(p, 64, 64)[0];
assert_eq!(between(&plain), 0, "the gap should be open to begin with");
assert!(between(&closed) > 200, "closing should have filled the gap");
let mut canvas = Canvas::new(SIZE);
let outcome = canvas
.save_layer_filtered(
Layer::opacity(1.0),
None,
&ImageFilter::Matrix {
transform: Transform2D::from(Affine2::from_translation(Vec2::new(8.0, 0.0))),
},
)
.map(|_| ());
assert!(
matches!(outcome, Err(Error::Unsupported(_))),
"a matrix should point the caller at `Layer::with_matrix`, got {outcome:?}"
);
}
#[test]
fn a_clipped_backdrop_a_matrix_moves_fills_from_outside_the_clip() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 16.0, 128.0),
&Paint::fill(Color::BLACK).with_anti_alias(false),
)
.expect("stripe");
canvas.save();
canvas
.clip_rect(Rect::new(32.0, 32.0, 96.0, 96.0))
.expect("the clip");
canvas
.save_layer_backdrop(
Layer::opacity(1.0),
None,
&ImageFilter::Matrix {
transform: Transform2D::from(Affine2::from_translation(Vec2::new(40.0, 0.0))),
},
)
.expect("moved backdrop");
canvas.restore();
canvas.restore();
let moved = render(&mut ctx, canvas);
assert_eq!(
pixel(&moved, 48, 64),
[0, 0, 0, 255],
"the stripe, moved forty pixels right from outside the clip"
);
assert_eq!(
pixel(&moved, 64, 64),
[255, 255, 255, 255],
"and white past it"
);
assert_eq!(
pixel(&moved, 8, 64),
[0, 0, 0, 255],
"outside the clip the stripe is where it was"
);
}
#[test]
fn a_backdrop_takes_any_image_filter_including_the_one_that_moves_it() {
let Some(mut ctx) = context() else { return };
let ground = |canvas: &mut Canvas| {
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(64.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::srgb(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("ground");
};
let shot = |ctx: &mut Context, backdrop: Option<ImageFilter>| {
let mut canvas = Canvas::new(SIZE);
ground(&mut canvas);
if let Some(filter) = backdrop {
canvas
.save_layer_backdrop(Layer::opacity(1.0), None, &filter)
.expect("backdrop");
canvas.restore();
}
render(ctx, canvas)
};
let plain = shot(&mut ctx, None);
assert_eq!(
pixel(&plain, 96, 64),
[255, 255, 255, 255],
"the right half"
);
assert_eq!(pixel(&plain, 32, 64), [0, 0, 0, 255], "the left half");
let inverted = shot(
&mut ctx,
Some(ImageFilter::Color(ColorFilter::matrix([
-1.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
]))),
);
assert_eq!(
pixel(&inverted, 96, 64),
[0, 0, 0, 255],
"the white half should have come back black"
);
assert_eq!(
pixel(&inverted, 32, 64),
[255, 255, 255, 255],
"the black half should have come back white"
);
let spread = shot(
&mut ctx,
Some(ImageFilter::Dilate {
radius_x: 12.0,
radius_y: 0.0,
}),
);
assert_eq!(
pixel(&spread, 56, 64),
[255, 255, 255, 255],
"the dilation should have carried the edge left of where it was"
);
let moved = shot(
&mut ctx,
Some(ImageFilter::Matrix {
transform: Transform2D::from(Affine2::from_translation(Vec2::new(16.0, 0.0))),
}),
);
assert_eq!(
pixel(&moved, 72, 64),
[0, 0, 0, 255],
"the edge should have moved right, leaving black where white was"
);
assert_eq!(
pixel(&moved, 88, 64),
[255, 255, 255, 255],
"and white should be where the edge moved to"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas
.draw_rect(
Rect::new(112.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::BLACK).with_anti_alias(false),
)
.expect("stripe");
canvas
.save_layer_backdrop(
Layer::opacity(1.0),
None,
&ImageFilter::Matrix {
transform: Transform2D::from(Affine2::from_scale(Vec2::splat(0.5))),
},
)
.expect("halved backdrop");
canvas.restore();
let halved = render(&mut ctx, canvas);
assert_eq!(
pixel(&halved, 100, 64),
[255, 255, 255, 255],
"past the halved image the target should show through, not the edge \
texel smeared across it"
);
assert_eq!(pixel(&halved, 60, 32), [0, 0, 0, 255], "the halved stripe");
let mut canvas = Canvas::new(SIZE);
ground(&mut canvas);
let outcome = canvas
.save_layer_backdrop(
Layer::opacity(1.0),
None,
&ImageFilter::Matrix {
transform: Transform2D::from(Affine2::from_scale(Vec2::new(1.0, 0.0))),
},
)
.map(|_| ());
assert!(
matches!(outcome, Err(Error::Unsupported(_))),
"a singular matrix backdrop should be refused, got {outcome:?}"
);
}
#[test]
fn a_stencil_clip_survives_the_pass_a_backdrop_filter_cuts() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, sigma: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.clip_out_rect(Rect::new(96.0, 96.0, 128.0, 128.0))
.expect("clip out");
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::srgb(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("red");
canvas.save_layer(Layer::opacity(1.0).with_backdrop_blur(sigma));
canvas.restore();
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::srgb(0.0, 1.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("green");
render(ctx, canvas)
};
let uncut = shot(&mut ctx, 0.0);
assert_eq!(pixel(&uncut, 32, 32), [0, 255, 0, 255], "green over red");
assert_eq!(
pixel(&uncut, 112, 112),
[0, 0, 0, 255],
"the corner removed"
);
let cut = shot(&mut ctx, 8.0);
assert_eq!(
pixel(&cut, 32, 32),
[0, 255, 0, 255],
"the draw after the backdrop should still land, so the clip has to have \
been made again in the pass the backdrop cut"
);
assert_eq!(
pixel(&cut, 112, 112),
[0, 0, 0, 255],
"and it should still be the same clip -- rebuilt too wide would let the \
green into the corner"
);
}
#[test]
fn a_backdrop_blur_softens_what_is_behind_the_layer_and_nothing_else() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, sigma: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(64.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("edge");
canvas.save_layer_bounds(
Layer::opacity(1.0).with_backdrop_blur(sigma),
Rect::new(0.0, 48.0, 128.0, 80.0),
);
canvas.restore();
render(ctx, canvas)
};
let plain = draw(&mut ctx, 0.0);
let frosted = draw(&mut ctx, 6.0);
let hard = |pixels: &[u8], y: u32| {
(56u32..72)
.map(|x| pixel(pixels, x, y))
.filter(|p| p[0] > 8 && p[0] < 247)
.count()
};
assert_eq!(hard(&plain, 64), 0, "the control edge is not hard");
let soft = hard(&frosted, 64);
assert!(
soft >= 8,
"the backdrop was not blurred: {soft} intermediate columns at the edge"
);
assert_eq!(
hard(&frosted, 16),
0,
"the backdrop blur reached above the layer"
);
assert_eq!(
hard(&frosted, 112),
0,
"the backdrop blur reached below the layer"
);
assert!(
pixel(&frosted, 4, 64)[0] < 8,
"the left of the panel is not black"
);
assert!(
pixel(&frosted, 124, 64)[0] > 247,
"the right of the panel is not white"
);
}
#[test]
fn a_tint_recolors_an_image_and_keeps_it_premultiplied() {
let Some(mut ctx) = context() else { return };
let size = Extent2D::new(2, 1);
let mut icon = vec![0u8; 2 * 4];
icon[0..4].copy_from_slice(&[255, 255, 255, 255]);
icon[4..8].copy_from_slice(&[128, 128, 128, 128]);
let mut image = ctx
.create_image(size, PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &icon).expect("upload");
let draw = |ctx: &mut Context, image: &_, tint: Color, texel: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_source_pixels(Rect::new(texel, 0.0, texel + 1.0, 1.0), size)
.with_tint(tint)
.with_anti_alias(false),
)
.expect("icon");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixel(&pixels, 64, 64)
};
let plain = draw(&mut ctx, &image, Color::WHITE, 0.0);
assert_eq!(
plain,
[255, 255, 255, 255],
"a white tint changed the image"
);
let red = draw(&mut ctx, &image, Color::linear(1.0, 0.0, 0.0, 1.0), 0.0);
assert_eq!(red, [255, 0, 0, 255], "an opaque texel tinted red");
let edge = draw(&mut ctx, &image, Color::linear(1.0, 0.0, 0.0, 1.0), 1.0);
assert!(
edge[0].abs_diff(128) <= 2 && edge[3].abs_diff(128) <= 2,
"a tinted half-covered texel came back {edge:?}"
);
assert!(
edge[0] <= edge[3] + 1,
"the tint left color above alpha, so the result is not premultiplied: {edge:?}"
);
let faded = draw(&mut ctx, &image, Color::linear(1.0, 0.0, 0.0, 0.5), 0.0);
assert!(
faded[0].abs_diff(128) <= 2 && faded[3].abs_diff(128) <= 2,
"a half-alpha tint came back {faded:?}"
);
ctx.destroy_image(image);
}
#[test]
fn a_sprite_can_be_drawn_from_a_sheet_by_naming_its_texels() {
let Some(mut ctx) = context() else { return };
let size = Extent2D::new(4, 4);
let color_of =
|x: usize, y: usize| -> [u8; 4] { [(x * 60 + 15) as u8, (y * 60 + 15) as u8, 200, 255] };
let mut sheet = vec![0u8; 4 * 4 * 4];
for y in 0..4usize {
for x in 0..4usize {
let at = (y * 4 + x) * 4;
sheet[at..at + 4].copy_from_slice(&color_of(x, y));
}
}
let mut image = ctx
.create_image(size, PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &sheet).expect("upload");
let draw = |ctx: &mut Context, image: &_, source: Rect| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_source_pixels(source, size)
.with_anti_alias(false),
)
.expect("sprite");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
for (x, y) in [(0usize, 0usize), (1, 0), (3, 1), (2, 3)] {
let source = Rect::new(x as f32, y as f32, x as f32 + 1.0, y as f32 + 1.0);
let pixels = draw(&mut ctx, &image, source);
let want = color_of(x, y);
for (px, py) in [(64u32, 64u32), (2, 2), (125, 2), (2, 125), (125, 125)] {
let got = pixel(&pixels, px, py);
assert_eq!(
[got[0], got[1]],
[want[0], want[1]],
"texel ({x}, {y}) came back {got:?} at ({px}, {py}), wanted {want:?}"
);
}
}
let pixels = draw(&mut ctx, &image, Rect::new(0.0, 0.0, 2.0, 1.0));
let first = color_of(0, 0);
let at_first_center = pixel(&pixels, 32, 64);
assert_eq!(
[at_first_center[0], at_first_center[1]],
[first[0], first[1]],
"a two-texel selection is not being stretched across the destination"
);
let second = color_of(1, 0);
let at_second_center = pixel(&pixels, 96, 64);
assert_eq!(
[at_second_center[0], at_second_center[1]],
[second[0], second[1]],
"the second texel of the selection is not where it belongs"
);
ctx.destroy_image(image);
}
#[test]
fn an_arc_leaves_the_part_of_the_circle_it_does_not_sweep() {
let Some(mut ctx) = context() else { return };
let mut builder = PathBuilder::new();
builder.arc(
Vec2::new(64.0, 64.0),
Vec2::splat(40.0),
-std::f32::consts::FRAC_PI_2,
std::f32::consts::TAU * 0.75,
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_path(
&builder.build(),
&Paint::stroke(Color::WHITE, 8.0).with_anti_alias(false),
)
.expect("arc");
let pixels = render(&mut ctx, canvas);
for (name, x, y) in [
("twelve", 64, 24),
("three", 104, 64),
("six", 64, 104),
("nine", 24, 64),
] {
assert!(
pixel(&pixels, x, y)[0] > 200,
"{name} o'clock should be on the arc"
);
}
assert_eq!(
pixel(&pixels, 36, 36),
[0, 0, 0, 255],
"the unswept quarter was drawn"
);
assert_eq!(pixel(&pixels, 64, 64), [0, 0, 0, 255], "the ring is filled");
}
#[test]
fn a_dashed_stroke_draws_less_than_a_solid_one_and_leaves_real_gaps() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, dash: Option<Dash>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_line(
Vec2::new(0.0, 64.0),
Vec2::new(128.0, 64.0),
&Paint::stroke(Color::WHITE, 8.0)
.with_dash(dash)
.with_anti_alias(false),
)
.expect("line");
render(ctx, canvas)
};
let lit = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.filter(|texel| texel[0] > 128)
.count()
};
let solid = draw(&mut ctx, None);
let dashed = draw(&mut ctx, Some(Dash::new(vec![16.0, 16.0], 0.0)));
let (whole, cut) = (lit(&solid), lit(&dashed));
assert!(whole > 0, "the solid line drew nothing to compare against");
let ratio = cut as f32 / whole as f32;
assert!(
(0.4..0.6).contains(&ratio),
"a half-on pattern drew {ratio} of the line"
);
assert_eq!(
pixel(&dashed, 24, 64),
[0, 0, 0, 255],
"the first gap is not empty"
);
assert!(pixel(&dashed, 8, 64)[0] > 200, "the first dash is missing");
let shifted = draw(&mut ctx, Some(Dash::new(vec![16.0, 16.0], 16.0)));
assert!(
pixel(&shifted, 24, 64)[0] > 200,
"a phase of one interval should put a dash where the gap was"
);
assert_eq!(
pixel(&shifted, 8, 64),
[0, 0, 0, 255],
"and a gap where the dash was"
);
}
#[test]
fn a_dashed_rounded_rectangle_dashes_rather_than_drawing_solid() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, dash: Option<Dash>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect(
Rect::new(16.0, 16.0, 112.0, 112.0),
16.0,
&Paint::stroke(Color::WHITE, 6.0).with_dash(dash),
)
.expect("rrect");
render(ctx, canvas)
};
let lit = |pixels: &[u8]| {
pixels
.chunks_exact(4)
.filter(|texel| texel[0] > 128)
.count()
};
let solid = lit(&draw(&mut ctx, None));
let dashed = lit(&draw(&mut ctx, Some(Dash::new(vec![10.0, 10.0], 0.0))));
assert!(solid > 0, "the solid outline drew nothing");
let ratio = dashed as f32 / solid as f32;
assert!(
(0.35..0.65).contains(&ratio),
"the dashed outline drew {ratio} of the solid one, so the pattern was ignored"
);
}
#[test]
fn a_tiled_gradient_tiles_the_same_whether_or_not_its_stops_fit() {
let Some(mut ctx) = context() else { return };
let ramp_stops = |n: usize| -> Vec<GradientStop> {
(0..n)
.map(|i| {
let t = i as f32 / (n - 1) as f32;
GradientStop::new(Color::srgb(1.0 - t, 0.0, t, 1.0), t)
})
.collect()
};
let render_with = |ctx: &mut Context, stops: Vec<GradientStop>, tile: TileMode| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("ground");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(Vec2::ZERO, Vec2::new(32.0, 0.0), stops)
.with_tile_mode(tile)
.with_blend(BlendMode::SrcOver)
.with_anti_alias(false),
)
.expect("gradient");
render(ctx, canvas)
};
for tile in [
TileMode::Clamp,
TileMode::Repeat,
TileMode::Mirror,
TileMode::Decal,
] {
let walked = render_with(&mut ctx, ramp_stops(MAX_STOPS), tile);
let sampled = render_with(&mut ctx, ramp_stops(MAX_STOPS + 3), tile);
let mut worst = 0i32;
for x in 0..128u32 {
let a = pixel(&walked, x, 64);
let b = pixel(&sampled, x, 64);
for channel in 0..4 {
worst = worst.max((a[channel] as i32 - b[channel] as i32).abs());
}
}
assert!(
worst <= 2,
"{tile:?}: the two paths disagree by {worst}, which is more than rounding"
);
}
let repeated = render_with(&mut ctx, ramp_stops(MAX_STOPS + 3), TileMode::Repeat);
let clamped = render_with(&mut ctx, ramp_stops(MAX_STOPS + 3), TileMode::Clamp);
let at = pixel(&repeated, 64, 64);
assert!(
at[0] > 200 && at[2] < 60,
"a repeating ramp did not begin again, got {at:?}"
);
let held = pixel(&clamped, 64, 64);
assert!(
held[2] > 200 && held[0] < 60,
"a clamped ramp did not hold its end, got {held:?}"
);
}
#[test]
fn a_gradient_with_many_stops_places_each_one_where_it_was_asked_for() {
let Some(mut ctx) = context() else { return };
let stops = vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(1.0, 1.0, 0.0, 1.0), 0.2),
GradientStop::new(Color::linear(0.0, 1.0, 0.0, 1.0), 0.4),
GradientStop::new(Color::linear(0.0, 1.0, 1.0, 1.0), 0.6),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 0.8),
GradientStop::new(Color::linear(1.0, 0.0, 1.0, 1.0), 1.0),
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), stops)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
for (name, x, want) in [
("red", 0u32, [255u8, 0, 0]),
("yellow", 25, [255, 255, 0]),
("green", 51, [0, 255, 0]),
("cyan", 77, [0, 255, 255]),
("blue", 102, [0, 0, 255]),
("magenta", 127, [255, 0, 255]),
] {
let got = pixel(&pixels, x, 64);
for channel in 0..3 {
assert!(
(got[channel] as i32 - want[channel] as i32).abs() <= 12,
"the {name} stop came back {got:?}, wanted about {want:?}"
);
}
}
}
#[test]
fn a_gradient_tiles_beyond_its_own_extent() {
let Some(mut ctx) = context() else { return };
let inside = 16;
let modes = [TileMode::Clamp, TileMode::Repeat, TileMode::Decal];
let images: Vec<Vec<u8>> = modes.iter().map(|t| tiled_ramp(&mut ctx, *t)).collect();
for image in &images[1..] {
for channel in 0..4 {
assert!(
(images[0][(inside * 4 + channel) as usize] as i32
- image[(inside * 4 + channel) as usize] as i32)
.abs()
<= 2,
"the modes disagree inside the ramp, where they should not"
);
}
}
let clamped = pixel(&images[0], 100, 64);
assert!(
clamped[2] > 240 && clamped[0] < 16,
"clamp should hold the end color, got {clamped:?}"
);
let repeated = pixel(&images[1], 64, 64);
assert!(
repeated[0] > 240 && repeated[2] < 16,
"repeat should begin the ramp again, got {repeated:?}"
);
let next_period = pixel(&images[1], 96, 64);
for channel in 0..4 {
assert!(
(repeated[channel] as i32 - next_period[channel] as i32).abs() <= 2,
"repeat is not periodic: {repeated:?} against {next_period:?}"
);
}
let decaled = pixel(&images[2], 100, 64);
assert!(
decaled.iter().take(3).all(|c| *c > 240),
"decal should leave the ground alone, got {decaled:?}"
);
}
#[test]
fn mirroring_repeats_without_the_seam_that_repeating_leaves() {
let Some(mut ctx) = context() else { return };
let repeated = tiled_ramp(&mut ctx, TileMode::Repeat);
let mirrored = tiled_ramp(&mut ctx, TileMode::Mirror);
let jump = |image: &[u8]| {
let before = pixel(image, 30, 64);
let after = pixel(image, 34, 64);
(0..3)
.map(|c| (before[c] as i32 - after[c] as i32).abs())
.max()
.unwrap_or(0)
};
let seam = jump(&repeated);
assert!(
seam > 200,
"repeating should jump at the period boundary, but moved only {seam}"
);
let joined = jump(&mirrored);
assert!(
joined < 40,
"mirroring should join at the period boundary, but jumped {joined}"
);
let before = pixel(&mirrored, 24, 64);
let after = pixel(&mirrored, 39, 64);
for channel in 0..3 {
assert!(
(before[channel] as i32 - after[channel] as i32).abs() <= 6,
"the second copy should mirror the first: {before:?} against {after:?}"
);
}
}
#[test]
fn a_partial_sweep_holds_its_end_color_around_the_rest_of_the_turn() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::sweep_gradient(
Vec2::new(64.0, 64.0),
0.0,
std::f32::consts::PI,
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("sweep");
let pixels = render(&mut ctx, canvas);
let start = pixel(&pixels, 64 + 40, 64);
assert!(
start[0] > 240 && start[2] < 16,
"the arc should begin at the first stop, got {start:?}"
);
let middle = pixel(&pixels, 64, 64 + 40);
assert!(
middle[0] > 100 && middle[0] < 160 && middle[2] > 100 && middle[2] < 160,
"half way round the arc should be half way along the ramp, got {middle:?}"
);
let outside = pixel(&pixels, 64, 64 - 40);
assert!(
outside[2] > 240 && outside[0] < 16,
"outside the arc should hold the end color, got {outside:?}"
);
}
#[test]
fn a_sweep_gradient_runs_around_its_center() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::sweep_gradient(
Vec2::new(64.0, 64.0),
0.0,
std::f32::consts::TAU,
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("sweep");
let pixels = render(&mut ctx, canvas);
let near = pixel(&pixels, 64 + 12, 64);
let far = pixel(&pixels, 64 + 48, 64);
for channel in 0..4 {
assert!(
(near[channel] as i32 - far[channel] as i32).abs() <= 2,
"a sweep should not vary with distance: near {near:?}, far {far:?}"
);
}
let above = pixel(&pixels, 64, 64 - 40);
assert_ne!(near, above, "a sweep should vary with angle");
}
#[test]
fn an_advanced_blend_mode_is_either_available_or_refused_through_the_api() {
let Some(mut ctx) = context() else { return };
let available = ctx.capabilities().advanced_blend;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.6, 0.6, 0.6, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(0.5, 0.5, 0.5, 1.0))
.with_blend(BlendMode::Multiply)
.with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
let drawn = ctx.draw(&mut surface, &canvas.finish());
if available {
drawn.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
let got = pixel(&pixels, 64, 64);
let backdrop = pixel(
&render(&mut ctx, {
let mut plain = Canvas::new(SIZE);
plain.clear(Color::linear(0.6, 0.6, 0.6, 1.0));
plain
}),
64,
64,
);
assert!(
got[0] < backdrop[0],
"multiply gave {got:?}, which is not darker than the backdrop {backdrop:?}"
);
} else {
assert!(
matches!(drawn, Err(emblema::Error::Unsupported(_))),
"the device reports no advanced blending but the draw was not refused"
);
}
ctx.destroy_surface(surface);
}
#[test]
fn a_clip_confines_drawing_to_a_rectangle() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.clip_rect(Rect::new(20.0, 10.0, 60.0, 40.0))
.expect("clip");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(30, 20), "the middle of the clip was not drawn");
assert!(
lit(21, 11),
"the top-left corner inside the clip was not drawn"
);
assert!(
lit(59, 39),
"the bottom-right corner inside the clip was not drawn"
);
for (x, y, where_) in [
(19, 20, "left of the clip"),
(60, 20, "right of the clip"),
(30, 9, "above the clip"),
(30, 40, "below the clip"),
(100, 100, "far outside the clip"),
] {
assert!(!lit(x, y), "{where_} was drawn anyway");
}
}
#[test]
fn clips_intersect_rather_than_replacing_one_another() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.clip_rect(Rect::new(10.0, 10.0, 70.0, 50.0)).unwrap();
canvas
.clip_rect(Rect::new(40.0, 30.0, 100.0, 90.0))
.unwrap();
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(50, 40), "the shared region was not drawn");
assert!(
!lit(20, 20),
"a region only the first clip allowed was drawn"
);
assert!(
!lit(80, 70),
"a region only the second clip allowed was drawn"
);
}
#[test]
fn restore_returns_the_clip_along_with_the_transform() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
canvas.clip_rect(Rect::new(0.0, 0.0, 20.0, 20.0)).unwrap();
canvas.restore();
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
assert!(
pixel(&pixels, 100, 100)[0] > 128,
"a clip outlived the save that scoped it"
);
}
#[test]
fn a_clip_moves_with_the_transform_that_was_in_force_when_it_was_set() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.translate(64.0, 64.0);
canvas.clip_rect(Rect::new(0.0, 0.0, 40.0, 40.0)).unwrap();
canvas
.draw_rect(
Rect::new(-128.0, -128.0, 128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(70, 70), "the clip did not travel with the transform");
assert!(!lit(20, 20), "the clip stayed at the device origin");
assert!(!lit(110, 110), "the clip extended past where it was placed");
}
#[test]
fn a_rotated_clip_is_the_rotated_shape_and_not_its_bounding_box() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.translate(64.0, 64.0);
canvas.rotate(std::f32::consts::FRAC_PI_4);
canvas
.clip_rect(Rect::new(-30.0, -30.0, 30.0, 30.0))
.expect("clip");
canvas
.draw_rect(
Rect::new(-128.0, -128.0, 128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(64, 64), "the middle of the clip was not drawn");
assert!(lit(64, 90), "a point inside the diamond was not drawn");
assert!(
!lit(100, 100),
"the clip reached a corner only its bounding box covers"
);
assert!(!lit(10, 64), "the clip reached outside its bounding box");
}
#[test]
fn a_clip_narrowed_to_nothing_draws_nothing() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::srgb(0.2, 0.4, 0.6, 1.0));
canvas.clip_rect(Rect::new(0.0, 0.0, 20.0, 20.0)).unwrap();
canvas.clip_rect(Rect::new(60.0, 60.0, 80.0, 80.0)).unwrap();
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)),
)
.expect("rect");
let recording = canvas.finish();
assert!(
recording.is_empty(),
"a draw that could reach no pixel was still recorded"
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
assert_eq!(pixel(&pixels, 64, 64), [51, 102, 153, 255]);
}
#[test]
fn a_path_clip_confines_drawing_to_the_path() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let mut builder = PathBuilder::new();
builder
.move_to(Vec2::new(64.0, 16.0))
.line_to(Vec2::new(112.0, 100.0))
.line_to(Vec2::new(16.0, 100.0))
.close();
canvas.clip_path(&builder.build()).expect("clip");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(64, 80), "the middle of the triangle was not drawn");
assert!(lit(64, 30), "near the apex was not drawn");
for (x, y, corner) in [(20, 20, "top-left"), (108, 20, "top-right")] {
assert!(
!lit(x, y),
"the {corner} corner outside the triangle was drawn"
);
}
assert!(!lit(64, 110), "below the triangle was drawn");
}
#[test]
fn a_path_clip_intersects_with_a_rectangular_one() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.clip_rect(Rect::new(0.0, 0.0, 64.0, 128.0))
.expect("rect clip");
let mut builder = PathBuilder::new();
builder
.move_to(Vec2::new(64.0, 16.0))
.line_to(Vec2::new(112.0, 100.0))
.line_to(Vec2::new(16.0, 100.0))
.close();
canvas.clip_path(&builder.build()).expect("path clip");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = |x, y| pixel(&pixels, x, y)[0] > 128;
assert!(lit(50, 80), "the region both clips admit was not drawn");
assert!(
!lit(80, 80),
"a region inside the triangle but outside the rectangle was drawn"
);
assert!(
!lit(30, 30),
"a region inside the rectangle but outside the triangle was drawn"
);
}
#[test]
fn restore_undoes_a_path_clip() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
let mut builder = PathBuilder::new();
builder
.move_to(Vec2::new(64.0, 16.0))
.line_to(Vec2::new(112.0, 100.0))
.line_to(Vec2::new(16.0, 100.0))
.close();
canvas.clip_path(&builder.build()).expect("clip");
canvas.restore();
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
for (x, y) in [(4, 4), (124, 4), (4, 124), (124, 124), (64, 64)] {
assert!(
pixel(&pixels, x, y)[0] > 128,
"({x}, {y}) was still confined by a clip that had been restored"
);
}
}
#[test]
fn nested_path_clips_intersect_and_unwind_one_level_at_a_time() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let triangle = |apex_left: bool| {
let mut builder = PathBuilder::new();
if apex_left {
builder
.move_to(Vec2::new(16.0, 64.0))
.line_to(Vec2::new(100.0, 16.0))
.line_to(Vec2::new(100.0, 112.0))
.close();
} else {
builder
.move_to(Vec2::new(112.0, 64.0))
.line_to(Vec2::new(28.0, 16.0))
.line_to(Vec2::new(28.0, 112.0))
.close();
}
builder.build()
};
canvas.save();
canvas.clip_path(&triangle(true)).expect("outer");
canvas.save();
canvas.clip_path(&triangle(false)).expect("inner");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let both = render(&mut ctx, canvas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
canvas.clip_path(&triangle(true)).expect("outer");
canvas.save();
canvas.clip_path(&triangle(false)).expect("inner");
canvas.restore();
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let outer_only = render(&mut ctx, canvas);
let lit = |p: &[u8], x, y| pixel(p, x, y)[0] > 128;
assert!(!lit(&both, 22, 64), "the two clips did not intersect");
assert!(
lit(&outer_only, 22, 64),
"restoring did not lift the inner clip"
);
assert!(
!lit(&outer_only, 8, 64),
"restoring lifted the outer clip as well"
);
}
fn quadrant_image() -> Vec<u8> {
let mut pixels = vec![0u8; 4 * 4 * 4];
for y in 0..4u32 {
for x in 0..4u32 {
let i = ((y * 4 + x) * 4) as usize;
let color: [u8; 4] = match (x < 2, y < 2) {
(true, true) => [255, 0, 0, 255],
(false, true) => [0, 255, 0, 255],
(true, false) => [0, 0, 255, 255],
(false, false) => [255, 255, 0, 255],
};
pixels[i..i + 4].copy_from_slice(&color);
}
}
pixels
}
#[test]
fn an_image_paint_draws_a_texture_through_the_api() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0)).with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
for (x, y, want, corner) in [
(16u32, 16u32, [255u8, 0, 0, 255], "top-left"),
(112, 16, [0, 255, 0, 255], "top-right"),
(16, 112, [0, 0, 255, 255], "bottom-left"),
(112, 112, [255, 255, 0, 255], "bottom-right"),
] {
assert_eq!(
pixel(&pixels, x, y),
want,
"the {corner} quadrant sampled the wrong part of the image"
);
}
}
#[test]
fn an_image_travels_with_the_canvas_transform() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.translate(64.0, 64.0);
canvas.rotate(std::f32::consts::PI);
canvas
.draw_rect(
Rect::new(-64.0, -64.0, 64.0, 64.0),
&Paint::image(0, Rect::new(-64.0, -64.0, 64.0, 64.0)).with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(pixel(&pixels, 112, 112), [255, 0, 0, 255]);
assert_eq!(pixel(&pixels, 16, 16), [255, 255, 0, 255]);
}
#[test]
fn drawing_an_image_paint_without_the_image_is_refused() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.expect("rect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
let result = ctx.draw(&mut surface, &canvas.finish());
ctx.destroy_surface(surface);
assert!(result.is_err(), "a paint sampling slot 0 drew without it");
}
fn overlapping_circles(canvas: &mut Canvas, alpha: f32) {
for center in [Vec2::new(52.0, 64.0), Vec2::new(76.0, 64.0)] {
canvas
.draw_circle(
center,
28.0,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, alpha)).with_anti_alias(false),
)
.expect("circle");
}
}
#[test]
fn a_layer_applies_its_alpha_to_the_group_rather_than_to_each_shape() {
let Some(mut ctx) = context() else { return };
let mut direct = Canvas::new(SIZE);
direct.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
overlapping_circles(&mut direct, 0.5);
let direct = render(&mut ctx, direct);
let mut grouped = Canvas::new(SIZE);
grouped.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
grouped.save_layer(Layer::opacity(0.5));
overlapping_circles(&mut grouped, 1.0);
grouped.restore();
let grouped = render(&mut ctx, grouped);
let outside = (36u32, 64u32);
let (a, b) = (
pixel(&direct, outside.0, outside.1),
pixel(&grouped, outside.0, outside.1),
);
for channel in 0..4 {
assert!(
(a[channel] as i32 - b[channel] as i32).abs() <= 1,
"the two differ where only one circle covers: {a:?} against {b:?}"
);
}
let overlap = (64u32, 64u32);
let direct_red = pixel(&direct, overlap.0, overlap.1)[0];
let grouped_red = pixel(&grouped, overlap.0, overlap.1)[0];
assert!(
direct_red > grouped_red + 8,
"the overlap is {direct_red} drawn directly and {grouped_red} through a layer; \
a layer that composited per shape would make these equal"
);
assert_eq!(
pixel(&grouped, overlap.0, overlap.1),
pixel(&grouped, outside.0, outside.1),
"the group was not composited as one image"
);
}
#[test]
fn a_layer_composites_with_its_own_blend_mode() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 1.0, 1.0));
canvas.save_layer(Layer::default().with_blend(BlendMode::Plus));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 64, 64), [255, 0, 255, 255]);
}
#[test]
fn layers_nest() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer(Layer::opacity(0.5));
canvas.save_layer(Layer::opacity(0.5));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
canvas.restore();
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
for (channel, want) in got.iter().take(3).zip([64u8, 64, 64]) {
assert!(
(*channel as i32 - want as i32).abs() <= 2,
"two half-opacity layers gave {got:?}, expected about a quarter"
);
}
}
#[test]
fn a_clip_in_force_when_a_layer_opens_confines_the_result() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.clip_rect(Rect::new(0.0, 0.0, 64.0, 128.0))
.expect("clip");
canvas.save_layer(Layer::default());
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 32, 64),
[255, 255, 255, 255],
"inside the clip"
);
assert_eq!(pixel(&pixels, 96, 64), [0, 0, 0, 255], "outside the clip");
}
#[test]
fn a_clip_inside_a_layer_does_not_escape_it() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer(Layer::default());
canvas
.clip_rect(Rect::new(0.0, 0.0, 64.0, 128.0))
.expect("clip");
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("clipped");
canvas.restore();
canvas
.draw_rect(
Rect::new(64.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.0, 1.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("unclipped");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 32, 64),
[255, 0, 0, 255],
"inside the layer clip"
);
assert_eq!(
pixel(&pixels, 96, 64),
[0, 255, 0, 255],
"the layer's clip outlived the layer"
);
}
#[test]
fn a_recording_without_layers_still_has_exactly_one_pass() {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(Rect::from_size(16.0, 16.0), &Paint::fill(Color::WHITE))
.expect("rect");
let recording = canvas.finish();
assert_eq!(recording.layer_count(), 0);
assert_eq!(recording.passes.len(), 1);
}
#[test]
fn a_layer_left_open_is_composited_rather_than_discarded() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer(Layer::default());
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let recording = canvas.finish();
assert_eq!(recording.layer_count(), 1);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
assert_eq!(pixel(&pixels, 64, 64), [255, 255, 255, 255]);
}
#[test]
fn the_backends_agree_on_a_layered_frame() {
let (Ok(mut vulkan), Ok(mut gles)) = (
Context::new(BackendPreference::Vulkan),
Context::new(BackendPreference::Gles),
) else {
eprintln!("skipping: both backends are needed");
return;
};
let build = || {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.1, 0.1, 0.2, 1.0));
canvas.save_layer(Layer::opacity(0.6));
overlapping_circles(&mut canvas, 1.0);
canvas.save_layer(Layer::opacity(0.5).with_blend(BlendMode::Plus));
canvas
.draw_rect(
Rect::new(20.0, 20.0, 108.0, 60.0),
&Paint::fill(Color::linear(0.0, 0.8, 0.4, 1.0)).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
canvas.restore();
canvas.finish()
};
let a = {
let mut surface = vulkan
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
vulkan.draw(&mut surface, &build()).expect("draw");
let pixels = vulkan.read(&mut surface).expect("read");
vulkan.destroy_surface(surface);
pixels
};
let b = {
let mut surface = gles
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
gles.draw(&mut surface, &build()).expect("draw");
let pixels = gles.read(&mut surface).expect("read");
gles.destroy_surface(surface);
pixels
};
let worst = a
.iter()
.zip(&b)
.map(|(x, y)| (*x as i32 - *y as i32).abs())
.max()
.unwrap_or(0);
assert!(
worst <= 1,
"the backends differ by up to {worst} on a layered frame"
);
assert_ne!(
pixel(&a, 64, 40),
pixel(&a, 4, 124),
"the layered frame drew nothing"
);
}
fn two_glyph_atlas() -> (Atlas, GlyphKey, GlyphKey) {
let mut atlas = Atlas::new(64);
let solid = GlyphKey {
subpixel: 0,
font: 1,
glyph: 1,
size: 16,
};
let half = GlyphKey {
subpixel: 0,
font: 1,
glyph: 2,
size: 16,
};
atlas
.insert(
solid,
&Coverage {
width: 8,
height: 8,
texels: vec![255; 64],
},
)
.expect("solid glyph");
atlas
.insert(
half,
&Coverage {
width: 8,
height: 8,
texels: vec![128; 64],
},
)
.expect("half glyph");
(atlas, solid, half)
}
fn upload_atlas(ctx: &mut Context, atlas: &Atlas) -> emblema::Image {
let mut image = ctx
.create_image(
Extent2D::new(atlas.size(), atlas.size()),
PixelFormat::R8Unorm,
)
.expect("atlas image");
ctx.write_image(&mut image, atlas.texels()).expect("upload");
image
}
#[test]
fn a_glyph_run_draws_its_coverage_tinted_by_the_paint() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, half) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_glyphs(
&[
PositionedGlyph::new(solid, [16.0, 16.0], atlas.get(solid).unwrap()),
PositionedGlyph::new(half, [48.0, 16.0], atlas.get(half).unwrap()),
],
&atlas,
0,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)),
)
.expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(pixel(&pixels, 20, 20), [255, 0, 0, 255], "the solid glyph");
let faint = pixel(&pixels, 52, 20);
assert!(
(faint[0] as i32 - 128).abs() <= 2 && faint[1] == 0 && faint[2] == 0,
"the half-coverage glyph came back {faint:?}"
);
assert_eq!(
pixel(&pixels, 100, 100),
[0, 0, 0, 255],
"between the glyphs"
);
}
#[test]
fn a_run_of_many_glyphs_is_one_draw() {
let (atlas, solid, _) = two_glyph_atlas();
let rect = atlas.get(solid).unwrap();
let glyphs: Vec<PositionedGlyph> = (0..24)
.map(|i| PositionedGlyph::new(solid, [i as f32 * 5.0, 40.0], rect))
.collect();
let mut canvas = Canvas::new(SIZE);
canvas
.draw_glyphs(&glyphs, &atlas, 0, &Paint::fill(Color::WHITE))
.expect("glyphs");
let recording = canvas.finish();
assert_eq!(
recording.draw_count(),
1,
"a run of {} glyphs should be one draw",
glyphs.len()
);
}
#[test]
fn a_glyph_run_travels_with_the_transform_and_the_clip() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, _) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let rect = atlas.get(solid).unwrap();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.clip_rect(Rect::new(0.0, 0.0, 64.0, 128.0))
.expect("clip");
canvas.translate(24.0, 24.0);
canvas
.draw_glyphs(
&[
PositionedGlyph::new(solid, [0.0, 0.0], rect),
PositionedGlyph::new(solid, [56.0, 0.0], rect),
],
&atlas,
0,
&Paint::fill(Color::WHITE),
)
.expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(
pixel(&pixels, 28, 28),
[255, 255, 255, 255],
"the first glyph"
);
assert_eq!(pixel(&pixels, 84, 28), [0, 0, 0, 255], "the second glyph");
}
#[test]
fn a_glyph_missing_from_the_atlas_is_refused() {
let (atlas, solid, _) = two_glyph_atlas();
let absent = GlyphKey {
subpixel: 0,
font: 9,
glyph: 9,
size: 9,
};
let mut canvas = Canvas::new(SIZE);
let result = canvas.draw_glyphs(
&[PositionedGlyph::new(
absent,
[0.0, 0.0],
atlas.get(solid).unwrap(),
)],
&atlas,
0,
&Paint::fill(Color::WHITE),
);
assert!(result.is_err(), "a glyph outside the atlas was accepted");
}
#[test]
fn glyphs_take_a_solid_color_rather_than_a_gradient() {
let (atlas, solid, _) = two_glyph_atlas();
let mut canvas = Canvas::new(SIZE);
let result = canvas.draw_glyphs(
&[PositionedGlyph::new(
solid,
[0.0, 0.0],
atlas.get(solid).unwrap(),
)],
&atlas,
0,
&Paint::linear_gradient(
Vec2::new(0.0, 0.0),
Vec2::new(64.0, 0.0),
vec![
GradientStop::new(Color::WHITE, 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 0.0, 1.0), 1.0),
],
),
);
assert!(result.is_err(), "a gradient paint was accepted for glyphs");
}
#[test]
fn the_backends_agree_on_a_glyph_run() {
let (Ok(mut vulkan), Ok(mut gles)) = (
Context::new(BackendPreference::Vulkan),
Context::new(BackendPreference::Gles),
) else {
eprintln!("skipping: both backends are needed");
return;
};
let (atlas, solid, half) = two_glyph_atlas();
let build = || {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.1, 1.0));
let glyphs: Vec<PositionedGlyph> = (0..6)
.map(|i| {
let key = if i % 2 == 0 { solid } else { half };
PositionedGlyph::new(key, [8.0 + i as f32 * 18.0, 40.0], atlas.get(key).unwrap())
})
.collect();
canvas
.draw_glyphs(
&glyphs,
&atlas,
0,
&Paint::fill(Color::linear(1.0, 0.8, 0.2, 1.0)),
)
.expect("glyphs");
canvas.finish()
};
let render_on = |ctx: &mut Context| {
let image = upload_atlas(ctx, &atlas);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &build(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
};
let a = render_on(&mut vulkan);
let b = render_on(&mut gles);
let worst = a
.iter()
.zip(&b)
.map(|(x, y)| (*x as i32 - *y as i32).abs())
.max()
.unwrap_or(0);
assert!(
worst <= 1,
"the backends differ by up to {worst} on a glyph run"
);
assert_ne!(
pixel(&a, 12, 44),
pixel(&a, 120, 120),
"the glyph run drew nothing"
);
}
#[test]
fn a_glyph_run_is_correct_after_the_atlas_has_grown() {
let Some(mut ctx) = context() else { return };
let marker = GlyphKey {
subpixel: 0,
font: 1,
glyph: 1,
size: 16,
};
let coverage = Coverage {
width: 6,
height: 6,
texels: vec![255; 36],
};
let draw = |ctx: &mut Context, atlas: &Atlas| {
let image = upload_atlas(ctx, atlas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_glyphs(
&[PositionedGlyph::new(
marker,
[40.0, 40.0],
atlas.get(marker).unwrap(),
)],
atlas,
0,
&Paint::fill(Color::WHITE),
)
.expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
};
let mut small = Atlas::new(32);
small.insert(marker, &coverage).expect("marker");
let before = draw(&mut ctx, &small);
let mut grown = Atlas::new(32);
grown.insert(marker, &coverage).expect("marker");
let mut filler = 2u16;
while grown.growths() == 0 {
grown
.insert(
GlyphKey {
subpixel: 0,
font: 1,
glyph: filler,
size: 16,
},
&Coverage {
width: 6,
height: 6,
texels: vec![64; 36],
},
)
.expect("should grow rather than refuse");
filler += 1;
assert!(filler < 400, "the atlas never grew");
}
assert!(grown.size() > small.size(), "the atlas did not get bigger");
assert!(grown.is_dirty(), "a grown atlas owes an upload");
assert_eq!(
grown.compactions(),
0,
"this is about growth, not repacking"
);
let after = draw(&mut ctx, &grown);
let worst = before
.iter()
.zip(&after)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert_eq!(
worst, 0,
"growing the atlas moved or altered the glyph on screen"
);
assert!(
before.iter().any(|&b| b > 128),
"the marker did not render at all"
);
}
#[test]
fn a_glyph_run_is_correct_after_the_atlas_has_been_repacked() {
let Some(mut ctx) = context() else { return };
let mut atlas = Atlas::with_limit(32, 32);
let solid = GlyphKey {
subpixel: 0,
font: 1,
glyph: 1,
size: 16,
};
let marker = Coverage {
width: 6,
height: 6,
texels: vec![255; 36],
};
atlas.insert(solid, &marker).expect("solid");
let mut filler = 2u16;
while atlas
.insert(
GlyphKey {
subpixel: 0,
font: 1,
glyph: filler,
size: 16,
},
&Coverage {
width: 6,
height: 6,
texels: vec![64; 36],
},
)
.is_ok()
{
filler += 1;
assert!(filler < 200, "the atlas never filled");
}
atlas.begin_frame();
atlas.insert(solid, &marker).expect("refresh");
atlas
.insert(
GlyphKey {
subpixel: 0,
font: 1,
glyph: 999,
size: 16,
},
&Coverage {
width: 6,
height: 6,
texels: vec![128; 36],
},
)
.expect("should make room");
assert_eq!(atlas.compactions(), 1, "the atlas did not repack");
assert!(atlas.is_dirty(), "a repacked atlas owes an upload");
let image = upload_atlas(&mut ctx, &atlas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_glyphs(
&[PositionedGlyph::new(
solid,
[40.0, 40.0],
atlas.get(solid).unwrap(),
)],
&atlas,
0,
&Paint::fill(Color::linear(0.0, 1.0, 0.0, 1.0)),
)
.expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(
pixel(&pixels, 42, 42),
[0, 255, 0, 255],
"the repacked glyph sampled the wrong part of the atlas"
);
}
fn bounds_are_invisible(ctx: &mut Context, build: impl Fn(&mut Canvas, Option<Rect>)) {
let record = |bounds: Option<Rect>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
build(&mut canvas, bounds);
canvas.finish()
};
let draw = |ctx: &mut Context, recording: &_| {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let bounded_recording = record(Some(LAYER_BOUNDS));
assert!(
bounded_recording
.passes
.iter()
.any(|p| p.extent.width < SIZE.width || p.extent.height < SIZE.height),
"no pass got a smaller target, so this compares two identical paths"
);
let full = draw(ctx, &record(None));
let bounded = draw(ctx, &bounded_recording);
let worst = full
.iter()
.zip(&bounded)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(
worst <= 2,
"a bounded layer differs from a full-size one by {worst}"
);
assert!(full.iter().any(|&b| b > 32), "the scene rendered nothing");
}
const LAYER_BOUNDS: Rect = Rect {
left: 24.0,
top: 40.0,
right: 96.0,
bottom: 104.0,
};
fn open_layer(canvas: &mut Canvas, bounds: Option<Rect>, layer: Layer) {
match bounds {
Some(b) => canvas.save_layer_bounds(layer, b),
None => canvas.save_layer(layer),
};
}
fn layer_contents(canvas: &mut Canvas) {
canvas
.draw_rect(
LAYER_BOUNDS,
&Paint::linear_gradient(
Vec2::new(LAYER_BOUNDS.left, LAYER_BOUNDS.top),
Vec2::new(LAYER_BOUNDS.right, LAYER_BOUNDS.bottom),
vec![
GradientStop::new(Color::linear(1.0, 0.2, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.4, 1.0, 1.0), 1.0),
],
)
.with_anti_alias(false),
)
.expect("gradient");
canvas
.draw_circle(
Vec2::new(60.0, 72.0),
26.0,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 0.7)).with_anti_alias(false),
)
.expect("circle");
}
const BLUR_REGION: Rect = Rect {
left: 40.0,
top: 40.0,
right: 88.0,
bottom: 88.0,
};
fn blurred_square(ctx: &mut Context, sigma: f32, bounds: Option<Rect>) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let layer = Layer::default().with_blur(sigma);
match bounds {
Some(region) => canvas.save_layer_bounds(layer, region),
None => canvas.save_layer(layer),
};
canvas
.draw_rect(
BLUR_REGION,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("square");
canvas.restore();
render(ctx, canvas)
}
#[test]
fn a_blurred_layer_spreads_beyond_the_shape_it_holds() {
let Some(mut ctx) = context() else { return };
let sharp = blurred_square(&mut ctx, 0.0, None);
let soft = blurred_square(&mut ctx, 8.0, None);
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * SIZE.width + x) * 4) as usize];
assert_eq!(at(&sharp, 64, 34), 0, "a sharp layer stops at its edge");
assert!(
at(&soft, 64, 34) > 32,
"a blurred layer should reach past its shape, got {}",
at(&soft, 64, 34)
);
let near = at(&soft, 64, 36);
let far = at(&soft, 64, 28);
assert!(
near > far && far > 0,
"the blur should fall off with distance, got {near} then {far}"
);
assert_eq!(at(&soft, 64, 64), 255, "the middle should be undimmed");
}
#[test]
fn a_larger_sigma_spreads_further() {
let Some(mut ctx) = context() else { return };
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * SIZE.width + x) * 4) as usize] as i32;
let small = blurred_square(&mut ctx, 3.0, None);
let large = blurred_square(&mut ctx, 12.0, None);
let probe = (64, 30);
assert!(
at(&large, probe.0, probe.1) > at(&small, probe.0, probe.1),
"a larger sigma should reach further"
);
assert!(
at(&large, 64, 46) < at(&small, 64, 46),
"spreading further should dim the inside it came from"
);
}
#[test]
fn a_blur_of_zero_records_no_extra_passes() {
let mut canvas = Canvas::new(SIZE);
canvas.save_layer(Layer::default());
canvas
.draw_rect(BLUR_REGION, &Paint::fill(Color::WHITE))
.expect("square");
canvas.restore();
let plain = canvas.finish().passes.len();
for sigma in [0.0, -3.0, f32::NAN] {
let mut canvas = Canvas::new(SIZE);
canvas.save_layer(Layer::default().with_blur(sigma));
canvas
.draw_rect(BLUR_REGION, &Paint::fill(Color::WHITE))
.expect("square");
canvas.restore();
assert_eq!(
canvas.finish().passes.len(),
plain,
"a blur of {sigma} should record no extra passes"
);
}
}
#[test]
fn a_blur_keeps_softening_past_the_tap_budget() {
let Some(mut ctx) = context() else { return };
let extent = Extent2D::new(256, 256);
let render = |ctx: &mut Context, sigma: f32| {
let mut canvas = Canvas::new(extent);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::default().with_blur(sigma));
canvas
.draw_rect(
Rect::new(96.0, 96.0, 160.0, 160.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("square");
canvas.restore();
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * 256 + x) * 4) as usize] as i32;
let sigmas = [16.0f32, 32.0, 60.0];
let rendered: Vec<Vec<u8>> = sigmas.iter().map(|s| render(&mut ctx, *s)).collect();
for pair in rendered.windows(2) {
assert!(
at(&pair[1], 128, 56) > at(&pair[0], 128, 56),
"a larger sigma stopped reaching further"
);
assert!(
at(&pair[1], 128, 128) < at(&pair[0], 128, 128),
"a larger sigma stopped dimming the middle"
);
}
}
#[test]
fn blurred_layers_nest() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::default().with_blur(4.0));
canvas.save_layer(Layer::opacity(0.8).with_blur(3.0));
canvas
.draw_rect(
BLUR_REGION,
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("square");
canvas.restore();
canvas.restore();
let recording = canvas.finish();
assert_eq!(
recording.passes.len(),
7,
"two blurred layers and a root should be seven passes"
);
let nested = render_recording(&mut ctx, &recording);
let at = |pixels: &[u8], x: u32, y: u32| pixels[((y * SIZE.width + x) * 4) as usize] as i32;
let once = blurred_square(&mut ctx, 4.0, None);
assert!(
at(&nested, 64, 35) > at(&once, 64, 35),
"two blurs should reach further than one"
);
assert!(
at(&nested, 64, 64) < 255,
"the inner layer's opacity should still apply"
);
}
#[test]
fn a_bounded_blurred_layer_matches_a_full_size_one() {
let Some(mut ctx) = context() else { return };
let full = blurred_square(&mut ctx, 8.0, None);
let bounded = blurred_square(&mut ctx, 8.0, Some(BLUR_REGION));
let worst = full
.iter()
.zip(&bounded)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(
worst <= 1,
"bounding a blurred layer changed the picture by {worst}"
);
let mut canvas = Canvas::new(SIZE);
canvas.save_layer_bounds(Layer::default().with_blur(8.0), BLUR_REGION);
canvas
.draw_rect(BLUR_REGION, &Paint::fill(Color::WHITE))
.expect("square");
canvas.restore();
let recording = canvas.finish();
assert!(
recording.passes[0].extent.width < SIZE.width,
"the layer should still have gotten a smaller target"
);
assert!(
recording.passes[0].extent.width > BLUR_REGION.width() as u32,
"the target should be outset past the content it holds"
);
}
#[test]
fn a_bounded_layer_renders_the_same_as_a_full_size_one() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
open_layer(canvas, bounds, Layer::opacity(0.6));
layer_contents(canvas);
canvas.restore();
});
}
#[test]
fn a_bounded_layer_renders_the_same_under_a_transform() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
canvas.save();
canvas.translate(12.0, -8.0);
canvas.scale(0.75, 0.5);
open_layer(canvas, bounds, Layer::opacity(0.6));
layer_contents(canvas);
canvas.restore();
canvas.restore();
});
}
#[test]
fn a_bounded_layer_renders_the_same_under_a_rotation() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
canvas.save();
canvas.translate(64.0, 72.0);
canvas.rotate(0.4);
canvas.translate(-64.0, -72.0);
open_layer(canvas, bounds, Layer::opacity(0.6));
layer_contents(canvas);
canvas.restore();
canvas.restore();
});
}
fn two_overlapping(canvas: &mut Canvas, alpha: f32, grouped: bool) {
let red = Color::srgb(1.0, 0.0, 0.0, if grouped { 1.0 } else { alpha });
if grouped {
canvas.save_layer(Layer::opacity(alpha));
}
for rect in [
Rect::new(16.0, 16.0, 96.0, 96.0),
Rect::new(32.0, 32.0, 112.0, 112.0),
] {
canvas
.draw_rect(rect, &Paint::fill(red).with_blend(BlendMode::SrcOver))
.expect("rect");
}
if grouped {
canvas.restore();
}
}
#[test]
fn a_groups_opacity_is_applied_to_the_group_and_nesting_multiplies_it() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, draw: &dyn Fn(&mut Canvas)| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
draw(&mut canvas);
render(ctx, canvas)
};
let (both, one) = ((64u32, 64u32), (20u32, 20u32));
let flat = shot(&mut ctx, &|c| two_overlapping(c, 0.49, true));
assert_eq!(
pixel(&flat, both.0, both.1),
pixel(&flat, one.0, one.1),
"a group's alpha applies to the finished group, so its overlap is not \
darker than the rest of it"
);
let got = pixel(&flat, both.0, both.1);
let want = (0.49 * 255.0) as u8;
assert!(
got[0].abs_diff(want) <= 2,
"a layer at forty-nine hundredths over black should give {want} in red, \
got {got:?}"
);
let per_draw = shot(&mut ctx, &|c| two_overlapping(c, 0.49, false));
assert_ne!(
pixel(&per_draw, both.0, both.1),
pixel(&per_draw, one.0, one.1),
"two translucent draws should compound where they overlap; if they do \
not, the check above proves nothing"
);
let nested = shot(&mut ctx, &|c| {
c.save_layer(Layer::opacity(0.7));
two_overlapping(c, 0.7, true);
c.restore();
});
let (got, want) = (pixel(&nested, both.0, both.1), pixel(&flat, both.0, both.1));
let apart = got[0].abs_diff(want[0]);
assert!(
apart <= 2,
"seven tenths inside seven tenths should be forty-nine hundredths: \
{got:?} against {want:?}"
);
}
#[test]
fn an_arc_that_sweeps_nothing_survives_a_mask_blur_and_a_sweep_gradient() {
let Some(mut ctx) = context() else { return };
let mut builder = PathBuilder::default();
builder.arc(Vec2::new(60.0, 60.0), Vec2::new(50.0, 50.0), 0.0, 0.0);
let path = builder.build();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_path(
&path,
&Paint::default()
.with_shader(Shader::SweepGradient {
center: Vec2::new(60.0, 60.0),
start_angle: std::f32::consts::FRAC_PI_4,
end_angle: 3.0 * std::f32::consts::FRAC_PI_4,
stops: vec![
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::BLACK, 1.0),
],
tile: TileMode::Mirror,
})
.with_mask_blur(20.0),
)
.expect("a degenerate arc is not an error");
let pixels = render(&mut ctx, canvas);
let ground = [0u8, 0, 0, 255];
let moved = pixels
.chunks_exact(4)
.filter(|texel| *texel != ground)
.count();
assert_eq!(
moved, 0,
"an arc sweeping nothing put color on {moved} pixels"
);
}
#[test]
fn bounded_layers_nest() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
open_layer(canvas, bounds, Layer::opacity(0.8));
layer_contents(canvas);
open_layer(
canvas,
bounds.map(|_| Rect::new(40.0, 56.0, 88.0, 96.0)),
Layer::opacity(0.5),
);
canvas
.draw_rect(
Rect::new(40.0, 56.0, 88.0, 96.0),
&Paint::fill(Color::linear(0.1, 1.0, 0.3, 1.0)).with_anti_alias(false),
)
.expect("inner");
canvas.restore();
canvas.restore();
});
}
#[test]
fn a_clip_inside_a_bounded_layer_lands_where_it_would_have() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
open_layer(canvas, bounds, Layer::opacity(0.9));
canvas.save();
canvas
.clip_rect(Rect::new(32.0, 48.0, 84.0, 96.0))
.expect("scissor");
let mut triangle = PathBuilder::new();
triangle
.move_to(Vec2::new(60.0, 44.0))
.line_to(Vec2::new(92.0, 100.0))
.line_to(Vec2::new(28.0, 100.0))
.close();
canvas.clip_path(&triangle.build()).expect("stencil");
layer_contents(canvas);
canvas.restore();
canvas.restore();
});
}
#[test]
fn an_antialiased_bounded_layer_renders_the_same_as_a_full_size_one() {
let Some(mut ctx) = context() else { return };
bounds_are_invisible(&mut ctx, |canvas, bounds| {
open_layer(canvas, bounds, Layer::opacity(0.7));
canvas
.draw_circle(
Vec2::new(60.0, 72.0),
28.0,
&Paint::fill(Color::linear(0.9, 0.4, 0.1, 1.0)),
)
.expect("circle");
canvas.restore();
});
}
#[test]
fn glyphs_and_images_in_a_bounded_layer_land_where_they_would_have() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, _) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let rect = atlas.get(solid).unwrap();
let record = |bounds: Option<Rect>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
open_layer(&mut canvas, bounds, Layer::opacity(0.75));
canvas
.draw_rect(
Rect::new(28.0, 44.0, 92.0, 76.0),
&Paint::image(0, Rect::new(28.0, 44.0, 92.0, 76.0)).with_anti_alias(false),
)
.expect("image");
canvas
.draw_glyphs(
&[
PositionedGlyph::new(solid, [32.0, 80.0], rect),
PositionedGlyph::new(solid, [60.0, 80.0], rect),
],
&atlas,
0,
&Paint::fill(Color::WHITE),
)
.expect("glyphs");
canvas.restore();
canvas.finish()
};
let mut draw = |recording: &_| {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, recording, &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let bounded_recording = record(Some(LAYER_BOUNDS));
assert!(bounded_recording.passes[0].extent.width < SIZE.width);
let full = draw(&record(None));
let bounded = draw(&bounded_recording);
ctx.destroy_image(image);
let worst = full
.iter()
.zip(&bounded)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(worst <= 1, "glyphs or the image moved by {worst}");
assert!(full.iter().any(|&b| b > 32), "the scene rendered nothing");
}
#[test]
fn content_outside_a_layers_bounds_is_clipped_rather_than_trusted() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer_bounds(Layer::default(), Rect::new(32.0, 32.0, 96.0, 64.0));
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 96.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 48),
[255, 255, 255, 255],
"inside the bounds the shape is drawn"
);
assert_eq!(
pixel(&pixels, 64, 80),
[0, 0, 0, 255],
"outside the bounds it is cut off, not sampled from somewhere else"
);
}
#[test]
fn a_layer_gets_a_target_the_size_of_its_bounds() {
let mut canvas = Canvas::new(SIZE);
canvas.save_layer_bounds(Layer::default(), Rect::new(24.0, 40.0, 96.0, 104.0));
canvas
.draw_rect(
Rect::new(24.0, 40.0, 96.0, 104.0),
&Paint::fill(Color::WHITE),
)
.expect("rect");
canvas.restore();
let recording = canvas.finish();
assert_eq!(recording.passes[0].extent, Extent2D::new(72, 64));
assert_eq!(
recording.root().extent,
SIZE,
"the root is the caller's surface"
);
}
#[test]
fn fractional_bounds_are_rounded_outward() {
let mut canvas = Canvas::new(SIZE);
canvas.save_layer_bounds(Layer::default(), Rect::new(24.3, 40.9, 95.1, 103.2));
canvas
.draw_rect(Rect::from_size(128.0, 128.0), &Paint::fill(Color::WHITE))
.expect("rect");
canvas.restore();
let recording = canvas.finish();
assert_eq!(recording.passes[0].extent, Extent2D::new(72, 64));
}
#[test]
fn bounds_that_cannot_be_honored_still_produce_a_layer_that_holds_the_content() {
fn layer_extent(open: impl FnOnce(&mut Canvas)) -> Extent2D {
let mut canvas = Canvas::new(SIZE);
open(&mut canvas);
canvas
.draw_rect(Rect::from_size(64.0, 64.0), &Paint::fill(Color::WHITE))
.expect("rect");
canvas.restore();
canvas.finish().passes[0].extent
}
let holds = |extent: Extent2D, what: &str| {
assert!(
extent.width >= 64 && extent.height >= 64,
"{what}: {extent:?} is too small to hold a 64x64 draw"
);
assert!(
extent.width <= SIZE.width && extent.height <= SIZE.height,
"{what}: {extent:?} is larger than the frame"
);
};
let empty = layer_extent(|canvas| {
canvas.save_layer_bounds(Layer::default(), Rect::new(50.0, 50.0, 50.0, 50.0));
});
holds(empty, "empty bounds");
let offscreen = layer_extent(|canvas| {
canvas.save_layer_bounds(Layer::default(), Rect::new(400.0, 400.0, 500.0, 500.0));
});
holds(offscreen, "bounds outside the frame");
}
fn conical_stops() -> Vec<GradientStop> {
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
]
}
#[test]
fn a_conical_gradient_whose_first_circle_is_a_point_at_the_center_is_a_radial_gradient() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::radial_gradient(Vec2::new(64.0, 64.0), 60.0, conical_stops())
.with_anti_alias(false),
)
.expect("radial");
let radial = render(&mut ctx, canvas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::conical_gradient(
Vec2::new(64.0, 64.0),
0.0,
Vec2::new(64.0, 64.0),
60.0,
conical_stops(),
)
.with_anti_alias(false),
)
.expect("conical");
let conical = render(&mut ctx, canvas);
let mut worst = 0i32;
let mut worst_at = (0, 0);
for y in 0..128 {
for x in 0..128 {
let (a, b) = (pixel(&radial, x, y), pixel(&conical, x, y));
for channel in 0..4 {
let delta = (a[channel] as i32 - b[channel] as i32).abs();
if delta > worst {
worst = delta;
worst_at = (x, y);
}
}
}
}
let (x, y) = worst_at;
assert!(
worst <= 1,
"a conical gradient from a point differs from the radial gradient it is: \
{worst} at ({x}, {y}), radial {:?} against conical {:?}",
pixel(&radial, x, y),
pixel(&conical, x, y)
);
}
#[test]
fn a_conical_gradient_between_concentric_circles_holds_the_first_color_inside_the_inner_one() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::conical_gradient(
Vec2::new(64.0, 64.0),
20.0,
Vec2::new(64.0, 64.0),
60.0,
conical_stops(),
)
.with_anti_alias(false),
)
.expect("conical");
let pixels = render(&mut ctx, canvas);
let middle = pixel(&pixels, 64, 64);
let inner_edge = pixel(&pixels, 64 + 18, 64);
assert!(
middle[0] > 240 && middle[2] < 16,
"the hole should hold the first stop, got {middle:?}"
);
for channel in 0..4 {
assert!(
(middle[channel] as i32 - inner_edge[channel] as i32).abs() <= 2,
"the hole is not flat: center {middle:?} against {inner_edge:?}"
);
}
let halfway = pixel(&pixels, 64 + 40, 64);
assert!(
halfway[0] > 90 && halfway[0] < 165 && halfway[2] > 90 && halfway[2] < 165,
"midway between the circles should be midway along the ramp, got {halfway:?}"
);
}
#[test]
fn every_point_on_the_second_circle_reaches_the_last_stop_wherever_the_first_sits() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::conical_gradient(
Vec2::new(44.0, 64.0),
0.0,
Vec2::new(64.0, 64.0),
40.0,
conical_stops(),
)
.with_anti_alias(false),
)
.expect("conical");
let pixels = render(&mut ctx, canvas);
let focus = pixel(&pixels, 44, 64);
assert!(
focus[0] > 240 && focus[2] < 16,
"the first circle collapsed to a point should be the first stop, got {focus:?}"
);
let on_circle = [
pixel(&pixels, 64 + 39, 64),
pixel(&pixels, 64 - 39, 64),
pixel(&pixels, 64, 64 + 39),
pixel(&pixels, 64, 64 - 39),
];
for sample in on_circle {
assert!(
sample[2] > 235 && sample[0] < 24,
"a point on the second circle should be the last stop, got {sample:?}"
);
}
}
#[test]
fn a_conical_gradient_whose_circles_are_tangent_draws_only_the_half_plane_it_spans() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::conical_gradient(
Vec2::new(44.0, 64.0),
0.0,
Vec2::new(64.0, 64.0),
20.0,
conical_stops(),
)
.with_anti_alias(false),
)
.expect("conical");
let pixels = render(&mut ctx, canvas);
for (x, y) in [(84, 64), (64, 84)] {
let sample = pixel(&pixels, x, y);
assert!(
sample[2] > 235 && sample[0] < 24,
"({x}, {y}) is on the second circle and should be the last stop, got {sample:?}"
);
}
for (x, y) in [(20, 64), (4, 4), (4, 124)] {
let sample = pixel(&pixels, x, y);
assert_eq!(
sample,
[0, 0, 0, 255],
"({x}, {y}) is on no circle of the family and should be untouched"
);
}
}
#[test]
fn a_mesh_draws_the_triangles_it_names_and_nothing_else() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mesh = Vertices::new(
VertexMode::Triangles,
vec![
Vec2::new(16.0, 16.0),
Vec2::new(112.0, 16.0),
Vec2::new(16.0, 112.0),
],
)
.expect("mesh");
canvas
.draw_vertices(&mesh, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("mesh");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 24, 24),
[255, 255, 255, 255],
"inside the triangle"
);
assert_eq!(
pixel(&pixels, 100, 100),
[0, 0, 0, 255],
"the corner the triangle does not cover"
);
}
#[test]
fn a_mesh_travels_through_the_canvas_transform() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.translate(64.0, 0.0);
let mesh = Vertices::new(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 16.0),
Vec2::new(48.0, 16.0),
Vec2::new(0.0, 112.0),
],
)
.expect("mesh");
canvas
.draw_vertices(&mesh, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("mesh");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 72, 24),
[255, 255, 255, 255],
"the mesh should have moved with the transform"
);
assert_eq!(
pixel(&pixels, 8, 24),
[0, 0, 0, 255],
"the mesh should not still be where it was written"
);
}
#[test]
fn a_mesh_reads_the_texture_where_its_coordinates_say_rather_than_where_it_sits() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let corners = vec![
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
Vec2::new(128.0, 128.0),
Vec2::new(0.0, 128.0),
];
let mirrored = vec![
Vec2::new(1.0, 0.0),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 1.0),
Vec2::new(1.0, 1.0),
];
let mesh = Vertices::indexed(
VertexMode::Triangles,
corners,
mirrored,
vec![0, 1, 2, 0, 2, 3],
)
.expect("mesh");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_vertices(&mesh, &Paint::image(0, Rect::from_size(128.0, 128.0)))
.expect("mesh");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
for (x, y, want, corner) in [
(16u32, 16u32, [0u8, 255, 0, 255], "top-left"),
(112, 16, [255, 0, 0, 255], "top-right"),
(16, 112, [255, 255, 0, 255], "bottom-left"),
(112, 112, [0, 0, 255, 255], "bottom-right"),
] {
assert_eq!(
pixel(&pixels, x, y),
want,
"the {corner} corner read the wrong texel; the coordinates were ignored"
);
}
}
#[test]
fn texture_coordinates_are_taken_by_any_shader_that_can_read_them() {
let mut canvas = Canvas::new(SIZE);
let mesh = Vertices::textured(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 0.0),
Vec2::new(64.0, 0.0),
Vec2::new(0.0, 64.0),
],
vec![Vec2::ZERO, Vec2::X, Vec2::Y],
)
.expect("mesh");
canvas
.draw_vertices(&mesh, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("a solid paint takes coordinates it has no use for");
canvas
.draw_vertices(
&mesh,
&Paint::runtime_effect(0, vec![0.0; emblema::RUNTIME_FLOATS]),
)
.expect("a program reads a mesh's coordinates as `uv`");
}
#[test]
fn a_source_rectangle_on_a_textured_mesh_is_refused_rather_than_applied_twice() {
let mut canvas = Canvas::new(SIZE);
let mesh = Vertices::textured(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 0.0),
Vec2::new(64.0, 0.0),
Vec2::new(0.0, 64.0),
],
vec![Vec2::ZERO, Vec2::X, Vec2::Y],
)
.expect("mesh");
let paint =
Paint::image(0, Rect::from_size(64.0, 64.0)).with_source(Rect::new(0.0, 0.0, 0.5, 0.5));
assert!(
canvas.draw_vertices(&mesh, &paint).is_err(),
"a source rectangle and per-vertex coordinates both select part of the texture"
);
}
fn shuffled_quadrants() -> Vec<Sprite> {
let quarter = |x, y| SourceRect::new(x, y, 2.0, 2.0);
vec![
Sprite::new(
quarter(2.0, 2.0),
Affine2::from_scale_angle_translation(Vec2::splat(32.0), 0.0, Vec2::new(0.0, 0.0)),
),
Sprite::new(
quarter(0.0, 2.0),
Affine2::from_scale_angle_translation(Vec2::splat(32.0), 0.0, Vec2::new(64.0, 0.0)),
),
Sprite::new(
quarter(2.0, 0.0),
Affine2::from_scale_angle_translation(Vec2::splat(32.0), 0.0, Vec2::new(0.0, 64.0)),
),
Sprite::new(
quarter(0.0, 0.0),
Affine2::from_scale_angle_translation(Vec2::splat(32.0), 0.0, Vec2::new(64.0, 64.0)),
),
]
}
#[test]
fn an_atlas_draws_each_sprite_from_the_part_of_the_sheet_it_named() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_atlas(
&shuffled_quadrants(),
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.expect("atlas");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
for (x, y, want, place) in [
(32u32, 32u32, [255u8, 255, 0, 255], "top-left"),
(96, 32, [0, 0, 255, 255], "top-right"),
(32, 96, [0, 255, 0, 255], "bottom-left"),
(96, 96, [255, 0, 0, 255], "bottom-right"),
] {
assert_eq!(
pixel(&pixels, x, y),
want,
"the {place} sprite read the wrong part of the sheet"
);
}
}
#[test]
fn an_atlas_is_one_draw_however_many_sprites_it_holds() {
let mut canvas = Canvas::new(SIZE);
canvas
.draw_atlas(
&shuffled_quadrants(),
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.expect("atlas");
let recording = canvas.finish();
let pass = recording.passes.first().expect("one pass");
assert_eq!(
pass.batch.draw_count(),
1,
"four sprites should be one draw, not one draw each"
);
}
#[test]
fn an_atlas_sprite_travels_through_its_own_transform() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let placement = Affine2::from_translation(Vec2::splat(64.0))
* Affine2::from_angle(std::f32::consts::FRAC_PI_2)
* Affine2::from_translation(Vec2::splat(-64.0))
* Affine2::from_scale(Vec2::splat(32.0));
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_atlas(
&[Sprite::new(SourceRect::new(0.0, 0.0, 4.0, 4.0), placement)],
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.expect("atlas");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
for (x, y, want, place) in [
(96u32, 32u32, [255u8, 0, 0, 255], "top-right"),
(96, 96, [0, 255, 0, 255], "bottom-right"),
(32, 96, [255, 255, 0, 255], "bottom-left"),
(32, 32, [0, 0, 255, 255], "top-left"),
] {
assert_eq!(
pixel(&pixels, x, y),
want,
"the {place} corner is not where a quarter turn puts it"
);
}
}
#[test]
fn an_atlas_needs_the_size_of_the_sheet_it_reads() {
let mut canvas = Canvas::new(SIZE);
assert!(
canvas
.draw_atlas(
&shuffled_quadrants(),
Extent2D::new(0, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.is_err(),
"a sheet with no texels should be refused rather than divided by"
);
}
#[test]
fn a_blend_filter_agrees_with_the_same_blend_done_by_the_blender() {
let Some(mut ctx) = context() else { return };
let material = Color::linear(0.6, 0.2, 0.1, 0.8);
let constant = Color::linear(0.2, 0.7, 0.4, 0.5);
let area = Rect::from_size(128.0, 128.0);
for mode in [
BlendMode::SrcOver,
BlendMode::DstOver,
BlendMode::SrcIn,
BlendMode::DstIn,
BlendMode::SrcOut,
BlendMode::DstOut,
BlendMode::SrcATop,
BlendMode::DstATop,
BlendMode::Xor,
BlendMode::Plus,
BlendMode::Modulate,
BlendMode::Src,
BlendMode::Dst,
BlendMode::Clear,
] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
canvas
.draw_rect(
area,
&Paint::fill(material)
.with_blend(BlendMode::Src)
.with_anti_alias(false),
)
.expect("material");
canvas
.draw_rect(
area,
&Paint::fill(constant)
.with_blend(mode)
.with_anti_alias(false),
)
.expect("constant");
let blended = render(&mut ctx, canvas);
let filter = ColorFilter::blend(constant.to_array(), mode);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
canvas
.draw_rect(
area,
&Paint::fill(material)
.with_color_filter(filter)
.with_blend(BlendMode::Src)
.with_anti_alias(false),
)
.expect("filtered");
let filtered = render(&mut ctx, canvas);
let (a, b) = (pixel(&blended, 64, 64), pixel(&filtered, 64, 64));
for channel in 0..4 {
assert!(
(a[channel] as i32 - b[channel] as i32).abs() <= 2,
"{mode:?} as a filter gives {b:?} where the blender gives {a:?}"
);
}
}
}
#[test]
fn a_color_matrix_recolors_a_gradient_which_no_tint_could() {
let Some(mut ctx) = context() else { return };
#[rustfmt::skip]
let swap = ColorFilter::matrix([
0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
]);
let stops = || {
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
]
};
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(Vec2::new(8.0, 0.0), Vec2::new(120.0, 0.0), stops())
.with_color_filter(swap)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
let left = pixel(&pixels, 4, 64);
let right = pixel(&pixels, 124, 64);
assert!(
left[2] > 240 && left[0] < 16,
"the red end should have become blue, got {left:?}"
);
assert!(
right[0] > 240 && right[2] < 16,
"the blue end should have become red, got {right:?}"
);
let middle = pixel(&pixels, 64, 64);
assert!(
middle[0] > 40 && middle[0] < 215 && middle[2] > 40 && middle[2] < 215,
"the middle of the gradient should still be a mixture, got {middle:?}"
);
}
#[test]
fn an_advanced_blend_mode_is_a_filter_the_shader_evaluates_rather_than_a_matrix() {
for mode in [
BlendMode::Overlay,
BlendMode::HardLight,
BlendMode::Difference,
BlendMode::Hue,
BlendMode::Luminosity,
] {
let filter = ColorFilter::blend([1.0, 1.0, 1.0, 1.0], mode);
assert!(
matches!(filter, ColorFilter::Blend { .. }),
"{mode:?} is not affine and must not become a matrix: {filter:?}"
);
}
for mode in [
BlendMode::SrcOver,
BlendMode::SrcIn,
BlendMode::Modulate,
BlendMode::Plus,
] {
let filter = ColorFilter::blend([1.0, 1.0, 1.0, 1.0], mode);
assert!(
matches!(filter, ColorFilter::Matrix { .. }),
"{mode:?} is affine and should stay a matrix: {filter:?}"
);
}
}
#[test]
fn a_color_matrix_is_applied_to_straight_color_not_premultiplied() {
let Some(mut ctx) = context() else { return };
#[rustfmt::skip]
let add_green = ColorFilter::matrix([
1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0, 0.5,
0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
]);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 0.5))
.with_color_filter(add_green)
.with_anti_alias(false),
)
.expect("filtered");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
assert!(
(got[0] as i32 - 128).abs() <= 2,
"red should be halved by the alpha, got {got:?}"
);
assert!(
(got[1] as i32 - 64).abs() <= 2,
"green should be a quarter: half of a half. Twice that means the matrix \
was applied to premultiplied color. Got {got:?}"
);
}
#[test]
fn a_luminance_matrix_turns_every_color_the_same_gray_it_weighs() {
let Some(mut ctx) = context() else { return };
const R: f32 = 0.2126;
const G: f32 = 0.7152;
const B: f32 = 0.0722;
#[rustfmt::skip]
let gray = ColorFilter::matrix([
R, G, B, 0.0, 0.0,
R, G, B, 0.0, 0.0,
R, G, B, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
]);
for (name, color, want) in [
("red", Color::linear(1.0, 0.0, 0.0, 1.0), R),
("green", Color::linear(0.0, 1.0, 0.0, 1.0), G),
("blue", Color::linear(0.0, 0.0, 1.0, 1.0), B),
] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(color)
.with_color_filter(gray)
.with_anti_alias(false),
)
.expect("filtered");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
let expected = (want * 255.0).round() as i32;
for channel in 0..3 {
assert!(
(got[channel] as i32 - expected).abs() <= 2,
"{name} should weigh to {expected} in every channel, got {got:?}"
);
}
}
}
#[test]
fn a_mesh_interpolates_the_colors_its_vertices_carry() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mesh = Vertices::colored(
VertexMode::Triangles,
vec![
Vec2::new(64.0, 8.0),
Vec2::new(120.0, 112.0),
Vec2::new(8.0, 112.0),
],
vec![
Color::linear(1.0, 0.0, 0.0, 1.0),
Color::linear(0.0, 1.0, 0.0, 1.0),
Color::linear(0.0, 0.0, 1.0, 1.0),
],
)
.expect("mesh");
canvas
.draw_vertices(&mesh, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("mesh");
let pixels = render(&mut ctx, canvas);
for (x, y, channel, corner) in [
(64u32, 20u32, 0usize, "top"),
(108, 104, 1, "bottom-right"),
(20, 104, 2, "bottom-left"),
] {
let got = pixel(&pixels, x, y);
let others: Vec<u8> = (0..3).filter(|c| *c != channel).map(|c| got[c]).collect();
assert!(
got[channel] > 150 && others.iter().all(|v| *v < 110),
"the {corner} corner should be dominated by its own color, got {got:?}"
);
}
let middle = pixel(&pixels, 64, 80);
assert!(
(0..3).all(|c| middle[c] > 40 && middle[c] < 160),
"the middle should mix all three corners, got {middle:?}"
);
}
#[test]
fn a_vertex_color_multiplies_the_paint_rather_than_replacing_it() {
let Some(mut ctx) = context() else { return };
let corners = vec![
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
Vec2::new(0.0, 128.0),
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mesh = Vertices::colored(
VertexMode::Triangles,
corners,
vec![Color::srgb(1.0, 0.5, 0.0, 1.0); 3],
)
.expect("mesh");
canvas
.draw_vertices(
&mesh,
&Paint::fill(Color::srgb(0.5, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("mesh");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 20, 20);
for (channel, want) in [(0usize, 128i32), (1, 128), (2, 0)] {
assert!(
(got[channel] as i32 - want).abs() <= 2,
"channel {channel} should be the product of paint and vertex, got {got:?}"
);
}
}
#[test]
fn an_atlas_tints_each_sprite_on_its_own_in_one_draw() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &[255u8; 4 * 4 * 4])
.expect("upload");
let whole = SourceRect::new(0.0, 0.0, 4.0, 4.0);
let place =
|x: f32| Affine2::from_scale_angle_translation(Vec2::splat(16.0), 0.0, Vec2::new(x, 0.0));
let sprites = vec![
Sprite::new(whole, place(0.0)).with_color(Color::linear(1.0, 0.0, 0.0, 1.0)),
Sprite::new(whole, place(64.0)).with_color(Color::linear(0.0, 1.0, 0.0, 1.0)),
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_atlas(
&sprites,
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)),
)
.expect("atlas");
let recording = canvas.finish();
assert_eq!(
recording.passes[0].batch.draw_count(),
1,
"tinting per sprite must not split the batch"
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &recording, &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(pixel(&pixels, 32, 32), [255, 0, 0, 255], "the first sprite");
assert_eq!(
pixel(&pixels, 96, 32),
[0, 255, 0, 255],
"the second sprite"
);
}
#[test]
fn a_vertex_color_is_interpolated_premultiplied_across_a_fading_edge() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mesh = Vertices::full(
VertexMode::Triangles,
vec![
Vec2::new(8.0, 32.0),
Vec2::new(120.0, 32.0),
Vec2::new(120.0, 96.0),
Vec2::new(8.0, 96.0),
],
Vec::new(),
vec![
Color::linear(1.0, 0.0, 0.0, 1.0),
Color::linear(1.0, 0.0, 0.0, 0.0),
Color::linear(1.0, 0.0, 0.0, 0.0),
Color::linear(1.0, 0.0, 0.0, 1.0),
],
vec![0, 1, 2, 0, 2, 3],
)
.expect("mesh");
canvas
.draw_vertices(
&mesh,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("mesh");
let pixels = render(&mut ctx, canvas);
let middle = pixel(&pixels, 64, 64);
assert!(
(middle[0] as i32 - 128).abs() <= 6,
"halfway along the fade should be half strength; twice that means the \
color was interpolated straight and then used as premultiplied. Got {middle:?}"
);
}
#[test]
fn nearest_sampling_reads_one_texel_where_linear_blends_two() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let draw = |ctx: &mut Context, sampling: Sampling| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_sampling(sampling)
.with_anti_alias(false),
)
.expect("image");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let linear = draw(&mut ctx, Sampling::Linear);
let nearest = draw(&mut ctx, Sampling::Nearest);
ctx.destroy_image(image);
for x in [62u32, 66] {
let got = pixel(&linear, x, 32);
assert!(
got[0] > 20 && got[1] > 20,
"linear at ({x}, 32) should mix the two quadrants, got {got:?}"
);
}
assert_eq!(
pixel(&nearest, 62, 32),
[255, 0, 0, 255],
"nearest left of the seam should be the red texel alone"
);
assert_eq!(
pixel(&nearest, 66, 32),
[0, 255, 0, 255],
"nearest right of the seam should be the green texel alone"
);
for (x, y) in [(16u32, 16u32), (112, 112)] {
assert_eq!(
pixel(&linear, x, y),
pixel(&nearest, x, y),
"the two modes should agree away from a boundary at ({x}, {y})"
);
}
}
#[test]
fn an_image_filter_blur_of_a_solid_agrees_with_the_mask_blur_of_the_same_shape() {
let Some(mut ctx) = context() else { return };
let shape = || concave_path(Rect::new(32.0, 40.0, 96.0, 96.0));
let color = Color::linear(0.9, 0.3, 0.2, 1.0);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.05, 0.05, 0.08, 1.0));
canvas
.draw_path(&shape(), &Paint::fill(color).with_mask_blur(6.0))
.expect("mask blur");
let masked = render(&mut ctx, canvas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.05, 0.05, 0.08, 1.0));
canvas
.draw_path(
&shape(),
&Paint::fill(color).with_image_filter(ImageFilter::blur(6.0)),
)
.expect("image filter");
let filtered = render(&mut ctx, canvas);
let mut worst = 0i32;
for (a, b) in masked.chunks_exact(4).zip(filtered.chunks_exact(4)) {
for channel in 0..4 {
worst = worst.max((a[channel] as i32 - b[channel] as i32).abs());
}
}
assert!(
worst <= 2,
"blurring coverage and blurring the result should agree on a solid \
color; they differ by {worst}"
);
}
#[test]
fn an_image_filter_blurs_the_result_where_a_mask_blur_blurs_the_mask() {
let Some(mut ctx) = context() else { return };
let gradient = || {
Paint::linear_gradient(
Vec2::new(32.0, 0.0),
Vec2::new(96.0, 0.0),
vec![
GradientStop::new(Color::linear(1.0, 0.2, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.4, 1.0, 1.0), 1.0),
],
)
};
let area = Rect::new(32.0, 40.0, 96.0, 88.0);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(area, &gradient().with_mask_blur(6.0))
.expect("a mask blur over a gradient");
let masked = render(&mut ctx, canvas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(area, &gradient().with_image_filter(ImageFilter::blur(6.0)))
.expect("image filter");
let pixels = render(&mut ctx, canvas);
let just_outside = pixel(&pixels, 64, 36);
let far_outside = pixel(&pixels, 64, 8);
assert!(
just_outside.iter().take(3).any(|v| *v > 20),
"the blur should reach past the shape, got {just_outside:?}"
);
assert_eq!(
far_outside,
[0, 0, 0, 255],
"the blur should not reach the whole target"
);
let left = pixel(&pixels, 40, 64);
let right = pixel(&pixels, 88, 64);
assert!(
left[0] > right[0] && right[2] > left[2],
"the gradient should survive the blur: left {left:?}, right {right:?}"
);
let worst = (0..128u32)
.flat_map(|x| (0..128u32).map(move |y| (x, y)))
.map(|(x, y)| {
let a = pixel(&masked, x, y);
let b = pixel(&pixels, x, y);
(0..3)
.map(|c| (a[c] as i32 - b[c] as i32).abs())
.max()
.unwrap_or(0)
})
.max()
.expect("a frame");
assert!(
worst > 8,
"the two orders came back within {worst} levels of each other, so one \
of them is not doing what its name says"
);
}
#[test]
fn a_filtered_stroke_keeps_the_half_of_itself_that_lies_outside_the_path() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
20.0,
&Paint::stroke(Color::linear(1.0, 1.0, 1.0, 1.0), 40.0).with_mask_blur(1.0),
)
.expect("stroke");
let pixels = render(&mut ctx, canvas);
for (x, y) in [(64u32, 28u32), (64, 100), (28, 64), (100, 64)] {
let got = pixel(&pixels, x, y);
assert!(
got[0] > 200,
"({x}, {y}) is inside the stroke and should be painted, got {got:?}"
);
}
}
fn mask_blur_probe(ctx: &mut Context, style: MaskBlurStyle) -> ([u8; 4], [u8; 4], [u8; 4]) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
34.0,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_mask_blur(6.0)
.with_mask_blur_style(style),
)
.expect("mask blur");
let pixels = render(ctx, canvas);
(
pixel(&pixels, 64, 64),
pixel(&pixels, 64, 30),
pixel(&pixels, 64, 24),
)
}
#[test]
fn each_mask_blur_style_keeps_the_part_of_the_blur_it_names() {
let Some(mut ctx) = context() else { return };
let (inside, edge, outside) = mask_blur_probe(&mut ctx, MaskBlurStyle::Normal);
assert!(
inside[0] > 240,
"normal should be solid well inside: {inside:?}"
);
assert!(
edge[0] > 40 && edge[0] < 220,
"normal should be soft at the edge: {edge:?}"
);
assert!(outside[0] > 4, "normal should reach outside: {outside:?}");
let (inside, edge, outside) = mask_blur_probe(&mut ctx, MaskBlurStyle::Solid);
assert!(inside[0] > 240, "solid should be solid inside: {inside:?}");
assert!(
edge[0] > 240,
"solid keeps the shape at full strength, so its own edge is hard: {edge:?}"
);
assert!(
outside[0] > 4,
"solid should still blur outside: {outside:?}"
);
let (inside, edge, outside) = mask_blur_probe(&mut ctx, MaskBlurStyle::Outer);
assert_eq!(
inside,
[0, 0, 0, 255],
"outer draws nothing inside the shape"
);
assert!(outside[0] > 4, "outer is the blur outside: {outside:?}");
assert!(
edge[0] < 240,
"the shape is taken out of the blur, so its edge is not full strength: {edge:?}"
);
let (inside, edge, outside) = mask_blur_probe(&mut ctx, MaskBlurStyle::Inner);
assert_eq!(
outside,
[0, 0, 0, 255],
"inner draws nothing outside the shape"
);
assert!(
inside[0] > 240,
"inner is solid away from the edge: {inside:?}"
);
assert!(
edge[0] > 4 && edge[0] < 240,
"inner fades toward the shape's own edge: {edge:?}"
);
}
fn mask_blur_gradient_probe(
ctx: &mut Context,
style: MaskBlurStyle,
) -> ([u8; 4], [u8; 4], [u8; 4], [u8; 4]) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
34.0,
&Paint::default()
.with_shader(Shader::LinearGradient {
start: Vec2::new(30.0, 0.0),
end: Vec2::new(98.0, 0.0),
stops: vec![
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.0, 0.0, 1.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
})
.with_mask_blur(6.0)
.with_mask_blur_style(style),
)
.expect("mask blur over a gradient");
let pixels = render(ctx, canvas);
(
pixel(&pixels, 44, 64),
pixel(&pixels, 84, 64),
pixel(&pixels, 64, 30),
pixel(&pixels, 64, 24),
)
}
#[test]
fn each_mask_blur_style_keeps_its_own_part_of_a_gradient_too() {
let Some(mut ctx) = context() else { return };
let sharp_edge = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
34.0,
&Paint::default().with_shader(Shader::LinearGradient {
start: Vec2::new(30.0, 0.0),
end: Vec2::new(98.0, 0.0),
stops: vec![
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.0, 0.0, 1.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
}),
)
.expect("unblurred reference");
pixel(&render(&mut ctx, canvas), 64, 30)
};
let strength = |p: [u8; 4]| p[0] as u32 + p[1] as u32 + p[2] as u32;
let full = strength(sharp_edge);
let red_then_blue = |left: [u8; 4], right: [u8; 4], what: &str| {
assert!(
left[0] > left[2] + 60,
"{what}: the gradient's red end should be red, got {left:?}"
);
assert!(
right[2] > right[0] + 60,
"{what}: the gradient's blue end should be blue, got {right:?}"
);
};
let (left, right, edge, outside) = mask_blur_gradient_probe(&mut ctx, MaskBlurStyle::Normal);
red_then_blue(left, right, "normal");
assert!(
strength(edge) * 10 < full * 9,
"normal should be soft at the edge: {edge:?} against {full} at full coverage"
);
assert!(
outside.iter().take(3).any(|c| *c > 4),
"normal should reach outside: {outside:?}"
);
let (left, right, edge, outside) = mask_blur_gradient_probe(&mut ctx, MaskBlurStyle::Solid);
red_then_blue(left, right, "solid");
assert_eq!(
edge, sharp_edge,
"solid keeps the shape at full strength, so its own edge is the \
unblurred one"
);
assert!(
outside.iter().take(3).any(|c| *c > 4),
"solid should still blur outside: {outside:?}"
);
let (left, right, edge, outside) = mask_blur_gradient_probe(&mut ctx, MaskBlurStyle::Outer);
assert_eq!(left, [0, 0, 0, 255], "outer draws nothing inside the shape");
assert_eq!(
right,
[0, 0, 0, 255],
"outer draws nothing inside the shape"
);
assert!(
outside.iter().take(3).any(|c| *c > 4),
"outer is the blur outside: {outside:?}"
);
assert!(
strength(edge) < full,
"the shape is taken out of the blur, so its edge is not full strength: \
{edge:?} against {full}"
);
let (left, right, _edge, outside) = mask_blur_gradient_probe(&mut ctx, MaskBlurStyle::Inner);
red_then_blue(left, right, "inner");
assert_eq!(
outside,
[0, 0, 0, 255],
"inner draws nothing outside the shape"
);
}
#[test]
fn the_two_halves_of_a_blur_add_up_to_the_whole_of_it() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, style: MaskBlurStyle| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_path(
&concave_path(Rect::new(30.0, 30.0, 98.0, 98.0)),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_mask_blur(6.0)
.with_mask_blur_style(style),
)
.expect("mask blur");
render(ctx, canvas)
};
let whole = draw(&mut ctx, MaskBlurStyle::Normal);
let inner = draw(&mut ctx, MaskBlurStyle::Inner);
let outer = draw(&mut ctx, MaskBlurStyle::Outer);
let mut worst = 0i32;
let mut worst_at = 0usize;
for (i, ((w, a), b)) in whole
.chunks_exact(4)
.zip(inner.chunks_exact(4))
.zip(outer.chunks_exact(4))
.enumerate()
{
let delta = (w[0] as i32 - (a[0] as i32 + b[0] as i32)).abs();
if delta > worst {
worst = delta;
worst_at = i;
}
}
assert!(
worst <= 4,
"the inner and outer halves should reconstruct the whole blur; they \
differ by {worst} at pixel ({}, {})",
worst_at % 128,
worst_at / 128
);
}
fn shadow_probe(ctx: &mut Context, elevation: f32, transparent: bool, draw_card: bool) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.9, 0.9, 0.92, 1.0));
let card = {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 80.0))
.line_to(Vec2::new(40.0, 80.0))
.close();
b.build()
};
canvas
.draw_shadow(
&card,
Color::linear(0.0, 0.0, 0.0, 1.0),
elevation,
transparent,
)
.expect("shadow");
if draw_card {
canvas
.draw_path(&card, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("card");
}
render(ctx, canvas)
}
#[test]
fn a_shadow_falls_below_what_casts_it_and_widens_with_elevation() {
let Some(mut ctx) = context() else { return };
let low = shadow_probe(&mut ctx, 3.0, false, true);
let high = shadow_probe(&mut ctx, 12.0, false, true);
let below_low = pixel(&low, 64, 88)[0] as i32;
let below_high = pixel(&high, 64, 88)[0] as i32;
assert!(
below_high < below_low,
"raising the object should darken the ground below it: {below_low} then {below_high}"
);
let above_low = pixel(&low, 64, 30)[0] as i32;
let above_high = pixel(&high, 64, 30)[0] as i32;
assert!(
above_low > 220 && above_high > 220,
"the light is above, so nothing should fall above the object: {above_low}, {above_high}"
);
let beside_low = pixel(&low, 34, 60)[0] as i32;
let beside_high = pixel(&high, 34, 60)[0] as i32;
assert!(
beside_high < beside_low - 8,
"raising the object should spread its shadow sideways too: {beside_low} then {beside_high}"
);
}
#[test]
fn an_object_resting_on_the_surface_casts_no_shadow() {
let Some(mut ctx) = context() else { return };
let flat = shadow_probe(&mut ctx, 0.0, false, false);
let first = &flat[0..4];
assert!(
flat.chunks_exact(4).all(|texel| texel == first),
"an elevation of zero should leave the ground untouched"
);
}
#[test]
fn the_occluder_flag_is_accepted_and_changes_nothing() {
let Some(mut ctx) = context() else { return };
let opaque = shadow_probe(&mut ctx, 10.0, false, true);
let transparent = shadow_probe(&mut ctx, 10.0, true, true);
assert_eq!(
opaque, transparent,
"the occluder flag changed the picture, and upstream's does not"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_shadow(
&Rect::new(40.0, 40.0, 88.0, 80.0).to_rounded_path(4.0),
Color::BLACK,
10.0,
false,
)
.expect("shadow");
assert_eq!(
canvas.finish().passes.len(),
1,
"a shadow over a rounded rectangle should not open a layer"
);
let below = pixel(&opaque, 64, 86)[0] as i32;
assert!(below < 210, "the shadow below the card is missing: {below}");
let on_card = pixel(&opaque, 64, 70)[0] as i32;
assert!(
on_card > 240,
"the card should cover its own shadow: {on_card}"
);
}
#[test]
fn a_point_is_drawn_as_the_cap_it_would_have_had() {
let Some(mut ctx) = context() else { return };
let draw = |ctx: &mut Context, cap: LineCap| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_points(
PointMode::Points,
&[Vec2::new(64.0, 64.0)],
&Paint {
style: Style::Stroke(StrokeStyle {
cap,
..StrokeStyle::new(40.0)
}),
..Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false)
},
)
.expect("points");
render(ctx, canvas)
};
let round = draw(&mut ctx, LineCap::Round);
let square = draw(&mut ctx, LineCap::Square);
let butt = draw(&mut ctx, LineCap::Butt);
let corner = (64 + 18, 64 + 18);
assert!(
pixel(&square, corner.0, corner.1)[0] > 240,
"a square cap should fill its corners"
);
assert_eq!(
pixel(&round, corner.0, corner.1),
[0, 0, 0, 255],
"a round cap should not reach its corners"
);
assert!(
pixel(&round, 64, 64)[0] > 240 && pixel(&square, 64, 64)[0] > 240,
"both should cover the point itself"
);
let first = &butt[0..4];
assert!(
butt.chunks_exact(4).all(|texel| texel == first),
"a butt cap adds nothing to a segment of no length, so nothing is drawn"
);
}
#[test]
fn the_clip_bounds_narrow_with_every_kind_of_clip() {
let mut canvas = Canvas::new(SIZE);
let whole = canvas.destination_clip_bounds();
assert_eq!(
(whole.left, whole.top, whole.right, whole.bottom),
(0.0, 0.0, 128.0, 128.0),
"an unclipped canvas may reach all of its target"
);
canvas.save();
canvas.clip_rect(Rect::new(16.0, 16.0, 96.0, 96.0)).unwrap();
let after_rect = canvas.destination_clip_bounds();
assert_eq!(
(
after_rect.left,
after_rect.top,
after_rect.right,
after_rect.bottom
),
(16.0, 16.0, 96.0, 96.0)
);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(32.0, 32.0))
.line_to(Vec2::new(64.0, 32.0))
.line_to(Vec2::new(64.0, 64.0))
.close();
canvas.clip_path(&b.build()).unwrap();
let after_path = canvas.destination_clip_bounds();
assert_eq!(
(
after_path.left,
after_path.top,
after_path.right,
after_path.bottom
),
(32.0, 32.0, 64.0, 64.0),
"a path clip narrows what is reachable even though the scissor is unchanged"
);
canvas.restore();
let restored = canvas.destination_clip_bounds();
assert_eq!(
(restored.left, restored.top, restored.right, restored.bottom),
(0.0, 0.0, 128.0, 128.0),
"restoring gives back what the save was holding"
);
}
#[test]
fn the_local_clip_bounds_are_stated_in_the_callers_own_coordinates() {
let mut canvas = Canvas::new(SIZE);
canvas.clip_rect(Rect::new(32.0, 32.0, 96.0, 96.0)).unwrap();
canvas.save();
canvas.translate(32.0, 32.0);
let local = canvas.local_clip_bounds();
assert_eq!(
(local.left, local.top, local.right, local.bottom),
(0.0, 0.0, 64.0, 64.0),
"a translation moves the origin the bounds are stated from"
);
canvas.restore();
canvas.save();
canvas.scale(2.0, 2.0);
let local = canvas.local_clip_bounds();
assert_eq!(
(local.left, local.top, local.right, local.bottom),
(16.0, 16.0, 48.0, 48.0),
"a scale changes what a unit is"
);
canvas.restore();
canvas.save();
canvas.rotate(std::f32::consts::FRAC_PI_4);
let local = canvas.local_clip_bounds();
assert!(
local.right - local.left > 64.0 * 1.4,
"a rotation should give a conservative box, got {}",
local.right - local.left
);
canvas.restore();
}
#[test]
fn a_collapsed_transform_leaves_nothing_reachable() {
let mut canvas = Canvas::new(SIZE);
canvas.scale(0.0, 1.0);
let local = canvas.local_clip_bounds();
assert_eq!(
(local.right - local.left, local.bottom - local.top),
(0.0, 0.0),
"a transform that cannot be inverted reaches nothing"
);
}
fn effect_uniforms(threshold: f32) -> Vec<f32> {
let mut out = vec![0.0; RUNTIME_FLOATS];
out[0..4].copy_from_slice(&[1.0, 0.0, 0.0, 1.0]);
out[4..8].copy_from_slice(&[0.0, 0.7, 0.2, 1.0]);
out[20] = threshold;
out
}
#[test]
fn a_caller_can_fill_a_shape_with_their_own_fragment_program() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_FS_GLSL.to_string(),
})
.expect("register");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
48.0,
&Paint::runtime_effect(program, effect_uniforms(0.0)).with_anti_alias(false),
)
.expect("effect");
let pixels = render(&mut ctx, canvas);
assert_eq!(pixel(&pixels, 40, 64), [255, 0, 0, 255], "the left half");
close_enough(
pixel(&pixels, 88, 64),
[0, 178, 51, 255],
1,
"the right half, in the caller's second color",
);
assert_eq!(
pixel(&pixels, 4, 4),
[0, 0, 0, 255],
"outside the circle the effect did not run"
);
}
#[test]
fn an_effects_uniforms_travel_with_the_paint_that_names_it() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_FS_GLSL.to_string(),
})
.expect("register");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 60.0),
&Paint::runtime_effect(program, effect_uniforms(-0.5)).with_anti_alias(false),
)
.expect("upper");
canvas
.draw_rect(
Rect::new(0.0, 68.0, 128.0, 128.0),
&Paint::runtime_effect(program, effect_uniforms(0.5)).with_anti_alias(false),
)
.expect("lower");
let pixels = render(&mut ctx, canvas);
close_enough(
pixel(&pixels, 64, 30),
[0, 178, 51, 255],
1,
"past the first",
);
assert_eq!(
pixel(&pixels, 64, 100),
[255, 0, 0, 255],
"before the second"
);
}
#[test]
fn a_paint_naming_a_program_nobody_registered_is_refused() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::runtime_effect(11, effect_uniforms(0.0)),
)
.expect("recording a draw does not touch a device");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
let result = ctx.draw(&mut surface, &canvas.finish());
ctx.destroy_surface(surface);
assert!(
result.is_err(),
"a program nobody registered should be refused when the recording is drawn"
);
}
#[test]
fn a_runtime_effect_can_filter_what_was_drawn_rather_than_fill_it() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_IMAGE_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_IMAGE_FS_GLSL.to_string(),
})
.expect("register");
let tint = |r: f32, g: f32, b: f32| {
let mut uniforms = vec![0.0; RUNTIME_FLOATS];
uniforms[0..4].copy_from_slice(&[r, g, b, 1.0]);
ImageFilter::Runtime {
program,
uniforms,
sampling: Sampling::Nearest,
}
};
let shot = |ctx: &mut Context, filter: ImageFilter| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 96.0),
&Paint::linear_gradient(
Vec2::new(32.0, 0.0),
Vec2::new(96.0, 0.0),
vec![
GradientStop::new(Color::srgb(1.0, 1.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.15, 0.15, 0.15, 1.0), 1.0),
],
)
.with_anti_alias(false)
.with_image_filter(filter),
)
.expect("rect");
render(ctx, canvas)
};
let plain = shot(&mut ctx, ImageFilter::None);
let (left, right) = (pixel(&plain, 36, 64), pixel(&plain, 92, 64));
assert!(
left[0] > right[0] + 100,
"the unfiltered gradient should run bright to dark: {left:?} to {right:?}"
);
let filtered = shot(&mut ctx, tint(1.0, 0.4, 0.0));
let got = pixel(&filtered, 36, 64);
assert!(
got[0] > 200 && got[1] < got[0] / 2 && got[2] < 16,
"the program should have tinted what was drawn, got {got:?}"
);
let (l, r) = (pixel(&filtered, 36, 64), pixel(&filtered, 92, 64));
assert!(
l[0] > r[0] + 100,
"the filtered result is flat, so the program sampled something other \
than the layer: {l:?} to {r:?}"
);
assert_eq!(
pixel(&filtered, 8, 8),
[0, 0, 0, 255],
"the filter reached outside the layer"
);
let other = shot(&mut ctx, tint(0.0, 0.4, 1.0));
assert_ne!(
pixel(&filtered, 64, 64),
pixel(&other, 64, 64),
"both tints gave the same picture, so the uniforms did not arrive"
);
let composed = shot(
&mut ctx,
ImageFilter::compose(tint(1.0, 0.4, 0.0), ImageFilter::blur(6.0)),
);
let halo = pixel(&composed, 28, 64);
assert!(
halo[0] > 4,
"the blur half of the composition did nothing: {halo:?}"
);
assert!(
halo[0] > halo[2],
"the tint half of the composition did nothing: {halo:?}"
);
}
#[test]
fn a_runtime_effect_can_read_a_texture_the_caller_supplied() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_IMAGE_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_IMAGE_FS_GLSL.to_string(),
})
.expect("register");
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let mut uniforms = vec![0.0; RUNTIME_FLOATS];
uniforms[0..4].copy_from_slice(&[1.0, 1.0, 1.0, 1.0]);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::runtime_effect(program, uniforms)
.with_effect_image(0)
.with_anti_alias(false),
)
.expect("effect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
for (x, y, want, corner) in [
(16u32, 112u32, [255u8, 0, 0, 255], "bottom-left"),
(112, 112, [0, 255, 0, 255], "bottom-right"),
(16, 16, [0, 0, 255, 255], "top-left"),
(112, 16, [255, 255, 0, 255], "top-right"),
] {
assert_eq!(
pixel(&pixels, x, y),
want,
"the {corner} of the frame read the wrong texel"
);
}
}
fn nine_region_image() -> Vec<u8> {
const BLOCKS: [[u8; 3]; 9] = [
[220, 40, 40],
[40, 200, 60],
[50, 90, 230],
[230, 200, 40],
[200, 60, 200],
[60, 200, 200],
[255, 140, 40],
[130, 130, 130],
[255, 255, 255],
];
let mut out = vec![0u8; 12 * 12 * 4];
for y in 0..12usize {
for x in 0..12usize {
let block = (y / 4) * 3 + (x / 4);
let i = (y * 12 + x) * 4;
out[i..i + 3].copy_from_slice(&BLOCKS[block]);
out[i + 3] = 255;
}
}
out
}
#[test]
fn a_nine_patch_stretches_its_middle_and_keeps_its_corners() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(12, 12), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &nine_region_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_image_nine(
0,
Extent2D::new(12, 12),
Rect::new(4.0, 4.0, 8.0, 8.0),
Rect::new(8.0, 8.0, 120.0, 120.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("nine patch");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(
pixel(&pixels, 10, 10),
[220, 40, 40, 255],
"the top-left corner keeps its own block"
);
assert_eq!(
pixel(&pixels, 118, 10),
[50, 90, 230, 255],
"the top-right corner keeps its own"
);
assert_eq!(
pixel(&pixels, 10, 118),
[255, 140, 40, 255],
"and the bottom-left"
);
assert_eq!(
pixel(&pixels, 40, 10),
[40, 200, 60, 255],
"past the corner is the top edge, stretched along one axis only"
);
assert_eq!(
pixel(&pixels, 10, 40),
[230, 200, 40, 255],
"and down the side is the left edge"
);
assert_eq!(
pixel(&pixels, 64, 64),
[200, 60, 200, 255],
"the middle stretches both ways"
);
}
#[test]
fn a_nine_patch_center_outside_the_image_is_refused() {
let mut canvas = Canvas::new(SIZE);
assert!(
canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 9.0, 9.0),
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::WHITE),
)
.is_err(),
"a center reaching past the image leaves no nine pieces to draw"
);
}
#[test]
fn drawing_the_paint_fills_the_clip_rather_than_the_target() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.clip_rect(Rect::new(32.0, 32.0, 96.0, 96.0)).unwrap();
canvas.save();
canvas.scale(0.5, 0.5);
canvas
.draw_paint(&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false))
.expect("paint");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[255, 255, 255, 255],
"inside the clip should be filled whatever the transform"
);
assert_eq!(
pixel(&pixels, 16, 64),
[0, 0, 0, 255],
"and nothing outside it"
);
assert_eq!(pixel(&pixels, 64, 16), [0, 0, 0, 255], "on either axis");
}
#[test]
fn drawing_a_color_blends_where_clearing_replaces() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(1.0, 0.0, 0.0, 1.0));
canvas.clip_rect(Rect::new(0.0, 0.0, 64.0, 128.0)).unwrap();
canvas
.draw_color(Color::linear(0.0, 0.0, 1.0, 0.5), BlendMode::SrcOver)
.expect("color");
let pixels = render(&mut ctx, canvas);
let mixed = pixel(&pixels, 32, 64);
assert!(
mixed[0] > 100 && mixed[2] > 100,
"half-transparent blue over red should be both, got {mixed:?}"
);
assert_eq!(
pixel(&pixels, 96, 64),
[255, 0, 0, 255],
"outside the clip the ground is untouched"
);
}
#[test]
fn a_layer_matrix_moves_the_finished_image_rather_than_its_contents() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer_bounds(
Layer::opacity(1.0).with_matrix(Affine2::from_translation(Vec2::new(40.0, 0.0))),
Rect::new(8.0, 40.0, 56.0, 88.0),
);
canvas
.draw_rect(
Rect::new(16.0, 48.0, 48.0, 80.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("inside");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 72, 64),
[255, 255, 255, 255],
"the finished layer should have moved by the matrix"
);
assert_eq!(
pixel(&pixels, 32, 64),
[0, 0, 0, 255],
"and left nothing where it was drawn"
);
}
#[test]
fn a_layer_matrix_that_folds_the_plane_composites_where_it_was_drawn() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer_bounds(
Layer::opacity(1.0).with_matrix(Affine2::from_scale(Vec2::new(0.0, 1.0))),
Rect::new(32.0, 32.0, 96.0, 96.0),
);
canvas
.draw_rect(
Rect::new(40.0, 40.0, 88.0, 88.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("inside");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[255, 255, 255, 255],
"a matrix with no inverse should leave the layer where it was"
);
}
#[test]
fn a_matrix_image_filter_moves_what_was_drawn() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(32.0, 32.0),
20.0,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_image_filter(
ImageFilter::Matrix {
transform: Affine2::from_scale(Vec2::splat(2.0)).into(),
},
),
)
.expect("filtered");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[255, 255, 255, 255],
"the doubled circle should cover the center of the frame"
);
assert_eq!(
pixel(&pixels, 100, 64),
[255, 255, 255, 255],
"and reach where only a doubled one could"
);
assert_eq!(
pixel(&pixels, 14, 32),
[0, 0, 0, 255],
"and leave where it was written"
);
}
#[test]
fn an_image_filter_on_a_shape_with_a_fast_path_is_not_quietly_dropped() {
let Some(mut ctx) = context() else { return };
for which in ["circle", "rounded rectangle"] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint =
Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_image_filter(ImageFilter::Matrix {
transform: Affine2::from_translation(Vec2::new(48.0, 0.0)).into(),
});
if which == "circle" {
canvas
.draw_circle(Vec2::new(32.0, 64.0), 20.0, &paint)
.expect("circle");
} else {
canvas
.draw_rrect(Rect::new(12.0, 44.0, 52.0, 84.0), 8.0, &paint)
.expect("rrect");
}
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 80, 64),
[255, 255, 255, 255],
"the {which} should have moved by the filter"
);
assert_eq!(
pixel(&pixels, 32, 64),
[0, 0, 0, 255],
"and left where it was written"
);
}
}
fn encode_srgb(linear: f32) -> f32 {
if linear <= 0.003_130_8 {
linear * 12.92
} else {
1.055 * linear.powf(1.0 / 2.4) - 0.055
}
}
fn decode_srgb(encoded: f32) -> f32 {
if encoded <= 0.040_45 {
encoded / 12.92
} else {
((encoded + 0.055) / 1.055).powf(2.4)
}
}
#[test]
fn the_gamma_filter_follows_the_curve_at_both_ends_of_it() {
let Some(mut ctx) = context() else { return };
const SAMPLES: [f32; 4] = [0.001, 0.002_5, 0.2, 0.75];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
for (i, value) in SAMPLES.iter().enumerate() {
let x = i as f32 * 32.0;
canvas
.draw_rect(
Rect::new(x, 0.0, x + 32.0, 128.0),
&Paint::fill(Color::srgb(*value, *value, *value, 1.0))
.with_color_filter(ColorFilter::linear_to_srgb())
.with_anti_alias(false),
)
.expect("encoded");
}
let pixels = render(&mut ctx, canvas);
for (i, value) in SAMPLES.iter().enumerate() {
let want = (encode_srgb(*value) * 255.0).round() as i32;
let got = pixel(&pixels, i as u32 * 32 + 16, 64);
assert!(
(got[0] as i32 - want).abs() <= 2,
"linear {value} should encode to {want}, got {}. A power of 2.2 \
would give {} instead.",
got[0],
(value.powf(1.0 / 2.2) * 255.0).round() as i32
);
}
}
#[test]
fn the_gamma_pair_undo_each_other() {
let Some(mut ctx) = context() else { return };
const LINEAR: f32 = 0.35;
let encoded = encode_srgb(LINEAR);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::new(0.0, 0.0, 64.0, 128.0),
&Paint::fill(Color::srgb(LINEAR, LINEAR, LINEAR, 1.0))
.with_color_filter(ColorFilter::linear_to_srgb())
.with_anti_alias(false),
)
.expect("encoded");
canvas
.draw_rect(
Rect::new(64.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::srgb(encoded, encoded, encoded, 1.0))
.with_color_filter(ColorFilter::srgb_to_linear())
.with_anti_alias(false),
)
.expect("decoded");
let pixels = render(&mut ctx, canvas);
let left = pixel(&pixels, 32, 64);
let right = pixel(&pixels, 96, 64);
let want_left = (encoded * 255.0).round() as i32;
let want_right = (decode_srgb(encoded) * 255.0).round() as i32;
assert_eq!(
want_right,
(LINEAR * 255.0).round() as i32,
"the host curve does not round-trip, so the test itself is wrong"
);
assert!(
(left[0] as i32 - want_left).abs() <= 2,
"encoding {LINEAR} should give {want_left}, got {left:?}"
);
assert!(
(right[0] as i32 - want_right).abs() <= 2,
"decoding {encoded} should give back {want_right}, got {right:?}. \
The two directions are not inverses."
);
}
#[test]
fn the_gamma_filter_curves_color_and_leaves_alpha_alone() {
let Some(mut ctx) = context() else { return };
const LINEAR: f32 = 0.25;
const ALPHA: f32 = 0.5;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::srgb(LINEAR, LINEAR, LINEAR, ALPHA))
.with_color_filter(ColorFilter::linear_to_srgb())
.with_anti_alias(false),
)
.expect("filtered");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
let want = (encode_srgb(LINEAR) * ALPHA * 255.0).round() as i32;
assert!(
(got[3] as i32 - (ALPHA * 255.0).round() as i32).abs() <= 2,
"alpha should pass through the curve untouched, got {got:?}"
);
assert!(
(got[0] as i32 - want).abs() <= 2,
"the straight color should be curved and then premultiplied, which is \
{want}. Curving the premultiplied channel would give {} instead. Got \
{got:?}",
(encode_srgb(LINEAR * ALPHA) * 255.0).round() as i32
);
}
fn lit_span(pixels: &[u8], along_x: bool, fixed: u32) -> Option<(u32, u32)> {
let n = if along_x { SIZE.width } else { SIZE.height };
let lit: Vec<u32> = (0..n)
.filter(|i| {
let (x, y) = if along_x { (*i, fixed) } else { (fixed, *i) };
pixel(pixels, x, y)[0] > 127
})
.collect();
Some((*lit.first()?, *lit.last()?))
}
fn filtered_square(ctx: &mut Context, rect: Rect, filter: ImageFilter) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
rect,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_image_filter(filter),
)
.expect("drew");
render(ctx, canvas)
}
#[test]
fn dilating_grows_a_shape_by_the_radius_on_every_side() {
let Some(mut ctx) = context() else { return };
const RADIUS: f32 = 8.0;
let pixels = filtered_square(
&mut ctx,
Rect::new(40.0, 40.0, 88.0, 88.0),
ImageFilter::Dilate {
radius_x: RADIUS,
radius_y: RADIUS,
},
);
let r = RADIUS as u32;
assert_eq!(
lit_span(&pixels, true, 64),
Some((40 - r, 87 + r)),
"the square should grow by {r} to the left and right"
);
assert_eq!(
lit_span(&pixels, false, 64),
Some((40 - r, 87 + r)),
"and by {r} above and below"
);
}
#[test]
fn eroding_shrinks_a_shape_by_the_radius_on_every_side() {
let Some(mut ctx) = context() else { return };
const RADIUS: f32 = 8.0;
let pixels = filtered_square(
&mut ctx,
Rect::new(40.0, 40.0, 88.0, 88.0),
ImageFilter::Erode {
radius_x: RADIUS,
radius_y: RADIUS,
},
);
let r = RADIUS as u32;
assert_eq!(
lit_span(&pixels, true, 64),
Some((40 + r, 87 - r)),
"the square should lose {r} from each side"
);
assert_eq!(
lit_span(&pixels, false, 64),
Some((40 + r, 87 - r)),
"and {r} from the top and bottom"
);
}
#[test]
fn eroding_eats_an_edge_that_sits_against_the_layers_own_bound() {
let Some(mut ctx) = context() else { return };
const RADIUS: f32 = 8.0;
let pixels = filtered_square(
&mut ctx,
Rect::new(0.0, 0.0, 64.0, 64.0),
ImageFilter::Erode {
radius_x: RADIUS,
radius_y: RADIUS,
},
);
let r = RADIUS as u32;
assert_eq!(
lit_span(&pixels, true, 32),
Some((r, 63 - r)),
"the left edge is against the bound and should still be eaten into. \
Starting at zero means the filter read the border texel repeated."
);
}
#[test]
fn a_morphology_reaches_by_its_own_radius_along_each_axis() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer_bounds(
Layer::opacity(1.0).with_morphology(Morphology::dilate(12.0, 0.0)),
Rect::new(0.0, 0.0, 128.0, 128.0),
);
canvas
.draw_rect(
Rect::new(40.0, 40.0, 88.0, 88.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("drew");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
lit_span(&pixels, true, 64),
Some((28, 99)),
"twelve each way horizontally"
);
assert_eq!(
lit_span(&pixels, false, 64),
Some((40, 87)),
"and nothing at all vertically. Room to grow was left above and below, \
so growth here means the vertical pass took the horizontal radius."
);
}
#[test]
fn a_radius_past_one_pass_is_split_across_passes_and_stays_exact() {
let Some(mut ctx) = context() else { return };
let radius = MORPHOLOGY_TAPS as f32 + 4.0;
let pixels = filtered_square(
&mut ctx,
Rect::new(40.0, 40.0, 88.0, 88.0),
ImageFilter::Dilate {
radius_x: radius,
radius_y: 0.0,
},
);
let r = radius as u32;
assert_eq!(
lit_span(&pixels, true, 64),
Some((40 - r, 87 + r)),
"a radius of {r} should reach {r}, however many passes that takes"
);
}
#[test]
fn dilating_a_translucent_shape_spreads_its_coverage_with_its_color() {
let Some(mut ctx) = context() else { return };
const RADIUS: f32 = 8.0;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::new(40.0, 40.0, 88.0, 88.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 0.5))
.with_anti_alias(false)
.with_image_filter(ImageFilter::Dilate {
radius_x: RADIUS,
radius_y: RADIUS,
}),
)
.expect("drew");
let pixels = render(&mut ctx, canvas);
for (x, where_) in [(64, "the middle"), (36, "the ring the dilation added")] {
let got = pixel(&pixels, x, 64);
assert!(
(got[0] as i32 - 128).abs() <= 2,
"{where_} should be half-strength white over black, got {got:?}"
);
}
assert_eq!(
pixel(&pixels, 30, 64),
[0, 0, 0, 255],
"eight pixels is eight pixels"
);
}
#[test]
fn a_morphology_radius_is_a_whole_number_of_texels() {
let Some(mut ctx) = context() else { return };
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let below = filtered_square(
&mut ctx,
square,
ImageFilter::Dilate {
radius_x: 0.4,
radius_y: 0.4,
},
);
assert_eq!(
lit_span(&below, true, 64),
Some((40, 87)),
"four tenths of a texel is no texels, which is the shape unchanged"
);
let above = filtered_square(
&mut ctx,
square,
ImageFilter::Dilate {
radius_x: 0.6,
radius_y: 0.6,
},
);
assert_eq!(
lit_span(&above, true, 64),
Some((39, 88)),
"six tenths is one texel, applied and allowed for in the bounds"
);
}
#[test]
fn composing_two_filters_applies_the_inner_one_first() {
let Some(mut ctx) = context() else { return };
let pixels = filtered_square(
&mut ctx,
Rect::new(48.0, 48.0, 80.0, 80.0),
ImageFilter::compose(
ImageFilter::Dilate {
radius_x: 8.0,
radius_y: 8.0,
},
ImageFilter::Dilate {
radius_x: 4.0,
radius_y: 4.0,
},
),
);
assert_eq!(
lit_span(&pixels, true, 64),
Some((36, 91)),
"twelve each way, which is the two radii together. Twelve from one side \
only would mean the outer layer cropped what the inner one grew."
);
}
#[test]
fn composing_a_move_covers_both_where_it_drew_and_where_it_landed() {
let Some(mut ctx) = context() else { return };
let move_right = ImageFilter::Matrix {
transform: Affine2::from_translation(Vec2::new(32.0, 0.0)).into(),
};
let grow = ImageFilter::Dilate {
radius_x: 8.0,
radius_y: 0.0,
};
let after = filtered_square(
&mut ctx,
Rect::new(24.0, 48.0, 56.0, 80.0),
ImageFilter::compose(grow.clone(), move_right.clone()),
);
assert_eq!(
lit_span(&after, true, 64),
Some((48, 95)),
"moved to 56..87 and then grown by eight each way"
);
let before = filtered_square(
&mut ctx,
Rect::new(24.0, 48.0, 56.0, 80.0),
ImageFilter::compose(move_right, grow),
);
assert_eq!(
lit_span(&before, true, 64),
Some((48, 95)),
"grown to 16..63 and then moved right by thirty-two"
);
}
#[test]
fn composing_with_a_filter_that_does_nothing_is_the_other_filter() {
let plain = ImageFilter::blur(4.0);
assert_eq!(
ImageFilter::compose(plain.clone(), ImageFilter::None),
plain,
"an inner filter that does nothing leaves the outer one alone"
);
assert_eq!(
ImageFilter::compose(ImageFilter::None, plain.clone()),
plain,
"and so does an outer one"
);
assert!(
ImageFilter::compose(ImageFilter::None, ImageFilter::None).is_identity(),
"two of them are still nothing"
);
assert_eq!(
ImageFilter::compose(
plain.clone(),
ImageFilter::Dilate {
radius_x: 0.0,
radius_y: 0.0
}
),
plain,
"a radius of zero is a filter that does nothing"
);
let small = ImageFilter::Dilate {
radius_x: 0.2,
radius_y: 0.2,
};
assert!(
!small.is_identity(),
"a small positive radius is a filter until a scale says otherwise"
);
assert_ne!(
ImageFilter::compose(plain.clone(), small),
plain,
"so composing with it keeps both halves"
);
}
#[test]
fn composing_an_erosion_with_a_dilation_depends_on_which_runs_first() {
let Some(mut ctx) = context() else { return };
const RADIUS: f32 = 5.0;
let mut builder = PathBuilder::new();
builder
.move_to(Vec2::new(32.0, 32.0))
.line_to(Vec2::new(96.0, 32.0))
.line_to(Vec2::new(96.0, 60.0))
.line_to(Vec2::new(112.0, 60.0))
.line_to(Vec2::new(112.0, 68.0))
.line_to(Vec2::new(96.0, 68.0))
.line_to(Vec2::new(96.0, 96.0))
.line_to(Vec2::new(32.0, 96.0))
.close();
let spiked = builder.build();
let erode = ImageFilter::Erode {
radius_x: RADIUS,
radius_y: RADIUS,
};
let dilate = ImageFilter::Dilate {
radius_x: RADIUS,
radius_y: RADIUS,
};
let draw = |ctx: &mut Context, filter: ImageFilter| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_path(
&spiked,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_image_filter(filter),
)
.expect("drew");
render(ctx, canvas)
};
let opened = draw(
&mut ctx,
ImageFilter::compose(dilate.clone(), erode.clone()),
);
let (left, right) = lit_span(&opened, true, 64).expect("the block survives an opening");
assert_eq!(left, 32, "an opening leaves the block where it was");
assert!(
right < 100,
"the spike is thinner than twice the radius and an opening should have \
taken it, but the row still reaches {right}"
);
let closed = draw(&mut ctx, ImageFilter::compose(erode, dilate));
let (left, right) = lit_span(&closed, true, 64).expect("the block survives a closing");
assert_eq!(left, 32, "a closing leaves the block where it was too");
assert!(
right > 105,
"a closing keeps the spike, and this row should still reach past 105. \
Reaching {right} means the erosion ran first, which is an opening."
);
}
fn step_image(left: u8, right: u8, alpha: u8) -> Vec<u8> {
let mut pixels = vec![0u8; 8 * 8 * 4];
for y in 0..8u32 {
for x in 0..8u32 {
let i = ((y * 8 + x) * 4) as usize;
let level = if x < 4 { left } else { right };
pixels[i..i + 4].copy_from_slice(&[level, level, level, alpha]);
}
}
pixels
}
fn drawn_at(ctx: &mut Context, texels: &[u8], sampling: Sampling) -> Vec<u8> {
let mut image = ctx
.create_image(Extent2D::new(8, 8), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, texels).expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_sampling(sampling)
.with_anti_alias(false),
)
.expect("image");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
}
#[test]
fn cubic_sampling_leaves_a_flat_image_exactly_flat() {
let Some(mut ctx) = context() else { return };
const LEVEL: u8 = 137;
let pixels = drawn_at(&mut ctx, &step_image(LEVEL, LEVEL, 255), Sampling::Cubic);
for x in [8u32, 16, 22, 64, 71, 120] {
assert_eq!(
pixel(&pixels, x, 64),
[LEVEL, LEVEL, LEVEL, 255],
"a flat image read at ({x}, 64) should be its own color exactly"
);
}
}
#[test]
fn cubic_sampling_overshoots_a_step_where_linear_cannot() {
let Some(mut ctx) = context() else { return };
const DARK: u8 = 64;
const LIGHT: u8 = 191;
let texels = step_image(DARK, LIGHT, 255);
let linear = drawn_at(&mut ctx, &texels, Sampling::Linear);
let cubic = drawn_at(&mut ctx, &texels, Sampling::Cubic);
let under = pixel(&cubic, 48, 64)[0];
let over = pixel(&cubic, 80, 64)[0];
assert!(
under < DARK,
"a cubic read a texel before the step should undershoot below {DARK}, \
got {under}"
);
assert!(
over > LIGHT,
"and a texel after it should overshoot above {LIGHT}, got {over}"
);
assert_eq!(
(pixel(&linear, 48, 64)[0], pixel(&linear, 80, 64)[0]),
(DARK, LIGHT),
"linear stays between the two levels, which is the whole contrast"
);
for x in 0..SIZE.width {
let got = pixel(&cubic, x, 64)[0];
assert!(
(DARK as i32 - 8..=LIGHT as i32 + 8).contains(&(got as i32)),
"cubic at ({x}, 64) rang out to {got}, far past what this curve does"
);
}
}
#[test]
fn cubic_sampling_keeps_a_translucent_image_premultiplied() {
let Some(mut ctx) = context() else { return };
let mut texels = step_image(0, 0, 0);
for y in 0..8u32 {
for x in 0..8u32 {
let i = ((y * 8 + x) * 4) as usize;
let texel: [u8; 4] = if x < 4 {
[200, 200, 200, 200]
} else {
[0, 0, 0, 255]
};
texels[i..i + 4].copy_from_slice(&texel);
}
}
let pixels = drawn_at(&mut ctx, &texels, Sampling::Cubic);
for x in 40..88u32 {
let got = pixel(&pixels, x, 64);
assert!(
got[0] as i32 <= got[3] as i32 + 1,
"at ({x}, 64) the color {} exceeds its own alpha {}, which the \
clamp at the end of the cubic read is there to prevent",
got[0],
got[3]
);
}
}
fn striped_image() -> Vec<u8> {
let mut texels = vec![0u8; 64 * 64 * 4];
for y in 0..64u32 {
for x in 0..64u32 {
let i = ((y * 64 + x) * 4) as usize;
let level = if x % 8 == 0 { 255 } else { 0 };
texels[i..i + 4].copy_from_slice(&[level, level, level, 255]);
}
}
texels
}
fn striped_at(ctx: &mut Context, side: f32, chained: bool, sampling: Sampling) -> Vec<u8> {
let extent = Extent2D::new(64, 64);
let mut image = if chained {
ctx.create_mipmapped_image(extent, PixelFormat::Rgba8Unorm)
} else {
ctx.create_image(extent, PixelFormat::Rgba8Unorm)
}
.expect("image");
ctx.write_image(&mut image, &striped_image())
.expect("upload");
let where_ = Rect::new(32.0, 32.0, 32.0 + side, 32.0 + side);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
where_,
&Paint::image(0, where_)
.with_sampling(sampling)
.with_anti_alias(false),
)
.expect("image");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
}
#[test]
fn mipmapped_sampling_reads_the_level_built_for_the_size_it_is_drawn_at() {
let Some(mut ctx) = context() else { return };
let linear = striped_at(&mut ctx, 8.0, false, Sampling::Linear);
let mipmapped = striped_at(&mut ctx, 8.0, true, Sampling::Mipmap);
for x in 32..40u32 {
assert_eq!(
pixel(&linear, x, 36)[0],
0,
"a linear read at eight texels per pixel misses every stripe, which \
is the aliasing this exists to fix"
);
let got = pixel(&mipmapped, x, 36)[0];
assert!(
(got as i32 - 32).abs() <= 2,
"at ({x}, 36) the mipmapped read should be the image's own average, \
which is 255 over 8, or 32. Got {got}"
);
}
}
#[test]
fn mipmapped_sampling_at_full_size_is_the_image_itself() {
let Some(mut ctx) = context() else { return };
let linear = striped_at(&mut ctx, 64.0, false, Sampling::Linear);
let mipmapped = striped_at(&mut ctx, 64.0, true, Sampling::Mipmap);
for x in 32..96u32 {
assert_eq!(
pixel(&mipmapped, x, 36),
pixel(&linear, x, 36),
"at ({x}, 36) a mipmapped read at full size differs from a linear one"
);
}
assert_eq!(
pixel(&mipmapped, 32, 36)[0],
255,
"the first column is a stripe and should be white"
);
assert_eq!(
pixel(&mipmapped, 33, 36)[0],
0,
"and the one beside it is not"
);
}
#[test]
fn mipmapped_sampling_magnified_is_still_the_largest_level() {
let Some(mut ctx) = context() else { return };
let mipmapped = striped_at(&mut ctx, 128.0, true, Sampling::Mipmap);
let linear = striped_at(&mut ctx, 128.0, false, Sampling::Linear);
for x in 32..96u32 {
assert_eq!(
pixel(&mipmapped, x, 36),
pixel(&linear, x, 36),
"at ({x}, 36) a magnified mipmapped read differs from a linear one"
);
}
assert_eq!(
pixel(&mipmapped, 32, 36)[0],
255,
"and the stripes are still there rather than averaged away"
);
}
#[test]
fn mipmapped_sampling_of_an_image_without_a_chain_is_linear() {
let Some(mut ctx) = context() else { return };
let unchained = striped_at(&mut ctx, 8.0, false, Sampling::Mipmap);
let linear = striped_at(&mut ctx, 8.0, false, Sampling::Linear);
for x in 32..40u32 {
assert_eq!(
pixel(&unchained, x, 36),
pixel(&linear, x, 36),
"at ({x}, 36) a mipmapped read of a one-level texture should be the \
linear read exactly"
);
}
}
#[test]
fn a_mip_chain_has_one_level_per_halving_of_the_longer_axis() {
use emblema::mip_levels_for;
assert_eq!(
mip_levels_for(Extent2D::new(1, 1)),
1,
"one texel is one level"
);
assert_eq!(mip_levels_for(Extent2D::new(64, 64)), 7);
assert_eq!(
mip_levels_for(Extent2D::new(100, 100)),
7,
"100 → 50 → 25 → 12 → 6 → 3 → 1"
);
assert_eq!(
mip_levels_for(Extent2D::new(8, 1)),
4,
"the longer axis decides, and the short one holds at a single texel"
);
assert_eq!(mip_levels_for(Extent2D::new(1, 8)), 4, "either way round");
}
#[test]
fn a_blur_is_measured_in_the_targets_axes_not_the_layers_own() {
let Some(mut ctx) = context() else { return };
const SIGMA: f32 = 5.0;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer_bounds(
Layer::opacity(1.0).with_blur(SIGMA),
Rect::new(0.0, 0.0, 128.0, 128.0),
);
canvas.translate(64.0, 64.0);
canvas.scale(2.0, 0.5);
canvas.rotate(0.6);
canvas
.draw_rect(
Rect::new(-3.0, -3.0, 3.0, 3.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)),
)
.expect("drew");
canvas.restore();
let pixels = render(&mut ctx, canvas);
let reach = |dx: i32, dy: i32| {
(1..60)
.find(|k| pixel(&pixels, (64 + dx * k) as u32, (64 + dy * k) as u32)[0] < 24)
.unwrap_or(60)
};
let (right, left, down, up) = (reach(1, 0), reach(-1, 0), reach(0, 1), reach(0, -1));
assert!(
(right - left).abs() <= 2 && (down - up).abs() <= 2,
"the halo should be centered: right {right}, left {left}, down {down}, up {up}"
);
assert!(
(right - down).abs() <= 2 && (left - up).abs() <= 2,
"the halo should reach the same distance horizontally and vertically. \
A blur taken in the layer's own coordinates would come out four times \
wider than tall here. Got right {right}, down {down}"
);
}
#[test]
fn a_blur_falls_off_like_a_gaussian_rather_than_like_a_box() {
let Some(mut ctx) = context() else { return };
const SIGMA: f32 = 5.0;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save_layer_bounds(
Layer::opacity(1.0).with_blur(SIGMA),
Rect::new(0.0, 0.0, 128.0, 128.0),
);
canvas
.draw_rect(
Rect::new(63.0, 0.0, 65.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("drew");
canvas.restore();
let pixels = render(&mut ctx, canvas);
let near = pixel(&pixels, 64 + 3, 64)[0] as f32;
let far = pixel(&pixels, 64 + 6, 64)[0] as f32;
assert!(
far > 1.0,
"the sample at ten pixels is {far}, too dark to take a ratio from"
);
let ratio = near / far;
let gaussian = (((6.0f32).powi(2) - (3.0f32).powi(2)) / (2.0 * SIGMA * SIGMA)).exp();
assert!(
(ratio - gaussian).abs() < 1.2,
"the falloff from five pixels to ten is a ratio of {ratio:.2}, where a \
Gaussian of sigma {SIGMA} gives {gaussian:.2}. Uniform weights over \
the same reach give one -- a flat profile rather than a curve."
);
}
#[test]
fn a_radial_gradient_of_no_radius_settles_on_the_stop_it_was_heading_for() {
let Some(mut ctx) = context() else { return };
let stops = [
GradientStop::new(Color::linear(1.0, 1.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 1.0, 0.0, 1.0), 1.0),
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_shader(Shader::RadialGradient {
center: Vec2::new(64.0, 64.0),
radius: 0.0,
stops: stops.to_vec(),
tile: TileMode::Clamp,
})
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
for (x, y) in [(2u32, 2u32), (64, 64), (126, 126), (2, 126), (100, 30)] {
assert_eq!(
pixel(&pixels, x, y),
[0, 255, 0, 255],
"at ({x}, {y}) a radius of zero should be the last stop everywhere"
);
}
}
#[test]
fn a_radial_gradient_of_no_radius_under_decal_draws_nothing() {
let Some(mut ctx) = context() else { return };
let stops = [
GradientStop::new(Color::linear(1.0, 1.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 1.0, 0.0, 1.0), 1.0),
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::srgb(0.2, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_shader(Shader::RadialGradient {
center: Vec2::new(64.0, 64.0),
radius: 0.0,
stops: stops.to_vec(),
tile: TileMode::Decal,
})
.with_blend(BlendMode::SrcOver)
.with_anti_alias(false),
)
.expect("gradient");
let pixels = render(&mut ctx, canvas);
let ground = pixel(&pixels, 64, 64);
assert_eq!(
ground[0], 51,
"the ground should show through, not a gradient: got {ground:?}"
);
}
#[test]
fn no_shader_puts_a_pixel_down_under_a_collapsed_transform() {
let Some(mut ctx) = context() else { return };
let stops = vec![
GradientStop::new(Color::linear(1.0, 1.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 1.0, 0.0, 1.0), 1.0),
];
let shaders: Vec<(&str, Shader)> = vec![
("solid", Shader::Solid(Color::linear(1.0, 0.0, 0.0, 1.0))),
(
"linear",
Shader::LinearGradient {
start: Vec2::ZERO,
end: Vec2::new(128.0, 128.0),
stops: stops.clone(),
tile: TileMode::Clamp,
},
),
(
"radial",
Shader::RadialGradient {
center: Vec2::new(64.0, 64.0),
radius: 40.0,
stops: stops.clone(),
tile: TileMode::Clamp,
},
),
(
"sweep",
Shader::SweepGradient {
center: Vec2::new(64.0, 64.0),
start_angle: 0.0,
end_angle: std::f32::consts::TAU,
stops: stops.clone(),
tile: TileMode::Clamp,
},
),
(
"conical",
Shader::ConicalGradient {
start_center: Vec2::new(40.0, 64.0),
start_radius: 0.0,
end_center: Vec2::new(64.0, 64.0),
end_radius: 50.0,
stops,
tile: TileMode::Clamp,
},
),
];
for (name, shader) in shaders {
for (how, transform) in [
("scale(0, 1)", Affine2::from_scale(Vec2::new(0.0, 1.0))),
("scale(1, 0)", Affine2::from_scale(Vec2::new(1.0, 0.0))),
("scale(0, 0)", Affine2::from_scale(Vec2::ZERO)),
] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
canvas.concat(transform);
let _ = canvas.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_shader(shader.clone()),
);
canvas.restore();
let pixels = render(&mut ctx, canvas);
let lit = pixels
.chunks_exact(4)
.filter(|texel| *texel != [0, 0, 0, 255])
.count();
assert_eq!(
lit, 0,
"a {name} paint under {how} put {lit} pixel(s) on the frame, \
where the shape it was drawn with has no area at all"
);
}
}
for (kind, how, transform) in [
(
"circle",
"scale(0, 1)",
Affine2::from_scale(Vec2::new(0.0, 1.0)),
),
(
"circle",
"scale(1, 0)",
Affine2::from_scale(Vec2::new(1.0, 0.0)),
),
("circle", "scale(0, 0)", Affine2::from_scale(Vec2::ZERO)),
(
"rounded rect",
"scale(0, 1)",
Affine2::from_scale(Vec2::new(0.0, 1.0)),
),
(
"rounded rect",
"scale(1, 0)",
Affine2::from_scale(Vec2::new(1.0, 0.0)),
),
(
"stroked circle",
"scale(0, 1)",
Affine2::from_scale(Vec2::new(0.0, 1.0)),
),
(
"stroked circle",
"scale(0, 0)",
Affine2::from_scale(Vec2::ZERO),
),
] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
canvas.concat(transform);
let white = Color::linear(1.0, 1.0, 1.0, 1.0);
let _ = match kind {
"circle" => canvas.draw_circle(Vec2::new(64.0, 64.0), 40.0, &Paint::fill(white)),
"rounded rect" => canvas.draw_rrect(
Rect::new(20.0, 20.0, 108.0, 108.0),
16.0,
&Paint::fill(white),
),
_ => canvas.draw_circle(Vec2::new(64.0, 64.0), 40.0, &Paint::stroke(white, 8.0)),
};
canvas.restore();
let pixels = render(&mut ctx, canvas);
let lit = pixels
.chunks_exact(4)
.filter(|texel| *texel != [0, 0, 0, 255])
.count();
assert_eq!(
lit, 0,
"a {kind} under {how} put {lit} pixel(s) on the frame, and that \
shape's coverage is computed from the inverted mapping rather \
than from tessellated geometry"
);
}
}
#[test]
fn a_composition_may_hold_a_composition_in_either_half() {
let Some(mut ctx) = context() else { return };
let dilate = |radius: f32| ImageFilter::Dilate {
radius_x: radius,
radius_y: 0.0,
};
let (a, b, c) = (dilate(4.0), dilate(8.0), dilate(2.0));
let flat = ImageFilter::compose(a.clone(), ImageFilter::compose(b.clone(), c.clone()));
let nested = ImageFilter::compose(ImageFilter::compose(a, b), c);
let span = |ctx: &mut Context, filter: ImageFilter| {
let pixels = filtered_square(ctx, Rect::new(48.0, 48.0, 80.0, 80.0), filter);
lit_span(&pixels, true, 64)
};
let right_bracketed = span(&mut ctx, flat);
let left_bracketed = span(&mut ctx, nested);
assert_eq!(
right_bracketed,
Some((34, 93)),
"three dilations of four, eight and two should reach fourteen each way"
);
assert_eq!(
left_bracketed, right_bracketed,
"the same three filters bracketed the other way gave a different \
picture, so how the caller nested them changed what was drawn"
);
}
#[test]
fn a_color_filter_can_be_half_of_an_image_filter_composition() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, filter: ImageFilter| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(40.0, 40.0, 88.0, 88.0),
&Paint::fill(Color::srgb(0.9, 0.3, 0.1, 1.0)).with_image_filter(filter),
)
.expect("rect");
render(ctx, canvas)
};
let gamma = || ImageFilter::Color(ColorFilter::srgb_to_linear());
let blur = || ImageFilter::blur(6.0);
let at = |p: &[u8], x: u32, y: u32| pixel(p, x, y);
let plain = shot(&mut ctx, ImageFilter::None);
let recolored = shot(&mut ctx, gamma());
assert_ne!(
at(&plain, 64, 64),
at(&recolored, 64, 64),
"a color filter used as an image filter changed nothing"
);
let mut through_paint = Canvas::new(SIZE);
through_paint.clear(Color::BLACK);
through_paint
.draw_rect(
Rect::new(40.0, 40.0, 88.0, 88.0),
&Paint::fill(Color::srgb(0.9, 0.3, 0.1, 1.0))
.with_color_filter(ColorFilter::srgb_to_linear()),
)
.expect("rect");
let through_paint = render(&mut ctx, through_paint);
let (a, b) = (at(&recolored, 64, 64), at(&through_paint, 64, 64));
let apart = a
.iter()
.zip(&b)
.map(|(x, y)| x.abs_diff(*y))
.max()
.unwrap_or(0);
assert!(
apart <= 1,
"the two spellings of one color filter should agree to the rounding of \
the extra store: {a:?} against {b:?}"
);
let blurred = shot(&mut ctx, blur());
for (label, filter) in [
("color outside blur", ImageFilter::compose(gamma(), blur())),
("blur outside color", ImageFilter::compose(blur(), gamma())),
] {
let composed = shot(&mut ctx, filter);
assert_ne!(
at(&composed, 40, 64),
at(&blurred, 40, 64),
"{label}: the color half of the composition did nothing"
);
assert!(
at(&composed, 34, 64)[0] > 4,
"{label}: the blur half of the composition did nothing"
);
}
}
#[test]
fn a_color_filter_recolors_what_a_runtime_effect_drew() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_FS_GLSL.to_string(),
})
.expect("register");
const R: f32 = 0.2126;
const G: f32 = 0.7152;
const B: f32 = 0.0722;
#[rustfmt::skip]
let luminance = ColorFilter::matrix([
R, G, B, 0.0, 0.0,
R, G, B, 0.0, 0.0,
R, G, B, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
]);
let draw = |ctx: &mut Context, filter: ColorFilter| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_shader(Shader::RuntimeEffect {
program,
uniforms: effect_uniforms(0.5),
images: Vec::new(),
})
.with_color_filter(filter)
.with_anti_alias(false),
)
.expect("effect");
render(ctx, canvas)
};
assert_eq!(
pixel(&draw(&mut ctx, ColorFilter::None), 64, 64),
[255, 0, 0, 255],
"the program should draw red without a filter, or this test is measuring \
something else"
);
let filtered = pixel(&draw(&mut ctx, luminance), 64, 64);
assert!(
(filtered[0] as i32 - 54).abs() <= 2 && filtered[0] == filtered[1],
"the luminance of red is 54 in all three channels, got {filtered:?}. \
Unchanged red means the filter was accepted and dropped"
);
}
#[test]
fn a_filter_blends_where_it_meets_the_frame_not_inside_its_own_layer() {
let Some(mut ctx) = context() else { return };
let ground = Color::linear(0.0, 1.0, 1.0, 1.0);
let shape = Rect::new(24.0, 24.0, 104.0, 104.0);
let draw = |ctx: &mut Context, paint: Paint| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(ground);
canvas.draw_rect(shape, &paint).expect("drew");
render(ctx, canvas)
};
let base = Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0))
.with_blend(BlendMode::Plus)
.with_anti_alias(false);
let unfiltered = pixel(&draw(&mut ctx, base.clone()), 64, 64);
assert_eq!(
unfiltered,
[255, 255, 255, 255],
"red under Plus over cyan is white before any filter is involved"
);
for (what, paint) in [
(
"a blur",
base.clone().with_image_filter(ImageFilter::blur(3.0)),
),
(
"a dilation",
base.clone().with_image_filter(ImageFilter::Dilate {
radius_x: 4.0,
radius_y: 4.0,
}),
),
("a mask blur", base.clone().with_mask_blur(4.0)),
(
"a solid mask blur",
base.clone()
.with_mask_blur(4.0)
.with_mask_blur_style(MaskBlurStyle::Solid),
),
] {
assert_eq!(
pixel(&draw(&mut ctx, paint), 64, 64),
unfiltered,
"{what} changed how the paint met the frame. Red rather than white \
means the blend ran inside the layer, against its transparent black"
);
}
}
fn square_mesh(color: Color) -> Vertices {
Vertices::full(
VertexMode::Triangles,
vec![
Vec2::new(34.0, 34.0),
Vec2::new(94.0, 34.0),
Vec2::new(94.0, 94.0),
Vec2::new(34.0, 94.0),
],
vec![],
vec![color; 4],
vec![0, 1, 2, 0, 2, 3],
)
.expect("mesh")
}
#[test]
fn an_image_filter_applies_to_a_mesh_as_it_does_to_a_shape() {
let Some(mut ctx) = context() else { return };
let mesh = square_mesh(Color::linear(1.0, 0.0, 0.0, 1.0));
let base = Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_anti_alias(false);
let draw = |ctx: &mut Context, paint: Paint| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.draw_vertices(&mesh, &paint).expect("mesh");
let pixels = render(ctx, canvas);
let lit: Vec<u32> = (0..SIZE.width)
.filter(|x| pixel(&pixels, *x, 64)[0] > 0 || pixel(&pixels, *x, 64)[1] > 0)
.collect();
(
*lit.first().expect("something drew"),
*lit.last().expect("something drew"),
)
};
assert_eq!(
draw(&mut ctx, base.clone()),
(34, 93),
"the mesh alone spans its own vertices"
);
assert_eq!(
draw(
&mut ctx,
base.clone().with_image_filter(ImageFilter::Dilate {
radius_x: 10.0,
radius_y: 10.0
})
),
(24, 103),
"a dilation of ten should reach ten further each way. The mesh's own \
span means the filter was dropped"
);
let (left, right) = draw(&mut ctx, base.with_image_filter(ImageFilter::blur(6.0)));
assert!(
left < 34 && right > 93,
"a blur should carry color past the mesh, but it spans {left}..{right}"
);
}
fn uncolored_concave_mesh() -> Vertices {
Vertices::indexed(
VertexMode::Triangles,
vec![
Vec2::new(34.0, 34.0),
Vec2::new(94.0, 34.0),
Vec2::new(94.0, 64.0),
Vec2::new(64.0, 64.0),
Vec2::new(64.0, 94.0),
Vec2::new(34.0, 94.0),
Vec2::new(34.0, 64.0),
],
vec![],
vec![0, 1, 2, 0, 2, 6, 6, 3, 4, 6, 4, 5],
)
.expect("mesh")
}
#[test]
fn a_mask_blur_over_a_mesh_the_paint_fills_matches_the_same_shape_as_a_path() {
let Some(mut ctx) = context() else { return };
let paint = || Paint::fill(Color::srgb(1.0, 1.0, 1.0, 1.0)).with_mask_blur(6.0);
let mut as_mesh = Canvas::new(SIZE);
as_mesh.clear(Color::BLACK);
as_mesh
.draw_vertices(&uncolored_concave_mesh(), &paint())
.expect("a mesh the paint fills takes a mask blur");
let mesh_pixels = render(&mut ctx, as_mesh);
let mut as_path = Canvas::new(SIZE);
as_path.clear(Color::BLACK);
as_path
.draw_path(&concave_path(Rect::new(34.0, 34.0, 94.0, 94.0)), &paint())
.expect("path");
let path_pixels = render(&mut ctx, as_path);
for (x, y) in [(50u32, 50u32), (64, 34), (64, 28), (34, 34)] {
let (mesh, path) = (pixel(&mesh_pixels, x, y), pixel(&path_pixels, x, y));
assert_eq!(
mesh, path,
"({x}, {y}): the mesh and the path should be the same picture"
);
}
let halo = pixel(&mesh_pixels, 64, 28);
assert!(
halo[0] > 4 && halo[0] < 240,
"nothing reached past the mesh, so nothing was blurred: {halo:?}"
);
}
#[test]
fn a_mask_blur_on_a_mesh_is_refused_rather_than_dropped() {
let Some(mut ctx) = context() else { return };
let _ = &mut ctx;
let mesh = square_mesh(Color::linear(1.0, 0.0, 0.0, 1.0));
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let outcome = canvas
.draw_vertices(
&mesh,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)).with_mask_blur(6.0),
)
.map(|_| ());
assert!(
matches!(outcome, Err(Error::Unsupported(_))),
"a mask blur on a mesh should be refused, got {outcome:?}"
);
}
#[test]
fn every_draw_that_takes_a_paint_honors_its_image_filter() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let white = Color::linear(1.0, 1.0, 1.0, 1.0);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut builder = PathBuilder::new();
builder
.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 88.0))
.line_to(Vec2::new(40.0, 88.0))
.close();
let path = builder.build();
let mesh = square_mesh(white);
let span = |ctx: &mut Context, name: &str, filter: ImageFilter| -> (u32, u32) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let paint = Paint::fill(white)
.with_anti_alias(false)
.with_image_filter(filter.clone());
match name {
"draw_path" => canvas.draw_path(&path, &paint).map(|_| ()),
"draw_rect" => canvas.draw_rect(square, &paint).map(|_| ()),
"draw_rrect" => canvas.draw_rrect(square, 8.0, &paint).map(|_| ()),
"draw_circle" => canvas
.draw_circle(Vec2::new(64.0, 64.0), 24.0, &paint)
.map(|_| ()),
"draw_oval" => canvas
.draw_oval(Rect::new(40.0, 44.0, 88.0, 84.0), &paint)
.map(|_| ()),
"draw_drrect" => canvas
.draw_drrect(square, 8.0, Rect::new(56.0, 56.0, 72.0, 72.0), 4.0, &paint)
.map(|_| ()),
"draw_line" => canvas
.draw_line(
Vec2::new(40.0, 64.0),
Vec2::new(88.0, 64.0),
&Paint::stroke(white, 12.0).with_image_filter(filter.clone()),
)
.map(|_| ()),
"draw_points" => canvas
.draw_points(
PointMode::Points,
&[Vec2::new(64.0, 64.0)],
&Paint::fill(white)
.with_style(Style::Stroke(StrokeStyle {
cap: LineCap::Round,
..StrokeStyle::new(40.0)
}))
.with_image_filter(filter.clone()),
)
.map(|_| ()),
"draw_vertices" => canvas.draw_vertices(&mesh, &paint).map(|_| ()),
"draw_atlas" => canvas
.draw_atlas(
&[Sprite {
source: SourceRect {
x: 0.0,
y: 0.0,
width: 4.0,
height: 4.0,
},
color: white,
transform: Affine2::from_scale_angle_translation(
Vec2::splat(12.0),
0.0,
Vec2::new(40.0, 40.0),
),
}],
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(4.0, 4.0)).with_image_filter(filter.clone()),
)
.map(|_| ()),
"draw_image_nine" => canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
square,
&paint,
)
.map(|_| ()),
other => unreachable!("{other}"),
}
.unwrap_or_else(|e| panic!("{name}: {e}"));
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let lit: Vec<u32> = (0..SIZE.width)
.filter(|x| {
let texel = pixel(&pixels, *x, 64);
texel[0] > 0 || texel[1] > 0 || texel[2] > 0
})
.collect();
(
*lit.first().unwrap_or_else(|| panic!("{name} drew nothing")),
*lit.last().expect("drew nothing"),
)
};
for name in [
"draw_path",
"draw_rect",
"draw_rrect",
"draw_circle",
"draw_oval",
"draw_drrect",
"draw_line",
"draw_points",
"draw_vertices",
"draw_atlas",
"draw_image_nine",
] {
let (left, right) = span(&mut ctx, name, ImageFilter::None);
let filtered = span(
&mut ctx,
name,
ImageFilter::Dilate {
radius_x: 10.0,
radius_y: 10.0,
},
);
let (want_left, want_right) = (left - 10, right + 10);
assert!(
filtered.0.abs_diff(want_left) <= 1 && filtered.1.abs_diff(want_right) <= 1,
"{name} did not apply a dilation of ten: got {filtered:?}, wanted \
about ({want_left}, {want_right}). Its own unfiltered extent of \
({left}, {right}) means the filter was accepted and dropped"
);
}
ctx.destroy_image(image);
let clip = Rect::new(40.0, 40.0, 88.0, 88.0);
let edge = |ctx: &mut Context, filter: ImageFilter| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let _ = canvas.clip_rect(clip);
canvas
.draw_paint(
&Paint::fill(white)
.with_anti_alias(false)
.with_image_filter(filter),
)
.expect("paint");
pixel(&render(ctx, canvas), 41, 64)[0]
};
assert_eq!(
edge(&mut ctx, ImageFilter::None),
255,
"unfiltered, the fill meets the clip as a wall"
);
let blurred = edge(&mut ctx, ImageFilter::blur(6.0));
assert!(
blurred < 200,
"a blurred paint should soften on the inside of its clip, but the pixel \
beside the edge reads {blurred}"
);
}
#[test]
fn every_draw_that_takes_a_paint_honors_its_color_filter_and_blend() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &[255u8, 0, 0, 255].repeat(16))
.expect("upload");
let (atlas, glyph, _) = two_glyph_atlas();
let atlas_image = upload_atlas(&mut ctx, &atlas);
let glyph_run = [PositionedGlyph::new(
glyph,
[60.0, 60.0],
atlas.get(glyph).unwrap(),
)];
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 88.0))
.line_to(Vec2::new(40.0, 88.0))
.close();
let path = b.build();
let mesh = square_mesh(red);
let sample = |ctx: &mut Context,
name: &str,
adjust: &dyn Fn(Paint) -> Paint,
ground: Color|
-> [u8; 4] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(ground);
let paint = adjust(Paint::fill(red).with_anti_alias(false));
let img = adjust(Paint::image(0, Rect::from_size(4.0, 4.0)).with_anti_alias(false));
match name {
"draw_path" => canvas.draw_path(&path, &paint).map(|_| ()),
"draw_rect" => canvas.draw_rect(square, &paint).map(|_| ()),
"draw_rrect" => canvas.draw_rrect(square, 8.0, &paint).map(|_| ()),
"draw_circle" => canvas
.draw_circle(Vec2::new(64.0, 64.0), 24.0, &paint)
.map(|_| ()),
"draw_oval" => canvas.draw_oval(square, &paint).map(|_| ()),
"draw_drrect" => canvas
.draw_drrect(square, 8.0, Rect::new(80.0, 80.0, 86.0, 86.0), 1.0, &paint)
.map(|_| ()),
"draw_line" => canvas
.draw_line(
Vec2::new(40.0, 64.0),
Vec2::new(88.0, 64.0),
&adjust(Paint::stroke(red, 40.0)),
)
.map(|_| ()),
"draw_points" => canvas
.draw_points(
PointMode::Points,
&[Vec2::new(64.0, 64.0)],
&adjust(Paint::fill(red).with_style(Style::Stroke(StrokeStyle {
cap: LineCap::Round,
..StrokeStyle::new(48.0)
}))),
)
.map(|_| ()),
"draw_vertices" => canvas.draw_vertices(&mesh, &paint).map(|_| ()),
"draw_atlas" => canvas
.draw_atlas(
&[Sprite {
source: SourceRect {
x: 0.0,
y: 0.0,
width: 4.0,
height: 4.0,
},
color: Color::linear(1.0, 1.0, 1.0, 1.0),
transform: Affine2::from_scale_angle_translation(
Vec2::splat(12.0),
0.0,
Vec2::new(40.0, 40.0),
),
}],
Extent2D::new(4, 4),
&img,
)
.map(|_| ()),
"draw_image_nine" => canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
square,
&img,
)
.map(|_| ()),
"draw_paint" => {
let _ = canvas.clip_rect(square);
canvas.draw_paint(&paint).map(|_| ())
}
"draw_glyphs" => canvas
.draw_glyphs(&glyph_run, &atlas, 1, &paint)
.map(|_| ()),
other => unreachable!("{other}"),
}
.unwrap_or_else(|e| panic!("{name}: {e}"));
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("s");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image, &atlas_image])
.expect("d");
let px = ctx.read(&mut surface).expect("r");
ctx.destroy_surface(surface);
let i = ((64u32 * 128 + 64) * 4) as usize;
[px[i], px[i + 1], px[i + 2], px[i + 3]]
};
#[rustfmt::skip]
let half = ColorFilter::matrix([0.5,0.0,0.0,0.0,0.0, 0.0,0.5,0.0,0.0,0.0, 0.0,0.0,0.5,0.0,0.0, 0.0,0.0,0.0,1.0,0.0]);
let black = Color::linear(0.0, 0.0, 0.0, 1.0);
let cyan = Color::linear(0.0, 1.0, 1.0, 1.0);
for name in [
"draw_path",
"draw_rect",
"draw_rrect",
"draw_circle",
"draw_oval",
"draw_drrect",
"draw_line",
"draw_points",
"draw_vertices",
"draw_atlas",
"draw_image_nine",
"draw_paint",
"draw_glyphs",
] {
let plain = sample(&mut ctx, name, &|p| p, black);
let filtered = sample(&mut ctx, name, &|p: Paint| p.with_color_filter(half), black);
let blended = sample(
&mut ctx,
name,
&|p: Paint| p.with_blend(BlendMode::Plus),
cyan,
);
assert_eq!(
plain[0], 255,
"{name} should draw full red before anything is applied to it"
);
assert!(
(filtered[0] as i32 - 128).abs() <= 2,
"{name} did not halve its color: {} rather than 128, which is the \
filter being accepted and dropped",
filtered[0]
);
assert_eq!(
blended,
[255, 255, 255, 255],
"{name} drew red over cyan under Plus and did not add. Red back \
means the blend was accepted and dropped"
);
}
ctx.destroy_image(image);
ctx.destroy_image(atlas_image);
}
#[test]
fn every_draw_that_takes_a_paint_applies_or_refuses_a_mask_blur() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &[255u8, 0, 0, 255].repeat(16))
.expect("upload");
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 88.0))
.line_to(Vec2::new(40.0, 88.0))
.close();
let path = b.build();
let mesh = square_mesh(red);
let edge = |ctx: &mut Context, name: &str, sigma: f32| -> std::result::Result<u8, String> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
let paint = Paint::fill(red)
.with_anti_alias(false)
.with_mask_blur(sigma);
let img = Paint::image(0, Rect::from_size(4.0, 4.0))
.with_anti_alias(false)
.with_mask_blur(sigma);
let r = match name {
"draw_path" => canvas.draw_path(&path, &paint).map(|_| ()),
"draw_rect" => canvas.draw_rect(square, &paint).map(|_| ()),
"draw_rrect" => canvas.draw_rrect(square, 8.0, &paint).map(|_| ()),
"draw_circle" => canvas
.draw_circle(Vec2::new(64.0, 64.0), 24.0, &paint)
.map(|_| ()),
"draw_oval" => canvas.draw_oval(square, &paint).map(|_| ()),
"draw_drrect" => canvas
.draw_drrect(square, 8.0, Rect::new(80.0, 80.0, 86.0, 86.0), 1.0, &paint)
.map(|_| ()),
"draw_line" => canvas
.draw_line(
Vec2::new(40.0, 64.0),
Vec2::new(88.0, 64.0),
&Paint::stroke(red, 40.0).with_mask_blur(sigma),
)
.map(|_| ()),
"draw_points" => canvas
.draw_points(
PointMode::Points,
&[Vec2::new(64.0, 64.0)],
&Paint::fill(red)
.with_style(Style::Stroke(StrokeStyle {
cap: LineCap::Round,
..StrokeStyle::new(48.0)
}))
.with_mask_blur(sigma),
)
.map(|_| ()),
"draw_vertices" => canvas.draw_vertices(&mesh, &paint).map(|_| ()),
"draw_atlas" => canvas
.draw_atlas(
&[Sprite {
source: SourceRect {
x: 0.0,
y: 0.0,
width: 4.0,
height: 4.0,
},
color: Color::linear(1.0, 1.0, 1.0, 1.0),
transform: Affine2::from_scale_angle_translation(
Vec2::splat(12.0),
0.0,
Vec2::new(40.0, 40.0),
),
}],
Extent2D::new(4, 4),
&img,
)
.map(|_| ()),
"draw_image_nine" => canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
square,
&img,
)
.map(|_| ()),
"draw_paint" => {
let _ = canvas.clip_rect(square);
canvas.draw_paint(&paint).map(|_| ())
}
other => unreachable!("{other}"),
};
if let Err(e) = r {
return Err(format!("{e}"));
}
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("s");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("d");
let px = ctx.read(&mut surface).expect("r");
ctx.destroy_surface(surface);
let i = ((64u32 * 128 + 42) * 4) as usize;
Ok(px[i])
};
const REFUSES: [&str; 3] = ["draw_vertices", "draw_atlas", "draw_image_nine"];
for name in [
"draw_path",
"draw_rect",
"draw_rrect",
"draw_circle",
"draw_oval",
"draw_drrect",
"draw_line",
"draw_points",
"draw_vertices",
"draw_atlas",
"draw_image_nine",
"draw_paint",
] {
let sharp = edge(&mut ctx, name, 0.0);
let soft = edge(&mut ctx, name, 8.0);
if REFUSES.contains(&name) {
assert!(
soft.is_err(),
"{name} reads its color from a texture, so a mask blur over it \
is a guess rather than a picture. It should be refused, not accepted"
);
continue;
}
let sharp = sharp.unwrap_or_else(|e| panic!("{name} without a blur: {e}"));
let soft = soft.unwrap_or_else(|e| panic!("{name} with a blur: {e}"));
assert_eq!(
sharp, 255,
"{name} should meet its own edge at full strength when nothing is \
blurring it"
);
assert!(
soft < sharp,
"{name} accepted a mask blur and drew the same {soft} it draws \
without one, which is the blur being dropped"
);
}
ctx.destroy_image(image);
}
#[test]
fn every_draw_that_takes_a_paint_obeys_the_transform_and_the_clip() {
let Some(mut ctx) = context() else { return };
let honors_scissor_when_multisampled = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let _ = canvas.clip_rect(Rect::new(56.0, 0.0, 128.0, 128.0));
canvas
.draw_line(
Vec2::new(40.0, 64.0),
Vec2::new(88.0, 64.0),
&Paint::stroke(Color::srgb(1.0, 1.0, 1.0, 1.0), 40.0),
)
.expect("probe");
let pixels = render(&mut ctx, canvas);
pixel(&pixels, 55, 64) == [0, 0, 0, 255]
};
if !honors_scissor_when_multisampled {
eprintln!(
"skipping: this driver writes outside a scissor when the pass is \
multisampled, so the clip half of this test cannot run"
);
}
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &[255u8, 0, 0, 255].repeat(16))
.expect("upload");
let (atlas, glyph, _) = two_glyph_atlas();
let atlas_image = upload_atlas(&mut ctx, &atlas);
let glyph_run = [
PositionedGlyph::new(glyph, [40.0, 60.0], atlas.get(glyph).unwrap()),
PositionedGlyph::new(glyph, [80.0, 60.0], atlas.get(glyph).unwrap()),
];
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 88.0))
.line_to(Vec2::new(40.0, 88.0))
.close();
let path = b.build();
let mesh = square_mesh(red);
let span = |ctx: &mut Context, name: &str, setup: &dyn Fn(&mut Canvas)| -> (u32, u32) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
setup(&mut canvas);
let paint = Paint::fill(red).with_anti_alias(false);
let img = Paint::image(0, Rect::from_size(4.0, 4.0)).with_anti_alias(false);
match name {
"draw_path" => canvas.draw_path(&path, &paint).map(|_| ()),
"draw_rect" => canvas.draw_rect(square, &paint).map(|_| ()),
"draw_rrect" => canvas.draw_rrect(square, 8.0, &paint).map(|_| ()),
"draw_circle" => canvas
.draw_circle(Vec2::new(64.0, 64.0), 24.0, &paint)
.map(|_| ()),
"draw_oval" => canvas.draw_oval(square, &paint).map(|_| ()),
"draw_drrect" => canvas
.draw_drrect(square, 8.0, Rect::new(80.0, 80.0, 86.0, 86.0), 1.0, &paint)
.map(|_| ()),
"draw_line" => canvas
.draw_line(
Vec2::new(40.0, 64.0),
Vec2::new(88.0, 64.0),
&Paint::stroke(red, 40.0),
)
.map(|_| ()),
"draw_points" => canvas
.draw_points(
PointMode::Points,
&[Vec2::new(64.0, 64.0)],
&Paint::fill(red).with_style(Style::Stroke(StrokeStyle {
cap: LineCap::Round,
..StrokeStyle::new(48.0)
})),
)
.map(|_| ()),
"draw_vertices" => canvas.draw_vertices(&mesh, &paint).map(|_| ()),
"draw_atlas" => canvas
.draw_atlas(
&[Sprite {
source: SourceRect {
x: 0.0,
y: 0.0,
width: 4.0,
height: 4.0,
},
color: Color::linear(1.0, 1.0, 1.0, 1.0),
transform: Affine2::from_scale_angle_translation(
Vec2::splat(12.0),
0.0,
Vec2::new(40.0, 40.0),
),
}],
Extent2D::new(4, 4),
&img,
)
.map(|_| ()),
"draw_image_nine" => canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
square,
&img,
)
.map(|_| ()),
"draw_glyphs" => canvas
.draw_glyphs(&glyph_run, &atlas, 1, &paint)
.map(|_| ()),
other => unreachable!("{other}"),
}
.unwrap_or_else(|e| panic!("{name}: {e}"));
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("s");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image, &atlas_image])
.expect("d");
let px = ctx.read(&mut surface).expect("r");
ctx.destroy_surface(surface);
let lit: Vec<u32> = (0..128)
.filter(|x| {
let q = ((64u32 * 128 + x) * 4) as usize;
px[q] > 0
})
.collect();
(
lit.first().copied().unwrap_or(999),
lit.last().copied().unwrap_or(999),
)
};
let mut wedge = PathBuilder::new();
wedge
.move_to(Vec2::new(56.0, -40.0))
.line_to(Vec2::new(200.0, -40.0))
.line_to(Vec2::new(200.0, 200.0))
.line_to(Vec2::new(56.0, 200.0))
.close();
let wedge = wedge.build();
for name in [
"draw_path",
"draw_rect",
"draw_rrect",
"draw_circle",
"draw_oval",
"draw_drrect",
"draw_line",
"draw_points",
"draw_vertices",
"draw_atlas",
"draw_image_nine",
"draw_glyphs",
] {
let plain = span(&mut ctx, name, &|_| {});
assert_ne!(plain.0, 999, "{name} drew nothing to compare against");
let moved = span(&mut ctx, name, &|c: &mut Canvas| {
c.translate(16.0, 0.0);
});
assert_eq!(
moved,
(plain.0 + 16, plain.1 + 16),
"{name} did not move with the canvas transform"
);
let scissored = span(&mut ctx, name, &|c: &mut Canvas| {
let _ = c.clip_rect(Rect::new(56.0, 0.0, 128.0, 128.0));
});
assert!(
!honors_scissor_when_multisampled || scissored.0 >= 56 && scissored.1 == plain.1,
"{name} drew outside a rectangular clip: {scissored:?} where the \
clip begins at 56 and the drawing ends at {}",
plain.1
);
let stencilled = span(&mut ctx, name, &|c: &mut Canvas| {
let _ = c.clip_path(&wedge);
});
assert!(
stencilled.0 >= 56 && stencilled.1 == plain.1,
"{name} drew outside a stencil clip: {stencilled:?}. A rectangle \
narrows the scissor and anything else is tested per fragment, so \
one can hold while the other does not"
);
}
ctx.destroy_image(image);
ctx.destroy_image(atlas_image);
}
#[test]
fn every_material_draws_the_same_inside_a_layer_as_outside_one() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &[255u8, 0, 0, 255].repeat(16))
.expect("upload");
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let square = Rect::new(40.0, 40.0, 88.0, 88.0);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(40.0, 40.0))
.line_to(Vec2::new(88.0, 40.0))
.line_to(Vec2::new(88.0, 88.0))
.line_to(Vec2::new(40.0, 88.0))
.close();
let path = b.build();
let mesh = square_mesh(red);
let stops = vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
];
let render_with = |ctx: &mut Context, name: &str, layered: bool| -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
if layered {
canvas.save_layer_bounds(
Layer::opacity(1.0),
Rect::new(32.0, 32.0, 100.0, 100.0),
);
}
let paint = Paint::fill(red).with_anti_alias(false);
let img = Paint::image(0, Rect::from_size(4.0, 4.0)).with_anti_alias(false);
match name {
"solid rect" => canvas.draw_rect(square, &paint).map(|_| ()),
"path" => canvas.draw_path(&path, &paint).map(|_| ()),
"rrect" => canvas.draw_rrect(square, 12.0, &paint).map(|_| ()),
"circle" => canvas
.draw_circle(Vec2::new(64.0, 64.0), 24.0, &paint)
.map(|_| ()),
"linear gradient" => canvas
.draw_rect(
square,
&Paint::fill(red)
.with_anti_alias(false)
.with_shader(Shader::LinearGradient {
start: Vec2::new(40.0, 40.0),
end: Vec2::new(88.0, 88.0),
stops: stops.clone(),
tile: TileMode::Clamp,
}),
)
.map(|_| ()),
"radial gradient" => canvas
.draw_rect(
square,
&Paint::fill(red)
.with_anti_alias(false)
.with_shader(Shader::RadialGradient {
center: Vec2::new(64.0, 64.0),
radius: 24.0,
stops: stops.clone(),
tile: TileMode::Clamp,
}),
)
.map(|_| ()),
"sweep gradient" => canvas
.draw_rect(
square,
&Paint::fill(red)
.with_anti_alias(false)
.with_shader(Shader::SweepGradient {
center: Vec2::new(64.0, 64.0),
start_angle: 0.0,
end_angle: std::f32::consts::TAU,
stops: stops.clone(),
tile: TileMode::Clamp,
}),
)
.map(|_| ()),
"conical gradient" => canvas
.draw_rect(
square,
&Paint::fill(red)
.with_anti_alias(false)
.with_shader(Shader::ConicalGradient {
start_center: Vec2::new(50.0, 64.0),
start_radius: 0.0,
end_center: Vec2::new(64.0, 64.0),
end_radius: 24.0,
stops: stops.clone(),
tile: TileMode::Clamp,
}),
)
.map(|_| ()),
"image" => canvas.draw_rect(square, &img).map(|_| ()),
"mesh" => canvas.draw_vertices(&mesh, &paint).map(|_| ()),
"image nine" => canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
square,
&img,
)
.map(|_| ()),
other => unreachable!("{other}"),
}
.unwrap_or_else(|e| panic!("{name}: {e}"));
if layered {
canvas.restore();
}
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("s");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("d");
let px = ctx.read(&mut surface).expect("r");
ctx.destroy_surface(surface);
px
};
fn allowance(material: &str) -> i32 {
match material {
"solid rect" | "rrect" | "circle" => 8,
_ => 2,
}
}
for name in [
"solid rect",
"path",
"rrect",
"circle",
"linear gradient",
"radial gradient",
"sweep gradient",
"conical gradient",
"image",
"mesh",
"image nine",
] {
let direct = render_with(&mut ctx, name, false);
let layered = render_with(&mut ctx, name, true);
assert!(
direct.chunks_exact(4).any(|texel| texel != [0, 0, 0, 255]),
"{name} drew nothing, so this comparison says nothing"
);
let worst = direct
.iter()
.zip(&layered)
.map(|(a, b)| (*a as i32 - *b as i32).abs())
.max()
.unwrap_or(0);
let allowed = allowance(name);
assert!(
worst <= allowed,
"{name} drew differently inside a layer than outside one, by {worst} \
where {allowed} is allowed. A layer is a target of another size and \
origin, so a material whose mapping assumed the frame comes out \
wrong in one"
);
}
ctx.destroy_image(image);
}
#[test]
fn a_glyph_run_takes_an_image_filter() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, _) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let run = [PositionedGlyph::new(
solid,
[48.0, 48.0],
atlas.get(solid).unwrap(),
)];
let span = |ctx: &mut Context, paint: &Paint| -> (i32, i32) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.draw_glyphs(&run, &atlas, 0, paint).expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let mut low = i32::MAX;
let mut high = -1;
for y in 0..SIZE.height {
for x in 0..SIZE.width {
if pixel(&pixels, x, y)[0] > 0 {
low = low.min(x as i32);
high = high.max(x as i32);
}
}
}
(low, high)
};
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let plain = span(&mut ctx, &Paint::fill(red));
assert_eq!(plain, (48, 55), "the fixture glyph is eight texels wide");
let dilated = span(
&mut ctx,
&Paint::fill(red).with_image_filter(ImageFilter::Dilate {
radius_x: 10.0,
radius_y: 10.0,
}),
);
assert_eq!(
dilated,
(38, 65),
"a dilation of ten should reach ten further each way. The glyph's own \
extent means the filter was accepted and dropped"
);
let blurred = span(
&mut ctx,
&Paint::fill(red).with_image_filter(ImageFilter::blur(5.0)),
);
assert!(
blurred.0 < 48 && blurred.1 > 55,
"a blur should carry the glyph past its own box, but it spans {blurred:?}"
);
ctx.destroy_image(image);
}
#[test]
fn a_glyph_run_takes_all_four_mask_blur_styles() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, other) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let run = [
PositionedGlyph::new(solid, [30.0, 48.0], atlas.get(solid).unwrap()),
PositionedGlyph::new(other, [92.0, 48.0], atlas.get(other).unwrap()),
];
let look = |ctx: &mut Context, paint: &Paint| -> (u8, u8, usize) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.draw_glyphs(&run, &atlas, 0, paint).expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
let mut lit = 0;
for y in 0..SIZE.height {
for x in 0..SIZE.width {
if pixel(&pixels, x, y)[0] > 0 {
lit += 1;
}
}
}
(pixel(&pixels, 33, 51)[0], pixel(&pixels, 26, 51)[0], lit)
};
let red = Color::linear(1.0, 0.0, 0.0, 1.0);
let (sharp_center, sharp_halo, sharp_lit) = look(&mut ctx, &Paint::fill(red));
assert_eq!(
(sharp_center, sharp_halo),
(255, 0),
"the first fixture glyph is a solid block with nothing around it"
);
assert!(
sharp_lit > 64,
"only {sharp_lit} lit, which is one glyph rather than two"
);
let masked = |style: MaskBlurStyle| {
Paint::fill(red)
.with_mask_blur(5.0)
.with_mask_blur_style(style)
};
let (center, halo, lit) = look(&mut ctx, &masked(MaskBlurStyle::Normal));
assert!(
center < 255 && center > 0,
"normal softens the middle, got {center}"
);
assert!(halo > 0, "normal reaches outside the glyph, got {halo}");
assert!(
lit > sharp_lit * 4,
"normal covers far more than the glyph did"
);
let (center, halo, _) = look(&mut ctx, &masked(MaskBlurStyle::Solid));
assert_eq!(center, 255, "solid keeps the glyph itself at full strength");
assert!(halo > 0, "and still puts the blur outside it, got {halo}");
let (center, halo, _) = look(&mut ctx, &masked(MaskBlurStyle::Outer));
assert_eq!(center, 0, "outer removes the glyph and keeps only its halo");
assert!(halo > 0, "and the halo is what is left, got {halo}");
let (center, halo, lit) = look(&mut ctx, &masked(MaskBlurStyle::Inner));
assert!(
center < 255 && center > 0,
"inner softens within the glyph, got {center}"
);
assert_eq!(halo, 0, "inner puts nothing outside the glyph, got {halo}");
assert_eq!(lit, sharp_lit, "and covers exactly what the glyph covered");
ctx.destroy_image(image);
}
fn ramped_stops(hue: usize) -> Vec<GradientStop> {
(0..=MAX_STOPS + 2)
.map(|i| {
let t = i as f32 / (MAX_STOPS + 2) as f32;
let color = match hue {
0 => Color::srgb(t, 1.0 - t, 0.5, 1.0),
_ => Color::srgb(0.5, t * 0.2, 1.0 - t, 1.0),
};
GradientStop::new(color, t)
})
.collect()
}
#[test]
fn a_recording_drawn_into_another_keeps_its_own_layers_and_ramps() {
let Some(mut ctx) = context() else { return };
let mut inner = Canvas::new(Extent2D::new(64, 64));
inner.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
inner.save_layer_bounds(Layer::opacity(0.5), Rect::new(0.0, 0.0, 64.0, 64.0));
inner
.draw_rect(
Rect::new(4.0, 4.0, 60.0, 60.0),
&Paint::fill(Color::srgb(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("picture layer");
inner.restore();
inner
.draw_rect(
Rect::new(8.0, 24.0, 56.0, 40.0),
&Paint::fill(Color::srgb(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_shader(Shader::LinearGradient {
start: Vec2::new(8.0, 24.0),
end: Vec2::new(56.0, 40.0),
stops: ramped_stops(0),
tile: TileMode::Clamp,
}),
)
.expect("picture gradient");
let picture = inner.finish();
assert_eq!(
(picture.passes.len(), picture.ramps.len()),
(2, 1),
"the picture should carry a layer and a ramp, or this proves nothing"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.05, 0.05, 0.05, 1.0));
canvas.save_layer_bounds(Layer::opacity(1.0), Rect::new(0.0, 0.0, 20.0, 20.0));
canvas
.draw_rect(
Rect::new(2.0, 2.0, 18.0, 18.0),
&Paint::fill(Color::linear(0.0, 1.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("host layer");
canvas.restore();
canvas
.draw_rect(
Rect::new(0.0, 108.0, 128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_shader(Shader::LinearGradient {
start: Vec2::new(0.0, 108.0),
end: Vec2::new(128.0, 128.0),
stops: ramped_stops(1),
tile: TileMode::Clamp,
}),
)
.expect("host gradient");
canvas.save();
canvas.translate(40.0, 30.0);
canvas
.draw_recording(&picture, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("recording");
canvas.restore();
let combined = canvas.finish();
assert_eq!(
(combined.passes.len(), combined.ramps.len()),
(4, 2),
"the picture's passes and ramps should have been appended, not merged"
);
let pixels = render_recording(&mut ctx, &combined);
assert_eq!(
pixel(&pixels, 10, 10),
[0, 255, 0, 255],
"the host's layer changed when a picture was drawn beside it"
);
let host_ramp = pixel(&pixels, 64, 118);
assert!(
host_ramp[0] > 100 && host_ramp[1] < 60,
"the host's gradient should still run through its own stops, got \
{host_ramp:?}. A high green would be the picture's ramp"
);
let inside = pixel(&pixels, 60, 50);
assert!(
inside[0] > 100 && inside[0] < 180 && inside[1] < 40,
"the picture's layer should be red at half opacity over the ground, \
got {inside:?}. Full red would mean it sampled the wrong pass"
);
let picture_ramp = pixel(&pixels, 60, 62);
assert!(
picture_ramp[1] > 100,
"the picture's gradient should run through its own stops -- green \
rising as red falls -- and not the host's, whose green never passes a \
fifth. Got {picture_ramp:?}"
);
}
#[test]
fn a_recording_lands_where_the_transform_puts_it() {
let Some(mut ctx) = context() else { return };
let mut inner = Canvas::new(Extent2D::new(64, 64));
inner.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
inner
.draw_rect(
Rect::new(8.0, 8.0, 56.0, 56.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let picture = inner.finish();
let span = |ctx: &mut Context, place: &dyn Fn(&mut Canvas)| -> (u32, u32) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
place(&mut canvas);
canvas
.draw_recording(&picture, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("recording");
canvas.restore();
let pixels = render(ctx, canvas);
let lit: Vec<u32> = (0..SIZE.width)
.filter(|x| pixel(&pixels, *x, 40)[0] > 40)
.collect();
(
*lit.first().expect("the picture drew nothing"),
*lit.last().expect("the picture drew nothing"),
)
};
assert_eq!(
span(&mut ctx, &|_| {}),
(8, 55),
"a picture at the origin should land where it drew"
);
assert_eq!(
span(&mut ctx, &|c: &mut Canvas| {
c.translate(48.0, 0.0);
}),
(56, 103),
"a picture should move with the transform"
);
assert_eq!(
span(&mut ctx, &|c: &mut Canvas| {
c.translate(16.0, 0.0);
c.scale(1.5, 1.5);
}),
(27, 100),
"a picture scaled by half again should span half again as much"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
canvas.scale(0.0, 1.0);
canvas
.draw_recording(&picture, &Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0)))
.expect("collapsed");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert!(
pixels.chunks_exact(4).all(|texel| texel == [0, 0, 0, 255]),
"a picture under a collapsed transform should draw nothing at all"
);
}
#[test]
fn a_runtime_program_can_sample_more_than_one_texture() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_TWO_IMAGES_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_TWO_IMAGES_FS_GLSL.to_string(),
})
.expect("register");
let mut first = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("first");
ctx.write_image(&mut first, &[255u8, 0, 0, 255].repeat(16))
.expect("upload first");
let mut second = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("second");
ctx.write_image(&mut second, &[255u8, 128, 0, 255].repeat(16))
.expect("upload second");
let draw = |ctx: &mut Context, slots: &[u32]| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_anti_alias(false)
.with_shader(Shader::RuntimeEffect {
program,
uniforms: {
let mut out = vec![0.0; RUNTIME_FLOATS];
out[0..4].copy_from_slice(&[1.0, 1.0, 1.0, 1.0]);
out
},
images: slots.to_vec(),
}),
)
.expect("effect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&first, &second])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let both = pixel(&draw(&mut ctx, &[0, 1]), 64, 64);
assert!(
both[0] < 8 && (both[1] as i32 - 128).abs() <= 2 && both[2] < 8,
"the difference of the two textures should be half green, got {both:?}"
);
let same = pixel(&draw(&mut ctx, &[0, 0]), 64, 64);
assert_eq!(
same,
[0, 0, 0, 255],
"a texture differenced with itself is black; got {same:?}, which means \
the two bindings held different textures when they were told not to"
);
let one = pixel(&draw(&mut ctx, &[0]), 64, 64);
assert!(
one[1] > 200 && one[2] > 200,
"an undeclared second texture should read the white placeholder, whose \
difference from red is cyan. Got {one:?}"
);
ctx.destroy_image(first);
ctx.destroy_image(second);
}
#[test]
fn a_difference_clip_removes_the_rectangle_and_nothing_else() {
let Some(mut ctx) = context() else { return };
let lit = |ctx: &mut Context, setup: &dyn Fn(&mut Canvas)| -> usize {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.save();
setup(&mut canvas);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("fill");
canvas.restore();
render(ctx, canvas)
.chunks_exact(4)
.filter(|texel| texel[0] > 0)
.count()
};
let whole = lit(&mut ctx, &|_| {});
assert_eq!(whole, 16384, "the unclipped fill covers the frame");
let holed = lit(&mut ctx, &|c: &mut Canvas| {
c.clip_out_rect(Rect::new(48.0, 48.0, 80.0, 80.0))
.expect("out");
});
assert_eq!(
holed,
whole - 32 * 32,
"a difference clip should remove exactly the rectangle it names"
);
let both = lit(&mut ctx, &|c: &mut Canvas| {
c.clip_rect(Rect::new(24.0, 24.0, 104.0, 104.0))
.expect("in");
c.clip_out_rect(Rect::new(48.0, 48.0, 80.0, 80.0))
.expect("out");
});
assert_eq!(
both,
80 * 80 - 32 * 32,
"an intersect and a difference should compose to the one less the other"
);
let turned = lit(&mut ctx, &|c: &mut Canvas| {
c.rotate(0.4);
c.clip_out_rect(Rect::new(30.0, 10.0, 70.0, 50.0))
.expect("out");
c.rotate(-0.4);
});
assert_eq!(
turned,
whole - 40 * 40,
"a rotated difference clip should remove the quadrilateral's own area"
);
}
#[test]
fn the_ring_between_two_rounded_rectangles_is_hollow() {
let Some(mut ctx) = context() else { return };
let lit = |ctx: &mut Context, setup: &dyn Fn(&mut Canvas)| -> usize {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
setup(&mut canvas);
render(ctx, canvas)
.chunks_exact(4)
.filter(|texel| texel[0] > 0)
.count()
};
let paint = Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false);
let outer = Rect::new(16.0, 16.0, 112.0, 112.0);
let inner = Rect::new(48.0, 48.0, 80.0, 80.0);
let ring = lit(&mut ctx, &|c: &mut Canvas| {
c.draw_drrect(outer, 0.0, inner, 0.0, &paint).expect("ring");
});
assert_eq!(
ring,
96 * 96 - 32 * 32,
"the ring should be the outer rectangle less the inner one; a nonzero \
fill rule would leave it solid at {}",
96 * 96
);
for hollow in [
Rect::new(64.0, 64.0, 64.0, 64.0),
Rect::new(80.0, 80.0, 48.0, 48.0),
] {
let solid = lit(&mut ctx, &|c: &mut Canvas| {
c.draw_drrect(outer, 0.0, hollow, 0.0, &paint)
.expect("solid");
});
assert_eq!(
solid,
96 * 96,
"an inner rectangle of no area should leave the outer shape, got \
{solid} for {hollow:?}"
);
}
let rounded_outside = lit(&mut ctx, &|c: &mut Canvas| {
c.draw_drrect(outer, 24.0, inner, 0.0, &paint)
.expect("ring");
});
assert!(
rounded_outside < ring,
"rounding the outer rectangle should remove its corners, got \
{rounded_outside} against {ring}"
);
let rounded_inside = lit(&mut ctx, &|c: &mut Canvas| {
c.draw_drrect(outer, 0.0, inner, 12.0, &paint)
.expect("ring");
});
assert!(
rounded_inside > ring,
"rounding the hole should shrink it and so light more, got \
{rounded_inside} against {ring}"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_drrect(outer, 18.0, Rect::new(40.0, 40.0, 88.0, 88.0), 10.0, &paint)
.expect("ring");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[0, 0, 0, 255],
"the inner rectangle should be a hole"
);
assert!(
pixel(&pixels, 64, 28)[0] > 240,
"the band between them should be filled"
);
assert_eq!(
pixel(&pixels, 4, 4),
[0, 0, 0, 255],
"and nothing outside the outer one"
);
}
#[test]
fn a_mesh_takes_a_runtime_effect_unless_it_is_textured() {
let Some(mut ctx) = context() else { return };
let program = ctx
.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_FS_GLSL.to_string(),
})
.expect("register");
let mesh = Vertices::new(
VertexMode::Triangles,
vec![
Vec2::new(16.0, 112.0),
Vec2::new(112.0, 112.0),
Vec2::new(64.0, 16.0),
],
)
.expect("mesh");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_vertices(
&mesh,
&Paint::runtime_effect(program, effect_uniforms(0.0)).with_anti_alias(false),
)
.expect("effect on a mesh");
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 44, 100),
[255, 0, 0, 255],
"inside the triangle, left of the split"
);
close_enough(
pixel(&pixels, 84, 100),
[0, 178, 51, 255],
1,
"inside the triangle, right of it",
);
assert_eq!(
pixel(&pixels, 64, 8),
[0, 0, 0, 255],
"above the apex is outside the mesh"
);
assert_eq!(
pixel(&pixels, 20, 20),
[0, 0, 0, 255],
"and so is the corner the triangle does not reach"
);
let textured = Vertices::full(
VertexMode::Triangles,
vec![
Vec2::new(16.0, 112.0),
Vec2::new(112.0, 112.0),
Vec2::new(64.0, 16.0),
],
vec![Vec2::ZERO, Vec2::X, Vec2::Y],
Vec::new(),
vec![0, 1, 2],
)
.expect("mesh");
let mut canvas = Canvas::new(SIZE);
assert!(
canvas
.draw_vertices(
&textured,
&Paint::runtime_effect(program, effect_uniforms(0.0)),
)
.is_ok(),
"a textured mesh under an effect reads its coordinates as `uv`"
);
}
#[test]
fn a_skew_is_a_transform_class_of_its_own() {
let Some(mut ctx) = context() else { return };
let sheared = |ctx: &mut Context, k: f32, draw: &dyn Fn(&mut Canvas, &Paint)| -> usize {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save();
canvas.translate(64.0, 64.0);
let mut shear = Affine2::IDENTITY;
shear.matrix2.y_axis.x = k;
canvas.concat(shear);
canvas.translate(-64.0, -64.0);
draw(
&mut canvas,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
);
canvas.restore();
render(ctx, canvas)
.chunks_exact(4)
.filter(|texel| texel[0] > 0)
.count()
};
let square = Rect::new(48.0, 48.0, 80.0, 80.0);
for k in [0.0, 0.25, 0.5, 1.0] {
let lit = sheared(&mut ctx, k, &|c: &mut Canvas, p: &Paint| {
c.draw_rect(square, p).expect("fill");
});
assert_eq!(lit, 32 * 32, "a shear of {k} should preserve the area");
}
let where_lit = |ctx: &mut Context, k: f32, at: (u32, u32)| -> bool {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.translate(64.0, 64.0);
let mut shear = Affine2::IDENTITY;
shear.matrix2.y_axis.x = k;
canvas.concat(shear);
canvas.translate(-64.0, -64.0);
canvas
.draw_rect(
square,
&Paint::fill(Color::linear(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("fill");
pixel(&render(ctx, canvas), at.0, at.1)[0] > 0
};
for at in [(44, 52), (84, 76)] {
assert!(
where_lit(&mut ctx, 0.5, at),
"{at:?} is inside the sheared parallelogram"
);
assert!(
!where_lit(&mut ctx, 0.0, at),
"{at:?} is outside the upright square, so a shear that never \
reached the geometry would leave it dark"
);
}
let clipped = sheared(&mut ctx, 0.5, &|c: &mut Canvas, p: &Paint| {
c.clip_rect(square).expect("clip");
c.draw_rect(Rect::from_size(128.0, 128.0), p).expect("fill");
});
assert_eq!(
clipped,
32 * 32,
"a clip under a shear should admit the parallelogram, not its bounding \
box of {}",
48 * 32
);
for (radius, name) in [(0.0, "square corners"), (8.0, "rounded corners")] {
let upright = sheared(&mut ctx, 0.0, &|c: &mut Canvas, p: &Paint| {
c.draw_rrect(square, radius, p).expect("rrect");
});
let slanted = sheared(&mut ctx, 0.5, &|c: &mut Canvas, p: &Paint| {
c.draw_rrect(square, radius, p).expect("rrect");
});
assert!(
upright.abs_diff(slanted) * 100 <= upright,
"a sheared rounded rectangle with {name} should keep its area, got \
{slanted} against {upright}"
);
}
let upright = sheared(&mut ctx, 0.0, &|c: &mut Canvas, p: &Paint| {
c.draw_circle(Vec2::new(64.0, 64.0), 16.0, p)
.expect("circle");
});
let slanted = sheared(&mut ctx, 0.5, &|c: &mut Canvas, p: &Paint| {
c.draw_circle(Vec2::new(64.0, 16.0 + 48.0), 16.0, p)
.expect("circle");
});
assert!(
upright.abs_diff(slanted) * 100 <= upright,
"a sheared circle is an ellipse of the same area, got {slanted} \
against {upright}"
);
}
#[test]
fn an_atlas_batch_honors_the_paint_s_blend() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let sprite = |x: f32| {
let mut sprite = Sprite::new(
SourceRect::new(2.0, 2.0, 2.0, 2.0),
Affine2::from_scale_angle_translation(Vec2::splat(24.0), 0.0, Vec2::new(x, 40.0)),
);
sprite.color = Color::srgb(0.5, 0.5, 0.5, 1.0);
sprite
};
let sprites = [sprite(28.0), sprite(52.0)];
let overlap = |ctx: &mut Context, blend: BlendMode| -> [u8; 4] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_atlas(
&sprites,
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)).with_blend(blend),
)
.expect("atlas");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixel(&pixels, 60, 52)
};
let over = overlap(&mut ctx, BlendMode::SrcOver);
let plus = overlap(&mut ctx, BlendMode::Plus);
ctx.destroy_image(image);
assert!(
(100..160).contains(&over[0]),
"SrcOver should leave the top sprite's half brightness, got {over:?}"
);
assert!(
plus[0] > 230,
"Plus should add the two halves to full brightness, got {plus:?}"
);
}
fn receding(along_x: f32, along_y: f32) -> [f32; 16] {
[
1.0, 0.0, 0.0, along_x, 0.0, 1.0, 0.0, along_y, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
]
}
fn white_run(pixels: &[u8], row: u32) -> usize {
(0..SIZE.width)
.filter(|x| pixel(pixels, *x, row)[0] > 128)
.count()
}
fn rect_under(ctx: &mut Context, matrix: &[f32; 16]) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.concat_4x4(matrix);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
render(ctx, canvas)
}
#[test]
fn a_perspective_transform_makes_a_rectangle_a_trapezoid() {
let Some(mut ctx) = context() else { return };
let perspective = rect_under(&mut ctx, &receding(0.0, 0.004));
let near = white_run(&perspective, 20);
let far = white_run(&perspective, 70);
assert!(
near > far + 8,
"a receding plane must narrow: {near} wide near, {far} far"
);
let affine = rect_under(&mut ctx, &receding(0.0, 0.0));
assert_eq!(
white_run(&affine, 20),
white_run(&affine, 70),
"without perspective the two rows are the same width"
);
assert!(
perspective != affine,
"the perspective row changed no pixel"
);
}
#[test]
fn a_gradient_under_perspective_is_locked_to_the_shape() {
let Some(mut ctx) = context() else { return };
let matrix = receding(0.004, 0.0);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.concat_4x4(&matrix);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::WHITE)
.with_shader(Shader::LinearGradient {
start: Vec2::new(0.0, 0.0),
end: Vec2::new(128.0, 0.0),
stops: vec![
GradientStop::new(Color::BLACK, 0.0),
GradientStop::new(Color::WHITE, 1.0),
],
tile: TileMode::Clamp,
})
.with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let inverse = Transform2D::from_column_major_4x4(&matrix)
.inverse()
.expect("invertible");
let mut worst_projective = 0.0f32;
let mut worst_affine = 0.0f32;
for x in [10u32, 20, 30, 40, 50, 60] {
let measured = pixel(&pixels, x, 64)[0] as f32;
let user = inverse.project_point2(Vec2::new(x as f32 + 0.5, 64.5));
let projective = (user.x / 128.0).clamp(0.0, 1.0) * 255.0;
let affine = ((x as f32 + 0.5) / 128.0) * 255.0;
worst_projective = worst_projective.max((measured - projective).abs());
worst_affine = worst_affine.max((measured - affine).abs());
}
assert!(
worst_projective < 12.0,
"the gradient did not follow the transform: off by {worst_projective}"
);
assert!(
worst_affine > 24.0,
"the transform made no difference to the gradient, so this proves nothing"
);
}
#[test]
fn a_shape_across_the_vanishing_line_draws_its_near_half_and_no_more() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.concat_4x4(&receding(0.0, -0.01));
canvas
.draw_rect(
Rect::new(16.0, 0.0, 112.0, 400.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
let pixels = render(&mut ctx, canvas);
let lit = (0..SIZE.height)
.map(|y| white_run(&pixels, y))
.sum::<usize>();
let total = (SIZE.width * SIZE.height) as usize;
assert!(lit > 0, "the half in front of the vanishing line is drawn");
assert!(
lit < total,
"a shape crossing the vanishing line put the whole frame down"
);
for y in (0..SIZE.height).step_by(8) {
for x in (0..SIZE.width).step_by(8) {
let p = pixel(&pixels, x, y);
assert!(
p == [0, 0, 0, 255] || p == [255, 255, 255, 255],
"pixel at {x},{y} is {p:?}, which is neither the fill nor the background"
);
}
}
}
#[test]
fn a_layer_can_be_placed_by_a_matrix_that_carries_perspective() {
let Some(mut ctx) = context() else { return };
let placed = |ctx: &mut Context, along_x: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.save_layer(
Layer::opacity(1.0)
.with_matrix(Transform2D::from_column_major_4x4(&receding(along_x, 0.0))),
)
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
render(ctx, canvas)
};
let perspective = placed(&mut ctx, 0.006);
let flat = placed(&mut ctx, 0.0);
assert_eq!(
white_run(&flat, 32),
white_run(&flat, 96),
"without a perspective row the two rows match"
);
assert!(
perspective != flat,
"the perspective row moved no pixel of the finished layer"
);
let lit = (0..SIZE.height)
.map(|y| white_run(&perspective, y))
.sum::<usize>();
assert!(lit > 0, "the placed layer is visible");
assert!(
lit < (SIZE.width * SIZE.height) as usize,
"a placed layer put the whole frame down"
);
}
#[test]
fn a_textured_mesh_under_perspective_is_not_interpolated_flat() {
let Some(mut ctx) = context() else { return };
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
const SLOPE: f32 = 0.006;
let mesh = Vertices::indexed(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
Vec2::new(128.0, 128.0),
Vec2::new(0.0, 128.0),
],
vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(0.0, 1.0),
],
vec![0, 1, 2, 0, 2, 3],
)
.expect("mesh");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.concat_4x4(&receding(SLOPE, 0.0));
canvas
.draw_vertices(
&mesh,
&Paint::image(0, Rect::from_size(128.0, 128.0)).with_sampling(Sampling::Nearest),
)
.expect("mesh");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
let row = 8;
let seam = (0..SIZE.width)
.find(|x| {
let p = pixel(&pixels, *x, row);
p[1] > p[0] && p[3] == 255
})
.expect("the quad covers this row and both quadrants appear in it");
let correct = 64.0 / (1.0 + SLOPE * 64.0);
let flat = 64.0 / (1.0 + SLOPE * 128.0);
assert!(
(seam as f32 - correct).abs() <= 2.0,
"the seam is at {seam}, and the texture's midpoint maps to {correct}"
);
assert!(
(correct - flat).abs() > 6.0,
"this transform does not separate the two answers, so the test proves nothing"
);
}
#[test]
fn a_caller_can_assemble_the_mask_blur_a_gradient_is_refused() {
let Some(mut ctx) = context() else { return };
let whole = Rect::new(0.0, 0.0, 128.0, 128.0);
let masked = |ctx: &mut Context, sigma: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer_bounds(Layer::opacity(1.0), whole);
canvas
.draw_rect(
whole,
&Paint::fill(Color::WHITE).with_shader(Shader::LinearGradient {
start: Vec2::new(0.0, 0.0),
end: Vec2::new(128.0, 0.0),
stops: vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
}),
)
.expect("fill");
canvas.save_layer_bounds(
Layer::opacity(1.0)
.with_blur(sigma)
.with_blend(BlendMode::DstIn),
whole,
);
canvas
.draw_circle(Vec2::new(64.0, 64.0), 36.0, &Paint::fill(Color::WHITE))
.expect("coverage");
canvas.restore();
canvas.restore();
render(ctx, canvas)
};
let pixels = masked(&mut ctx, 6.0);
let sharp = masked(&mut ctx, 0.0);
let ramp = |image: &[u8]| {
(0..SIZE.width)
.filter(|x| {
let p = pixel(image, *x, 64);
let brightest = p[0].max(p[1]).max(p[2]);
brightest > 8 && brightest < 100
})
.count()
};
let left = pixel(&pixels, 40, 64);
let right = pixel(&pixels, 88, 64);
assert!(
left[0] > right[0] + 40 && right[2] > left[2] + 40,
"the gradient did not survive the mask: {left:?} against {right:?}"
);
assert!(
ramp(&pixels) > ramp(&sharp) + 8,
"the masked edge is {} pixels wide against {} unblurred, so the blur did \
not reach the coverage",
ramp(&pixels),
ramp(&sharp)
);
assert_eq!(pixel(&pixels, 4, 64), [0, 0, 0, 255], "beyond the blur");
}
type NamedDrawing = (&'static str, Box<dyn Fn(&mut Canvas)>);
#[test]
fn every_drawing_operation_answers_to_a_transform_with_perspective() {
let Some(mut ctx) = context() else { return };
let paint = Paint::fill(Color::WHITE).with_anti_alias(false);
let stroked = Paint::stroke(Color::WHITE, 6.0).with_anti_alias(false);
let square = Rect::new(24.0, 24.0, 104.0, 104.0);
let mut wedge = PathBuilder::new();
wedge
.move_to(Vec2::new(24.0, 104.0))
.line_to(Vec2::new(64.0, 24.0))
.line_to(Vec2::new(104.0, 104.0));
let wedge = wedge.build();
let operations: Vec<NamedDrawing> = vec![
("draw_path", {
let wedge = wedge.clone();
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_path(&wedge, &paint).expect("path");
})
}),
("draw_rect", {
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_rect(square, &paint).expect("rect");
})
}),
("draw_rrect", {
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_rrect(square, 16.0, &paint).expect("rrect");
})
}),
("draw_circle", {
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_circle(Vec2::new(64.0, 64.0), 40.0, &paint)
.expect("circle");
})
}),
("draw_oval", {
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_oval(Rect::new(20.0, 36.0, 108.0, 92.0), &paint)
.expect("oval");
})
}),
("draw_drrect", {
let paint = paint.clone();
Box::new(move |c: &mut Canvas| {
c.draw_drrect(square, 20.0, Rect::new(48.0, 48.0, 80.0, 80.0), 8.0, &paint)
.expect("drrect");
})
}),
("draw_line", {
let stroked = stroked.clone();
Box::new(move |c: &mut Canvas| {
c.draw_line(Vec2::new(16.0, 96.0), Vec2::new(112.0, 32.0), &stroked)
.expect("line");
})
}),
("draw_points", {
let stroked = stroked.clone();
Box::new(move |c: &mut Canvas| {
c.draw_points(
PointMode::Lines,
&[
Vec2::new(24.0, 32.0),
Vec2::new(104.0, 48.0),
Vec2::new(24.0, 80.0),
Vec2::new(104.0, 96.0),
],
&stroked,
)
.expect("points");
})
}),
("draw_shadow", {
let wedge = wedge.clone();
Box::new(move |c: &mut Canvas| {
c.draw_shadow(&wedge, Color::WHITE, 6.0, false)
.expect("shadow");
})
}),
("stroked path", {
let wedge = wedge.clone();
let stroked = stroked.clone();
Box::new(move |c: &mut Canvas| {
c.draw_path(&wedge, &stroked).expect("stroke");
})
}),
("draw_recording", {
let mut inner = Canvas::new(Extent2D::new(64, 64));
inner.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
inner
.draw_rect(
Rect::new(8.0, 8.0, 56.0, 56.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("rect");
let picture = inner.finish();
Box::new(move |c: &mut Canvas| {
c.draw_recording(&picture, &Paint::fill(Color::WHITE))
.expect("recording");
})
}),
];
for (name, draw) in operations {
let render_with = |ctx: &mut Context, slope: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.concat_4x4(&receding(slope, 0.0));
draw(&mut canvas);
render(ctx, canvas)
};
let perspective = render_with(&mut ctx, 0.006);
let flat = render_with(&mut ctx, 0.0);
assert!(
perspective.iter().any(|&v| v != 0),
"{name} drew nothing at all under perspective"
);
assert!(
perspective != flat,
"{name} renders the same with the perspective row dropped, so it is \
not carrying the transform it was given"
);
}
}
#[test]
fn a_glyph_run_answers_to_a_transform_with_perspective() {
let Some(mut ctx) = context() else { return };
let (atlas, solid, _) = two_glyph_atlas();
let image = upload_atlas(&mut ctx, &atlas);
let run = |ctx: &mut Context, slope: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas.concat_4x4(&receding(slope, 0.0));
let glyphs: Vec<PositionedGlyph> = (0..5)
.map(|i| {
PositionedGlyph::new(
solid,
[8.0 + i as f32 * 22.0, 56.0],
atlas.get(solid).unwrap(),
)
})
.collect();
canvas
.draw_glyphs(&glyphs, &atlas, 0, &Paint::fill(Color::WHITE))
.expect("glyphs");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let perspective = run(&mut ctx, 0.006);
let flat = run(&mut ctx, 0.0);
ctx.destroy_image(image);
assert!(
perspective.iter().any(|&v| v != 0),
"the run drew nothing under perspective"
);
assert_ne!(
perspective, flat,
"a glyph run renders the same with the perspective row dropped"
);
let lit: Vec<u32> = (0..SIZE.width)
.filter(|x| (0..SIZE.height).any(|y| pixel(&perspective, *x, y)[0] > 128))
.collect();
let gaps: Vec<u32> = lit
.windows(2)
.filter(|w| w[1] - w[0] > 1)
.map(|w| w[1] - w[0])
.collect();
assert!(
gaps.len() >= 3,
"expected several gaps between glyphs, found {gaps:?}"
);
assert!(
gaps.first() > gaps.last(),
"the gaps do not narrow toward the far side: {gaps:?}"
);
}
#[test]
fn a_gradient_carries_the_same_color_however_many_stops_state_it() {
let Some(mut ctx) = context() else { return };
let bright = Color::srgb(1.2, 0.0, 0.0, 1.0);
let ends = vec![
GradientStop::new(bright, 0.0),
GradientStop::new(Color::srgb(0.6, 0.0, 0.0, 1.0), 0.5),
GradientStop::new(Color::srgb(0.0, 0.0, 0.0, 1.0), 1.0),
];
let mut many = ends.clone();
for (offset, value) in [(0.25f32, 0.9f32), (0.75, 0.3)] {
many.push(GradientStop::new(Color::srgb(value, 0.0, 0.0, 1.0), offset));
}
many.sort_by(|a, b| a.offset.partial_cmp(&b.offset).unwrap());
assert!(ends.len() <= MAX_STOPS, "the control must be walked");
assert!(many.len() > MAX_STOPS, "the subject must be tabulated");
let halve = ColorFilter::matrix([
0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
]);
let render_with = |ctx: &mut Context, stops: Vec<GradientStop>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), stops)
.with_color_filter(halve)
.with_anti_alias(false),
)
.expect("gradient");
render(ctx, canvas)
};
let walked = render_with(&mut ctx, ends);
let tabulated = render_with(&mut ctx, many);
let mut worst = 0i32;
let mut at = 0u32;
for x in 0..128u32 {
let a = pixel(&walked, x, 64);
let b = pixel(&tabulated, x, 64);
for channel in 0..4 {
let delta = (a[channel] as i32 - b[channel] as i32).abs();
if delta > worst {
worst = delta;
at = x;
}
}
}
assert!(
worst <= 2,
"adding a stop that changes nothing changed the picture by {worst} at x={at}: \
walked {:?} against tabulated {:?}",
pixel(&walked, at, 64),
pixel(&tabulated, at, 64)
);
}
fn wide_pixels(ctx: &mut Context, canvas: Canvas) -> Vec<[f32; 4]> {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba16Float)
.expect("floating-point surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let bytes = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
unpack_half(&bytes)
}
fn unpack_half(bytes: &[u8]) -> Vec<[f32; 4]> {
bytes
.chunks_exact(8)
.map(|texel| {
let mut out = [0.0; 4];
for (channel, slot) in out.iter_mut().enumerate() {
let at = channel * 2;
*slot = half::f16::from_le_bytes([texel[at], texel[at + 1]]).to_f32();
}
out
})
.collect()
}
fn wide_pixels_with_images(
ctx: &mut Context,
canvas: Canvas,
images: &[&emblema::Image],
) -> Vec<[f32; 4]> {
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba16Float)
.expect("floating-point surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), images)
.expect("draw");
let bytes = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
unpack_half(&bytes)
}
fn wide_pixel(pixels: &[[f32; 4]], x: u32, y: u32) -> [f32; 4] {
pixels[(y * SIZE.width + x) as usize]
}
#[test]
fn a_color_outside_the_srgb_primaries_reaches_a_floating_point_target() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().float_render_targets {
eprintln!("skipping: this device cannot render into a floating-point target");
return;
}
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::display_p3(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let wide = wide_pixels(&mut ctx, canvas);
let inside = wide_pixel(&wide, 64, 64);
assert!((inside[0] - 1.093_066).abs() < 0.01, "red {}", inside[0]);
assert!((inside[1] + 0.226_742).abs() < 0.01, "green {}", inside[1]);
assert!((inside[2] + 0.150_137).abs() < 0.01, "blue {}", inside[2]);
assert!(inside[1] < -0.02, "green came back {}", inside[1]);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::display_p3(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let narrow = render(&mut ctx, canvas);
assert_eq!(pixel(&narrow, 64, 64), [255, 0, 0, 255]);
}
#[test]
fn a_wide_color_survives_a_layer_when_the_root_can_hold_it() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().float_render_targets {
eprintln!("skipping: this device cannot render into a floating-point target");
return;
}
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(Layer::opacity(1.0));
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::display_p3(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
canvas.restore();
let wide = wide_pixels(&mut ctx, canvas);
let inside = wide_pixel(&wide, 64, 64);
assert!(
inside[1] < -0.02,
"the layer flattened the color to {inside:?}"
);
assert!((inside[0] - 1.093_066).abs() < 0.02, "red {}", inside[0]);
}
#[test]
fn a_layer_that_asks_for_nothing_keeps_the_tones_of_what_it_holds() {
for preference in [BackendPreference::Vulkan, BackendPreference::Gles] {
let Ok(mut ctx) = Context::new(preference) else {
eprintln!("skipping {preference:?}: no such backend here");
continue;
};
for anti_alias in [false, true] {
tones_survive_a_layer(&mut ctx, anti_alias, preference);
}
}
}
fn tones_survive_a_layer(ctx: &mut Context, anti_alias: bool, backend: BackendPreference) {
let draw = |ctx: &mut Context, layered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if layered {
canvas.save_layer(Layer::opacity(1.0));
}
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::linear_gradient(
Vec2::ZERO,
Vec2::new(128.0, 0.0),
vec![
GradientStop::new(Color::linear(0.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.02, 0.02, 0.02, 1.0), 1.0),
],
)
.with_anti_alias(anti_alias),
)
.expect("gradient");
if layered {
canvas.restore();
}
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("srgb surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let direct = draw(ctx, false);
let layered = draw(ctx, true);
let distinct = |p: &[u8]| {
(0..128u32)
.map(|x| pixel(p, x, 64)[0])
.collect::<std::collections::BTreeSet<_>>()
.len()
};
let worst = (0..128u32)
.map(|x| (pixel(&direct, x, 64)[0] as i32 - pixel(&layered, x, 64)[0] as i32).abs())
.max()
.expect("a row");
assert!(
worst <= 2,
"{backend:?} with anti_alias {anti_alias}: a layer changed the picture by \
{worst} levels, {} distinct tones drawn directly against {} through the \
layer",
distinct(&direct),
distinct(&layered)
);
assert!(
distinct(&direct) > 20,
"the probe ramp resolved only {} tones, so it cannot show quantization",
distinct(&direct)
);
}
#[test]
fn a_mask_blur_over_a_gradient_matches_what_a_caller_would_assemble() {
let Some(mut ctx) = context() else { return };
let whole = Rect::new(0.0, 0.0, 128.0, 128.0);
let shader = Shader::LinearGradient {
start: Vec2::new(0.0, 0.0),
end: Vec2::new(128.0, 0.0),
stops: vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
};
let circle = (Vec2::new(64.0, 64.0), 36.0);
let sigma = 6.0;
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
circle.0,
circle.1,
&Paint::fill(Color::WHITE)
.with_shader(shader.clone())
.with_mask_blur(sigma),
)
.expect("the paint refused a mask blur over a gradient");
let built = render(&mut ctx, canvas);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer_bounds(Layer::opacity(1.0), whole);
canvas
.draw_rect(whole, &Paint::fill(Color::WHITE).with_shader(shader))
.expect("fill");
canvas.save_layer_bounds(
Layer::opacity(1.0)
.with_blur(sigma)
.with_blend(BlendMode::DstIn),
whole,
);
canvas
.draw_circle(circle.0, circle.1, &Paint::fill(Color::WHITE))
.expect("coverage");
canvas.restore();
canvas.restore();
let assembled = render(&mut ctx, canvas);
let mut worst = 0i32;
for y in (0..128u32).step_by(4) {
for x in (0..128u32).step_by(4) {
let a = pixel(&built, x, y);
let b = pixel(&assembled, x, y);
for channel in 0..4 {
worst = worst.max((a[channel] as i32 - b[channel] as i32).abs());
}
}
}
assert!(
worst <= 2,
"the paint and the hand-built arrangement disagree by {worst}"
);
let left = pixel(&built, 40, 64);
let right = pixel(&built, 88, 64);
assert!(
left[0] > right[0] + 40 && right[2] > left[2] + 40,
"the gradient did not survive: {left:?} against {right:?}"
);
}
#[test]
fn a_shear_is_no_obstacle_to_a_thin_stroke_and_zero_is_a_hairline() {
let Some(mut ctx) = context() else { return };
let sheared = |ctx: &mut Context, width: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mut skew = Affine2::IDENTITY;
skew.matrix2.y_axis.x = 0.5;
canvas.concat(skew);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(20.0, 20.0))
.line_to(Vec2::new(20.0, 100.0));
canvas
.draw_path(&b.build(), &Paint::stroke(Color::WHITE, width))
.expect("a stroke under a shear");
let pixels = render(ctx, canvas);
(0..128u32)
.flat_map(|x| (0..128u32).map(move |y| (x, y)))
.filter(|(x, y)| pixel(&pixels, *x, *y)[0] > 20)
.count()
};
let half = sheared(&mut ctx, 0.5);
assert!(
half > 40,
"half a pixel of width under a shear should still draw a line"
);
let none = sheared(&mut ctx, 0.0);
assert!(
none > 40,
"a width of zero is a hairline and should draw a line of its own, and \
lit {none} pixels against {half} for half a pixel of width"
);
let lit_at = |ctx: &mut Context, width: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_line(
Vec2::new(8.0, 64.0),
Vec2::new(120.0, 64.0),
&Paint::stroke(Color::WHITE, width),
)
.expect("a line");
let pixels = render(ctx, canvas);
pixel(&pixels, 64, 64)[0]
};
let at_zero = lit_at(&mut ctx, 0.0);
let just_above = lit_at(&mut ctx, 0.02);
assert!(
at_zero > 100,
"a hairline is drawn at full coverage, and came back at {at_zero}"
);
assert!(
just_above < 40,
"a fiftieth of a pixel is dimmed to nearly nothing, and came back at \
{just_above}"
);
}
#[test]
fn a_layer_draws_the_same_picture_whether_or_not_its_bounds_were_named() {
let Some(mut ctx) = context() else {
return;
};
let held = Rect::new(24.0, 24.0, 104.0, 104.0);
let content = |canvas: &mut Canvas| {
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
40.0,
&Paint::default().with_shader(Shader::RadialGradient {
center: Vec2::new(52.0, 58.0),
radius: 44.0,
stops: vec![
GradientStop {
offset: 0.0,
color: Color::srgb(1.0, 0.9, 0.2, 1.0),
},
GradientStop {
offset: 1.0,
color: Color::srgb(0.1, 0.2, 0.9, 1.0),
},
],
tile: TileMode::Clamp,
}),
)
.expect("a gradient inside the layer");
};
let mut unbounded = Canvas::new(SIZE);
unbounded.clear(Color::srgb(0.1, 0.1, 0.1, 1.0));
unbounded.save_layer(Layer::opacity(0.7).with_blur(6.0));
content(&mut unbounded);
unbounded.restore();
let loose = render(&mut ctx, unbounded);
let mut bounded = Canvas::new(SIZE);
bounded.clear(Color::srgb(0.1, 0.1, 0.1, 1.0));
bounded.save_layer_bounds(Layer::opacity(0.7).with_blur(6.0), held);
content(&mut bounded);
bounded.restore();
let tight = render(&mut ctx, bounded);
let max = (0..loose.len())
.map(|i| loose[i].abs_diff(tight[i]))
.max()
.unwrap_or(0);
assert!(
max <= 1,
"the two spellings differ by {max} levels, which is more than rounding"
);
}
#[test]
fn a_filtered_layer_with_no_bounds_is_sized_by_what_the_filter_reaches() {
let Some(mut ctx) = context() else {
return;
};
let sigma = 8.0;
let at = Vec2::new(64.0, 64.0);
let radius = 20.0;
let mut filtered = Canvas::new(SIZE);
filtered.clear(Color::BLACK);
filtered
.save_layer_filtered(Layer::opacity(1.0), None, &ImageFilter::blur(sigma))
.expect("a blur filters a group");
filtered
.draw_circle(at, radius, &Paint::fill(Color::WHITE))
.expect("content");
filtered.restore();
let recording = filtered.finish();
let extent = recording.passes[0].extent;
let mut plain = Canvas::new(SIZE);
plain.clear(Color::BLACK);
plain.save_layer(Layer::opacity(1.0));
plain
.draw_circle(at, radius, &Paint::fill(Color::WHITE))
.expect("content");
plain.restore();
let content_only = plain.finish().passes[0].extent;
assert!(
extent.width > content_only.width && extent.height > content_only.height,
"{extent:?} is no larger than the {content_only:?} the content alone needs, \
so the filter's reach was never added and its halo is cut"
);
assert!(
extent.width < SIZE.width && extent.height < SIZE.height,
"{extent:?} is the whole frame, so nothing was derived"
);
let through_filter = render_recording(&mut ctx, &recording);
let mut direct = Canvas::new(SIZE);
direct.clear(Color::BLACK);
direct.save_layer(Layer::opacity(1.0).with_blur(sigma));
direct
.draw_circle(at, radius, &Paint::fill(Color::WHITE))
.expect("content");
direct.restore();
let through_layer = render(&mut ctx, direct);
let worst = through_filter
.iter()
.zip(&through_layer)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(
worst <= 1,
"the two spellings of one blur disagree by {worst} levels"
);
}
#[test]
fn a_layer_multiplied_into_the_frame_zeroes_what_it_did_not_draw() {
let Some(mut ctx) = context() else {
return;
};
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas.save_layer(Layer::opacity(1.0).with_blend(BlendMode::Modulate));
canvas
.draw_rect(
Rect::new(48.0, 48.0, 80.0, 80.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("the layer's own content");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[255, 255, 255, 255],
"the layer's own content should have survived being multiplied by white"
);
for (x, y) in [(8, 8), (120, 8), (8, 120), (120, 120), (64, 16)] {
assert_eq!(
pixel(&pixels, x, y),
[0, 0, 0, 0],
"({x},{y}) was not multiplied, so the layer did not cover it"
);
}
}
#[test]
fn an_analytic_blurred_rectangle_agrees_with_the_blur_it_replaces() {
let Some(mut ctx) = context() else {
return;
};
for (radius, sigma, rect) in [
(16.0, 4.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(16.0, 8.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(0.0, 6.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(40.0, 5.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(4.0, 5.0, Rect::new(14.0, 54.0, 114.0, 74.0)),
(4.0, 5.0, Rect::new(54.0, 14.0, 74.0, 114.0)),
(2.0, 7.0, Rect::new(20.0, 60.0, 108.0, 68.0)),
(16.0, 12.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(16.0, 20.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
(16.0, 40.0, Rect::new(34.0, 30.0, 94.0, 98.0)),
] {
let paint = Paint::fill(Color::WHITE).with_mask_blur(sigma);
let mut analytic = Canvas::new(SIZE);
analytic.clear(Color::BLACK);
analytic.draw_rrect(rect, radius, &paint).expect("analytic");
let one = render(&mut ctx, analytic);
let reference = if radius > 0.0 {
rect.to_rounded_path_with_radii([[radius; 2]; 4])
} else {
square_path(rect)
};
let mut general = Canvas::new(SIZE);
general.clear(Color::BLACK);
let reach = ((sigma - 0.5) * 1.7320508f32).max(0.0).ceil();
general.save_layer_bounds(
Layer::opacity(1.0).with_blur(sigma),
Rect::new(
rect.left - reach,
rect.top - reach,
rect.right + reach,
rect.bottom + reach,
),
);
general
.draw_path(&reference, &Paint::fill(Color::WHITE))
.expect("general");
general.restore();
let two = render(&mut ctx, general);
let worst = one
.iter()
.zip(&two)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
let mean = one
.iter()
.zip(&two)
.map(|(a, b)| a.abs_diff(*b) as u64)
.sum::<u64>() as f64
/ one.len() as f64;
assert!(
worst <= 64,
"radius {radius} sigma {sigma}: the two routes differ by {worst} levels"
);
assert!(
mean <= 10.0,
"radius {radius} sigma {sigma}: the two routes differ by {mean:.2} on average"
);
assert!(
worst > 0,
"radius {radius} sigma {sigma}: the routes agree exactly, so the \
analytic one was not taken"
);
}
}
#[test]
fn an_analytic_blurred_rectangle_costs_no_passes() {
let paint = Paint::fill(Color::WHITE).with_mask_blur(6.0);
let rect = Rect::new(34.0, 30.0, 94.0, 98.0);
let mut analytic = Canvas::new(SIZE);
analytic.draw_rrect(rect, 16.0, &paint).expect("analytic");
assert_eq!(
analytic.finish().passes.len(),
1,
"a blurred rounded rectangle should not have opened a layer"
);
let mut mesh = Canvas::new(SIZE);
mesh.draw_path(&rect.to_rounded_path_with_radii([[16.0; 2]; 4]), &paint)
.expect("mesh");
assert_eq!(
mesh.finish().passes.len(),
1,
"a blurred convex outline should not have opened a layer"
);
let mut general = Canvas::new(SIZE);
general
.draw_path(&concave_path(rect), &paint)
.expect("general");
assert!(
general.finish().passes.len() > 1,
"the general route should still be drawing into a layer"
);
}
#[test]
fn a_blurred_oval_is_a_shadow_mesh_that_reads_as_its_blur() {
let oval = Rect::new(24.0, 44.0, 104.0, 84.0);
let sigma = 4.0;
let paint = Paint::fill(Color::WHITE).with_mask_blur(sigma);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.draw_oval(oval, &paint).expect("mesh");
let recording = canvas.finish();
assert_eq!(
recording.passes.len(),
1,
"a blurred oval should be one draw, not a layer and its blur passes"
);
let Some(mut ctx) = context() else { return };
let mut mesh = Canvas::new(SIZE);
mesh.clear(Color::BLACK);
mesh.draw_oval(oval, &paint).expect("mesh");
let mesh = render(&mut ctx, mesh);
let reach = ((sigma - 0.5) * 1.7320508f32).max(0.0).ceil();
let mut layer = Canvas::new(SIZE);
layer.clear(Color::BLACK);
layer.save_layer_bounds(
Layer::opacity(1.0).with_blur(sigma),
Rect::new(
oval.left - reach,
oval.top - reach,
oval.right + reach,
oval.bottom + reach,
),
);
layer
.draw_oval(oval, &Paint::fill(Color::WHITE))
.expect("layer");
layer.restore();
let layer = render(&mut ctx, layer);
assert!(pixel(&mesh, 64, 64)[0] > 250, "{:?}", pixel(&mesh, 64, 64));
assert_eq!(pixel(&mesh, 64, 20)[0], 0, "the shadow reached too far");
let edge = pixel(&mesh, 24, 64)[0];
assert!(edge > 60 && edge < 200, "the edge is not soft: {edge}");
let mean = mesh
.iter()
.zip(&layer)
.map(|(a, b)| a.abs_diff(*b) as u64)
.sum::<u64>() as f64
/ mesh.len() as f64;
assert!(
mean < 2.0,
"the mesh and the blurred layer should be the same shadow; the mean \
differs by {mean:.2} levels"
);
}
#[test]
fn the_two_halves_of_an_evaluated_blur_add_up_to_the_whole_of_it_too() {
let Some(mut ctx) = context() else {
return;
};
let draw = |ctx: &mut Context, style: MaskBlurStyle| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rrect(
Rect::new(34.0, 34.0, 94.0, 94.0),
8.0,
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 1.0))
.with_mask_blur(6.0)
.with_mask_blur_style(style),
)
.expect("mask blur");
render(ctx, canvas)
};
let normal = draw(&mut ctx, MaskBlurStyle::Normal);
let outer = draw(&mut ctx, MaskBlurStyle::Outer);
let inner = draw(&mut ctx, MaskBlurStyle::Inner);
let worst = (0..normal.len())
.filter(|i| i % 4 != 3)
.map(|i| (outer[i] as i32 + inner[i] as i32 - normal[i] as i32).unsigned_abs())
.max()
.unwrap_or(0);
assert!(
worst <= 4,
"the inner and outer halves should reconstruct the whole evaluated \
blur; they differ by {worst}"
);
}
#[test]
fn a_blur_under_an_anisotropic_transform_is_not_evaluated_analytically() {
let Some(mut ctx) = context() else {
return;
};
let rect = Rect::new(20.0, 20.0, 50.0, 44.0);
let paint = Paint::fill(Color::WHITE).with_mask_blur(5.0);
let mut through_rect = Canvas::new(SIZE);
through_rect.clear(Color::BLACK);
through_rect.scale(2.0, 1.0);
through_rect.draw_rect(rect, &paint).expect("rect");
let one = render(&mut ctx, through_rect);
let mut through_path = Canvas::new(SIZE);
through_path.clear(Color::BLACK);
through_path.scale(2.0, 1.0);
through_path
.draw_path(&square_path(rect), &paint)
.expect("path");
let two = render(&mut ctx, through_path);
let differing = (0..one.len()).filter(|&i| one[i] != two[i]).count();
assert_eq!(
differing, 0,
"{differing} channels differ, so the rectangle was evaluated analytically \
under a transform that stretches one axis"
);
}
#[test]
fn a_blur_under_perspective_is_not_evaluated_analytically() {
let Some(mut ctx) = context() else {
return;
};
let rect = Rect::new(30.0, 30.0, 90.0, 80.0);
let paint = Paint::fill(Color::WHITE).with_mask_blur(5.0);
let perspective = [
1.0, 0.0, 0.0, 0.0015, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
];
let mut through_rect = Canvas::new(SIZE);
through_rect.clear(Color::BLACK);
through_rect.concat_4x4(&perspective);
through_rect.draw_rect(rect, &paint).expect("rect");
let one = render(&mut ctx, through_rect);
let mut through_path = Canvas::new(SIZE);
through_path.clear(Color::BLACK);
through_path.concat_4x4(&perspective);
through_path
.draw_path(&square_path(rect), &paint)
.expect("path");
let two = render(&mut ctx, through_path);
let differing = (0..one.len()).filter(|&i| one[i] != two[i]).count();
assert_eq!(
differing, 0,
"{differing} channels differ, so the rectangle was evaluated analytically \
under a perspective transform"
);
}
#[test]
fn a_blurred_rectangle_is_the_same_turned_either_way() {
let Some(mut ctx) = context() else {
return;
};
let paint = Paint::fill(Color::WHITE).with_mask_blur(5.0);
let mut wide = Canvas::new(SIZE);
wide.clear(Color::BLACK);
wide.draw_rrect(Rect::new(14.0, 54.0, 114.0, 74.0), 4.0, &paint)
.expect("wide");
let wide = render(&mut ctx, wide);
let mut tall = Canvas::new(SIZE);
tall.clear(Color::BLACK);
tall.draw_rrect(Rect::new(54.0, 14.0, 74.0, 114.0), 4.0, &paint)
.expect("tall");
let tall = render(&mut ctx, tall);
let mut worst = 0u8;
for y in 0..SIZE.height {
for x in 0..SIZE.width {
let a = pixel(&wide, x, y);
let b = pixel(&tall, y, x);
for channel in 0..4 {
worst = worst.max(a[channel].abs_diff(b[channel]));
}
}
}
assert!(
worst <= 1,
"the wide rectangle and its transpose differ by {worst} levels, so the \
long-axis correction is not symmetric in the axes"
);
}
#[test]
fn an_evaluated_blur_serves_the_combining_styles_as_the_sampled_one_did() {
let Some(mut ctx) = context() else {
return;
};
let rect = Rect::new(34.0, 34.0, 94.0, 94.0);
let radius = 8.0;
for style in [
MaskBlurStyle::Solid,
MaskBlurStyle::Outer,
MaskBlurStyle::Inner,
] {
let paint = Paint::fill(Color::srgb(0.9, 0.4, 0.2, 1.0))
.with_mask_blur(6.0)
.with_mask_blur_style(style);
let mut evaluated = Canvas::new(SIZE);
evaluated.clear(Color::BLACK);
evaluated
.draw_rrect(rect, radius, &paint)
.expect("evaluated");
let one = render(&mut ctx, evaluated);
let mut sampled = Canvas::new(SIZE);
sampled.clear(Color::BLACK);
sampled
.draw_path(&rect.to_rounded_path_with_radii([[radius; 2]; 4]), &paint)
.expect("sampled");
let two = render(&mut ctx, sampled);
let worst = one
.iter()
.zip(&two)
.map(|(a, b)| a.abs_diff(*b))
.max()
.unwrap_or(0);
assert!(
worst <= 32,
"{style:?}: the evaluated and sampled halves differ by {worst} levels"
);
assert!(
worst > 0,
"{style:?}: identical, so the blurred half was not evaluated"
);
}
}
#[test]
fn a_mask_blurs_layer_is_sized_for_the_route_that_draws_into_it() {
let rect = Rect::new(44.0, 44.0, 84.0, 84.0);
let paint = Paint::fill(Color::WHITE)
.with_mask_blur(10.0)
.with_mask_blur_style(MaskBlurStyle::Outer);
let mut evaluated = Canvas::new(SIZE);
evaluated.draw_rrect(rect, 6.0, &paint).expect("evaluated");
let evaluated = evaluated.finish();
let mut sampled = Canvas::new(SIZE);
sampled
.draw_path(&square_path(rect), &paint)
.expect("sampled");
let sampled = sampled.finish();
let wide = evaluated.passes[0].extent;
let narrow = sampled.passes[0].extent;
assert!(
wide.width > narrow.width && wide.height > narrow.height,
"the evaluated route's layer is {wide:?} and the sampled route's is \
{narrow:?}; the first should be the wider, since its blur reaches \
further"
);
assert!(
narrow.width < 80,
"the sampled route's layer is {narrow:?}, which is the evaluated \
reach rather than its own"
);
}
#[test]
fn a_rounded_superellipse_leaves_the_side_earlier_than_a_circular_corner() {
let Some(mut ctx) = context() else { return };
let bounds = Rect::new(4.0, 4.0, 124.0, 124.0);
let radii: RoundingRadii = [[40.0, 40.0]; 4];
let mut render = |squircle: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::fill(Color::WHITE).with_anti_alias(false);
if squircle {
canvas
.draw_rsuperellipse(bounds, radii, &paint)
.expect("squircle");
} else {
canvas
.draw_rrect_with_radii(bounds, radii, &paint)
.expect("rounded rect");
}
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
};
let squircle = render(true);
let rounded = render(false);
for (x, y) in [(4u32, 40u32), (40, 4)] {
assert_eq!(
pixel(&rounded, x, y),
[255, 255, 255, 255],
"the circular corner covers ({x}, {y})"
);
assert_eq!(
pixel(&squircle, x, y),
[0, 0, 0, 255],
"the superellipse has already left the side at ({x}, {y})"
);
}
for shape in [&squircle, &rounded] {
assert_eq!(pixel(shape, 64, 6), [255, 255, 255, 255], "mid side");
assert_eq!(pixel(shape, 64, 64), [255, 255, 255, 255], "middle");
assert_eq!(pixel(shape, 5, 5), [0, 0, 0, 255], "the corner point");
}
}
#[test]
fn a_superellipse_clip_removes_what_falls_outside_the_curve() {
let Some(mut ctx) = context() else { return };
let bounds = Rect::new(4.0, 4.0, 124.0, 124.0);
let radii: RoundingRadii = [[40.0, 40.0]; 4];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save();
canvas
.clip_rsuperellipse(bounds, radii)
.expect("clip to the squircle");
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("fill through the clip");
canvas.restore();
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
assert_eq!(pixel(&pixels, 64, 64), [255, 255, 255, 255], "the middle");
assert_eq!(
pixel(&pixels, 20, 20),
[255, 255, 255, 255],
"inside the superellipse corner"
);
assert_eq!(
pixel(&pixels, 5, 5),
[0, 0, 0, 255],
"the corner point is outside the shape and must be clipped away"
);
assert_eq!(
pixel(&pixels, 4, 40),
[0, 0, 0, 255],
"a clip to the bounding rectangle would leave this lit"
);
}
fn half_every_channel() -> ImageFilter {
ImageFilter::Color(ColorFilter::matrix([
0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
]))
}
#[test]
fn a_shared_backdrop_id_filters_what_was_behind_all_of_the_layers_naming_it() {
let Some(mut ctx) = context() else { return };
let left = Rect::new(16.0, 16.0, 80.0, 112.0);
let right = Rect::new(48.0, 16.0, 112.0, 112.0);
let shot = |ctx: &mut Context, id: Option<i64>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
for bounds in [left, right] {
let layer = match id {
Some(id) => Layer::opacity(1.0).with_backdrop_id(id),
None => Layer::opacity(1.0),
};
canvas
.save_layer_backdrop(layer, Some(bounds), &half_every_channel())
.expect("backdrop");
canvas.restore();
}
render(ctx, canvas)
};
let apart = shot(&mut ctx, None);
let shared = shot(&mut ctx, Some(7));
for (x, side) in [(32, "the left layer alone"), (96, "the right layer alone")] {
for (name, shot) in [("apart", &apart), ("shared", &shared)] {
let got = pixel(shot, x, 64);
assert!(
got[0].abs_diff(128) <= 2 && got[3] == 255,
"{side}, {name}: white halved once is about 128, got {got:?}"
);
}
}
let got = pixel(&apart, 64, 64);
assert!(
got[0].abs_diff(64) <= 2,
"without an id the second layer filters the first layer's result, so \
the overlap should be white quartered -- about 64, got {got:?}"
);
let got = pixel(&shared, 64, 64);
assert!(
got[0].abs_diff(128) <= 2,
"with a shared id both layers filter the capture taken before either \
drew, so the overlap should be white halved once -- about 128, got \
{got:?}"
);
}
#[test]
fn a_shared_backdrop_id_captures_once_and_filters_once() {
let passes = |id: Option<i64>, rows: usize| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
for row in 0..rows {
let top = 8.0 + 24.0 * row as f32;
let layer = match id {
Some(id) => Layer::opacity(1.0).with_backdrop_id(id),
None => Layer::opacity(1.0),
};
canvas
.save_layer_backdrop(
layer,
Some(Rect::new(16.0, top, 112.0, top + 16.0)),
&half_every_channel(),
)
.expect("backdrop");
canvas.restore();
}
canvas.finish().passes.len()
};
assert_eq!(
passes(None, 1),
passes(Some(3), 1) + 1,
"the first layer to name an id has nothing to share with, and only a \
layer without one crops its region out of the capture"
);
let apart = passes(None, 4) - passes(None, 1);
let shared = passes(Some(3), 4) - passes(Some(3), 1);
assert_eq!(
apart, 12,
"three more rows without an id should each cost four passes -- the cut \
that captures the backdrop, the crop of the row's region out of it, \
the filter over that, and the row's own layer"
);
assert_eq!(
shared, 3,
"three more rows sharing an id and a filter should each cost only their \
own layer: the capture is taken once and the filter is run over it \
once. Apart, the same three rows cost {apart} passes"
);
}
#[test]
fn a_clipped_shared_backdrop_draws_what_stating_the_clip_would() {
let Some(mut ctx) = context() else { return };
let corners = [
Rect::new(8.0, 8.0, 56.0, 56.0),
Rect::new(72.0, 72.0, 120.0, 120.0),
];
let shot = |ctx: &mut Context, bounded: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
for row in 0..8 {
let top = 16.0 * row as f32;
canvas
.draw_rect(
Rect::new(0.0, top, 128.0, top + 8.0),
&Paint::fill(Color::srgb(0.1, 0.4, 0.8, 1.0)),
)
.expect("the stripes");
}
for clip in corners {
let layer = Layer::opacity(1.0).with_backdrop_id(11);
canvas.save();
canvas.clip_rect(clip).expect("the clip");
let bounds = bounded.then_some(clip);
canvas
.save_layer_backdrop(layer, bounds, &half_every_channel())
.expect("backdrop");
canvas.restore();
canvas.restore();
}
render(ctx, canvas)
};
let from_clip = shot(&mut ctx, false);
let from_bounds = shot(&mut ctx, true);
assert_eq!(
from_clip, from_bounds,
"the two spellings of one clipped shared backdrop draw the same picture"
);
let inside = pixel(&from_clip, 16, 16);
let outside = pixel(&from_clip, 64, 16);
for channel in 0..3 {
assert!(
inside[channel].abs_diff(outside[channel] / 2) <= 2,
"the panel holds the stripe halved: {inside:?} against {outside:?}"
);
}
}
#[test]
fn a_backdrop_id_reaches_into_a_layer_opened_after_it() {
let Some(mut ctx) = context() else { return };
let panel = Rect::new(32.0, 32.0, 96.0, 96.0);
let shot = |ctx: &mut Context, id: Option<i64>| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
let first = match id {
Some(id) => Layer::opacity(1.0).with_backdrop_id(id),
None => Layer::opacity(1.0),
};
canvas
.save_layer_backdrop(first, Some(panel), &half_every_channel())
.expect("the capture");
canvas.restore();
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::BLACK).with_anti_alias(false),
)
.expect("ground");
canvas.save_layer(Layer::opacity(1.0));
let second = match id {
Some(id) => Layer::opacity(1.0).with_backdrop_id(id),
None => Layer::opacity(1.0),
};
canvas
.save_layer_backdrop(second, Some(panel), &half_every_channel())
.expect("the sharer");
canvas.restore();
canvas.restore();
render(ctx, canvas)
};
let got = pixel(&shot(&mut ctx, None), 64, 64);
assert!(
got[0] <= 2,
"captured afresh, the second panel should have filtered the black \
ground, got {got:?}"
);
let got = pixel(&shot(&mut ctx, Some(11)), 64, 64);
assert!(
got[0].abs_diff(128) <= 2,
"the id should have carried the white capture into the nested layer, \
which halves it to about 128, got {got:?}"
);
}
fn ink(pixels: &[u8]) -> f64 {
pixels.chunks(4).map(|p| p[0] as f64).sum::<f64>() / 255.0
}
#[test]
fn a_stroke_thinner_than_a_pixel_fades_instead_of_disappearing() {
let Some(mut ctx) = context() else { return };
let line = |ctx: &mut Context, width: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let mut b = PathBuilder::new();
b.move_to(Vec2::new(64.3, 8.0))
.line_to(Vec2::new(64.3, 120.0));
canvas
.draw_path(&b.build(), &Paint::stroke(Color::WHITE, width))
.expect("a thin stroke");
ink(&render(ctx, canvas))
};
let whole = line(&mut ctx, 1.0);
assert!(
(whole - 112.0).abs() < 2.0,
"a stroke one pixel wide over 112 pixels should lay down about 112 \
pixels of ink, got {whole:.2}"
);
let half = line(&mut ctx, 0.5);
assert!(
(half - whole).abs() < 3.0,
"at half a pixel the alpha scale reaches one, so the ink should match \
the whole-pixel case: {half:.2} against {whole:.2}"
);
for (width, factor) in [(0.25f32, 0.5), (0.125, 0.25), (0.0625, 0.125)] {
let got = line(&mut ctx, width);
let want = whole * factor;
assert!(
(got - want).abs() < 3.0,
"a stroke {width} pixels wide should lay down {factor} of the ink a \
whole pixel does -- about {want:.2}, got {got:.2}"
);
}
assert!(
line(&mut ctx, 0.15) > 20.0,
"a stroke of 0.15 pixels should still be visible"
);
}
#[test]
fn the_two_stroke_routes_thin_out_the_same_way() {
let Some(mut ctx) = context() else { return };
let circle = |ctx: &mut Context, width: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
40.0,
&Paint::stroke(Color::WHITE, width),
)
.expect("a thin circle");
ink(&render(ctx, canvas))
};
let whole = circle(&mut ctx, 1.0);
for (width, factor) in [(0.5f32, 1.0), (0.25, 0.5), (0.125, 0.25)] {
let got = circle(&mut ctx, width);
let want = whole * factor;
assert!(
(got - want).abs() < whole * 0.05,
"the analytic route should follow the same rule: a stroke {width} \
wide wants {factor} of the whole-pixel ink, about {want:.2}, got \
{got:.2}"
);
}
}
#[test]
fn the_two_ways_to_draw_a_ring_agree_on_its_color() {
let Some(mut ctx) = context() else { return };
let outer = Rect::new(20.0, 20.0, 108.0, 108.0);
let inner = Rect::new(26.0, 26.0, 102.0, 102.0);
let outer_radii = [[6.0, 6.0], [12.0, 12.0], [24.0, 24.0], [54.0, 54.0]];
let inner_radii = [[0.0, 0.0], [6.0, 6.0], [18.0, 18.0], [48.0, 48.0]];
let sky = Color::srgb(135.0 / 255.0, 206.0 / 255.0, 235.0 / 255.0, 1.0);
let differenced = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_drrect_with_radii(outer, outer_radii, inner, inner_radii, &Paint::fill(sky))
.expect("a difference of two rounded rectangles");
render(&mut ctx, canvas)
};
let cleared = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rrect_with_radii(outer, outer_radii, &Paint::fill(sky))
.expect("the outer rectangle");
canvas
.draw_rrect_with_radii(
inner,
inner_radii,
&Paint::fill(sky).with_blend(BlendMode::Clear),
)
.expect("the inner rectangle cleared out of it");
render(&mut ctx, canvas)
};
let mut worst = 0i32;
let mut differing = 0usize;
for (a, b) in differenced.chunks_exact(4).zip(cleared.chunks_exact(4)) {
let delta = a[..3]
.iter()
.zip(&b[..3])
.map(|(p, q)| (*p as i32 - *q as i32).abs())
.max()
.unwrap_or(0);
worst = worst.max(delta);
if delta > 0 {
differing += 1;
}
}
assert_eq!(
(worst, differing),
(0, 0),
"the two constructions of one ring should be the same color everywhere: \
{differing} pixel(s) differ, worst by {worst}"
);
let on_the_ring = pixel(&differenced, 64, 23);
assert!(
on_the_ring[2] > 200 && on_the_ring[0] > 100,
"the top edge of the ring should be sky blue, got {on_the_ring:?}"
);
let inside = pixel(&differenced, 64, 64);
assert_eq!(
inside,
[0, 0, 0, 255],
"the middle should be the hole, not the fill"
);
}
fn stroke_covers(pixels: &[u8], x: std::ops::Range<u32>, y: std::ops::Range<u32>) -> Vec<u8> {
let mut out = Vec::new();
for row in y {
for column in x.clone() {
let p = pixel(pixels, column, row);
if p[2] > 200 && p[0] < 250 {
out.push(p[0]);
}
}
}
out
}
#[test]
fn a_translucent_stroke_blends_with_itself_only_where_its_caps_overlap() {
let Some(mut ctx) = context() else { return };
let sweep = 5.93f32;
let (cx, cy, r) = (64.0f32, 64.0f32, 26.0f32);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
let mut b = PathBuilder::new();
for i in 0..=128 {
let a = sweep * (i as f32 / 128.0);
let p = Vec2::new(cx + r * a.cos(), cy + r * a.sin());
if i == 0 {
b.move_to(p);
} else {
b.line_to(p);
}
}
canvas
.draw_path(
&b.build(),
&Paint::stroke(Color::srgb(0.0, 0.0, 1.0, 0.5), 40.0).with_style(Style::Stroke(
StrokeStyle::new(40.0).with_cap(LineCap::Round),
)),
)
.expect("a wide translucent arc");
let pixels = render(&mut ctx, canvas);
for (label, x, y) in [
("the far side", 8..30u32, 50..80u32),
("the top", 50..80u32, 8..26u32),
("the bottom", 50..80u32, 100..120u32),
] {
let covers = stroke_covers(&pixels, x, y);
assert!(
covers.len() > 150,
"{label} should be mostly stroke, got {} pixels",
covers.len()
);
let twice = covers.iter().filter(|v| **v < 120).count();
assert_eq!(
twice,
0,
"{label}: {twice} of {} stroke pixels blended more than once, so the \
run of the stroke is covering itself",
covers.len()
);
let once = covers.iter().filter(|v| v.abs_diff(128) <= 2).count();
assert!(
once * 10 > covers.len() * 9,
"{label}: only {once} of {} pixels carry a single cover, so this \
window is edge rather than run",
covers.len()
);
}
let gap = stroke_covers(&pixels, 84..120u32, 55..75u32);
let doubled = gap.iter().filter(|v| **v < 120).count();
assert!(
doubled > 100,
"the two caps should be on top of each other near the gap, and only \
{doubled} of {} pixels there blended twice",
gap.len()
);
}
#[test]
fn a_rectangle_drawn_two_ways_agrees_everywhere_but_its_corners() {
let Some(mut ctx) = context() else { return };
let corners = |r: Rect| {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(r.left, r.top))
.line_to(Vec2::new(r.right, r.top))
.line_to(Vec2::new(r.right, r.bottom))
.line_to(Vec2::new(r.left, r.bottom))
.close();
b.build()
};
for (label, rect, paint) in [
(
"aligned to the pixel grid",
Rect::new(20.0, 20.0, 100.0, 100.0),
Paint::fill(Color::WHITE),
),
(
"on pixel centers",
Rect::new(20.5, 20.5, 100.5, 100.5),
Paint::fill(Color::WHITE),
),
(
"stroked",
Rect::new(18.0, 30.0, 110.0, 96.0),
Paint::stroke(Color::WHITE, 9.0),
),
] {
let primitive = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.draw_rect(rect, &paint).expect("the primitive");
render(&mut ctx, canvas)
};
let as_path = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_path(&corners(rect), &paint)
.expect("the same four corners");
render(&mut ctx, canvas)
};
let lit = primitive.chunks_exact(4).filter(|p| p[0] > 8).count();
assert!(
lit > 500,
"{label}: the rectangle should cover a good part of the frame, got \
{lit} pixels"
);
let mut differing = Vec::new();
for (i, (a, b)) in primitive
.chunks_exact(4)
.zip(as_path.chunks_exact(4))
.enumerate()
{
let delta = a
.iter()
.zip(b)
.map(|(p, q)| (*p as i32 - *q as i32).abs())
.max()
.unwrap_or(0);
if delta > 1 {
let (x, y) = (i as u32 % SIZE.width, i as u32 / SIZE.width);
differing.push((x, y, delta));
}
}
let corners = if matches!(paint.style, Style::Stroke(_)) {
16
} else {
4
};
assert!(
differing.len() <= corners,
"{label}: {} pixels differ between the two routes, which is more \
than the {corners} a corner apiece can account for: {differing:?}",
differing.len()
);
for (x, y, delta) in &differing {
let _ = delta;
let reach = 2.5
+ match &paint.style {
Style::Stroke(style) => style.width / 2.0,
_ => 0.0,
};
let near_x =
(*x as f32 - rect.left).abs() <= reach || (*x as f32 - rect.right).abs() <= reach;
let near_y =
(*y as f32 - rect.top).abs() <= reach || (*y as f32 - rect.bottom).abs() <= reach;
assert!(
near_x && near_y,
"{label}: ({x}, {y}) differs by {delta} and is not at a corner \
of {rect:?}, so the two routes part company along an edge"
);
}
}
}
#[test]
fn a_stroked_rectangle_has_the_corners_its_join_asks_for() {
let Some(mut ctx) = context() else { return };
let rect = Rect::new(18.0, 30.0, 110.0, 96.0);
let width = 9.0f32;
let (cx, cy) = (
(rect.left - width / 2.0).ceil() as u32,
(rect.top - width / 2.0).ceil() as u32,
);
let corner_of = |ctx: &mut Context, join: LineJoin| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
rect,
&Paint::stroke(Color::WHITE, width)
.with_style(Style::Stroke(StrokeStyle::new(width).with_join(join))),
)
.expect("a stroked rectangle");
pixel(&render(ctx, canvas), cx, cy)
};
let mitered = corner_of(&mut ctx, LineJoin::Miter);
assert!(
mitered[0] > 200,
"a mitered corner should reach ({cx}, {cy}), got {mitered:?}"
);
for join in [LineJoin::Bevel, LineJoin::Round] {
let got = corner_of(&mut ctx, join);
assert!(
got[0] < 100,
"{join:?} should not reach ({cx}, {cy}), got {got:?}"
);
}
}
#[test]
fn a_layer_matrix_recovers_what_fell_outside_the_frame() {
let Some(mut ctx) = context() else { return };
let green = Paint::fill(Color::srgb(0.0, 1.0, 0.0, 1.0));
let radius = 30.0;
let shot = |ctx: &mut Context, at: f32, moved_by: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(
Layer::opacity(1.0).with_matrix(Affine2::from_translation(Vec2::new(moved_by, 0.0))),
);
canvas
.draw_circle(Vec2::new(at, 64.0), radius, &green)
.expect("a circle");
canvas.restore();
let pixels = render(ctx, canvas);
pixels.chunks_exact(4).filter(|p| p[1] > 100).count()
};
let moved_inside = shot(&mut ctx, 34.0, 40.0);
assert!(
moved_inside > 2_000,
"a circle moved within the frame should still be there, got \
{moved_inside} pixels"
);
let moved_in_from_outside = shot(&mut ctx, -36.0, 100.0);
assert!(
moved_in_from_outside.abs_diff(moved_inside) * 20 < moved_inside,
"a circle drawn off the frame and translated in should arrive whole: \
{moved_in_from_outside} pixels against {moved_inside} for the same \
circle drawn where the layer already reached"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(
Layer::opacity(1.0).with_matrix(Affine2::from_translation(Vec2::new(100.0, 0.0))),
);
canvas
.draw_circle(Vec2::new(-36.0, 64.0), radius, &green)
.expect("a circle off the left edge");
canvas.restore();
let pixels = render(&mut ctx, canvas);
assert_eq!(
pixel(&pixels, 64, 64),
[0, 255, 0, 255],
"the circle should land in the middle of the frame"
);
assert_eq!(
pixel(&pixels, 64 + (radius as u32) + 4, 64),
[0, 0, 0, 255],
"and stop where a circle of that radius stops"
);
}
#[test]
fn a_stroke_too_wide_to_tessellate_draws_rather_than_aborting() {
let Some(mut ctx) = context() else { return };
let bar = |width: f32| {
let mut b = PathBuilder::new();
b.move_to(Vec2::new(20.0, 40.0))
.line_to(Vec2::new(90.0, 40.0))
.line_to(Vec2::new(90.0, 100.0));
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::stroke(Color::WHITE, width).with_style(Style::Stroke(
StrokeStyle::new(width)
.with_cap(LineCap::Round)
.with_join(LineJoin::Round),
));
canvas.draw_path(&b.build(), &paint).expect("a stroke");
canvas
};
let drawn = render(&mut ctx, bar(6.0));
assert!(
drawn.chunks_exact(4).filter(|p| p[0] > 128).count() > 200,
"a six-wide stroke should draw"
);
let whole = (SIZE.width * SIZE.height) as usize;
for width in [1e3f32, 1e6, 1e9] {
let wide = render(&mut ctx, bar(width));
let covered = wide.chunks_exact(4).filter(|p| p[0] > 128).count();
assert_eq!(
covered, whole,
"a stroke {width:e} wide should cover the frame"
);
}
for width in [1e30f32, f32::MAX] {
let wide = render(&mut ctx, bar(width));
assert_eq!(
wide.len(),
whole * 4,
"a stroke {width:e} wide returned a frame of the wrong size"
);
let corrupt = wide
.chunks_exact(4)
.filter(|p| p[0] != p[1] || p[1] != p[2] || p[3] != 255)
.count();
assert_eq!(
corrupt, 0,
"a stroke {width:e} wide put {corrupt} pixels in the frame that are \
neither the background nor the stroke"
);
}
}
#[test]
fn a_nine_patch_is_one_draw_and_the_same_picture_as_nine() {
let Some(mut ctx) = context() else { return };
let sheet = Extent2D {
width: 32,
height: 32,
};
let mut texels = vec![0u8; 32 * 32 * 4];
for y in 0..32usize {
for x in 0..32usize {
let edge = !(8..24).contains(&x) || !(8..24).contains(&y);
let color: [u8; 4] = if edge {
[255, 0, 0, 255]
} else {
[0, 0, 255, 255]
};
texels[(y * 32 + x) * 4..(y * 32 + x) * 4 + 4].copy_from_slice(&color);
}
}
let mut image = ctx
.create_image(sheet, PixelFormat::Rgba8Unorm)
.expect("sheet");
ctx.write_image(&mut image, &texels).expect("upload");
let center = Rect::new(8.0, 8.0, 24.0, 24.0);
let into = Rect::new(4.0, 4.0, 124.0, 124.0);
let render_with = |ctx: &mut Context, canvas: Canvas| {
let recording = canvas.finish();
let draws: usize = recording.passes.iter().map(|p| p.batch.draws().len()).sum();
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &recording, &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
(draws, pixels)
};
let merged = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_image_nine(0, sheet, center, into, &Paint::default())
.expect("a nine-patch");
render_with(&mut ctx, canvas)
};
let separate = {
let (w, h) = (sheet.width as f32, sheet.height as f32);
let sx = [0.0, center.left, center.right, w];
let sy = [0.0, center.top, center.bottom, h];
let dx = [
into.left,
into.left + center.left,
into.right - (w - center.right),
into.right,
];
let dy = [
into.top,
into.top + center.top,
into.bottom - (h - center.bottom),
into.bottom,
];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
for row in 0..3 {
for column in 0..3 {
let destination = Rect::new(dx[column], dy[row], dx[column + 1], dy[row + 1]);
let paint = Paint::default().with_shader(Shader::Image {
slot: 0,
rect: destination,
alpha: 1.0,
tile: [TileMode::Clamp; 2],
source: Rect::new(
sx[column] / w,
sy[row] / h,
sx[column + 1] / w,
sy[row + 1] / h,
),
tint: Color::WHITE,
sampling: Sampling::Linear,
});
canvas.draw_rect(destination, &paint).expect("a patch");
}
}
render_with(&mut ctx, canvas)
};
ctx.destroy_image(image);
assert_eq!(merged.0, 1, "a nine-patch should record one draw");
assert_eq!(
separate.0, 9,
"nine patches drawn one at a time are nine draws"
);
let differing = merged
.1
.chunks_exact(4)
.zip(separate.1.chunks_exact(4))
.filter(|(a, b)| a != b)
.count();
let worst = merged
.1
.iter()
.zip(&separate.1)
.map(|(a, b)| (*a as i32 - *b as i32).abs())
.max()
.unwrap_or(0);
assert_eq!(
(differing, worst),
(0, 0),
"one draw should be the same picture as nine: {differing} pixel(s) \
differ, worst by {worst}. Without the half-texel inset this is about \
twelve hundred pixels and a hundred and seventy levels, which is the \
seams bleeding"
);
}
#[test]
fn a_field_of_points_is_one_draw_with_the_edge_each_dot_had() {
let Some(mut ctx) = context() else { return };
let points: Vec<Vec2> = (0..16)
.map(|i| {
let a = i as f32 * 0.4;
Vec2::new(64.0 + 40.0 * a.cos(), 64.0 + 40.0 * a.sin())
})
.collect();
let radius = 4.5f32;
let field = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let paint = Paint::stroke(Color::WHITE, radius * 2.0).with_style(Style::Stroke(
StrokeStyle::new(radius * 2.0).with_cap(LineCap::Round),
));
canvas
.draw_points(PointMode::Points, &points, &paint)
.expect("a field");
canvas
};
let separately = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
for center in &points {
canvas
.draw_circle(*center, radius, &Paint::fill(Color::WHITE))
.expect("a dot");
}
canvas
};
let shot = |ctx: &mut Context, canvas: Canvas| {
let recording = canvas.finish();
let draws: usize = recording.passes.iter().map(|p| p.batch.draws().len()).sum();
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &recording).expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
(draws, pixels)
};
let (field_draws, field_pixels) = shot(&mut ctx, field);
let (dot_draws, dot_pixels) = shot(&mut ctx, separately);
assert_eq!(field_draws, 1, "sixteen points should record one draw");
assert!(
dot_draws > field_draws,
"circles drawn one at a time should still be more draws than the field: \
{dot_draws} against {field_draws}"
);
let lit = field_pixels.chunks_exact(4).filter(|p| p[0] > 8).count();
assert!(
lit > 800,
"the field should draw something, got {lit} pixels"
);
let differing = field_pixels
.chunks_exact(4)
.zip(dot_pixels.chunks_exact(4))
.filter(|(a, b)| a != b)
.count();
let worst = field_pixels
.iter()
.zip(&dot_pixels)
.map(|(a, b)| (*a as i32 - *b as i32).abs())
.max()
.unwrap_or(0);
assert_eq!(
(differing, worst),
(0, 0),
"one draw should be the same picture as sixteen: {differing} pixel(s) \
differ, worst by {worst}. Without the pixel of outset on the quad this \
is ninety-two pixels, where the disc meets the quad it is drawn on"
);
}
fn blur_reach_of(pixels: &[u8]) -> u32 {
let mut reach = 0;
for x in 0..SIZE.width {
if pixel(pixels, x, SIZE.height / 2)[0] > 8 {
reach = reach.max((x as i32 - SIZE.width as i32 / 2).unsigned_abs());
}
}
reach
}
#[test]
fn a_blur_scales_with_the_transform() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, scale: f32, blurred: &dyn Fn(&mut Canvas, Rect)| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save();
canvas.scale(scale, scale);
let side = 24.0 / scale;
let at = 64.0 / scale;
blurred(
&mut canvas,
Rect::new(
at - side / 2.0,
at - side / 2.0,
at + side / 2.0,
at + side / 2.0,
),
);
canvas.restore();
blur_reach_of(&render(ctx, canvas))
};
for (what, draw) in [
(
"a paint's mask blur",
&(|canvas: &mut Canvas, r: Rect| {
canvas
.draw_rect(r, &Paint::fill(Color::WHITE).with_mask_blur(4.0))
.expect("a blurred rectangle");
}) as &dyn Fn(&mut Canvas, Rect),
),
(
"a layer's blur",
&(|canvas: &mut Canvas, r: Rect| {
canvas.save_layer(Layer::opacity(1.0).with_blur(4.0));
canvas
.draw_rect(r, &Paint::fill(Color::WHITE))
.expect("a rectangle in a blurred layer");
canvas.restore();
}) as &dyn Fn(&mut Canvas, Rect),
),
] {
let plain = shot(&mut ctx, 1.0, draw);
let scaled = shot(&mut ctx, 3.0, draw);
let grew = (scaled - 12) as f32 / (plain - 12).max(1) as f32;
assert!(
(grew - 3.0).abs() < 0.5,
"{what}: reach went from {plain} to {scaled} under a scale of three, \
a growth of {grew:.2} where about three was wanted. A sigma that \
does not scale gives a growth of one"
);
}
}
#[test]
fn a_blurred_clear_erases_by_its_falloff_rather_than_by_its_bounds() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, sigma: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::srgb(0.2, 0.4, 1.0, 1.0)),
)
.expect("a ground to erase from");
canvas
.draw_circle(
Vec2::new(64.0, 64.0),
36.0,
&Paint::fill(Color::WHITE)
.with_mask_blur(sigma)
.with_blend(BlendMode::Clear),
)
.expect("a blurred hole");
render(ctx, canvas)
};
let alpha = |pixels: &[u8], x: usize, y: usize| pixels[(y * 128 + x) * 4 + 3];
let sharp = shot(&mut ctx, 0.0);
let cut = sharp.chunks_exact(4).filter(|p| p[3] == 0).count();
let disc = (std::f32::consts::PI * 36.0 * 36.0) as usize;
assert!(
cut.abs_diff(disc) < disc / 20,
"a sharp clear should erase the circle: {cut} against about {disc}"
);
let blurred = shot(&mut ctx, 7.0);
assert_eq!(
alpha(&blurred, 64, 64),
0,
"the middle should be erased outright"
);
assert_eq!(
alpha(&blurred, 2, 2),
255,
"the corner is outside the reach"
);
assert_eq!(
alpha(&blurred, 18, 18),
255,
"the erased region has to be round; this is a corner of its bounding box"
);
let ramp: Vec<u8> = (64..128).map(|x| alpha(&blurred, x, 64)).collect();
assert!(
ramp.windows(2).all(|w| w[0] <= w[1]),
"alpha should climb monotonically out of the hole: {ramp:?}"
);
let partial = ramp.iter().filter(|a| (8..248).contains(*a)).count();
assert!(
partial >= 12,
"the hole's edge should fade over many pixels; {partial} of the radius \
carried a partial alpha"
);
}
#[test]
fn a_blend_color_filter_in_an_advanced_mode_computes_the_specified_formula() {
let Some(mut ctx) = context() else { return };
let dst = [0.8f32, 0.3, 0.6];
let src = [0.25f32, 0.9, 0.1];
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::srgb(dst[0], dst[1], dst[2], 1.0)).with_color_filter(
ColorFilter::blend([src[0], src[1], src[2], 1.0], BlendMode::Difference),
),
)
.expect("a filtered rectangle");
let pixels = render(&mut ctx, canvas);
let got = pixel(&pixels, 64, 64);
for (channel, (d, s)) in dst.iter().zip(src.iter()).enumerate() {
let want = ((d - s).abs() * 255.0).round() as u8;
assert!(
got[channel].abs_diff(want) <= 2,
"channel {channel} of |dst - src| should be about {want}, got {}",
got[channel]
);
}
assert_eq!(
got[3], 255,
"an opaque draw stays opaque through the filter"
);
}
#[test]
fn a_layers_blur_reaches_past_stated_bounds_however_it_was_spelled() {
let Some(mut ctx) = context() else { return };
let square = Rect::new(44.0, 44.0, 84.0, 84.0);
let bounds = square;
let shot = |ctx: &mut Context, filtered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if filtered {
canvas
.save_layer_filtered(Layer::opacity(1.0), Some(bounds), &ImageFilter::blur(6.0))
.expect("a blur is available as a layer filter");
} else {
canvas.save_layer_bounds(Layer::opacity(1.0).with_blur(6.0), bounds);
}
canvas
.draw_rect(square, &Paint::fill(Color::WHITE))
.expect("a square to blur");
canvas.restore();
render(ctx, canvas)
};
let extent = |pixels: &[u8]| {
let lit: Vec<(usize, usize)> = (0..128usize)
.flat_map(|y| (0..128usize).map(move |x| (x, y)))
.filter(|(x, y)| pixels[(y * 128 + x) * 4] > 8)
.collect();
assert!(!lit.is_empty(), "the blurred square drew nothing");
(
lit.iter().map(|p| p.0).min().unwrap(),
lit.iter().map(|p| p.0).max().unwrap(),
)
};
let on_the_layer = extent(&shot(&mut ctx, false));
let as_a_filter = extent(&shot(&mut ctx, true));
assert_eq!(
as_a_filter, on_the_layer,
"the same blur stated two ways should reach the same distance past the \
bound; as a filter it reached {as_a_filter:?} and on the layer {on_the_layer:?}"
);
assert!(
on_the_layer.0 < 44 && on_the_layer.1 > 83,
"a blur of six should carry past a bound at forty-four and eighty-four; \
it reached {on_the_layer:?}"
);
}
#[test]
fn a_gradient_on_a_mesh_is_read_at_the_texture_coordinates() {
let Some(mut ctx) = context() else { return };
let positions = [
Vec2::new(24.0, 104.0),
Vec2::new(64.0, 24.0),
Vec2::new(104.0, 104.0),
];
let ramp = Shader::LinearGradient {
start: Vec2::new(24.0, 24.0),
end: Vec2::new(104.0, 104.0),
stops: vec![
GradientStop::new(Color::srgb(0.0, 0.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::srgb(1.0, 0.0, 0.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
};
let shot = |ctx: &mut Context, coords: [Vec2; 3]| {
let mesh = Vertices::textured(VertexMode::Triangles, positions.to_vec(), coords.to_vec())
.expect("a triangle with coordinates");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_vertices(&mesh, &Paint::fill(Color::WHITE).with_shader(ramp.clone()))
.expect("a gradient read at a mesh's coordinates");
render(ctx, canvas)
};
let along = shot(&mut ctx, positions);
let across = shot(
&mut ctx,
[
Vec2::new(104.0, 104.0),
Vec2::new(64.0, 24.0),
Vec2::new(24.0, 104.0),
],
);
let differing = along
.chunks_exact(4)
.zip(across.chunks_exact(4))
.filter(|(a, b)| a[0].abs_diff(b[0]) > 8)
.count();
assert!(
differing > 500,
"reversing the coordinates should change the picture; {differing} pixels \
differ, which means the gradient was read at the position instead"
);
let _lit: Vec<u8> = along
.chunks_exact(4)
.filter(|p| p[0] > 4 || p[2] > 4)
.map(|p| p[0])
.collect();
let mesh = Vertices::new(VertexMode::Triangles, positions.to_vec())
.expect("a triangle with no coordinates");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_vertices(&mesh, &Paint::fill(Color::WHITE).with_shader(ramp.clone()))
.expect("a gradient on a mesh with no coordinates");
let by_position = render(&mut ctx, canvas);
let apart = along
.chunks_exact(4)
.zip(by_position.chunks_exact(4))
.filter(|(a, b)| (0..4).any(|c| a[c].abs_diff(b[c]) > 2))
.count();
assert_eq!(
apart, 0,
"coordinates equal to the positions should read the gradient exactly \
where the positions do; {apart} pixels differ"
);
}
#[test]
fn a_color_filter_colors_the_shape_and_not_the_rest_of_its_quad() {
let Some(mut ctx) = context() else { return };
let filter = ColorFilter::blend([0.5, 0.0, 0.5, 0.5], BlendMode::SrcOver);
let paint = Paint::fill(Color::srgb(1.0, 1.0, 0.0, 1.0)).with_color_filter(filter);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas
.draw_circle(Vec2::new(32.0, 32.0), 24.0, &paint)
.expect("the circle");
canvas
.draw_oval(Rect::new(72.0, 8.0, 120.0, 56.0), &paint)
.expect("the oval");
canvas
.draw_rrect(Rect::new(8.0, 72.0, 56.0, 120.0), 20.0, &paint)
.expect("the rounded rectangle");
let shot = render(&mut ctx, canvas);
for (x, y, shape) in [
(10, 10, "circle"),
(74, 10, "oval"),
(10, 74, "rounded rectangle"),
] {
assert_eq!(
pixel(&shot, x, y),
[255, 255, 255, 255],
"the {shape}'s quad outside the shape was colored by its filter"
);
}
for (x, y, shape) in [
(32, 32, "circle"),
(96, 32, "oval"),
(32, 96, "rounded rectangle"),
] {
let p = pixel(&shot, x, y);
assert!(
p[0] < 240 && p[2] > 40,
"the {shape} should be yellow tinted purple, and is {p:?}"
);
}
}
#[test]
fn a_color_filter_that_recolors_nothing_still_draws_the_shape() {
let Some(mut ctx) = context() else { return };
let blue = Color::srgb(0.0, 0.0, 1.0, 1.0);
let green = Color::srgb(0.0, 1.0, 0.0, 1.0);
let shot = |ctx: &mut Context, filtered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas.save_layer(Layer::opacity(1.0));
canvas
.draw_circle(Vec2::new(64.0, 64.0), 48.0, &Paint::fill(blue))
.expect("the blue circle");
canvas.save();
canvas
.clip_rect(Rect::new(40.0, 40.0, 88.0, 88.0))
.expect("the clip");
let mut paint = Paint::fill(green);
if filtered {
paint = paint.with_image_filter(ImageFilter::Color(ColorFilter::blend(
Color::WHITE.to_array(),
BlendMode::Dst,
)));
}
canvas
.draw_circle(Vec2::new(64.0, 64.0), 48.0, &paint)
.expect("the green circle");
canvas.restore();
canvas.restore();
render(ctx, canvas)
};
let plain = shot(&mut ctx, false);
let filtered = shot(&mut ctx, true);
let inside = pixel(&plain, 64, 64);
assert!(
inside[1] > 200 && inside[2] < 60,
"the square should be green, and is {inside:?}"
);
let ring = pixel(&plain, 64, 24);
assert!(
ring[2] > 200 && ring[1] < 60,
"the circle outside the square should be blue, and is {ring:?}"
);
assert_eq!(
pixel(&plain, 4, 4),
[255, 255, 255, 255],
"and white outside"
);
assert_eq!(
plain, filtered,
"a color filter in Dst mode changed the picture, and the mode is the \
identity"
);
let passes = |filtered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
let mut paint = Paint::fill(green);
if filtered {
paint = paint.with_image_filter(ImageFilter::Color(ColorFilter::blend(
Color::WHITE.to_array(),
BlendMode::Dst,
)));
}
canvas
.draw_circle(Vec2::new(64.0, 64.0), 48.0, &paint)
.expect("the circle");
canvas.finish().passes.len()
};
assert_eq!(
passes(true),
passes(false),
"a color filter that recolors nothing should cost no pass"
);
}
#[test]
fn a_point_smaller_than_a_pixel_still_covers_one() {
let Some(mut ctx) = context() else { return };
let lit = |ctx: &mut Context, width: f32, blurred: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
let mut paint =
Paint::fill(Color::srgb(0.0, 0.0, 0.0, 1.0)).with_style(Style::Stroke(StrokeStyle {
cap: LineCap::Round,
..StrokeStyle::new(width)
}));
if blurred {
paint.image_filter = ImageFilter::blur(1.0);
}
canvas
.draw_points(PointMode::Points, &[Vec2::new(64.0, 64.0)], &paint)
.expect("the point");
let pixels = render(ctx, canvas);
(0..128u32)
.flat_map(|y| (0..128u32).map(move |x| (x, y)))
.filter(|(x, y)| pixel(&pixels, *x, *y)[0] < 250)
.count()
};
for blurred in [false, true] {
let route = match blurred {
true => "the per-point route",
false => "the field route",
};
assert!(
lit(&mut ctx, 0.0, blurred) > 0,
"{route}: a width of zero is a point one pixel across, and drew \
nothing"
);
assert!(
lit(&mut ctx, 0.1, blurred) > 0,
"{route}: a point a twentieth of a pixel in radius is widened to \
half of one, and drew nothing"
);
}
}
#[test]
fn a_hairline_lands_on_one_row_of_pixels() {
let Some(mut ctx) = context() else { return };
let drawn = |ctx: &mut Context, y: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas
.draw_line(
Vec2::new(8.0, y),
Vec2::new(120.0, y),
&Paint::stroke(Color::srgb(0.0, 0.0, 0.0, 1.0), 0.0),
)
.expect("the hairline");
let pixels = render(ctx, canvas);
let lit = (0..128u32)
.flat_map(|y| (0..128u32).map(move |x| (x, y)))
.filter(|(x, y)| pixel(&pixels, *x, *y)[0] < 250)
.count();
let darkest = (0..128u32)
.map(|row| pixel(&pixels, 64, row)[0])
.min()
.unwrap_or(255);
(lit, darkest)
};
let (lit, darkest) = drawn(&mut ctx, 64.0);
assert_eq!(
lit, 112,
"a snapped hairline covers one row of 112 pixels, and covered {lit}"
);
assert!(
darkest < 40,
"the row it lands on is fully covered, and its darkest pixel is {darkest}"
);
let (offset_lit, offset_darkest) = drawn(&mut ctx, 64.5);
assert_eq!(
(offset_lit, offset_darkest),
(lit, darkest),
"a hairline at 64.5 should draw exactly as one at 64.0"
);
}
#[test]
fn a_hairline_with_a_shader_keeps_its_shader_over_the_snap() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, width: f32| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas.scale(2.0, 2.0);
let paint = Paint::default()
.with_style(Style::Stroke(StrokeStyle::new(width)))
.with_shader(Shader::LinearGradient {
start: Vec2::new(4.0, 0.0),
end: Vec2::new(60.0, 0.0),
stops: vec![
GradientStop {
offset: 0.0,
color: Color::srgb(1.0, 0.0, 0.0, 1.0),
},
GradientStop {
offset: 1.0,
color: Color::srgb(0.0, 0.0, 1.0, 1.0),
},
],
tile: TileMode::Clamp,
});
canvas
.draw_line(Vec2::new(4.0, 32.0), Vec2::new(60.0, 32.0), &paint)
.expect("the line");
render(ctx, canvas)
};
let crossing = |pixels: &[u8]| {
(8..120u32).find(|x| {
(0..128u32)
.map(|y| pixel(pixels, *x, y))
.filter(|p| p[0] < 250 || p[2] < 250)
.any(|p| p[2] > p[0])
})
};
let hairline = shot(&mut ctx, 0.0);
let wider = shot(&mut ctx, 1.0);
let (thin, thick) = (
crossing(&hairline).expect("the hairline has a ramp"),
crossing(&wider).expect("the wider line has a ramp"),
);
assert!(
thin.abs_diff(thick) <= 3,
"the gradient's middle is at {thin} on a hairline and {thick} on a line a \
pixel wide, so the hairline read its shader in the wrong space"
);
let rows = (0..128u32)
.filter(|y| (0..128u32).any(|x| pixel(&hairline, x, *y)[1] < 250))
.count();
assert_eq!(
rows, 2,
"a shaded hairline is not snapped, so it covers two rows at half \
coverage and covered {rows}"
);
}
#[test]
fn plus_saturates_in_eight_bits_and_does_not_in_a_float_target() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().float_render_targets {
eprintln!("skipping: this device cannot render into a floating-point target");
return;
}
let ground = Color::srgb(0.9, 1.0, 0.9, 1.0);
let build = |filtered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(ground);
let layer = Layer::opacity(1.0);
match filtered {
true => {
canvas.save_layer(layer.with_color_filter(ColorFilter::blend(
Color::srgb(1.0, 0.0, 0.0, 1.0).to_array(),
BlendMode::Plus,
)));
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::WHITE).with_anti_alias(false),
)
.expect("the rect");
}
false => {
canvas
.draw_rect(
Rect::new(16.0, 16.0, 112.0, 112.0),
&Paint::fill(Color::srgb(1.0, 0.0, 0.0, 1.0))
.with_blend(BlendMode::Plus)
.with_anti_alias(false),
)
.expect("the rect");
return canvas;
}
}
canvas.restore();
canvas
};
for filtered in [false, true] {
let route = match filtered {
true => "a Plus color filter on the group",
false => "a Plus blend on the draw",
};
let wide = wide_pixels(&mut ctx, build(filtered));
let inside = wide_pixel(&wide, 64, 64);
assert!(
inside[0] > 1.05,
"{route}: red plus a ground of nine tenths should pass one in a \
float target, and came back {}",
inside[0]
);
let narrow = render(&mut ctx, build(filtered));
assert_eq!(
pixel(&narrow, 64, 64)[0],
255,
"{route}: an eight-bit target has to clip the same sum"
);
}
}
#[test]
fn an_atlas_tint_in_plus_is_clipped_where_the_other_routes_are_not() {
let Some(mut ctx) = context() else { return };
if !ctx.capabilities().float_render_targets {
eprintln!("skipping: this device cannot render into a floating-point target");
return;
}
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let build = || {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let sprites: Vec<Sprite> = shuffled_quadrants()
.into_iter()
.map(|sprite| Sprite {
color: Color::WHITE,
..sprite
})
.collect();
canvas
.draw_atlas(
&sprites,
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0)).with_tint_blend(BlendMode::Plus),
)
.expect("atlas");
canvas
};
let wide = wide_pixels_with_images(&mut ctx, build(), &[&image]);
let inside = wide_pixel(&wide, 32, 32);
assert!(
(inside[0] - 1.0).abs() < 0.01 && (inside[1] - 1.0).abs() < 0.01,
"the tint route clamps in the shader, so a saturated channel plus white \
has to come back at one even in a float target, and the yellow quadrant \
came back {inside:?} -- if this now passes one, the clamp came out and \
§13 of docs/non-parity.md needs deleting rather than editing"
);
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &build().finish(), &[&image])
.expect("draw");
let narrow = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
assert_eq!(
pixel(&narrow, 32, 32),
[255, 255, 255, 255],
"an eight-bit target has to clip the same sum"
);
}
#[test]
fn an_advanced_color_filter_against_a_transparent_color_is_the_identity() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, filtered: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
let mut layer = Layer::opacity(0.3);
if filtered {
layer = layer.with_color_filter(ColorFilter::blend(
[0.0, 0.0, 0.0, 0.0],
BlendMode::Saturation,
));
}
canvas.save_layer(layer);
canvas
.draw_rect(
Rect::new(24.0, 24.0, 96.0, 96.0),
&Paint::fill(Color::srgb(0.5, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("the maroon rect");
canvas
.draw_rect(
Rect::new(48.0, 48.0, 120.0, 120.0),
&Paint::fill(Color::srgb(0.0, 0.0, 1.0, 1.0)).with_anti_alias(false),
)
.expect("the blue rect");
canvas.restore();
render(ctx, canvas)
};
let plain = shot(&mut ctx, false);
let filtered = shot(&mut ctx, true);
assert_eq!(
plain, filtered,
"a Saturation filter against a transparent color is the identity, so it \
must leave the group exactly as it found it"
);
let inside = pixel(&plain, 100, 100);
assert!(
inside[2] > 200 && inside[0] < 220 && inside[0] > 120,
"the blue rectangle at three tenths over white should be a pale blue, \
and is {inside:?}"
);
}
#[test]
fn an_antialiased_draw_after_a_backdrop_filter_renders() {
let Some(mut ctx) = context() else { return };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.0, 0.3, 0.0, 1.0)).with_anti_alias(false),
)
.expect("ground");
canvas.save_layer(Layer::opacity(1.0).with_backdrop_blur(4.0));
canvas
.draw_rect(
Rect::new(16.0, 16.0, 64.0, 64.0),
&Paint::fill(Color::linear(1.0, 1.0, 1.0, 0.5)).with_anti_alias(false),
)
.expect("in the layer");
canvas.restore();
let mut builder = Path::builder();
builder.move_to(Vec2::new(70.5, 70.5));
builder.line_to(Vec2::new(120.5, 80.5));
builder.line_to(Vec2::new(80.5, 120.5));
builder.close();
canvas
.draw_path(
&builder.build(),
&Paint::fill(Color::WHITE).with_anti_alias(true),
)
.expect("a triangle after the cut");
let recording = canvas.finish();
let root = &recording.passes[recording.passes.len() - 1];
assert_eq!(
root.descriptor.samples, 4,
"the triangle asked for antialiasing"
);
assert!(
root.descriptor.clear.is_some(),
"a multisampled pass must clear, and the whole-target redraw makes that free"
);
let pixels = render_recording(&mut ctx, &recording);
let at = |x: u32, y: u32| {
let i = ((y * SIZE.width + x) * 4) as usize;
pixels[i]
};
assert!(
at(95, 85) > 200,
"the triangle is drawn, found {}",
at(95, 85)
);
}
#[test]
fn culling_hidden_pixels_changes_no_pixel() {
let Some(mut ctx) = context() else { return };
fn shape(recording: &emblema::Recording) -> (usize, usize) {
let draws: Vec<_> = recording
.passes
.iter()
.flat_map(|pass| pass.batch.draws())
.collect();
(
draws.len(),
draws.iter().filter(|d| d.clip.is_some()).count(),
)
}
type Scene = (&'static str, bool, fn(&mut Canvas));
let scenes: [Scene; 9] = [
("a bar over a wash", true, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.1, 0.2, 0.4, 1.0)),
)
.expect("wash");
canvas
.draw_rect(Rect::new(0.0, 0.0, 128.0, 32.0), &Paint::fill(Color::WHITE))
.expect("bar");
}),
("a sidebar too, sharing a corner", true, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.1, 0.2, 0.4, 1.0)),
)
.expect("wash");
canvas
.draw_rect(Rect::new(0.0, 0.0, 128.0, 32.0), &Paint::fill(Color::WHITE))
.expect("bar");
canvas
.draw_rect(
Rect::new(0.0, 0.0, 40.0, 128.0),
&Paint::fill(Color::linear(0.8, 0.8, 0.2, 1.0)),
)
.expect("sidebar");
}),
("a shadow that has to outlive its card", true, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.9, 0.9, 0.9, 1.0)),
)
.expect("ground");
canvas
.draw_shadow(
&Rect::new(32.0, 32.0, 96.0, 80.0).to_rounded_path(4.0),
Color::BLACK,
6.0,
false,
)
.expect("shadow");
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 80.0),
&Paint::fill(Color::WHITE),
)
.expect("card");
}),
("a rounded card, which occludes nothing", false, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.1, 0.5, 0.3, 1.0)),
)
.expect("wash");
canvas
.draw_rrect(
Rect::new(16.0, 16.0, 112.0, 112.0),
14.0,
&Paint::fill(Color::WHITE),
)
.expect("rounded card");
}),
("a translucent wash under an opaque bar", true, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.9, 0.9, 0.9, 1.0)),
)
.expect("ground");
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.0, 0.0, 0.0, 0.5)),
)
.expect("a half-transparent wash");
canvas
.draw_rect(
Rect::new(32.0, 32.0, 96.0, 80.0),
&Paint::fill(Color::WHITE),
)
.expect("bar");
}),
("a bar half a pixel off the grid", true, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.1, 0.2, 0.4, 1.0)),
)
.expect("wash");
canvas
.draw_rect(Rect::new(0.0, 0.0, 128.0, 32.5), &Paint::fill(Color::WHITE))
.expect("bar");
}),
("a clip and a layer over an opaque fill", false, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.2, 0.2, 0.6, 1.0)),
)
.expect("wash");
canvas.save();
canvas
.clip_path(&Rect::new(8.0, 8.0, 120.0, 72.0).to_rounded_path(12.0))
.expect("a stencil clip");
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::WHITE),
)
.expect("an opaque fill inside the clip");
canvas.restore();
canvas.save_layer(Layer::opacity(0.5));
canvas
.draw_rect(
Rect::new(40.0, 40.0, 100.0, 100.0),
&Paint::fill(Color::linear(1.0, 0.4, 0.0, 1.0)),
)
.expect("in the layer");
canvas.restore();
}),
(
"a bar over a wash, in a layer narrowed to them",
true,
|canvas| {
canvas.save_layer(Layer::opacity(0.5));
canvas
.draw_rect(
Rect::new(24.0, 40.0, 104.0, 120.0),
&Paint::fill(Color::linear(0.1, 0.6, 0.2, 1.0)),
)
.expect("wash");
canvas
.draw_rect(
Rect::new(56.0, 48.0, 96.0, 88.0),
&Paint::fill(Color::linear(0.9, 0.3, 0.1, 1.0)),
)
.expect("bar");
canvas.restore();
},
),
("a translucent mesh over a wash", false, |canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::fill(Color::linear(0.1, 0.2, 0.4, 1.0)),
)
.expect("wash");
let mesh = Vertices::full(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 0.0),
Vec2::new(128.0, 0.0),
Vec2::new(128.0, 128.0),
Vec2::new(0.0, 128.0),
],
Vec::new(),
vec![Color::linear(1.0, 0.0, 0.0, 0.25); 4],
vec![0, 1, 3, 1, 2, 3],
)
.expect("mesh");
canvas
.draw_vertices(&mesh, &Paint::fill(Color::WHITE))
.expect("mesh");
}),
];
for (name, culls, build) in scenes {
let record = |keep_hidden: bool| {
let mut canvas = Canvas::new(SIZE);
if keep_hidden {
canvas.keep_hidden_draws();
}
canvas.clear(Color::BLACK);
build(&mut canvas);
canvas.finish()
};
let (culled_recording, whole_recording) = (record(false), record(true));
let (culled_shape, whole_shape) = (shape(&culled_recording), shape(&whole_recording));
assert_eq!(
culled_shape != whole_shape,
culls,
"{name}: culled {culled_shape:?} against {whole_shape:?}, expected culling = {culls}"
);
let culled = render_recording(&mut ctx, &culled_recording);
let whole = render_recording(&mut ctx, &whole_recording);
assert_eq!(culled.len(), whole.len(), "{name}: different sizes");
let worst = culled
.iter()
.zip(&whole)
.enumerate()
.map(|(i, (a, b))| (a.abs_diff(*b), i, *a, *b))
.max();
let differing = culled.iter().zip(&whole).filter(|(a, b)| a != b).count();
if let Some((delta, index, got, want)) = worst {
assert_eq!(
delta,
0,
"{name}: byte {index} is {got} against {want}, {differing} of {} differ",
culled.len()
);
}
}
}
#[test]
fn a_scissor_does_not_change_what_a_derivative_free_draw_paints() {
let Some(mut ctx) = context() else { return };
let strips = [
Rect::new(0.0, 0.0, 128.0, 32.0),
Rect::new(0.0, 80.0, 128.0, 128.0),
Rect::new(0.0, 32.0, 32.0, 80.0),
Rect::new(96.0, 32.0, 128.0, 80.0),
];
let wash = |canvas: &mut Canvas| {
canvas
.draw_rect(
Rect::new(0.0, 0.0, 128.0, 128.0),
&Paint::default()
.with_shader(Shader::LinearGradient {
start: Vec2::new(0.0, 0.0),
end: Vec2::new(128.0, 128.0),
stops: vec![
GradientStop {
offset: 0.0,
color: Color::linear(0.1, 0.2, 0.6, 1.0),
},
GradientStop {
offset: 1.0,
color: Color::linear(0.9, 0.4, 0.1, 1.0),
},
],
tile: TileMode::Clamp,
})
.with_anti_alias(false),
)
.expect("gradient");
};
let once = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
wash(&mut canvas);
render_recording(&mut ctx, &canvas.finish())
};
let in_strips = {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
for strip in strips {
canvas.save();
canvas.clip_rect(strip).expect("a scissor");
wash(&mut canvas);
canvas.restore();
}
render_recording(&mut ctx, &canvas.finish())
};
let inside_card = |x: u32, y: u32| (32..96).contains(&x) && (32..80).contains(&y);
let mut worst = (0u8, 0u32, 0u32);
for y in 0..SIZE.height {
for x in 0..SIZE.width {
if inside_card(x, y) {
continue;
}
let (a, b) = (pixel(&once, x, y), pixel(&in_strips, x, y));
for channel in 0..4 {
let delta = a[channel].abs_diff(b[channel]);
if delta > worst.0 {
worst = (delta, x, y);
}
}
}
}
assert_eq!(
worst.0, 0,
"a scissored gradient differs from an unscissored one by {} at ({}, {})",
worst.0, worst.1, worst.2
);
}
fn about_the_middle(transform: Affine2) -> Transform2D {
let middle = Vec2::splat(64.0);
Transform2D::from(
Affine2::from_translation(middle) * transform * Affine2::from_translation(-middle),
)
}
fn quadrants_under(ctx: &mut Context, shader_transform: Transform2D) -> Vec<u8> {
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::linear(0.0, 0.0, 0.0, 1.0));
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_sampling(Sampling::Nearest)
.with_shader_transform(shader_transform)
.with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
}
#[test]
fn an_image_turns_and_mirrors_by_its_shader_transform_alone() {
let Some(mut ctx) = context() else { return };
let (red, green, blue, yellow) = (
[255u8, 0, 0, 255],
[0u8, 255, 0, 255],
[0u8, 0, 255, 255],
[255u8, 255, 0, 255],
);
let corners = |pixels: &[u8]| {
[
pixel(pixels, 16, 16),
pixel(pixels, 112, 16),
pixel(pixels, 16, 112),
pixel(pixels, 112, 112),
]
};
let half_turn = quadrants_under(&mut ctx, about_the_middle(Affine2::from_angle(PI)));
assert_eq!(
corners(&half_turn),
[yellow, blue, green, red],
"a half turn"
);
let quarter = quadrants_under(&mut ctx, about_the_middle(Affine2::from_angle(PI / 2.0)));
assert_eq!(
corners(&quarter),
[blue, red, yellow, green],
"a quarter turn"
);
let mirrored = quadrants_under(
&mut ctx,
about_the_middle(Affine2::from_scale(Vec2::new(-1.0, 1.0))),
);
assert_eq!(corners(&mirrored), [green, red, yellow, blue], "a mirror");
}
fn black_to_white() -> Vec<GradientStop> {
vec![
GradientStop::new(Color::linear(0.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(1.0, 1.0, 1.0, 1.0), 1.0),
]
}
fn gradient_shot(ctx: &mut Context, paint: Paint) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(Rect::from_size(128.0, 128.0), &paint.with_anti_alias(false))
.expect("gradient");
render(ctx, canvas)
}
#[test]
fn a_radial_gradient_stretched_by_its_shader_transform_is_an_ellipse() {
let Some(mut ctx) = context() else { return };
let pixels = gradient_shot(
&mut ctx,
Paint::radial_gradient(Vec2::splat(64.0), 40.0, black_to_white())
.with_shader_transform(about_the_middle(Affine2::from_scale(Vec2::new(2.0, 1.0)))),
);
close_enough(
pixel(&pixels, 64 + 60, 64),
pixel(&pixels, 64, 64 + 30),
2,
"equally far through an ellipse twice as wide as tall",
);
let (wide, tall) = (pixel(&pixels, 64 + 30, 64), pixel(&pixels, 64, 64 + 30));
assert!(
tall[0] > wide[0] + 40,
"the same distance is further through the ramp across the short axis: \
right {wide:?}, below {tall:?}"
);
}
#[test]
fn a_skewed_linear_gradient_slants_its_bands_inside_a_rectangle() {
let Some(mut ctx) = context() else { return };
let skew = Affine2::from_cols(Vec2::X, Vec2::new(0.5, 1.0), Vec2::ZERO);
let pixels = gradient_shot(
&mut ctx,
Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), black_to_white())
.with_shader_transform(Transform2D::from(skew)),
);
close_enough(
pixel(&pixels, 40, 0),
pixel(&pixels, 60, 40),
2,
"one band, slanted",
);
let (top, below) = (pixel(&pixels, 40, 0), pixel(&pixels, 40, 40));
assert!(
top[0] > below[0] + 20,
"straight down crosses bands: top {top:?}, below {below:?}"
);
}
#[test]
fn a_sweep_gradient_turns_with_its_shader_transform() {
let Some(mut ctx) = context() else { return };
let sweep = || Paint::sweep_gradient(Vec2::splat(64.0), 0.0, 2.0 * PI, black_to_white());
let plain = gradient_shot(&mut ctx, sweep());
let turned = gradient_shot(
&mut ctx,
sweep().with_shader_transform(about_the_middle(Affine2::from_angle(PI / 2.0))),
);
close_enough(
pixel(&turned, 64 - 30, 64),
pixel(&plain, 64, 64 + 30),
2,
"a quarter of the way round, a quarter turn on",
);
close_enough(
pixel(&turned, 64, 64 - 30),
pixel(&plain, 64 - 30, 64),
2,
"half way round, a quarter turn on",
);
}
#[test]
fn a_shader_transform_keeps_its_perspective() {
let Some(mut ctx) = context() else { return };
let mut m = [0.0f32; 16];
for i in [0, 5, 10, 15] {
m[i] = 1.0;
}
m[3] = 1.0 / 256.0;
let gradient = || Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), black_to_white());
let plain = gradient_shot(&mut ctx, gradient());
let projected = gradient_shot(
&mut ctx,
gradient().with_shader_transform(Transform2D::from_column_major_4x4(&m)),
);
close_enough(
pixel(&projected, 51, 64),
pixel(&plain, 64, 64),
3,
"the ramp's middle, divided through by w",
);
}
#[test]
fn a_textured_mesh_refuses_a_shader_transform_and_a_nine_slice_drops_its_paints() {
let mut canvas = Canvas::new(SIZE);
let mesh = Vertices::textured(
VertexMode::Triangles,
vec![
Vec2::new(0.0, 0.0),
Vec2::new(64.0, 0.0),
Vec2::new(0.0, 64.0),
],
vec![Vec2::ZERO, Vec2::X, Vec2::Y],
)
.expect("mesh");
let turned = Transform2D::from(Affine2::from_angle(0.5));
let refused = canvas
.draw_vertices(
&mesh,
&Paint::image(0, Rect::from_size(64.0, 64.0)).with_shader_transform(turned),
)
.map(|_| ());
assert!(
matches!(refused, Err(Error::Unsupported(why)) if why.contains("shader transform")),
"{refused:?}"
);
canvas
.draw_vertices(
&mesh,
&Paint::linear_gradient(Vec2::ZERO, Vec2::X, black_to_white())
.with_shader_transform(turned),
)
.expect("a gradient's space placed in the coordinates' space");
canvas
.draw_image_nine(
0,
Extent2D::new(4, 4),
Rect::new(1.0, 1.0, 3.0, 3.0),
Rect::from_size(64.0, 64.0),
&Paint::fill(Color::WHITE).with_shader_transform(turned),
)
.expect("a nine-slice's paint keeps its blend, not its shader");
}
fn every_shader_at(ctx: &mut Context, opacity: f32) -> Vec<Vec<u8>> {
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let stops = || {
vec![
GradientStop::new(Color::srgb(1.0, 0.8, 0.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.2, 0.4, 1.0, 1.0), 1.0),
]
};
let paints = [
Paint::fill(Color::srgb(0.9, 0.5, 0.2, 1.0)),
Paint::image(0, Rect::from_size(128.0, 128.0)).with_sampling(Sampling::Nearest),
Paint::linear_gradient(Vec2::ZERO, Vec2::new(128.0, 0.0), stops()),
Paint::radial_gradient(Vec2::splat(64.0), 60.0, stops()),
Paint::sweep_gradient(Vec2::splat(64.0), 0.0, 2.0 * PI, stops()),
Paint::conical_gradient(Vec2::splat(40.0), 4.0, Vec2::splat(64.0), 60.0, stops()),
];
let shots = paints
.into_iter()
.map(|paint| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_path(
&square_path(Rect::from_size(128.0, 128.0)),
&paint.with_opacity(opacity).with_anti_alias(false),
)
.expect("fill");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
pixels
})
.collect();
ctx.destroy_image(image);
shots
}
#[test]
fn a_paints_opacity_scales_what_every_shader_produces() {
let Some(mut ctx) = context() else { return };
let full = every_shader_at(&mut ctx, 1.0);
let half = every_shader_at(&mut ctx, 0.5);
let names = ["solid", "image", "linear", "radial", "sweep", "conical"];
for ((full, half), name) in full.iter().zip(&half).zip(names) {
for (x, y) in [(16, 16), (100, 30), (64, 64), (30, 110), (112, 112)] {
let f = pixel(full, x, y);
let want = [
(f32::from(f[0]) / 2.0).round() as u8,
(f32::from(f[1]) / 2.0).round() as u8,
(f32::from(f[2]) / 2.0).round() as u8,
255,
];
close_enough(pixel(half, x, y), want, 2, &format!("{name} at ({x}, {y})"));
}
}
}
#[test]
fn a_paints_opacity_survives_a_new_shader_and_reaches_the_rectangle_route() {
let Some(mut ctx) = context() else { return };
let gradient = Shader::LinearGradient {
start: Vec2::ZERO,
end: Vec2::new(128.0, 0.0),
stops: vec![
GradientStop::new(Color::srgb(1.0, 1.0, 1.0, 1.0), 0.0),
GradientStop::new(Color::srgb(0.0, 0.6, 1.0, 1.0), 1.0),
],
tile: TileMode::Clamp,
};
let paint = Paint::default()
.with_opacity(0.5)
.with_shader(gradient)
.with_anti_alias(false);
assert_eq!(paint.opacity, 0.5);
let shot = |ctx: &mut Context, rect_route: bool| {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if rect_route {
canvas.draw_rect(Rect::from_size(128.0, 128.0), &paint)
} else {
canvas.draw_path(&square_path(Rect::from_size(128.0, 128.0)), &paint)
}
.expect("fill");
render(ctx, canvas)
};
let (rect, path) = (shot(&mut ctx, true), shot(&mut ctx, false));
for x in [4, 40, 64, 90, 124] {
close_enough(
pixel(&rect, x, 64),
pixel(&path, x, 64),
2,
&format!("the two routes at x {x}"),
);
}
let left = pixel(&path, 4, 64);
assert!(
(120..=136).contains(&left[0]),
"white at half opacity over black: {left:?}"
);
}
#[test]
fn an_opacity_of_nothing_or_not_a_number_draws_nothing_and_a_runtime_effect_keeps_its_color() {
let solid = Paint::fill(Color::WHITE);
assert!(!solid.clone().with_opacity(0.0).is_visible());
assert!(!solid.clone().with_opacity(f32::NAN).is_visible());
assert!(!solid.clone().with_opacity(-1.0).is_visible());
assert_eq!(
*solid.clone().with_opacity(4.0).effective_shader(),
Shader::Solid(Color::WHITE)
);
let effect = Paint::runtime_effect(0, vec![0.5; 4]).with_opacity(0.25);
assert_eq!(*effect.effective_shader(), effect.shader);
assert!(effect.is_visible());
}
fn sweep_shot(ctx: &mut Context, start: f32, end: f32, tile: TileMode) -> Vec<u8> {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_rect(
Rect::from_size(128.0, 128.0),
&Paint::sweep_gradient(
Vec2::splat(64.0),
start,
end,
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
],
)
.with_tile_mode(tile)
.with_anti_alias(false),
)
.expect("sweep");
render(ctx, canvas)
}
fn toward(pixels: &[u8], angle: f32) -> [u8; 4] {
let (s, c) = angle.sin_cos();
pixel(
pixels,
(64.0 + 40.0 * c).round() as u32,
(64.0 + 40.0 * s).round() as u32,
)
}
#[test]
fn a_sweep_measures_its_angle_from_the_positive_x_axis_as_upstream_does() {
let Some(mut ctx) = context() else { return };
let (red, blue) = ([255u8, 0, 0, 255], [0u8, 0, 255, 255]);
let clamped = sweep_shot(&mut ctx, PI / 4.0, PI, TileMode::Clamp);
close_enough(
toward(&clamped, PI / 8.0),
red,
2,
"before the start, clamped",
);
close_enough(toward(&clamped, 1.5 * PI), blue, 2, "past the end, clamped");
let decal = sweep_shot(&mut ctx, PI / 4.0, PI, TileMode::Decal);
close_enough(
toward(&decal, PI / 8.0),
[0, 0, 0, 255],
2,
"before the start, decal",
);
let across = sweep_shot(&mut ctx, -PI / 2.0, PI / 2.0, TileMode::Clamp);
close_enough(
toward(&across, -PI / 8.0),
blue,
2,
"above the axis, past the end",
);
let below = toward(&across, PI / 8.0);
assert!(
below[0] > 60 && below[2] > 60,
"below the axis, inside the arc, a mix of both: {below:?}"
);
}
fn atlas_tinted(ctx: &mut Context, color: Color, mode: BlendMode) -> Vec<u8> {
atlas_tinted_at(ctx, color, mode, 1.0)
}
fn atlas_tinted_at(ctx: &mut Context, color: Color, mode: BlendMode, opacity: f32) -> Vec<u8> {
let mut image = ctx
.create_image(Extent2D::new(4, 4), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &quadrant_image())
.expect("upload");
let sprites: Vec<Sprite> = shuffled_quadrants()
.into_iter()
.map(|s| s.with_color(color))
.collect();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_atlas(
&sprites,
Extent2D::new(4, 4),
&Paint::image(0, Rect::from_size(128.0, 128.0))
.with_tint_blend(mode)
.with_opacity(opacity),
)
.expect("atlas");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
}
#[test]
fn an_atlas_blends_the_sprite_over_its_color_in_dart_uis_order() {
let Some(mut ctx) = context() else { return };
let magenta = Color::srgb(1.0, 0.0, 1.0, 1.0);
let over = atlas_tinted(&mut ctx, magenta, BlendMode::SrcOver);
assert_eq!(
pixel(&over, 32, 32),
[255, 255, 0, 255],
"the sheet's yellow"
);
assert_eq!(pixel(&over, 96, 96), [255, 0, 0, 255], "the sheet's red");
let dst = atlas_tinted(&mut ctx, magenta, BlendMode::Dst);
assert_eq!(pixel(&dst, 32, 32), [255, 0, 255, 255], "the color alone");
let modulated = atlas_tinted(&mut ctx, magenta, BlendMode::Modulate);
assert_eq!(
pixel(&modulated, 32, 32),
[255, 0, 0, 255],
"yellow times magenta"
);
}
#[test]
fn an_atlas_fades_after_its_blend() {
let Some(mut ctx) = context() else { return };
let magenta = Color::srgb(1.0, 0.0, 1.0, 1.0);
let over = atlas_tinted_at(&mut ctx, magenta, BlendMode::SrcOver, 0.5);
close_enough(
pixel(&over, 32, 32),
[128, 128, 0, 255],
2,
"half the yellow",
);
close_enough(pixel(&over, 96, 96), [128, 0, 0, 255], 2, "half the red");
let dst = atlas_tinted_at(&mut ctx, magenta, BlendMode::Dst, 0.5);
close_enough(
pixel(&dst, 32, 32),
[128, 0, 128, 255],
2,
"half the magenta",
);
let modulated = atlas_tinted_at(&mut ctx, magenta, BlendMode::Modulate, 0.5);
close_enough(
pixel(&modulated, 32, 32),
[128, 0, 0, 255],
2,
"half of red",
);
}
#[test]
fn a_nine_slice_fades_by_its_paints_opacity() {
let Some(mut ctx) = context() else { return };
let shot = |ctx: &mut Context, opacity: f32| {
let mut image = ctx
.create_image(Extent2D::new(12, 12), PixelFormat::Rgba8Unorm)
.expect("image");
ctx.write_image(&mut image, &nine_region_image())
.expect("upload");
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas
.draw_image_nine(
0,
Extent2D::new(12, 12),
Rect::new(4.0, 4.0, 8.0, 8.0),
Rect::new(8.0, 8.0, 120.0, 120.0),
&Paint::fill(Color::WHITE)
.with_opacity(opacity)
.with_anti_alias(false),
)
.expect("nine patch");
let mut surface = ctx
.create_surface(SIZE, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw_with_images(&mut surface, &canvas.finish(), &[&image])
.expect("draw");
let pixels = ctx.read(&mut surface).expect("read");
ctx.destroy_surface(surface);
ctx.destroy_image(image);
pixels
};
let (full, half) = (shot(&mut ctx, 1.0), shot(&mut ctx, 0.5));
for (x, y) in [(12, 12), (64, 12), (64, 64), (116, 116), (12, 90)] {
let f = pixel(&full, x, y);
let want = [
(f32::from(f[0]) / 2.0).round() as u8,
(f32::from(f[1]) / 2.0).round() as u8,
(f32::from(f[2]) / 2.0).round() as u8,
255,
];
close_enough(pixel(&half, x, y), want, 2, &format!("({x}, {y})"));
}
}
#[test]
fn a_bounded_backdrop_filters_what_is_behind_it() {
let Some(mut ctx) = context() else { return };
for (scale, clipped, bounded) in [
(1.0, false, true),
(1.0, true, false),
(2.0, true, false),
(2.0, true, true),
] {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::WHITE);
canvas.save();
canvas.scale(scale, scale);
let s = 64.0 / scale;
let red = Paint::fill(Color::srgb(1.0, 0.0, 0.0, 1.0));
let blue = Paint::fill(Color::srgb(0.0, 0.0, 1.0, 1.0));
canvas
.draw_rect(Rect::new(0.0, 0.0, s, 2.0 * s), &red)
.expect("red");
canvas
.draw_rect(Rect::new(s, 0.0, 2.0 * s, 2.0 * s), &blue)
.expect("blue");
let region = Rect::new(1.25 * s, 0.25 * s, 1.75 * s, 0.75 * s);
if clipped {
canvas.save();
canvas.clip_rect(region).expect("clip");
}
canvas
.save_layer_backdrop(
Layer::opacity(1.0),
bounded.then_some(region),
&half_every_channel(),
)
.expect("backdrop");
canvas.restore();
if clipped {
canvas.restore();
}
canvas.restore();
let shot = render(&mut ctx, canvas);
for (x, y) in [(82, 18), (96, 32), (110, 46)] {
let got = pixel(&shot, x, y);
assert!(
got[0] <= 2 && got[2].abs_diff(128) <= 2,
"scale {scale}, clipped {clipped}, bounded {bounded}: at ({x}, {y}) the \
backdrop should be the blue behind it halved, and is {got:?}"
);
}
}
}
const LOCAL_RAMP: f32 = 64.0;
fn local_effect(ctx: &mut Context) -> u32 {
ctx.register_program(&emblema::RuntimeProgram {
spirv: emblema_shaders::EFFECT_LOCAL_SPV.to_vec(),
glsl_es: emblema_shaders::EFFECT_LOCAL_FS_GLSL.to_string(),
})
.expect("register")
}
fn local_uniforms() -> Vec<f32> {
let mut out = vec![0.0; RUNTIME_FLOATS];
out[20] = LOCAL_RAMP;
out
}
#[test]
fn a_runtime_effect_reads_its_own_position_under_a_transform() {
#[rustfmt::skip]
let perspective: [f32; 16] = [
1.2, 0.0, 0.0, 0.004,
0.1, 1.0, 0.0, 0.002,
0.0, 0.0, 1.0, 0.0,
20.0, 24.0, 0.0, 1.0,
];
type Inverse = fn(f32, f32) -> (f32, f32);
type Place<'a> = &'a dyn Fn(&mut Canvas);
let cases: [(&str, Place, Inverse); 4] = [
("identity", &|_| {}, |x, y| (x, y)),
(
"translated and scaled",
&|c| {
c.translate(32.0, 16.0).scale(1.5, 1.5);
},
|x, y| ((x - 32.0) / 1.5, (y - 16.0) / 1.5),
),
(
"rotated a quarter turn",
&|c| {
c.translate(100.0, 10.0).rotate(PI / 2.0);
},
|x, y| (y - 10.0, 100.0 - x),
),
(
"in perspective",
&move |c| {
c.concat_4x4(&perspective);
},
|x, y| {
let (a, b, c, d, tx, ty, p, q) = (1.2, 0.0, 0.1, 1.0, 20.0, 24.0, 0.004, 0.002);
let (m00, m01, r0) = (a - p * x, c - q * x, x - tx);
let (m10, m11, r1) = (b - p * y, d - q * y, y - ty);
let det = m00 * m11 - m01 * m10;
((r0 * m11 - m01 * r1) / det, (m00 * r1 - m10 * r0) / det)
},
),
];
let mut ran = 0;
for preference in [BackendPreference::Vulkan, BackendPreference::Gles] {
let Ok(mut ctx) = Context::new(preference) else {
eprintln!("skipping {preference:?}: not available");
continue;
};
ran += 1;
let program = local_effect(&mut ctx);
for (name, place, inverse) in &cases {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
place(&mut canvas);
canvas
.draw_rect(
Rect::new(0.0, 0.0, LOCAL_RAMP, LOCAL_RAMP),
&Paint::runtime_effect(program, local_uniforms()).with_anti_alias(false),
)
.expect("effect");
let pixels = render(&mut ctx, canvas);
let mut checked = 0;
for y in (0..SIZE.height).step_by(3) {
for x in (0..SIZE.width).step_by(3) {
let (lx, ly) = inverse(x as f32 + 0.5, y as f32 + 0.5);
let inside = 2.0..LOCAL_RAMP - 2.0;
if !inside.contains(&lx) || !inside.contains(&ly) {
continue;
}
let level = |v: f32| (v / LOCAL_RAMP * 255.0).round() as u8;
close_enough(
pixel(&pixels, x, y),
[level(lx), level(ly), 0, 255],
2,
&format!("{preference:?}, {name}, at ({x}, {y})"),
);
checked += 1;
}
}
assert!(checked > 50, "{name}: only {checked} pixels fell inside");
}
}
if ran == 0 {
eprintln!("skipping: no backend available");
}
}
#[test]
fn a_drawn_surface_is_sampled_as_an_image_on_both_backends() {
let extent = Extent2D::new(16, 16);
for mut ctx in every_backend() {
let backend = format!("{:?}", ctx.backend());
let mut first = Canvas::new(extent);
first.clear(Color::TRANSPARENT);
first
.draw_rect(
Rect::new(0.0, 0.0, 8.0, 16.0),
&Paint::fill(Color::srgb(1.0, 0.0, 0.0, 1.0)).with_anti_alias(false),
)
.expect("rect");
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("surface");
ctx.draw(&mut surface, &first.finish()).expect("draw");
let drawn = ctx.read(&mut surface).expect("read the surface");
let mut image = surface.into_image();
assert_eq!(image.extent(), extent, "{backend}");
let read = ctx.read_image(&mut image).expect("read the image");
assert_eq!(read, drawn, "{backend}: the image is not what was drawn");
let mut second = Canvas::new(extent);
second.clear(Color::srgb(0.0, 0.0, 1.0, 1.0));
second
.draw_rect(
Rect::new(0.0, 0.0, 16.0, 16.0),
&Paint::image(0, Rect::new(0.0, 0.0, 16.0, 16.0)).with_anti_alias(false),
)
.expect("image");
let mut target = ctx
.create_surface(extent, PixelFormat::Rgba8Unorm)
.expect("target");
ctx.draw_with_images(&mut target, &second.finish(), &[&image])
.expect("draw the image");
let pixels = ctx.read(&mut target).expect("read");
let at = |x: u32, y: u32| {
let i = ((y * extent.width + x) * 4) as usize;
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
};
assert_eq!(at(3, 8), [255, 0, 0, 255], "{backend}: the left half");
assert_eq!(at(12, 8), [0, 0, 255, 255], "{backend}: the right half");
ctx.destroy_surface(target);
ctx.destroy_image(image);
}
}
#[test]
fn a_float32_surface_reads_back_as_floats_on_both_backends() {
let extent = Extent2D::new(4, 4);
for mut ctx in every_backend() {
let backend = format!("{:?}", ctx.backend());
if !ctx
.capabilities()
.float32(PixelFormat::Rgba32Float)
.is_some_and(|f| f.render)
{
eprintln!("skipping {backend}: no Rgba32Float target");
continue;
}
let third = 1.0f32 / 3.0;
let mut canvas = Canvas::new(extent);
canvas.clear(Color::srgb(third, 0.5, 0.25, 1.0));
let mut surface = ctx
.create_surface(extent, PixelFormat::Rgba32Float)
.expect("surface");
ctx.draw(&mut surface, &canvas.finish()).expect("draw");
let mut image = surface.into_image();
let bytes = ctx.read_image(&mut image).expect("read");
ctx.destroy_image(image);
assert_eq!(bytes.len(), 4 * 4 * 16, "{backend}");
let floats: Vec<f32> = bytes
.chunks_exact(4)
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
for texel in floats.chunks_exact(4) {
assert_eq!(texel, [third, 0.5, 0.25, 1.0], "{backend}");
}
}
}