Version: Unity 6.0 (6000.0)
语言 : 中文
为粒子系统 (Particle System) 应用 GPU 实例化
自定义着色器中的粒子系统 GPU 实例化示例

表面着色器中的粒子系统 GPU 实例化示例

以下是使用粒子系统 GPU 实例化的表面着色器的完整运行示例:


Shader "Instanced/ParticleMeshesSurface" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        // And generate the shadow pass with instancing support
        #pragma surface surf Standard nolightmap nometa noforwardadd keepalpha fullforwardshadows addshadow vertex:vert
        // Enable instancing for this shader
        #pragma multi_compile_instancing
        #pragma instancing_options procedural:vertInstancingSetup
        #pragma exclude_renderers gles
        #include "UnityStandardParticleInstancing.cginc"
        sampler2D _MainTex;
        struct Input {
            float2 uv_MainTex;
            fixed4 vertexColor;
        };
        fixed4 _Color;
        half _Glossiness;
        half _Metallic;
        void vert (inout appdata_full v, out Input o)
        {
            UNITY_INITIALIZE_OUTPUT(Input, o);
            vertInstancingColor(o.vertexColor);
            vertInstancingUVs(v.texcoord, o.uv_MainTex);
        }

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * IN.vertexColor * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

上面的示例与常规表面着色器之间存在许多微小差异,正是这些不同之处使得表面着色器可以使用粒子实例化。

首先,必须添加以下两行以启用程序实例化 (Procedural Instancing),并指定内置顶点设置函数。此函数位于 UnityStandardParticleInstancing.cginc 中,用于加载每个实例(每个粒子)的位置数据:

        #pragma instancing_options procedural:vertInstancingSetup
        #include "UnityStandardParticleInstancing.cginc"

此示例中的其他修改是对顶点函数的修改,此函数增加了两行来应用每个实例的属性,具体而言就是粒子颜色和纹理帧动画纹理坐标:

            vertInstancingColor(o.vertexColor);
            vertInstancingUVs(v.texcoord, o.uv_MainTex);
为粒子系统 (Particle System) 应用 GPU 实例化
自定义着色器中的粒子系统 GPU 实例化示例