vulkanhlsl

Dynamic index in vk::binding(index, 0)?


I've recently been introduced to a new rendering system which uses the bindings from Vulkan and I've created a system where I bind a lot of textures from a vector.

This causes an issue that everytime I create a shader I have to tell it which texture it has to use statically.

[[vk::binding(1, 0)]]Texture2D spriteTexture : register(t0);
//Where the one is now the index of what texture I am using.
//When I send in vertex data I bind a texture ID (texID) which if instead of binding a texture I bind a textureArray I can use the texID to choose texture.


struct PixelInput
{
    [[vk::location(0)]] float4 position : POSITION;
    [[vk::location(1)]] float4 color : COLOR;
    [[vk::location(2)]] float2 uv : UV;
    [[vk::location(3)]] int texID : TEXID;
};

float4 PSMain(PixelInput input) : SV_TARGET
{
    float4 color = spriteTexture.Sample(UISampler, input.uv);
    return color;
};

This works but I want to make something which allows me to change texture during runtime without changing shaders.

[[vk::binding(vk::location(3), 0)]]Texture2D spriteTexture : register(t0);
//I know this doesn't work but why? I have tried googling some documentation of vk::location and vk::binding but mostly just found old repositories on github.
struct PixelInput
{
    [[vk::location(0)]] float4 position : POSITION;
    [[vk::location(1)]] float4 color : COLOR;
    [[vk::location(2)]] float2 uv : UV;
};

Solution

  • The core Vulkan specification is based on the same static binding model as OpenGL, and uses fixed bind points for resources.

    Descriptor indexing using a shader-based index is possible and widely available, but relies on newer drivers/extensions to provide the functionality. To use it you need to enable the VK_EXT_descriptor_indexing extension (for Vulkan 1.1) or enable the descriptorIndexing feature (for Vulkan 1.2 or later).

    More information about descriptor indexing can be found here:

    https://docs.vulkan.org/samples/latest/samples/extensions/descriptor_indexing/README.html

    ... in particular note the uniformity requirement for descriptor indices, and the need to tag accesses as non-uniform if you cannot guarantee this.