Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.2

0.6.2 / src / gpu_player / tests_gpu_player.lucb

#==============================================================================================
#
#   tests_gpu_player - the GPU player against the CPU player
#
#   DESCRIPTION:
#       Each scene is a display list drawn by the CPU player into a surface and by the GPU
#       compositor into an offscreen texture of the same size (crossing tile edges), then
#       compared pixel by pixel within a fuzzy bound (how far a channel may be off, and how
#       many pixels may be off by more), as Ladybird's ref tests compare. A machine without a
#       GPU device skips them. Scrolling scenes draw again at another offset and check that
#       the kept tiles were moved, not drawn again.
#
#       Copyright (c) 2026 the luce-browser authors.
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Support =================================================================================

let test_width: i32 = 700
let test_height: i32 = 300

## A color from its channels.
func test_rgba(r: u8, g: u8, b: u8, a: u8) -> gfx.Color:
    return gfx.Color(m_value = ((u32)a << 24) | ((u32)r << 16) | ((u32)g << 8) | (u32)b)

## A device rectangle.
func test_box(x: i32, y: i32, width: i32, height: i32) -> gfx.DevicePixelRect:
    return gfx.DevicePixelRect(m_location = gfx.IntPoint(m_x = x, m_y = y), m_size = gfx.IntSize(m_width = width, m_height = height))

## The same radius at every corner.
func test_radii(radius: i32) -> display_list.CornerRadii:
    let r = display_list.CornerRadius(horizontal_radius = radius, vertical_radius = radius)
    return display_list.CornerRadii(top_left = r, top_right = r, bottom_right = r, bottom_left = r)

## A scene's list: commands appended under `context`.
struct TestList:
    var tree: display_list.AccumulatedVisualContextTree*
    var list: display_list.DisplayList*

## An empty list whose tree has the viewport's scroll node (frame 1) as node 1.
func test_list() -> TestList:
    let tree = display_list.accumulated_visual_context_tree_create()
    _ = display_list.accumulated_visual_context_tree_append(tree, display_list.VisualContextData.scroll_data(display_list.ScrollData(scroll_frame_index = 1, is_sticky = false)), 0)
    return TestList(tree = tree, list = display_list.display_list_create(tree))

## Appends `command` under node `context` (0: none, 1: the scroll node).
func test_add(scene: const TestList*, command: display_list.DisplayListCommand, context: u64):
    _ = display_list.display_list_append(scene.list, command, context)

## A snapshot with frame 1 scrolled by (`x`, `y`) device pixels.
func test_snapshot(x: f32, y: f32) -> display_list.ScrollStateSnapshot:
    var snapshot: display_list.ScrollStateSnapshot
    ak.vector_append_t(&snapshot.m_device_offsets, gfx.FloatPoint(m_x = 0.0, m_y = 0.0))
    ak.vector_append_t(&snapshot.m_device_offsets, gfx.FloatPoint(m_x = -x, m_y = -y))
    return snapshot

## The CPU player's frame of `scene` as premultiplied RGBA bytes.
func test_cpu_frame(scene: const TestList*, snapshot: const display_list.ScrollStateSnapshot*, out: u8[]):
    let player = display_list.display_list_player_cpu_create()
    let surface = gfx.painting_surface_create_with_size(gfx.IntSize(m_width = test_width, m_height = test_height), gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied)
    display_list.display_list_player_execute((display_list.DisplayListPlayer*)player, scene.list, snapshot, surface)
    let bitmap = gfx.painting_surface_bitmap(surface)
    for y in 0..<test_height:
        let row = gfx.bitmap_scanline_const(bitmap, y) else trap("scanline")
        for x in 0..<test_width:
            let value = row[(usize)x]
            let at = ((usize)y * (usize)test_width + (usize)x) * 4
            out[at] = (u8)((value >> 16) & 0xff)
            out[at + 1] = (u8)((value >> 8) & 0xff)
            out[at + 2] = (u8)(value & 0xff)
            out[at + 3] = (u8)(value >> 24)

## The GPU compositor's frame of `scene` into `texture`, read back into `out`.
func test_gpu_frame(compositor: GpuCompositor*, texture: gpu.Texture, scene: const TestList*, snapshot: const display_list.ScrollStateSnapshot*, out: u8[]) -> !:
    let frame = try texture.frame()
    defer frame.release()
    let target = try frame.value().target()
    defer target.release()
    try gpu_compositor_draw(compositor, scene.list, snapshot, target.value(), test_width, test_height)
    _ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 0.0))
    try texture.read(out)

## Draws `scene` both ways at the scroll offsets of `snapshots` and traps when more than
## `max_pixels` pixels differ by more than `max_difference` in a channel; answers the
## compositor's statistics after the last frame. The GPU draws into a texture of
## `target_format`: rgba8 composites through the frame texture and its decode, rgba8_linear
## (which blends on stored values, as an encoded surface does) takes the tiles directly.
func test_compare(name: str, scene: const TestList*, snapshots: const display_list.ScrollStateSnapshot[], max_difference: i32, max_pixels: usize,
                  target_format: gpu.Format = gpu.Format.rgba8) -> GpuPlayerStats?:
    # Frames this large need the process heap, not a test's bounded one.
    with memory.heap:
        var device = gpu.Device.open() catch failure: return none
        defer device.destroy()
        var texture = gpu.Texture.create(device, (u32)test_width, (u32)test_height, target_format) catch failure: trap(f"{name}: {failure.message}")
        defer texture.destroy()
        let compositor = gpu_compositor_create()
        defer gpu_compositor_destroy(compositor)
        let bytes = (usize)test_width * (usize)test_height * 4
        let expected = (new u8[bytes] --- in memory.heap) else trap("out of memory")
        let actual = (new u8[bytes] --- in memory.heap) else trap("out of memory")
        defer free(expected) in memory.heap
        defer free(actual) in memory.heap
        gpu_player_reset_stats()
        for snapshot in snapshots:
            test_cpu_frame(scene, &snapshot, expected)
            test_gpu_frame(compositor, texture, scene, &snapshot, actual) catch failure: trap(f"{name}: {failure.message}")
            var worst: i32 = 0
            var differing: usize = 0
            var at: usize = 0
            while at < bytes:
                var pixel_worst: i32 = 0
                for channel in 0..<(usize)4:
                    let d = (i32)expected[at + channel] - (i32)actual[at + channel]
                    let magnitude = d if d >= 0 else -d
                    pixel_worst = gpu_max(pixel_worst, magnitude)
                worst = gpu_max(worst, pixel_worst)
                if pixel_worst > max_difference:
                    if pixel_worst > 20:
                        let p = at // 4
                        print(f"{name}: pixel ({p % (usize)test_width}, {p // (usize)test_width}) cpu {expected[at]} {expected[at + 1]} {expected[at + 2]} {expected[at + 3]} gpu {actual[at]} {actual[at + 1]} {actual[at + 2]} {actual[at + 3]}")
                    differing += 1
                at += 4
            if differing > max_pixels:
                print(f"{name}: {differing} pixels differ by more than {max_difference} (worst {worst})")
                trap("the GPU player's pixels are not close enough to the CPU player's")
        return gpu_player_stats()

## An opaque page background over the whole frame, outside any scroll node.
func test_background(scene: const TestList*):
    test_add(scene, display_list.DisplayListCommand.fill_rect(display_list.FillRect(rect = test_box(0, 0, test_width, test_height), color = test_rgba(250, 250, 245, 255))), 0)

# mark: Scenes ==================================================================================

test "gpu player: rectangles, clips and translations match the CPU player":
    let scene = test_list()
    test_background(&scene)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(10, 10, 600, 40), color = test_rgba(200, 30, 30, 255))), 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(500, 30, 60, 200), color = test_rgba(20, 90, 200, 128))), 1)
    test_add(&scene, .save(display_list.Save()), 1)
    test_add(&scene, .add_clip_rect(display_list.AddClipRect(rect = test_box(100, 100, 450, 80))), 1)
    test_add(&scene, .translate(display_list.Translate(delta = gfx.IntPoint(m_x = 7, m_y = 3))), 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(80, 90, 600, 200), color = test_rgba(30, 160, 60, 255))), 1)
    test_add(&scene, .restore(display_list.Restore()), 1)
    test_add(&scene, .draw_rect(display_list.DrawRect(rect = test_box(20, 200, 300, 60), color = test_rgba(0, 0, 0, 255), rough = false)), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 37.0)]
    _ = test_compare("rectangles", &scene, snapshots, 2, 0)
    # The same straight onto a target that blends on stored values, with no frame texture.
    _ = test_compare("rectangles, direct", &scene, snapshots, 2, 0, gpu.Format.rgba8_linear)

test "gpu player: rounded rectangles and rounded clips match the CPU player within a fuzzy bound":
    let scene = test_list()
    test_background(&scene)
    test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(20, 20, 300, 120), color = test_rgba(40, 120, 220, 255), corner_radii = test_radii(18))), 1)
    test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(480, 60, 120, 200), color = test_rgba(240, 160, 60, 200), corner_radii = test_radii(40))), 1)
    test_add(&scene, .save(display_list.Save()), 1)
    test_add(&scene, .add_rounded_rect_clip(display_list.AddRoundedRectClip(corner_radii = test_radii(24), border_rect = test_box(60, 160, 380, 120), corner_clip = display_list.CornerClip.outside)), 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(0, 150, 700, 150), color = test_rgba(20, 140, 70, 255))), 1)
    test_add(&scene, .restore(display_list.Restore()), 1)
    let snapshots = [test_snapshot(0.0, 0.0)]
    # Analytic coverage differs from Skia's scan conversion on corner pixels only.
    _ = test_compare("rounded", &scene, snapshots, 40, 400)

