Version: 2019.4
ShaderLab: Pass
ShaderLab: Blending

ShaderLab culling and depth testing

Culling is an optimization that does not render polygons facing away from the viewer. All polygons have a front and a back side. Culling makes use of the fact that most objects are closed; if you have a cube, you will never see the sides facing away from you (there is always a side facing you in front of it) so Unity doesn’t need to draw the sides facing away. Hence the term: Backface culling.

The other feature that makes rendering looks correct is Depth testing. Depth testing makes sure that only the closest surface objects are drawn in a Scene.

Sintaxis

Cull

Cull Back | Front | Off

Controla qué lados de los polígonos deberían ser culled (no dibujados)

  • Back Don’t render polygons that are facing away from the viewer (default) i.e. back-facing polygons are culled.
  • Front Don’t render polygons that are facing towards the viewer. Used for turning objects inside-out.
  • Off Desactiva el culling - todas las caras son dibujadas. Utilizado para efectos especiales.

ZWrite

ZWrite On | Off

Controls whether pixels from this object are written to the depth buffer (default is On). If you’re drawing solid objects, leave this on. If you’re drawing semitransparent effects, switch to ZWrite Off. For more details read below.

ZTest

ZTest Less | Greater | LEqual | GEqual | Equal | NotEqual | Always

Cómo se debería realizar el depth testing. El predeterminado es LEqual (dibuja los objeto o en la distancia como objetos existentes; oculta los objetos detrás de ellos).

Offset

Offset Factor, Units

Le permite especificar un desplazamiento de profundidad con dos parámetros. factor y units. Factor escala la pendiente Z máxima, con respecto a X o Y del polígono, y units escala el valor del búfer de profundidad resoluble mínimo. Esto le permite forzar que un polígono se dibuje encima de otro, aunque en realidad estén en la misma posición. Por ejemplo, Offset 0, -1 acerca el polígono a la cámara ignorando la pendiente del polígono, mientras que ’Offset –1, –1` acercará aún más el polígono cuando se observa un ángulo de pastoreo.

Ejemplos

Este objeto solo va a renderizar las caras traseras de un objeto:

Shader "Show Insides" {
    SubShader {
        Pass {
            Material {
                Diffuse (1,1,1,1)
            }
            Lighting On
            Cull Front
        }
    }
}

Intente aplicarlo a un cubo, y mire cómo la geometría se siente todo mal cuando gira alrededor de este. Esto se debe a que usted solamente está viendo partes internas de su cubo.

Transparent shader con escrituras depth (profundas)

Usualmente los shaders semi-transparentes no escriben al depth buffer. Sin embargo, esto puede crear problemas de orden de dibujo, especialmente con meshes complejos no-convexos. Si usted quiere desvanecer de entrada y salida meshes así, entonces utilizar un shader que llene el depth buffer antes de renderizar transparencia podría ser útil.

Objeto semi-transparente; izquierda: Transparent/Diffuse shader; derecha: shader que escribe al depth buffer.
Objeto semi-transparente; izquierda: Transparent/Diffuse shader; derecha: shader que escribe al depth buffer.

Shader "Transparent/Diffuse ZWrite" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}
SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 200

    // extra pass that renders to depth buffer only
    Pass {
        ZWrite On
        ColorMask 0
    }

    // paste in forward rendering passes from Transparent/Diffuse
    UsePass "Transparent/Diffuse/FORWARD"
}
Fallback "Transparent/VertexLit"
}

Depurando normales

El siguiente es más interesante; primero renderizamos el objeto con una iluminación normal vertex, luego renderizamos las caras traseras con un brillo rosado. Esto tiene el efecto de resaltar dónde sea que sus normales necesiten ser volteadas. Si usted ve que los objetos que están controlados por físicas son ‘chupados’ por cualquier mesh, intente asignar este shader a ellos. Si cualquier parte rosada está visible, estas partes van a jalar cualquier cosa que tenga la desdicha de tocarla.

Aquí vamos:

Shader "Reveal Backfaces" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" { }
    }
    SubShader {
        // Render the front-facing parts of the object.
        // We use a simple white material, and apply the main texture.
        Pass {
            Material {
                Diffuse (1,1,1,1)
            }
            Lighting On
            SetTexture [_MainTex] {
                Combine Primary * Texture
            }
        }

        // Now we render the back-facing triangles in the most
        // irritating color in the world: BRIGHT PINK!
        Pass {
            Color (1,0,1,1)
            Cull Front
        }
    }
}

Glass (vidrio) Culling

Controlar Culling es útil para más que depurar caras traseras. Si usted tiene objetos transparentes, usualmente usted quiere mostrar el lado trasero de un objeto. Si usted renderiza sin ningún culling (Cull Off), es bastante probable que usted tenga algunas caras traseras sobre-poniéndose a las caras delanteras.

Aquí hay un shader simple que funcionará en los objetos convexos (esferas, cubos, parabrisas de coches).

Shader "Simple Glass" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,0)
        _SpecColor ("Spec Color", Color) = (1,1,1,1)
        _Emission ("Emmisive Color", Color) = (0,0,0,0)
        _Shininess ("Shininess", Range (0.01, 1)) = 0.7
        _MainTex ("Base (RGB)", 2D) = "white" { }
    }

    SubShader {
        // We use the material in many passes by defining them in the subshader.
        // Anything defined here becomes default values for all contained passes.
        Material {
            Diffuse [_Color]
            Ambient [_Color]
            Shininess [_Shininess]
            Specular [_SpecColor]
            Emission [_Emission]
        }
        Lighting On
        SeparateSpecular On

        // Set up alpha blending
        Blend SrcAlpha OneMinusSrcAlpha

        // Render the back facing parts of the object.
        // If the object is convex, these will always be further away
        // than the front-faces.
        Pass {
            Cull Front
            SetTexture [_MainTex] {
                Combine Primary * Texture
            }
        }
        // Render the parts of the object facing us.
        // If the object is convex, these will be closer than the
        // back-faces.
        Pass {
            Cull Back
            SetTexture [_MainTex] {
                Combine Primary * Texture
            }
        }
    }
}
ShaderLab: Pass
ShaderLab: Blending