unity-game-enginerenderingshadermeshurp

Custom Shader with URP


I am using a custom shader for a mesh, which is basically a "sight-blocker" to other meshes. You cannot see the mesh itself and every other mesh behind it is occluded by it. Proper occlusion example

Now I upgraded the project to the Universal Render Pipeline according to Unitys documentation: https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.1/manual/InstallURPIntoAProject.html

Unfortunatly, the shader appears to be incompatible with the URP, causing the "sight-blocker" to show the pixels of the mesh behind it but moves then aswell when rotating/moving the viewport: Strange Occlusion example

Since I dont have any experience with shaders, could you please support me converting the shader to work with URP (or maybe its a problem to configuration of the URP itself?).

Shader "Custom/InvisibleStencilShader"
{
    SubShader
    {
        // Make sure this shader is rendered before others
        Tags { "Queue" = "Geometry-1" }

        // This pass will write to the stencil buffer
        Pass
        {
            // Disable color buffer writes
            ColorMask 0
            // Write a value of 1 to the stencil buffer
            Stencil
            {
                Ref 1
                Comp Always
                Pass Replace
            }
        }
    }
}

Thanks in advance


Solution

  • I figured it out and wanted to let you know how I solved it in the end.

    Basically i found a reference tutorial on urp's stencil buffer here: https://bdts.com.au/tips-and-resources/unity-create-windows-portals-using-stencils-with-the-universal-render-pipeline-urp.html

    The following steps achieve the desired effect:

    1. Put every Mesh that should be occluded on a new layer called "HiddenObjects".

    2. Put the mask Mesh (that occludes the other meshes) on a new layer called "Mask".

    3. Exclude the new created layers from the Rendering on the URP Asset: Exclude new masks from URP Asset

    4. Add new Renderer Feature called "HiddenObjects" and "Mask" to the URP Asset with following settings: New Renderer Features with their settings

    5. Last but not least, add the following shader to the Mask GameObject with a new Material (to hide the mask-mesh):

    .

    Shader "Custom/StencilMask"
    {
        SubShader
        {
            Pass
            {
                ZWrite Off
            }
        }
    }
    

    There is one little tradeoff with this solution, but it works for me as good as before: Only Plane Meshes are occluding properly, solid meshes somehow don't work. The final result looks like this now: final result