# Raymarched Volumetric Cloud Sky in Godot 4 Compatibility (WebGL 2)

> Compatibility-safe sky shader in Godot 4.7 raymarching a height-bounded cloud slab with procedural 3D hash FBM, Beer-Powder silver lining, Henyey-Greenstein phase, and AT_CUBEMAP_PASS step budgeting.

- **Canonical page:** https://gamecrew.ai/techniques/godot/volumetric-clouds-sky-webgl
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** atmosphere
- **Tags:** `clouds`, `volumetric`, `sky`, `raymarching`, `weather`, `shader`, `gdshader`, `compatibility`, `beer-powder`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Godot 4's Compatibility renderer (WebGL 2 in the browser) does not include Vulkan-only `FogVolume` / `volumetric_fog_enabled`, so atmospheric cloudscapes are built directly inside a custom `shader_type sky` attached to `WorldEnvironment.environment.sky`!

Best-in-field pattern for Compatibility WebGL 2 skies:
1. **Analytical Ray-Slab Intersection (`EYEDIR.y > 0.02`)**: Intersect `EYEDIR` with `[cloud_base, cloud_top]` so horizon and ground rays skip raymarching completely.
2. **`AT_CUBEMAP_PASS` Step Halving**: Godot evaluates `sky()` both for the background and for ambient radiance cubemaps. Branching on `AT_CUBEMAP_PASS` to run `6` coarse steps for ambient cubemaps and `20` jittered steps for the visible sky cuts GPU cost by > 60% while keeping sky ambient color accurate!
3. **Dual-Lobe Henyey-Greenstein + Beer-Powder**: Forward scattering along `LIGHT0_DIRECTION` creates glowing silver-lined cumulus rims against warm dusk or crisp blue zenith gradients.

## Mathematical & Algorithmic Core

- **Slab Bounds** (camera at $y = 0$ relative to altitude band $[b, h]$):
  $$t_0 = \frac{b}{\max(0.025, d_y)}, \qquad t_1 = \min\!\left(2600.0, \frac{h}{\max(0.025, d_y)}\right)$$
- **Beer-Powder Energy**: $E(\tau) = 2 e^{-\tau}(1 - e^{-2\tau})$, blended with height fraction $u \in [0, 1]$ so cloud bellies pick up cool ambient sky bounce while crowns catch direct `LIGHT0_COLOR`.

## Engine Implementation

### 1. Compatibility Volumetric Sky Shader (`Assets/Game/Shaders/volumetric_clouds.gdshader`)

```glsl
shader_type sky;

uniform vec3 sky_zenith : source_color = vec3(0.13, 0.29, 0.57);
uniform vec3 sky_horizon : source_color = vec3(0.64, 0.76, 0.89);
uniform vec3 sky_ground : source_color = vec3(0.16, 0.17, 0.22);
uniform vec3 cloud_lit : source_color = vec3(1.00, 0.97, 0.92);
uniform vec3 cloud_shadow : source_color = vec3(0.35, 0.42, 0.55);
uniform float cloud_coverage : hint_range(0.1, 0.9) = 0.54;
uniform float cloud_scale : hint_range(0.0005, 0.01) = 0.0022;
uniform vec2 wind_velocity = vec2(7.0, 3.0);

float hash13(vec3 p3) {
	p3 = fract(p3 * 0.1031);
	p3 += dot(p3, p3.zyx + 31.32);
	return fract((p3.x + p3.y) * p3.z);
}

float value_noise3(vec3 x) {
	vec3 i = floor(x);
	vec3 f = fract(x);
	f = f * f * (3.0 - 2.0 * f);
	return mix(
		mix(mix(hash13(i + vec3(0, 0, 0)), hash13(i + vec3(1, 0, 0)), f.x),
		    mix(hash13(i + vec3(0, 1, 0)), hash13(i + vec3(1, 1, 0)), f.x), f.y),
		mix(mix(hash13(i + vec3(0, 0, 1)), hash13(i + vec3(1, 0, 1)), f.x),
		    mix(hash13(i + vec3(0, 1, 1)), hash13(i + vec3(1, 1, 1)), f.x), f.y),
		f.z
	);
}

float cloud_fbm(vec3 p) {
	float v = 0.55 * value_noise3(p);
	p = p * 2.03 + vec3(17.1, 9.3, 5.7);
	v += 0.30 * value_noise3(p);
	p = p * 2.07 + vec3(3.4, 21.8, 11.2);
	v += 0.15 * value_noise3(p);
	return v;
}

float henyey_greenstein(float cos_theta, float g) {
	float g2 = g * g;
	float d = max(1e-3, 1.0 + g2 - 2.0 * g * cos_theta);
	return (1.0 - g2) / (12.56637 * d * sqrt(d));
}

float sample_cloud(vec3 p, float base_y, float top_y) {
	float h = clamp((p.y - base_y) / (top_y - base_y), 0.0, 1.0);
	float profile = clamp(h / 0.18, 0.0, 1.0) * clamp((1.0 - h) / 0.45, 0.0, 1.0);
	if (profile <= 0.001) {
		return 0.0;
	}
	vec3 wind = vec3(wind_velocity.x, 0.0, wind_velocity.y) * TIME;
	float n = cloud_fbm((p + wind) * cloud_scale);
	float d = clamp((n - (1.0 - cloud_coverage)) / max(0.1, cloud_coverage), 0.0, 1.0) * profile;
	return d;
}

void sky() {
	vec3 dir = normalize(EYEDIR);
	vec3 sun_dir = LIGHT0_ENABLED ? normalize(LIGHT0_DIRECTION) : normalize(vec3(0.4, 0.65, 0.3));
	vec3 sun_col = LIGHT0_ENABLED ? LIGHT0_COLOR * min(LIGHT0_ENERGY, 2.0) : vec3(1.0, 0.94, 0.84);

	float up = clamp(dir.y, 0.0, 1.0);
	vec3 sky_col = mix(sky_horizon, sky_zenith, pow(up, 0.6));
	if (dir.y < 0.0) {
		sky_col = mix(sky_horizon, sky_ground, clamp(-dir.y * 4.0, 0.0, 1.0));
	}
	float sun_disc = pow(clamp(dot(dir, sun_dir), 0.0, 1.0), 220.0) * 1.4;
	sky_col += sun_col * sun_disc;

	if (dir.y > 0.025) {
		float base_y = 140.0;
		float top_y = 320.0;
		float t0 = base_y / dir.y;
		float t1 = min(2400.0, top_y / dir.y);
		if (t1 > t0) {
			int steps = AT_CUBEMAP_PASS ? 6 : 20;
			float dt = (t1 - t0) / float(steps);
			float jitter = AT_CUBEMAP_PASS ? 0.5 : fract(52.9829189 * fract(dot(SKY_COORDS * 1024.0, vec2(0.06711, 0.00583))));
			float t = t0 + jitter * dt;

			float cos_theta = dot(dir, sun_dir);
			float phase = mix(henyey_greenstein(cos_theta, -0.25), henyey_greenstein(cos_theta, 0.65), 0.72);
			float silver = 0.42 + phase * 3.1;

			float trans = 1.0;
			vec3 accum = vec3(0.0);
			float sigma = 0.048;

			for (int i = 0; i < 20; i++) {
				if (i >= steps || trans < 0.03) {
					break;
				}
				vec3 p = dir * t;
				float d = sample_cloud(p, base_y, top_y);
				if (d > 0.003) {
					float d_sun = sample_cloud(p + sun_dir * 36.0, base_y, top_y);
					float tau = d_sun * sigma * 48.0;
					float beer_powder = 2.0 * exp(-tau) * (1.0 - exp(-2.0 * max(0.1, tau)));
					float h = clamp((p.y - base_y) / (top_y - base_y), 0.0, 1.0);
					vec3 c = mix(cloud_shadow * mix(0.45, 0.9, h), cloud_lit * sun_col, clamp(beer_powder * silver, 0.0, 1.0));
					float step_t = exp(-d * sigma * dt);
					accum += trans * (1.0 - step_t) * c;
					trans *= step_t;
				}
				t += dt;
			}
			float horizon_fade = clamp((dir.y - 0.025) / 0.12, 0.0, 1.0);
			sky_col = mix(sky_col, sky_col * trans + accum, horizon_fade);
		}
	}
	COLOR = sky_col;
}
```

### 2. Wiring into `WorldEnvironment` from GDScript (`Assets/Game/Scripts/gameplay/cloud_sky.gd`)

```gdscript
class_name CloudSky
extends RefCounted

static func apply(world_env: WorldEnvironment, coverage := 0.54) -> ShaderMaterial:
	var shader := load("res://Assets/Game/Shaders/volumetric_clouds.gdshader") as Shader
	var mat := ShaderMaterial.new()
	mat.shader = shader
	mat.set_shader_parameter("cloud_coverage", clampf(coverage, 0.15, 0.85))

	var sky := Sky.new()
	sky.sky_material = mat
	sky.radiance_size = Sky.RADIANCE_SIZE_128

	if world_env.environment == null:
		world_env.environment = Environment.new()
	var env := world_env.environment
	env.background_mode = Environment.BG_SKY
	env.sky = sky
	env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
	env.ambient_light_sky_contribution = 0.65
	env.ambient_light_energy = 1.0
	return mat
```

## Browser, Mobile & Software-Renderer Budgets

- **`Sky.PROCESS_MODE_REALTIME` vs `Sky.RADIANCE_SIZE_128`**: Keep `radiance_size = Sky.RADIANCE_SIZE_128` and `AT_CUBEMAP_PASS ? 6 : 20` so animated wind updates smoothly in WebGL 2 without re-baking a 512px cubemap every frame.
- **Loop Ceiling in WebGL 2**: Always write a constant integer loop ceiling (`for (int i = 0; i < 20; i++)`) with an `if (i >= steps) break;` guard so WebGL 2 GLSL ES 3.0 drivers unroll/validate cleanly.

## Verification Checklist

1. Ensure a `DirectionalLight3D` exists in the scene so `LIGHT0_ENABLED` and `LIGHT0_DIRECTION` drive the silver lining.
2. Run `compile`, `scene`, and `capture`, then inspect `Captures/*.png` to verify readable cloud silhouettes and bright horizon/zenith separation.

## Official references

- Andrew Schneider & Nathan Vos (SIGGRAPH 2015, Guerrilla Games — Real-Time Volumetric Cloudscapes)
- Sébastien Hillaire (SIGGRAPH 2016 — Physically Based Sky and Cloud Rendering)
- Godot 4 Sky Shader & Compatibility Renderer Architecture