test "gpu player: a path filled with a color is the CPU player's coverage":
    let scene = test_list()
    test_background(&scene)
    var path: gfx.Path
    gfx.path_move_to(&path, gfx.FloatPoint(m_x = 30.0, m_y = 30.0))
    gfx.path_line_to(&path, gfx.FloatPoint(m_x = 640.5, m_y = 40.0))
    gfx.path_line_to(&path, gfx.FloatPoint(m_x = 420.0, m_y = 260.25))
    gfx.path_close(&path)
    let bounds = test_box(30, 30, 611, 231)
    test_add(&scene, .fill_path(display_list.FillPath(path_bounding_rect = bounds, path = path, opacity = 1.0, paint_style_or_color = .color(test_rgba(90, 20, 160, 255)),
                                                      winding_rule = gfx.WindingRule.even_odd, should_anti_alias = display_list.ShouldAntiAlias.yes)), 1)
    let snapshots = [test_snapshot(0.0, 0.0)]
    _ = test_compare("path", &scene, snapshots, 2, 0)

test "gpu player: lines are the CPU player's strokes":
    let scene = test_list()
    test_background(&scene)
    let styles = [gfx.LineStyle.solid, gfx.LineStyle.dotted, gfx.LineStyle.dashed]
    for i in 0..<(i32)3:
        test_add(&scene, .draw_line(display_list.DrawLine(color = test_rgba(0, 0, 200, 255), from_ = gfx.IntPoint(m_x = 20, m_y = 30 + i * 40), to = gfx.IntPoint(m_x = 650, m_y = 30 + i * 40),
                                                          thickness = 1 + i * 2, style = styles[(usize)i], alternate_color = test_rgba(0, 0, 0, 0))), 1)
    test_add(&scene, .draw_line(display_list.DrawLine(color = test_rgba(200, 0, 0, 255), from_ = gfx.IntPoint(m_x = 600, m_y = 10), to = gfx.IntPoint(m_x = 600, m_y = 290),
                                                      thickness = 3, style = gfx.LineStyle.solid, alternate_color = test_rgba(0, 0, 0, 0))), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 21.0)]
    _ = test_compare("lines", &scene, snapshots, 2, 0)

test "gpu player: outer box shadows are the CPU player's blurred masks":
    let scene = test_list()
    test_background(&scene)
    for i in 0..<(i32)3:
        let x = 40 + i * 220
        test_add(&scene, .paint_outer_box_shadow(display_list.PaintOuterBoxShadow(color = test_rgba(0, 0, 0, 90), blur_radius = 6 + i * 8, device_content_rect = test_box(x, 60, 160, 120),
                                                                                  content_corner_radii = test_radii(i * 10), shadow_rect = test_box(x + 4, 66, 160, 120), shadow_corner_radii = test_radii(i * 10))), 1)
        test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(x, 60, 160, 120), color = test_rgba(255, 255, 255, 255), corner_radii = test_radii(i * 10))), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 13.0)]
    _ = test_compare("shadows", &scene, snapshots, 40, 300)

test "gpu player: images are sampled as the CPU player samples them":
    let scene = test_list()
    test_background(&scene)
    let bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, gfx.IntSize(m_width = 8, m_height = 6)) else trap("bitmap")
    for j in 0..<(i32)6:
        let row = gfx.bitmap_scanline(bitmap, j) else trap("scanline")
        for i in 0..<(i32)8:
            row[(usize)i] = 0xff000000 | ((u32)(i * 32) << 16) | ((u32)(j * 40) << 8) | (u32)((i + j) % 2 * 255)
    var color_space: gfx.ColorSpace = ---
    gfx.color_space_construct(&color_space)
    let image = gfx.immutable_bitmap_create_color_space(bitmap, color_space)
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(10, 10, 8, 6), clip_rect = test_box(0, 0, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.nearest_neighbor)), 1)
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(40, 20, 160, 120), clip_rect = test_box(0, 0, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.nearest_neighbor)), 1)
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(420, 20, 240, 180), clip_rect = test_box(430, 30, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.bilinear)), 1)
    let snapshots = [test_snapshot(0.0, 0.0)]
    _ = test_compare("image", &scene, snapshots, 3, 0)

test "gpu player: a scroll moves kept tiles; unsupported commands fall back per tile":
    let scene = test_list()
    test_background(&scene)
    for i in 0..<(i32)30:
        test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(20 + i * 7, i * 40, 200, 30), color = test_rgba((u8)(i * 8), 100, 200, 255))), 1)
    # A shape under perspective far down the page: its tile is the CPU player's.
    var matrix = gfx.scale_matrix(gfx.FloatVector3([1.0, 1.0, 1.0]))
    matrix.m_elements[3][0] = 0.0005
    let tilted = display_list.accumulated_visual_context_tree_append(scene.tree, display_list.VisualContextData.transform_data(display_list.TransformData(matrix = matrix, origin = gfx.FloatPoint(m_x = 100.0, m_y = 1100.0))), 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(100, 1100, 300, 50), color = test_rgba(255, 0, 0, 255))), tilted)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 100.0), test_snapshot(0.0, 400.0), test_snapshot(0.0, 900.0)]
    let stats = test_compare("scroll", &scene, snapshots, 2, 0) else return
    # Without tiles kept, four frames of two layers would draw 4 x (2 + 2) tiles or more.
    if stats.gpu_tiles + stats.cpu_tiles + stats.empty_tiles > 12:
        print(f"scroll: {stats.gpu_tiles} GPU, {stats.cpu_tiles} CPU and {stats.empty_tiles} empty tiles drawn")
        trap("a scroll drew kept tiles again")
    if stats.cpu_tiles == 0 or stats.fallbacks[(usize)GpuFallback.perspective] == 0:
        trap("the tile under perspective did not fall back to the CPU player")

test "gpu player: nested rounded clips go through a clip mask, not to the CPU":
    let scene = test_list()
    test_background(&scene)
    for i in 0..<(i32)3:
        let x = 30 + i * 220
        test_add(&scene, .save(display_list.Save()), 1)
        test_add(&scene, .add_rounded_rect_clip(display_list.AddRoundedRectClip(corner_radii = test_radii(30), border_rect = test_box(x, 20, 180, 240), corner_clip = display_list.CornerClip.outside)), 1)
        test_add(&scene, .add_rounded_rect_clip(display_list.AddRoundedRectClip(corner_radii = test_radii(20 + i * 10), border_rect = test_box(x + 20, 60, 180, 220), corner_clip = display_list.CornerClip.outside)), 1)
        test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(x - 10, 0, 220, 300), color = test_rgba(30, 90 + (u8)(i * 50), 200, 255))), 1)
        test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(x + 40, 120, 100, 60), color = test_rgba(250, 200, 40, 255), corner_radii = test_radii(12))), 1)
        test_add(&scene, .restore(display_list.Restore()), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 9.0)]
    let stats = test_compare("nested clips", &scene, snapshots, 40, 900) else return
    if stats.cpu_tiles > 0:
        trap("nested rounded clips sent a tile to the CPU player")

test "gpu player: an image drawn smaller samples its mipmaps":
    let scene = test_list()
    test_background(&scene)
    let bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, gfx.IntSize(m_width = 256, m_height = 256)) else trap("bitmap")
    for j in 0..<(i32)256:
        let row = gfx.bitmap_scanline(bitmap, j) else trap("scanline")
        for i in 0..<(i32)256:
            # Stripes four texels wide: drawn at a quarter, they average to grey.
            let on = (i // 4 + j // 4) % 2 == 0
            row[(usize)i] = 0xff000000 | (0x00e0e0e0 if on else 0x00202020)
    var color_space: gfx.ColorSpace = ---
    gfx.color_space_construct(&color_space)
    let image = gfx.immutable_bitmap_create_color_space(bitmap, color_space)
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(40, 40, 64, 64), clip_rect = test_box(0, 0, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.bilinear_mipmap)), 1)
    # Between levels (a weight), and an odd size (the 1-2-1 downsampler).
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(150, 30, 101, 87), clip_rect = test_box(0, 0, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.bilinear_mipmap)), 1)
    test_add(&scene, .draw_scaled_immutable_bitmap(display_list.DrawScaledImmutableBitmap(dst_rect = test_box(300, 30, 37, 200), clip_rect = test_box(0, 0, 700, 300), bitmap = image, scaling_mode = gfx.ScalingMode.bilinear_mipmap)), 1)
    let snapshots = [test_snapshot(0.0, 0.0)]
    # Skia's own levels, chosen and blended as its pattern blends them.
    let stats = test_compare("mipmaps", &scene, snapshots, 2, 0) else return
    if stats.cpu_tiles > 0:
        trap("a downscaled image sent a tile to the CPU player")

test "gpu player: a full atlas grows and draws on, without a CPU tile":
    let scene = test_list()
    test_background(&scene)
    # Sixty distinct paths of up to 300 pixels a side: more coverage than 2048 squared holds.
    for i in 0..<(i32)60:
        var path: gfx.Path
        let x = (f32)(10 + (i * 37) % 380)
        let y = (f32)(5 + (i * 23) % 20)
        let size = (f32)(200 + (i * 13) % 100)
        gfx.path_move_to(&path, gfx.FloatPoint(m_x = x, m_y = y))
        gfx.path_line_to(&path, gfx.FloatPoint(m_x = x + size, m_y = y + 3.5))
        gfx.path_line_to(&path, gfx.FloatPoint(m_x = x + size * 0.5, m_y = y + size * 0.9))
        gfx.path_close(&path)
        let bounds = test_box((i32)x, (i32)y, (i32)size + 1, (i32)(size * 0.9) + 1)
        test_add(&scene, .fill_path(display_list.FillPath(path_bounding_rect = bounds, path = path, opacity = 1.0, paint_style_or_color = .color(test_rgba((u8)(i * 4), 40, 160, 60)),
                                                          winding_rule = gfx.WindingRule.even_odd, should_anti_alias = display_list.ShouldAntiAlias.yes)), 1)
    let snapshots = [test_snapshot(0.0, 0.0)]
    # Sixty translucent layers: blending in floats drifts from Skia's 8-bit lowp by a few.
    let stats = test_compare("atlas", &scene, snapshots, 6, 0) else return
    if stats.cpu_tiles > 0:
        trap("a full atlas sent a tile to the CPU player")
    # The resident count holds the atlas: 4096 squared once it grew.
    if stats.resident_bytes < (u64)(gpu_atlas_largest * gpu_atlas_largest):
        trap("the atlas did not grow")

## Appends an effects node (opacity, blend operator) under node `parent`; answers its index.
func test_effects(scene: const TestList*, opacity: f32, operator: gfx.CompositingAndBlendingOperator, parent: u64) -> u64:
    let data = display_list.EffectsData(opacity = opacity, blend_mode = operator, gfx_filter = none)
    return display_list.accumulated_visual_context_tree_append(scene.tree, display_list.VisualContextData.effects_data(data), parent)

test "gpu player: opacity groups, blend modes and isolated groups are layers on the GPU":
    let scene = test_list()
    # The background in the plane the blends are in: a blend reads only what its plane drew.
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(0, -20, test_width, test_height + 40), color = test_rgba(250, 250, 245, 255))), 1)
    # Stripes under everything, so the blend modes have a backdrop to blend with.
    for i in 0..<(i32)14:
        test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(i * 50, 0, 25, 300), color = test_rgba((u8)(i * 18), 120, (u8)(255 - i * 18), 255))), 1)
    # A group at half opacity: its overlapping shapes do not show through each other.
    let half = test_effects(&scene, 0.5, gfx.CompositingAndBlendingOperator.normal, 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(20, 20, 120, 80), color = test_rgba(220, 40, 40, 255))), half)
    test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(70, 50, 120, 80), color = test_rgba(40, 40, 220, 255), corner_radii = test_radii(20))), half)
    # Blend modes, separable and not.
    let operators = [gfx.CompositingAndBlendingOperator.multiply, gfx.CompositingAndBlendingOperator.screen, gfx.CompositingAndBlendingOperator.overlay,
                     gfx.CompositingAndBlendingOperator.difference, gfx.CompositingAndBlendingOperator.color_burn, gfx.CompositingAndBlendingOperator.soft_light,
                     gfx.CompositingAndBlendingOperator.hue, gfx.CompositingAndBlendingOperator.luminosity]
    for i in 0..<(usize)8:
        let node = test_effects(&scene, 0.8, operators[i], 1)
        test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(220 + (i32)i * 55, 30, 45, 120), color = test_rgba(250, (u8)(60 + i * 20), 30, 200))), node)
    # An isolated group masked by a rounded rectangle composited with destination-in, as CSS
    # masks are drawn.
    test_add(&scene, .save_layer(display_list.SaveLayer()), 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(40, 170, 260, 110), color = test_rgba(20, 160, 90, 255))), 1)
    let mask = test_effects(&scene, 1.0, gfx.CompositingAndBlendingOperator.destination_in, 1)
    test_add(&scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(60, 180, 200, 90), color = test_rgba(0, 0, 0, 255), corner_radii = test_radii(45))), mask)
    test_add(&scene, .restore(display_list.Restore()), 1)
    # A translucent group under a rounded clip: the clip applies when the layer is drawn back.
    test_add(&scene, .save(display_list.Save()), 1)
    test_add(&scene, .add_rounded_rect_clip(display_list.AddRoundedRectClip(corner_radii = test_radii(30), border_rect = test_box(360, 170, 300, 110), corner_clip = display_list.CornerClip.outside)), 1)
    let clipped = test_effects(&scene, 0.6, gfx.CompositingAndBlendingOperator.normal, 1)
    test_add(&scene, .fill_rect(display_list.FillRect(rect = test_box(340, 160, 340, 130), color = test_rgba(240, 200, 30, 255))), clipped)
    test_add(&scene, .restore(display_list.Restore()), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 11.0)]
    # Layers composite in floats where Skia's raster pipeline rounds in 8 bits; the corner
    # pixels of the rounded clip, the mask and the group's shape differ as analytic coverage
    # differs from scan conversion (about 420 of them).
    let stats = test_compare("layers", &scene, snapshots, 3, 500) else return
    if stats.cpu_tiles > 0:
        trap("a layer sent a tile to the CPU player")

