Module scratch_allocator

Source
Expand description

A linear allocator that can be used for scratch resources.

It is exposed through the InFlightContext struct, but you can also create your own instances elsewhere.

The allocator works by linearly incrementing an offset on every allocation. Deallocation is only possible by calling ScratchAllocator::reset, which will free all memory and reset the offset to zero.

§Example

// Function that uses the buffer in some way and returns a fence
// that is signaled when the work is done.
fn use_the_buffer(buffer: BufferView) -> Fence<()> {
    unimplemented!()
}

fn use_scratch_allocator<A: Allocator>(device: Device, alloc: &mut A) -> Result<()> {
    let mut allocator = ScratchAllocator::new(device.clone(), alloc, 128 as u64, vk::BufferUsageFlags::UNIFORM_BUFFER)?;
    let buffer: BufferView = allocator.allocate(128 as u64)?;
    let mut fence = use_the_buffer(buffer);
    fence.wait()?;
    // SAFETY: We just waited for the fence, so all work using our allocator is done.
    unsafe { allocator.reset(); }
    // We are back at the beginning of the allocator, so there are 128 bytes free again.
    let buffer: BufferView = allocator.allocate(128 as u64)?;
    Ok(())
}

Structs§

ScratchAllocator
A linear allocator used for short-lived resources. A good example of such a resource is a buffer that needs to be updated every frame, like a uniform buffer for transform data. Because of this typical usage, the scratch allocator allocates memory with MemoryType::CpuToGpu.