本文主要是介绍Unity3D 点光源使用衰减公式Shader,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Unity在内部使用一张名为_LightTexture0的纹理来计算光源衰减。第一次看到比较懵逼,本着学习的态度,就自己实现一个衰减公式。衰减公式参考龙书:
shader:
Shader "NinCoolShader/MyForwardRendering2"
{Properties{_Diffuse("Diffuse", Color) = (1, 1, 1, 1)_Specular("Specular", Color) = (1, 1, 1, 1)_Gloss("Gloss", Range(8.0, 256)) = 20_fAttenuation0("Attenuation0", Range(0.01, 1.0)) = 0.01_fAttenuation1("Attenuation1", Range(0.01, 1.0)) = 0.01_fAttenuation2("Attenuation2", Range(0.01, 1.0)) = 0.01}SubShader{Tags { "RenderType"="Opaque" }Pass{CGPROGRAM#pragma multi_compile_fwdbase#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"struct a2v{float4 vertex : POSITION;float3 normal : NORMAL;};struct v2f{float4 pos : SV_POSITION;float3 worldNormal : TEXCOORD0;float3 worldPos : TEXCOORD1;};v2f vert (a2v v){v2f o;o.pos = mul(UNITY_MATRIX_MVP, v.vertex);o.worldNormal = UnityObjectToWorldNormal(v.normal);o.worldPos = mul(_Object2World, v.vertex).xyz;return o;}fixed4 frag (v2f i) : SV_Target{fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;fixed atten = 1.0;return fixed4(ambient * atten, 1.0);}ENDCG}Pass{Tags{"LightMode" = "ForwardAdd"}Blend One OneCGPROGRAM#pragma multi_compile_fwdadd#pragma vertex vert#pragma fragment frag#include "Lighting.cginc"#include "AutoLight.cginc"fixed4 _Diffuse;fixed4 _Specular;float _Gloss;float _fAttenuation0;float _fAttenuation1;float _fAttenuation2;struct a2v{float4 vertex : POSITION;float3 normal : NORMAL;};struct v2f {float4 pos : SV_POSITION;float3 worldNormal : TEXCOORD0;float3 worldPos : TEXCOORD1;};v2f vert(a2v v) {v2f o;o.pos = mul(UNITY_MATRIX_MVP, v.vertex);o.worldNormal = UnityObjectToWorldNormal(v.normal);o.worldPos = mul(_Object2World, v.vertex).xyz;return o;}fixed4 frag(v2f i) : SV_Target{fixed3 worldNormal = normalize(i.worldNormal);fixed3 dirVertex2Light = _WorldSpaceLightPos0.xyz - i.worldPos.xyz;float fDistance = length(dirVertex2Light);fixed atten = 1.0 / (_fAttenuation0 + _fAttenuation1 * fDistance + pow(_fAttenuation2, 2) * fDistance);fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz - i.worldPos.xyz);fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * max(0, dot(worldNormal, worldLightDir));fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);fixed3 halfDir = normalize(worldLightDir + viewDir);fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss);return fixed4((diffuse + specular) * atten, 1.0);}ENDCG}}
}
这里并不讨论ForwardBase和ForwardAdd的区别以及内置的变量,如果想要了解的可以参考官方文档。
这篇关于Unity3D 点光源使用衰减公式Shader的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!