## Appends a transform node (rotation by `degrees` about the z axis, then scale `scale`) about
## `origin` under node `parent`; answers its index.
func test_transform(scene: const TestList*, degrees: f32, scale: f32, origin_x: f32, origin_y: f32, parent: u64) -> u64:
    var matrix = gfx.rotation_matrix(gfx.FloatVector3([0.0, 0.0, 1.0]), degrees * 3.14159265 / 180.0)
    matrix = gfx.float_matrix4_x4_mul(&matrix, gfx.scale_matrix(gfx.FloatVector3([scale, scale, 1.0])))
    let data = display_list.TransformData(matrix = matrix, origin = gfx.FloatPoint(m_x = origin_x, m_y = origin_y))
    return display_list.accumulated_visual_context_tree_append(scene.tree, display_list.VisualContextData.transform_data(data), parent)

## Shapes under `node`: a rectangle, a rounded rectangle, a frame and a path, around (x, y).
func test_shapes(scene: const TestList*, x: i32, y: i32, node: u64):
    test_add(scene, .fill_rect(display_list.FillRect(rect = test_box(x, y, 90, 50), color = test_rgba(200, 40, 40, 255))), node)
    test_add(scene, .fill_rect_with_rounded_corners(display_list.FillRectWithRoundedCorners(rect = test_box(x + 20, y + 30, 80, 60), color = test_rgba(30, 90, 210, 220), corner_radii = test_radii(14))), node)
    test_add(scene, .draw_rect(display_list.DrawRect(rect = test_box(x - 10, y - 10, 120, 110), color = test_rgba(0, 0, 0, 255), rough = false)), node)
    var path: gfx.Path
    gfx.path_move_to(&path, gfx.FloatPoint(m_x = (f32)x + 5.0, m_y = (f32)y + 95.0))
    gfx.path_line_to(&path, gfx.FloatPoint(m_x = (f32)x + 60.5, m_y = (f32)y + 70.0))
    gfx.path_line_to(&path, gfx.FloatPoint(m_x = (f32)x + 100.0, m_y = (f32)y + 99.25))
    gfx.path_close(&path)
    test_add(scene, .fill_path(display_list.FillPath(path_bounding_rect = test_box(x + 5, y + 70, 96, 30), path = path, opacity = 1.0, paint_style_or_color = .color(test_rgba(20, 150, 60, 255)),
                                                     winding_rule = gfx.WindingRule.nonzero, should_anti_alias = display_list.ShouldAntiAlias.yes)), node)

test "gpu player: rotated, flipped and scaled content is drawn on the GPU":
    let scene = test_list()
    test_background(&scene)
    # Half turns and quarter turns about fractional origins (an icon flipped by CSS), with a
    # clip that lands between pixels; a turn by 30 degrees; a scale.
    let flipped = test_transform(&scene, 180.0, 1.0, 90.5, 80.25, 1)
    test_add(&scene, .save(display_list.Save()), flipped)
    test_add(&scene, .add_clip_rect(display_list.AddClipRect(rect = test_box(25, 25, 100, 70))), flipped)
    test_shapes(&scene, 30, 30, flipped)
    test_add(&scene, .restore(display_list.Restore()), flipped)
    let quarter = test_transform(&scene, 90.0, 1.0, 260.0, 150.5, 1)
    test_shapes(&scene, 210, 100, quarter)
    let tilted = test_transform(&scene, 30.0, 1.0, 430.0, 150.0, 1)
    test_shapes(&scene, 380, 100, tilted)
    let scaled = test_transform(&scene, 0.0, 1.5, 520.0, 60.0, 1)
    test_shapes(&scene, 520, 60, scaled)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 7.0)]
    # The shapes are the CPU rasterizer's coverage; the fractional clip is analytic, as is a
    # rectangle's anti-aliased clip, within a level or two.
    let stats = test_compare("transforms", &scene, snapshots, 3, 40) else return
    if stats.cpu_tiles > 0:
        trap("a transform sent a tile to the CPU player")

