Hi everyone.
I’ve created a really simple test program to use a compute shader within UE4 to do some very very basic processing. **I’d like to be able to get the processed data back into the CPU side of things. **I have a simple struct defined from which I create a Structured Buffer.
So, first I create the data:
struct MyStruct{
int i;
float f;
};
int dim = 10;
TResourceArray<MyStruct> data;
MyStruct init;
init.i = 0;
init.f = 0.0f;
data.Init(init, dim);
for (int i = 0; i < dim; i++){
data*.i = i;
}
Onwards to the creation of the StructuredBuffer:
//this can be used to set initial data of the buffer
FRHIResourceCreateInfo CreateInfo;
CreateInfo.ResourceArray = &data;
FStructuredBufferRHIRef StructResource = RHICreateStructuredBuffer(
sizeof(MyStruct),
data.Num() * sizeof(MyStruct),
BUF_UnorderedAccess | BUF_ShaderResource,
CreateInfo
);
Afterwards the steps aren’t totally clear to me, but here’s what I figured would work:
I get the UAV for the data:
FUnorderedAccessViewRHIRef StructUAV = RHICreateUnorderedAccessView(StructResource, false, false);
I get my custom compute shader:
FRHICommandListImmediate& RHICmdList = GRHICommandList.GetImmediateCommandList();
TShaderMapRef<MyCS> MyCS(GetGlobalShaderMap());
FComputeShaderRHIParamRef CSRef = MyCS->GetComputeShader();
RHICmdList.SetComputeShader(CSRef);
I set the UAV “into” the shader:
//RWBuffer is a FShaderResourceParameter defined and bound in the custom CS.
RHICmdList.SetUAVParameter(CSRef, MyCS->RWBuffer.GetBaseIndex(), StructUAV);
Finally, I dispatch the compute shader:
DispatchComputeShader(RHICmdList, *MyCS, 2, 1, 1);
It compiles and doesn’t crash. However, I’ve rummaged through the RHI methods and whatnot and haven’t found anything that could let me access the data I processed in the compute shader. Does anyone have an idea on how to achieve this? I know it is usual to do it with output textures, for example, but I imagine there would be a more direct way (DirectX has a CopyResource function, for instance…)
Thanks in advance!
NOTES:
I am using the ENQUEUE_UNIQUE_RENDER_COMMAND macro to send stuff to the rendering thread. I just haven’t shown it for the sake of brevity.
The compute shader has a DECLARE_SHADER_TYPE and IMPLEMENT_SHADER_TYPE correctly set up (I think). If need be, I may also post the CS code here.