简体   繁体   English

金属着色器输出数据(GPGPU)

[英]Metal shader output data (GPGPU)

I'm trying to implement some image detection algorithms on ios and I need some data preparation that should work as shader (Metal) so it should pass output array with result data. 我正在尝试在ios上实现一些图像检测算法,并且我需要一些应作为着色器(金属)使用的数据准备,因此它应将结果数据传递给输出数组。

Small example: SWIFT 小例子:SWIFT

...
// Create buffer
var resultBuffer = device.makeBuffer(length: SIZE * MemoryLayout<Int32>.size, options: .storageModeShared)!

// Set buffer to encoder
computeCommandEncoder?.setBuffer(resultBuffer, offset: 0, index: 0)
...
// Call shader
commandBuffer.commit()
commandBuffer.waitUntilCompleted()

// Print first element for test
var p = resultBuffer.contents()
let first = p.load(as: UInt32.self)
print("first = \(first)")

MSL (Metal Shader) MSL(金属着色器)

...
kernel void preparation(
  texture2d<float, access::read> inTexture [[texture(0)]], // Input texture

  texture2d<float, access::write> outTexture [[texture(1)]], // Output texture
  device uint* result [[ buffer(0) ]], // Output buffer
                uint2 gid [[thread_position_in_grid]])
{
    result[0] = 5; // Just for test set first element to 5
    float4 colorAtPixel = inTexture.read(gid);
    outTexture.write(colorAtPixel, gid); // Copy color from input texture to output texture
}

So I expect it should print 所以我希望它可以打印

first = 5

But it prints 但它打印

first = 0

So it seems shader does not change buffer content? 这样看来着色器不会更改缓冲区内容吗? Any ideas how to make it to work? 有什么想法使它起作用吗?

PS I use iOs 11.2, iPhone 5S, XCode 9.2 PS我使用iOs 11.2,iPhone 5S,XCode 9.2

You are attempting to write to the same output memory location from every pixel in the thread group. 您试图从线程组中的每个像素写入相同的输出存储位置。 If you are writing to a memory location, you have to take special care to only write to 1 memory location for each pixel identified by each gid element. 如果要写入一个存储位置,则必须格外小心,仅对每个gid元素标识的每个像素写入1个存储位置。 The better way to do this is to just read from an input texture and write to the output texture for each pixel, just remove the uint*result buffer and use the textures directly and your headaches will go away. 更好的方法是只读取输入纹理并为每个像素写入输出纹理,只需删除uint * result缓冲区并直接使用纹理,您的头痛就会消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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