## Color stops at evenly spread positions, or at `positions` when they are as many.
func test_stops(colors: const gfx.Color[], positions: const f32[]) -> display_list.ColorStopData:
    var stops: ak.Vector[gfx.ColorStop]
    for i in 0..<colors.length:
        let position = positions[i] if positions.length == colors.length else (f32)i / (f32)(colors.length - 1)
        ak.vector_append_t(&stops, gfx.ColorStop(color = colors[i], position = position))
    return display_list.ColorStopData(list = stops)

test "gpu player: gradients run the raster pipeline's stages on the GPU":
    let scene = test_list()
    test_background(&scene)
    let warm = [test_rgba(255, 40, 0, 255), test_rgba(250, 220, 30, 255), test_rgba(20, 90, 230, 255)]
    let none_: f32[1] = [0.0]
    let srgb = display_list.ColorInterpolationMethod.rectangular_color_space(value = css_data.RectangularColorSpace.srgb)
    # Linear: an angle, a hard stop, a repeating one, translucent colors.
    test_add(&scene, .paint_linear_gradient(display_list.PaintLinearGradient(gradient_rect = test_box(10, 10, 160, 120),
                                                                             linear_gradient_data = display_list.LinearGradientData(gradient_angle = 30.0, color_stops = test_stops(warm, none_), interpolation_method = srgb))), 1)
    let hard: f32[4] = [0.0, 0.5, 0.5, 1.0]
    test_add(&scene, .paint_linear_gradient(display_list.PaintLinearGradient(gradient_rect = test_box(180, 10, 160, 120),
                                                                             linear_gradient_data = display_list.LinearGradientData(gradient_angle = 90.0, color_stops = test_stops([test_rgba(0, 120, 0, 255), test_rgba(0, 200, 90, 255), test_rgba(40, 0, 160, 128), test_rgba(220, 0, 160, 40)], hard), interpolation_method = srgb))), 1)
    var repeating = test_stops([test_rgba(30, 30, 30, 255), test_rgba(230, 230, 230, 255)], [0.0, 0.1])
    repeating.repeat_length = 0.1
    test_add(&scene, .paint_linear_gradient(display_list.PaintLinearGradient(gradient_rect = test_box(350, 10, 160, 120),
                                                                             linear_gradient_data = display_list.LinearGradientData(gradient_angle = 135.0, color_stops = repeating, interpolation_method = srgb))), 1)
    # Radial and conic. (A conic seam on an exact pixel diagonal, a start angle of 45 degrees,
    # can land on the other side: Metal compiles fragment programs with fast math, which
    # reassociates the matrix stage; see docs/GPU-LUCE-GPU-REQUESTS.md, item 8.)
    test_add(&scene, .paint_radial_gradient(display_list.PaintRadialGradient(rect = test_box(520, 10, 170, 120), center = gfx.IntPoint(m_x = 70, m_y = 50), size = gfx.IntSize(m_width = 90, m_height = 60),
                                                                             radial_gradient_data = display_list.RadialGradientData(color_stops = test_stops(warm, none_), interpolation_method = srgb))), 1)
    test_add(&scene, .paint_conic_gradient(display_list.PaintConicGradient(rect = test_box(10, 150, 140, 140), position = gfx.IntPoint(m_x = 70, m_y = 70),
                                                                           conic_gradient_data = display_list.ConicGradientData(start_angle = 40.0, color_stops = test_stops(warm, none_), interpolation_method = srgb))), 1)
    # Interpolation spaces and hue methods: each through its own stages.
    let spaces = [display_list.ColorInterpolationMethod.rectangular_color_space(value = css_data.RectangularColorSpace.srgb_linear),
                  display_list.ColorInterpolationMethod.rectangular_color_space(value = css_data.RectangularColorSpace.oklab),
                  display_list.ColorInterpolationMethod.rectangular_color_space(value = css_data.RectangularColorSpace.lab),
                  display_list.ColorInterpolationMethod.rectangular_color_space(value = css_data.RectangularColorSpace.display_p3),
                  display_list.ColorInterpolationMethod.polar_color_interpolation_method(value = display_list.PolarColorInterpolationMethod(color_space = css_data.PolarColorSpace.oklch, hue_interpolation_method = css_data.HueInterpolationMethod.longer)),
                  display_list.ColorInterpolationMethod.polar_color_interpolation_method(value = display_list.PolarColorInterpolationMethod(color_space = css_data.PolarColorSpace.hsl, hue_interpolation_method = css_data.HueInterpolationMethod.shorter)),
                  display_list.ColorInterpolationMethod.polar_color_interpolation_method(value = display_list.PolarColorInterpolationMethod(color_space = css_data.PolarColorSpace.hwb, hue_interpolation_method = css_data.HueInterpolationMethod.increasing)),
                  display_list.ColorInterpolationMethod.polar_color_interpolation_method(value = display_list.PolarColorInterpolationMethod(color_space = css_data.PolarColorSpace.lch, hue_interpolation_method = css_data.HueInterpolationMethod.decreasing))]
    for i in 0..<(usize)8:
        test_add(&scene, .paint_linear_gradient(display_list.PaintLinearGradient(gradient_rect = test_box(160 + (i32)i * 66, 150, 60, 140),
                                                                                 linear_gradient_data = display_list.LinearGradientData(gradient_angle = 180.0, color_stops = test_stops([test_rgba(255, 0, 80, 255), test_rgba(30, 200, 255, 160)], none_), interpolation_method = spaces[i]))), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 5.0)]
    # The same stages in floats: off by a level where a value lands on a rounding boundary.
    let stats = test_compare("gradients", &scene, snapshots, 2, 0) else return
    if stats.cpu_tiles > 0:
        trap("a gradient sent a tile to the CPU player")

