Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.2

0.6.2 / src / gpu_player / replay.lucb

#==============================================================================================
#
#   replay - a tile's recorded draws submitted as texture frames, and the CPU player's tiles
#
#   DESCRIPTION:
#       gpu_replay_tile records the GPU player's draws into the tile texture's frame and
#       presents it (cleared to transparent first, or over what the tile holds when the
#       recording drew part of it already): each draw under its scissor, the `rects` batches as
#       one triangle list each, the others with shaders/tile.frag (one program for every kind
#       of draw): runs of atlas masks and of rounded rectangles with circular corners that
#       share a scissor and clips as one instanced draw each, the other draws one instance
#       each. A tile that needs more than a frame's draws goes on in another frame that keeps
#       what the first drew. The atlas's pending uploads are sent first, so the frame samples
#       them, and the clip masks its draws use are rendered first, one r8 texture each
#       (tile.frag's clip kind).
#
#       gpu_cpu_tile draws a tile the GPU player gave up on with the CPU player
#       (DisplayListPlayerCpu through the same tile seam) into a scratch surface and uploads
#       it: BGRA premultiplied bytes swizzled to the tile's RGBA.
#
#       Copyright (c) 2026 the luce-browser authors.
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Pipelines ===============================================================================

## The shaders tiles are drawn with (shaders/tile.frag: every kind of draw) and composited with
## (shaders/composite.frag), and their pipelines: into rgba8_linear tiles, into r8 clip masks,
## and composites per target format.
pub struct GpuPipelines:
    var shader: gpu.Shader
    var composite_shader: gpu.Shader
    var tile: gpu.Pipeline
    var tile_replace: gpu.Pipeline
    var clip: gpu.Pipeline
    ## The composite pipeline per frame target format (index 8: a presentation surface).
    var composite: (gpu.Pipeline?)[9]

    ## The composite pipeline for targets of `target_format` (none: a surface).
    pub func composite_for(device: gpu.Device, target_format: gpu.Format?) -> gpu.Pipeline!:
        let index: usize = (usize)(target_format else gpu.Format.rgba8) if target_format != none else 8
        if let pipeline = self.composite[index]:
            return pipeline
        let pipeline = try gpu.Pipeline.create(device, self.composite_shader, gpu.Blend.over, target_format)
        self.composite[index] = pipeline
        return pipeline

    ## Releases every pipeline and the shader.
    pub func release():
        self.tile.destroy()
        self.tile_replace.destroy()
        self.clip.destroy()
        for index in 0..<(usize)9:
            if let pipeline = self.composite[index]:
                var handle = pipeline
                handle.destroy()
        self.shader.destroy()
        self.composite_shader.destroy()

## The pipelines on `device`.
pub func gpu_pipelines_create(device: gpu.Device) -> GpuPipelines!:
    let shader = try gpu.Shader.create(device, tile_frag_words, tile_frag_msl)
    let composite_shader = try gpu.Shader.create(device, composite_frag_words, composite_frag_msl)
    return GpuPipelines(shader = shader, composite_shader = composite_shader, tile = try gpu.Pipeline.create(device, shader, gpu.Blend.over, gpu.Format.rgba8_linear),
                        tile_replace = try gpu.Pipeline.create(device, shader, gpu.Blend.replace, gpu.Format.rgba8_linear),
                        clip = try gpu.Pipeline.create(device, shader, gpu.Blend.over, gpu.Format.r8))

## The uniforms of a composite (composite.frag): the texture with its top left at (`x`, `y`) of
## the target, decoded from sRGB when `decode`.
pub func gpu_composite_uniforms(x: f32, y: f32, decode: bool) -> f32[3]:
    return [x, y, 1.0 if decode else 0.0]

# mark: Replay state ============================================================================

## What replay keeps between tiles: the clip masks' textures (one per mask of a recording),
## the layers' (one per depth) and the backdrop a blend mode reads, reused tile after tile;
## and scratch lists.
pub struct GpuReplay:
    var masks: ak.Vector[gpu.Texture]
    var layers: ak.Vector[gpu.Texture]
    var backdrop: gpu.Texture?
    var table: gpu.Texture?
    var instances: ak.Vector[gpu.ShadeInstance]
    var vertices: ak.Vector[gpu.Vertex]

    ## Releases the textures and lists.
    pub func release():
        for texture in ak.vector_span(&self.masks):
            var handle = texture
            handle.destroy()
        ak.vector_clear(&self.masks)
        for texture in ak.vector_span(&self.layers):
            var handle = texture
            handle.destroy()
        ak.vector_clear(&self.layers)
        if let texture = self.backdrop:
            var handle = texture
            handle.destroy()
            self.backdrop = none
        if let texture = self.table:
            var handle = texture
            handle.destroy()
            self.table = none
        ak.vector_clear(&self.instances)
        ak.vector_clear(&self.vertices)

## The luce-gpu draws one tile frame takes before the tile goes on in another (luce-gpu's
## default limit is 4096).
let gpu_frame_draws: usize = 4000

## One texture frame of a tile and its root target.
struct GpuTileFrame:
    var frame: interop.Reference[gpu.Frame]?
    var root: interop.View[gpu.RenderTarget]?

    ## Begins a frame of `texture`, over its contents when `keep`.
    func open(texture: gpu.Texture, keep: bool) -> !:
        let frame = try texture.frame(keep)
        let root = frame.value().target() catch failure:
            frame.release()
            error(failure.code, failure.message)
        self.frame = frame
        self.root = root

    ## The frame's root target.
    func target() -> const gpu.RenderTarget*:
        return (self.root else trap("gpu_player: no tile frame")).value()

    ## Presents the frame (cleared to transparent unless it keeps) and lets it go.
    func present() -> !:
        let frame = self.frame else return
        if let root = self.root:
            root.release()
        self.root = none
        self.frame = none
        defer frame.release()
        _ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 0.0))

    ## Lets the frame go without presenting it.
    func release():
        if let root = self.root:
            root.release()
        if let frame = self.frame:
            frame.release()
        self.root = none
        self.frame = none

# mark: GPU tiles ===============================================================================

## A texture being drawn into while a tile replays: the tile's, or an open layer's, its frame,
## the draws in that frame, and whether the frame samples the layer texture one deeper (a
## frame's draws run when it is presented, so that texture cannot take another layer before).
struct GpuReplayTarget:
    var texture: gpu.Texture?
    var frame: GpuTileFrame
    var draws: usize
    var samples_layer: bool

    ## Begins drawing into `texture`, over its contents when `keep`.
    func open(texture: gpu.Texture, keep: bool) -> !:
        self.texture = texture
        self.draws = 0
        self.samples_layer = false
        try self.frame.open(texture, keep)

    ## Presents what is drawn and begins again over it.
    func split() -> !:
        let texture = self.texture else trap("gpu_player: no replay target")
        try self.frame.present()
        try self.frame.open(texture, true)
        self.draws = 0
        self.samples_layer = false

## Draws `player`'s recording into `texture` (`size` pixels square): cleared first, or over
## what it holds when `keep`. A layer's draws go into a texture of their own, composited into
## the target below when the layer ends.
pub func gpu_replay_tile(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, texture: gpu.Texture, size: i32, keep: bool) -> !:
    try player.atlas.submit_uploads()
    try gpu_upload_table(player)
    try gpu_render_masks(player, pipelines, size)
    var targets: GpuReplayTarget[9]
    var depth: usize = 0
    try targets[0].open(texture, keep)
    errdefer:
        for level in 0..<depth + 1:
            targets[level].frame.release()
    let bounds = GpuRect(width = size, height = size)
    let draws = ak.vector_span_const(&player.draws)
    var index: usize = 0
    while index < draws.length:
        let kind = draws[index].kind
        if kind == GpuDrawKind.layer_begin:
            if depth + 1 == 9:
                trap("gpu_player: layers deeper than the recording allows")
            let layer = try gpu_layer_texture(player, depth, size)
            if targets[depth].samples_layer:
                try targets[depth].split()
            depth += 1
            try targets[depth].open(layer, false)
            index += 1
            continue
        if kind == GpuDrawKind.layer_end:
            if depth == 0:
                trap("gpu_player: a layer ends that did not begin")
            try targets[depth].frame.present()
            let layer = targets[depth].texture else trap("gpu_player: no layer texture")
            depth -= 1
            try gpu_composite_layer(player, pipelines, &targets[depth], layer, ak.vector_at_const(&player.layers, draws[index].first), size)
            index += 1
            continue
        if targets[depth].draws == gpu_frame_draws:
            try targets[depth].split()
        let scissor = draws[index].scissor.intersected(bounds)
        if scissor.is_empty():
            index += 1
            continue
        let view = try targets[depth].frame.target().clipped(gpu.Rect((f64)scissor.x, (f64)scissor.y, (f64)scissor.width, (f64)scissor.height))
        let used = gpu_replay_run(player, pipelines, view.value(), draws, index, size) catch failure:
            view.release()
            error(failure.code, failure.message)
        view.release()
        index += used
        targets[depth].draws += 1
    # A recording given up mid-layer has no ends for its layers: their contents are dropped.
    while depth > 0:
        targets[depth].frame.release()
        depth -= 1
    try targets[0].frame.present()

