dymokomi/luce-gpu
Source of release 0.5.1
#==============================================================================================
#
# mesh - Device buffers and indexed mesh drawing
#
# DESCRIPTION:
# A Buffer is device storage a program fills and later rewrites in part: a mesh's
# positions, topology, normals or colors. A mesh draw pulls its vertices from up to
# seven buffers (shaders/mesh.glsl), so a changed position array redraws after one
# upload with no per-vertex CPU work. The same buffers draw surfaces, constant-width
# wires and face ids for picking; the shading (Lambert, flat, zebra, isophotes, normals)
# is a parameter, so switching it re-uploads nothing.
#
#==============================================================================================
# mark: Buffers ================================================================================
## The most bytes one buffer holds: Vulkan's guaranteed storage-buffer range.
pub let buffer_limit: usize = 134217728
## Device storage. Copies alias ownership; one owner destroys it on the main
## thread. Recorded draws keep it alive until their frame finishes.
pub struct Buffer:
var state: BufferState*?
## A buffer holding `data` (at least 4 bytes, at most `buffer_limit`).
pub static func create(device: Device, data: const u8[]) -> Buffer!:
let owner = try device.checked()
if data.length < 4 or data.length > buffer_limit or data.length % 4 != 0:
error(invalid_geometry, "a GPU buffer holds 4 to 134217728 bytes, a multiple of four")
let native = try backend_buffer_create(owner, data)
errdefer owner.destroy_buffer(owner.native, native)
let state = try new BufferState(owner, native, 1, data.length) in memory.heap
owner.references += 1
return Buffer(state)
## Replace `data.length` bytes at `offset`. Draws recorded before this call
## see the old contents and later ones the new: the copy is ordered on the
## device's queue, so nothing waits for work in flight.
pub func upload(offset: usize, data: const u8[]) -> !:
try check_thread()
let state = self.state else error(closed, "the GPU buffer is closed")
if offset % 4 != 0 or data.length % 4 != 0 or offset > state.bytes or data.length > state.bytes - offset:
error(invalid_geometry, "a buffer upload must be four-byte aligned and inside the buffer")
if data.length == 0: return
try backend_buffer_upload(state.device, state.native, offset, data)
pub func bytes() -> usize:
let state = self.state else return 0
return state.bytes
pub func is_open() -> bool:
return self.state != none
pub func destroy():
if let state = self.state:
require_thread()
self.state = none
release_buffer(state)
struct BufferState:
let device: DeviceState*
let native: void*
var references: usize
let bytes: usize
func release_buffer(state: BufferState*):
state.references -= 1
if state.references == 0:
state.device.destroy_buffer(state.device.native, state.native)
release_device(state.device)
free(state) in memory.heap
# mark: Mesh draws =============================================================================
## What a mesh draw produces: shaded surfaces, wires between point pairs, or
## face ids (into an rgba8_linear target) for picking.
pub enum MeshKind as u8:
surface = 0
wires = 1
ids = 2
## The buffers a mesh draw reads (shaders/mesh.glsl); unused ones stay closed.
## Surfaces and ids: `triangles` holds three corner ids per triangle, `faces`
## one face id per triangle. Wires: `triangles` holds two point ids per edge.
pub struct MeshBuffers:
pub var triangles: Buffer
pub var corners: Buffer
pub var positions: Buffer
pub var normals: Buffer
pub var colors: Buffer
pub var faces: Buffer
pub var flags: Buffer
## Parameter block size in f32 values; the layout is mesh.glsl's `Parameters`.
## The block only grows at its end: a new parameter is appended, and its
## default, zero, leaves its feature off. draw_mesh takes any block from
## `mesh_base_parameter_count` values up to this size and fills the values
## a shorter block leaves out with zeros, so a caller written against an
## older layout draws as it did.
pub let mesh_parameter_count: usize = 124
## The block's first layout, through `mesh_accent`.
pub let mesh_base_parameter_count: usize = 120
## Parameter offsets, in f32 values, into the block `draw_mesh` takes.
pub let mesh_clip: usize = 0
pub let mesh_world: usize = 16
pub let mesh_normal_matrix: usize = 32
pub let mesh_tint: usize = 48
pub let mesh_ambient: usize = 52
pub let mesh_light_direction: usize = 56
pub let mesh_light_color: usize = 72
pub let mesh_eye: usize = 88
pub let mesh_mode: usize = 92
pub let mesh_zebra: usize = 96
pub let mesh_zebra_axis: usize = 100
pub let mesh_zebra_dark: usize = 104
pub let mesh_zebra_light: usize = 108
pub let mesh_line: usize = 112
pub let mesh_accent: usize = 116
## Curvature shading: x the value (0 mean, 1 Gaussian, 2 k1, 3 k2, 4 the
## larger |k|), y the value the color map spans (only read by the curvature
## shading).
pub let mesh_curvature: usize = 120
## Shading modes (the block's mode.x).
pub enum Shading as u8:
lit = 0
flat = 1
zebra = 2
isophote = 3
normals = 4
unlit = 5
## A diverging colour map of principal curvatures (k1, k2) the colors
## buffer carries: blue below zero, green at zero, red above.
curvature = 6
## A recorded mesh draw: retained buffers and its parameter block.
struct MeshDraw:
var buffers: BufferState*?[7]
var parameters: f32[124]
var kind: MeshKind
func release_mesh_draw(draw: MeshDraw*):
for buffer in draw.buffers:
if let state = buffer: release_buffer(state)
free(draw) in memory.heap
## Record `vertices` mesh vertices (3 per triangle, 6 per wire edge) into
## `target`, depth tested. `parameters` is the block, `mesh_base_parameter_count`
## to `mesh_parameter_count` values (see mesh_parameter_count); draw_mesh
## fills its viewport size and clip-space y sign. slope_bias
## pushes surfaces back for a coplanar wire overlay, in logical pixels.
pub func draw_mesh(target: const RenderTarget*, buffers: const MeshBuffers*, vertices: usize, parameters: const f32[], kind: MeshKind, slope_bias: f64 = 0.0) -> !:
try target.frame.check()
if parameters.length < mesh_base_parameter_count or parameters.length > mesh_parameter_count or vertices == 0 or vertices % (6 if kind == MeshKind.wires else 3) != 0:
error(invalid_geometry, "a mesh draw needs its parameter block and whole triangles or edges")
if not (slope_bias >= 0.0 and slope_bias <= 32.0) or (kind == MeshKind.wires and slope_bias != 0.0):
error(invalid_geometry, "slope bias requires surfaces and a finite factor in 0..32")
# mode.w holds the id base as bits, not a number.
for index in 0..<parameters.length:
if index != mesh_mode + 3 and not math32.is_finite(parameters[index]): error(invalid_geometry, "nonfinite mesh parameters")
let device = target.frame.device else error(unavailable, "a standalone frame cannot draw device buffers")
let handles: Buffer[7] = [buffers.triangles, buffers.corners, buffers.positions, buffers.normals, buffers.colors, buffers.faces, buffers.flags]
for handle in handles:
if let state = handle.state:
if state.device != device: error(wrong_device, "a mesh buffer belongs to another device")
if handles[0].state == none or handles[2].state == none:
error(invalid_geometry, "a mesh draw needs its triangles (or edges) and positions")
let size = try target.size()
if size.width <= 0.0 or size.height <= 0.0: return
let scale_x = frame_scale(target.frame.size.pixel_width, target.frame.size.width)
let scale_y = frame_scale(target.frame.size.pixel_height, target.frame.size.height)
let depth_slope = slope_bias * math.max(scale_x, scale_y)
let region = Viewport(target.rectangle.x * scale_x, target.rectangle.y * scale_y, size.pixel_width, size.pixel_height)
var draw = try new MeshDraw(kind = kind) in memory.heap
memory.copy(draw.parameters[..<parameters.length], parameters, parameters.length)
# Parameters an older, shorter block leaves out are off.
for index in parameters.length..<mesh_parameter_count: draw.parameters[index] = 0.0
draw.parameters[mesh_line + 1] = (f32)size.width
draw.parameters[mesh_line + 2] = (f32)size.height
draw.parameters[mesh_eye + 3] = -1.0 if device.backend == Backend.vulkan else 1.0
for index in 0..<handles.length:
if let state = handles[index].state:
state.references += 1
draw.buffers[index] = state
target.frame.canvas.mesh(draw, target.clipping, region, vertices, (f32)depth_slope) catch failure:
release_mesh_draw(draw)
error(failure.code, failure.message)
func backend_buffer_create(device: DeviceState*, data: const u8[]) -> void*!:
if (platform.windows or platform.linux) and device.backend == Backend.vulkan:
return (void*)try vulkan_buffer_create((VulkanDevice*)device.native, data)
if platform.macos and platform.arm64:
return try metal_buffer_create((MetalDevice*)device.native, data)
error(unsupported, "GPU buffers are unavailable on this backend")
func backend_buffer_upload(device: DeviceState*, native: void*, offset: usize, data: const u8[]) -> !:
if (platform.windows or platform.linux) and device.backend == Backend.vulkan:
try vulkan_buffer_upload((VulkanDevice*)device.native, (VulkanBuffer*)native, offset, data)
return
if platform.macos and platform.arm64:
try metal_buffer_upload((MetalDevice*)device.native, native, offset, data)
return
error(unsupported, "GPU buffers are unavailable on this backend")
func backend_buffer_destroyer(backend: Backend) -> func(void*, void*) -> unit:
if (platform.windows or platform.linux) and backend == Backend.vulkan: return vulkan_buffer_release
if platform.macos and platform.arm64 and backend == Backend.metal: return metal_buffer_release
trap("GPU buffers are unavailable on this backend")