【風宇沖】Unity3D教程寶典之Shader篇:第十六講自訂光照模型

來源:互聯網
上載者:User
原創文章如需轉載請註明:轉載自風宇沖Unity3D教程學院

                            Shader第十六講 自訂光照模型


十四講我們實現了基本的Surface Shader,十五講講了光照模型的基礎知識。這一講說的是如何寫光照模型。自訂光照模型主要分為4步:(0)架設架構,填寫需要的參數(1)計算漫反射強度(2)計算鏡面反射強度(3)結合漫反射光與鏡面反射光
代碼配有中文注釋,配合上上講的光照公式,一步一步實現即可。
  1. //  Author: 風宇沖
  2. Shader "Custom/T_customLightModel" {
  3.   Properties
  4.   {
  5.     _MainTex ("Texture", 2D) = "white" {}
  6.   }
  7.  
  8.   Subshader
  9.   {
  10.      //alpha測試,配合surf中的o.Alpha = c.a;
  11.   AlphaTest Greater 0.4
  12.   CGPROGRAM
  13.   #pragma surface surf lsyLightModel 
  14.  
  15.   //命名規則:Lighting接#pragma suface之後起的名字
  16.   //lightDir :點到光源的單位向量   viewDir:點到攝像機的單位向量   atten:衰減係數
  17.   float4 LightinglsyLightModel(SurfaceOutput s, float3 lightDir,half3 viewDir, half atten)
  18.   {
  19.   float4 c;
  20.  
  21.   //(1)漫反射強度
  22.   float diffuseF = max(0,dot(s.Normal,lightDir));
  23.  
  24.   //(2)鏡面反射強度
  25.   float specF;
  26.   float3 H = normalize(lightDir+viewDir);
  27.   float specBase = max(0,dot(s.Normal,H));
  28.   // shininess 鏡面強度係數,這裡設定為8
  29.   specF = pow(specBase,8);
  30.  
  31.   //(3)結合漫反射光與鏡面反射光
  32.   c.rgb = s.Albedo * _LightColor0 * diffuseF *atten + _LightColor0*specF; 
  33.   c.a = s.Alpha;
  34.   return c;
  35.   }
  36.  
  37.   struct Input
  38.   {
  39.   float2 uv_MainTex;
  40.   };
  41.  
  42.   void vert(inout appdata_full v)
  43.   {
  44. //這裡可以做特殊位置上的處理
  45.   }
  46.   sampler2D _MainTex;
  47.  
  48.   void surf(Input IN,inout SurfaceOutput o)
  49.   {
  50.   half4 c = tex2D(_MainTex, IN.uv_MainTex);
  51.   o.Albedo = c.rgb;
  52.   o.Alpha = c.a;
  53.   }
  54.   ENDCG
  55.   }
  56. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.