## Uploads the recording's program table, whole rows of it, before the frames that read it.
func gpu_upload_table(player: DisplayListPlayerGpu*) -> !:
    let floats = ak.vector_size(&player.table)
    if floats == 0:
        return
    let device = player.device else trap("gpu_player: no device")
    if player.replay.table == none:
        player.replay.table = try gpu.Texture.create(device, (u32)gpu_table_width, (u32)gpu_table_height, gpu.Format.rgba32_float)
    let table = player.replay.table else trap("gpu_player: no table")
    let row = gpu_table_width * 4
    let rows = (floats + row - 1) // row
    while ak.vector_size(&player.table) < rows * row:
        ak.vector_append_t(&player.table, 0.0)
    let values = ak.vector_span_const(&player.table)
    try table.upload(u8[]((u8*)&values[0], rows * row * 4), gpu.Region(0, 0, (u32)gpu_table_width, (u32)rows))

## The texture of the layer opened at `depth` (layers at one depth never overlap in time).
func gpu_layer_texture(player: DisplayListPlayerGpu*, depth: usize, size: i32) -> gpu.Texture!:
    let device = player.device else trap("gpu_player: no device")
    while ak.vector_size(&player.replay.layers) <= depth:
        ak.vector_append_t(&player.replay.layers, try gpu.Texture.create(device, (u32)size, (u32)size, gpu.Format.rgba8_linear))
    return *ak.vector_at(&player.replay.layers, depth)

## Composites `layer` into `target` as `job` says, under the clips it was saved under: an
## `over` draw at the layer's opacity, or for another blend mode a draw that reads the target
## as it is (a copy, the backdrop) and writes the blend of the two, lerped by the clips'
## coverage as Skia's raster pipeline lerps it.
func gpu_composite_layer(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, target: GpuReplayTarget*, layer: gpu.Texture, job: const GpuLayerJob*, size: i32) -> !:
    let scissor = job.outer.clip.intersected(GpuRect(width = size, height = size))
    if scissor.is_empty():
        return
    var uniforms: f32[32]
    if let clip = job.outer.rounded:
        for i in 0..<(usize)4:
            uniforms[i] = clip.rect[i]
        for i in 0..<(usize)8:
            uniforms[4 + i] = clip.radii[i]
        uniforms[gpu_uniform_clip_mode] = clip.mode
    var clip_mask: gpu.Texture? = none
    if job.outer.mask != 0:
        uniforms[gpu_uniform_mask] = 1.0
        clip_mask = *ak.vector_at_const(&player.replay.masks, (usize)job.outer.mask - 1)
    let instance = gpu.ShadeInstance(rect = [(f32)scissor.x, (f32)scissor.y, (f32)scissor.width, (f32)scissor.height])
    if target.draws == gpu_frame_draws:
        try target.split()
    target.draws += 1
    target.samples_layer = true
    if job.blend == (u32)raster.BlendMode.source_over:
        uniforms[gpu_uniform_kind] = gpu_kind_composite
        uniforms[gpu_uniform_header + 3] = job.opacity
        let view = try target.frame.target().clipped(gpu.Rect((f64)scissor.x, (f64)scissor.y, (f64)scissor.width, (f64)scissor.height))
        defer view.release()
        try gpu_shade_run(pipelines, view.value(), [instance], &uniforms[0], layer, clip_mask, gpu.Filter.nearest)
        return
    # The target's pixels so far, copied where the blend reads them.
    let device = player.device else trap("gpu_player: no device")
    let texture = target.texture else trap("gpu_player: no replay target")
    if player.replay.backdrop == none:
        player.replay.backdrop = try gpu.Texture.create(device, (u32)size, (u32)size, gpu.Format.rgba8_linear)
    let backdrop = player.replay.backdrop else trap("gpu_player: no backdrop")
    try target.split()
    target.samples_layer = true
    try gpu.copy_texture(texture, gpu.Region((u32)scissor.x, (u32)scissor.y, (u32)scissor.width, (u32)scissor.height), backdrop, (u32)scissor.x, (u32)scissor.y)
    uniforms[gpu_uniform_kind] = gpu_kind_blend
    uniforms[gpu_uniform_header] = job.opacity
    uniforms[gpu_uniform_header + 1] = (f32)job.blend
    let view = try target.frame.target().clipped(gpu.Rect((f64)scissor.x, (f64)scissor.y, (f64)scissor.width, (f64)scissor.height))
    defer view.release()
    let bytes = u8[]((u8*)&uniforms[0], 128)
    try gpu.shade_instances(view.value(), pipelines.tile_replace, [instance], bytes, [layer, clip_mask else layer, backdrop], gpu.Filter.nearest)

## Renders the recording's clip masks, each into its texture (r8, the tile's size): cleared
## to 1, then each clip multiplied in.
func gpu_render_masks(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, size: i32) -> !:
    let jobs = ak.vector_span_const(&player.masks)
    let device = player.device else return
    while ak.vector_size(&player.replay.masks) < jobs.length:
        let texture = try gpu.Texture.create(device, (u32)size, (u32)size, gpu.Format.r8)
        ak.vector_append_t(&player.replay.masks, texture)
    let whole = gpu.Rect(0.0, 0.0, (f64)size, (f64)size)
    for index in 0..<jobs.length:
        let job = jobs[index]
        var tile = GpuTileFrame()
        try tile.open(*ak.vector_at(&player.replay.masks, index), false)
        errdefer tile.release()
        for which in 0..<job.count:
            let clip = job.clips[which]
            var uniforms: f32[16]
            for i in 0..<(usize)4:
                uniforms[i] = clip.rect[i]
            for i in 0..<(usize)8:
                uniforms[4 + i] = clip.radii[i]
            uniforms[gpu_uniform_clip_mode] = clip.mode
            uniforms[gpu_uniform_kind] = gpu_kind_clip
            try gpu.shade(tile.target(), pipelines.clip, whole, u8[]((u8*)&uniforms[0], 64), none, gpu.Filter.nearest)
        # r8 keeps the red of the clear: 1 everywhere before the clips.
        let frame = tile.frame else trap("gpu_player: no mask frame")
        if let root = tile.root:
            root.release()
        tile.root = none
        tile.frame = none
        defer frame.release()
        _ = try frame.value().present(gpu.Color(1.0, 0.0, 0.0, 1.0))

## The clip mask texture of `draw` (none without one).
func gpu_mask_texture(player: const DisplayListPlayerGpu*, draw: const GpuDraw*) -> gpu.Texture?:
    if draw.mask == 0:
        return none
    return *ak.vector_at_const(&player.replay.masks, (usize)draw.mask - 1)

## Draws `draws[start]` into `target`, with the draws after it that join it in one instanced
## draw; how many it drew.
func gpu_replay_run(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, target: const gpu.RenderTarget*, draws: const GpuDraw[], start: usize, size: i32) -> usize!:
    let draw = draws[start]
    let clip_mask = gpu_mask_texture(player, &draw)
    match draw.kind:
        .rects:
            let vertices = &player.replay.vertices
            ak.vector_clear(vertices)
            let scale = 2.0 / (f32)size
            for index in draw.first..<draw.first + draw.count:
                let record = ak.vector_at_const(&player.rects, index)
                gpu_append_quad(vertices, record, scale)
            try target.triangles(ak.vector_span_const(vertices))
            return 1
        .fill:
            if gpu_circular(&draw):
                return try gpu_replay_shapes(player, pipelines, target, draws, start, clip_mask)
            return try gpu_replay_instances(player, pipelines, target, draws, start, none, clip_mask, gpu.Filter.nearest)
        .mask:
            return try gpu_replay_instances(player, pipelines, target, draws, start, draw.image, clip_mask, gpu.Filter.nearest)
        .stages:
            return try gpu_replay_instances(player, pipelines, target, draws, start, player.replay.table, clip_mask, gpu.Filter.nearest, draw.image)
        .image:
            let image = draw.image else return 1
            return try gpu_replay_instances(player, pipelines, target, draws, start, image, clip_mask, gpu.Filter.nearest)
        _: return 1

## Whether a `fill` draw's corners are circular (each corner's radii equal), which an
## instanced shape carries.
func gpu_circular(draw: const GpuDraw*) -> bool:
    for corner in 0..<(usize)4:
        if draw.data[4 + corner * 2] != draw.data[5 + corner * 2]:
            return false
    return true

## Whether two draws can be one instanced draw: the same kind, scissor, clip mask, texture and
## uniforms.
func gpu_joins(a: const GpuDraw*, b: const GpuDraw*) -> bool:
    # Images draw one by one (each its own texture); every mask of a recording samples the
    # atlas's one texture (making room draws what came before).
    if a.kind != b.kind or a.kind == GpuDrawKind.image or a.scissor != b.scissor or a.mask != b.mask:
        return false
    for index in 0..<(usize)32:
        if a.uniforms[index] != b.uniforms[index]:
            return false
    return true

## Draws an instanced run: `draws[start]` and the draws after it that join it, each its
## rectangle and instance values, with `image` at binding 1; how many it drew.
func gpu_replay_instances(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, target: const gpu.RenderTarget*, draws: const GpuDraw[], start: usize,
                          image: gpu.Texture?, clip_mask: gpu.Texture?, filter: gpu.Filter, extra: gpu.Texture? = none) -> usize!:
    let instances = &player.replay.instances
    ak.vector_clear(instances)
    var end = start
    while end < draws.length and (end == start or gpu_joins(&draws[start], &draws[end])):
        if draws[end].kind == GpuDrawKind.fill and end > start and gpu_circular(&draws[end]):
            break
        let draw = draws[end]
        ak.vector_append_t(instances, gpu.ShadeInstance(rect = [(f32)draw.area.x, (f32)draw.area.y, (f32)draw.area.width, (f32)draw.area.height], data = draw.data))
        end += 1
    try gpu_shade_run(pipelines, target, ak.vector_span_const(instances), &draws[start].uniforms[0], image, clip_mask, filter, extra)
    return end - start

## One instanced draw of tile.frag with `uniforms` (32 floats), `image` at binding 1, the clip
## mask at binding 2 and `extra` at binding 3.
func gpu_shade_run(pipelines: const GpuPipelines*, target: const gpu.RenderTarget*, instances: const gpu.ShadeInstance[], uniforms: const f32*, image: gpu.Texture?,
                   clip_mask: gpu.Texture?, filter: gpu.Filter, extra: gpu.Texture? = none) -> !:
    let bytes = u8[]((u8*)uniforms, 128)
    if let third = extra:
        let first = image else third
        try gpu.shade_instances(target, pipelines.tile, instances, bytes, [first, clip_mask else first, third], filter)
    elif let mask = clip_mask:
        try gpu.shade_instances(target, pipelines.tile, instances, bytes, [image else mask, mask], filter)
    elif let first = image:
        try gpu.shade_instances(target, pipelines.tile, instances, bytes, [first], filter)
    else:
        try gpu.shade_instances(target, pipelines.tile, instances, bytes, none, filter)

## A run of `fill` draws with circular corners and the same clips as one instanced draw of
## tile.frag's shapes; how many it drew.
func gpu_replay_shapes(player: DisplayListPlayerGpu*, pipelines: const GpuPipelines*, target: const gpu.RenderTarget*, draws: const GpuDraw[], start: usize, clip_mask: gpu.Texture?) -> usize!:
    let instances = &player.replay.instances
    ak.vector_clear(instances)
    var end = start
    while end < draws.length and draws[end].kind == GpuDrawKind.fill and gpu_circular(&draws[end]) and gpu_same_clips(&draws[start], &draws[end]):
        let draw = draws[end]
        let v = draw.straight
        var instance = gpu.ShadeInstance(rect = [(f32)draw.area.x, (f32)draw.area.y, (f32)draw.area.width, (f32)draw.area.height])
        for i in 0..<(usize)4:
            instance.data[i] = draw.data[i]
            instance.data[4 + i] = draw.data[4 + i * 2]
        instance.data[8] = (f32)(((v >> 16) & 0xff) * 256 + ((v >> 8) & 0xff))
        instance.data[9] = (f32)((v & 0xff) * 256 + (v >> 24))
        instance.data[10] = draw.uniforms[gpu_uniform_header + 4]
        instance.data[11] = draw.uniforms[gpu_uniform_header + 5]
        ak.vector_append_t(instances, instance)
        end += 1
    var uniforms: f32[32]
    for index in 0..<gpu_uniform_header:
        uniforms[index] = draws[start].uniforms[index]
    uniforms[gpu_uniform_kind] = gpu_kind_shapes
    try gpu_shade_run(pipelines, target, ak.vector_span_const(instances), &uniforms[0], none, clip_mask, gpu.Filter.nearest)
    return end - start

## Whether two draws share a scissor, a clip mask and the header's clips.
func gpu_same_clips(a: const GpuDraw*, b: const GpuDraw*) -> bool:
    if a.scissor != b.scissor or a.mask != b.mask:
        return false
    for index in 0..<gpu_uniform_kind:
        if a.uniforms[index] != b.uniforms[index]:
            return false
    return true

## The two triangles of a solid rectangle in clip coordinates of a tile (`scale` is 2 / side).
func gpu_append_quad(vertices: ak.Vector[gpu.Vertex]*, record: const GpuRectRecord*, scale: f32):
    let left = (f32)record.rect.x * scale - 1.0
    let right = (f32)(record.rect.x + record.rect.width) * scale - 1.0
    let top = 1.0 - (f32)record.rect.y * scale
    let bottom = 1.0 - (f32)(record.rect.y + record.rect.height) * scale
    let rgba = record.color
    let a = gpu.Vertex(x = left, y = top, z = 0.0, red = rgba[0], green = rgba[1], blue = rgba[2], alpha = rgba[3])
    var b = a
    b.x = right
    var d = a
    d.x = right
    d.y = bottom
    var e = a
    e.y = bottom
    ak.vector_append_t(vertices, a)
    ak.vector_append_t(vertices, b)
    ak.vector_append_t(vertices, d)
    ak.vector_append_t(vertices, a)
    ak.vector_append_t(vertices, d)
    ak.vector_append_t(vertices, e)

# mark: CPU tiles ===============================================================================

## The CPU player and the tile surface it draws into, made by the first CPU tile of a frame
## and reused by the frame's other ones. It lives on the stack of gpu_compositor_draw, where
## an engine's collector sees it: the player and the surface are made with the caller's
## allocator, and nothing the compositor keeps across frames points there.
pub struct GpuCpuScratch:
    var player: display_list.DisplayListPlayerCpu*?
    var surface: gfx.PaintingSurface*?

## Draws commands `layer.first..<layer.end` with the CPU player into the scratch tile surface
## (cleared first) from `origin` of the layer's plane, then uploads it into `texture` through
## `pixels` (a tile's bytes).
pub func gpu_cpu_tile(scratch: GpuCpuScratch*, list: display_list.DisplayList*, snapshot: const display_list.ScrollStateSnapshot*, layer: const GpuLayer*,
                      origin: gfx.IntPoint, texture: gpu.Texture, pixels: u8[]) -> !:
    if scratch.player == none:
        scratch.player = display_list.display_list_player_cpu_create()
    let player = scratch.player else trap("gpu_player: no CPU player")
    var surface = scratch.surface else gfx.painting_surface_create_with_size(gfx.IntSize(m_width = gpu_tile_size, m_height = gpu_tile_size), gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied)
    let bitmap = gfx.painting_surface_bitmap(surface)
    if scratch.surface != none:
        for y in 0..<gfx.bitmap_height(bitmap):
            let row = gfx.bitmap_scanline(bitmap, y) else continue
            for x in 0..<gfx.bitmap_width(bitmap):
                row[(usize)x] = 0
    scratch.surface = surface
    display_list.display_list_player_execute_tile((display_list.DisplayListPlayer*)player, list, snapshot, surface, layer.first, layer.end, origin)
    let width = gfx.bitmap_width(bitmap)
    let height = gfx.bitmap_height(bitmap)
    for y in 0..<height:
        let row = gfx.bitmap_scanline_const(bitmap, y) else continue
        let base = (usize)y * (usize)width * 4
        for x in 0..<width:
            let value = row[(usize)x]
            let at = base + (usize)x * 4
            pixels[at] = (u8)((value >> 16) & 0xff)
            pixels[at + 1] = (u8)((value >> 8) & 0xff)
            pixels[at + 2] = (u8)(value & 0xff)
            pixels[at + 3] = (u8)(value >> 24)
    try texture.upload(pixels)