ios – 金属着色语言 – (控制台)输出?

前端之家收集整理的这篇文章主要介绍了ios – 金属着色语言 – (控制台)输出?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以使用控制台输出调试我的金属着色语言代码(比如在 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)")
...

.Metal文件

...
kernel void shader(...,device int &printBuffer [[8]],...) {
...
printBuffer = 123;
...
}

控制台输出始终为myMetalOutput:0

解决方法

如果有人需要,这是一个有效的解决方案:
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;

}

猜你在找的iOS相关文章