简体   繁体   中英

How to use Depth Testing with CAMetalLayer using Metal and Swift?

Recently I decided to learn how to use the Metal framework with Swift. I read some turorials, watched videos, did a few things and finally I got to part where I have to use Depth Testing to make things look good.

I haven't done such low level graphics programming before, so I looked around the whole Internet on how Depth Testing works and how to implemented it using CAMetalLayer and Metal.

However all examples of Depth Testing, which I found, were done using Open GL and I couldn't find such functions in Metal.

How do I implement Depth Testing with CAMetalLayer using Metal and Swift?

Thank you in advance!

This is a good example. http://metalbyexample.com/up-and-running-3/

The key is that CAMetalLayer does not maintain the depth map for you. You need to create and manage explicitly the depth texture. And attach the depth texture to the depth-stencil descriptor which you use to create the render-encoder.

The question of this Stackoverflow post contains your answer, although it's written in Obj-C. But basically, like what Dong Feng has pointed out, you need to create and manage the depth texture by yourself.

Here's a Swift 4 snippet for how to create a depth texture

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)!
}

And here's how you need to attach it to a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM