Search code examples
directxshaderhlsldirectx-11sharpdx

Shader reflection : variable name?


How (if at all possible) could i get the name of variables / structure members in a shader from reflection?

I'm talking about raw hlsl shaders (no effet Framework / no D3DX, just raw directX).

I'm using SharpDX and found out how to get most of the information i need from the shader signature

new SharpDX.D3DCompiler.ShaderReflection(MyShaderByteCode); 

I can get most of the information i need, but while i can retrieve the sementic name (TEXCOORD, POSITION etc) i can't retrieve the actual name of the element (there's no "name" property).

Am i going about this the wrong way? Is this even possible at all?

struct Vertex
{
    float4 Position : POSITION;
    float2 UVPosition : TEXCOORD;
};

struct Pixel
{
    float4 Position : SV_POSITION;
    float2 UVPosition : TEXCOORD;
};

float4x4 worldViewProj;

Texture2D<float4> diffuse   : register(t0);
Texture2D<float4> height    : register(t1);
Texture2D<float4> lightmap  : register(t2);
SamplerState pictureSampler;

Pixel PerVertex(Vertex input)
{
    Pixel output = (Pixel) 0;
    input.Position.z += height.SampleLevel(pictureSampler, input.UVPosition, 0).r / 2;
    output.Position = mul(input.Position, worldViewProj);
    output.UVPosition = input.UVPosition;
    return output;
}

float4 PerPixel(Pixel input) : SV_Target
{
    return diffuse.Sample(pictureSampler, input.UVPosition) * lightmap.Sample(pictureSampler, input.UVPosition);
}

What i can retrieve is "POSITION" and "TEXCOORD", what i want to retrieve is "Position" and "UVPosition"


Solution

  • You need to iterate trough constant buffers. Please note that is a Constant Buffer is not used, it will be stripped off the bytecode.

    Attached code that iterates though all variables:

    SharpDX.D3DCompiler.ShaderReflection sr = new SharpDX.D3DCompiler.ShaderReflection(mybytecode);
            for (int i = 0; i < sr.Description.ConstantBuffers; i++)
            {
                SharpDX.D3DCompiler.ConstantBuffer cb = sr.GetConstantBuffer(i);
                for (int j = 0; j < cb.Description.VariableCount; j++)
                {
                    SharpDX.D3DCompiler.ShaderReflectionVariable variable = cb.GetVariable(j);
                    Console.WriteLine(variable.Description.Name);
                }
            }