使用#define指令模块化地创建着色器

作者:追风剑情 发布于:2016-3-6 13:38 分类:Shader

一、创建MyCgInclude.cginc文件

#ifndef MY_CG_INCLUDE
#define MY_CG_INCLUDE

fixed4 _MyColor;

//半兰伯特光照模型
inline fixed4 LightingHalfLambert (SurfaceOutput s, fixed3 lightDir, fixed atten)
{
	fixed diff = max (0, dot(s.Normal, lightDir));
	//如果定义了HalfLambert宏,则采用半兰伯特光照模型,否则采用普通的NdotL漫反射模型。
	#ifdef HalfLambert
	diff = (diff + 0.5)*0.5;
	#endif
	
	fixed4 c;
	c.rgb = s.Albedo*_LightColor0.rgb*((diff*_MyColor.rgb)*atten*2);
	c.a = s.Alpha;
	return c;
}

#endif

二、创建着色器

Shader "Custom/HalfLambertShader" {
	Properties {
		_MainTex ("Base (RGB)", 2D) = "white" {}
		_DesatValue ("Desaturate", Range(0, 1)) = 0.5
		_MyColor ("My Color", Color) = (1,1,1,1)
	}
	SubShader {
		Tags { "RenderType"="Opaque" }
		LOD 200
		
		CGPROGRAM
		//定义HalfLambert宏,以便启用半兰伯特光照模型。
		#define HalfLambert
		#include "MyCgInclude.cginc"
		#pragma surface surf HalfLambert

		sampler2D _MainTex;

		struct Input {
			float2 uv_MainTex;
		};

		void surf (Input IN, inout SurfaceOutput o) {
			half4 c = tex2D (_MainTex, IN.uv_MainTex);
			o.Albedo = c.rgb;
			o.Alpha = c.a;
		}
		ENDCG
	} 
	FallBack "Diffuse"
}

使用半兰伯特光照模型的效果

b111.png

使用NdotL漫反射模型效果

n1111.png

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号