A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(fog): the fog's beams follow the clouds of the sky, so a gap in them is a shaft
yhhad895b1a92e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fba643897..ccc606ed3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Light beams that follow the clouds.** `heightFog` has a `cloudShade`: its volumetric light marches the sun's ray up through the cloud layer of a `skyAtmosphere` whose clouds cast shadows (the same density the sky draws, fixed to the world and drifting with its wind), so a gap in the clouds is a beam in the air and what they cover is dark, whichever way the camera looks. `volumeRange` may now be as long as a million units, for beams through clouds kilometres up. The sky's clouds are copied onto the fog each frame, and an effect's uniform may be `internal`, which an inspector does not list.- **Sparkle on the water.** The Water shader reads two tiled normal maps that scroll over the surface (`u_detailMap`, `u_detailTile0/1`, `u_detailStrength0/1`, `u_detailFlow0/1`), packed into the one texture a material has room for, so the sun's glints on small slopes come from lit specular response and not a white texture; a material that sets no strength is unchanged.- **A generated world's plants.** A recipe's members can name a **plant** in the rules' `plants` (a `.esworld` file holds them): several parts (a trunk and its crown), a cheaper mesh and a far version, the colourings the art gives it, how far it is sunk and its `unit` (100 for metres in a world of centimetres). The world is laid out from the rules as the eye moves, the plants grown a cell at a time by the machinery a `PlacedFoliage` uses: a chunk stands at once and fills in over the frames after it inside the frame's budget, a cheaper mesh stands in at the middle distance, and a tree's crossed cards, laid out as a layer of their own, stand for it far off. A plant with no cards of its own may use its cheaper mesh as its far version and set `farKeep`, the share of its plants that version draws, so ground cover far off costs a share of what it does near; a member with `attach: 'align'` leans a plant with the ground, so a stone on a slope sits as the slope lies; the far versions are laid out in cells as wide as the shortest distance they are shown over allows, which took the Terrain & Water example's draws from about 1,800 to about 1,100. The terrain's paint is a field each of its layers (`paint.grass`), a rules file names noise fields of its own, and fields are worked out only where a condition reads them. The Terrain & Water example's woods, shrubs, stones, grass, flowers and reeds are laid out this way from `assets/worlds/plants.esworld`.- **Each terrain layer says how it meets the others.** A `.esterrainlayer` may name a `heightBlend`: 0 blends by the paint alone (grass into sand), 1 by the layers' heights (stones standing through grass), weighted by how much of each layer is there; absent, it is the material's `u_heightBlend`. The editor's layer panel sets it.@@ -62,6 +63,7 @@ published separately; it ships inside the editor.### Fixed+- **A cloud's shadow stays where the cloud is.** The shadow a sky's clouds cast on the scene added the camera's position to the cloud's, so it slid across the ground as the camera moved while the cloud in the sky stood still; it is taken from the same place the sky draws the cloud from.- **A leaf or a blade of grass no longer has a pale edge.** A cutout texture (one with a Mip Coverage) has the colour of its solid texels carried into its clear ones when it is cooked, as a model's cutouts already did: what an artist leaves under alpha 0, often white, was averaged in at every leaf's edge by the filter and the mips. The source image is not touched.- **A world's layers over an area are counted over the area.** The chunks of a procedural layer are walked over the part of the wanted radius that lies in the layer's extent, not over the whole radius, and a generated world on an area of terrain takes the terrain's bounds as its extent: a layer wanted a thousand chunk-widths out no longer costs seconds a frame.- **A level-of-detail group with only a cull size is no longer ignored.** A `LODGroup` with no stand-in mesh and a `cullSize` draws the renderer's own mesh while it is big enough and nothing once it is smaller, where it used to be dropped as if it were not there, so a tuft of grass had no distance to be drawn to.diff --git a/desktop b/desktopindex 3a07b5b63..0337753d4 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 3a07b5b6386d94fc7892a6c76be8f769423c4d06+Subproject commit 0337753d463af2ff79cc40f9f6ad36441ef8306fdiff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdxindex e021f073d..a11a8b9d7 100644--- a/docs/astro/src/content/docs/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx@@ -290,6 +290,12 @@ eye — so a building's shadow is dark fog and the gap between two of them a beathat casts shadows (the effect reads the same atlas the meshes receive from), and `volumeRange` says how farfrom the camera the air is walked; beyond it the fog still dims but takes no shafts.+`cloudShade` makes those beams follow the sky's clouds, so a gap in them is a shaft that stands in the air whichever way the camera looks, not+only toward the sun. The fog marches the sun's ray up through the cloud layer of a `skyAtmosphere` with `cloudShadow` above 0 (the clouds are then+fixed to the world and drift with its wind), against the same density the sky draws; what the clouds cover is dark air. Its beams are as long as+`volumeRange`, in world units, and a beam through clouds kilometres up needs air that far up: a fog with a low `heightFalloff` and a `volumeRange` of+a few kilometres. The sky's cover, height, thickness and wind are copied onto the fog each frame; they are not settings of the fog's own.+`lightShafts` finds the sun's light through whatever stands in front of it, in screen space: each pixelmarches toward the sun's place on screen and counts how much of the way is open sky. It needs thesun on screen or just off it, and only what the depth buffer holds can cast a shaft. Together the twodiff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdxindex fe1256e28..564d10c32 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx@@ -216,6 +216,12 @@ registerEffect({一盏投射阴影的方向光(效果读的是网格接收阴影用的同一张图集),`volumeRange` 说空气从相机起走多远;超出之后雾仍然让画面变暗,但不再有光束。+`cloudShade` 让这些光束跟着天空的云走:云的缺口就是一道光束,站在空气里,不管相机朝哪边看,不只是朝着太阳。+雾把太阳的光线向上穿过 `cloudShadow` 大于 0 的 `skyAtmosphere` 的云层(云此时固定在世界里,随风漂移),+用的是和天空画出来的同一份密度;云盖住的地方是暗的空气。光束的长度是 `volumeRange`(世界单位),穿过几公里+高的云需要同样高的空气:`heightFalloff` 取小,`volumeRange` 取几公里。天空的覆盖、高度、厚度和风每帧+复制到雾上,不是雾自己的设置。+`lightShafts` 在屏幕空间里找出太阳光穿过前方遮挡物的样子:每个像素朝太阳在屏幕上的位置步进,数这一路有多少是开阔天空。太阳需要在屏幕上或刚好在屏幕外,而且只有深度缓冲里有的东西才能投出光束。两者配合出低角度太阳的"雾加光束"的样子;`lightShafts` 仍是屏幕空间的,带阴影的体积光是 `heightFog` 的 `volumetric`。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 07b76ea37..f4f9cc4cf 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3755,6 +3755,7 @@ uniforms: EffectUniformDef[]## EffectUniformDef — interface @experimental```defaultValue: number+internal: boolean | undefinedlabel: stringmax: numbermin: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b37d65ec0..a6659e491 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3763,6 +3763,7 @@ uniforms: EffectUniformDef[]## EffectUniformDef — interface @experimental```defaultValue: number+internal: boolean | undefinedlabel: stringmax: numbermin: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 945c1c003..506c9bf52 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3750,6 +3750,7 @@ uniforms: EffectUniformDef[]## EffectUniformDef — interface @experimental```defaultValue: number+internal: boolean | undefinedlabel: stringmax: numbermin: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 18d54f908..417b75553 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3750,6 +3750,7 @@ uniforms: EffectUniformDef[]## EffectUniformDef — interface @experimental```defaultValue: number+internal: boolean | undefinedlabel: stringmax: numbermin: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 9c7519312..9356a941d 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3750,6 +3750,7 @@ uniforms: EffectUniformDef[]## EffectUniformDef — interface @experimental```defaultValue: number+internal: boolean | undefinedlabel: stringmax: numbermin: numberdiff --git a/sdk/src/postprocess/cloudShafts.ts b/sdk/src/postprocess/cloudShafts.tsnew file mode 100644index 000000000..5aefe8da4--- /dev/null+++ b/sdk/src/postprocess/cloudShafts.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cloudShafts.ts+ * @brief The sky's clouds, handed to the fog so its beams stand where the clouds let the sun through.+ *+ * @details The fog walks the air against the shadow map, which knows nothing of the clouds: they are drawn by the sky, kilometres up. The sky's+ * cloud layer (coverage, height, thickness, wind) is copied onto the fog each frame, so its shader can march the sun's ray up through+ * the same density the dome draws. Only a sky whose clouds cast shadows is followed: those are fixed to the world, and a cloud that rides+ * with the camera has no place a shaft could stand.+ */+import { getEffectDef } from './effects';+import type { BlendedEffect } from './volumeBlending';++function value(effect: BlendedEffect, type: string, name: string): number {+ const set = effect.uniforms.get(name);+ if (set !== undefined) return set;+ return getEffectDef(type)?.uniforms.find((u) => u.name === name)?.defaultValue ?? 0;+}++/** Writes onto the fog what it reads of the sky's clouds; with no Cloud Shafts, no sky, or clouds that cast no shadow, the fog's clouds are none. */+export function applyCloudsToFog(effects: Map<string, BlendedEffect>): void {+ const fog = effects.get('heightFog');+ if (!fog || !fog.enabled) return;+ const sky = effects.get('skyAtmosphere');+ if (value(fog, 'heightFog', 'u_cloudShade') <= 0 || !sky || !sky.enabled || value(sky, 'skyAtmosphere', 'u_cloudShadow') <= 0) {+ fog.uniforms.set('u_skyCover', 0);+ return;+ }+ const overcast = Math.min(Math.max(value(sky, 'skyAtmosphere', 'u_overcast'), 0), 1);+ const angle = value(sky, 'skyAtmosphere', 'u_windDirection') * Math.PI / 180;+ const speed = value(sky, 'skyAtmosphere', 'u_windSpeed');+ const set = (name: string, v: number): void => { fog.uniforms.set(name, v); };+ set('u_skyCover', Math.max(value(sky, 'skyAtmosphere', 'u_clouds'), overcast * 0.95));+ set('u_skyBase', value(sky, 'skyAtmosphere', 'u_cloudBase'));+ set('u_skyThickness', value(sky, 'skyAtmosphere', 'u_cloudThickness'));+ set('u_skyAltitude', value(sky, 'skyAtmosphere', 'u_altitude'));+ set('u_skyUnits', value(sky, 'skyAtmosphere', 'u_unitsPerKm'));+ set('u_skySigma', 1.3 * (1 + overcast * 1.5));+ set('u_skyWindX', Math.sin(angle) * speed);+ set('u_skyWindZ', Math.cos(angle) * speed);+}diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.tsindex f764bf174..e16decbd4 100644--- a/sdk/src/postprocess/effects.ts+++ b/sdk/src/postprocess/effects.ts@@ -33,6 +33,8 @@ export interface EffectUniformDef {* black / extreme distortion at a volume's soft edge.*/neutralValue?: number;+ /** Set by the engine from another effect, not by a scene: an inspector does not list it. */+ internal?: boolean;}/** A texture parameter (LUT, mask): the sampler uniform it binds to. */@@ -402,7 +404,19 @@ registerEffect({// directional light that casts a shadow, and costs 24 taps a pixel.{ name: 'u_volumetric', label: 'Volumetric Light', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },// How far from the camera the air is walked: past it the fog still dims, but takes no shafts.- { name: 'u_volumeRange', label: 'Volumetric Range', min: 100, max: 30000, step: 100, defaultValue: 3000 },+ { name: 'u_volumeRange', label: 'Volumetric Range', min: 100, max: 1000000, step: 100, defaultValue: 3000 },+ // How much the sky's clouds cut the beams: a gap in them is a shaft, and what they cover is dark air. It follows the clouds+ // of a skyAtmosphere that has Cloud Shadows above 0 (the clouds are then fixed to the world, so the shafts stand where they do).+ { name: 'u_cloudShade', label: 'Cloud Shafts', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },+ // What it reads of that sky, written each frame from the sky effect (see applyCloudsToFog).+ { name: 'u_skyCover', label: 'Sky Cover', min: 0, max: 1, step: 0.01, defaultValue: 0, internal: true },+ { name: 'u_skyBase', label: 'Sky Cloud Base', min: 0.2, max: 10, step: 0.1, defaultValue: 1.5, internal: true },+ { name: 'u_skyThickness', label: 'Sky Cloud Thickness', min: 0.2, max: 8, step: 0.1, defaultValue: 2.5, internal: true },+ { name: 'u_skyAltitude', label: 'Sky Altitude', min: 0, max: 20, step: 0.1, defaultValue: 0.1, internal: true },+ { name: 'u_skyUnits', label: 'Sky Units per km', min: 1, max: 100000, step: 1, defaultValue: 1000, internal: true },+ { name: 'u_skySigma', label: 'Sky Cloud Density', min: 0, max: 10, step: 0.1, defaultValue: 1.3, internal: true },+ { name: 'u_skyWindX', label: 'Sky Wind X', min: -2, max: 2, step: 0.01, defaultValue: 0, internal: true },+ { name: 'u_skyWindZ', label: 'Sky Wind Z', min: -2, max: 2, step: 0.01, defaultValue: 0, internal: true },],colors: [{ name: 'u_fogColor', label: 'Colour', defaultValue: { r: 0.62, g: 0.7, b: 0.8, a: 1 } },diff --git a/sdk/src/postprocess/sources/atmosphere.ts b/sdk/src/postprocess/sources/atmosphere.tsindex 760bce4ce..51139d361 100644--- a/sdk/src/postprocess/sources/atmosphere.ts+++ b/sdk/src/postprocess/sources/atmosphere.ts@@ -202,7 +202,7 @@ void main() {float windAngle = radians(u_windDirection);vec3 windDrift = vec3(sin(windAngle), 0.0, cos(windAngle)) * (u_windSpeed * u_time.x) + anchor;if (geometry) {- float lit = cloudShadowAt(worldFromDepth(v_texCoord, depth), entry, sun, max(u_clouds, overcast * 0.95), overcast, windDrift);+ float lit = cloudShadowAt(worldFromDepth(v_texCoord, depth), entry, sun, max(u_clouds, overcast * 0.95), overcast, windDrift - anchor);fragColor = vec4(src.rgb * lit, src.a);return;}@@ -454,7 +454,7 @@ fn cloudShadowAt(world : vec3f, cam : vec3f, sun : vec3f, coverage : f32, overcalet windAngle = radians(mc.u_windDirection);let windDrift = vec3f(sin(windAngle), 0.0, cos(windAngle)) * (mc.u_windSpeed * tc.u_time.x) + anchor;if (geometry) {- let lit = cloudShadowAt(worldFromDepth(v.v_texCoord, depth), entry, sun, max(mc.u_clouds, overcast * 0.95), overcast, windDrift, v.pos.xy);+ let lit = cloudShadowAt(worldFromDepth(v.v_texCoord, depth), entry, sun, max(mc.u_clouds, overcast * 0.95), overcast, windDrift - anchor, v.pos.xy);return vec4f(src.rgb * lit, src.a);}@@ -573,7 +573,16 @@ fn cloudShadowAt(world : vec3f, cam : vec3f, sun : vec3f, coverage : f32, overca#pragma param u_skyFog float default(0.8) range(0,1)#pragma param u_followSun float default(1) range(0,1)#pragma param u_volumetric float default(0) range(0,1)-#pragma param u_volumeRange float default(3000) range(100,30000)+#pragma param u_volumeRange float default(3000) range(100,1000000)+#pragma param u_cloudShade float default(0) range(0,1)+#pragma param u_skyCover float default(0) range(0,1)+#pragma param u_skyBase float default(1.5) range(0.2,10)+#pragma param u_skyThickness float default(2.5) range(0.2,8)+#pragma param u_skyAltitude float default(0.1) range(0,20)+#pragma param u_skyUnits float default(1000) range(1,100000)+#pragma param u_skySigma float default(1.3) range(0,10)+#pragma param u_skyWindX float default(0) range(-2,2)+#pragma param u_skyWindZ float default(0) range(-2,2)#pragma lights#pragma fragment@@ -596,6 +605,49 @@ float phaseHG(float cosine) {return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;}++float hash13(vec3 p) {+ p = fract(p * 0.1031);+ p += dot(p, p.zyx + 31.32);+ return fract((p.x + p.y) * p.z);+}+float vnoise(vec3 p) {+ vec3 i = floor(p);+ vec3 f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ float a = mix(hash13(i), hash13(i + vec3(1, 0, 0)), f.x);+ float b = mix(hash13(i + vec3(0, 1, 0)), hash13(i + vec3(1, 1, 0)), f.x);+ float c = mix(hash13(i + vec3(0, 0, 1)), hash13(i + vec3(1, 0, 1)), f.x);+ float d = mix(hash13(i + vec3(0, 1, 1)), hash13(i + vec3(1, 1, 1)), f.x);+ return mix(mix(a, b, f.y), mix(c, d, f.y), f.z);+}+/// The sky's cloud density, the same one the dome draws (see skyAtmosphere), at a point in kilometres.+float cloudDensity(vec3 p, float coverage, float base, float thick) {+ float h = clamp((p.y - base) / thick, 0.0, 1.0);+ float shape = smoothstep(0.0, 0.14, h) * smoothstep(1.0, 0.55, h);+ vec3 q = vec3(p.x, p.y * 1.8, p.z) * 0.32;+ float n = vnoise(q) * 0.58 + vnoise(q * 2.13) * 0.28 + 0.07;+ return smoothstep(1.0 - coverage, 1.0 - coverage + 0.22, n) * shape;+}+/// How much of the sun reaches the air at @p world through the cloud layer, 1 being all of it: the sun's ray marched up through the slab.+float cloudLight(vec3 world, float camY, vec3 sun, vec3 drift) {+ if (u_cloudShade <= 0.001 || u_skyCover <= 0.01 || sun.y <= 0.02) return 1.0;+ float k = 1.0 / max(u_skyUnits, 1e-3);+ float h = u_skyAltitude + (world.y - camY) * k;+ float tt = (u_skyBase + u_skyThickness - h) / sun.y;+ if (tt <= 0.0) return 1.0;+ float tb = max(u_skyBase - h, 0.0) / sun.y;+ const int N = 4;+ float ds = (tt - tb) / float(N);+ float tau = 0.0;+ for (int i = 0; i < N; ++i) {+ float t = tb + (float(i) + 0.5) * ds;+ vec3 q = vec3(world.x * k + sun.x * t, h + sun.y * t, world.z * k + sun.z * t) + drift;+ tau += cloudDensity(q, u_skyCover, u_skyBase, u_skyThickness) * u_skySigma * ds;+ }+ return 1.0 - u_cloudShade * (1.0 - exp(-tau));+}+/// What the exponential density integrates to along a ray: the eye's density, the length,/// and the term for how fast the ray leaves the fog. Written so a level ray (no climb)/// needs no division, and so a long ray downward cannot overflow.@@ -656,11 +708,15 @@ void main() {float jitter = ign(gl_FragCoord.xy);float transmit = 1.0;float lit = 0.0;+ // The clouds are as the sky draws them, fixed in the world and drifting; their light changes slowly along the ray, so every third step asks.+ vec3 drift = vec3(u_skyWindX, 0.0, u_skyWindZ) * u_time.x;+ float shade = 1.0;for (int i = 0; i < VOLUME_STEPS; ++i) {float t = u_startDistance + (float(i) + jitter) * ds;vec3 p = entry + dir * t;+ if (i % 3 == 0) shade = cloudLight(p, entry.y, sun, drift);float dens = u_density * exp(clamp(-u_heightFalloff * (p.y - u_baseHeight), -60.0, 60.0));- lit += transmit * dens * ds * sunVisibility(p, tiles.x, tiles.y);+ lit += transmit * dens * ds * sunVisibility(p, tiles.x, tiles.y) * shade;transmit *= exp(-dens * ds);}float strength = clamp(lightColor.a, 0.0, 8.0) * 0.5;@@ -682,6 +738,46 @@ fn phaseHG(cosine : f32) -> f32 {return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;}+fn hash13(p0 : vec3f) -> f32 {+ var p = fract(p0 * 0.1031);+ p = p + dot(p, p.zyx + 31.32);+ return fract((p.x + p.y) * p.z);+}+fn vnoise(p : vec3f) -> f32 {+ let i = floor(p);+ var f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ let a = mix(hash13(i), hash13(i + vec3f(1, 0, 0)), f.x);+ let b = mix(hash13(i + vec3f(0, 1, 0)), hash13(i + vec3f(1, 1, 0)), f.x);+ let c = mix(hash13(i + vec3f(0, 0, 1)), hash13(i + vec3f(1, 0, 1)), f.x);+ let d = mix(hash13(i + vec3f(0, 1, 1)), hash13(i + vec3f(1, 1, 1)), f.x);+ return mix(mix(a, b, f.y), mix(c, d, f.y), f.z);+}+fn cloudDensity(p : vec3f, coverage : f32, base : f32, thick : f32) -> f32 {+ let h = clamp((p.y - base) / thick, 0.0, 1.0);+ let shape = smoothstep(0.0, 0.14, h) * smoothstep(1.0, 0.55, h);+ let q = vec3f(p.x, p.y * 1.8, p.z) * 0.32;+ let n = vnoise(q) * 0.58 + vnoise(q * 2.13) * 0.28 + 0.07;+ return smoothstep(1.0 - coverage, 1.0 - coverage + 0.22, n) * shape;+}+fn cloudLight(world : vec3f, camY : f32, sun : vec3f, drift : vec3f) -> f32 {+ if (mc.u_cloudShade <= 0.001 || mc.u_skyCover <= 0.01 || sun.y <= 0.02) { return 1.0; }+ let k = 1.0 / max(mc.u_skyUnits, 1e-3);+ let h = mc.u_skyAltitude + (world.y - camY) * k;+ let tt = (mc.u_skyBase + mc.u_skyThickness - h) / sun.y;+ if (tt <= 0.0) { return 1.0; }+ let tb = max(mc.u_skyBase - h, 0.0) / sun.y;+ let N = 4;+ let ds = (tt - tb) / f32(N);+ var tau = 0.0;+ for (var i : i32 = 0; i < N; i = i + 1) {+ let t = tb + (f32(i) + 0.5) * ds;+ let q = vec3f(world.x * k + sun.x * t, h + sun.y * t, world.z * k + sun.z * t) + drift;+ tau = tau + cloudDensity(q, mc.u_skyCover, mc.u_skyBase, mc.u_skyThickness) * mc.u_skySigma * ds;+ }+ return 1.0 - mc.u_cloudShade * (1.0 - exp(-tau));+}+fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {let k = mc.u_heightFalloff;let dens = mc.u_density * exp(clamp(-k * (eyeY - mc.u_baseHeight), -60.0, 60.0));@@ -739,11 +835,14 @@ fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {let jitter = ign(v.pos.xy);var transmit = 1.0;var lit = 0.0;+ let drift = vec3f(mc.u_skyWindX, 0.0, mc.u_skyWindZ) * tc.u_time.x;+ var shade = 1.0;for (var i : i32 = 0; i < VOLUME_STEPS; i = i + 1) {let t = mc.u_startDistance + (f32(i) + jitter) * ds;let p = entry + dir * t;+ if (i % 3 == 0) { shade = cloudLight(p, entry.y, sun, drift); }let dens = mc.u_density * exp(clamp(-mc.u_heightFalloff * (p.y - mc.u_baseHeight), -60.0, 60.0));- lit = lit + transmit * dens * ds * sunVisibility(p, found.tiles.x, found.tiles.y);+ lit = lit + transmit * dens * ds * sunVisibility(p, found.tiles.x, found.tiles.y) * shade;transmit = transmit * exp(-dens * ds);}let strength = clamp(found.color.a, 0.0, 8.0) * 0.5;diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.tsindex 5d3c3f9b8..2a6c6ecef 100644--- a/sdk/src/postprocess/volumeSystem.ts+++ b/sdk/src/postprocess/volumeSystem.ts@@ -11,6 +11,7 @@ import { blendVolumeEffects, computeVolumeFactor, type ActiveVolume, type Blendeimport type { ShaderHandle } from '../render/material';import { Material } from '../render/material';import { applyWeatherToEffects, currentWeather, currentWeatherDrive } from './weather';+import { applyCloudsToFog } from './cloudShafts';import { applyUnderwaterToEffects, currentUnderwater } from './underwater';import { applyTimeToEffects, currentTimeOfDay, currentTimeDrive, timeLightsApplied } from './timeOfDay';@@ -282,6 +283,7 @@ export const postProcessVolumeSystem = defineSystem(if (weather) applyWeatherToEffects(blended, weather, currentWeatherDrive());const clock = currentTimeOfDay();if (clock) applyTimeToEffects(blended, clock, currentTimeDrive(), timeLightsApplied());+ applyCloudsToFog(blended);// A camera under water: the effect the water module says it needs.applyUnderwaterToEffects(blended, currentUnderwater());diff --git a/sdk/tests/cloud-shafts.test.ts b/sdk/tests/cloud-shafts.test.tsnew file mode 100644index 000000000..67d413e22--- /dev/null+++ b/sdk/tests/cloud-shafts.test.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The fog's beams standing where the sky's clouds let the sun through: what the fog is told of the sky.+ */+import { describe, it, expect } from 'vitest';+import { applyCloudsToFog } from '../src/postprocess/cloudShafts';+import type { BlendedEffect } from '../src/postprocess/volumeBlending';+import '../src/postprocess/effects';++const effect = (uniforms: Record<string, number> = {}, enabled = true): BlendedEffect => ({+ enabled, uniforms: new Map(Object.entries(uniforms)), textures: new Map(), colors: new Map(),+});++describe('applyCloudsToFog', () => {+ it('copies the sky\'s cloud layer onto a fog that asks for cloud shafts, with the wind as a velocity in kilometres a second', () => {+ const fog = effect({ u_cloudShade: 0.8 });+ const sky = effect({ u_cloudShadow: 0.6, u_clouds: 0.4, u_overcast: 0.5, u_cloudBase: 2, u_cloudThickness: 3, u_unitsPerKm: 100000, u_windSpeed: 0.1, u_windDirection: 90 });+ applyCloudsToFog(new Map([['heightFog', fog], ['skyAtmosphere', sky]]));+ // An overcast of half is a cover of 0.475, above the sky's own 0.4.+ expect(fog.uniforms.get('u_skyCover')).toBeCloseTo(0.475, 6);+ expect(fog.uniforms.get('u_skyBase')).toBe(2);+ expect(fog.uniforms.get('u_skyThickness')).toBe(3);+ expect(fog.uniforms.get('u_skyUnits')).toBe(100000);+ expect(fog.uniforms.get('u_skySigma')).toBeCloseTo(1.3 * 1.75, 6);+ expect(fog.uniforms.get('u_skyWindX')).toBeCloseTo(0.1, 6);+ expect(fog.uniforms.get('u_skyWindZ')).toBeCloseTo(0, 6);+ });++ it('leaves the fog with no clouds without Cloud Shafts, a sky, or clouds that cast shadows', () => {+ const cases: [BlendedEffect, BlendedEffect | undefined][] = [+ [effect({ u_cloudShade: 0 }), effect({ u_cloudShadow: 0.6 })],+ [effect({ u_cloudShade: 1 }), undefined],+ [effect({ u_cloudShade: 1 }), effect({ u_cloudShadow: 0 })],+ [effect({ u_cloudShade: 1 }), effect({ u_cloudShadow: 0.6 }, false)],+ ];+ for (const [fog, sky] of cases) {+ applyCloudsToFog(new Map(sky ? [['heightFog', fog], ['skyAtmosphere', sky]] : [['heightFog', fog]]));+ expect(fog.uniforms.get('u_skyCover')).toBe(0);+ }+ });++ it('does nothing for a scene with no fog', () => {+ const sky = effect({ u_cloudShadow: 0.6 });+ expect(() => applyCloudsToFog(new Map([['skyAtmosphere', sky]]))).not.toThrow();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ad7ecb4e9..062fb03b3 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2838,6 +2838,8 @@ export const NOTED = {{"note":"A generated world's plants."},"fix(cook): a cutout texture has its colour carried into its clear texels, so a leaf has no pale edge":{"note":"A leaf or a blade of grass no longer has a pale edge."},+ "feat(fog): the fog's beams follow the clouds of the sky, so a gap in them is a shaft":+ {"note":"Light beams that follow the clouds."},"feat(water): two tiled, scrolling detail normal maps give the surface its sparkle":{"note":"Sparkle on the water."},"fix(lod): a LODGroup with only a cull size is no longer ignored":