Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-gpu

Source of release 0.5.7

0.5.7 / src / gpu / texture.lucb

#==============================================================================================
#
#   texture - An owned two-dimensional texture
#
#   DESCRIPTION:
#       A texture on one device: uploaded from and read back into tightly packed CPU pixels,
#       sampled by image draws, and rendered into by its own frames. The zero value is closed;
#       copies alias ownership, so borrow and destroy one owner. Draws recorded against a
#       texture and its open frames keep its storage alive after the handle is destroyed.
#
#==============================================================================================

# mark: Textures ==============================================================================
## An owned texture; the zero value is closed and copies alias ownership.
pub struct Texture:
    var state: TextureState*?

    ## Allocate an uninitialised `width` by `height` texture of `format`, each
    ## dimension in 1..16384. A `storage` texture can also be bound to compute
    ## kernels as a storage image, loaded and stored (`unsupported` where the
    ## device cannot store the format). A `mipmaps` texture has the full chain
    ## of smaller levels, down to one texel, which `generate_mipmaps` fills from
    ## the first and `Filter.trilinear` samples; only the formats frames render
    ## into have them, and not as storage images (`invalid_geometry`).
    pub static func create(device: Device, width: u32, height: u32, pixel_format: Format, storage: bool = false, mipmaps: bool = false) -> Texture!:
        let device_state = try device.checked()
        if width == 0 or height == 0 or width > 16384 or height > 16384:
            error(invalid_geometry, "texture dimensions must be in 1..16384")
        if mipmaps and (storage or not renderable(pixel_format)):
            error(invalid_geometry, "mipmapped textures are of the 8- and 16-bit formats and are not storage images")
        let levels = mip_levels(width, height) if mipmaps else 1
        let native = try backend_texture_create(device_state, width, height, pixel_format, storage, levels)
        errdefer backend_texture_destroy(device_state, native)
        let state = try new TextureState(device = device_state, native = native, width = width, height = height, format = pixel_format, storage = storage, levels = levels) in memory.heap
        device_state.references += 1
        return Texture(state = state)

    ## The width in texels.
    pub func width() -> u32!:
        return (try self.checked()).width

    ## The height in texels.
    pub func height() -> u32!:
        return (try self.checked()).height

    ## The texel format.
    pub func pixel_format() -> Format!:
        return (try self.checked()).format

    ## Replace `region` (the whole texture by default) with tightly packed,
    ## top-down `pixels` in the texture's format. The copy is ordered after earlier
    ## submissions and before later ones (it need not have finished when this
    ## returns); `pixels` may be reused at once.
    pub func upload(pixels: const u8[], region: Region? = none) -> !:
        let state = try self.checked()
        let area = try state.check_region(region, pixels.length)
        try backend_texture_upload(state.device, state.native, pixels, area)

    ## Read `region` (the whole texture by default) back into `pixels`, tightly
    ## packed and top-down in the texture's format, after every earlier submission
    ## that touched it has completed.
    pub func read(pixels: u8[], region: Region? = none) -> !:
        let state = try self.checked()
        let area = try state.check_region(region, pixels.length)
        try read_texture(state, pixels, area)

    ## How many mip levels it has: 1, or the full chain of a `mipmaps` texture.
    pub func levels() -> u32!:
        return (try self.checked()).levels

    ## Fill every level after the first from the one before it, each texel the
    ## average of four (a box filter), on the queue like `upload`: ordered after
    ## earlier submissions (an upload, a frame or a copy into the first level)
    ## and before later ones, without waiting. Uploads, frames and copies write
    ## the first level only, so call this after changing it. Nothing to do for a
    ## texture without mipmaps.
    pub func generate_mipmaps() -> !:
        let state = try self.checked()
        if state.levels > 1:
            try backend_texture_mipmaps(state.device, state.native)

    ## Whether compute kernels can bind the texture as a storage image.
    pub func storage() -> bool!:
        return (try self.checked()).storage

    ## Begin one recording frame whose target is this texture; a point is `scale`
    ## texels (in 1..16, a window's backing scale for a layer drawn as the window
    ## draws), one by default. The 32-bit formats are not rendered into
    ## (`invalid_geometry`).
    ## `present` clears the texture to the given color and draws, ordered
    ## before every later submission, so the result can be read or sampled
    ## immediately after without waiting for the GPU: only `read` waits. With
    ## `keep`, `present` draws over the texture's contents instead of clearing
    ## them (its color is then unused): a frame adds to what earlier frames,
    ## uploads and copies left.
    pub func frame(keep: bool = false, scale: f64 = 1.0) -> interop.Reference[Frame]!:
        let state = try self.checked()
        if not renderable(state.format):
            error(invalid_geometry, "32-bit textures are written by compute kernels, not rendered into")
        if state.active_frame:
            error(frame_in_use, "the texture already has an active frame")
        if not (scale >= 1.0 and scale <= 16.0):
            error(invalid_geometry, "a texture frame's scale must be in 1..16")
        let columns = (f64)state.width
        let rows = (f64)state.height
        let size = window.Size(width = columns / scale, height = rows / scale, pixel_width = columns, pixel_height = rows, scale = scale)
        let native = try new Frame(size)
        let owner = try interop.Reference[Frame].adopt(native, frame_type)
        errdefer owner.release()
        let recording = (try native.state_value()).value()
        recording.presentation = (void*)state
        recording.device = state.device
        recording.format = state.format
        recording.validate = check_texture_frame
        recording.submit = submit_texture_frame
        recording.release = release_texture_frame
        recording.keep = keep_texture_canvas
        recording.canvas = state.device.spare
        state.device.spare = Canvas()
        state.references += 1
        state.active_frame = true
        state.keep = keep
        return owner

    ## Release this handle on the main thread; recorded draws and open frames keep
    ## the storage until they finish.
    pub func destroy():
        let state = self.state else return
        require_thread()
        self.state = none
        state.closed = true
        release_texture(state)

    func checked() -> TextureState*!:
        try check_thread()
        let state = self.state else error(closed, "the GPU texture is closed")
        if state.closed:
            error(closed, "the GPU texture is closed")
        return state

