Toon Liquid Shader - Unity Shader

August 23, 2018
10m
Unity 3DTech ArtShaders

This is how the shader will end up looking:

Shader along with simple liquid wobble physics
Liquid shader preview

This shader is pretty neat and somewhat easy to implement as well as to understand. Since we will be adding some basic physics to the toon water as it is moved about we will have to support that in the vertex shader as well.

So let's start by looking at the properties:


Properties
{
 _Colour ("Colour", Color) = (1,1,1,1)
 _FillAmount ("Fill Amount", Range(-10,10)) = 0.0
 [HideInInspector] _WobbleX ("WobbleX", Range(-1,1)) = 0.0
 [HideInInspector] _WobbleZ ("WobbleZ", Range(-1,1)) = 0.0
 _TopColor ("Top Color", Color) = (1,1,1,1)
 _FoamColor ("Foam Line Color", Color) = (1,1,1,1)
 _Rim ("Foam Line Width", Range(0,0.1)) = 0.0
 _RimColor ("Rim Color", Color) = (1,1,1,1)
 _RimPower ("Rim Power", Range(0,10)) = 0.0
}

Just the usual stuff that we are used to. The only thing that may stand out is the [HideInInspector] tag, This works just like the HideInInspector attribute we have while writing C# code. This tag prevents this property from being displayed in the editor while viewing the material. However we can still access this property from our C# code during run time.
Now we will go through how they were declared in CG PROGRAM.


/*1*/float _FillAmount;
/*2*/float _WobbleX;
/*3*/float _WobbleZ;
/*4*/float4 _TopColor;
/*5*/float4 _RimColor;
/*6*/float4 _FoamColor;
/*7*/float4 _Colour;
/*8*/float _Rim;
/*9*/float _RimPower;
  1. _FillAmount is the height of the liquid, Larger the value the more it's filled.
  2. _WobbleX when we have rudimentary physics for the liquid to move about this affects x-axis motion.
  3. _WobbleZ when we have rudimentary physics for the liquid to move about this affects z-axis motion.
  4. _TopColor refers to the top part of the foam's color.
  5. _RimColor refers to the rim lighting color.
  6. _FoamColor is the foam's color.
  7. _Colour is the actual liquid's color.
  8. _Rim is the amount of rim lighting used.
  9. _RimPower is the sharpness of the rim lighting.

We have to set up some conditions for our pass:


Pass
{
 Zwrite On
 Cull Off // we want the front and back faces
 AlphaToMask On // transparency
 CGPROGRAM
 #pragma vertex vert
 #pragma fragment frag
 .
 .
 .
}

If you have been following the blog for a while now you should know what Zwrite OnCull Off do.
Here we are not performing culling as the front face acts as the actual container and the back face which is a simple color acts as the top of the liquid thereby making it look solid even though it's not.

But AlphaToMask On might be new to you. AlphaMask will add wherever the geometry of the object ends up to a mask which won't allow geometry of the same material to come through as along as the alpha value at that point is less than what is already in the mask. (At least from what I understood. 😅)
Let's get started with the vertex shader:

C#

float4 RotateAroundYInDegrees (float4 vertex, float degrees)
{
 float alpha = degrees * UNITY_PI / 180;
 float sina, cosa;
 sincos(alpha, sina, cosa);
 float2x2 m = float2x2(cosa, sina, -sina, cosa);
 return float4(vertex.yz , mul(m, vertex.xz)).xzyw ;
}

v2f vert (appdata v)
{
 v2f o;
 o.vertex = UnityObjectToClipPos(v.vertex);
 float3 worldPos = mul (unity_ObjectToWorld, v.vertex.xyz);
 // rotate it around XY
 float3 worldPosX= RotateAroundYInDegrees(float4(worldPos,0),360);
 // rotate around XZ
 float3 worldPosZ = float3 (worldPosX.y, worldPosX.z, worldPosX.x);
 // combine rotations with worldPos, based on sine wave from script
 float3 worldPosAdjusted = worldPos + (worldPosX  * _WobbleX)+ (worldPosZ* _WobbleZ); 
 // how high up the liquid is
 o.fillEdge =  worldPosAdjusted.y + _FillAmount;
 o.viewDir = normalize(ObjSpaceViewDir(v.vertex));
 o.normal = v.normal;
 return o;
}

Most of it is explained by the comments themselves but if the wobble thing seems confusing remember that it is just lifting side upwards or downwards depending on the position of the vertex and the wobble values given to the shader for each axis. 

