最近我决定学习如何在 Swift 中使用 Metal 框架。我阅读了一些教程,观看了视频,做了一些事情,最后我不得不使用深度测试来让事情看起来不错。
我以前没有做过这么低级的图形编程,所以我在整个互联网上查看了深度测试的工作原理以及如何使用 CAMetalLayer 和 Metal 来实现它。
然而,我发现的所有深度测试示例都是使用 Open GL 完成的,我在 Metal 中找不到这样的功能。
如何使用 Metal 和 Swift 使用 CAMetalLayer 实现深度测试?
先感谢您!
最近我决定学习如何在 Swift 中使用 Metal 框架。我阅读了一些教程,观看了视频,做了一些事情,最后我不得不使用深度测试来让事情看起来不错。
我以前没有做过这么低级的图形编程,所以我在整个互联网上查看了深度测试的工作原理以及如何使用 CAMetalLayer 和 Metal 来实现它。
然而,我发现的所有深度测试示例都是使用 Open GL 完成的,我在 Metal 中找不到这样的功能。
如何使用 Metal 和 Swift 使用 CAMetalLayer 实现深度测试?
先感谢您!
这是一个很好的例子。 http://metalbyexample.com/up-and-running-3/
关键是它CAMetalLayer不会为您维护深度图。您需要明确地创建和管理深度纹理。并将深度纹理附加到用于创建渲染编码器的深度模板描述符。
这篇 Stackoverflow 帖子的问题包含您的答案,尽管它是用 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.