# Volumetric Cloud Rendering in Unity 6 URP

> Height-band raymarched volumetric cloud dome in Unity 6 URP HLSL using Perlin-Worley FBM, Schneider's Beer-Powder law, dual-lobe Henyey-Greenstein silver lining, interleaved gradient noise jitter, WebGL 2 loop/LOD rules, and llvmpipe step scaling.

- **Canonical page:** https://gamecrew.ai/techniques/unity/volumetric-clouds
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** atmosphere
- **Tags:** `clouds`, `volumetric`, `raymarching`, `sky`, `weather`, `shader`, `urp`, `beer-powder`, `henyey-greenstein`, `noise`, `texture3d`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Use height-band raymarched volumetric clouds whenever the sky is a primary compositional element — flight games, open islands, mountain climbs, sailing slices, or dramatic dusk vistas — where flat billboard cards break parallax or clip into peaks.

Field standard (Guerrilla Games' *Horizon: Zero Dawn* and Frostbite's physically based sky):
- **Spherical or planar height slab** (`[cloudBaseY, cloudTopY]`): clouds live inside a bounded altitude shell with an analytic height-fraction remap (rounded cumulus bottoms, billowy anvil/stratus tops) so rays outside the shell terminate in $O(1)$ before stepping.
- **Perlin-Worley base shape + Worley erosion**: broad low-frequency Perlin-Worley FBM establishes macro cloud coverage, and higher-frequency inverted Worley noise erodes only the outer silhouette (`smoothstep` edge erosion) rather than hollowing the cloud interior.
- **Dual-lobe Henyey-Greenstein phase + Beer-Powder dark-edge boost**: clouds scatter strongly toward the sun ($g_f \approx 0.65$, silver lining) with a weak back-scatter lobe ($g_b \approx -0.25$), while Schneider's powder term $(1 - e^{-2 d})$ brightens thin sunlit fringes when looking away from the sun.
- **Stochastic ray-start jitter**: offsetting `tStart` by 0–1 step using Jorge Jimenez's Interleaved Gradient Noise trades ugly wood-grain banding for subtle dither at half the step count.

## Mathematical & Algorithmic Core

1. **Ray-Slab Intersection**: Intersect world ray $\mathbf{o} + t\,\mathbf{d}$ ($d_y > 0.02$) with horizontal planes $y_{\min}$ and $y_{\max}$:
   $$t_0 = \max\!\left(0, \frac{y_{\min} - o_y}{d_y}\right), \qquad t_1 = \min\!\left(t_{\max}, \frac{y_{\max} - o_y}{d_y}\right)$$
2. **Height Gradient Profile**: For normalized altitude $h = \mathrm{saturate}\!\left(\frac{p_y - y_{\min}}{y_{\max} - y_{\min}}\right)$, round the base and crown:
   $$w(h) = \mathrm{saturate}(h / 0.18) \cdot \mathrm{saturate}((1 - h) / 0.45)$$
3. **Dual-Lobe Henyey-Greenstein Phase**: For $\mu = \mathbf{d} \cdot \mathbf{L}_{\text{sun}}$:
   $$\Phi_{\text{HG}}(\mu, g) = \frac{1 - g^2}{4\pi (1 + g^2 - 2g\mu)^{3/2}}, \qquad \Phi(\mu) = \mathrm{lerp}(\Phi_{\text{HG}}(\mu, -0.25),\; \Phi_{\text{HG}}(\mu, 0.65),\; 0.72)$$
4. **Beer-Lambert + Powder Light Energy** (Schneider 2015) with 3-tap cone march toward `_MainLightPosition.xyz`:
   $$E(\tau) = 2 \, e^{-\tau} \left(1 - e^{-2\tau}\right)$$
5. **Early Transmittance Exit**: Accumulate front-to-back $(\text{rgb}, T)$ using analytic step extinction $T_i = e^{-\sigma_e \rho \Delta t}$ and break as soon as $T < 0.02$.

## Engine Implementation

### 1. URP Volumetric Cloud Dome Shader (`Assets/Game/Shaders/VolumetricCloudDome.shader`)

Follows Unity 6 URP rules strictly: `Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl` + `Lighting.hlsl`, `CBUFFER_START(UnityPerMaterial)` for SRP Batcher compatibility, `[loop]` with compile-time ceiling `MAX_STEPS = 48` and explicit `SAMPLE_TEXTURE3D_LOD` so WebGL 2 HLSL-to-GLSL ES 3.0 compilation never fails on gradient instructions inside dynamic loops.

```hlsl
Shader "Custom/VolumetricCloudDome"
{
    Properties
    {
        _CloudNoise3D ("3D Cloud Noise (R=Base, G=Detail)", 3D) = "white" {}
        _SkyZenith ("Sky Zenith", Color) = (0.14, 0.30, 0.58, 1)
        _SkyHorizon ("Sky Horizon", Color) = (0.62, 0.74, 0.88, 1)
        _CloudLit ("Cloud Sunlit", Color) = (1.00, 0.97, 0.92, 1)
        _CloudShadow ("Cloud Shadow", Color) = (0.36, 0.43, 0.56, 1)
        _CloudAltitude ("Base Y, Top Y, Scale, Coverage", Vector) = (140.0, 340.0, 0.0018, 0.52)
        _CloudWind ("Wind XZ, Density, SilverLining", Vector) = (6.0, 2.5, 0.045, 1.35)
        _StepCount ("Raymarch Steps", Float) = 28.0
    }
    SubShader
    {
        Tags { "RenderPipeline" = "UniversalPipeline" "Queue" = "Background+10" "RenderType" = "Background" }
        Pass
        {
            Name "VolumetricCloudDome"
            Tags { "LightMode" = "UniversalForward" }
            Cull Front
            ZWrite Off
            ZTest LEqual

            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.5

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            TEXTURE3D(_CloudNoise3D);
            SAMPLER(sampler_CloudNoise3D);

            CBUFFER_START(UnityPerMaterial)
                half4 _SkyZenith;
                half4 _SkyHorizon;
                half4 _CloudLit;
                half4 _CloudShadow;
                float4 _CloudAltitude;
                float4 _CloudWind;
                float _StepCount;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 worldPos : TEXCOORD0;
            };

            Varyings vert(Attributes input)
            {
                Varyings o;
                float3 camPos = GetCameraPositionWS();
                float3 world = camPos + input.positionOS.xyz;
                o.worldPos = world;
                o.positionCS = TransformWorldToHClip(world);
                return o;
            }

            float InterleavedGradientNoise(float2 pixel)
            {
                return frac(52.9829189 * frac(dot(pixel, float2(0.06711056, 0.00583715))));
            }

            float HenyeyGreenstein(float cosTheta, float g)
            {
                float g2 = g * g;
                float denom = max(1e-3, 1.0 + g2 - 2.0 * g * cosTheta);
                return (1.0 - g2) / (4.0 * PI * denom * sqrt(denom));
            }

            float SampleCloudDensity(float3 worldPos, float timeSec)
            {
                float baseY = _CloudAltitude.x;
                float topY = max(baseY + 20.0, _CloudAltitude.y);
                float h = saturate((worldPos.y - baseY) / (topY - baseY));
                float profile = saturate(h / 0.18) * saturate((1.0 - h) / 0.45);
                if (profile <= 0.001) return 0.0;

                float3 wind = float3(_CloudWind.x, 0.0, _CloudWind.y) * timeSec;
                float3 uvw = (worldPos + wind) * _CloudAltitude.z;
                half4 n = SAMPLE_TEXTURE3D_LOD(_CloudNoise3D, sampler_CloudNoise3D, uvw, 0.0);
                half4 detail = SAMPLE_TEXTURE3D_LOD(_CloudNoise3D, sampler_CloudNoise3D, uvw * 3.1 - wind * 0.002, 0.0);

                float coverage = _CloudAltitude.w;
                float baseShape = saturate((n.r - (1.0 - coverage)) / max(0.08, coverage)) * profile;
                float erosion = lerp(detail.g, 1.0 - detail.g, saturate(h * 1.4)) * 0.28;
                return saturate(baseShape - erosion * (1.0 - baseShape * 0.65));
            }

            half4 frag(Varyings input) : SV_Target
            {
                float3 camPos = GetCameraPositionWS();
                float3 rayDir = normalize(input.worldPos - camPos);
                Light mainLight = GetMainLight();
                float3 sunDir = normalize(mainLight.direction);

                float horizonT = pow(1.0 - saturate(rayDir.y), 3.0);
                float3 sky = lerp(_SkyZenith.rgb, _SkyHorizon.rgb, horizonT);
                float sunDisc = pow(saturate(dot(rayDir, sunDir)), 256.0) * 1.6;
                sky += mainLight.color * sunDisc;

                if (rayDir.y <= 0.025)
                {
                    return half4(sky, 1.0);
                }

                float baseY = _CloudAltitude.x;
                float topY = max(baseY + 20.0, _CloudAltitude.y);
                float t0 = max(0.0, (baseY - camPos.y) / rayDir.y);
                float t1 = min(2800.0, (topY - camPos.y) / rayDir.y);
                if (t1 <= t0)
                {
                    return half4(sky, 1.0);
                }

                int steps = clamp((int)_StepCount, 8, 48);
                float dt = (t1 - t0) / (float)steps;
                float jitter = InterleavedGradientNoise(input.positionCS.xy);
                float t = t0 + jitter * dt;

                float cosTheta = dot(rayDir, sunDir);
                float phase = lerp(HenyeyGreenstein(cosTheta, -0.25), HenyeyGreenstein(cosTheta, 0.65), 0.72);
                float silver = 0.35 + phase * _CloudWind.w * 2.4;

                float transmittance = 1.0;
                float3 scattered = float3(0.0, 0.0, 0.0);
                float sigma = _CloudWind.z;
                float timeSec = _Time.y;

                [loop]
                for (int i = 0; i < 48; i++)
                {
                    if (i >= steps || transmittance < 0.02) break;
                    float3 p = camPos + rayDir * t;
                    float d = SampleCloudDensity(p, timeSec);
                    if (d > 0.002)
                    {
                        float dSun = SampleCloudDensity(p + sunDir * 28.0, timeSec)
                                   + SampleCloudDensity(p + sunDir * 72.0, timeSec) * 0.7;
                        float tau = dSun * sigma * 42.0;
                        float beerPowder = 2.0 * exp(-tau) * (1.0 - exp(-2.0 * max(0.08, tau)));
                        float h = saturate((p.y - baseY) / (topY - baseY));
                        float ambient = lerp(0.35, 0.85, h);
                        float3 cloudCol = lerp(_CloudShadow.rgb * ambient, _CloudLit.rgb * mainLight.color, saturate(beerPowder * silver));

                        float stepExt = d * sigma * dt;
                        float stepTrans = exp(-stepExt);
                        scattered += transmittance * (1.0 - stepTrans) * cloudCol;
                        transmittance *= stepTrans;
                    }
                    t += dt;
                }

                float horizonFade = saturate((rayDir.y - 0.025) / 0.14);
                float3 finalCol = lerp(sky, sky * transmittance + scattered, horizonFade);
                return half4(finalCol, 1.0);
            }
            ENDHLSL
        }
    }
}
```

### 2. Procedural 3D Perlin-Worley `Texture3D` & Software-Renderer Scaling (`Assets/Game/Runtime/Rendering/VolumetricCloudSky.cs`)

Generates a tileable $32^3$ 2-channel 3D noise texture once (< 4 ms on CPU, 128 KB VRAM, zero external asset dependency) and automatically scales `_StepCount` down to `12` when running under Mesa `llvmpipe` or `SwiftShader` so headless captures finish in seconds.

```csharp
using UnityEngine;
using UnityEngine.Rendering;

namespace Game.Rendering
{
    public sealed class VolumetricCloudSky : MonoBehaviour
    {
        private Material _material;
        private Texture3D _noise3D;

        public static VolumetricCloudSky Attach(Shader cloudShader, float coverage = 0.54f, float baseY = 140f, float topY = 340f)
        {
            var go = new GameObject("VolumetricCloudDome");
            var mf = go.AddComponent<MeshFilter>();
            var mr = go.AddComponent<MeshRenderer>();

            var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            mf.sharedMesh = sphere.GetComponent<MeshFilter>().sharedMesh;
            DestroyImmediate(sphere);

            go.transform.localScale = Vector3.one * 3200f;
            mr.shadowCastingMode = ShadowCastingMode.Off;
            mr.receiveShadows = false;

            var sky = go.AddComponent<VolumetricCloudSky>();
            sky.Initialize(mr, cloudShader, coverage, baseY, topY);
            return sky;
        }

        private void Initialize(MeshRenderer renderer, Shader shader, float coverage, float baseY, float topY)
        {
            _noise3D = BuildTileableCloudNoise(32);
            _material = new Material(shader);
            _material.SetTexture("_CloudNoise3D", _noise3D);
            _material.SetVector("_CloudAltitude", new Vector4(baseY, topY, 0.0018f, Mathf.Clamp(coverage, 0.15f, 0.85f)));

            string gpu = (SystemInfo.graphicsDeviceName ?? string.Empty).ToLowerInvariant();
            bool softwareGpu = gpu.Contains("llvmpipe") || gpu.Contains("softpipe") || gpu.Contains("swiftshader");
            _material.SetFloat("_StepCount", softwareGpu ? 12f : 28f);

            renderer.sharedMaterial = _material;
        }

        public static Texture3D BuildTileableCloudNoise(int size)
        {
            var tex = new Texture3D(size, size, size, TextureFormat.RG16, false)
            {
                wrapMode = TextureWrapMode.Repeat,
                filterMode = FilterMode.Bilinear,
                name = "ProceduralCloudNoise3D"
            };
            var pixels = new Color[size * size * size];
            int idx = 0;
            for (int z = 0; z < size; z++)
            {
                for (int y = 0; y < size; y++)
                {
                    for (int x = 0; x < size; x++)
                    {
                        Vector3 p = new Vector3(x, y, z) / size;
                        float worley1 = 1f - TileableWorley(p, 4);
                        float worley2 = 1f - TileableWorley(p, 8);
                        float worley3 = 1f - TileableWorley(p, 16);
                        float fbm = worley1 * 0.625f + worley2 * 0.25f + worley3 * 0.125f;
                        float baseCloud = Mathf.Clamp01(Mathf.PerlinNoise(p.x * 4f + p.z * 2f, p.y * 4f - p.z * 2f) * 0.55f + fbm * 0.65f);
                        pixels[idx++] = new Color(baseCloud, worley3, 0f, 1f);
                    }
                }
            }
            tex.SetPixels(pixels);
            tex.Apply(false, true);
            return tex;
        }

        private static float TileableWorley(Vector3 uvw, int cells)
        {
            Vector3 scaled = uvw * cells;
            Vector3Int baseCell = Vector3Int.FloorToInt(scaled);
            float minDistSq = 4f;
            for (int dz = -1; dz <= 1; dz++)
            {
                for (int dy = -1; dy <= 1; dy++)
                {
                    for (int dx = -1; dx <= 1; dx++)
                    {
                        Vector3Int n = baseCell + new Vector3Int(dx, dy, dz);
                        int wx = ((n.x % cells) + cells) % cells;
                        int wy = ((n.y % cells) + cells) % cells;
                        int wz = ((n.z % cells) + cells) % cells;
                        Vector3 feature = new Vector3(dx, dy, dz) + Hash3(wx, wy, wz) - (scaled - baseCell);
                        float d2 = feature.sqrMagnitude;
                        if (d2 < minDistSq) minDistSq = d2;
                    }
                }
            }
            return Mathf.Clamp01(Mathf.Sqrt(minDistSq));
        }

        private static Vector3 Hash3(int x, int y, int z)
        {
            uint h = (uint)(x * 73856093 ^ y * 19349663 ^ z * 83492791);
            h = (h ^ 61u) ^ (h >> 16);
            h *= 9u;
            h ^= h >> 4;
            h *= 0x27d4eb2du;
            h ^= h >> 15;
            return new Vector3(
                (h & 1023u) / 1023f,
                ((h >> 10) & 1023u) / 1023f,
                ((h >> 20) & 1023u) / 1023f);
        }

        private void OnDestroy()
        {
            if (_material != null) Destroy(_material);
            if (_noise3D != null) Destroy(_noise3D);
        }
    }
}
```

## Browser, Mobile & Software-Renderer Budgets

- **WebGL 2 Shader Compiler**: Never use `SAMPLE_TEXTURE3D` (implicit derivatives) inside `[loop]` branches with early `break`; always call `SAMPLE_TEXTURE3D_LOD(..., 0.0)` and keep a constant loop upper bound (`i < 48`) so HLSLcc / ANGLE emits valid GLSL ES 3.0.
- **`Texture3D` Size**: Keep procedural `Texture3D` to $32^3$ (`RG16` = 128 KB) or $48^3$ max so scene startup takes $< 5\text{ ms}$ and WebGL heap stays lean.
- **Software Renderer (`llvmpipe` / `SwiftShader`)**: Full-screen raymarching at 64+ steps with 4x MSAA can push CPU batch captures past 60 seconds. Scaling `_StepCount` to `12` on `llvmpipe`/`SwiftShader` and keeping capture MSAA at `1` renders each view in $< 1.5\text{ s}$ while preserving silhouette and sun-rim lighting.
- **Shader Stripping in WebGL Builds**: Reference `VolumetricCloudDome.shader` from `Resources/Shaders/` or a serialized scene material built during `SceneBuilder` so `BuildPlayer` includes the shader in the WebGL bundle.

## Verification Checklist

1. Place shader under `Assets/Game/Resources/Shaders/VolumetricCloudDome.shader` (loaded via `Resources.Load<Shader>("Shaders/VolumetricCloudDome")`) so both EditMode/PlayMode and WebGL player builds retain it.
2. Ensure the camera `farClipPlane` exceeds the dome radius (`>= 2000f` for a `3200f` diameter dome, i.e., `1600f` radius) and `CameraClearFlags` does not fight the `Background+10` pass.
3. Run `compile`, `scene`, and `capture`, then open `Captures/*.png` with `Read` to confirm distinct sunlit crowns, shadowed cloud bellies, and smooth horizon blending (brightness $> 0.12$, contrast $> 0.08$).

## Official references

- Andrew Schneider & Nathan Vos (SIGGRAPH 2015 / 2017, Guerrilla Games — The Real-Time Volumetric Cloudscapes of Horizon: Zero Dawn)
- Sébastien Hillaire (SIGGRAPH 2016 / EGSR 2020 — Physically Based Sky, Atmosphere and Cloud Rendering)
- Jorge Jimenez (SIGGRAPH 2014 — Interleaved Gradient Noise)
