Skip to content

RI::createBuffer, RI::destroyBuffer

What it does

A buffer is a range of GPU-accessible memory with no pixel format: shaders can read or write it as structured elements, raw bytes, or constant data, and copy commands can transfer bytes between buffers.

RI::createBuffer(device, memory, offset, desc) creates a buffer of desc.size bytes placed in memory at offset. It allocates no device memory itself; the buffer's bytes live inside memory. Query the required size, alignment, and allowed memory kinds first with RI::bufferRequirements. RI::destroyBuffer(device, buffer) destroys the buffer without freeing memory.

The returned RI::Buffer exposes public fields you can read directly:

  • size and usage: copied from desc;
  • gpuAddress: the buffer's 64-bit GPU virtual address, always available;
  • mapped: the buffer's CPU pointer (memory.mapped + offset), or nullptr when memory is RI::MemoryKind::eGPU.

The usage flags (RI::BufferUsage) declare how the buffer will be used. Set every flag you need and omit the rest, because unused flags can reduce performance on some GPUs.

BufferUsage Lets you Vulkan usage D3D12
eRead write a ReadView (StructuredBuffer, ByteAddressBuffer) STORAGE_BUFFER -
eReadWrite write a ReadWriteView (RWStructuredBuffer, RWByteAddressBuffer) STORAGE_BUFFER ALLOW_UNORDERED_ACCESS
eConstant write a ConstantBufferView (ConstantBuffer<T>) UNIFORM_BUFFER -
eCopySrc / eCopyDst copy from or to the buffer (cmdCopyBuffer, copies); eCopyDst also enables cmdClearBuffer, cmdWriteSmallData, and cmdResolveQueries TRANSFER_SRC / TRANSFER_DST ALLOW_UNORDERED_ACCESS for eCopyDst in eGPU / eGPUUpload
eIndirect read indirect arguments or counts from it (indirect) INDIRECT_BUFFER -
eIndex bind it as an index buffer (cmdDrawIndexed) INDEX_BUFFER -
eAccelerationStructureInput pass vertices, indices, or instances to an acceleration-structure build (raytracing) ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_KHR -
eIndirectScratch use it as driver scratch memory for cmdExecuteIndirectWithRootData PREPROCESS_BUFFER_EXT (VkBufferUsageFlags2) -

On Vulkan, every buffer also receives VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT so its GPU address is always valid. Combine flags with |.

Signature

// <RI/RI.hpp>, namespace RI
Buffer createBuffer(Device &device, const Memory &memory, uint64 offset, const BufferDesc &desc);
// <RI/RI.hpp>, namespace RI
void destroyBuffer(Device &device, Buffer &buffer);
// <RI/RI.hpp>, namespace RI
struct Buffer {
    uint64 size = 0;
    BufferUsage usage = BufferUsage::eNone;
    uint64 gpuAddress = 0;  // always available (P61)
    void *mapped = nullptr; // memory.mapped + offset, or nullptr for eGPU memory
    // internal: backend-private state (not part of the API)
};

From the header: A buffer placed in user memory at offset (P31). It owns no memory.

Field Type Default Description
size uint64 0
usage BufferUsage BufferUsage::eNone
gpuAddress uint64 0 always available (P61)
mapped void * nullptr memory.mapped + offset, or nullptr for eGPU memory
// <RI/RI.hpp>, namespace RI
struct BufferDesc {
    uint64 size = 0;
    BufferUsage usage = BufferUsage::eNone;
    std::string_view name; // empty: unnamed (P106)
};
Field Type Default Description
size uint64 0
usage BufferUsage BufferUsage::eNone
name std::string_view empty: unnamed (P106)
// <RI/RI.hpp>, namespace RI
enum class BufferUsage : uint32 {
    eNone = 0,
    eRead = rvl::eBit(0),      // ReadView: StructuredBuffer, ByteAddressBuffer
    eReadWrite = rvl::eBit(1), // ReadWriteView: RWStructuredBuffer, RWByteAddressBuffer
    eConstant = rvl::eBit(2),  // ConstantBufferView: ConstantBuffer<T>
    eCopySrc = rvl::eBit(3),
    eCopyDst = rvl::eBit(4),
    eIndirect = rvl::eBit(5), // indirect arguments (P48)
    eIndex = rvl::eBit(6),    // index buffer for cmdDrawIndexed (P39)
    eAccelerationStructureInput = rvl::eBit(7), // vertices, indices or instances of a build (P49)
    eIndirectScratch = rvl::eBit(8), // scratch of cmdExecuteIndirectWithRootData (P48)
};

From the header: What a buffer may be used for (P58). Read and read-write views are shader accesses through descriptors (P87); GPU addresses are always available (P61).

Value Meaning
eNone
eRead ReadView: StructuredBuffer, ByteAddressBuffer
eReadWrite ReadWriteView: RWStructuredBuffer, RWByteAddressBuffer
eConstant ConstantBufferView: ConstantBuffer
eCopySrc
eCopyDst
eIndirect indirect arguments (P48)
eIndex index buffer for cmdDrawIndexed (P39)
eAccelerationStructureInput vertices, indices or instances of a build (P49)
eIndirectScratch scratch of cmdExecuteIndirectWithRootData (P48)

Example

RI::Buffer input = RI::createBuffer(device, gpuMemory, 0, dataDesc);
RI::Buffer output = RI::createBuffer(device, gpuMemory, outputOffset, dataDesc);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopySrc});
RI::Buffer params =
    RI::createBuffer(device, uploadMemory, paramsOffset, {.size = 256, .usage = RI::BufferUsage::eConstant});
RI::Buffer result = RI::createBuffer(device, readbackMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopyDst});

Writing through a mapped buffer:

// Upload memory stays mapped: write through buffer.mapped, no map call.
auto *values = static_cast<float *>(staging.mapped);
for (uint32 i = 0; i < kCount; ++i) {
    values[i] = static_cast<float>(i);
}
const float offset = 0.25f;
std::memcpy(params.mapped, &offset, sizeof(offset));

The same in native code

RI::Buffer input = RI::createBuffer(device, gpuMemory, 0, dataDesc);
RI::Buffer output = RI::createBuffer(device, gpuMemory, outputOffset, dataDesc);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopySrc});
RI::Buffer params =
    RI::createBuffer(device, uploadMemory, paramsOffset, {.size = 256, .usage = RI::BufferUsage::eConstant});
RI::Buffer result = RI::createBuffer(device, readbackMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopyDst});
// A buffer placed in `memory` at `offset` (which must respect the alignment).
VkBuffer createBuffer(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, const VkBufferCreateInfo &info) {
    VkBuffer buffer = VK_NULL_HANDLE;
    check(vkCreateBuffer(device, &info, nullptr, &buffer), "vkCreateBuffer");
    check(vkBindBufferMemory(device, buffer, memory, offset), "vkBindBufferMemory");
    return buffer;
}
VkBuffer input = createBuffer(device, gpuMemory, 0, dataInfo);
VkBuffer output = createBuffer(device, gpuMemory, outputOffset, dataInfo);
VkBuffer staging = createBuffer(device, uploadMemory, 0, stagingInfo);
VkBuffer params = createBuffer(device, uploadMemory, paramsOffset, paramsInfo);
VkBuffer result = createBuffer(device, readbackMemory, 0, resultInfo);
// A buffer's GPU address (64-bit), usable in shaders and GPU-built tables.
const VkBufferDeviceAddressInfo addressInfo{.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = input};
const VkDeviceAddress inputAddress = vkGetBufferDeviceAddress(device, &addressInfo);

What to watch for: Vulkan creates a buffer unbound and binds it to memory once with vkBindBufferMemory. For vkGetBufferDeviceAddress to work, the buffer must be created with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT and the memory must be allocated with VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT.

D3D12_RESOURCE_DESC1 bufferDesc(UINT64 size, D3D12_RESOURCE_FLAGS flags) {
    return {.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,
            .Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
            .Width = size,
            .Height = 1,
            .DepthOrArraySize = 1,
            .MipLevels = 1,
            .Format = DXGI_FORMAT_UNKNOWN,
            .SampleDesc = {.Count = 1, .Quality = 0},
            .Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
            .Flags = flags}; // ALLOW_UNORDERED_ACCESS for read-write (UAV) use
}
// A buffer placed in `heap` at `offset`. Buffers have no layout: UNDEFINED.
ComPtr<ID3D12Resource> createBuffer(ID3D12Device10 *device, ID3D12Heap *heap, UINT64 offset,
                                    const D3D12_RESOURCE_DESC1 &desc) {
    ComPtr<ID3D12Resource> buffer;
    check(device->CreatePlacedResource2(heap, offset, &desc, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0, nullptr,
                                        IID_PPV_ARGS(&buffer)),
          "CreatePlacedResource2");
    return buffer;
}
ComPtr<ID3D12Resource> input = createBuffer(device.Get(), gpuMemory.Get(), 0, dataDesc);
ComPtr<ID3D12Resource> output = createBuffer(device.Get(), gpuMemory.Get(), outputOffset, dataDesc);
ComPtr<ID3D12Resource> staging =
    createBuffer(device.Get(), uploadMemory.Get(), 0, bufferDesc(kBytes, D3D12_RESOURCE_FLAG_NONE));
ComPtr<ID3D12Resource> params =
    createBuffer(device.Get(), uploadMemory.Get(), paramsOffset, bufferDesc(256, D3D12_RESOURCE_FLAG_NONE));
ComPtr<ID3D12Resource> result =
    createBuffer(device.Get(), readbackMemory.Get(), 0, bufferDesc(kBytes, D3D12_RESOURCE_FLAG_NONE));
const D3D12_GPU_VIRTUAL_ADDRESS inputAddress = input->GetGPUVirtualAddress(); // every buffer has one

What to watch for: CreatePlacedResource2 (with enhanced barriers) takes an initial layout; buffers have no layouts, so it takes D3D12_BARRIER_LAYOUT_UNDEFINED and stays in that state.

Rules and errors

  • offset must be a multiple of the alignment returned by bufferRequirements, and the required size starting at offset must fit inside memory. On Vulkan, memory's native type must also allow the buffer (pass &requirements to allocateMemory when the kind's default type does not). In validation builds, violating any of these rules or passing a freed RI::Memory is a programmer error.
  • On Vulkan, BufferUsage::eAccelerationStructureInput requires DeviceLimits::rayTracing, and BufferUsage::eIndirectScratch requires DeviceLimits::indirectRootData; calling createBuffer without the required feature reports an unsupported error.
  • Destroy a buffer only after the GPU has finished all work that uses it (once its timeline point is reached), and before freeing memory.
  • destroyBuffer resets the passed RI::Buffer struct to its default empty state. Because RI::Buffer is a thin handle-like value, copies still refer to the same buffer. In validation builds, using any copy of a destroyed buffer (in a command, descriptor write, or destroyBuffer) is a programmer error: this buffer 'particles' was destroyed (object #42) for a buffer named particles, or this buffer was destroyed or belongs to another device (object #42) without a name.
  • Two buffers may share memory (aliasing) if they are never used at the same time.
  • A constant buffer's size should be a multiple of 256 bytes: a ConstantBufferView covers a range rounded up to 256 bytes, and the rounded range must fit in the buffer (writeDescriptors).