unityshader之surfaceshader
阿新 • • 發佈:2019-02-15
這節課主要講述了關於surface shader的知識,surface shader是對vertex shader 和 fragment shader的更高一層的包裝,不需要我們再去編寫pass通道了,這裡講學習筆記貼出來,有不對的地方歡迎指正,程式碼是unity自帶的surface shader的範本;
Shader "Custom/sf" {
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 {
//surface shader 中不需要編寫pass通道,是對vertex shader和fragment shader的一種包裝
Tags { "RenderType"="Opaque" } //tags 渲染型別的描述,opaque表示不透明
LOD 200 //層級細節,後續再講
CGPROGRAM //代表使用CG語言編寫shader直到ENDCG結束
// Physically based Standard lighting model, and enable shadows on all light types
//#pragma表示一個編譯指令 ;surface表示該shader型別是surface shader ;
// surf表示一個函式名稱,在下面的程式碼中編寫這個函式;Standard 表示一種光照模型(函式),unity內有lightingStandard這個函式(5.0以前版本是lambert)
//fullforwardshadows是一種陰影型別,該型別支援所有的陰影型別在forward渲染路徑下,shder陰影型別
//還有addshadow和tessellate型別
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
//這個指令代表使用3.0的光照,預設是2.0,越高光照效果越好
#pragma target 3.0
sampler2D _MainTex; //紋理單位sampler2D
//輸入結構體,描述uv紋理座標 ,注意這個uv紋理變數必須是小寫uv + sampler2D的變數名,uv不能少,unityshader官方如此表述
struct Input {
float2 uv_MainTex;
};
half _Glossiness; //對應於properties中的屬性在函式體內的宣告,注意變數型別關鍵字不一樣了
half _Metallic; //2d--sampler2D; color--fixed4; Range--half
fixed4 _Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_CBUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_CBUFFER_END
//inout該函式表示即時輸入也是輸出
void surf (Input IN, inout SurfaceOutputStandard o) { //surf函式兩個引數,一個Input,SurfaceOutputStandard表示5.0以後版本中基於物理的光照模型的結構體
//之前是SurfaceOutput結構體(固定名稱)
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;//tex2D是CG中的一個函式,主要用來使用紋理座標從紋理中得到資料,
//然後賦值給SurfaceOutputStandard中的Albedo,Metallic,Smoothness,Alpha
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse" //上面的shader都不管用時,就預設使用diffuse shader渲染物體,扮演備胎的角色
}
然後在貼一張SurfaceOutputStandard的官方API截圖和5.0以後alpha設定的截圖;