test "gpu player: ellipses and repeated images are drawn on the GPU":
    let scene = test_list()
    test_background(&scene)
    test_add(&scene, .fill_ellipse(display_list.FillEllipse(rect = test_box(20, 20, 120, 70), color = test_rgba(200, 60, 20, 255))), 1)
    test_add(&scene, .fill_ellipse(display_list.FillEllipse(rect = test_box(160, 30, 9, 9), color = test_rgba(20, 20, 20, 255))), 1)
    test_add(&scene, .draw_ellipse(display_list.DrawEllipse(rect = test_box(190, 20, 140, 90), color = test_rgba(30, 90, 200, 255), thickness = 3)), 1)
    let tilted = test_transform(&scene, 25.0, 1.0, 400.0, 60.0, 1)
    test_add(&scene, .fill_ellipse(display_list.FillEllipse(rect = test_box(350, 30, 120, 60), color = test_rgba(40, 160, 90, 200))), tilted)
    # A small image repeated along x, along y, and both, at its size and scaled up bilinearly.
    let bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, gfx.IntSize(m_width = 6, m_height = 5)) else trap("bitmap")
    for j in 0..<(i32)5:
        let row = gfx.bitmap_scanline(bitmap, j) else trap("scanline")
        for i in 0..<(i32)6:
            row[(usize)i] = 0xff000000 | ((u32)(i * 40) << 16) | ((u32)(j * 50) << 8) | (u32)(255 - i * 30)
    var color_space: gfx.ColorSpace = ---
    gfx.color_space_construct(&color_space)
    let image = gfx.immutable_bitmap_create_color_space(bitmap, color_space)
    let repeats = [display_list.DrawRepeatedImmutableBitmapRepeat(x = true, y = false), display_list.DrawRepeatedImmutableBitmapRepeat(x = false, y = true),
                   display_list.DrawRepeatedImmutableBitmapRepeat(x = true, y = true)]
    for i in 0..<(usize)3:
        let x = 20 + (i32)i * 230
        test_add(&scene, .save(display_list.Save()), 1)
        test_add(&scene, .add_clip_rect(display_list.AddClipRect(rect = test_box(x, 130, 210, 160))), 1)
        test_add(&scene, .draw_repeated_immutable_bitmap(display_list.DrawRepeatedImmutableBitmap(dst_rect = test_box(x + 30, 150, 6, 5), clip_rect = test_box(x, 130, 210, 160), bitmap = image,
                                                                                                  scaling_mode = gfx.ScalingMode.nearest_neighbor, repeat = repeats[i])), 1)
        test_add(&scene, .draw_repeated_immutable_bitmap(display_list.DrawRepeatedImmutableBitmap(dst_rect = test_box(x + 100, 200, 27, 22), clip_rect = test_box(x, 130, 210, 160), bitmap = image,
                                                                                                  scaling_mode = gfx.ScalingMode.bilinear, repeat = repeats[i])), 1)
        test_add(&scene, .restore(display_list.Restore()), 1)
    let snapshots = [test_snapshot(0.0, 0.0), test_snapshot(0.0, 3.0)]
    # The raster port's anti-aliased fill of an oval is not quite translation-invariant: the
    # oval rastered at another whole-pixel offset (as the GPU player rasters it, for its tile)
    # differs on its last row by up to 30 levels, about 25 pixels here.
    let stats = test_compare("ellipses and patterns", &scene, snapshots, 3, 40) else return
    if stats.cpu_tiles > 0:
        trap("an ellipse or a repeated image sent a tile to the CPU player")