Search Unity

Frustum new/far clipping planes: how do they work?

Discussion in 'General Graphics' started by cowlinator, Feb 13, 2015.

  1. cowlinator

    cowlinator

    Joined:
    Mar 15, 2012
    Posts:
    69
  2. Dolkar

    Dolkar

    Joined:
    Jun 8, 2013
    Posts:
    576
    Well, this is really hard to answer without explaining a bunch of stuff first. Anyway, here goes:

    The thing is, the graphics hardware is a massively parallel processor. The triangles of a mesh are not rendered one at a time, but instead in pretty much random order. You still want them to be ordered by the distance to the camera though. This is handled by using a z-buffer that stores the smallest distance to the camera of every triangle that has been rendered to this point, at each pixel. Every time a new pixel is being rendered, it is tested against this distance. If it's closer to the camera, then the value in the z-buffer is updated to the new smallest distance and that pixel is rendered. However, if the pixel is further than this distance, it is instead discarded, because it should not be visible.

    For optimal performance, this "z-test" is usually performed right after the triangle is rasterized, even before a pixel shader gets executed. It would be wasteful to render every pixel of a very expensive material only to have 90% of it thrown away because it's hidden behind a wall. This is also a reason why Unity sorts opaque objects roughly from front to back before rendering them, to maximize this occlusion culling potential.

    So where am I going with all this? Shaders that use the clip() instruction can't have this z-test performed early. You have no way of knowing which pixel should write its depth before you actually execute the pixel shader! So the entire idea of early z test goes out of the window and it instead has to be done after the shader finished, wasting cycles if the pixels ends up occluded.

    On the other hand, clipping planes are implemented in hardware so the pixels and their depths can be checked against them early before the shader runs no matter what. I'm not sure about mobile, but desktop GPUs mostly support arbitrary user clip planes as well. Either way, that feature is to my knowledge not exposed in Unity.

    As a disclaimer... this is how it works on desktop GPUs.. Mobile could be doing it differently, resulting in larger performance drop when clip is used. In any case, hardware clip planes are not affected, because the rasterizer itself can cull against them.
     
  3. cowlinator

    cowlinator

    Joined:
    Mar 15, 2012
    Posts:
    69
    Thank you Dolkar!