Sitemap

Shield shader

7 min readFeb 3, 2018

--

Press enter or click to view image in full size

This was created following this video by Makin’ Stuff Look Good in Unity. This was an excellent tutorial, but I did have to take some extra time to really unwrap some of the parts he goes over very quickly. Essentially this shader is a combination of a few components:

  1. A sphere with UVs
  2. Use of a camera depth texture
  3. An intersection calculation between the sphere and the depth texture
  4. A hexagonal texture, which is applied with a sin wave and animated over time.
  5. A rim shader

My first issue was trying to get the depth texture to work. After plugging in the first blob of code, I wasn’t seeing any intersections. And since this is a shader, which are very challenging to debug (how I miss NSLog!), I resorted to some other ways to make sure my depth texture was coming through.

First I wrote this script and added it to the main camera

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class OnRenderMaterial : MonoBehaviour
{

public Material EffectMaterial;

private void OnEnable()
{
GetComponent<Camera>().depthTextureMode = DepthTextureMode.Depth;
}

private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Graphics.Blit(src, dest, EffectMaterial);
}

}

For the actual shader, the depth texture mode will be .DepthNormals, but I wanted to start with something simpler. If the camera is in deferred mode, this is something that is already being generated by the G-Buffer, thus this you get this for free. In forward rendering this will be generated if shadows are enabled, otherwise this will be an extra pass.

OnRenderImage() passes the current view through the given material (and its shader), and renders that instead of whatever the camera would have normally shown. This is the basis for image shader post-processing effects. MSLGWU has a great tutorial on this as well.

Now to actually try to render this depth texture to the screen.

Shader "Unlit/ShowDepth"
{
Properties {
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
Cull Off ZWrite Off ZTest Always

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};

sampler2D _CameraDepthTexture;
sampler2D _MainTex;
float4 _MainTex_ST;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);

return o;

}

fixed4 frag (v2f i) : SV_Target
{
float depth = 1 - Linear01Depth(tex2D(_CameraDepthTexture, i.uv));
return depth;
}
ENDCG
}
}
}

After much trial and even more error, I found a few “gotchas” with how this works.

  • As he points out in the tutorial, you must have a _MainTex property
Properties {
_MainTex ("Texture", 2D) = "white" {}
}

even though you aren’t going to use it. I believe this helps Unity assign the texture it generates to the shader, as I had a similar issue when trying to set a variable in a shader from a script. This must help define the public interface to the shader.

  • From the Unity documentation, Cull Off ZWrite Off ZTest Always is recommended for all image processing shaders.
  • Add sampler2D _CameraDepthTexture; as a declared property, next to the also required _sampler2D _MainTex; and _MainTex_ST;.

The frag shader is the only other tricky bit here. This line

1 - Linear01Depth(tex2D(_CameraDepthTexture, i.uv));

does a couple of things. First, it reads the _CameraDepthTexture like any other texture, and applies it to the uvs. Mind you, the uvs in this case are literally just one that goes across the whole screen. Secondly Linear01Depth is a UnityCG.cginc macro that normalizes the depth texture values going from the near to the far camera plane. Otherwise the values might not show up terribly well.

Get Aaron Hedquist’s stories in your inbox

Join Medium for free to get updates from this writer.

You should then end up with something like this on the right:

Press enter or click to view image in full size
Depth texture values rendered on the right

Next is to how use that in the shield shader to show white when the sphere intersects the boxes (or any other geometry).

First the vertex shader:

sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
sampler2D _CameraDepthNormalsTexture;
v2f vert (appdata v)
{

v2f o;
o.vertex = UnityObjectToClipPos (v.vertex);

o.screenuv = ((o.vertex.xy / o.vertex.w) + 1) / 2;
o.screenuv.y = 1 - o.screenuv.y;

o.depth = -mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.w;

return o;

}

The line o.screenuv = ((o.vertex.xy / o.vertex.w) + 1) / 2; computes the screen space UV position to sample the depth texture in the frag shader. The 1 — o.screenuv.y; is to flip the y depending on which graphics card you are using (this appears correct for DX).

o.depth = -mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.w;

This computes the depth of the vertex. Note that is isn’t using the typical UNITY_MATRIX_MVP matrix, as we don’t want it in clip space, just world space.

Frag shader:

fixed4 frag (v2f i) : SV_Target
{

float3 normalValues;
float screenDepth;

// unpack the depth from the depth texture
DecodeDepthNormal(tex2D(_CameraDepthNormalsTexture, i.screenuv), screenDepth, normalValues);

// find the distance between screen depth and fragment depth
float diff = screenDepth - i.depth;

float intersect = 0;

if (diff > 0) {
// _ProjectionParams.w = 1 / far plane
intersect = 1 - smoothstep(0, _ProjectionParams.w * 0.3, diff);
}

fixed4 sweetColor = fixed4(lerp(_Color.rgb, fixed3(1,1,1), pow(intersect, 2)), 1);

fixed4 col = sweetColor * _Color.a + intersect;
return col;

}

