我可以使用控制台输出调试我的金属着色语言代码(比如在
Swift中打印)吗?
如果有,怎么样?
如果不是,有没有其他方法从我的.Metal文件输出变量? (也许通过使用commandEncoder-buffer将数据从.Metal文件传递到我的.swift文件?)
我没有成功尝试通过commandEncoder传递对Int变量(在我的.swift文件中)的引用到我的.Metal文件.在.Metal文件中,我为int变量赋值,但是如果我在swift文件中打印Int,则指定的值不存在.
.swift文件:
... var myMetalOutput: Int = 0 ... let printBuffer = device.newBufferWithBytes(&myMetalOutput,length: sizeof(Int),options: MTLResourceOptions.cpuCacheModeDefaultCache) commandEncoder.setBuffer(printBuffer,offset: 0,atIndex: 8) ... commandBuffer.commit() drawable.present() print("myMetalOutput: \(myMetalOutput)") ...
... kernel void shader(...,device int &printBuffer [[8]],...) { ... printBuffer = 123; ... }
解决方法
如果有人需要,这是一个有效的解决方案:
let device = MTLCreateSystemDefaultDevice()! let commandQueue = device.newCommandQueue() let defaultLibrary = device.newDefaultLibrary()! let commandBuffer = commandQueue.commandBuffer() let computeCommandEncoder = commandBuffer.computeCommandEncoder() let program = defaultLibrary.newFunctionWithName("shader") do { let computePipelineFilter = try device.newComputePipelineStateWithFunction(program!) computeCommandEncoder.setComputePipelineState(computePipelineFilter) var resultdata = [Int](count: 1,repeatedValue: 0) let outVectorBuffer = device.newBufferWithBytes(&resultdata,length: sizeofValue(1),options: MTLResourceOptions.cpuCacheModeDefaultCache) computeCommandEncoder.setBuffer(outVectorBuffer,atIndex: 0) let threadsPerGroup = MTLSize(width:1,height:1,depth:1) let numThreadgroups = MTLSize(width:1,depth:1) computeCommandEncoder.dispatchThreadgroups(numThreadgroups,threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.addCompletedHandler {commandBuffer in let data = NSData(bytes: outVectorBuffer.contents(),length: sizeof(NSInteger)) var out: NSInteger = 0 data.getBytes(&out,length: sizeof(NSInteger)) print("data: \(out)") } commandBuffer.commit() } catch { fatalError("newComputePipelineStateWithFunction Failed ") }
着色器:
kernel void shader(device int &printBuffer [[buffer(0)]],uint id [[ thread_position_in_grid ]]) { printBuffer = 123; }