struct TextureState:
    var device: DeviceState*
    var native: void*
    var width: u32
    var height: u32
    var format: Format
    var storage: bool
    var levels: u32 = 1
    var references: usize = 1
    var closed: bool
    var active_frame: bool
    # Whether the active frame draws over the contents rather than clearing.
    var keep: bool

    func check_region(region: Region?, bytes: usize) -> Region!:
        let area = region else Region(0, 0, self.width, self.height)
        if area.width == 0 or area.height == 0 or area.x > self.width - area.width or area.y > self.height - area.height:
            error(invalid_geometry, "a texture region must lie inside the texture and be non-empty")
        if bytes != (usize)area.width * (usize)area.height * texel_bytes(self.format):
            error(invalid_pixels, "pixel data must be tightly packed for the region and the texture's format")
        return area

# mark: Copies between textures ==============================================================
## Copy `region` of `source` into `target` with its top left at (`x`, `y`): a
## blit on the device's queue, like `upload`, outside any frame, of texels
## exactly as stored. Ordered after every earlier submission and before every
## later one, without waiting. Both textures belong to one device
## (`wrong_device`), share a format (`invalid_pixels`), and are two textures
## (`invalid_geometry`); both rectangles lie inside their textures. Only the
## first mip level is written: call `generate_mipmaps` after.
##
## This is not `copy_image`, which draws a texture into a frame's target,
## scaled and filtered, as one of the frame's draws.
pub func copy_texture(source: Texture, region: Region, target: Texture, x: u32, y: u32) -> !:
    let copied = try source.checked()
    let written = try target.checked()
    if copied.device != written.device:
        error(wrong_device, "copied textures must belong to one GPU device")
    if copied.format != written.format:
        error(invalid_pixels, "copied textures must share a format")
    if copied == written:
        error(invalid_geometry, "copy_texture copies between two textures")
    if region.width == 0 or region.height == 0 or region.width > copied.width or region.height > copied.height or region.x > copied.width - region.width or region.y > copied.height - region.height:
        error(invalid_geometry, "a copied region must lie inside its source texture and be non-empty")
    if region.width > written.width or region.height > written.height or x > written.width - region.width or y > written.height - region.height:
        error(invalid_geometry, "a copied region must land inside its target texture")
    try backend_texture_copy(copied.device, copied.native, region, written.native, x, y)

## The levels of a full mip chain for a `width` by `height` texture.
func mip_levels(width: u32, height: u32) -> u32:
    var side = width if width > height else height
    var levels: u32 = 1
    while side > 1:
        side = side >> 1
        levels += 1
    return levels

func release_texture(state: TextureState*):
    state.references -= 1
    if state.references == 0:
        backend_texture_destroy(state.device, state.native)
        release_device(state.device)
        free(state) in memory.heap

# mark: Frames on a texture ===================================================================
## Every image draw in `canvas` must sample a texture of `device`.
func check_canvas_device(canvas: Canvas, device: DeviceState*) -> !:
    for draw in canvas.draws[..<canvas.draw_count]:
        for image in draw.images:
            if let texture = image:
                if texture.device != device:
                    error(wrong_device, "a draw samples a texture from another GPU device")
        if let pipeline = draw.pipeline:
            if pipeline.device != device:
                error(wrong_device, "a draw uses a pipeline from another GPU device")

func check_texture_frame(context: void*, acquired: window.Size, extent: bool) -> !:
    _ = acquired
    _ = extent
    let state = (TextureState*)context
    try check_thread()
    if state.closed:
        error(closed, "the frame's texture is closed")

func submit_texture_frame(context: void*, canvas: Canvas, color: Color) -> PresentResult!:
    let state = (TextureState*)context
    try check_canvas_device(canvas, state.device)
    try check_canvas_target(canvas, state.format)
    for draw in canvas.draws[..<canvas.draw_count]:
        for image in draw.images:
            if let texture = image:
                if texture == state:
                    error(invalid_geometry, "a texture frame cannot sample the texture it renders into")
    try backend_texture_render(state.device, state.native, canvas, color, state.keep)
    return PresentResult.submitted

## Keep a finished texture frame's canvas for the device's next one.
func keep_texture_canvas(context: void*, canvas: Canvas):
    let state = (TextureState*)context
    var kept = canvas
    kept.recycle()
    let previous = state.device.spare
    state.device.spare = kept
    var dropped = previous
    dropped.destroy()

func release_texture_frame(context: void*):
    require_thread()
    let state = (TextureState*)context
    state.active_frame = false
    release_texture(state)