简体   繁体   中英

Use Compute Shader to Process the Render Target

I would like to use the Render Target as the input the Compute Shader in DirectX 11. I only need to read the Render Target in the Compute Shader, and in my case I do not have to render the Compute Shader output (although I do have to consume this in the CPU later, and may need to process it in additional Compute Shader passes.)

I have seen comments that this is possible, but I cannot seem to find any sample code that shows how to consume the render target (a Texture2D) as a Compute Shader Buffer in a Shader Resource View. I have tried a number of options, but have not been able to create the Shader Resource View that the Computer Shader needs as input.

A pointer to a fragment of sample code would be most appreciated.

Your resource needs to indeed have Shader resource usage mode to be readable via compute shader: -For a standard render target : D3D11_BIND_SHADER_RESOURCE -For a swap chain : DXGI_USAGE_SHADER_INPUT in swap chain description.

Then you just create a Shader Resource View as usual.

It is also possible (in some extents), to have your buffer also writeable directly by the compute shader. Flags is D3D11_BIND_UNORDERED_ACCESS or DXGI_USAGE_UNORDERED_ACCESS in that case (please note this doesn't work for multisampled textures tho).

Here is a very simple compute shader that reads samples from a texture from UV coords:

RWStructuredBuffer<float4> rwbuffer;

//Render target previously rendered
Texture2D tex;

//Buffer containing uvs for sampling
 StructuredBuffer<float2> uv <string uiname="UV Buffer";>;

 SamplerState mySampler : IMMUTABLE
 {
     Filter = MIN_MAG_MIP_LINEAR;
     AddressU = Clamp;
     AddressV = Clamp;
 };

 [numthreads(1, 1, 1)]
 void CS( uint3 i : SV_DispatchThreadID)
 { 
//Read color and write to buffer
rwbuffer[i.x] = tex.SampleLevel(mySampler,uv[i.x],0);
 }

 technique11 Process
 {
pass P0
{
    SetComputeShader( CompileShader( cs_5_0, CS() ) );
}
 }

Hope that helps.

the first requirement to create a shader resource view from a texture is to create the texture with the good flags. The flag is D3D11_BIND_SHADER_RESOURCE . It has to be set in the decription binding member before calling CreateTexture2D.

If the render target is not create by you, but from the swap chain, you cannot bind it as an SRV. You will need an intermediate frame buffer and copy it to the back buffer at the end of the frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM