Skip to content

Instantly share code, notes, and snippets.

@fanhexin
Last active August 30, 2024 08:42
Show Gist options
  • Save fanhexin/5d6728b85204b60fede9ee83c2e0050a to your computer and use it in GitHub Desktop.
Save fanhexin/5d6728b85204b60fede9ee83c2e0050a to your computer and use it in GitHub Desktop.
Planar shadow shader for unity buildin render pipline.
Shader "Custom/PlanarShadow"
{
Properties {
_ShadowColor ("Shadow Color", Color) = (0,0,0,1)
_PlaneHeight ("planeHeight", Float) = 0
}
SubShader {
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
Pass {
ZWrite On
ZTest LEqual
Blend SrcAlpha OneMinusSrcAlpha
Stencil {
Ref 0
Comp Equal
Pass IncrWrap
ZFail Keep
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_instancing
#include "UnityCG.cginc"
struct vsOut
{
float4 pos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
UNITY_INSTANCING_BUFFER_START(Props)
UNITY_DEFINE_INSTANCED_PROP(float4, _ShadowColor)
UNITY_DEFINE_INSTANCED_PROP(float, _PlaneHeight)
UNITY_INSTANCING_BUFFER_END(Props)
vsOut vert( appdata_base v)
{
vsOut o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
float4 vPosWorld = mul( unity_ObjectToWorld, v.vertex);
float4 lightDirection = -normalize(_WorldSpaceLightPos0);
float planeHeight = UNITY_ACCESS_INSTANCED_PROP(Props, _PlaneHeight);
float opposite = vPosWorld.y - planeHeight;
float cosTheta = -lightDirection.y; // = lightDirection dot (0,-1,0)
float hypotenuse = opposite / cosTheta;
float3 vPos = vPosWorld.xyz + ( lightDirection * hypotenuse );
o.pos = mul (UNITY_MATRIX_VP, float4(vPos.x, planeHeight, vPos.z ,1));
return o;
}
fixed4 frag( vsOut i) : COLOR
{
UNITY_SETUP_INSTANCE_ID(i);
return UNITY_ACCESS_INSTANCED_PROP(Props, _ShadowColor);
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment