Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.0

0.45.0 / src / canvas / bands.lucb

#==============================================================================================
#
#   canvas/bands - The flattened document as 8-bit sRGB, a row of cells at a time
#
#   DESCRIPTION:
#       Streamed exports (JPEG, PNG) take the composited document a band of 256 pixel rows at
#       a time. The GPU turns each band into its export bytes: encode.frag draws every
#       composited tile into a strip texture (64 tiles wide) as 8-bit sRGB, over the matte or
#       with its alpha, through the same 4097-step table the CPU used, so opaque pixels come
#       out byte for byte as before. The strips are read back with one read batch, at the
#       band's row pitch, straight into place: half the bytes of the half floats, and no
#       per-pixel work on the CPU.
#
#       While the encoder works through one band the next is already composited and on its way
#       back: two read batches take turns. A band wider than a batch holds (over 32768 pixels)
#       is read in parts instead, one after another.
#
#==============================================================================================

## How wide a strip of tiles drawn at once may be: 64 tiles, within every GPU's
## texture limit.
let strip_width: u32 = 16384

## A row of cells of the flattened document as 8-bit sRGB RGBA, one at a time:
## over `matte` (linear light) when its red is not negative, else alpha kept.
struct Bands:
    ## The band's pixels, `extent_x` wide, 8-bit sRGB RGBA.
    var band: u8[]
    ## One rgba8_linear strip per 16384 columns, 256 rows.
    var strips: gpu.Texture[]
    ## Linear light to 8-bit sRGB, 4097 steps across 0..1, as an r8 texture.
    var table: gpu.Texture
    var shader: gpu.Shader
    var pipeline: gpu.Pipeline
    ## Two read batches taking turns: band `row` in `reads[row % 2]`.
    var reads: gpu.ReadBatch[2]
    ## Strips per read batch, and parts per band (1: the next band is prefetched).
    var strips_per_part: usize
    var parts: usize
    ## The band already on its way back, or -1.
    var prepared: i64
    var matte: f64[3]

    static func begin(canvas: Canvas*, matte: f64[3]) -> Bands!:
        try canvas.require_open()
        let device = canvas.device else error(invalid, "draw the document once before saving it")
        let band = try new u8[(usize)canvas.extent_x * (usize)tile_size * 4] --- in memory.heap
        errdefer free(band) in memory.heap
        var bands = Bands(band = band, strips = try new gpu.Texture[(usize)((canvas.extent_x + strip_width - 1) // strip_width)] --- in memory.heap,
                          table = gpu.Texture(), shader = gpu.Shader(), pipeline = gpu.Pipeline(), reads = [gpu.ReadBatch(), gpu.ReadBatch()],
                          strips_per_part = 1, parts = 1, prepared = -1, matte = matte)
        errdefer bands.close()
        for index in 0..<bands.strips.length:
            bands.strips[index] = gpu.Texture()
        for index in 0..<bands.strips.length:
            let left = (u32)index * strip_width
            bands.strips[index] = try gpu.Texture.create(device, min_u32(strip_width, canvas.extent_x - left), tile_size, gpu.Format.rgba8_linear)
        var steps: u8[4097] = ---
        transfer.srgb_byte_table(steps)
        bands.table = try gpu.Texture.create(device, 4097, 1, gpu.Format.r8)
        try bands.table.upload(steps)
        bands.shader = try gpu.Shader.create(device, encode_frag_words, encode_frag_msl)
        bands.pipeline = try gpu.Pipeline.create(device, bands.shader, gpu.Blend.replace, gpu.Format.rgba8_linear)
        bands.reads[0] = try gpu.ReadBatch.begin(device)
        bands.reads[1] = try gpu.ReadBatch.begin(device)
        let strip_bytes = (usize)strip_width * (usize)tile_size * 4
        bands.strips_per_part = max_usize(1, bands.reads[0].capacity() // strip_bytes)
        bands.parts = (bands.strips.length + bands.strips_per_part - 1) // bands.strips_per_part
        return bands

    ## Row `row` of cells into `band`; how many pixel rows it holds.
    func fill(canvas: Canvas*, row: u32) -> usize!:
        let rows = min_u32(tile_size, canvas.extent_y - row * tile_size)
        if self.parts > 1:
            for part in 0..<self.parts:
                try self.prepare(canvas, row, part, 0)
                try self.take(canvas, row, part, 0)
                try settle_job(canvas)
            return (usize)rows
        let turn = (usize)(row % 2)
        if self.prepared != (i64)row:
            try self.prepare(canvas, row, 0, turn)
        # The next band goes to the GPU before this one is waited for.
        if row + 1 < tile_columns(canvas.extent_y):
            try self.prepare(canvas, row + 1, 0, 1 - turn)
        try self.take(canvas, row, 0, turn)
        try settle_job(canvas)
        return (usize)rows

    ## Draw part `part` of band `row` as export bytes into its strips, and send
    ## their read back in batch `turn` (a batch per band at the band's width, or
    ## one per part at the part's).
    func prepare(canvas: Canvas*, row: u32, part: usize, turn: usize) -> !:
        let document = canvas.document else error(invalid, "draw the document once before saving it")
        let composer = canvas.composer else error(invalid, "draw the document once before saving it")
        let rows = min_u32(tile_size, canvas.extent_y - row * tile_size)
        let first = part * self.strips_per_part
        let last = min_usize(self.strips.length, first + self.strips_per_part)
        let part_left = (u32)first * strip_width
        let part_width = min_u32(canvas.extent_x - part_left, (u32)(last - first) * strip_width)
        # The layer tiles this part needs, brought back together (decoded across
        # the processors) rather than one by one as each cell is composited.
        try composer.gather(document, part_left // tile_size, row, (part_left + part_width + tile_size - 1) // tile_size, row + 1, 0)
        let batch = &self.reads[turn]
        let base = (try batch.reserve((usize)part_width * (usize)rows * 4)) else error(invalid, "a band's part must fit a read batch")
        let over: f32 = 1.0 if self.matte[0] >= 0.0 else 0.0
        for index in first..<last:
            let left = (u32)index * strip_width
            let width = min_u32(strip_width, canvas.extent_x - left)
            let frame = try self.strips[index].frame()
            defer frame.release()
            let target = try frame.value().target()
            defer target.release()
            var x: u32 = 0
            while x < width:
                let texture = try composer.tile(document, (left + x) // tile_size, row, 0)
                let columns = min_u32(tile_size, width - x)
                # Over the matte, the colors mix as the document blends them.
                var params: f32[8] = [(f32)x, 0.0, over, document.srgb_flag(), (f32)self.matte[0], (f32)self.matte[1], (f32)self.matte[2], 0.0]
                try gpu.shade(target.value(), self.pipeline, gpu.Rect((f64)x, 0.0, (f64)columns, (f64)rows), u8[]((u8*)&params[0], 32), [texture, self.table], gpu.Filter.nearest)
                x += columns
            _ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 0.0))
            try batch.copy(self.strips[index], gpu.Region(0, 0, width, rows), base + (usize)(left - part_left) * 4, row_texels = part_width)
        try batch.submit()
        self.prepared = (i64)row

    ## Wait for part `part` of band `row` in batch `turn` and copy its rows into
    ## place in `band`.
    func take(canvas: Canvas*, row: u32, part: usize, turn: usize) -> !:
        let rows = (usize)min_u32(tile_size, canvas.extent_y - row * tile_size)
        let width = (usize)canvas.extent_x
        let part_left = part * self.strips_per_part * (usize)strip_width
        let part_width = min_usize(width - part_left, self.strips_per_part * (usize)strip_width)
        let batch = &self.reads[turn]
        try batch.wait()
        let bytes = try batch.bytes(0, part_width * rows * 4)
        if part_width == width:
            memory.copy(self.band[..<bytes.length], bytes, bytes.length)
        else:
            for y in 0..<rows:
                let destination = (y * width + part_left) * 4
                memory.copy(self.band[destination..<destination + part_width * 4], bytes[y * part_width * 4..<(y + 1) * part_width * 4], part_width * 4)
        try batch.reset()

    func close():
        self.reads[0].finish()
        self.reads[1].finish()
        self.pipeline.destroy()
        self.shader.destroy()
        self.table.destroy()
        for index in 0..<self.strips.length:
            self.strips[index].destroy()
        if self.strips.length > 0:
            free(self.strips) in memory.heap
            var none_left: gpu.Texture[]
            self.strips = none_left
        if self.band.length > 0:
            free(self.band) in memory.heap
            var no_band: u8[]
            self.band = no_band

func max_usize(a: usize, b: usize) -> usize:
    return a if a > b else b