Remember no vertices are moved around in this shader only the value for how much the liquid is supposed to rise up is passed to the fragment shader.

Fragment shader:


fixed4 frag (v2f i, fixed facing : VFACE) : SV_Target
{
   // rim light
   float dotProduct = 1 - pow(dot(i.normal, i.viewDir), _RimPower);
   float4 RimResult = smoothstep(0.5, 1.0, dotProduct);
   RimResult *= _RimColor;
   // foam edge
   /* 1 */ float4 foam = ( step(i.fillEdge, 0.5) - step(i.fillEdge, (0.5 - _Rim)));
   float4 foamColored = foam * (_FoamColor * 0.75);
   // rest of the liquid
   float4 result = step(i.fillEdge, 0.5) - foam;
   float4 resultColored = result * _Colour;
   // both together
   float4 finalResult = resultColored + foamColored;
   finalResult.rgb += RimResult;
   // color of backfaces/ top
   float4 topColor = _TopColor * (foam + result);
   //VFACE returns positive for front facing, negative for backfacing
   /* 2 */return facing > 0 ? finalResult : topColor;
}

Here again most of it is explained through comments but we will go over the unusual bits.
Let's break it down:

  1. The step function will return 0.0 unless the value is over 0.5 otherwise it will return 1.0.
    So when we make the foam edge we take a small part near the top so for that purpose we use the step function.
  2. You may have noticed that this fragment function has an extra parameter called VFACE and this gives us information about which face it is. Is the the back face or front face?
    If it is front face it gives us positive values ( > 0) or if it is back face it gives negative values ( < 0). Depending on the type of face we color it differently.

Let's move on to making the C# file that goes along with this.

C#

