Search code examples
iosmetal

Metal on iOS: when to read visibilityResultBuffer?


According to Apple's documentation we can monitor samples that pass the depth and stencil tests with setVisibilityResultMode. The result will be written into visibilityResultBuffer. However, I can't find any documentation about when I can access the visibilityResultBuffer to read the result. Is there any callback that can notify me the result is ready? Where can I find more detailed documentation or example about metal's visibilityResultMode?


Solution

  • It's safe to read visibility results on the CPU once the command buffer containing the draw calls you're testing for visibility completes. You can add a completed handler block to the command buffer to get notified of this:

    commandBuffer.addCompletedHandler { completedCommandBuffer in
        self.consumeVisibilityResults()
    }
    

    Remember to call addCompletedHandler(:) before you call commit on your command buffer.

    Note that this handler will be called asynchronously, after the drawing for your current frame is done, so you won't be able to use the visibility results of one frame in that same frame. For this reason, occlusion query-based visibility often has a frame or two of lag. You can read a good overview of this and related issues here.