Search code examples
c++directx-11directx-9texture2ddxgi

How to use swizzle .rrrg in directx11 shader


I have to create a texture with equivalent format of D3DFMT_A8L8 in directx9 to directx11. But the note in the documentation is not clear to me. Would someone explain what should be done? While creating input layout I am facing invalid parameter error.

D3DFMT_A8L8 => DXGI_FORMAT_R8G8_UNORM Note: Use swizzle .rrrg in shader to duplicate red and move green to the alpha components to get Direct3D 9 behavior.


Solution

  • In Direct3D 9, the "Luminance" formats would automatically be read in the shader as RGB values (replicated) because they were greyscale formats. In Direct3D 10+, there are no "Luminance" format. There are one and two channel formats, and there's no "special behavior" with them.

    Therefore, in a shader a DXGI_FORMAT_R8G8_UNORM texture will have the first channel in the 'r' channel and the second channel in the 'g' channel. The DXGI_FORMAT_R8G8_UNORM has the same memory foot-print as D3DFMT_A8L8, i.e. two 8-bit channels of unsigned normal integer data, but if you want the behavior in a modern shader that matches the old one you have to do it explicitly with shader swizzles:

    Texture2D<float4> Texture : register(t0);
    sampler Sampler : register(s0);
    
    float4 color = Texture.Sample(Sampler, pin.TexCoord);
    
    // Special-case for DXGI_FORMAT_R8G8_UNORM treated as D3DFMT_A8L8
    color = color.rrrg;
    

    This has nothing at all to do with input layouts. It's just the way a texture sampler works.