← All projects

Side project

Water Shader

A custom water shader for Unity written in CG, with Gerstner waves and parameters for color, refraction and shoreline behavior.

Type
Side project
Engine
Unity
Language
CG / HLSL
Try it
itch.io

More in the privacy policy.

Shader development

  • Wrote a custom water shader in Unity using CG.
  • Used the Gerstner wave function to deform a plane into realistic waves.
  • Added a normal map for lighting and surface detail.
  • Adjustable wave density, color, shoreline behavior, refraction strength and wave speed.
  • Unity
  • CG
  • HLSL
  • Gerstner waves
Wireframe of the deformed water mesh
float3 GerstnerWave(float4 wave, float3 p, inout float3 tangent, inout float3 binormal)
{
    float steepness = wave.z;
    float wavelength = wave.w;
    float k = 2 * UNITY_PI / wavelength;
    float c = sqrt(_Gravity / k);
    float2 d = normalize(wave.xy);
    float f = k * (dot(d, p.xz) - c * _Time.y);
    float a = steepness / k;
    float sinf = sin(f);
    float cosf = cos(f);

    tangent += float3(-d.x * d.x * (steepness * sinf), d.x * (steepness * cosf), -d.x * d.y * (steepness * sinf));
    binormal += float3(-d.x * d.y * (steepness * sinf), d.y * (steepness * cosf), -d.y * d.y * (steepness * sinf));
    return float3(d.x * (a * cosf), a * sinf, d.y * (a * cosf));
}
Properties {
        _Tess ("Tessellation", Range(1,32)) = 4
        _NormalMap ("Normalmap", 2D) = "bump" {}
        _SpecColor ("Spec color", color) = (0.5,0.5,0.5,0.5)
        _WaterFogColor ("Water Fog Color", Color) = (0, 0, 0, 0)
        _WaterFogDensity ("Water Fog Density", Range(0,2)) = 0.1
        _RefractionStrength ("Refraction Strength", Range(0,1)) = 0.25
        _Glossiness ("Glossiness", Range(0,2)) = 0.5
        _ShoreFade("Shoreline Distance", Range(0.9,2)) = 1
        _Gravity ("Wave Speed", Range(0, 20)) = 9.8
        _WaveA ("Wave A (dir, steepness, wavelength)", Vector) = (1,1,0.22,2.8)
        _WaveB ("Wave B", Vector) = (1,0.6,0.24,10.15)
        _WaveC ("Wave C", Vector) = (1,0.61,0.04,1.33)
    }

Interested in working together?