最近我决定学习如何在Swift中使用Metal框架。我阅读了一些杂志,观看了视频,做了一些事情,最后我得到了必须使用深度测试以使事情看起来很好的部分。
之前我还没有做过如此低水平的图形编程,因此我浏览了整个互联网,了解深度测试的工作原理以及如何使用CAMetalLayer和Metal实现它。
然而,我发现深度测试的所有例子都是使用Open GL完成的,我无法在Metal中找到这样的函数。
如何使用Metal和Swift使用CAMetalLayer实现深度测试?
提前谢谢!
答案 0 :(得分:2)
这是一个很好的例子。 http://metalbyexample.com/up-and-running-3/
关键是CAMetalLayer
不能为您维护深度图。您需要明确地创建和管理深度纹理。并将深度纹理附加到用于创建渲染编码器的深度模板描述符。
答案 1 :(得分:0)
this Stackoverflow post的问题包含您的答案,尽管它是用Obj-C编写的。但基本上,就像董锋指出的那样,您需要自己创建和管理深度纹理。
这是一个有关如何创建深度纹理的Swift 4代码段
func buildDepthTexture(_ device: MTLDevice, _ size: CGSize) -> MTLTexture {
let desc = MTLTextureDescriptor.texture2DDescriptor(
pixelFormat: .depth32Float_stencil8,
width: Int(size.width), height: Int(size.height), mipmapped: false)
desc.storageMode = .private
desc.usage = .renderTarget
return device.makeTexture(descriptor: desc)!
}
这是将其附加到MTLRenderPassDescriptor
let renderPassDesc = MTLRenderPassDescriptor()
let depthAttachment = renderPassDesc.depthAttachment!
// depthTexture is created using the above function
depthAttachment.texture = depthTexture
depthAttachment.clearDepth = 1.0
depthAttachment.storeAction = .dontCare
// Maybe set up color attachment, etc.