1using UnityEngine;
2public class Wobble : MonoBehaviour
3{
4    public float MaxWobble = 0.03f;
5    public float WobbleSpeed = 5.0f;
6    public float RecoveryRate = 1f;
7
8    Renderer rend;
9    Vector3 prevPos;
10    Vector3 prevRot;
11    float wobbleAmountToAddX;
12    float wobbleAmountToAddZ;
13
14    void Start()
15    {
16        rend = GetComponent<Renderer>();
17    }
18
19    private void Update()
20    {
21        // 1. decreases the wobble over time
22        wobbleAmountToAddX = Mathf.Lerp(wobbleAmountToAddX, 0, Time.deltaTime * RecoveryRate);
23        wobbleAmountToAddZ = Mathf.Lerp(wobbleAmountToAddZ, 0, Time.deltaTime * RecoveryRate);
24
25        // 2.make a sine wave of the decreasing wobble
26        float wobbleAmountX = wobbleAmountToAddX * Mathf.Sin(WobbleSpeed * Time.time);
27        float wobbleAmountZ = wobbleAmountToAddZ * Mathf.Sin(WobbleSpeed * Time.time);
28
29        // 3.send it to the shader
30        rend.material.SetFloat("_WobbleX", wobbleAmountX);
31        rend.material.SetFloat("_WobbleZ", wobbleAmountZ);
32
33        // 4.Move Speed
34        Vector3 moveSpeed = (prevPos - transform.position) / Time.deltaTime;
35        Vector3 rotationDelta = transform.rotation.eulerAngles - prevRot;
36
37        // 5.add clamped speed to wobble
38        wobbleAmountToAddX += Mathf.Clamp((moveSpeed.x + (rotationDelta.z * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
39        wobbleAmountToAddZ += Mathf.Clamp((moveSpeed.z + (rotationDelta.x * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
40
41        // 6.save the last position
42        prevPos = transform.position;
43        prevRot = transform.rotation.eulerAngles;
44    }
45}

This adds a wobble to the liquid making it look like it's being affected by the motion of the object.

  1. Here whatever the value of wobbleAmountToAddX/Y will tend to go back to 0 with time. The larger the RecoveryRate the faster the liquid will settle.
  2. Now a sin function will take the place of a simple liquid wobbling approximation. This sin function will keep returning values between -1.0 to +1.0. The effect of the sin function is only noticeable if the wobbleAmountToAddX/Y is greater than 0.0.
  3. Sending the wobbleAmountX/Z values to shader. 
  4. moveSpeed stores how fast the object moved in each axis from previous frame.
    The rotationDelta just contains the change in rotation in each axis from the previous frame.
  5. wobbleAmountToAddX/Z is assigned a value which is an arbitrary calculation that takes into consideration the moveSpeed as well the rotationDelta to determine the wobble.
  6. Just saving the position and rotation of the object for use in the next frame to calculate the moveSpeed and rotationDelta.
Shader Lab

1Shader "BitshiftProgrammer/Liquid"
2{
3    Properties
4    {
5		_Colour ("Colour", Color) = (1,1,1,1)
6        _FillAmount ("Fill Amount", Range(-10,10)) = 0.0
7		[HideInInspector] _WobbleX ("WobbleX", Range(-1,1)) = 0.0
8		[HideInInspector] _WobbleZ ("WobbleZ", Range(-1,1)) = 0.0
9        _TopColor ("Top Color", Color) = (1,1,1,1)
10		_FoamColor ("Foam Line Color", Color) = (1,1,1,1)
11        _Rim ("Foam Line Width", Range(0,0.1)) = 0.0
12		_RimColor ("Rim Color", Color) = (1,1,1,1)
13	    _RimPower ("Rim Power", Range(0,10)) = 0.0
14    }
15 
16    SubShader
17    {
18        Tags {"Queue"="Geometry"  "DisableBatching" = "True" }
19  
20        Pass
21        {
22		 Zwrite On
23		 Cull Off // we want the front and back faces
24		 AlphaToMask On // transparency
25         CGPROGRAM
26         #pragma vertex vert
27         #pragma fragment frag
28         #include "UnityCG.cginc"
29 
30         struct appdata
31         {
32           float4 vertex : POSITION;
33		   float3 normal : NORMAL;
34         };
35 
36         struct v2f
37         {
38            float4 vertex : SV_POSITION;
39			float3 viewDir : COLOR;
40		    float3 normal : COLOR2;
41			float fillEdge : TEXCOORD2;
42         };
43 
44         float _FillAmount, _WobbleX, _WobbleZ;
45         float4 _TopColor, _RimColor, _FoamColor, _Colour;
46         float _Rim, _RimPower;
47           
48		 float4 RotateAroundYInDegrees (float4 vertex, float degrees)
49         {
50			float alpha = degrees * UNITY_PI / 180;
51			float sina, cosa;
52			sincos(alpha, sina, cosa);
53			float2x2 m = float2x2(cosa, sina, -sina, cosa);
54			return float4(vertex.yz , mul(m, vertex.xz)).xzyw ;
55         }
56
57         v2f vert (appdata v)
58         {
59            v2f o;
60            o.vertex = UnityObjectToClipPos(v.vertex);
61            float3 worldPos = mul (unity_ObjectToWorld, v.vertex.xyz);
62			// rotate it around XY
63			float3 worldPosX= RotateAroundYInDegrees(float4(worldPos,0),360);
64			// rotate around XZ
65			float3 worldPosZ = float3 (worldPosX.y, worldPosX.z, worldPosX.x);
66			// combine rotations with worldPos, based on sine wave from script
67			float3 worldPosAdjusted = worldPos + (worldPosX  * _WobbleX)+ (worldPosZ* _WobbleZ); 
68			// how high up the liquid is
69			o.fillEdge =  worldPosAdjusted.y + _FillAmount;
70			o.viewDir = normalize(ObjSpaceViewDir(v.vertex));
71            o.normal = v.normal;
72            return o;
73         }
74
75         fixed4 frag (v2f i, fixed facing : VFACE) : SV_Target
76         {
77		   // rim light
78		   float dotProduct = 1 - pow(dot(i.normal, i.viewDir), _RimPower);
79           float4 RimResult = smoothstep(0.5, 1.0, dotProduct);
80           RimResult *= _RimColor;
81		   // foam edge
82		   float4 foam = ( step(i.fillEdge, 0.5) - step(i.fillEdge, (0.5 - _Rim)));
83           float4 foamColored = foam * (_FoamColor * 0.75);
84		   // rest of the liquid
85		   float4 result = step(i.fillEdge, 0.5) - foam;
86           float4 resultColored = result * _Colour;
87		   // both together
88           float4 finalResult = resultColored + foamColored;
89		   finalResult.rgb += RimResult;
90		   // color of backfaces/ top
91		   float4 topColor = _TopColor * (foam + result);
92		   //VFACE returns positive for front facing, negative for backfacing
93		   return facing > 0 ? finalResult : topColor;
94         }
95         ENDCG
96        }
97    }
98}