Skip to content

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.

feat(water): a waterline across the lens, caustics, light shafts, and a mirror under the surface

yhh893a03a9b2a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 488bdb52c..0266c37fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Waterline, caustics, shafts and a mirror under the water.** Under water the picture is lit and bounded like water. A camera with its lens half in the water has a waterline across it, soft and sliding as it dips; what it sees is lit by the web of caustics the waves focus the sun into (the Water material's `u_causticStrength`, `u_causticScale` and `u_causticSpeed`, also drawn on what lies under the water seen from above); the water along each ray scatters the sun into shafts (`u_shaftStrength`); and the surface seen from below, past the critical angle, mirrors the world beneath it.
- **Underwater view.** A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window).
- **Floating bodies.** Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries.
- **Rivers and splines.** A WaterBody can be a river: put a Spline on its entity and it lays a ribbon along the curve, as wide as the curve says at each point and at its height, with a current (`flowSpeed`, faster where it narrows) that the shader carries the waves and ripples along and that `Waters.sample` reports as `flow`. Splines are a new optional module (`esengine/spline`): a curve through points with a width each, measured by the distance along it.
diff --git a/desktop b/desktop
index eabc5c63d..48d0bc660 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit eabc5c63dee90ec69a53a2e49f3099b481e0fa60
+Subproject commit 48d0bc66056519f7f067ad1d72dc5d95f1c3bc2a
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index 8070df6e7..97ed66ef2 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -104,12 +104,23 @@ and the post-process volume system adds an **Underwater** effect for as long as
through, `u_range`), and the water takes it out colour by colour, red first, by the same `u_absorption` and `u_density` the surface's material draws with, and gives back
its own colour. A white wall under water is blue-green, and a far one more than a near one.
- **Dimmer with depth.** The colour the water gives back dims with how far down the camera is (`u_lightFalloff`), as the light that reaches it comes from above.
-- **No pop.** The effect ramps in over the first stretch below the surface (half the wave height, at least one unit), so crossing it is a fade and not a cut.
+- **A waterline across the lens.** Each pixel is asked whether its place on the camera's near plane is below the surface at the camera, so a camera with its lens half in the water has
+ a dry upper half and a wet lower half with a soft line between them (`u_band`, a twelfth of the near plane), and crossing the surface is the line sliding up the lens and not a cut.
+ The effect is on from a couple of near planes above the surface down.
+- **The sun through the waves.** What the camera sees is lit by the web of bright threads the waves focus the sun into: the same pattern the surface draws from above (`u_causticStrength`,
+ `u_causticScale`, `u_causticSpeed` on the Water material, which the effect is given), on what faces the sun and is not in its shadow, less the further the sun's light went through
+ the water to reach it. It follows the first directional light, and its shadow map where there is one.
+- **Light shafts.** The water along each ray scatters the sun toward the camera: the pattern is marched along the ray in 24 steps, each lit where the shadow map says the sun reaches it
+ and as much as the water above it lets through, which is what makes shafts (`u_shaftStrength`, `u_shaftRange`). It costs 24 taps a pixel in the water.
- **Yours if you wrote it.** A scene that authors an `underwater` effect in a volume keeps its numbers; only the camera's depth and how wholly it is under are filled in.
The surface itself, seen from below, is turned over and light goes the other way through it: from out of the water rays past the critical angle (about 49 degrees) are reflected
whole, so the water above is a window of sky overhead in a mirror, and the Fresnel term follows. The window's edge is not drawn as a circle on its own: it is where the
-refraction runs out.
+refraction runs out. What the mirror shows is the world below it: the reflected ray is followed through the picture of the scene the frame copied (20 steps, growing), and the colour of
+what it meets is what the water reflects, so a box on the bottom appears in the surface above it. Where the ray meets nothing on screen the mirror is the water's own dark colour.
+
+Seen from above, the same caustics light what is under the water through the surface: the Water shader finds where the refracted ray ends, where the sun's ray to that place crossed the
+surface, and lights it by the pattern there (and by the shadow map), so the web bends with the ripples that refract it.
## Splines
@@ -150,6 +161,8 @@ differ by the short waves, which are small.
default (0) the waves are measured on the world's xz plane, nothing is lifted and the surface is taken to lie flat. The component turns it to 1 (the
mesh's uv is its local x and z) for the body's own space.
+- **Caustics.** `u_causticStrength` (0 turns them off), `u_causticScale` (the size of one cell, in world units) and `u_causticSpeed` shape the web of light on what is under the water, seen from
+ above and, through the effect, from below.
- **Waves.** `u_waveLength`, `u_waveHeight`, `u_waveSpeed`, `u_waveDirection`; small ripples (`u_rippleStrength`, `u_rippleLength`) ride on them and
fade out with distance, so far water is calm rather than aliased.
- **Refraction and depth.** What is under the water is the picture of the opaque scene, shifted by the waves in proportion to how much water there
@@ -172,7 +185,9 @@ What is not there yet, so nobody is surprised:
- A river does not carve the ground, rapids and falls are not foamed by how fast or steep the water runs, and two bodies do not blend where they meet.
A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die toward the shore without breaking on it.
- Things float (see [Floating](#floating)); nothing swims yet, and a body in the water makes no ripple or wake.
-- Under the surface there is fog and tint but no light: no caustics on what lies below, no shafts of sun through the surface, and the surface seen from below mirrors the fog, not the
- water's own picture of itself. Each camera is under or not as a whole: there is no waterline across the lens.
+- Caustics and shafts follow the first directional light only, from a pattern and not a simulation: the web does not respond to the actual shape of the waves. From above the caustics
+ take what is under the water to face up (the picture holds no normals there), so a wall under the surface is lit as a floor would be.
+- The mirror from below is screen-space: it shows only what the frame has on screen, and a ray that leaves the picture or meets nothing finds the water's own colour.
+- The body of water a camera is under is the first the surface query finds at the camera's place: a camera under two overlapping bodies takes the numbers of the first.
- It does not react to what moves through it: no ripples, no wake.
- The waves are the four peaked sines, not a spectrum, and they lift the surface without pushing it sideways.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
index 913c3f9bd..9ef3fdec1 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -72,10 +72,14 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- **按穿过的水雾化。** 每个像素的光穿过了从眼睛到它出处的距离(天空没有表面,取水能被看穿的最长距离 `u_range`),水按颜色把光吸走,红色最先,用的是和水面材质绘制时相同的 `u_absorption` 和 `u_density`,再还给你它自己的颜色。水下一面白墙是蓝绿色的,远的比近的更甚。
- **越深越暗。** 水还回来的颜色随相机下沉的深度变暗(`u_lightFalloff`),因为到达它那里的光来自上方。
-- **没有突变。** 效果在水面以下的第一段距离里渐入(波高的一半,至少一个单位),所以穿过水面是淡入而不是硬切。
+- **横过镜头的水线。** 每个像素都会被问:它在相机近平面上的位置,是不是在相机所在处的水面之下。所以镜头一半在水里的相机,上半是干的、下半是湿的,中间有一条柔和的线(`u_band`,近平面的十二分之一),穿过水面就是这条线在镜头上滑过,而不是硬切。从水面上方几个近平面的距离起,效果就开始作用。
+- **穿过波浪的阳光。** 相机看到的东西,被波浪把阳光聚成的那张明亮细线网照亮:和水面从上往下画的是同一个图案(Water 材质上的 `u_causticStrength`、`u_causticScale`、`u_causticSpeed`,效果也会拿到),落在朝向太阳且不在它的阴影里的表面上,阳光穿过水到达那里走得越远就越弱。它跟随第一盏平行光,有阴影图时也用阴影图。
+- **光束。** 沿每条视线的水把阳光散射向相机:图案沿视线分 24 步行进,每一步在阴影图说阳光能到达的地方才亮,并且按它上面的水能放过多少光来衰减,这就是光束(`u_shaftStrength`、`u_shaftRange`)。它在水里每个像素花 24 次采样。
- **你写了就用你的。** 在体积里自己写了 `underwater` 效果的场景,保留它的数值;只会填入相机的深度和它完全没入的程度。
-水面本身从下面看是翻过来的,光穿过它的方向也反了:从水里出来,超过临界角(约 49 度)的光线被整个反射,所以上面的水是头顶一扇天空的窗户,窗户之外是水下世界的镜子,菲涅尔项也随之改变。窗户的边缘并不是自己画出来的圆:它就是折射走到尽头的地方。
+水面本身从下面看是翻过来的,光穿过它的方向也反了:从水里出来,超过临界角(约 49 度)的光线被整个反射,所以上面的水是头顶一扇天空的窗户,窗户之外是水下世界的镜子,菲涅尔项也随之改变。窗户的边缘并不是自己画出来的圆:它就是折射走到尽头的地方。镜子里映的是它下面的世界:反射光线沿着帧复制出来的场景画面一路走(20 步,步长递增),它碰到的东西的颜色就是水反射的颜色,所以水底的一个盒子会出现在它上面的水面里。光线在屏幕上没碰到任何东西的地方,镜子就是水自己的暗色。
+
+从上面看,同样的焦散会穿过水面照亮水下的东西:Water 着色器找出折射光线在哪里结束、到那里的阳光光线在哪里穿过水面,再按那里的图案(以及阴影图)给它打光,所以这张网会随折射它的涟漪一起弯曲。
## 样条
@@ -109,6 +113,7 @@ curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在
`builtin:water` 也可以单独用在任何网格上,这是组件出现之前做一块平水面的方式。`u_waveSpace` 取默认值(0)时,波浪按世界的 xz 平面度量,什么也不抬起,表面被当作是平的。组件把它设为 1(网格的 uv 是它的局部 x 和 z),使用水体自己的空间。
+- **焦散。** `u_causticStrength`(0 关掉它)、`u_causticScale`(一格的大小,世界单位)和 `u_causticSpeed` 决定水下东西上那张光网的样子,从上面看是这样,通过效果从下面看也是这样。
- **波浪。** `u_waveLength`、`u_waveHeight`、`u_waveSpeed`、`u_waveDirection`;小涟漪(`u_rippleStrength`、`u_rippleLength`)骑在它们上面,并随距离淡出,所以远处的水是平静的而不是闪烁的。
- **折射与水深。** 水下看到的是不透明场景的画面,被波浪按水量多少偏移。水深是**量出来的**:绘制水之前,帧会拷贝一份场景每个像素离眼睛多远,水在某个像素处的深度就是那个距离与水面自己的距离之差。光沿着这段水柱被吸收——红色最先(`u_absorption`、`u_density`)——水再还给你它自己的颜色,随水变深从 `u_shallowColor` 过渡到 `u_deepColor`。
- **反射。** 天空、灯光和环境按菲涅尔项反射(水是 1.333),所以俯视时清澈、掠射时像镜子。想要场景本身的倒影,在体积里加上屏幕空间反射。
@@ -122,6 +127,8 @@ curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在
- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫,两个水体相接处也不会融合。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
- 东西可以漂浮(见[漂浮](#漂浮));还没有东西能游泳,水里的物体也不会激起涟漪或尾迹。
-- 水下有雾和染色,但没有光:水下的物体上没有焦散,没有穿过水面的阳光束,从下面看水面时镜子里映的是雾,而不是水自己的画面。相机整个在水下或整个不在:镜头上没有横过的水线。
+- 焦散和光束只跟随第一盏平行光,来自一个图案而不是模拟:这张网并不响应波浪的真实形状。从上面看时,焦散把水下的东西当作朝上的面(画面里那里没有法线),所以水面下的一面墙会像地板一样被照亮。
+- 从下面看的镜子是屏幕空间的:它只显示帧里在屏幕上的东西,射线离开画面或什么也没碰到时,找到的是水自己的颜色。
+- 相机所在的水体,是水面查询在相机所在处找到的第一个:同时在两个重叠水体之下的相机,用的是第一个的数值。
- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。
- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。
diff --git a/sdk/src/postprocess/underwater.ts b/sdk/src/postprocess/underwater.ts
index 33fd1d9b0..420ca61f5 100644
--- a/sdk/src/postprocess/underwater.ts
+++ b/sdk/src/postprocess/underwater.ts
@@ -26,6 +26,14 @@ export interface UnderwaterState {
density: number;
/** The colour the water gives back, at the camera's depth, before the light fades with depth. */
scatter: [number, number, number];
+ /** The surface at the camera: its normal (out of the water) and the offset along it (`dot(normal, p) = offset` on the surface). A pixel is under water where its place on the camera's near plane is. */
+ plane: [number, number, number, number];
+ /** How soft the waterline across the lens is, in world units. */
+ band: number;
+ /** The Water material's caustics, so the light the camera sees is the light the surface draws. */
+ causticStrength: number;
+ causticScale: number;
+ causticSpeed: number;
}
let current: UnderwaterState | null = null;
@@ -58,16 +66,23 @@ export function applyUnderwaterToEffects(effects: Map<string, BlendedEffect>, st
effect.colors.set('u_absorption', colour(state.absorption));
effect.colors.set('u_scatterColor', colour(state.scatter));
effect.uniforms.set('u_density', state.density);
+ effect.uniforms.set('u_causticStrength', state.causticStrength);
+ effect.uniforms.set('u_causticScale', state.causticScale);
+ effect.uniforms.set('u_causticSpeed', state.causticSpeed);
}
effect.uniforms.set('u_amount', Math.min(Math.max(state.amount, 0), 1) * (effect.uniforms.get('u_amount') ?? 1));
effect.uniforms.set('u_cameraDepth', state.depth);
+ effect.uniforms.set('u_planeNx', state.plane[0]);
+ effect.uniforms.set('u_planeNy', state.plane[1]);
+ effect.uniforms.set('u_planeNz', state.plane[2]);
+ effect.uniforms.set('u_planeD', state.plane[3]);
+ effect.uniforms.set('u_band', state.band);
}
/**
- * How wholly a camera `depth` under a surface is under it: 0 at the surface, 1 from `fade` down. `depth` is positive under the surface; a camera above it
- * is not under it at all.
+ * How far above a surface a camera may be and still have part of its lens under it: its near plane reaches this far ahead of it, and a camera looking down
+ * puts the lower edge of that plane below it. Past this the whole lens is in the air.
*/
-export function submersion(depth: number, fade: number): number {
- if (!(depth > 0)) return 0;
- return Math.min(depth / Math.max(fade, 1e-6), 1);
+export function lensReach(nearPlane: number): number {
+ return Math.max(nearPlane, 0) * 2.5;
}
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index f4a0001a7..d0503d97a 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -12,6 +12,7 @@
*/
import { paramDefaultValue, reflectEsshader } from './shaderReflect';
+import { CAUSTICS_GLSL, CAUSTICS_WGSL } from './waterCaustics';
export interface BuiltinShaderTemplate {
id: string;
@@ -745,6 +746,11 @@ const WATER = `#pragma shader "Water"
#pragma param u_flowCycle float default(2) range(0.2,20) ui(slider)
// How much of the waves lifts the geometry: 1 for a lake or an ocean, 0 for a river, whose surface is drawn flat and moved only in the shading.
#pragma param u_geoWaves float default(1) range(0,1) ui(slider)
+// The net of light the waves throw on what is under the water: how strong it is, how large one cell of it is (world units), and how fast it swims. The Underwater
+// effect draws the same one from below, with these numbers, so the two halves of the picture agree.
+#pragma param u_causticStrength float default(0.6) range(0,3) ui(slider)
+#pragma param u_causticScale float default(2) range(0.05,2000) ui(slider)
+#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)
#pragma param u_sceneColor texture default(white)
#pragma param u_sceneDepthMap texture default(white) texel(data)
@@ -871,6 +877,66 @@ vec2 waveSlope(vec2 p, float time, float dist, out float crest) {
return slope;
}
+${CAUSTICS_GLSL}
+/// The first directional light that shines: xyz is where it stands in the sky, w 1 if there is one, color its colour and strength, tiles its place in the shadow atlas.
+void waterSun(out vec4 dir, out vec4 color, out ivec2 tiles) {
+ dir = vec4(0.0);
+ color = vec4(0.0);
+ tiles = ivec2(0);
+ for (int i = 0; i < 16; ++i) {
+ Light l = u_lights[i];
+ if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {
+ dir = vec4(-normalize(vec3(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);
+ color = l.color;
+ tiles = ivec2(int(l.shadowMap.x), int(l.shadowMap.y));
+ return;
+ }
+ }
+}
+
+/// Whether the sun reaches a point: one tap of the shadow map, 1 where there is none.
+float waterSunVisibility(vec3 worldPos, int first, int count) {
+#ifdef ES_RECEIVE_SHADOW
+ if (u_shadowParams.x < 0.5 || count <= 0) return 1.0;
+ for (int k = 0; k < 16; ++k) {
+ if (k >= count) break;
+ int t = first + k;
+ vec4 c = u_shadowMatrix[t] * vec4(worldPos, 1.0);
+ if (c.w <= 0.0) continue;
+ vec3 proj = c.xyz / c.w;
+ vec2 uv = proj.xy * 0.5 + 0.5;
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) continue;
+ vec4 rect = u_shadowTile[t];
+ vec2 at = rect.xy + uv * rect.z;
+ vec2 lo = rect.xy + u_shadowParams.y * 0.5;
+ vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;
+ float d = unpackDepth(textureLod(u_shadowMap, clamp(at, lo, hi), 0.0).rgb);
+ return d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025 ? 0.0 : 1.0;
+ }
+#endif
+ return 1.0;
+}
+
+/// What a ray from p along r meets in the picture of the scene the frame copied, as a colour with alpha 1, or alpha 0 where it meets nothing on screen.
+vec4 waterReflect(vec3 p, vec3 r, float eyeDist) {
+ float stride = max(0.5, eyeDist * 0.03);
+ float travelled = stride;
+ for (int i = 0; i < 20; ++i) {
+ vec3 q = p + r * travelled;
+ vec4 clip = u_projection * vec4(q, 1.0);
+ if (clip.w <= 1e-4) break;
+ vec2 uv = clip.xy / clip.w * 0.5 + 0.5;
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) break;
+ float qDist = u_camera.w > 0.5 ? length(q - u_camera.xyz) : -dot(q, u_camera.xyz);
+ float sceneDist = textureLod(u_sceneDepthMap, uv, 0.0).r;
+ // The ray has gone behind something the picture holds: that is what it met, if it did not skip clean through a thin one.
+ if (sceneDist < qDist && qDist - sceneDist < stride * 2.0 + 1.0) return vec4(textureLod(u_sceneColor, uv, 0.0).rgb, 1.0);
+ stride *= 1.25;
+ travelled += stride;
+ }
+ return vec4(0.0);
+}
+
/// The slope of the surface at p and how near it is to a crest: the waves, and the ripples they carry, flattened with distance.
vec2 waterSurface(vec2 p, float time, float dist, out float crest) {
vec2 slope = waveSlope(p, time, dist, crest);
@@ -958,6 +1024,21 @@ void main() {
if (dist1 < waterDist) { uv1 = clamp(uv0, vec2(0.001), vec2(0.999)); dist1 = behindDist; }
behind = texture(u_sceneColor, uv1).rgb;
column = max(dist1 - waterDist, 0.0);
+ // The sun through the waves lights what is under them in a web of bright threads, where the sun reaches it and as much as the water between lets through.
+ if (!below && haveDepth && u_causticStrength > 0.0) {
+ vec4 sunDir, sunColor;
+ ivec2 sunTiles;
+ waterSun(sunDir, sunColor, sunTiles);
+ float cosUp = dot(sunDir.xyz, Ngeo);
+ if (sunDir.w > 0.5 && cosUp > 0.05) {
+ vec3 seabed = P + bentWave * column;
+ float depthBelow = max(dot(P - seabed, Ngeo), 0.0);
+ vec3 onSurface = seabed + sunDir.xyz * (depthBelow / max(cosUp, 0.15));
+ float c = causticPattern(onSurface.xz / u_causticScale, time * u_causticSpeed);
+ float reachSun = exp(-dot(u_absorption.rgb, vec3(1.0 / 3.0)) * u_density * depthBelow / max(cosUp, 0.15));
+ behind *= 1.0 + u_causticStrength * c * cosUp * waterSunVisibility(seabed, sunTiles.x, sunTiles.y) * reachSun * min(sunColor.a, 2.0) * 0.5;
+ }
+ }
}
// The water in between takes the light out of it, red first, and gives back its own colour: more of it the deeper it goes.
@@ -994,6 +1075,13 @@ void main() {
fresnel = sinT >= 1.0 ? 1.0 : 0.0204 + (1.0 - 0.0204) * pow(1.0 - cosT, 5.0);
}
vec3 seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
+ // From below the water is a mirror past the critical angle, and what it mirrors is the world under it: the picture, followed along the reflected ray.
+ vec3 mirror = vec3(0.0);
+ if (below && fresnel > 0.02 && haveColor && haveDepth) {
+ vec4 met = waterReflect(P, reflect(-viewDir, N), waterDist);
+ mirror = met.a > 0.5 ? met.rgb : mix(u_shallowColor.rgb, u_deepColor.rgb, 0.5) * 0.25;
+ }
+ seen += mirror * fresnel * (1.0 - foam);
// Outside the lake's outline there is no water.
if (u_shoreOn > 0.5 && shoreDist < 0.0) discard;
fragColor = vec4(lit + seen, haveColor ? 1.0 : 0.85);
@@ -1064,6 +1152,67 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
return out;
}
+${CAUSTICS_WGSL}
+struct WaterSun { dir : vec4f, color : vec4f, tiles : vec2i };
+/// The first directional light that shines: dir.xyz is where it stands in the sky, dir.w 1 if there is one.
+fn waterSun() -> WaterSun {
+ var s : WaterSun;
+ s.dir = vec4f(0.0);
+ s.color = vec4f(0.0);
+ s.tiles = vec2i(0, 0);
+ for (var i = 0; i < 16; i++) {
+ let l = lc.u_lights[i];
+ if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {
+ s.dir = vec4f(-normalize(vec3f(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);
+ s.color = l.color;
+ s.tiles = vec2i(i32(l.shadowMap.x), i32(l.shadowMap.y));
+ return s;
+ }
+ }
+ return s;
+}
+
+fn waterSunVisibility(worldPos : vec3f, first : i32, count : i32) -> f32 {
+ if (lc.u_shadowParams.x < 0.5 || count <= 0) { return 1.0; }
+ for (var k = 0; k < 16; k++) {
+ if (k >= count) { break; }
+ let t = first + k;
+ let c = lc.u_shadowMatrix[t] * vec4f(worldPos, 1.0);
+ if (c.w <= 0.0) { continue; }
+ let proj = c.xyz / c.w;
+ let uv = proj.xy * 0.5 + 0.5;
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) { continue; }
+ let rect = lc.u_shadowTile[t];
+ let base = vec2f(rect.x, 1.0 - rect.y - rect.z);
+ let at = base + vec2f(uv.x, 1.0 - uv.y) * rect.z;
+ let lo = base + lc.u_shadowParams.y * 0.5;
+ let hi = base + rect.z - lc.u_shadowParams.y * 0.5;
+ let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);
+ return select(1.0, 0.0, d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025);
+ }
+ return 1.0;
+}
+
+/// What a ray from p along r meets in the picture of the scene the frame copied: the colour (xyz) and 1 (w), or w 0 where it meets nothing on screen.
+fn waterReflect(p : vec3f, r : vec3f, eyeDist : f32) -> vec4f {
+ var stride = max(0.5, eyeDist * 0.03);
+ var travelled = stride;
+ for (var i = 0; i < 20; i++) {
+ let q = p + r * travelled;
+ let clip = frame.projection * vec4f(q, 1.0);
+ if (clip.w <= 1e-4) { break; }
+ let uv = vec2f(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5);
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { break; }
+ var qDist = -dot(q, frame.camera.xyz);
+ if (frame.camera.w > 0.5) { qDist = length(q - frame.camera.xyz); }
+ let sceneDist = textureSampleLevel(u_sceneDepthMap, u_sceneDepthMap_s, uv, 0.0).r;
+ if (sceneDist < qDist && qDist - sceneDist < stride * 2.0 + 1.0) { return vec4f(textureSampleLevel(u_sceneColor, u_sceneColor_s, uv, 0.0).rgb, 1.0); }
+ stride = stride * 1.25;
+ travelled = travelled + stride;
+ }
+ return vec4f(0.0);
+}
+
/// The slope of the surface at p (x, y) and how near it is to a crest (z): the waves, and the ripples they carry, flattened with distance.
fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
let waves = waveSlope(p, time, dist);
@@ -1156,6 +1305,18 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
if (dist1 < waterDist) { uv1 = clamp(uv0, vec2f(0.001), vec2f(0.999)); dist1 = behindDist; }
behind = textureSampleLevel(u_sceneColor, u_sceneColor_s, uv1, 0.0).rgb;
column = max(dist1 - waterDist, 0.0);
+ if (!below && haveDepth && mc.u_causticStrength > 0.0) {
+ let sun = waterSun();
+ let cosUp = dot(sun.dir.xyz, Ngeo);
+ if (sun.dir.w > 0.5 && cosUp > 0.05) {
+ let seabed = P + bentWave * column;
+ let depthBelow = max(dot(P - seabed, Ngeo), 0.0);
+ let onSurface = seabed + sun.dir.xyz * (depthBelow / max(cosUp, 0.15));
+ let c = causticPattern(onSurface.xz / mc.u_causticScale, time * mc.u_causticSpeed);
+ let reachSun = exp(-dot(mc.u_absorption.rgb, vec3f(1.0 / 3.0)) * mc.u_density * depthBelow / max(cosUp, 0.15));
+ behind = behind * (1.0 + mc.u_causticStrength * c * cosUp * waterSunVisibility(seabed, sun.tiles.x, sun.tiles.y) * reachSun * min(sun.color.a, 2.0) * 0.5);
+ }
+ }
}
var transmit = exp(-mc.u_absorption.rgb * (mc.u_density * column));
@@ -1188,7 +1349,13 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
let cosT = sqrt(max(1.0 - sinT * sinT, 0.0));
if (sinT >= 1.0) { fresnel = 1.0; } else { fresnel = 0.0204 + (1.0 - 0.0204) * pow(1.0 - cosT, 5.0); }
}
- let seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
+ var seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
+ var mirror = vec3f(0.0);
+ if (below && fresnel > 0.02 && haveColor && haveDepth) {
+ let met = waterReflect(P, reflect(-viewDir, N), waterDist);
+ if (met.w > 0.5) { mirror = met.xyz; } else { mirror = mix(mc.u_shallowColor.rgb, mc.u_deepColor.rgb, vec3f(0.5)) * 0.25; }
+ }
+ seen = seen + mirror * fresnel * (1.0 - foam);
var alpha = 0.85;
if (haveColor) { alpha = 1.0; }
if (mc.u_shoreOn > 0.5 && shoreDist < 0.0) { discard; }
diff --git a/sdk/src/render/waterCaustics.ts b/sdk/src/render/waterCaustics.ts
new file mode 100644
index 000000000..69c86b15d
--- /dev/null
+++ b/sdk/src/render/waterCaustics.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waterCaustics.ts
+ * @brief The net of light a rippled surface throws on what is under it, as one pattern the Water shader and the Underwater effect both draw.
+ *
+ * @details A wave focuses the sun where its surface curves like a lens, and the light on the bottom is a web of bright threads on a darker ground that
+ * swims as the waves move. This is not a simulation of that: it is the picture of it, made from two fields of value noise drifting past each
+ * other at three scales. Where the two fields are equal is a bright thread, and the threads of the three scales laid over one another make
+ * the web. It needs only a position on the surface and the time, so the same pattern is found wherever it is asked, from above the water through
+ * the surface (the Water shader, lighting what it refracts) and from below it (the Underwater effect, lighting what the camera sees and the
+ * light it walks through).
+ *
+ * The pattern is written once per shading language and placed in each shader's source; the scale, the speed and the strength are the
+ * Water material's, and the Underwater effect is given the same ones, so the two halves agree about what the light is doing.
+ */
+
+/** GLSL: `causticPattern(p, t)`, 0 to 1, p in world units of the surface divided by the pattern's scale. */
+export const CAUSTICS_GLSL = `float causticHash(vec2 p) {
+ p = fract(p * vec2(0.1031, 0.1030));
+ p += dot(p, p.yx + 33.33);
+ return fract((p.x + p.y) * p.x);
+}
+float causticNoise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(causticHash(i), causticHash(i + vec2(1.0, 0.0)), f.x),
+ mix(causticHash(i + vec2(0.0, 1.0)), causticHash(i + vec2(1.0, 1.0)), f.x), f.y);
+}
+float causticPattern(vec2 p, float t) {
+ float sum = 0.0;
+ float weight = 1.0;
+ float norm = 0.0;
+ for (int i = 0; i < 3; ++i) {
+ float s = exp2(float(i));
+ float a = causticNoise(p * s + vec2(0.31, 0.12) * t * (1.0 + 0.3 * float(i)) + 7.0 * float(i));
+ float b = causticNoise(p * s * 1.37 - vec2(0.17, 0.4) * t * (1.0 + 0.2 * float(i)) + 31.0 * float(i));
+ float thread = max(1.0 - abs(a - b) * 3.2, 0.0);
+ sum += weight * thread * thread * thread * thread;
+ norm += weight;
+ weight *= 0.55;
+ }
+ return clamp(sum / norm * 2.2, 0.0, 1.0);
+}
+`;
+
+/** WGSL: the same. */
+export const CAUSTICS_WGSL = `fn causticHash(p0 : vec2f) -> f32 {
+ var p = fract(p0 * vec2f(0.1031, 0.1030));
+ p = p + dot(p, p.yx + 33.33);
+ return fract((p.x + p.y) * p.x);
+}
+fn causticNoise(p : vec2f) -> f32 {
+ let i = floor(p);
+ var f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(causticHash(i), causticHash(i + vec2f(1.0, 0.0)), f.x),
+ mix(causticHash(i + vec2f(0.0, 1.0)), causticHash(i + vec2f(1.0, 1.0)), f.x), f.y);
+}
+fn causticPattern(p : vec2f, t : f32) -> f32 {
+ var sum = 0.0;
+ var weight = 1.0;
+ var norm = 0.0;
+ for (var i : i32 = 0; i < 3; i = i + 1) {
+ let fi = f32(i);
+ let s = exp2(fi);
+ let a = causticNoise(p * s + vec2f(0.31, 0.12) * t * (1.0 + 0.3 * fi) + 7.0 * fi);
+ let b = causticNoise(p * s * 1.37 - vec2f(0.17, 0.4) * t * (1.0 + 0.2 * fi) + 31.0 * fi);
+ let thread = max(1.0 - abs(a - b) * 3.2, 0.0);
+ sum = sum + weight * thread * thread * thread * thread;
+ norm = norm + weight;
+ weight = weight * 0.55;
+ }
+ return clamp(sum / norm * 2.2, 0.0, 1.0);
+}
+`;
diff --git a/sdk/src/water/underwater.ts b/sdk/src/water/underwater.ts
index 95c0a64f6..db4c107ab 100644
--- a/sdk/src/water/underwater.ts
+++ b/sdk/src/water/underwater.ts
@@ -2,20 +2,28 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file underwater.ts
- * @brief Seeing from under the water: the effect that fogs the world by how much water the light has crossed, and the system that says when.
+ * @brief Seeing from under the water: the effect that fogs the world by how much water the light crossed, lights it with the sun through the waves, and the system that says when.
*
* @details The effect is the water's own: its definition and shader are registered here, with the rest of the water module, so a build with no water carries
- * none of it. Every pixel's light has crossed the distance from the eye to what it came from (the far range for the sky), and the
- * water takes it out colour by colour (red first: the same absorption and density the surface's material draws with) and gives back its own
- * colour, which dims with the camera's depth. The system reads the camera's place in the water from {@link Waters.sample} each frame
- * and tells the post-process volume system (see postprocess/underwater.ts), which adds the effect for as long as the camera is under.
+ * none of it. For each pixel it asks whether the pixel's place on the camera's near plane is under the surface (so a lens half in the water
+ * has a waterline across it, soft by `u_band`), and for those that are:
+ * - the light has crossed the distance from the eye to what it came from (the longest the water is seen through for the sky), and
+ * the water takes it out colour by colour (red first: the same absorption and density the surface's material draws with) and gives back
+ * its own colour, which dims with the camera's depth;
+ * - what the camera sees is lit by the sun through the waves: a web of bright threads on what faces the sun and is not in shadow, from the
+ * pattern the surface draws (render/waterCaustics.ts), less the further the sun's light went through the water to reach it;
+ * - and the water between the camera and what it sees scatters the sun toward it: the same pattern marched along the ray, 24 steps, each
+ * step in light where the shadow map says the sun reaches it, which is what makes shafts.
+ * The system reads the camera's place in the water from {@link Waters.sample} each frame and tells the post-process volume system (see
+ * postprocess/underwater.ts), which adds the effect for as long as the camera is under.
*/
import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
import { Camera, Transform, type CameraData, type TransformData } from '../ecs/component';
import { Material } from '../render/material';
+import { CAUSTICS_GLSL, CAUSTICS_WGSL } from '../render/waterCaustics';
import { registerEffect } from '../postprocess/effects';
-import { setUnderwaterState, submersion } from '../postprocess/underwater';
+import { setUnderwaterState, lensReach } from '../postprocess/underwater';
import { WatersRes } from './waterPlugin';
const SOURCE = `#pragma shader "PP Underwater"
@@ -28,6 +36,17 @@ const SOURCE = `#pragma shader "PP Underwater"
#pragma param u_cameraDepth float default(0) range(0,100000)
#pragma param u_lightFalloff float default(0.004) range(0,1)
#pragma param u_range float default(4000) range(10,100000)
+#pragma param u_planeNx float default(0) range(-1,1)
+#pragma param u_planeNy float default(1) range(-1,1)
+#pragma param u_planeNz float default(0) range(-1,1)
+#pragma param u_planeD float default(0) range(-1000000,1000000)
+#pragma param u_band float default(0.25) range(0,1000)
+#pragma param u_causticStrength float default(0.6) range(0,3)
+#pragma param u_causticScale float default(2) range(0.05,2000)
+#pragma param u_causticSpeed float default(0.35) range(0,4)
+#pragma param u_shaftStrength float default(0.5) range(0,4)
+#pragma param u_shaftRange float default(2000) range(10,100000)
+#pragma lights
#pragma fragment
precision highp float;
@@ -37,47 +56,167 @@ uniform sampler2D u_texture;
uniform highp sampler2D u_sceneDepth;
out vec4 fragColor;
+const int SHAFT_STEPS = 24;
+
+${CAUSTICS_GLSL}
+float ign(vec2 p) {
+ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));
+}
+/// How much of a ray's light a particle scatters toward the viewer: forward, the way water glows around the sun.
+float phaseHG(float cosine) {
+ const float g = 0.55;
+ return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;
+}
+
void main() {
vec4 src = texture(u_texture, v_texCoord);
- float depth = texelFetch(u_sceneDepth, ivec2(gl_FragCoord.xy), 0).r;
- // How much water the light of this pixel has crossed: the distance from the eye to the surface it came off, and for the sky (no surface) the longest
- // the water is seen through.
- float dist = u_range;
- if (depth < 1.0) {
- vec3 world = worldFromDepth(v_texCoord, depth);
- vec3 entry = worldFromDepth(v_texCoord, 0.0);
- dist = min(length(world - entry), u_range);
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ float depth = texelFetch(u_sceneDepth, clamp(ivec2(v_texCoord * vec2(size)), ivec2(0), size - ivec2(1)), 0).r;
+ bool sky = depth >= 1.0;
+ vec3 entry = worldFromDepth(v_texCoord, 0.0);
+ vec3 target = worldFromDepth(v_texCoord, sky ? 1.0 : depth);
+ // The face of what is seen, from how the picture's own world positions change from one pixel to the next (taken here, before any branch).
+ vec3 facing = cross(dFdx(target), dFdy(target));
+
+ // The waterline: this pixel is under water where its place on the camera's near plane is below the surface at the camera.
+ vec3 up = normalize(vec3(u_planeNx, u_planeNy, u_planeNz));
+ float wet = smoothstep(-u_band, u_band, u_planeD - dot(up, entry));
+ if (wet <= 0.0 || u_amount <= 0.0) { fragColor = src; return; }
+
+ vec3 dir = normalize(target - entry);
+ float len = sky ? u_range : min(length(target - entry), u_range);
+ vec3 transmit = exp(-u_absorption.rgb * (u_density * len));
+ float extinction = max(dot(u_absorption.rgb, vec3(1.0 / 3.0)) * u_density, 1e-5);
+
+ vec4 sunDir, sunColor;
+ ivec2 tiles;
+ findSun(sunDir, sunColor, tiles);
+ float cosUp = dot(sunDir.xyz, up);
+ bool sunny = sunDir.w > 0.5 && cosUp > 0.05;
+ float slant = max(cosUp, 0.15);
+ float clock = u_time.x * u_causticSpeed;
+
+ // What the camera sees, lit by the sun through the waves: a web of bright threads on what faces the sun, where the sun reaches it.
+ vec3 colour = src.rgb;
+ if (!sky && sunny && u_causticStrength > 0.0) {
+ vec3 normal = normalize(facing);
+ if (dot(normal, dir) > 0.0) normal = -normal;
+ float below = max(u_planeD - dot(up, target), 0.0);
+ vec3 onSurface = target + sunDir.xyz * (below / slant);
+ float web = causticPattern(onSurface.xz / u_causticScale, clock);
+ float reach = exp(-extinction * below / slant);
+ colour *= 1.0 + u_causticStrength * web * max(dot(normal, sunDir.xyz), 0.0) * sunVisibility(target, tiles.x, tiles.y) * reach * min(sunColor.a, 2.0) * 0.5;
}
- vec3 transmit = exp(-u_absorption.rgb * (u_density * dist));
+
// The water gives back its own colour, less of it the deeper the camera is: the light it scatters is what reached it from above.
vec3 scatter = u_scatterColor.rgb;
#ifdef ES_LINEAR
scatter = srgbToLinear(scatter);
#endif
scatter *= exp(-u_lightFalloff * u_cameraDepth);
- vec3 col = src.rgb * transmit + scatter * (1.0 - dot(transmit, vec3(1.0 / 3.0)));
- fragColor = vec4(mix(src.rgb, col, u_amount), src.a);
+ vec3 col = colour * transmit + scatter * (1.0 - dot(transmit, vec3(1.0 / 3.0)));
+
+ // Shafts: the sun scattered toward the eye by the water along the ray, wherever the shadow map says it gets in and in the pattern the waves throw.
+ if (sunny && u_shaftStrength > 0.0) {
+ float span = min(len, u_shaftRange);
+ float ds = span / float(SHAFT_STEPS);
+ float jitter = ign(gl_FragCoord.xy);
+ float through = 1.0;
+ float lit = 0.0;
+ for (int i = 0; i < SHAFT_STEPS; ++i) {
+ vec3 p = entry + dir * ((float(i) + jitter) * ds);
+ float below = u_planeD - dot(up, p);
+ if (below > 0.0) {
+ vec3 onSurface = p + sunDir.xyz * (below / slant);
+ float shaft = mix(1.0, min(causticPattern(onSurface.xz / u_causticScale, clock) * 1.6, 1.0), 0.7);
+ lit += through * ds * sunVisibility(p, tiles.x, tiles.y) * exp(-extinction * below / slant) * shaft;
+ }
+ through *= exp(-extinction * ds);
+ }
+ vec3 sunTint = sunColor.rgb / max(max(sunColor.r, sunColor.g), max(sunColor.b, 1e-3));
+ col += sunTint * lit * extinction * 0.5 * phaseHG(dot(dir, sunDir.xyz)) * u_shaftStrength * clamp(sunColor.a, 0.0, 8.0) * 8.0;
+ }
+ fragColor = vec4(mix(src.rgb, col, u_amount * wet), src.a);
}
#pragma end
#pragma fragment wgsl
+const SHAFT_STEPS : i32 = 24;
+
+${CAUSTICS_WGSL}
+fn ign(p : vec2f) -> f32 {
+ return fract(52.9829189 * fract(dot(p, vec2f(0.06711056, 0.00583715))));
+}
+fn phaseHG(cosine : f32) -> f32 {
+ let g = 0.55;
+ return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;
+}
+
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
- let depth = textureLoad(t7, vec2i(v.pos.xy), 0);
- var dist = mc.u_range;
- if (depth < 1.0) {
- let world = worldFromDepth(v.v_texCoord, depth);
- let entry = worldFromDepth(v.v_texCoord, 0.0);
- dist = min(length(world - entry), mc.u_range);
+ let size = vec2i(textureDimensions(t7, 0));
+ let depth = textureLoad(t7, clamp(vec2i(v.v_texCoord * vec2f(size)), vec2i(0), size - vec2i(1)), 0);
+ let sky = depth >= 1.0;
+ let entry = worldFromDepth(v.v_texCoord, 0.0);
+ var d = depth;
+ if (sky) { d = 1.0; }
+ let hit = worldFromDepth(v.v_texCoord, d);
+ let facing = cross(dpdx(hit), dpdy(hit));
+
+ let up = normalize(vec3f(mc.u_planeNx, mc.u_planeNy, mc.u_planeNz));
+ let wet = smoothstep(-mc.u_band, mc.u_band, mc.u_planeD - dot(up, entry));
+ if (wet <= 0.0 || mc.u_amount <= 0.0) { return src; }
+
+ let dir = normalize(hit - entry);
+ var len = min(length(hit - entry), mc.u_range);
+ if (sky) { len = mc.u_range; }
+ let transmit = exp(-mc.u_absorption.rgb * (mc.u_density * len));
+ let extinction = max(dot(mc.u_absorption.rgb, vec3f(1.0 / 3.0)) * mc.u_density, 1e-5);
+
+ let found = findSun();
+ let cosUp = dot(found.dir.xyz, up);
+ let sunny = found.dir.w > 0.5 && cosUp > 0.05;
+ let slant = max(cosUp, 0.15);
+ let clock = tc.u_time.x * mc.u_causticSpeed;
+
+ var colour = src.rgb;
+ if (!sky && sunny && mc.u_causticStrength > 0.0) {
+ var normal = normalize(facing);
+ if (dot(normal, dir) > 0.0) { normal = -normal; }
+ let below = max(mc.u_planeD - dot(up, hit), 0.0);
+ let onSurface = hit + found.dir.xyz * (below / slant);
+ let web = causticPattern(onSurface.xz / mc.u_causticScale, clock);
+ let reach = exp(-extinction * below / slant);
+ colour = colour * (1.0 + mc.u_causticStrength * web * max(dot(normal, found.dir.xyz), 0.0) * sunVisibility(hit, found.tiles.x, found.tiles.y) * reach * min(found.color.a, 2.0) * 0.5);
}
- let transmit = exp(-mc.u_absorption.rgb * (mc.u_density * dist));
+
var scatter = mc.u_scatterColor.rgb;
#ifdef ES_LINEAR
scatter = srgbToLinear(scatter);
#endif
scatter = scatter * exp(-mc.u_lightFalloff * mc.u_cameraDepth);
- let col = src.rgb * transmit + scatter * (1.0 - dot(transmit, vec3f(1.0 / 3.0)));
- return vec4f(mix(src.rgb, col, vec3f(mc.u_amount)), src.a);
+ var col = colour * transmit + scatter * (1.0 - dot(transmit, vec3f(1.0 / 3.0)));
+
+ if (sunny && mc.u_shaftStrength > 0.0) {
+ let span = min(len, mc.u_shaftRange);
+ let ds = span / f32(SHAFT_STEPS);
+ let jitter = ign(v.pos.xy);
+ var through = 1.0;
+ var lit = 0.0;
+ for (var i : i32 = 0; i < SHAFT_STEPS; i = i + 1) {
+ let p = entry + dir * ((f32(i) + jitter) * ds);
+ let below = mc.u_planeD - dot(up, p);
+ if (below > 0.0) {
+ let onSurface = p + found.dir.xyz * (below / slant);
+ let shaft = mix(1.0, min(causticPattern(onSurface.xz / mc.u_causticScale, clock) * 1.6, 1.0), 0.7);
+ lit = lit + through * ds * sunVisibility(p, found.tiles.x, found.tiles.y) * exp(-extinction * below / slant) * shaft;
+ }
+ through = through * exp(-extinction * ds);
+ }
+ let sunTint = found.color.rgb / max(max(found.color.r, found.color.g), max(found.color.b, 1e-3));
+ col = col + sunTint * lit * extinction * 0.5 * phaseHG(dot(dir, found.dir.xyz)) * mc.u_shaftStrength * clamp(found.color.a, 0.0, 8.0) * 8.0;
+ }
+ return vec4f(mix(src.rgb, col, vec3f(mc.u_amount * wet)), src.a);
}
#pragma end
`;
@@ -103,6 +242,19 @@ export function registerUnderwaterEffect(): void {
{ name: 'u_lightFalloff', label: 'Light Falloff', min: 0, max: 1, step: 0.0005, defaultValue: 0.004 },
// The longest the water is seen through: what the sky, which has no surface, is fogged by.
{ name: 'u_range', label: 'Range', min: 10, max: 100000, step: 10, defaultValue: 4000 },
+ // The surface at the camera, which the water module sets: its normal and offset, and how soft the line it makes across the lens is.
+ { name: 'u_planeNx', label: 'Surface Normal X', min: -1, max: 1, step: 0.01, defaultValue: 0 },
+ { name: 'u_planeNy', label: 'Surface Normal Y', min: -1, max: 1, step: 0.01, defaultValue: 1 },
+ { name: 'u_planeNz', label: 'Surface Normal Z', min: -1, max: 1, step: 0.01, defaultValue: 0 },
+ { name: 'u_planeD', label: 'Surface Offset', min: -1000000, max: 1000000, step: 1, defaultValue: 0 },
+ { name: 'u_band', label: 'Waterline Softness', min: 0, max: 1000, step: 0.05, defaultValue: 0.25 },
+ // The web of light on what faces the sun, as the Water material draws it from above: how strong, how large a cell (world units), how fast it swims.
+ { name: 'u_causticStrength', label: 'Caustics', min: 0, max: 3, step: 0.01, defaultValue: 0.6, neutralValue: 0 },
+ { name: 'u_causticScale', label: 'Caustic Scale', min: 0.05, max: 2000, step: 0.05, defaultValue: 2 },
+ { name: 'u_causticSpeed', label: 'Caustic Speed', min: 0, max: 4, step: 0.01, defaultValue: 0.35 },
+ // The sun scattered toward the camera by the water along each ray: how strong the shafts are, and how far from the camera they are walked.
+ { name: 'u_shaftStrength', label: 'Light Shafts', min: 0, max: 4, step: 0.01, defaultValue: 0.5, neutralValue: 0 },
+ { name: 'u_shaftRange', label: 'Shaft Range', min: 10, max: 100000, step: 10, defaultValue: 2000 },
],
colors: [
{ name: 'u_absorption', label: 'Absorption', defaultValue: { r: 0.45, g: 0.09, b: 0.05, a: 1 } },
@@ -140,28 +292,38 @@ export class UnderwaterPlugin implements Plugin {
if (!app.hasResource(WatersRes)) return;
const waters = app.getResource(WatersRes);
let eye: [number, number, number] | null = null;
+ let near = 1;
for (const entity of app.world.getEntitiesWithComponents([Camera, Transform])) {
- if (!(app.world.get(entity, Camera) as CameraData).isActive) continue;
+ const camera = app.world.get(entity, Camera) as CameraData;
+ if (!camera.isActive) continue;
const t = app.world.get(entity, Transform) as TransformData;
eye = [t.worldPosition.x, t.worldPosition.y, t.worldPosition.z];
+ near = camera.nearPlane;
break;
}
const sample = eye ? waters.sample(eye[0], eye[1], eye[2]) : null;
- if (!sample || !(sample.depth < 0)) { setUnderwaterState(null); return; }
+ // Under, or close enough above that part of the lens (the near plane ahead of the camera) can be: the effect decides pixel by pixel.
+ if (!sample || !(sample.depth < lensReach(near))) { setUnderwaterState(null); return; }
const built = waters.built_.get(sample.entity);
const instance = built?.instance ?? 0;
- const depth = -sample.depth;
+ const depth = Math.max(-sample.depth, 0);
const density = single(instance, 'u_density', 0.12);
const shallow = triple(instance, 'u_shallowColor', [0.10, 0.42, 0.46]);
const deep = triple(instance, 'u_deepColor', [0.01, 0.08, 0.15]);
// Deeper, the water gives back more of its deep colour: the same blend the surface draws.
const toDeep = 1 - Math.exp(-depth * density * 0.5);
+ const n = sample.normal;
setUnderwaterState({
- amount: submersion(depth, Math.max(1, (built?.data.waveHeight ?? 0) * 0.5)),
+ amount: 1,
depth,
absorption: triple(instance, 'u_absorption', [0.45, 0.09, 0.05]),
density,
scatter: [shallow[0] + (deep[0] - shallow[0]) * toDeep, shallow[1] + (deep[1] - shallow[1]) * toDeep, shallow[2] + (deep[2] - shallow[2]) * toDeep],
+ plane: [n[0], n[1], n[2], n[0] * sample.surface[0] + n[1] * sample.surface[1] + n[2] * sample.surface[2]],
+ band: Math.max(near * 0.08, 0.05),
+ causticStrength: single(instance, 'u_causticStrength', 0.6),
+ causticScale: single(instance, 'u_causticScale', 2),
+ causticSpeed: single(instance, 'u_causticSpeed', 0.35),
});
}, { name: 'UnderwaterSystem' }));
}
diff --git a/sdk/tests/water-underwater.test.ts b/sdk/tests/water-underwater.test.ts
index 00ed83dd7..13439a1ac 100644
--- a/sdk/tests/water-underwater.test.ts
+++ b/sdk/tests/water-underwater.test.ts
@@ -1,21 +1,20 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, expect, it } from 'vitest';
-import { applyUnderwaterToEffects, setUnderwaterState, currentUnderwater, submersion, type UnderwaterState } from '../src/postprocess/underwater';
+import { applyUnderwaterToEffects, setUnderwaterState, currentUnderwater, lensReach, type UnderwaterState } from '../src/postprocess/underwater';
import type { BlendedEffect } from '../src/postprocess/volumeBlending';
const state = (extra: Partial<UnderwaterState> = {}): UnderwaterState => ({
- amount: 1, depth: 40, absorption: [0.4, 0.1, 0.05], density: 0.02, scatter: [0.02, 0.2, 0.3], ...extra,
+ amount: 1, depth: 40, absorption: [0.4, 0.1, 0.05], density: 0.02, scatter: [0.02, 0.2, 0.3],
+ plane: [0, 1, 0, 5], band: 0.4, causticStrength: 0.6, causticScale: 2, causticSpeed: 0.35, ...extra,
});
const blank = (): BlendedEffect => ({ enabled: true, uniforms: new Map(), textures: new Map(), colors: new Map() });
-describe('submersion', () => {
- it('is none above the surface and at it, and whole from the fade down', () => {
- expect(submersion(-5, 2)).toBe(0);
- expect(submersion(0, 2)).toBe(0);
- expect(submersion(1, 2)).toBe(0.5);
- expect(submersion(2, 2)).toBe(1);
- expect(submersion(50, 2)).toBe(1);
+describe('lensReach', () => {
+ it('is a few near planes: how high above the surface part of the lens can still be in it', () => {
+ expect(lensReach(1)).toBe(2.5);
+ expect(lensReach(0.1)).toBeCloseTo(0.25, 10);
+ expect(lensReach(-3)).toBe(0);
});
});
@@ -37,6 +36,11 @@ describe('applyUnderwaterToEffects', () => {
expect(e.uniforms.get('u_cameraDepth')).toBe(40);
expect(e.colors.get('u_absorption')).toEqual({ r: 0.4, g: 0.1, b: 0.05, a: 1 });
expect(e.colors.get('u_scatterColor')).toEqual({ r: 0.02, g: 0.2, b: 0.3, a: 1 });
+ // The waterline: where the surface is at the camera, and how soft the line across the lens is.
+ expect([e.uniforms.get('u_planeNx'), e.uniforms.get('u_planeNy'), e.uniforms.get('u_planeNz'), e.uniforms.get('u_planeD')]).toEqual([0, 1, 0, 5]);
+ expect(e.uniforms.get('u_band')).toBe(0.4);
+ // The surface's caustics, so the camera sees the light the surface draws.
+ expect([e.uniforms.get('u_causticStrength'), e.uniforms.get('u_causticScale'), e.uniforms.get('u_causticSpeed')]).toEqual([0.6, 2, 0.35]);
});
it('keeps the numbers a scene authored, and only fills in the depth and the amount', () => {
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8b9e7d386..361e04478 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2567,6 +2567,8 @@ export const NOTED = {
{"note":"Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries."},
"feat(water): a camera under the surface sees through the water, fogged and tinted by what it has crossed":
{"note":"A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window)."},
+ "feat(water): a waterline across the lens, caustics, light shafts, and a mirror under the surface":
+ {"note":"Under water the picture is lit and bounded like water. A camera with its lens half in the water has a waterline across it, soft and sliding as it dips; what it sees is lit by the web of caustics the waves focus the sun into (the Water material's `u_causticStrength`, `u_causticScale` and `u_causticSpeed`, also drawn on what lies under the water seen from above); the water along each ray scatters the sun into shafts (`u_shaftStrength`); and the surface seen from below, past the critical angle, mirrors the world beneath it."},
"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":
{"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":