Skip to content

Instantly share code, notes, and snippets.

@rstecca
Last active June 6, 2023 16:55
Show Gist options
  • Save rstecca/4e933d4dc4b9007adbe1f7344b4c3f68 to your computer and use it in GitHub Desktop.
Save rstecca/4e933d4dc4b9007adbe1f7344b4c3f68 to your computer and use it in GitHub Desktop.
Minimal example of a Surface Shader using a Grab Pass
Shader "Custom/MinimalSurfaceWithGrabPass"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
_SeeThrough ("See Through (not a transparency)", Range(0,1)) = 0.5
}
SubShader
{
// In tags we use Transparent+1 to get everything behind
Tags { "Queue"="Transparent+1" "RenderType"="Opaque" }
LOD 200
GrabPass { "_GrabTex" }
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows vertex:vert
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.5
// This is similar to appdata_full but we keep it here to have more control
struct appdata {
float4 vertex : POSITION;
float4 tangent : TANGENT;
float3 normal : NORMAL;
float4 texcoord : TEXCOORD0;
float4 texcoord1 : TEXCOORD1;
float4 texcoord2 : TEXCOORD2;
//float4 texcoord3 : TEXCOORD3;
fixed4 color : COLOR;
};
struct Input
{
float2 uv_MainTex : TEXCOORD0;
float4 GrabTexUV : TEXCOORD1; // the uv slot for the grab texture. Note that we don't use uv_GrabTex because...
//.. Unity would take the "uv_" as something known and tries to initialize it in a way that gives error
// so we want our own variable name here.
};
sampler2D _GrabTex;
sampler2D _MainTex;
half _Glossiness;
half _Metallic;
float _SeeThrough;
fixed4 _Color;
void vert(inout appdata v, out Input o) {
//v.vertex.xyz = ... // do things to vertices
o.uv_MainTex = v.texcoord;
float4 hpos = UnityObjectToClipPos (v.vertex);
o.GrabTexUV = ComputeGrabScreenPos(hpos); // compute the uvs for the grab texture (using Unity's utilities)
}
void surf (Input IN, inout SurfaceOutputStandard o)
{
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
// and here's how we USE the grab texture
o.Albedo = (1.0 - _SeeThrough) * c + (_SeeThrough) * tex2Dproj( _GrabTex, UNITY_PROJ_COORD(IN.GrabTexUV));
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment