Provides a mechanism to lay out data into GPU buffers ensuring WGSL's memory layout requirements are met.
Features
- supports all WGSL host-shareable types + wrapper types (
&T
,&mut T
,Box<T>
, ...) - supports data types from a multitude of crates as features
- covers a wide area of use cases (see examples)
Motivation
Having to manually lay out data into GPU buffers can become very tedious and error prone. How do you make sure the data in the buffer is laid out correctly? Enforce it so that future changes don't break this delicate balance?
encase
gives you the ability to make sure at compile time that your types will be laid out correctly.
Design
The core trait is ShaderType
which mainly contains metadata about the given type.
The WriteInto
, ReadFrom
and CreateFrom
traits represent the ability of a type to be written into the buffer, read from the buffer and created from the buffer respectively.
Most data types can implement the above traits via their respective macros:
impl_vector!
for vectorsimpl_matrix!
for matricesimpl_rts_array!
for runtime-sized arraysimpl_wrapper!
for wrappersShaderType
for structs
The UniformBuffer
, StorageBuffer
, DynamicUniformBuffer
and DynamicStorageBuffer
structs are wrappers around an underlying raw buffer (a type implementing BufferRef
and/or BufferMut
depending on required capability). They facilitate the read/write/create operations.
Examples
Write affine transform to uniform buffer
use ;
let transform = AffineTransform2D ;
let mut buffer = new;
buffer.write.unwrap;
let byte_buffer = buffer.into_inner;
// write byte_buffer to GPU
assert_eq!;
Create vector instance by reading from dynamic uniform buffer at specific offset
use DynamicUniformBuffer;
// read byte_buffer from GPU
let byte_buffer = ;
let mut buffer = new;
buffer.set_offset;
let vector: Vector2 = buffer.create.unwrap;
assert_eq!;
Write and read back data from storage buffer
use ;
let mut positions = Positions ;
let mut byte_buffer: = Vec new;
let mut buffer = new;
buffer.write.unwrap;
// write byte_buffer to GPU
// change length on GPU side
byte_buffer = 2;
// read byte_buffer from GPU
let mut buffer = new;
buffer.read.unwrap;
assert_eq!;
Write different data types to dynamic storage buffer
use ;
let mut byte_buffer: = Vec new;
let mut buffer = new_with_alignment;
let offsets = ;
// write byte_buffer to GPU
assert_eq!;
Supports writing to uninitialized memory as well.
use MaybeUninit;
use ;
let mut uninit_buffer: = Vec new;
let mut buffer = new_with_alignment;
let offsets = ;
// SAFETY: Vec<u8> and Vec<MaybeUninit<u8>> share the same layout.
let byte_buffer: = unsafe ;
forget;
// write byte_buffer to GPU
assert_eq!;