簡體   English   中英

金屬着色器輸出數據(GPGPU)

[英]Metal shader output data (GPGPU)

我正在嘗試在ios上實現一些圖像檢測算法,並且我需要一些應作為着色器(金屬)使用的數據准備,因此它應將結果數據傳遞給輸出數組。

小例子: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(金屬着色器)

...
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
}

所以我希望它可以打印

first = 5

但它打印

first = 0

這樣看來着色器不會更改緩沖區內容嗎? 有什么想法使它起作用嗎?

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

您試圖從線程組中的每個像素寫入相同的輸出存儲位置。 如果要寫入一個存儲位置,則必須格外小心,僅對每個gid元素標識的每個像素寫入1個存儲位置。 更好的方法是只讀取輸入紋理並為每個像素寫入輸出紋理,只需刪除uint * result緩沖區並直接使用紋理,您的頭痛就會消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM