Shedex
Shedex

Reputation: 131

how can i load an array of uniform buffer objects into the shader?

shader code:

// UBO for MVP matrices   
layout (binding = 0) uniform UniformBufferObject {
        mat4 model;
        mat4 view;
        mat4 proj;
} ubo;

this works fine because its just one struct and I can set the VkWriteDescriptorSet.descriptorCount to 1. But how can I create an array of those structs?

// Want to do something like this
// for lighting calculations
layout (binding = 2) uniform Light {
    vec3 position;
    vec3 color;
} lights[4];

I have the data for all of the four lights stored in one buffer. When I set the VkWriteDescriptorSet.descriptorCount to four, Do I have to create four VkDescriptorBufferInfo? If so, I dont know what to put into offset and range.

Upvotes: 1

Views: 4599

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474436

All of the blocks in a uniform buffer array live in the same descriptor. However, they are still different blocks; they get a different VkDescriptorBufferInfo info object. So those blocks don't have to come from sequential regions of storage.

Note: The KHR_vulkan_glsl extension gets this wrong, if you look pay close attention. It notes that arrays of opaque types should go into a single descriptor, but arrays of interface blocks don't. The actual glslangValidator compiler (and SPIR-V and Vulkan) do handle it as I described.

However, you cannot access the elements of an interface block array with anything other than dynamically uniform expressions. And even that requires having a certain feature available; without that feature, you can only access the array with constant expressions.

What you probably want is an array within the block, not an array of blocks:

struct Light
{
  vec4 position; //(NEVER use `vec3` in blocks)
  vec4 color;
};

layout (set = 0, binding = 2, std140) uniform Lights {
  Light lights[4];
};

This means that you have a single descriptor in binding slot 2 (descriptorCount is 1). And the buffer's data should be 4 sequential structs.

Upvotes: 3

Related Questions