一、思维导图
二、ShaderForge节点
1)光源:
2)环境:
3)光源+环境:(总)
三、脚本实现
//OldSchoolPlus
Shader "Shader/U3D_006" {
Properties {
_BaseCol("基础色",COLOR)=(1.0,1.0,1.0,1.0)
_LightCol("灯光色",COLOR)=(1.0,1.0,1.0,1.0)
_Occlusion("AO图",2D)="while"{}
_SpecularPow("高光次幂",Range(1,90))=30
_EnvInt("环境光影响度",Range(0,1))=0.2
_EnvUpCol("环境天顶颜色",COLOR)=(1.0,1.0,1.0,1.0)
_EnvSideCol("环境水平颜色",COLOR)=(.5,.5,.5,1.0)
_EnvDownCol("环境地表颜色",COLOR)=(0.0,0.0,0.0,1.0)
}
SubShader {
Tags {
"RenderType"="Opaque"
}
Pass {
Name "FORWARD"
Tags {
"LightMode"="ForwardBase"
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
//投影相关文件
#include "AutoLight.cginc"
#include "Lighting.cginc"
#pragma multi_compile_fwdbase_fullshadows
#pragma target 3.0
uniform float3 _BaseCol;
uniform float3 _LightCol;
uniform sampler2D _Occlusion;
uniform float _SpecularPow;
uniform float _EnvInt;
uniform float3 _EnvUpCol;
uniform float3 _EnvSideCol;
uniform float3 _EnvDownCol;
//输入结构
struct VertexInput {
float4 vertex : POSITION; //顶点信息 Get✔
float3 normal : NORMAL; //法线信息 Get✔
float2 uv0:TEXCOORD0;
};
//输出结构
struct VertexOutput {
float4 pos : SV_POSITION; //顶点屏幕位置
float4 posWS:TEXCOORD0;
float3 nDirWS:TEXCOORD1; //世界空间法线信息
float2 uv:TEXCOORD2;
LIGHTING_COORDS(3,4)
};
//输入结构>>>顶点Shader>>>输出结构
VertexOutput vert (VertexInput v) {
VertexOutput o = (VertexOutput)0; //新建输出结构
o.pos = UnityObjectToClipPos( v.vertex ); //变换顶点信息
o.posWS=mul(unity_ObjectToWorld, v.vertex);
o.nDirWS=UnityObjectToWorldNormal(v.normal); //变换法线信息
o.uv=v.uv0; //传递uv数据
TRANSFER_VERTEX_TO_FRAGMENT(o);
return o; //输出结构
}
//输出结构>>像素Shader
float4 frag(VertexOutput i) : COLOR {
//准备向量
float3 nDir=i.nDirWS;
float3 lDir=normalize(_WorldSpaceLightPos0.xyz);
float3 rDir=reflect(-lDir,nDir);
float3 vDir=normalize(_WorldSpaceCameraPos.xyz-i.posWS.xyz);
float upMask=max(0.0,nDir.g);
float downMask=max(0.0,-nDir.g);
float sideMask=1.0-upMask-downMask;
//准备点积结果
float nDotl=dot(nDir,lDir);
float rDotv=dot(rDir,vDir);
//光照模型
float shadow=LIGHT_ATTENUATION(i);
float Lambert= max(0.0,nDotl);
float Phong=pow(max(0.0,rDotv),_SpecularPow);
float3 dirLighting=(_BaseCol*Lambert+Phong)*_LightCol*shadow;
//混合环境色
float3 envCol=(_EnvUpCol*upMask+_EnvSideCol*sideMask+_EnvDownCol*downMask)*Lambert*_EnvInt;
//采样AO图
float occlusion=tex2D(_Occlusion,i.uv);
//计算环境光照
float3 envLighting=envCol*occlusion*_BaseCol;
//返回结果
float3 finalRGB=dirLighting+envLighting;
return float4(finalRGB,1.0); //输出其最终颜色
}
ENDCG
}
}
FallBack "Diffuse"
CustomEditor "ShaderForgeMaterialInspector"
}