Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-vector

Source of release 0.6.0

0.6.0 / src / vector / windows.lucb

#==============================================================================================
#
#   vector/windows - Vector elements drawn only where their edges are
#
#   DESCRIPTION:
#       A vector element costs its edges, not its area. Its SVG is parsed once over the
#       whole canvas, and its outlines (already flattened to segments by luce-svg) sort the
#       256-pixel cells it can reach into three kinds (cells.lucb):
#         - edge cells, within a band of any segment (the stroke's reach and a pixel or two
#           of anti-aliasing), which luce-svg draws, a window of a few cells at a time;
#         - inside cells, wholly within the fill, which are one color throughout: one of
#           them is drawn and every other shares its tile;
#         - outside cells, which stay empty.
#       The processors draw a wave of windows from the one parsed drawing (every element of
#       the layer the cells need, render.lucb) and turn their cells into half floats;
#       the main thread uploads them (the GPU is its), sharing one tile among cells that came
#       out one color throughout.
#
#==============================================================================================

## Cells a window spans across at most: its buffer is this many cells' pixels.
let window_cells: u32 = 4

## One window of a wave: its first cell and how many cells across, its size in pixels,
## and what its worker made of it — each cell as half floats, whether the cell holds
## anything, and whether it is one pixel throughout.
struct ShapeWindow:
    var column: u32
    var row: u32
    var across: u32
    var width: u32
    var height: u32
    var drawing: const svg.Drawing*?
    var canvas_width: u32
    var canvas_height: u32
    var pixels: f32[]
    var cells: u8[]
    var painted: bool[4]
    var uniform: bool[4]
    var failed: bool

## A run of cells to draw, `across` cells from (`column`, `row`).
struct CellRun:
    var column: u32
    var row: u32
    var across: u32

## A tile already made for a cell of one pixel throughout, by that pixel's half floats.
struct SharedTile:
    var pixel: u64
    var column: u32
    var row: u32

## Draws windows of cells from one parsed drawing on the processors and uploads them.
struct WindowPainter:
    var device: gpu.Device
    var windows: ShapeWindow[]
    var workers: usize
    var shared: SharedTile[16]
    var shared_count: usize

    static func make(device: gpu.Device, drawing: const svg.Drawing*?, width: u32, height: u32) -> WindowPainter!:
        let workers = (usize)math.imin(16, math.imax(1, (i64)os.cpus()))
        let per_tile = (usize)tile_size * (usize)tile_size * 8
        let span = (usize)window_cells * (usize)tile_size
        let windows = try new ShapeWindow[workers] --- in memory.heap
        var made: usize = 0
        errdefer:
            release_windows(windows[..<made])
            free(windows) in memory.heap
        for index in 0..<workers:
            let pixels = try new f32[span * (usize)tile_size * 4] --- in memory.heap
            errdefer free(pixels) in memory.heap
            let cells = try new u8[(usize)window_cells * per_tile] --- in memory.heap
            windows[index] = ShapeWindow(column = 0, row = 0, across = 0, width = 0, height = 0, drawing = drawing, canvas_width = width, canvas_height = height,
                                         pixels = pixels, cells = cells, painted = [false, false, false, false], uniform = [false, false, false, false], failed = false)
            made += 1
        var shared: SharedTile[16] = ---
        return WindowPainter(device = device, windows = windows, workers = workers, shared = shared, shared_count = 0)

    ## Draw every run of cells of kind `kind` in `plan`, row by row, a window at most
    ## `window_cells` across, a wave of windows at a time.
    func draw_runs(plan: const CellPlan*, kind: u8, tiles: Tiles*) -> !:
        var runs: CellRun[16] = ---
        var count: usize = 0
        for row in plan.reach.top..<plan.reach.bottom:
            var column = plan.reach.left
            while column < plan.reach.right:
                if plan.kind(column, row) != kind:
                    column += 1
                    continue
                var across: u32 = 1
                while across < window_cells and column + across < plan.reach.right and plan.kind(column + across, row) == kind:
                    across += 1
                runs[count] = CellRun(column = column, row = row, across = across)
                count += 1
                column += across
                if count == self.workers:
                    try self.draw(runs[..<count], tiles)
                    count = 0
        if count > 0:
            try self.draw(runs[..<count], tiles)

    ## Draw `runs` (at most one per worker) on the processors and upload their cells.
    func draw(runs: const CellRun[], tiles: Tiles*) -> !:
        for index in 0..<runs.length:
            let window = &self.windows[index]
            let left = runs[index].column * tile_size
            let top = runs[index].row * tile_size
            window.column = runs[index].column
            window.row = runs[index].row
            window.across = runs[index].across
            window.width = min_u32(runs[index].across * tile_size, window.canvas_width - left)
            window.height = min_u32(tile_size, window.canvas_height - top)
            window.failed = false
        try draw_windows(self.windows[..<runs.length])
        for index in 0..<runs.length:
            if self.windows[index].failed:
                error(invalid, "a shape window could not be drawn")
            try upload_window(self.device, tiles, &self.windows[index], self.shared[..<16], &self.shared_count)

    func close():
        release_windows(self.windows)
        free(self.windows) in memory.heap

