Unity Shader学习:球谐光照
烘培/采样 与 还原
shader部分:
Shader "Unlit/SHTest"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {
}
}
SubShader
{
Tags {
"RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal:NORMAL;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float3 worldNormal:TEXCOORD1;
};
#define PI 3.14159265358
#define Y0(v) (1.0 / 2.0) * sqrt(1.0 / PI)
#define Y1(v) sqrt(3.0 / (4.0 * PI)) * v.y
#define Y2(v) sqrt(3.0 / (4.0 * PI)) * v.z
#define Y3(v) sqrt(3.0 / (4.0 * PI)) * v.x
#define Y4(v) 1.0 / 2.0 * sqrt(15.0 / PI) * v.x * v.y
#define Y5(v) 1.0 / 2.0 * sqrt(15.0 / PI) * v.z * v.y
#define Y6(v) 1.0 / 4.0 * sqrt(5.0 / PI) * (-1 + 3 * v.z * v.z)
#define Y7(v) 1.0 / 2.0 * sqrt(15.0 / PI) * v.z * v.x
#define Y8(v) 1.0 / 4.0 * sqrt(15.0 / PI) * (v.x * v.x - v.y * v.y)
StructuredBuffer<float4> SH9Data;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.worldNormal = UnityObjectToWorldNormal(v.normal);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float4 c0 = SH9Data[0];
float4 c1 = SH9Data[1];
float4 c2 = SH9Data[2];
float4 c3 = SH9Data[3];
float4 c4 = SH9Data[4];
float4 c5 = SH9Data[5];
float4 c6 = SH9Data[6];
float4 c7 = SH9Data[7];
float4 c8 = SH9Data[8];
float3 v = normalize(i.worldNormal.xyz);
float4 sh9 = c0 * Y0(v) + c1 * Y1(v) + c2 <