Get result of GPU in CPU

I wanted to get result values of compute shader by GPU in CPU. And I found that next three should have the common data format.

1) format for MTLTextureDescriptor
2) output of compute shader
3) receiving data format in CPU

So I was able to succeed ONLY for 16 bit unsigned integer. Is this right???
Anyway the code is like as follows.

1) format for MTLTextureDescriptor
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(MTLPixelFormat.R16Uint, width: width, height: height, mipmapped: false)

texture = device.newTextureWithDescriptor(textureDescriptor)
texture is an object of MTLTexture protocol, and this texture is for output of compute shader.

2) output of compute shader
kernel void hogeComputeShader(texture2d<half, access::read>  inTexture   [[ texture(0) ]],
                      texture2d<unsigned short, access::write> outTexture  [[ texture(1) ]],
                      uint2                          gid         [[ thread_position_in_grid ]]) {
This is a name and arguments of compute shader. The first argument is for input and second is for output.
Output values are written by “write”, not by “return” in this case.
”unsigned short” means 16 bit unsigned integer.

3) receiving data format in CPU
After completion of process in GPU, I succeeded to receive the result data as follows in CPU :
    typealias UInt16Pointer = UnsafeMutablePointer
    let pointer = UInt16Pointer.alloc(w*h)
    let region = MTLRegionMake2D(0,0 , w,h)
    texture.getBytes(pointer, bytesPerRow: w*sizeof(UInt16), fromRegion: region, mipmapLevel: 0)
By the way I was not able to get data as I expected at first. Because I tried to access to data before GPU finished its task. So I had to use MTLCommandBufferのaddCompleteHandler: method to know the end of GPU’s task.

memo:iOS 8.1.3 / Swift 1.1
Develop | Comments(0) | Trackback(0)