## The worker pool draws `windows`, this thread among them.
func draw_windows(windows: ShapeWindow[]) -> !:
    if windows.length > 0:
        pool.run(windows.length, window_entry, (void*)&windows[0])

func window_entry(context: void*?, index: usize):
    let windows = (ShapeWindow*)(context else return)
    draw_window(&windows[index])

## Draw `window` from the whole drawing and turn each of its cells into half floats,
## as `Tiles.write` does: straight alpha, clear past the document's edge.
func draw_window(window: ShapeWindow*):
    let width = (usize)window.width
    let height = (usize)window.height
    let pixels = window.pixels[..<width * height * 4]
    let drawing = window.drawing else return
    svg.rasterize_rgba_window(drawing, window.canvas_width, window.canvas_height, window.column * tile_size, window.row * tile_size,
                              window.width, window.height, pixels, svg.Color(r = 0.0, g = 0.0, b = 0.0)) catch _:
        window.failed = true
        return
    let per_tile = (usize)tile_size * (usize)tile_size * 8
    let side = (usize)tile_size
    let count = (width + side - 1) // side
    # Inside a shape one value repeats pixel after pixel: each channel keeps its last
    # conversion, and a value like it skips `to_half`.
    var last_value: f32[4] = [0.0, 0.0, 0.0, 0.0]
    var last_half: u16[4] = [0, 0, 0, 0]
    for cell in 0..<count:
        let bytes = window.cells[cell * per_tile..<(cell + 1) * per_tile]
        let across = min_usize(side, width - cell * side)
        var painted = false
        for y in 0..<side:
            for x in 0..<side:
                let destination = (y * side + x) * 8
                if y >= height or x >= across:
                    for index in 0..<(usize)8:
                        bytes[destination + index] = 0
                    continue
                let source = (y * width + cell * side + x) * 4
                for channel in 0..<(usize)4:
                    let value = pixels[source + channel]
                    if value != last_value[channel]:
                        last_value[channel] = value
                        last_half[channel] = to_half(value)
                    let half = last_half[channel]
                    bytes[destination + channel * 2] = (u8)(half & 0xff)
                    bytes[destination + channel * 2 + 1] = (u8)(half >> 8)
                if pixels[source + 3] != 0.0:
                    painted = true
        window.painted[cell] = painted
        window.uniform[cell] = painted and one_pixel(bytes)
    for cell in count..<(usize)window_cells:
        window.painted[cell] = false
        window.uniform[cell] = false

## Whether a cell's half floats are one pixel throughout.
func one_pixel(bytes: const u8[]) -> bool:
    for index in 8..<bytes.length:
        if bytes[index] != bytes[index % 8]:
            return false
    return true

## The first pixel of a cell's half floats as one number.
func pixel_key(bytes: const u8[]) -> u64:
    var key: u64 = 0
    for index in 0..<(usize)8:
        key = key | ((u64)bytes[index] << ((u64)index * 8))
    return key

## Put `window`'s painted cells into `tiles`: a cell one pixel throughout shares
## the tile already made for that pixel, when there is one.
func upload_window(device: gpu.Device, tiles: Tiles*, window: const ShapeWindow*, shared: SharedTile[], shared_count: usize*) -> !:
    let per_tile = (usize)tile_size * (usize)tile_size * 8
    for cell in 0..<(usize)window.across:
        if not window.painted[cell]:
            continue
        let column = window.column + (u32)cell
        let bytes = window.cells[cell * per_tile..<(cell + 1) * per_tile]
        if window.uniform[cell]:
            let key = pixel_key(bytes)
            var found = false
            for index in 0..<*shared_count:
                if shared[index].pixel == key:
                    try tiles.share(column, window.row, shared[index].column, shared[index].row)
                    found = true
                    break
            if found:
                continue
            if *shared_count < shared.length:
                shared[*shared_count] = SharedTile(pixel = key, column = column, row = window.row)
                *shared_count += 1
        var texture = try gpu.Texture.create(device, tile_size, tile_size, gpu.Format.rgba16_float)
        errdefer texture.destroy()
        try texture.upload(bytes)
        try tiles.set(column, window.row, texture)

func release_windows(windows: ShapeWindow[]):
    for index in 0..<windows.length:
        free(windows[index].pixels) in memory.heap
        free(windows[index].cells) in memory.heap

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