Search Unity

Bug Where I did wrong with the stencil?

Discussion in 'Shaders' started by vladimir_shyshkin, Mar 4, 2021.

?

Where I did wrong with the stencil?

Poll closed Mar 11, 2021.
  1. shader

    1 vote(s)
    100.0%
  2. unity

    0 vote(s)
    0.0%
  1. vladimir_shyshkin

    vladimir_shyshkin

    Joined:
    Apr 21, 2020
    Posts:
    2
    Hi,

    I'm just trying to render some objects in each other using the stencil. Like here(This is the Edit View):

    upload_2021-3-4_16-49-50.png


    Here is the code of the shader:

    Shader "Unlit/NewUnlitShader"
    {
    Properties
    {
    _MainTex ("Texture", 2D) = "white" {}
    _Color ("Color", Color) = (1,1,1)
    }
    SubShader
    {
    Tags { "RenderType"="Opaque"}
    LOD 100

    Stencil
    {
    Ref 0
    Comp equal
    Pass IncrSat
    }

    Pass
    {
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    // make fog work
    #pragma multi_compile_fog

    #include "UnityCG.cginc"

    struct appdata
    {
    float4 vertex : POSITION;
    float2 uv : TEXCOORD0;
    };

    struct v2f
    {
    float2 uv : TEXCOORD0;
    UNITY_FOG_COORDS(1)
    float4 vertex_cl : COLOR_VERT;
    float4 vertex : SV_POSITION;
    };

    sampler2D _MainTex;
    float4 _MainTex_ST;
    float3 _Color;
    float4x4 _Size;

    v2f vert (appdata v)
    {
    v2f o;
    o.vertex_cl = v.vertex;
    o.vertex = mul(_Size, v.vertex);
    o.vertex = UnityObjectToClipPos(o.vertex) ;

    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
    }

    fixed4 frag (v2f i) : SV_Target
    {
    // sample the texture
    fixed4 col = i.vertex_cl;
    // apply fog
    UNITY_APPLY_FOG(i.fogCoord, col);
    return float4(col);
    }
    ENDCG
    }
    }
    }


    And the actual result in the scene(play mode):
    upload_2021-3-4_16-50-29.png


    Who can explain me where I did wrong.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    First, please use
    [code][/code]
    tags in the future.
    https://forum.unity.com/threads/using-code-tags-properly.143875/

    Second, stencil operations are highly dependent on the render order. You will need to ensure the cubes are rendering in the order necessary to achieve the look you want either by assigning a unique material per cube with different Queues, or with a c# script that sets the
    renderer.sortingOrder
    . The render order isn't exposed to the inspector or serialized (saved) in the scene for mesh renderer components, but is still respected by the rendering systems.
    https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html
     
    vladimir_shyshkin likes this.
  3. vladimir_shyshkin

    vladimir_shyshkin

    Joined:
    Apr 21, 2020
    Posts:
    2
    Thanks!