I altered the first line around getting the depth normal from the tutorial, as this looked like the preferred method to extract the depth from the docs and other examples, and I couldn’t quite rationalize the code from the tutorial.

To actually find the intersection, the delta is found by subtracting the screenDepth from the passed in fragment depth. This should look now look like:

Press enter or click to view image in full size

With that done, the rest of the tutorial focuses on the hex texture that animates down, and the rim shader. Of particular interest was the function he uses to make the hex texture appear in “stripes” as it animates down from the poles. Here’s the function:

float triWave(float t, float offset, float yOffset) {
return saturate(abs(frac(offset + t) * 2 - 1) + yOffset);
}

fixed4 texColor(v2f i, float rim) {
fixed4 mainTex = tex2D(_MainTex, i.uv);
mainTex.r *= triWave(_Time.x * 5, abs(i.objectPos.y) * 2, -0.7) * 6;
mainTex.g *= saturate(rim) * (sin(_Time.z + mainTex.b * 5) + 1);
return mainTex.r * _Color + mainTex.g * _Color;
}

Focusing on the triWave function, I wanted to break it down, so I put the formula into mathematical terms:

Press enter or click to view image in full size

You can see the formula and play with the values at this link to Desmos, an online graphing calculator. It really helps to understand why the magic numbers are what they are. He calls it “janky,” but looks legit to me! Using a linear function like this keeps the peaks angular, rather than the smooth slopes of a sine function, which is what he seemed to be after.

The final shader:

Shader "Unlit/ShieldShader2"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Color ("Color", Color) = (1,1,1,1)
_Edge ("Edge Intensity", Range(0.1,10)) = 2
}
SubShader
{
Tags {
"RenderType"="Transparent"
"Queue"="Transparent"
}
Blend One One
ZWrite Off
Cull Off

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;
float2 screenuv : TEXCOORD1;
float3 objectPos : TEXCOORD2;
float4 vertex : SV_POSITION;
float depth : DEPTH;
float3 normal : NORMAL;
float3 viewDir : TEXCOORD3;
};

sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
sampler2D _CameraDepthNormalsTexture;
float _Edge;

v2f vert (appdata v)
{

v2f o;
o.vertex = UnityObjectToClipPos (v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);

o.screenuv = ((o.vertex.xy / o.vertex.w) + 1) / 2;
o.screenuv.y = 1 - o.screenuv.y;
o.depth = -mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.w;

o.normal = UnityObjectToWorldNormal(v.normal);
o.viewDir = normalize(UnityWorldSpaceViewDir(mul(unity_ObjectToWorld, v.vertex)));
o.objectPos = v.vertex.xyz;

return o;

}

// https://www.desmos.com/calculator/xfmf9o043x
float triWave(float t, float offset, float yOffset) {
return saturate(abs(frac(offset + t) * 2 - 1) + yOffset);
}

fixed4 texColor(v2f i, float rim) {
fixed4 mainTex = tex2D(_MainTex, i.uv);
mainTex.r *= triWave(_Time.x * 5, abs(i.objectPos.y) * 2, -0.7) * 6;
mainTex.g *= saturate(rim) * (sin(_Time.z + mainTex.b * 5) + 1);
return mainTex.r * _Color + mainTex.g * _Color;
}

fixed4 frag (v2f i) : SV_Target
{

float3 normalValues;
float screenDepth;

// unpack the depth from the depth texture
DecodeDepthNormal(tex2D(_CameraDepthNormalsTexture, i.screenuv), screenDepth, normalValues);

// find the distance between screen depth and fragment depth
float diff = screenDepth - i.depth;

float intersect = 0;

if (diff > 0) {
// _ProjectionParams.w = 1 / far plane
intersect = 1 - smoothstep(0, _ProjectionParams.w * 0.3, diff);
}

float rim = 1 - abs(dot(i.normal, normalize(i.viewDir))) * 2;
float northPole = (i.objectPos.y - 0.45) * 20;
float glow = max(max(intersect, rim), northPole);

fixed4 sweetColor = fixed4(lerp(_Color.rgb, fixed3(1,1,1), pow(glow, _Edge)), 1);

fixed4 hexes = texColor(i, rim);

fixed4 col = _Color * _Color.a + sweetColor * glow + hexes;
return col;

}
ENDCG
}
}
}

--

--