Search Unity

Modifying shader to work with terrain instancing?

Discussion in 'Shaders' started by GoldFireStudios, Jul 1, 2020.

  1. GoldFireStudios

    GoldFireStudios

    Joined:
    Nov 21, 2018
    Posts:
    160
    I'm trying to get a snow shader that is working perfectly on individual objects to also work on the terrain with instancing enabled. It renders correctly on the terrain without instancing, but as soon as "draw instanced" is checked, the terrain either vanishes or starts glitching everywhere. The shader has GPU instancing enabled, and I tried to base it on the built-in terrain shader, which does work, but with no luck so far.

    The Included UnityPBSLighting.cginc is modified to include our snow shader functions and defines `SNOW_COMPUTE_OUTPUT_STANDARD`. The main difference compared to the built-in terrain shader is I removed the splatmap portions since I'm not using any textures on the terrain, but maybe that still needs to be in there?

    Code (CSharp):
    1. Shader "Snow/FullCoverage" {
    2.   Properties {
    3.     _Color ("Color", Color) = (1,1,1,1)
    4.     _MainTex ("Albedo (RGB)", 2D) = "white" {}
    5.     _Glossiness ("Smoothness", Range(0,1)) = 0.5
    6.     _Metallic ("Metallic", Range(0,1)) = 0.0
    7.     _SnowBlendAmount ("Blend Amount", Range(0,1)) = 1
    8.   }
    9.  
    10.   SubShader {
    11.     Tags { "RenderType"="Opaque" }
    12.     LOD 200
    13.  
    14.     CGPROGRAM
    15.     #pragma surface surf Standard addshadow fullforwardshadows
    16.     #pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap forwardadd
    17.     #pragma multi_compile_fog
    18.     #pragma target 3.0
    19.     #pragma exclude_renderers gles
    20.     #include "UnityPBSLighting.cginc"
    21.  
    22.     sampler2D _MainTex;
    23.  
    24.     struct Input {
    25.       float2 uv_MainTex;
    26.       float3 worldPos;
    27.       float3 worldNormal;
    28.     };
    29.  
    30.     half _Glossiness;
    31.     half _Metallic;
    32.     fixed4 _Color;
    33.  
    34.     UNITY_INSTANCING_BUFFER_START(Props)
    35.     UNITY_INSTANCING_BUFFER_END(Props)
    36.  
    37.     void surf (Input IN, inout SurfaceOutputStandard o) {
    38.       fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
    39.       o.Albedo = c.rgb;
    40.       o.Metallic = _Metallic;
    41.       o.Smoothness = _Glossiness;
    42.       o.Alpha = c.a;
    43.  
    44.       SNOW_COMPUTE_OUTPUT_STANDARD(IN.worldPos, IN.worldNormal);
    45.     }
    46.     ENDCG
    47.   }
    48.  
    49.   FallBack "Diffuse"
    50. }