这篇 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.