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(runtime): a TimeOfDay component moves the sun and the moon across the sky and draws the day, the dusk and the night

yhh30c7046504be
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce3a4970b..07f3eafd3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ published separately; it ships inside the editor.
### Added
- **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.
+- **Time of day.** A TimeOfDay component moves the sun and the moon across the sky, and a Sky Atmosphere effect draws the day, the dusk and the night. The sun is placed from the hour, the latitude and the season; the scene's directional light is aimed at it by day and at the moon by night, scaled and tinted by a day's curve, and the ambient light, baked reflections, fog and exposure follow. Sky Atmosphere draws the dome, the sun, a dusk glow, the moon and stars where there is no surface, and Weather greys it as it clouds over. A directional light that follows a panorama's sun can now be aimed by its own Transform (`aimFollowedSun`), which is what lets a panorama photographed with the sun in one place be lit by a sun that moves.
- **Weather.** A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself. A preset is a set of multipliers of what the scene already has — the sun at a fraction of its strength, the fog thicker, the picture greyer — plus absolute levels for rain and wetness, so one preset fits any project. The component drives the directional and ambient lights (in play mode only), the effects the scene's volumes resolve (Height Fog, Rain, Screen Space Reflections, Colour Grade, Auto Exposure), and takes `registerWeatherPreset` for weathers of a project's own. Volumes whose effects differ only in numbers now write the numbers into the passes they have instead of rebuilding them. Reflection probes follow the weather: the ambient light scales what baked probes show and how much colour they keep. The Ambient `Light` gains `reflectionScale` and `reflectionSaturation`, which the weather drives. Rain stays off what stands under a roof, and the Weather component turns a looping rain track up and down. The frame draws the scene once from straight above, depth only, around the camera whenever a `rain` effect is in the chain, and the effect keeps wetness, puddles, ripples and streaks off ground that something stands over; `soundSource` names the `AudioSource` the weather drives.
- **Quality levels are edited in Settings.** Settings → Project → Rendering edits each quality level, including which effects it runs. **Editing level** picks Low, Medium or High and the groups below — Rendering (render scale, minimum scale, MSAA), Shadows, Reflections and particles, Post-processing — show and change that level, so a level is read the way Unity's Quality page reads: a level, then its settings by subsystem. Post-processing lists every effect the engine has, ticked where the level runs it; an unticked one is skipped at that level wherever a camera's volume asks for it, with all of its passes. Device rules — the model, GPU, memory and core conditions Auto chooses a level by — are a table, shown when the mode is Auto, that says so on a row with no condition instead of dropping it while it is typed. Only what you change is saved to `project.esproject`, as a difference to that level, so an engine default that improves later still reaches a project that never touched it; a row's "changed" mark and reset follow the default of the level it is showing. The old per-level shadow distance rows are the Shadows group's Distance now. The effects a level leaves out had been matched by the prefix of a pass's name, which found none of Auto Exposure's passes; they are now matched by effect type. A new Quality Levels page in the performance docs describes it.
- **A G-buffer, and reflections that read it.** Reflections now know how rough and how metal each surface is, from a G-buffer the frame draws on request. A post-process shader that says `#pragma gbuffer` makes the scene target carry a second RGBA8 colour attachment, written in the same pass by the scene's own shaders — octahedral normal in `r`/`g`, roughness in `b`, metalness in `a` (0 where nothing wrote) — and finds it at `u_gbuffer`. A frame whose chain has no such effect makes none and compiles no variant. The render device grew multiple colour attachments for it on both backends: WebGL2 attaches and resolves a second target and sets the draw buffers per pipeline, and WebGPU declares the second target on every pipeline of the pass (written by the ones that write it, an empty write mask for the rest), clears it to zero and resolves it with the colour. Pipelines say whether they write it (`PipelineDesc::gbuffer`), a blended draw never does, and the second output is its own shader variant (`ES_GBUFFER`), so no pass pays for what it did not ask for. The built-in Model shader — what an imported glTF material becomes — writes it from the material's roughness, metalness and normal map. `ssr` reads it: it takes the surface's own normal (normal-map detail that depth cannot see), weighs and blurs the reflection by roughness, reflects a metal at nearly full strength where a dielectric reflects 4%, skips a surface rougher than `maxRoughness` before marching the ray, and takes the Rain effect's `wetness` as a film that smooths the ground. Where nothing wrote a record, it falls back to depth and the dielectric it has always assumed. Verified in the editor on both backends: of two floors that differ only in their material's roughness, the glossy one changes ten times the pixels the rough one does. Quality levels can also leave out expensive effects now: quality levels can now skip expensive post-process effects by name. A level's `skipEffects` lists the effects it leaves out, each named by its effect type (`ssr`, `taa`, `depthOfField`, `lightShafts`, `autoExposure`, …), and an effect leaves with all of its passes however they are named; a project's own list in its quality profile replaces the level's. By default low leaves out reflections, temporal anti-aliasing, depth of field and light shafts, and medium leaves out reflections and depth of field; high leaves out nothing. These defaults come from the work each effect does per pixel, not from a weak device: the editor's new `fx-cost` check measured every effect on Bistro at 2560×1600 on a fast desktop GPU, and none added more than about 6 ms (reflections ~5, bloom ~4, the example's whole eight-effect chain ~11, the rest within the ±3 ms the run drifts by), so the levels have not been checked against the hardware they are for. Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen.
diff --git a/README.md b/README.md
index 825adf8eb..0b07f06cc 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@
Estella is a **2D and 3D game engine** — sprites, tilemaps and UI as much as lit, shadowed, physically simulated 3D worlds — with a TypeScript SDK driven by a high-performance **C++** core — as WebAssembly on the web, and compiled ahead of time on native platforms. It outputs games that run in **web browsers**, on the **desktop**, in **WeChat MiniGames**, as single-file **playable ads**, and as native **Android / iOS** apps. A visual editor is available as a separate, free download.
<div align="center">
- <img src="docs/assets/weather-a53a539c.webp" alt="A Paris street corner rendered in real time by the Estella engine, moving from daylight through mist into rain with puddles" width="900" />
+ <img src="docs/assets/day-d24e90e8.webp" alt="A Paris street corner rendered in real time by the Estella engine, through a whole day: morning mist, sun, rain with puddles, and a night of lamps" width="900" />
<br/>
<sub><i>Amazon Lumberyard Bistro, rendered in real time by Estella (a sun that follows the sky, baked bounce light and reflections, the Neutral output transform). Scene © Amazon Lumberyard, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>, modified.</i></sub>
</div>
diff --git a/desktop b/desktop
index 616aacb99..048c4529e 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 616aacb99ef6afa56fb75157746dd0537e7c14db
+Subproject commit 048c4529e6587177179a63d271cd21610b8e7dab
diff --git a/docs/assets/day-d24e90e8.webp b/docs/assets/day-d24e90e8.webp
new file mode 100644
index 000000000..c575e894c
Binary files /dev/null and b/docs/assets/day-d24e90e8.webp differ
diff --git a/docs/assets/weather-a53a539c.webp b/docs/assets/weather-a53a539c.webp
deleted file mode 100644
index 066e70a7f..000000000
Binary files a/docs/assets/weather-a53a539c.webp and /dev/null differ
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 8bee66ec7..3d916c747 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -224,6 +224,7 @@ export default defineConfig({
{ label: '2D Lighting & Shadows', translations: { 'zh-CN': '2D 光照与阴影' }, slug: 'graphics/lighting' },
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'graphics/post-processing' },
{ label: 'Weather', translations: { 'zh-CN': '天气' }, slug: 'graphics/weather' },
+ { label: 'Time of Day', translations: { 'zh-CN': '昼夜' }, slug: 'graphics/time-of-day' },
{ label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'graphics/drawing' },
{ label: 'Video', translations: { 'zh-CN': '视频' }, slug: 'graphics/video' },
],
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 7f6bbd9ec..b46307222 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -24,6 +24,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `fxaa` | Fast anti-aliasing | `intensity` |
| `distanceFog` | Linear fog by distance from the camera | `near`, `far`, `intensity`, colour |
| `heightFog` | Exponential height fog with the sun's glow and a hazy horizon | `density`, `heightFalloff`, `baseHeight`, `sunAzimuth`, `sunElevation`, `skyFog`, colours |
+| `skyAtmosphere` | A sky with a time of day: dome, sun, dusk glow, moon and stars, drawn where there is no surface | `intensity`, `overcast`, `moon`, `stars`, `twilight`, `sunAzimuth`, `sunElevation` |
| `lightShafts` | Sun rays through whatever stands in front of it | `intensity`, `sunAzimuth`, `sunElevation`, `decay`, `reach` |
| `contactShadows` | The small sharp shadows at a contact a shadow map is too coarse to hold | `intensity`, `length`, `thickness` |
| `ssgi` | One bounce of diffuse light between the surfaces the camera sees | `intensity`, `radius`, `thickness`, `maxBounce` |
diff --git a/docs/astro/src/content/docs/graphics/time-of-day.mdx b/docs/astro/src/content/docs/graphics/time-of-day.mdx
new file mode 100644
index 000000000..e5a79f451
--- /dev/null
+++ b/docs/astro/src/content/docs/graphics/time-of-day.mdx
@@ -0,0 +1,67 @@
+---
+title: Time of Day
+description: A TimeOfDay component that moves the sun and the moon across the sky, dims and tints the lights, lights the fog, and draws a dusk glow and a night sky of stars.
+---
+
+A day is a path the sun takes and what the light, the sky and the fog are because of where it is. `TimeOfDay` places the
+sun with the astronomy that fits in four lines — an hour angle, a latitude and a season — so a day has the right shape
+(a long high arc in summer, a short low one in winter, sunrise toward the east) from three numbers a person can understand.
+Everything else is the same idea as [Weather](/graphics/weather/): **multipliers of what the scene already says**, so the
+same hour fits any project.
+
+## The component
+
+Add a `TimeOfDay` component to one entity.
+
+| Field | What it does |
+|---|---|
+| `hour` | The hour, 0–24 (12 is noon). The game advances it; set it in the editor to preview an hour. |
+| `daySeconds` | Seconds a whole day takes while the game runs. 0 holds the hour where it is. |
+| `latitude` | Where on the planet, in degrees (positive is north): how high the noon sun climbs. |
+| `declination` | The season, −23.5 to 23.5: positive is summer in the north. |
+| `north` | How far the world is turned from compass north (+Z) toward +X, in degrees — which way the sun rises. |
+| `drive` | What the time drives: Lights, Sky, Fog, Exposure, Reflections. |
+
+## What an hour changes
+
+- **The key light.** The scene's directional light (the one that follows a panorama's sun or casts shadows, else the first) is
+ aimed at the sun and scaled by a day's curve: warm and weak near the horizon, gone a little below it. While the sun is
+ down it is aimed at the **moon** and given a few hundredths of the sun's strength and a blue tint, so a night has shadows
+ that fall away from the moon. The crossover happens where both are dark, so nothing pops.
+- **The ambient light** is scaled and tinted — blue by night, warm at dusk — and **baked reflection probes** are dimmed and
+ drained of colour, since they were baked under a daytime sky.
+- **The sky.** A [Sky Atmosphere](/graphics/post-processing/) effect draws the dome, the sun, a dusk glow on the sun's side of the
+ horizon, the moon and the stars. It takes the sun from the clock, so it never mistakes the moon-lit key light for the sun.
+- **Fog.** Height Fog's colour is lit as the day is (dark at night, orange at dusk), and its glow follows the key light.
+- **Exposure.** Auto Exposure's compensation is raised at night so it stays readable (a scene without one gets it on its Colour
+ Grade).
+
+In the editor the scene's lights are left alone — as with Weather, previewing an hour never changes the scene you save — so
+the effects that follow the sun (sky, fog) are told where the clock's sun is instead. The lights move while the game runs.
+
+## With the weather
+
+Both scale the same lights, each from what the author set, so they compose: a rainy dusk is the dusk's colour times the rain's
+strength. The weather also greys the sky (`overcast`), hiding the sun, moon and stars as it clouds over.
+
+## Reading and driving it from code
+
+```ts
+import { timeOfDayAt, currentTimeOfDay, TimeOfDay } from 'esengine';
+
+// Where the sun is at 18:30 at latitude 51, in midsummer.
+const evening = timeOfDayAt(18.5, 51, 23);
+evening.sunDir; // unit vector toward the sun
+evening.daylight; // 0 at night, 1 by day
+
+// Set the hour: the system does the rest.
+world.insert(clockEntity, TimeOfDay, { hour: 6, daySeconds: 600 });
+```
+
+## Limits
+
+The baked lighting and the baked reflection probes are one moment's: the bake is of a daytime sky, so the lighting that is
+**not** from lights (lightmaps, probe volumes) does not move with the sun. A scene that is meant to pass through a whole day wants
+its sun and its sky live — a lit-by-lights scene, or a baked one whose bake is mostly the sky's soft light — and the dimming
+and tinting above do the rest. Windows and lamps do not light themselves at night; give them an emissive material or a light you
+turn on with `currentTimeOfDay().daylight`.
diff --git a/docs/astro/src/content/docs/graphics/weather.mdx b/docs/astro/src/content/docs/graphics/weather.mdx
index 4c3651488..db6ea395a 100644
--- a/docs/astro/src/content/docs/graphics/weather.mdx
+++ b/docs/astro/src/content/docs/graphics/weather.mdx
@@ -41,6 +41,7 @@ A turn is eased, so it starts and ends gently, and a finished turn lands on its
- **Reflections.** A baked reflection probe shows the sky it was baked under, so a rainy street would mirror a sunny one.
The ambient light carries `reflectionScale` and `reflectionSaturation` for exactly this: what baked probes show is
multiplied by the first and drained of colour by the second, and the weather turns both down.
+- **Sky.** A Sky Atmosphere effect is greyed by the preset's `overcast`: the sun, moon and stars are hidden as it clouds over.
- **Grade and exposure.** Colour Grade's saturation and contrast are scaled, and Auto Exposure's compensation raised.
The effects are applied after the scene's volumes have blended, so a scene that fogs itself thinly stays thinner than
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
index 12ad3a66c..573f8c3c5 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
@@ -23,6 +23,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `fxaa` | 快速抗锯齿 | `intensity` |
| `distanceFog` | 按到相机的距离做线性雾 | `near`、`far`、`intensity`、颜色 |
| `heightFog` | 指数高度雾,带太阳辉光和朦胧的地平线 | `density`、`heightFalloff`、`baseHeight`、`sunAzimuth`、`sunElevation`、`skyFog`、颜色 |
+| `skyAtmosphere` | 有昼夜的天空:天穹、太阳、黄昏辉光、月亮和星星,画在没有表面的地方 | `intensity`、`overcast`、`moon`、`stars`、`twilight`、`sunAzimuth`、`sunElevation` |
| `lightShafts` | 太阳光穿过前方遮挡物形成的光束 | `intensity`、`sunAzimuth`、`sunElevation`、`decay`、`reach` |
| `contactShadows` | 阴影贴图太粗放不下的接触处的小而锐利的阴影 | `intensity`、`length`、`thickness` |
| `ssgi` | 相机看得见的表面之间的一次漫反射光弹射 | `intensity`、`radius`、`thickness`、`maxBounce` |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/time-of-day.mdx b/docs/astro/src/content/docs/zh-cn/graphics/time-of-day.mdx
new file mode 100644
index 000000000..944a82c93
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/graphics/time-of-day.mdx
@@ -0,0 +1,60 @@
+---
+title: 昼夜
+description: 一个 TimeOfDay 组件,让太阳和月亮在天空中运行,调暗并染色灯光,为雾打光,并画出黄昏的辉光和满天星斗的夜空。
+---
+
+一天就是太阳走过的一条路径,以及灯光、天空和雾因为它在哪里而成为的样子。`TimeOfDay` 用四行就能写下的天文公式放置太阳——
+时角、纬度、季节——所以三个人人能懂的数,就能得到正确的一天的形状(夏天又长又高的弧线、冬天又短又低的弧线、日出偏东)。
+其余的和 [天气](/zh-cn/graphics/weather/) 是同一个思路:**场景已有设定的倍率**,同一个钟点适配任何项目。
+
+## 组件
+
+给某个实体加一个 `TimeOfDay` 组件。
+
+| 字段 | 作用 |
+|---|---|
+| `hour` | 钟点,0–24(12 是正午)。游戏运行时自行推进;在编辑器里设置它可以预览某个钟点。 |
+| `daySeconds` | 游戏运行时一整天持续多少秒。0 表示钟点停住。 |
+| `latitude` | 在星球上的位置,单位度(正为北):正午的太阳升多高。 |
+| `declination` | 季节,−23.5 到 23.5:正值是北半球的夏天。 |
+| `north` | 世界相对罗盘正北(+Z)朝 +X 转了多少度——太阳从哪边升起。 |
+| `drive` | 时间驱动什么:灯光、天空、雾、曝光、反射。 |
+
+## 一个钟点改变什么
+
+- **主光。** 场景里的方向光(跟随全景图太阳的、投射阴影的,否则取第一盏)对准太阳,并按白天的曲线缩放:贴近地平线时偏暖偏弱,
+ 落到地平线以下一点就熄灭。太阳落下后它对准**月亮**,强度是太阳的几百分之一,带蓝色,所以夜里的阴影背着月亮倒下。
+ 交接发生在两者都很暗的地方,不会突变。
+- **环境光**被缩放并染色——夜里偏蓝、黄昏偏暖——**烘焙反射探针**被调暗并褪色,因为它们是在白天的天空下烘焙的。
+- **天空。** [Sky Atmosphere](/zh-cn/graphics/post-processing/) 特效画出天穹、太阳、地平线上太阳那一侧的黄昏辉光、月亮和星星。
+ 它的太阳取自时钟,所以不会把月光下的主光当成太阳。
+- **雾。** Height Fog 的颜色随白天而被照亮(夜里暗、黄昏偏橙),辉光跟随主光。
+- **曝光。** 夜里 Auto Exposure 的补偿被抬高,让画面保持可读(没有它的场景改加在 Colour Grade 上)。
+
+在编辑器里场景的灯光保持不动——和天气一样,预览一个钟点永远不会改动你要保存的场景——所以跟随太阳的特效(天空、雾)改为被告知
+时钟的太阳在哪里。灯光在游戏运行时才会移动。
+
+## 与天气同用
+
+两者缩放的是同一批灯,各自从作者设定的值出发,所以可以叠加:雨中的黄昏就是黄昏的颜色乘上雨的强度。天气还会把天空压灰
+(`overcast`),天阴下来时太阳、月亮和星星随之隐去。
+
+## 在代码里读取和驱动
+
+```ts
+import { timeOfDayAt, currentTimeOfDay, TimeOfDay } from 'esengine';
+
+// 北纬 51 度、仲夏、18:30 时太阳在哪里。
+const evening = timeOfDayAt(18.5, 51, 23);
+evening.sunDir; // 指向太阳的单位向量
+evening.daylight; // 夜里 0,白天 1
+
+// 设置钟点,剩下的交给系统。
+world.insert(clockEntity, TimeOfDay, { hour: 6, daySeconds: 600 });
+```
+
+## 局限
+
+烘焙光照和烘焙反射探针只对应某一个时刻:烘焙的是白天的天空,所以**不来自灯**的那部分光照(光照贴图、探针体)不会随太阳移动。
+要走完一整天的场景,应让太阳和天空是实时的——由灯光照亮的场景,或者烘焙内容主要是天空柔光的场景——上面的调暗与染色会做其余的事。
+窗户和路灯不会在夜里自己亮起来:给它们自发光材质,或一盏用 `currentTimeOfDay().daylight` 来开关的灯。
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
index 6b4a3b536..6384ce82d 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx
@@ -34,6 +34,7 @@ description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或
天气只能把它提高。
- **反射。** 烘焙的反射探针显示的是它烘焙时的天空,所以下雨的街道会映出晴天的街道。环境光带有 `reflectionScale` 和
`reflectionSaturation` 就是为此:探针显示的内容乘以前者、按后者褪色,天气会把两者调低。
+- **天空。** Sky Atmosphere 特效会随预设的 `overcast` 变灰:天阴下来时太阳、月亮和星星随之隐去。
- **调色与曝光。** Colour Grade 的饱和度和对比度被缩放,Auto Exposure 的补偿被提高。
这些效果在场景的体积混合之后才施加,所以在同一场雨里,雾设得薄的场景仍然比雾设得厚的场景薄。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 0bf46ba1a..c1da6762e 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -1,12 +1,12 @@
{
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
- "public": 120,
+ "public": 122,
"beta": 164,
- "experimental": 2292,
+ "experimental": 2297,
"deprecated": 3
},
- "total": 2576,
+ "total": 2583,
"subsystems": [
{
"id": "mobile-controls",
@@ -1730,6 +1730,18 @@
"minigame"
]
},
+ {
+ "name": "currentTimeOfDay",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "currentWeather",
"kind": "function",
@@ -1862,6 +1874,18 @@
"minigame"
]
},
+ {
+ "name": "timeOfDayAt",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "weatherPresetId",
"kind": "function",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index e6eed3a04..344624437 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -72,6 +72,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
Light: { category: 'graphics', summary: 'A light — point, directional, spot or ambient — read by lit renderers, Lit materials and mesh shadow maps.', doc: 'graphics/lighting', anchor: 'light-types', anchorZh: '光源类型' },
ShadowCaster2D: { category: 'graphics', summary: 'Marks a renderer as an occluder, so 2D lights cast shadows from its silhouette.', doc: 'graphics/lighting', anchor: 'casting-shadows', anchorZh: '投射阴影' },
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
+ TimeOfDay: { category: 'graphics', summary: 'The time of day of a scene — where the sun and the moon are, and the light, sky, fog and exposure that follow — driving lights, a procedural sky, fog and exposure.', doc: 'graphics/time-of-day' },
Weather: { category: 'graphics', summary: 'The weather of a scene — a preset, a turn toward another, and an optional cycle — driving lights, fog, rain, grade, exposure and reflections.', doc: 'graphics/weather' },
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 8aa58dddc..10d7a0204 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2103,6 +2103,13 @@
"default": "false",
"doc": "Take direction and strength from the environment's sun, and light the sky without it."
},
+ {
+ "key": "aimFollowedSun",
+ "type": "boolean",
+ "default": "false",
+ "doc": "With Follow Environment Sun: aim by this light's Transform, not by the panorama.",
+ "advanced": true
+ },
{
"key": "environment",
"type": "Asset<environment>",
@@ -2137,6 +2144,13 @@
"range": "0–1",
"advanced": true
},
+ {
+ "key": "bakedTint",
+ "type": "Color",
+ "default": "#ffffff",
+ "doc": "Multiply baked indirect light (lightmaps, probe volumes) by this colour (1 = as baked).",
+ "advanced": true
+ },
{
"key": "enabled",
"type": "boolean",
@@ -5468,6 +5482,55 @@
"opacity"
]
},
+ {
+ "name": "TimeOfDay",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "hour",
+ "type": "number",
+ "default": "12",
+ "range": "0–24, step 0.05"
+ },
+ {
+ "key": "daySeconds",
+ "type": "number",
+ "default": "0",
+ "range": "0–86400, step 1"
+ },
+ {
+ "key": "latitude",
+ "type": "number",
+ "default": "40",
+ "range": "-90–90, step 1"
+ },
+ {
+ "key": "declination",
+ "type": "number",
+ "default": "15",
+ "range": "-23.5–23.5, step 0.5"
+ },
+ {
+ "key": "north",
+ "type": "number",
+ "default": "0",
+ "range": "-180–180, step 1"
+ },
+ {
+ "key": "drive",
+ "type": "number",
+ "default": "31"
+ }
+ ],
+ "animatable": [
+ "hour",
+ "daySeconds",
+ "latitude",
+ "declination",
+ "north",
+ "drive"
+ ]
+ },
{
"name": "TimelinePlayer",
"source": "ts",
diff --git a/docs/landing/day-249c47d9.webm b/docs/landing/day-249c47d9.webm
new file mode 100644
index 000000000..0e8dca59d
Binary files /dev/null and b/docs/landing/day-249c47d9.webm differ
diff --git a/docs/landing/day-2866a6b6.mp4 b/docs/landing/day-2866a6b6.mp4
new file mode 100644
index 000000000..d19199e3a
Binary files /dev/null and b/docs/landing/day-2866a6b6.mp4 differ
diff --git a/docs/landing/index.html b/docs/landing/index.html
index d320e74dc..b067a5179 100644
--- a/docs/landing/index.html
+++ b/docs/landing/index.html
@@ -446,18 +446,18 @@
<div class="shot">
<figure>
- <!-- A loop of the same street through a weather cycle, drawn by the engine one frame at a time:
- clear, morning mist, rain with puddles, clear again. The still is the poster, and what
+ <!-- A loop of the same street through a whole day, drawn by the engine one frame at a time:
+ dawn, morning mist, a sunlit noon, rain with puddles at dusk, a night of lamps, dawn again. The still is the poster, and what
a visitor who prefers no motion is left with. -->
<video id="hero-loop" width="1280" height="720" autoplay muted loop playsinline preload="metadata"
poster="/hero-5df1f015.png"
- aria-label="A Paris street corner rendered in real time by the Estella engine, moving from clear daylight through morning mist into rain, with wet cobbles, puddles that mirror the scene, and ripples">
- <source src="/weather-98a16f59.webm" type="video/webm" />
- <source src="/weather-6f249a87.mp4" type="video/mp4" />
+ aria-label="A Paris street corner rendered in real time by the Estella engine, through a whole day: morning mist, a sunlit noon with long shadows, rain with wet cobbles and puddles that mirror the scene, and a night lit by lamps">
+ <source src="/day-249c47d9.webm" type="video/webm" />
+ <source src="/day-2866a6b6.mp4" type="video/mp4" />
<img src="/hero-5df1f015.png" width="1742" height="980"
alt="A Paris street corner in daylight, rendered in real time by the Estella engine: a cafe, a scooter, cobbles and sun shadows" />
</video>
- <figcaption>Amazon Lumberyard Bistro, drawn by Estella through a weather cycle — clear, mist, then rain with wet ground, puddles and ripples. Sun and sky, baked bounce light, reflections, fog, auto exposure and the Neutral output transform, all engine effects. Scene © Amazon Lumberyard, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>, modified.</figcaption>
+ <figcaption>Amazon Lumberyard Bistro, drawn by Estella through a whole day — dawn mist, a sunlit noon, rain with wet ground and puddles at dusk, then a night of lamps. Sun and sky, baked bounce light, reflections, fog, auto exposure and the Neutral output transform, all engine effects. Scene © Amazon Lumberyard, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>, modified.</figcaption>
</figure>
</div>
</section>
diff --git a/docs/landing/weather-6f249a87.mp4 b/docs/landing/weather-6f249a87.mp4
deleted file mode 100644
index 99eb21e75..000000000
Binary files a/docs/landing/weather-6f249a87.mp4 and /dev/null differ
diff --git a/docs/landing/weather-98a16f59.webm b/docs/landing/weather-98a16f59.webm
deleted file mode 100644
index 1b7ddb195..000000000
Binary files a/docs/landing/weather-98a16f59.webm and /dev/null differ
diff --git a/examples/bistro/assets/scenes/main.esscene b/examples/bistro/assets/scenes/main.esscene
index 9c8877078..6d1646f2e 100644
--- a/examples/bistro/assets/scenes/main.esscene
+++ b/examples/bistro/assets/scenes/main.esscene
@@ -43,6 +43,14 @@
"priority": 0,
"weight": 1,
"effects": [
+ {
+ "type": "skyAtmosphere",
+ "enabled": true,
+ "uniforms": {
+ "u_intensity": 1.1,
+ "u_sunBrightness": 40
+ }
+ },
{
"type": "taa",
"enabled": true,
@@ -68926,6 +68934,36 @@
}
}
]
+ },
+ {
+ "id": 1151,
+ "name": "Time of Day",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "TimeOfDay",
+ "data": {
+ "hour": 12,
+ "daySeconds": 0,
+ "latitude": 48.8,
+ "declination": 12,
+ "north": 180,
+ "drive": 31
+ }
+ }
+ ]
}
]
}
\ No newline at end of file
diff --git a/examples/bistro/tools/build-scene.mjs b/examples/bistro/tools/build-scene.mjs
index 31615cdf8..4c7431159 100644
--- a/examples/bistro/tools/build-scene.mjs
+++ b/examples/bistro/tools/build-scene.mjs
@@ -48,6 +48,7 @@ add('Camera', [
tr(v3(EYE), aim({ x: TARGET[0] - EYE[0], y: TARGET[1] - EYE[1], z: TARGET[2] - EYE[2] })),
{ type: 'Camera', data: { projectionType: 0, fov: 33, nearPlane: 10, farPlane: 40000, isActive: true, priority: 0 } },
{ type: 'PostProcessVolume', data: { isGlobal: true, priority: 0, weight: 1, effects: [
+ { type: 'skyAtmosphere', enabled: true, uniforms: { u_intensity: 1.1, u_sunBrightness: 40 } },
{ type: 'taa', enabled: true, uniforms: { u_blend: 0.1 } },
{ type: 'ssao', enabled: true, uniforms: { u_radius: 70, u_intensity: 1, u_bias: 0.12, u_power: 1.5 } },
{ type: 'contactShadows', enabled: true, uniforms: { u_intensity: 0.55, u_length: 28, u_thickness: 10 } },
@@ -102,5 +103,11 @@ add('Weather', [
{ type: 'Weather', data: { preset: 0, target: -1, progress: 0, duration: 10, sequence: 'clear,mist,rain,clear', hold: 8, drive: 127, soundSource: 0 } },
]);
+// The hour the street is shot at, and how the sun walks: Paris in early autumn, the world turned so that noon is behind the camera.
+add('Time of Day', [
+ tr({ x: 0, y: 0, z: 0 }),
+ { type: 'TimeOfDay', data: { hour: 12, daySeconds: 0, latitude: 48.8, declination: 12, north: 180, drive: 31 } },
+]);
+
writeFileSync(SCENE, JSON.stringify({ version: 4, name: 'Main', entities }, null, 2));
console.log(`wrote ${entities.length} entities`);
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 9e61c2cbd..f454824b5 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 120 public · 152 beta · 1664 experimental · 3 deprecated
+Symbols: 122 public · 152 beta · 1669 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"174c991a07d3d3ef"
+"8eba82ff470da2d6"
```
## ANCHOR_AXES — const @experimental
@@ -4843,6 +4843,8 @@ BuiltinComponentDef<LightData>
## LightData — interface @experimental
```
+aimFollowedSun: boolean
+bakedTint: Color
color: Color
cookie: number
cookieSize: Vec2
@@ -9591,6 +9593,46 @@ scale: number
unscaledDelta: number
```
+## TimeDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Sky: 2; readonly Fog: 4; readonly Exposure: 8; readonly Reflections: 16; readonly All: 31; }
+```
+
+## TimeOfDay — const @experimental
+```
+ComponentDef<TimeOfDayData>
+```
+
+## TimeOfDayData — interface @experimental
+```
+daySeconds: number
+declination: number
+drive: number
+hour: number
+latitude: number
+north: number
+```
+
+## TimeOfDayState — interface @experimental
+```
+daylight: number
+exposure: number
+fogBrightness: number
+fogDusk: number
+hour: number
+light: number
+lightDir: [number, number, number]
+lightTint: [number, number, number]
+moonDir: [number, number, number]
+reflection: number
+reflectionSaturation: number
+sky: number
+skyTint: [number, number, number]
+sunAzimuth: number
+sunDir: [number, number, number]
+sunElevation: number
+```
+
## Timeline — const @experimental
```
ResourceDef<TimelineAPI>
@@ -10877,6 +10919,7 @@ fogDensity: number
fogGlow: number
fogTint: [number, number, number]
fogTintAmount: number
+overcast: number
puddles: number
rain: number
reflection: number
@@ -12006,6 +12049,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentTimeOfDay — function @public
+```
+(): TimeOfDayState | null
+```
+
## currentWeather — function @public
```
(): WeatherState | null
@@ -14246,6 +14294,11 @@ StatsPlugin
(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary
```
+## sunPosition — function @experimental
+```
+(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number; }
+```
+
## switchTheme — function @experimental
```
(world: World, tokens: ThemeTokens): void
@@ -14291,6 +14344,11 @@ TextPlugin
(): ThemeType
```
+## timeOfDayAt — function @public
+```
+(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 320a6de48..339d456c1 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 120 public · 157 beta · 1683 experimental · 3 deprecated
+Symbols: 122 public · 157 beta · 1688 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"174c991a07d3d3ef"
+"8eba82ff470da2d6"
```
## ANCHOR_AXES — const @experimental
@@ -4851,6 +4851,8 @@ BuiltinComponentDef<LightData>
## LightData — interface @experimental
```
+aimFollowedSun: boolean
+bakedTint: Color
color: Color
cookie: number
cookieSize: Vec2
@@ -9804,6 +9806,46 @@ scale: number
unscaledDelta: number
```
+## TimeDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Sky: 2; readonly Fog: 4; readonly Exposure: 8; readonly Reflections: 16; readonly All: 31; }
+```
+
+## TimeOfDay — const @experimental
+```
+ComponentDef<TimeOfDayData>
+```
+
+## TimeOfDayData — interface @experimental
+```
+daySeconds: number
+declination: number
+drive: number
+hour: number
+latitude: number
+north: number
+```
+
+## TimeOfDayState — interface @experimental
+```
+daylight: number
+exposure: number
+fogBrightness: number
+fogDusk: number
+hour: number
+light: number
+lightDir: [number, number, number]
+lightTint: [number, number, number]
+moonDir: [number, number, number]
+reflection: number
+reflectionSaturation: number
+sky: number
+skyTint: [number, number, number]
+sunAzimuth: number
+sunDir: [number, number, number]
+sunElevation: number
+```
+
## Timeline — const @experimental
```
ResourceDef<TimelineAPI>
@@ -11090,6 +11132,7 @@ fogDensity: number
fogGlow: number
fogTint: [number, number, number]
fogTintAmount: number
+overcast: number
puddles: number
rain: number
reflection: number
@@ -12259,6 +12302,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentTimeOfDay — function @public
+```
+(): TimeOfDayState | null
+```
+
## currentWeather — function @public
```
(): WeatherState | null
@@ -14509,6 +14557,11 @@ StatsPlugin
(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary
```
+## sunPosition — function @experimental
+```
+(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number; }
+```
+
## switchTheme — function @experimental
```
(world: World, tokens: ThemeTokens): void
@@ -14554,6 +14607,11 @@ TextPlugin
(): ThemeType
```
+## timeOfDayAt — function @public
+```
+(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 62de3c7e9..8ce8ead9f 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 120 public · 154 beta · 1663 experimental · 3 deprecated
+Symbols: 122 public · 154 beta · 1668 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4838,6 +4838,8 @@ BuiltinComponentDef<LightData>
## LightData — interface @experimental
```
+aimFollowedSun: boolean
+bakedTint: Color
color: Color
cookie: number
cookieSize: Vec2
@@ -9586,6 +9588,46 @@ scale: number
unscaledDelta: number
```
+## TimeDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Sky: 2; readonly Fog: 4; readonly Exposure: 8; readonly Reflections: 16; readonly All: 31; }
+```
+
+## TimeOfDay — const @experimental
+```
+ComponentDef<TimeOfDayData>
+```
+
+## TimeOfDayData — interface @experimental
+```
+daySeconds: number
+declination: number
+drive: number
+hour: number
+latitude: number
+north: number
+```
+
+## TimeOfDayState — interface @experimental
+```
+daylight: number
+exposure: number
+fogBrightness: number
+fogDusk: number
+hour: number
+light: number
+lightDir: [number, number, number]
+lightTint: [number, number, number]
+moonDir: [number, number, number]
+reflection: number
+reflectionSaturation: number
+sky: number
+skyTint: [number, number, number]
+sunAzimuth: number
+sunDir: [number, number, number]
+sunElevation: number
+```
+
## Timeline — const @experimental
```
ResourceDef<TimelineAPI>
@@ -10872,6 +10914,7 @@ fogDensity: number
fogGlow: number
fogTint: [number, number, number]
fogTintAmount: number
+overcast: number
puddles: number
rain: number
reflection: number
@@ -12001,6 +12044,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentTimeOfDay — function @public
+```
+(): TimeOfDayState | null
+```
+
## currentWeather — function @public
```
(): WeatherState | null
@@ -14251,6 +14299,11 @@ StatsPlugin
(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary
```
+## sunPosition — function @experimental
+```
+(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number; }
+```
+
## switchTheme — function @experimental
```
(world: World, tokens: ThemeTokens): void
@@ -14296,6 +14349,11 @@ TextPlugin
(): ThemeType
```
+## timeOfDayAt — function @public
+```
+(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 7fd99a262..4042bc453 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 120 public · 152 beta · 1685 experimental · 3 deprecated
+Symbols: 122 public · 152 beta · 1690 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4838,6 +4838,8 @@ BuiltinComponentDef<LightData>
## LightData — interface @experimental
```
+aimFollowedSun: boolean
+bakedTint: Color
color: Color
cookie: number
cookieSize: Vec2
@@ -9879,6 +9881,46 @@ scale: number
unscaledDelta: number
```
+## TimeDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Sky: 2; readonly Fog: 4; readonly Exposure: 8; readonly Reflections: 16; readonly All: 31; }
+```
+
+## TimeOfDay — const @experimental
+```
+ComponentDef<TimeOfDayData>
+```
+
+## TimeOfDayData — interface @experimental
+```
+daySeconds: number
+declination: number
+drive: number
+hour: number
+latitude: number
+north: number
+```
+
+## TimeOfDayState — interface @experimental
+```
+daylight: number
+exposure: number
+fogBrightness: number
+fogDusk: number
+hour: number
+light: number
+lightDir: [number, number, number]
+lightTint: [number, number, number]
+moonDir: [number, number, number]
+reflection: number
+reflectionSaturation: number
+sky: number
+skyTint: [number, number, number]
+sunAzimuth: number
+sunDir: [number, number, number]
+sunElevation: number
+```
+
## Timeline — const @experimental
```
ResourceDef<TimelineAPI>
@@ -11171,6 +11213,7 @@ fogDensity: number
fogGlow: number
fogTint: [number, number, number]
fogTintAmount: number
+overcast: number
puddles: number
rain: number
reflection: number
@@ -12305,6 +12348,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentTimeOfDay — function @public
+```
+(): TimeOfDayState | null
+```
+
## currentWeather — function @public
```
(): WeatherState | null
@@ -14555,6 +14603,11 @@ StatsPlugin
(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary
```
+## sunPosition — function @experimental
+```
+(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number; }
+```
+
## switchTheme — function @experimental
```
(world: World, tokens: ThemeTokens): void
@@ -14600,6 +14653,11 @@ TextPlugin
(): ThemeType
```
+## timeOfDayAt — function @public
+```
+(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c67d0dc46..8017f78bc 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 120 public · 152 beta · 1676 experimental · 3 deprecated
+Symbols: 122 public · 152 beta · 1681 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4845,6 +4845,8 @@ BuiltinComponentDef<LightData>
## LightData — interface @experimental
```
+aimFollowedSun: boolean
+bakedTint: Color
color: Color
cookie: number
cookieSize: Vec2
@@ -9593,6 +9595,46 @@ scale: number
unscaledDelta: number
```
+## TimeDrive — const @experimental
+```
+{ readonly Lights: 1; readonly Sky: 2; readonly Fog: 4; readonly Exposure: 8; readonly Reflections: 16; readonly All: 31; }
+```
+
+## TimeOfDay — const @experimental
+```
+ComponentDef<TimeOfDayData>
+```
+
+## TimeOfDayData — interface @experimental
+```
+daySeconds: number
+declination: number
+drive: number
+hour: number
+latitude: number
+north: number
+```
+
+## TimeOfDayState — interface @experimental
+```
+daylight: number
+exposure: number
+fogBrightness: number
+fogDusk: number
+hour: number
+light: number
+lightDir: [number, number, number]
+lightTint: [number, number, number]
+moonDir: [number, number, number]
+reflection: number
+reflectionSaturation: number
+sky: number
+skyTint: [number, number, number]
+sunAzimuth: number
+sunDir: [number, number, number]
+sunElevation: number
+```
+
## Timeline — const @experimental
```
ResourceDef<TimelineAPI>
@@ -10903,6 +10945,7 @@ fogDensity: number
fogGlow: number
fogTint: [number, number, number]
fogTintAmount: number
+overcast: number
puddles: number
rain: number
reflection: number
@@ -12032,6 +12075,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentTimeOfDay — function @public
+```
+(): TimeOfDayState | null
+```
+
## currentWeather — function @public
```
(): WeatherState | null
@@ -14282,6 +14330,11 @@ StatsPlugin
(frames: readonly CapturedFrame[], budgetMs?: number): CaptureSummary
```
+## sunPosition — function @experimental
+```
+(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number; }
+```
+
## switchTheme — function @experimental
```
(world: World, tokens: ThemeTokens): void
@@ -14327,6 +14380,11 @@ TextPlugin
(): ThemeType
```
+## timeOfDayAt — function @public
+```
+(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
+```
+
## timelinePlugin — const @experimental
```
TimelinePlugin
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 73466e1bc..1e1e225cb 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -188,6 +188,11 @@ export {
WEATHER_NONE,
type WeatherState,
type WeatherPreset,
+ timeOfDayAt,
+ sunPosition,
+ currentTimeOfDay,
+ TimeDrive,
+ type TimeOfDayState,
} from './postprocess';
// =============================================================================
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 00ce622c6..5f23569c5 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -167,6 +167,8 @@ export {
type PostProcessVolumeData,
Weather,
type WeatherData,
+ TimeOfDay,
+ type TimeOfDayData,
} from './ecs/component';
export {
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 12b66df7c..f061238fe 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -815,11 +815,13 @@ export interface LightPtrData {
meshShadows: boolean;
shadowExtent: number;
followEnvironmentSun: boolean;
+ aimFollowedSun: boolean;
environment: number;
environmentRotation: number;
drawEnvironment: boolean;
reflectionScale: number;
reflectionSaturation: number;
+ bakedTint: Color;
enabled: boolean;
}
@@ -844,12 +846,14 @@ export function fillLight(
out.meshShadows = u8[ptr + 72] !== 0;
out.shadowExtent = f32[(ptr + 76) >> 2];
out.followEnvironmentSun = u8[ptr + 80] !== 0;
+ out.aimFollowedSun = u8[ptr + 81] !== 0;
out.environment = u32[(ptr + 84) >> 2];
out.environmentRotation = f32[(ptr + 88) >> 2];
out.drawEnvironment = u8[ptr + 92] !== 0;
out.reflectionScale = f32[(ptr + 96) >> 2];
out.reflectionSaturation = f32[(ptr + 100) >> 2];
- out.enabled = u8[ptr + 104] !== 0;
+ const bakedTint_ = out.bakedTint; bakedTint_.r = f32[(ptr + 104) >> 2]; bakedTint_.g = f32[((ptr + 104) >> 2) + 1]; bakedTint_.b = f32[((ptr + 104) >> 2) + 2]; bakedTint_.a = f32[((ptr + 104) >> 2) + 3];
+ out.enabled = u8[ptr + 120] !== 0;
}
export function writeLight(
@@ -873,12 +877,14 @@ export function writeLight(
u8[ptr + 72] = data.meshShadows ? 1 : 0;
f32[(ptr + 76) >> 2] = data.shadowExtent;
u8[ptr + 80] = data.followEnvironmentSun ? 1 : 0;
+ u8[ptr + 81] = data.aimFollowedSun ? 1 : 0;
u32[(ptr + 84) >> 2] = data.environment;
f32[(ptr + 88) >> 2] = data.environmentRotation;
u8[ptr + 92] = data.drawEnvironment ? 1 : 0;
f32[(ptr + 96) >> 2] = data.reflectionScale;
f32[(ptr + 100) >> 2] = data.reflectionSaturation;
- u8[ptr + 104] = data.enabled ? 1 : 0;
+ f32[(ptr + 104) >> 2] = data.bakedTint.r; f32[((ptr + 104) >> 2) + 1] = data.bakedTint.g; f32[((ptr + 104) >> 2) + 2] = data.bakedTint.b; f32[((ptr + 104) >> 2) + 3] = data.bakedTint.a;
+ u8[ptr + 120] = data.enabled ? 1 : 0;
}
export function createLightData(): LightPtrData {
@@ -900,11 +906,13 @@ export function createLightData(): LightPtrData {
meshShadows: false,
shadowExtent: 0,
followEnvironmentSun: false,
+ aimFollowedSun: false,
environment: 0,
environmentRotation: 0,
drawEnvironment: false,
reflectionScale: 0,
reflectionSaturation: 0,
+ bakedTint: { r: 0, g: 0, b: 0, a: 0 },
enabled: false,
};
}
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 55cfa981d..6e0e78a85 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '174c991a07d3d3ef';
+export const ABI_LAYOUT_HASH = '8eba82ff470da2d6';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -476,17 +476,19 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
meshShadows: false,
shadowExtent: 0,
followEnvironmentSun: false,
+ aimFollowedSun: false,
environment: 0,
environmentRotation: 0,
drawEnvironment: false,
reflectionScale: 1,
reflectionSaturation: 1,
+ bakedTint: { r: 1, g: 1, b: 1, a: 1 },
enabled: true,
},
renderableField: 'enabled',
assetFields: [{ field: 'cookie', type: 'texture' as AssetFieldType }, { field: 'environment', type: 'environment' as AssetFieldType }],
entityFields: [],
- colorFields: ['color'],
+ colorFields: ['color', 'bakedTint'],
animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'intensity', 'radius', 'innerRadius', 'falloff', 'shadowStrength', 'cookieSize.x', 'cookieSize.y', 'innerAngle', 'outerAngle', 'shadowSoftness', 'sourceAngle', 'shadowDistance'],
fields: {
type: { enum: [{ label: 'Point', value: 0 }, { label: 'Directional', value: 1 }, { label: 'Ambient', value: 2 }, { label: 'Spot', value: 3 }], tooltip: "Point, Directional, Ambient, or Spot." },
@@ -505,11 +507,13 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional, Spot, Point).", shownWhen: { field: "type", values: [0, 1, 3] } },
shadowExtent: { min: 0, tooltip: "Shadow map coverage radius; 0 = fit the view.", advanced: true, shownWhen: { field: "type", values: [1] } },
followEnvironmentSun: { tooltip: "Take direction and strength from the environment's sun, and light the sky without it.", shownWhen: { field: "type", values: [1] } },
+ aimFollowedSun: { tooltip: "With Follow Environment Sun: aim by this light's Transform, not by the panorama.", advanced: true, shownWhen: { field: "type", values: [1] } },
environment: { tooltip: "Baked environment (.esenv) this Ambient light casts.", shownWhen: { field: "type", values: [2] } },
environmentRotation: { unit: "deg", tooltip: "Turn the environment about the up axis, in degrees.", shownWhen: { field: "type", values: [2] } },
drawEnvironment: { tooltip: "Draw this environment as the sky behind the scene.", shownWhen: { field: "type", values: [2] } },
reflectionScale: { min: 0, tooltip: "Scale what baked reflection probes show (1 = as baked).", advanced: true, shownWhen: { field: "type", values: [2] } },
reflectionSaturation: { min: 0, max: 1, tooltip: "How much colour baked reflection probes keep (0 = grey).", advanced: true, shownWhen: { field: "type", values: [2] } },
+ bakedTint: { tooltip: "Multiply baked indirect light (lightmaps, probe volumes) by this colour (1 = as baked).", advanced: true, shownWhen: { field: "type", values: [2] } },
},
},
LightProbeVolume: {
@@ -1499,11 +1503,13 @@ export interface LightData {
meshShadows: boolean;
shadowExtent: number;
followEnvironmentSun: boolean;
+ aimFollowedSun: boolean;
environment: number;
environmentRotation: number;
drawEnvironment: boolean;
reflectionScale: number;
reflectionSaturation: number;
+ bakedTint: Color;
enabled: boolean;
}
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index fbd1f1680..57cc6e4b0 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -1388,6 +1388,50 @@ export const Weather = defineComponent<WeatherData>('Weather', {
},
});
+export interface TimeOfDayData {
+ /** The hour of the day, 0..24 (12 is noon). The system advances it in play, and a value set here previews it in the editor. */
+ hour: number;
+ /** Seconds a whole day takes while the game runs; 0 holds the hour where it is. */
+ daySeconds: number;
+ /** Where on the planet, in degrees (positive north): how high the noon sun climbs and how long a day is. */
+ latitude: number;
+ /** The season, in degrees, -23.5 (winter) .. 23.5 (summer) in the north. */
+ declination: number;
+ /** How far the world is turned from compass north (+Z) toward +X, in degrees: which way the sun rises. */
+ north: number;
+ /** What the time drives: the lights, the sky, the fog, the exposure, the reflections. */
+ drive: number;
+}
+
+/**
+ * The time of day of a scene: where the sun and the moon are, and what the light, the sky and the fog are because of it.
+ *
+ * @details The sun crosses the sky along the path its latitude and the season give it; the scene's directional light is aimed
+ * at it (at the moon by night) and scaled by a day's curve — warm and weak near the horizon, gone once it is down — and
+ * the ambient light follows. A Sky Atmosphere effect draws the sun, a dusk glow, a moon and stars where it stands,
+ * and the fog is lit as the day is. It composes with Weather: both scale the same lights from what the author set.
+ */
+export const TimeOfDay = defineComponent<TimeOfDayData>('TimeOfDay', {
+ hour: 12,
+ daySeconds: 0,
+ latitude: 40,
+ declination: 15,
+ north: 0,
+ drive: 31,
+}, {
+ fields: {
+ hour: { min: 0, max: 24, step: 0.05, unit: 'h' },
+ daySeconds: { min: 0, max: 86400, step: 1, unit: 's' },
+ latitude: { min: -90, max: 90, step: 1, unit: 'deg' },
+ declination: { min: -23.5, max: 23.5, step: 0.5, unit: 'deg' },
+ north: { min: -180, max: 180, step: 1, unit: 'deg' },
+ drive: { flags: [
+ { label: 'Lights', value: 1 }, { label: 'Sky', value: 2 }, { label: 'Fog', value: 4 },
+ { label: 'Exposure', value: 8 }, { label: 'Reflections', value: 16 },
+ ] },
+ },
+});
+
export type {
RigidBody2DData, BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
};
diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.ts
index e88306f1c..8d259fe82 100644
--- a/sdk/src/postprocess.ts
+++ b/sdk/src/postprocess.ts
@@ -35,4 +35,9 @@ export {
WEATHER_NONE,
type WeatherState,
type WeatherPreset,
+ timeOfDayAt,
+ sunPosition,
+ currentTimeOfDay,
+ TimeDrive,
+ type TimeOfDayState,
} from './postprocess/index';
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index aa606e025..206ab87a4 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -235,6 +235,30 @@ registerEffect({
],
});
+registerEffect({
+ type: 'skyAtmosphere',
+ label: 'Sky Atmosphere',
+ factory: () => postProcessEffects.createSkyAtmosphere(),
+ uniforms: [
+ // How bright the day's sky is; the night's is its own.
+ { name: 'u_intensity', label: 'Brightness', min: 0, max: 8, step: 0.01, defaultValue: 1 },
+ // How much of the sky behind the scene (a panorama, a clear colour) is kept: 0 replaces it, 1 leaves it.
+ { name: 'u_panorama', label: 'Keep Background', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 1 },
+ // 0 is a clear sky; 1 a grey one with no sun, moon or stars. A Weather component drives it.
+ { name: 'u_overcast', label: 'Overcast', min: 0, max: 1, step: 0.01, defaultValue: 0 },
+ { name: 'u_sunSize', label: 'Sun Size', min: 0.2, max: 8, step: 0.1, defaultValue: 1 },
+ { name: 'u_sunBrightness', label: 'Sun Brightness', min: 0, max: 400, step: 1, defaultValue: 40 },
+ { name: 'u_moon', label: 'Moon', min: 0, max: 4, step: 0.05, defaultValue: 1 },
+ { name: 'u_stars', label: 'Stars', min: 0, max: 4, step: 0.05, defaultValue: 1 },
+ // How strong the glow of dusk and dawn is on the horizon.
+ { name: 'u_twilight', label: 'Twilight', min: 0, max: 2, step: 0.05, defaultValue: 1 },
+ // 1: the sun is the scene's directional light. 0: the two angles are. A TimeOfDay component writes them.
+ { name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },
+ { name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },
+ { name: 'u_sunElevation', label: 'Sun Elevation', min: -90, max: 90, step: 1, defaultValue: 35 },
+ ],
+});
+
registerEffect({
type: 'heightFog',
label: 'Height Fog',
@@ -252,7 +276,7 @@ registerEffect({
{ name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },
// Where the sun is when it is not followed, to colour the haze toward it: degrees from +Z toward +X, and above the horizon.
{ name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },
- { name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 25 },
+ { name: 'u_sunElevation', label: 'Sun Elevation', min: -90, max: 90, step: 1, defaultValue: 25 },
{ name: 'u_inscatter', label: 'Sun Glow', min: 0, max: 2, step: 0.01, defaultValue: 0.6, neutralValue: 0 },
{ name: 'u_sunExponent', label: 'Glow Sharpness', min: 1, max: 64, step: 1, defaultValue: 8 },
// How much of the sky takes the horizon haze; 0 leaves the sky untouched.
@@ -304,7 +328,7 @@ registerEffect({
{ name: 'u_thickness', label: 'Thickness', min: 0.5, max: 80, step: 0.5, defaultValue: 8 },
{ name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },
{ name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },
- { name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 35 },
+ { name: 'u_sunElevation', label: 'Sun Elevation', min: -90, max: 90, step: 1, defaultValue: 35 },
],
});
@@ -316,7 +340,7 @@ registerEffect({
{ name: 'u_intensity', label: 'Intensity', min: 0, max: 3, step: 0.01, defaultValue: 0.6, neutralValue: 0 },
{ name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },
{ name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },
- { name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 25 },
+ { name: 'u_sunElevation', label: 'Sun Elevation', min: -90, max: 90, step: 1, defaultValue: 25 },
// Per step of the march: lower fades the shafts sooner along their length.
{ name: 'u_decay', label: 'Decay', min: 0.8, max: 1, step: 0.005, defaultValue: 0.96 },
// How much of the way to the sun each pixel looks: shorter shafts at lower values.
diff --git a/sdk/src/postprocess/index.ts b/sdk/src/postprocess/index.ts
index a9aa246e5..38d99cdd8 100644
--- a/sdk/src/postprocess/index.ts
+++ b/sdk/src/postprocess/index.ts
@@ -47,3 +47,4 @@ export {
type WeatherState,
type WeatherPreset,
} from './weather';
+export { timeOfDayAt, sunPosition, currentTimeOfDay, TimeDrive, type TimeOfDayState } from './timeOfDay';
diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.ts
index ae84804a3..8b8c3402d 100644
--- a/sdk/src/postprocess/postProcessEffects.ts
+++ b/sdk/src/postprocess/postProcessEffects.ts
@@ -1506,6 +1506,236 @@ fn depthAt(texel : vec2i, size : vec2i) -> f32 {
return Material.compileShader(source);
},
+ /**
+ * A sky that has a time of day: the gradient of the dome, the sun and its halo, the glow of dusk, a moon, and stars.
+ *
+ * Drawn only where there is no surface (the depth buffer is at its far plane), so it replaces the panorama behind the
+ * scene and leaves everything in front of it alone. The dome is two colours — zenith and horizon — for the day and two
+ * for the night, mixed by how high the sun stands; near the horizon a warm glow gathers toward the sun's side of the
+ * sky. The sun is a disc with a halo, the moon a disc standing opposite it (high when the sun is far below the
+ * horizon), and the stars are points hashed from the view direction, so they hold still as the camera turns. An
+ * overcast sky greys the dome and hides all three.
+ *
+ * Where the sun is comes from the scene's own directional light, or — when the effect is told not to follow it — from two
+ * angles, which is what a TimeOfDay component writes. The effect is a sky and not a lighting model: what lights the
+ * scene is the lights, and `TimeOfDay` moves those too.
+ */
+ createSkyAtmosphere(): ShaderHandle {
+ const source = `#pragma shader "PP Sky Atmosphere"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1) range(0,8)
+#pragma param u_panorama float default(0) range(0,1)
+#pragma param u_overcast float default(0) range(0,1)
+#pragma param u_sunSize float default(1) range(0.2,8)
+#pragma param u_sunBrightness float default(40) range(0,400)
+#pragma param u_moon float default(1) range(0,4)
+#pragma param u_stars float default(1) range(0,4)
+#pragma param u_twilight float default(1) range(0,2)
+#pragma param u_followSun float default(1) range(0,1)
+#pragma param u_sunAzimuth float default(40) range(0,360)
+#pragma param u_sunElevation float default(35) range(-90,90)
+#pragma lights
+
+#pragma fragment
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform highp sampler2D u_sceneDepth;
+out vec4 fragColor;
+
+float hash13(vec3 p) {
+ p = fract(p * 0.1031);
+ p += dot(p, p.zyx + 31.32);
+ return fract((p.x + p.y) * p.z);
+}
+
+vec3 lin(vec3 c) {
+#ifdef ES_LINEAR
+ return srgbToLinear(c);
+#else
+ return c;
+#endif
+}
+
+void main() {
+ vec4 src = texture(u_texture, v_texCoord);
+ ivec2 size = textureSize(u_sceneDepth, 0);
+ float depth = texelFetch(u_sceneDepth, clamp(ivec2(v_texCoord * vec2(size)), ivec2(0), size - ivec2(1)), 0).r;
+ if (depth < 1.0) { fragColor = src; return; }
+
+ vec3 entry = worldFromDepth(v_texCoord, 0.0);
+ vec3 dir = normalize(worldFromDepth(v_texCoord, 1.0) - entry);
+
+ vec4 lightDir, lightColor;
+ ivec2 tiles;
+ findSun(lightDir, lightColor, tiles);
+ bool follow = u_followSun > 0.5 && lightDir.w > 0.5;
+ float az = radians(u_sunAzimuth);
+ float el = radians(u_sunElevation);
+ vec3 sun = follow ? lightDir.xyz : vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));
+ float se = sun.y;
+
+ float day = smoothstep(-0.10, 0.25, se);
+ float twi = exp(-se * se * 70.0);
+ float up = max(dir.y, 0.0);
+ float haze = pow(1.0 - up, 3.0);
+
+ vec3 dayCol = mix(lin(vec3(0.12, 0.30, 0.72)), lin(vec3(0.60, 0.74, 0.92)), haze) * 2.0 * u_intensity;
+ vec3 nightCol = mix(lin(vec3(0.003, 0.006, 0.02)), lin(vec3(0.016, 0.024, 0.06)), haze);
+ vec3 col = mix(nightCol, dayCol, day);
+
+ // The glow of dusk and dawn: low in the sky, and thickest on the sun's side of it.
+ vec2 flatDir = dir.xz / max(length(dir.xz), 1e-4);
+ vec2 flatSun = sun.xz / max(length(sun.xz), 1e-4);
+ float side = max(dot(flatDir, flatSun), 0.0);
+ col += lin(vec3(1.0, 0.42, 0.16)) * (twi * haze * (0.25 + 0.75 * side * side) * 1.6 * u_twilight);
+
+ float overcast = clamp(u_overcast, 0.0, 1.0);
+ float clear = 1.0 - overcast;
+
+ // The sun: a disc, a tight halo and a wide one, warm near the horizon and white above.
+ float cosd = dot(dir, sun);
+ float sunR = radians(0.265 * u_sunSize);
+ float disc = smoothstep(cos(sunR * 1.15), cos(sunR * 0.85), cosd);
+ float halo = pow(max(cosd, 0.0), 16.0) * 0.25 + pow(max(cosd, 0.0), 256.0);
+ vec3 sunCol = mix(lin(vec3(1.0, 0.55, 0.25)), lin(vec3(1.0, 0.96, 0.88)), smoothstep(0.0, 0.35, se));
+ float above = smoothstep(-0.02, 0.02, dir.y) * smoothstep(-0.05, 0.0, se);
+ col += sunCol * (disc * u_sunBrightness * clear + halo * (0.4 + 0.6 * clear)) * above;
+
+ // The moon stands opposite the sun and a little above where it would be, so it is up when the sun is well down.
+ float sAz = atan(sun.x, sun.z);
+ float sEl = asin(clamp(sun.y, -1.0, 1.0));
+ float mEl = -sEl * 0.85 + radians(12.0);
+ float mAz = sAz + 3.14159265;
+ vec3 moon = vec3(cos(mEl) * sin(mAz), sin(mEl), cos(mEl) * cos(mAz));
+ float md = dot(dir, moon);
+ float moonR = radians(0.26 * 2.5);
+ float moonDisc = smoothstep(cos(moonR * 1.1), cos(moonR * 0.9), md);
+ float moonGlow = pow(max(md, 0.0), 300.0) * 0.5 + pow(max(md, 0.0), 24.0) * 0.03;
+ float night = 1.0 - day;
+ col += lin(vec3(0.80, 0.88, 1.0)) * ((moonDisc * 3.0 + moonGlow) * u_moon * night * clear * smoothstep(-0.02, 0.04, dir.y));
+
+ // Stars: a point in some of the cells of a lattice over the sphere, brighter and more coloured at random.
+ if (night > 0.02 && dir.y > 0.0 && u_stars > 0.0) {
+ vec3 p = dir * 180.0;
+ vec3 id = floor(p);
+ vec3 fr = p - id;
+ float h = hash13(id);
+ if (h > 0.965) {
+ vec3 c = vec3(hash13(id + 7.1), hash13(id + 13.3), hash13(id + 3.7)) * 0.6 + 0.2;
+ float spot = smoothstep(0.22, 0.02, length(fr - c));
+ float bright = (0.4 + hash13(id + 1.7) * 1.6) * (h > 0.995 ? 3.0 : 1.0);
+ vec3 tint = mix(lin(vec3(1.0, 0.85, 0.7)), lin(vec3(0.7, 0.8, 1.0)), hash13(id + 5.3));
+ float seen = night * night * clear * smoothstep(0.0, 0.15, dir.y) * (1.0 - 0.9 * smoothstep(0.97, 0.999, md));
+ col += tint * (spot * bright * 2.5 * u_stars * seen);
+ }
+ }
+
+ // An overcast sky is grey and a little darker than the one above it.
+ float luma = dot(col, vec3(0.2126, 0.7152, 0.0722));
+ col = mix(col, vec3(luma) * 0.85, overcast * 0.85) * (1.0 - 0.3 * overcast);
+
+ fragColor = vec4(mix(col, src.rgb, clamp(u_panorama, 0.0, 1.0)), src.a);
+}
+#pragma end
+
+#pragma fragment wgsl
+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 lin(c : vec3f) -> vec3f {
+#ifdef ES_LINEAR
+ return srgbToLinear(c);
+#else
+ return c;
+#endif
+}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let size = vec2i(textureDimensions(t7, 0));
+ let depth = textureLoad(t7, clamp(vec2i(v.v_texCoord * vec2f(size)), vec2i(0), size - vec2i(1)), 0);
+ if (depth < 1.0) { return src; }
+
+ let entry = worldFromDepth(v.v_texCoord, 0.0);
+ let dir = normalize(worldFromDepth(v.v_texCoord, 1.0) - entry);
+
+ let found = findSun();
+ let follow = mc.u_followSun > 0.5 && found.dir.w > 0.5;
+ let az = radians(mc.u_sunAzimuth);
+ let el = radians(mc.u_sunElevation);
+ var sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));
+ if (follow) { sun = found.dir.xyz; }
+ let se = sun.y;
+
+ let day = smoothstep(-0.10, 0.25, se);
+ let twi = exp(-se * se * 70.0);
+ let up = max(dir.y, 0.0);
+ let haze = pow(1.0 - up, 3.0);
+
+ let dayCol = mix(lin(vec3f(0.12, 0.30, 0.72)), lin(vec3f(0.60, 0.74, 0.92)), haze) * 2.0 * mc.u_intensity;
+ let nightCol = mix(lin(vec3f(0.003, 0.006, 0.02)), lin(vec3f(0.016, 0.024, 0.06)), haze);
+ var col = mix(nightCol, dayCol, day);
+
+ let flatDir = dir.xz / max(length(dir.xz), 1e-4);
+ let flatSun = sun.xz / max(length(sun.xz), 1e-4);
+ let side = max(dot(flatDir, flatSun), 0.0);
+ col = col + lin(vec3f(1.0, 0.42, 0.16)) * (twi * haze * (0.25 + 0.75 * side * side) * 1.6 * mc.u_twilight);
+
+ let overcast = clamp(mc.u_overcast, 0.0, 1.0);
+ let clear = 1.0 - overcast;
+
+ let cosd = dot(dir, sun);
+ let sunR = radians(0.265 * mc.u_sunSize);
+ let disc = smoothstep(cos(sunR * 1.15), cos(sunR * 0.85), cosd);
+ let halo = pow(max(cosd, 0.0), 16.0) * 0.25 + pow(max(cosd, 0.0), 256.0);
+ let sunCol = mix(lin(vec3f(1.0, 0.55, 0.25)), lin(vec3f(1.0, 0.96, 0.88)), smoothstep(0.0, 0.35, se));
+ let above = smoothstep(-0.02, 0.02, dir.y) * smoothstep(-0.05, 0.0, se);
+ col = col + sunCol * (disc * mc.u_sunBrightness * clear + halo * (0.4 + 0.6 * clear)) * above;
+
+ let sAz = atan2(sun.x, sun.z);
+ let sEl = asin(clamp(sun.y, -1.0, 1.0));
+ let mEl = -sEl * 0.85 + radians(12.0);
+ let mAz = sAz + 3.14159265;
+ let moon = vec3f(cos(mEl) * sin(mAz), sin(mEl), cos(mEl) * cos(mAz));
+ let md = dot(dir, moon);
+ let moonR = radians(0.26 * 2.5);
+ let moonDisc = smoothstep(cos(moonR * 1.1), cos(moonR * 0.9), md);
+ let moonGlow = pow(max(md, 0.0), 300.0) * 0.5 + pow(max(md, 0.0), 24.0) * 0.03;
+ let night = 1.0 - day;
+ col = col + lin(vec3f(0.80, 0.88, 1.0)) * ((moonDisc * 3.0 + moonGlow) * mc.u_moon * night * clear * smoothstep(-0.02, 0.04, dir.y));
+
+ if (night > 0.02 && dir.y > 0.0 && mc.u_stars > 0.0) {
+ let p = dir * 180.0;
+ let id = floor(p);
+ let fr = p - id;
+ let h = hash13(id);
+ if (h > 0.965) {
+ let c = vec3f(hash13(id + 7.1), hash13(id + 13.3), hash13(id + 3.7)) * 0.6 + 0.2;
+ let spot = smoothstep(0.22, 0.02, length(fr - c));
+ var bright = 0.4 + hash13(id + 1.7) * 1.6;
+ if (h > 0.995) { bright = bright * 3.0; }
+ let tint = mix(lin(vec3f(1.0, 0.85, 0.7)), lin(vec3f(0.7, 0.8, 1.0)), hash13(id + 5.3));
+ let seen = night * night * clear * smoothstep(0.0, 0.15, dir.y) * (1.0 - 0.9 * smoothstep(0.97, 0.999, md));
+ col = col + tint * (spot * bright * 2.5 * mc.u_stars * seen);
+ }
+ }
+
+ let luma = dot(col, vec3f(0.2126, 0.7152, 0.0722));
+ col = mix(col, vec3f(luma) * 0.85, overcast * 0.85) * (1.0 - 0.3 * overcast);
+
+ return vec4f(mix(col, src.rgb, clamp(mc.u_panorama, 0.0, 1.0)), src.a);
+}
+#pragma end
+`;
+ return Material.compileShader(source);
+ },
+
/**
* Exponential height fog with the atmosphere's two tells: the sun's glow in the haze and a
* sky that thickens toward the horizon.
@@ -1533,7 +1763,7 @@ fn depthAt(texel : vec2i, size : vec2i) -> f32 {
#pragma param u_startDistance float default(0) range(0,3000)
#pragma param u_maxOpacity float default(1) range(0,1)
#pragma param u_sunAzimuth float default(40) range(0,360)
-#pragma param u_sunElevation float default(25) range(-10,90)
+#pragma param u_sunElevation float default(25) range(-90,90)
#pragma param u_inscatter float default(0.6) range(0,2)
#pragma param u_sunExponent float default(8) range(1,64)
#pragma param u_skyFog float default(0.8) range(0,1)
@@ -1999,7 +2229,7 @@ ${GBUFFER_WGSL}
#pragma param u_thickness float default(8) range(0.5,80)
#pragma param u_followSun float default(1) range(0,1)
#pragma param u_sunAzimuth float default(40) range(0,360)
-#pragma param u_sunElevation float default(35) range(-10,90)
+#pragma param u_sunElevation float default(35) range(-90,90)
#pragma lights
#pragma fragment
@@ -2119,7 +2349,7 @@ fn ign(p : vec2f) -> f32 {
#pragma param u_sunColor color default(1,0.85,0.6,1)
#pragma param u_intensity float default(0.6) range(0,3)
#pragma param u_sunAzimuth float default(40) range(0,360)
-#pragma param u_sunElevation float default(25) range(-10,90)
+#pragma param u_sunElevation float default(25) range(-90,90)
#pragma param u_decay float default(0.96) range(0.8,1)
#pragma param u_reach float default(0.6) range(0.1,1)
#pragma param u_followSun float default(1) range(0,1)
diff --git a/sdk/src/postprocess/timeOfDay.ts b/sdk/src/postprocess/timeOfDay.ts
new file mode 100644
index 000000000..268c73b96
--- /dev/null
+++ b/sdk/src/postprocess/timeOfDay.ts
@@ -0,0 +1,224 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file timeOfDay.ts
+ * @brief Where the sun and the moon are at an hour of the day, and what that does to the light, the fog and the sky.
+ *
+ * @details The sun is placed by the astronomy that fits in four lines — an hour angle, a latitude and a declination — so a
+ * day has the right shape (a long arc in summer, a low one in winter, sunrise toward the east) with three numbers a
+ * person can understand. Everything else is the same idea as the weather: MULTIPLIERS of what the scene already
+ * says (the sun at its strength times a curve, the fog's colour times how dark it is) so the same hour fits any
+ * scene. The moon stands opposite the sun and is the directional light's aim while the sun is down.
+ *
+ * The state is applied in two places, as the weather's is: to the lights (in play mode, from the weather
+ * system, which owns the lights so the two scale one number and not each other's last answer) and to the
+ * effects the volumes resolve.
+ */
+import type { BlendedEffect, Rgba } from './volumeBlending';
+import { getEffectDef } from './effects';
+
+export interface TimeOfDayState {
+ /** The hour this is the state of, 0..24. */
+ hour: number;
+ /** Unit vectors toward the sun and the moon, in world space (Y up). */
+ sunDir: [number, number, number];
+ moonDir: [number, number, number];
+ /** The sun's height above the horizon in degrees, negative below it. */
+ sunElevation: number;
+ /** The sun's azimuth as the effects take it: degrees from +Z toward +X. */
+ sunAzimuth: number;
+ /** 0 at night, 1 by day, with the dusk between. */
+ daylight: number;
+ /** The unit vector the key (directional) light shines FROM: the sun by day, the moon by night. */
+ lightDir: [number, number, number];
+ /** × the key light's strength, and what it is tinted: warm at the horizon, white overhead, blue by moonlight. */
+ light: number;
+ lightTint: [number, number, number];
+ /** × the ambient light's strength, and its tint. */
+ sky: number;
+ skyTint: [number, number, number];
+ /** × what baked reflection probes show, and × their colour. */
+ reflection: number;
+ reflectionSaturation: number;
+ /** × Height Fog's colour (how lit the haze is), and the dusk colour it moves toward and how far. */
+ fogBrightness: number;
+ fogDusk: number;
+ /** Stops added to the exposure compensation: a night is kept readable, not as bright as a day. */
+ exposure: number;
+}
+
+/** What a time of day drives. A bit each, so a project can take the sky from the clock and keep its own light. */
+export const TimeDrive = {
+ Lights: 1,
+ Sky: 2,
+ Fog: 4,
+ Exposure: 8,
+ Reflections: 16,
+ All: 31,
+} as const;
+
+const RAD = Math.PI / 180;
+
+const smooth = (a: number, b: number, x: number): number => {
+ const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
+ return t * t * (3 - 2 * t);
+};
+const mix = (a: number, b: number, t: number): number => a + (b - a) * t;
+const mix3 = (a: [number, number, number], b: [number, number, number], t: number): [number, number, number] =>
+ [mix(a[0], b[0], t), mix(a[1], b[1], t), mix(a[2], b[2], t)];
+
+/** A direction from an elevation and an azimuth, both in radians, the azimuth from +Z toward +X. */
+function direction(elevation: number, azimuth: number): [number, number, number] {
+ const c = Math.cos(elevation);
+ return [c * Math.sin(azimuth), Math.sin(elevation), c * Math.cos(azimuth)];
+}
+
+/**
+ * The sun's place at an hour: its elevation and its azimuth from +Z toward +X, in radians.
+ *
+ * @param hour Solar time, 0..24; 12 is noon.
+ * @param latitude Degrees; where on the planet. Positive is north.
+ * @param declination Degrees, -23.5..23.5: the season. Positive is summer in the north.
+ * @param north Degrees the world is turned from compass north (+Z) toward +X.
+ */
+export function sunPosition(hour: number, latitude: number, declination: number, north: number): { elevation: number; azimuth: number } {
+ const phi = latitude * RAD;
+ const delta = declination * RAD;
+ const hourAngle = (hour - 12) * 15 * RAD;
+ const sinE = Math.sin(phi) * Math.sin(delta) + Math.cos(phi) * Math.cos(delta) * Math.cos(hourAngle);
+ const elevation = Math.asin(Math.min(Math.max(sinE, -1), 1));
+ // From north, clockwise (east is 90): mornings are east of the meridian and afternoons west of it.
+ const cosA = (Math.sin(delta) - sinE * Math.sin(phi)) / Math.max(Math.cos(elevation) * Math.cos(phi), 1e-5);
+ let compass = Math.acos(Math.min(Math.max(cosA, -1), 1));
+ if (hourAngle > 0) compass = 2 * Math.PI - compass;
+ // Compass north is +Z and east is +X until `north` turns the world; the effects count azimuth from +Z toward +X.
+ return { elevation, azimuth: compass + north * RAD };
+}
+
+/** The time of day at an hour. @public */
+export function timeOfDayAt(hour: number, latitude = 40, declination = 15, north = 0): TimeOfDayState {
+ const h = ((hour % 24) + 24) % 24;
+ const sun = sunPosition(h, latitude, declination, north);
+ const sinE = Math.sin(sun.elevation);
+ const sunDir = direction(sun.elevation, sun.azimuth);
+ // The moon stands opposite the sun and higher than the sun is low, so it is up for most of a night. Matches Sky Atmosphere.
+ const moonEl = -sun.elevation * 0.85 + 12 * RAD;
+ const moonDir = direction(moonEl, sun.azimuth + Math.PI);
+ const sinM = Math.sin(moonEl);
+
+ const daylight = smooth(-0.12, 0.28, sinE);
+ const dusk = Math.exp(-sinE * sinE * 60);
+
+ // The sun's own light: gone a little below the horizon, warm and weak while it is low.
+ const sunStrength = Math.pow(smooth(-0.03, 0.3, sinE), 1.1);
+ const warm = smooth(0, 0.4, sinE);
+ const sunTint: [number, number, number] = [1, mix(0.55, 0.97, warm), mix(0.3, 0.94, warm)];
+ // The moon's: a few hundredths of the sun's, blue, and only once the sun is well out of the way.
+ const moonStrength = 0.06 * smooth(0.0, 0.12, sinM) * smooth(-0.03, -0.12, sinE);
+ const sunUp = sinE > -0.03;
+
+ const nightSky: [number, number, number] = [0.5, 0.62, 1];
+ const duskSky: [number, number, number] = [1, 0.72, 0.55];
+ const skyTint = mix3(mix3(nightSky, [1, 1, 1], daylight), duskSky, dusk * 0.45);
+
+ return {
+ hour: h,
+ sunDir, moonDir,
+ sunElevation: sun.elevation / RAD,
+ sunAzimuth: ((sun.azimuth / RAD) % 360 + 360) % 360,
+ daylight,
+ lightDir: sunUp ? sunDir : moonDir,
+ light: sunUp ? sunStrength : moonStrength,
+ lightTint: sunUp ? sunTint : [0.55, 0.68, 1],
+ sky: mix(0.14, 1, daylight) * mix(1, 0.8, dusk),
+ skyTint,
+ reflection: mix(0.12, 1, daylight),
+ reflectionSaturation: mix(0.6, 1, daylight),
+ fogBrightness: mix(0.035, 1, daylight),
+ fogDusk: dusk * 0.5,
+ exposure: (1 - daylight) * 1.1,
+ };
+}
+
+/** The state the frame is under, or null when no TimeOfDay is. Set by the weather system, read by the volumes. */
+let current: { state: TimeOfDayState; drive: number; lightsApplied: boolean } | null = null;
+
+export function setCurrentTimeOfDay(state: TimeOfDayState | null, drive: number = TimeDrive.All, lightsApplied = false): void {
+ current = state ? { state, drive, lightsApplied } : null;
+}
+
+/** The time of day the frame is under, or null. @public */
+export function currentTimeOfDay(): TimeOfDayState | null {
+ return current ? current.state : null;
+}
+
+export function currentTimeDrive(): number {
+ return current ? current.drive : 0;
+}
+
+/** Whether the scene's lights are being moved by the clock (play mode); in the editor the effects stand in for them. */
+export function timeLightsApplied(): boolean {
+ return current ? current.lightsApplied : false;
+}
+
+function value(effect: BlendedEffect, type: string, name: string, fallback = 0): number {
+ const set = effect.uniforms.get(name);
+ if (set !== undefined) return set;
+ return getEffectDef(type)?.uniforms.find((u) => u.name === name)?.defaultValue ?? fallback;
+}
+
+function scaled(c: Rgba, k: number): Rgba {
+ return { r: c.r * k, g: c.g * k, b: c.b * k, a: c.a };
+}
+
+/**
+ * Applies the hour to what the volumes blended: the sky takes the sun's place, the fog is lit as the day is, the exposure
+ * is kept readable.
+ *
+ * @details In the editor the scene's lights are not moved by the clock, so the effects that follow "the scene's sun" are
+ * told where the clock's sun is instead; in play they follow the light, which the clock has moved.
+ */
+export function applyTimeToEffects(effects: Map<string, BlendedEffect>, state: TimeOfDayState, drive: number, lightsApplied: boolean): void {
+ if (drive & TimeDrive.Sky) {
+ const sky = effects.get('skyAtmosphere');
+ if (sky && sky.enabled) {
+ // The sky always takes the sun from the clock: the key light is the moon at night, and a sky must not draw it as the sun.
+ sky.uniforms.set('u_followSun', 0);
+ sky.uniforms.set('u_sunAzimuth', state.sunAzimuth);
+ sky.uniforms.set('u_sunElevation', state.sunElevation);
+ }
+ }
+ if (drive & TimeDrive.Fog) {
+ const fog = effects.get('heightFog');
+ if (fog && fog.enabled) {
+ if (!lightsApplied) {
+ fog.uniforms.set('u_followSun', 0);
+ fog.uniforms.set('u_sunAzimuth', state.sunAzimuth);
+ fog.uniforms.set('u_sunElevation', state.sunElevation);
+ // Without the light the glow has to go with the sun on its own.
+ fog.uniforms.set('u_inscatter', value(fog, 'heightFog', 'u_inscatter') * smooth(-0.05, 0.2, state.sunDir[1]));
+ }
+ const colour = fog.colors.get('u_fogColor')
+ ?? getEffectDef('heightFog')?.colors?.find((c) => c.name === 'u_fogColor')?.defaultValue;
+ if (colour) {
+ const dusk: [number, number, number] = [0.95, 0.55, 0.35];
+ const a = state.fogDusk;
+ const toward = {
+ r: colour.r * (1 - a) + dusk[0] * a, g: colour.g * (1 - a) + dusk[1] * a, b: colour.b * (1 - a) + dusk[2] * a, a: colour.a,
+ };
+ // The haze at night is a little blue as well as dark: the sky it is lit by is.
+ const night = 1 - state.daylight;
+ const blue = { r: toward.r * (1 - 0.3 * night), g: toward.g * (1 - 0.15 * night), b: toward.b, a: toward.a };
+ fog.colors.set('u_fogColor', scaled(blue, state.fogBrightness));
+ }
+ }
+ }
+ if (drive & TimeDrive.Exposure) {
+ const ae = effects.get('autoExposure');
+ if (ae && ae.enabled) ae.uniforms.set('u_bias', value(ae, 'autoExposure', 'u_bias') + state.exposure);
+ else if (state.exposure > 1e-3) {
+ const grade = effects.get('colorGrade');
+ if (grade && grade.enabled) grade.uniforms.set('u_exposure', value(grade, 'colorGrade', 'u_exposure') + state.exposure * 1.5);
+ }
+ }
+}
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index 27c66b2e5..3897870e8 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -11,6 +11,7 @@ import { blendVolumeEffects, computeVolumeFactor, type ActiveVolume, type Blende
import type { ShaderHandle } from '../render/material';
import { Material } from '../render/material';
import { applyWeatherToEffects, currentWeather, currentWeatherDrive } from './weather';
+import { applyTimeToEffects, currentTimeOfDay, currentTimeDrive, timeLightsApplied } from './timeOfDay';
export interface PostProcessVolumeConfig {
enabled: boolean;
@@ -229,6 +230,8 @@ export const postProcessVolumeSystem = defineSystem(
// brings the effects a weather implies.
const weather = currentWeather();
if (weather) applyWeatherToEffects(blended, weather, currentWeatherDrive());
+ const clock = currentTimeOfDay();
+ if (clock) applyTimeToEffects(blended, clock, currentTimeDrive(), timeLightsApplied());
applyBlendedEffects(api, cameraEntity, blended);
}
diff --git a/sdk/src/postprocess/weather.ts b/sdk/src/postprocess/weather.ts
index f30a6ae36..99f9dbe4a 100644
--- a/sdk/src/postprocess/weather.ts
+++ b/sdk/src/postprocess/weather.ts
@@ -52,6 +52,8 @@ export interface WeatherState {
* whatever sky the scene had then. */
reflection: number;
reflectionSaturation: number;
+ /** How overcast the sky is, 0 clear .. 1 grey: what Sky Atmosphere draws no sun, moon or stars through. */
+ overcast: number;
/** How loud the rain on the soundtrack is, 0..2. */
sound: number;
}
@@ -63,7 +65,7 @@ const NEUTRAL: WeatherState = {
fogDensity: 1, fogTint: [0.7, 0.72, 0.76], fogTintAmount: 0, fogGlow: 1, skyFog: 1,
saturation: 1, contrast: 1, exposure: 0,
rain: 0, wetness: 0, puddles: 0, ssr: 1,
- reflection: 1, reflectionSaturation: 1, sound: 0,
+ reflection: 1, reflectionSaturation: 1, overcast: 0, sound: 0,
};
/** The presets every project has. Their ids are the dropdown's values, so they only ever grow. */
@@ -96,22 +98,22 @@ define(WEATHER_CLEAR, 'clear', {});
define(WEATHER_MIST, 'mist', {
sun: 0.45, sky: 0.9, shadowSoftness: 3, shadowStrength: 0.8, fogDensity: 8, fogTint: [0.86, 0.86, 0.84], fogTintAmount: 0.7, fogGlow: 1.8, skyFog: 1.7,
saturation: 0.86, contrast: 0.94, exposure: 0.2, wetness: 0.2, puddles: 0.1, ssr: 1.3, reflection: 0.85,
- reflectionSaturation: 0.9,
+ reflectionSaturation: 0.9, overcast: 0.55,
});
define(WEATHER_OVERCAST, 'overcast', {
sun: 0.25, sky: 0.85, sunTint: [0.9, 0.93, 1], shadowSoftness: 8, shadowStrength: 0.5, fogDensity: 3, fogTint: [0.62, 0.66, 0.72], fogTintAmount: 0.5,
fogGlow: 0.3, skyFog: 1.4, saturation: 0.85, contrast: 0.96, exposure: 0.25, wetness: 0.1, ssr: 1.2,
- reflection: 0.7, reflectionSaturation: 0.7,
+ reflection: 0.7, reflectionSaturation: 0.7, overcast: 0.95,
});
define(WEATHER_RAIN, 'rain', {
sun: 0.04, sky: 0.75, sunTint: [0.8, 0.86, 1], shadowSoftness: 10, shadowStrength: 0.3, fogDensity: 5.5, fogTint: [0.58, 0.63, 0.7], fogTintAmount: 0.8,
fogGlow: 0, skyFog: 1.7, saturation: 0.73, contrast: 0.93, exposure: 0.45, rain: 1.1, wetness: 1, puddles: 0.6,
- ssr: 2.6, reflection: 0.55, reflectionSaturation: 0.5, sound: 1,
+ ssr: 2.6, reflection: 0.55, reflectionSaturation: 0.5, overcast: 0.9, sound: 1,
});
define(WEATHER_STORM, 'storm', {
sun: 0.02, sky: 0.5, sunTint: [0.7, 0.78, 1], shadowSoftness: 10, shadowStrength: 0.2, fogDensity: 8, fogTint: [0.4, 0.44, 0.5], fogTintAmount: 0.9,
fogGlow: 0, skyFog: 1.8, saturation: 0.6, contrast: 0.9, exposure: 0.8, rain: 2.2, wetness: 1, puddles: 1,
- ssr: 3, reflection: 0.4, reflectionSaturation: 0.35, sound: 1.6,
+ ssr: 3, reflection: 0.4, reflectionSaturation: 0.35, overcast: 1, sound: 1.6,
});
/**
@@ -237,6 +239,10 @@ export function applyWeatherToEffects(effects: Map<string, BlendedEffect>, state
if (colour && state.fogTintAmount > 0) fog.colors.set('u_fogColor', towards(colour, state.fogTint, state.fogTintAmount));
}
}
+ if (drive & WeatherDrive.Fog) {
+ const sky = effects.get('skyAtmosphere');
+ if (sky && sky.enabled) sky.uniforms.set('u_overcast', Math.max(value(sky, 'skyAtmosphere', 'u_overcast'), state.overcast));
+ }
if (drive & WeatherDrive.Rain) {
if (state.rain > 0.001 || state.wetness > 0.001) {
// A rain the scene authored is a floor the weather rises above; one the weather brings is exactly its own.
diff --git a/sdk/src/postprocess/weatherSystem.ts b/sdk/src/postprocess/weatherSystem.ts
index 21f29c521..49c5154c6 100644
--- a/sdk/src/postprocess/weatherSystem.ts
+++ b/sdk/src/postprocess/weatherSystem.ts
@@ -2,18 +2,22 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file weatherSystem.ts
- * @brief Runs the scene's Weather: advances its turns and cycle, and puts it on the lights.
+ * @brief Runs the scene's Weather and TimeOfDay: advances them, and puts them on the lights.
*
- * @details Only the lights are written to — the effects are read from `currentWeather()` by the volume system a step later,
- * which is what lets the editor preview the post-process half of a weather without the scene's own lights being
- * changed (and saved) by it. The lights are rewritten only in play mode, from the strengths they were authored
- * with, and put back when the weather goes.
+ * @details Only the lights are written to — the effects are read from `currentWeather()` and `currentTimeOfDay()` by the
+ * volume system a step later, which is what lets the editor preview the post-process half of a weather or an hour
+ * without the scene's own lights being changed (and saved) by it. The lights are rewritten only in play mode, from
+ * the strengths they were authored with, and put back when the weather and the clock go. One system owns both
+ * because both scale the same lights: each from what the author set, neither from the other's last answer.
*/
import { defineSystem } from '../ecs/system';
import { Res, Time, type TimeData } from '../ecs/resource';
import { Query, Mut } from '../ecs/query';
import { GetWorld } from '../ecs/system';
-import { Weather, Light, type WeatherData, type LightData } from '../ecs/component';
+import {
+ Weather, TimeOfDay, Light, Transform,
+ type WeatherData, type TimeOfDayData, type LightData, type TransformData,
+} from '../ecs/component';
import { AudioSource, type AudioSourceData } from '../audio/AudioComponents';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
@@ -21,6 +25,7 @@ import { isEditor, isPlayMode } from '../ecs/env';
import {
blendWeather, setCurrentWeather, weatherPresetId, WEATHER_NONE, WeatherDrive, type WeatherState,
} from './weather';
+import { timeOfDayAt, setCurrentTimeOfDay, TimeDrive, type TimeOfDayState } from './timeOfDay';
/** What a light was authored with, kept so a weather scales the author's number and never its own last answer. */
interface LightBase {
@@ -30,7 +35,11 @@ interface LightBase {
reflectionSaturation: number;
sourceAngle: number;
shadowStrength: number;
- applied: number;
+ aimFollowedSun: boolean;
+ bakedTint: { r: number; g: number; b: number; a: number };
+ /** The aim the light had, once the clock has taken it. */
+ rotation: { x: number; y: number; z: number; w: number } | null;
+ applied: string;
}
const bases = new Map<Entity, LightBase>();
@@ -51,15 +60,77 @@ function restoreLights(world: World): void {
world.set(entity, Light, {
...data, intensity: base.intensity, color: { ...base.color },
reflectionScale: base.reflectionScale, reflectionSaturation: base.reflectionSaturation,
- sourceAngle: base.sourceAngle, shadowStrength: base.shadowStrength,
+ sourceAngle: base.sourceAngle, shadowStrength: base.shadowStrength, aimFollowedSun: base.aimFollowedSun,
+ bakedTint: { ...base.bakedTint },
});
}
+ if (base.rotation && world.has(entity, Transform)) {
+ const t = world.get(entity, Transform) as TransformData;
+ world.set(entity, Transform, { ...t, rotation: { ...base.rotation } });
+ }
}
bases.clear();
}
-function applyLights(world: World, state: WeatherState, drive: number): void {
+/** The rotation that turns a thing facing -Z (a light) to face `f`: a turn about Y, then one about X. */
+function aimQuaternion(f: [number, number, number]): { x: number; y: number; z: number; w: number } {
+ const len = Math.hypot(f[0], f[1], f[2]) || 1;
+ const yaw = Math.atan2(-f[0], -f[2]);
+ const pitch = Math.asin(Math.min(Math.max(f[1] / len, -1), 1));
+ const qy = { w: Math.cos(yaw / 2), x: 0, y: Math.sin(yaw / 2), z: 0 };
+ const qx = { w: Math.cos(pitch / 2), x: Math.sin(pitch / 2), y: 0, z: 0 };
+ return {
+ w: qy.w * qx.w - qy.x * qx.x - qy.y * qx.y - qy.z * qx.z,
+ x: qy.w * qx.x + qy.x * qx.w + qy.y * qx.z - qy.z * qx.y,
+ y: qy.w * qx.y - qy.x * qx.z + qy.y * qx.w + qy.z * qx.x,
+ z: qy.w * qx.z + qy.x * qx.y - qy.y * qx.x + qy.z * qx.w,
+ };
+}
+
+/**
+ * Whether the scene's key light already shines the way the clock says: the case in the editor when something other than the
+ * clock (a script, a hand) has set the lights to the hour, and the effects that follow the sun should follow that light.
+ */
+function keyLightAgrees(world: World, time: TimeOfDayState): boolean {
for (const entity of world.getEntitiesWithComponents([Light])) {
+ const data = world.get(entity, Light) as LightData;
+ if (data.type !== LIGHT_DIRECTIONAL || !(data.followEnvironmentSun || data.meshShadows) || !world.has(entity, Transform)) continue;
+ const q = (world.get(entity, Transform) as TransformData).rotation;
+ const f: [number, number, number] = [-2 * (q.x * q.z + q.w * q.y), -2 * (q.y * q.z - q.w * q.x), -(1 - 2 * (q.x * q.x + q.y * q.y))];
+ const l = time.lightDir;
+ return -(f[0] * l[0] + f[1] * l[1] + f[2] * l[2]) > 0.9985;
+ }
+ return false;
+}
+
+/** What is scaling the lights this frame: a weather, a time of day, either, both. */
+interface Rig {
+ weather: WeatherState | null;
+ weatherDrive: number;
+ time: TimeOfDayState | null;
+ timeDrive: number;
+}
+
+function applyLights(world: World, rig: Rig): void {
+ const { weather, time } = rig;
+ const lightsByWeather = !!weather && (rig.weatherDrive & WeatherDrive.Lights) !== 0;
+ const reflectionsByWeather = !!weather && (rig.weatherDrive & WeatherDrive.Reflections) !== 0;
+ const lightsByTime = !!time && (rig.timeDrive & TimeDrive.Lights) !== 0;
+ const reflectionsByTime = !!time && (rig.timeDrive & TimeDrive.Reflections) !== 0;
+
+ const lights = world.getEntitiesWithComponents([Light]);
+ // The sun of the scene, for the clock to aim: the lights that follow a panorama's sun or cast shadows, else the first directional.
+ const suns = new Set<Entity>();
+ let firstDirectional: Entity | null = null;
+ for (const entity of lights) {
+ const data = world.get(entity, Light) as LightData;
+ if (data.type !== LIGHT_DIRECTIONAL) continue;
+ if (firstDirectional === null) firstDirectional = entity;
+ if (data.followEnvironmentSun || data.meshShadows) suns.add(entity);
+ }
+ if (suns.size === 0 && firstDirectional !== null) suns.add(firstDirectional);
+
+ for (const entity of lights) {
const data = world.get(entity, Light) as LightData;
if (data.type !== LIGHT_DIRECTIONAL && data.type !== LIGHT_AMBIENT) continue;
let base = bases.get(entity);
@@ -68,33 +139,58 @@ function applyLights(world: World, state: WeatherState, drive: number): void {
intensity: data.intensity, color: { ...data.color },
reflectionScale: data.reflectionScale ?? 1, reflectionSaturation: data.reflectionSaturation ?? 1,
sourceAngle: data.sourceAngle ?? 0, shadowStrength: data.shadowStrength ?? 1,
- applied: Number.NaN,
+ aimFollowedSun: data.aimFollowedSun ?? false,
+ bakedTint: { ...(data.bakedTint ?? { r: 1, g: 1, b: 1, a: 1 }) }, rotation: null,
+ applied: '',
};
bases.set(entity, base);
}
const sun = data.type === LIGHT_DIRECTIONAL;
- const lights = (drive & WeatherDrive.Lights) !== 0;
- const reflections = (drive & WeatherDrive.Reflections) !== 0 && !sun;
- const scale = lights ? (sun ? state.sun : state.sky) : 1;
+ const wScale = lightsByWeather ? (sun ? weather!.sun : weather!.sky) : 1;
+ const tScale = lightsByTime ? (sun ? time!.light : time!.sky) : 1;
+ const wTint: [number, number, number] = lightsByWeather && sun ? weather!.sunTint : [1, 1, 1];
+ const tTint: [number, number, number] = lightsByTime ? (sun ? time!.lightTint : time!.skyTint) : [1, 1, 1];
+ const reflections = !sun && (reflectionsByWeather || reflectionsByTime);
+ const refl = (reflectionsByWeather ? weather!.reflection : 1) * (reflectionsByTime ? time!.reflection : 1);
+ const reflSat = (reflectionsByWeather ? weather!.reflectionSaturation : 1) * (reflectionsByTime ? time!.reflectionSaturation : 1);
+ const aimed = lightsByTime && sun && suns.has(entity);
+ // A bake holds one moment's light, so the ambient light's scale and tint are laid over it too.
+ const bake = !sun && (lightsByWeather || lightsByTime);
// The key is what the light would be told: nothing is written for a frame that would say the same again.
- const key = scale + (lights && sun ? state.sunTint[0] * 7 + state.sunTint[1] * 13 + state.sunTint[2] * 29 : 0)
- + (reflections ? state.reflection * 101 + state.reflectionSaturation * 211 : 0)
- + (lights && sun ? state.shadowSoftness * 307 + state.shadowStrength * 401 : 0);
+ const key = [
+ wScale, tScale, wTint[0], wTint[1], wTint[2], tTint[0], tTint[1], tTint[2], reflections ? refl : 0, reflections ? reflSat : 0,
+ lightsByWeather && sun ? weather!.shadowSoftness : 0, lightsByWeather && sun ? weather!.shadowStrength : 0,
+ bake ? 1 : 0, aimed ? time!.lightDir[0] : 0, aimed ? time!.lightDir[1] : 0, aimed ? time!.lightDir[2] : 0,
+ ].map((v) => v.toFixed(5)).join(',');
if (base.applied === key) continue;
base.applied = key;
- const color = lights && sun
- ? { r: base.color.r * state.sunTint[0], g: base.color.g * state.sunTint[1], b: base.color.b * state.sunTint[2], a: base.color.a }
- : { ...base.color };
+ const color = {
+ r: base.color.r * wTint[0] * tTint[0], g: base.color.g * wTint[1] * tTint[1], b: base.color.b * wTint[2] * tTint[2], a: base.color.a,
+ };
// A sun's width in the sky is 0.53 degrees: softer shadows are a wider source, and a hard-edged light (0) gains the
// difference too, so the setting always means something.
- const widen = lights && sun ? Math.max(state.shadowSoftness - 1, 0) * 0.53 : 0;
+ const widen = lightsByWeather && sun ? Math.max(weather!.shadowSoftness - 1, 0) * 0.53 : 0;
world.set(entity, Light, {
- ...data, intensity: base.intensity * scale, color,
+ ...data, intensity: base.intensity * wScale * tScale, color,
sourceAngle: base.sourceAngle + widen,
- shadowStrength: lights && sun ? Math.min(base.shadowStrength * state.shadowStrength, 1) : base.shadowStrength,
- reflectionScale: reflections ? base.reflectionScale * state.reflection : base.reflectionScale,
- reflectionSaturation: reflections ? base.reflectionSaturation * state.reflectionSaturation : base.reflectionSaturation,
+ shadowStrength: lightsByWeather && sun ? Math.min(base.shadowStrength * weather!.shadowStrength, 1) : base.shadowStrength,
+ reflectionScale: reflections ? base.reflectionScale * refl : base.reflectionScale,
+ reflectionSaturation: reflections ? base.reflectionSaturation * reflSat : base.reflectionSaturation,
+ aimFollowedSun: aimed ? true : base.aimFollowedSun,
+ bakedTint: bake
+ ? { r: base.bakedTint.r * wScale * tScale * tTint[0], g: base.bakedTint.g * wScale * tScale * tTint[1], b: base.bakedTint.b * wScale * tScale * tTint[2], a: 1 }
+ : { ...base.bakedTint },
});
+ if (aimed && world.has(entity, Transform)) {
+ const t = world.get(entity, Transform) as TransformData;
+ if (!base.rotation) base.rotation = { ...t.rotation };
+ const l = time!.lightDir;
+ world.set(entity, Transform, { ...t, rotation: aimQuaternion([-l[0], -l[1], -l[2]]) });
+ } else if (!aimed && base.rotation && world.has(entity, Transform)) {
+ const t = world.get(entity, Transform) as TransformData;
+ world.set(entity, Transform, { ...t, rotation: { ...base.rotation } });
+ base.rotation = null;
+ }
}
}
@@ -163,28 +259,52 @@ function advance(entity: Entity, data: WeatherData, dt: number): void {
}
export const weatherSystem = defineSystem(
- [Query(Mut(Weather)), Res(Time), GetWorld()],
- (weathers: Iterable<[Entity, WeatherData]>, time: TimeData, world: World) => {
+ [Query(Mut(Weather)), Query(Mut(TimeOfDay)), Res(Time), GetWorld()],
+ (weathers: Iterable<[Entity, WeatherData]>, times: Iterable<[Entity, TimeOfDayData]>, time: TimeData, world: World) => {
let found: [Entity, WeatherData] | null = null;
for (const entry of weathers) { found = entry; break; }
- if (!found) {
+ let clock: [Entity, TimeOfDayData] | null = null;
+ for (const entry of times) { clock = entry; break; }
+ if (!found && !clock) {
if (bases.size > 0) restoreLights(world);
if (soundBases.size > 0) restoreSound(world);
cycles.clear();
setCurrentWeather(null);
+ setCurrentTimeOfDay(null);
return;
}
- const [entity, data] = found;
const playing = !isEditor() || isPlayMode();
- if (playing) advance(entity, data, time.delta);
- const state = blendWeather(data.preset, data.target, data.progress);
- setCurrentWeather(state, data.drive);
+ let weatherState: WeatherState | null = null;
+ let weatherDrive = 0;
+ if (found) {
+ const [entity, data] = found;
+ if (playing) advance(entity, data, time.delta);
+ weatherState = blendWeather(data.preset, data.target, data.progress);
+ weatherDrive = data.drive;
+ setCurrentWeather(weatherState, data.drive);
+ } else {
+ setCurrentWeather(null);
+ }
+
+ let timeState: TimeOfDayState | null = null;
+ let timeDrive = 0;
+ if (clock) {
+ const data = clock[1];
+ if (playing && data.daySeconds > 0) data.hour = (data.hour + time.delta * 24 / data.daySeconds) % 24;
+ timeState = timeOfDayAt(data.hour, data.latitude, data.declination, data.north);
+ timeDrive = data.drive;
+ setCurrentTimeOfDay(timeState, data.drive, (playing && (data.drive & TimeDrive.Lights) !== 0) || (!playing && keyLightAgrees(world, timeState)));
+ } else {
+ setCurrentTimeOfDay(null);
+ }
- if (playing && (data.drive & (WeatherDrive.Lights | WeatherDrive.Reflections))) applyLights(world, state, data.drive);
+ const lightWork = (weatherState !== null && (weatherDrive & (WeatherDrive.Lights | WeatherDrive.Reflections)) !== 0)
+ || (timeState !== null && (timeDrive & (TimeDrive.Lights | TimeDrive.Reflections)) !== 0);
+ if (playing && lightWork) applyLights(world, { weather: weatherState, weatherDrive, time: timeState, timeDrive });
else if (bases.size > 0) restoreLights(world);
- if (playing && (data.drive & WeatherDrive.Sound) && data.soundSource) applySound(world, data.soundSource, state);
+ if (found && playing && (found[1].drive & WeatherDrive.Sound) && found[1].soundSource) applySound(world, found[1].soundSource, weatherState!);
else if (soundBases.size > 0) restoreSound(world);
},
{ name: 'WeatherSystem' }
@@ -196,4 +316,5 @@ export function resetWeatherSystem(): void {
soundBases.clear();
cycles.clear();
setCurrentWeather(null);
+ setCurrentTimeOfDay(null);
}
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 6a8d8d63c..334f55887 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -244,12 +244,14 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'meshShadows', type: 'bool', offset: 72 },
{ name: 'shadowExtent', type: 'f32', offset: 76 },
{ name: 'followEnvironmentSun', type: 'bool', offset: 80 },
+ { name: 'aimFollowedSun', type: 'bool', offset: 81 },
{ name: 'environment', type: 'u32', offset: 84 },
{ name: 'environmentRotation', type: 'f32', offset: 88 },
{ name: 'drawEnvironment', type: 'bool', offset: 92 },
{ name: 'reflectionScale', type: 'f32', offset: 96 },
{ name: 'reflectionSaturation', type: 'f32', offset: 100 },
- { name: 'enabled', type: 'bool', offset: 104 },
+ { name: 'bakedTint', type: 'color', offset: 104 },
+ { name: 'enabled', type: 'bool', offset: 120 },
],
},
LightProbeVolume: {
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index d5834292a..bfeae31a5 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -617,11 +617,13 @@ export interface Light {
meshShadows: boolean;
shadowExtent: number;
followEnvironmentSun: boolean;
+ aimFollowedSun: boolean;
environment: number;
environmentRotation: number;
drawEnvironment: boolean;
reflectionScale: number;
reflectionSaturation: number;
+ bakedTint: Vec4;
enabled: boolean;
}
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 7e8e3641b..92e70807f 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -217,6 +217,26 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
},
},
"Light": {
+ "aimFollowedSun": {
+ "advanced": true,
+ "shownWhen": {
+ "field": "type",
+ "values": [
+ 1,
+ ],
+ },
+ "tooltip": "With Follow Environment Sun: aim by this light's Transform, not by the panorama.",
+ },
+ "bakedTint": {
+ "advanced": true,
+ "shownWhen": {
+ "field": "type",
+ "values": [
+ 2,
+ ],
+ },
+ "tooltip": "Multiply baked indirect light (lightmaps, probe volumes) by this colour (1 = as baked).",
+ },
"cookie": {
"shownWhen": {
"field": "type",
@@ -1477,6 +1497,62 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"step": 1,
},
},
+ "TimeOfDay": {
+ "daySeconds": {
+ "max": 86400,
+ "min": 0,
+ "step": 1,
+ "unit": "s",
+ },
+ "declination": {
+ "max": 23.5,
+ "min": -23.5,
+ "step": 0.5,
+ "unit": "deg",
+ },
+ "drive": {
+ "flags": [
+ {
+ "label": "Lights",
+ "value": 1,
+ },
+ {
+ "label": "Sky",
+ "value": 2,
+ },
+ {
+ "label": "Fog",
+ "value": 4,
+ },
+ {
+ "label": "Exposure",
+ "value": 8,
+ },
+ {
+ "label": "Reflections",
+ "value": 16,
+ },
+ ],
+ },
+ "hour": {
+ "max": 24,
+ "min": 0,
+ "step": 0.05,
+ "unit": "h",
+ },
+ "latitude": {
+ "max": 90,
+ "min": -90,
+ "step": 1,
+ "unit": "deg",
+ },
+ "north": {
+ "max": 180,
+ "min": -180,
+ "step": 1,
+ "unit": "deg",
+ },
+ },
"TrailRenderer": {
"blendMode": {
"category": "Rendering",
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index bb1ffa5ec..40075f5c0 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -53,7 +53,7 @@ describe('embedded .esshader structure', () => {
it('found the filter, effect and grid sources', () => {
expect(CASES.filter((c) => c.name.startsWith('filters.ts')).length).toBe(1);
expect(CASES.filter((c) => c.name.startsWith('spriteFilter.ts')).length).toBe(2);
- expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(33);
+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(34);
expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);
});
diff --git a/sdk/tests/time-of-day.test.ts b/sdk/tests/time-of-day.test.ts
new file mode 100644
index 000000000..19dc6c9eb
--- /dev/null
+++ b/sdk/tests/time-of-day.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect } from 'vitest';
+import { timeOfDayAt, sunPosition, applyTimeToEffects, TimeDrive } from '../src/postprocess/timeOfDay';
+import { blendWeather, WEATHER_RAIN, WEATHER_CLEAR } from '../src/postprocess/weather';
+import type { BlendedEffect } from '../src/postprocess/volumeBlending';
+import '../src/postprocess/effects';
+
+const effect = (uniforms: Record<string, number> = {}, colors: Record<string, { r: number; g: number; b: number; a: number }> = {}): BlendedEffect => ({
+ enabled: true, uniforms: new Map(Object.entries(uniforms)), textures: new Map(), colors: new Map(Object.entries(colors)),
+});
+
+describe('sunPosition', () => {
+ it('stands highest at noon, at the height the latitude and season give', () => {
+ const noon = sunPosition(12, 40, 15, 0);
+ expect(noon.elevation * 180 / Math.PI).toBeCloseTo(90 - 40 + 15, 3);
+ const winter = sunPosition(12, 40, -20, 0);
+ expect(winter.elevation).toBeLessThan(noon.elevation);
+ });
+
+ it('rises in the east and sets in the west', () => {
+ const morning = timeOfDayAt(7).sunDir;
+ const evening = timeOfDayAt(17).sunDir;
+ expect(morning[0]).toBeGreaterThan(0.3);
+ expect(evening[0]).toBeLessThan(-0.3);
+ });
+
+ it('is below the horizon at midnight and symmetric about noon', () => {
+ expect(timeOfDayAt(0).sunDir[1]).toBeLessThan(-0.3);
+ expect(timeOfDayAt(9).sunDir[1]).toBeCloseTo(timeOfDayAt(15).sunDir[1], 5);
+ });
+
+ it('turns with the world', () => {
+ const a = timeOfDayAt(7, 40, 15, 0).sunDir;
+ const b = timeOfDayAt(7, 40, 15, 90).sunDir;
+ // A quarter turn takes +X to -Z.
+ expect(b[2]).toBeCloseTo(-a[0], 4);
+ expect(b[1]).toBeCloseTo(a[1], 6);
+ });
+});
+
+describe('timeOfDayAt', () => {
+ it('lights a day fully and a night with the moon alone', () => {
+ const noon = timeOfDayAt(12);
+ const night = timeOfDayAt(1);
+ expect(noon.light).toBeGreaterThan(0.95);
+ expect(noon.sky).toBeGreaterThan(0.9);
+ expect(night.light).toBeGreaterThan(0);
+ expect(night.light).toBeLessThan(0.08);
+ expect(night.lightTint[2]).toBeGreaterThan(night.lightTint[0]);
+ // The key light is aimed at the moon, which is above the horizon.
+ expect(night.lightDir[1]).toBeGreaterThan(0);
+ expect(night.sky).toBeLessThan(0.16);
+ });
+
+ it('makes the low sun warm and weak', () => {
+ const low = timeOfDayAt(6.3);
+ const noon = timeOfDayAt(12);
+ expect(low.light).toBeLessThan(noon.light);
+ expect(low.lightTint[2]).toBeLessThan(low.lightTint[0] - 0.05);
+ });
+
+ it('never has the key light jump in strength between neighbouring minutes', () => {
+ let previous = timeOfDayAt(0).light;
+ for (let m = 1; m <= 24 * 60; m++) {
+ const light = timeOfDayAt(m / 60).light;
+ expect(Math.abs(light - previous)).toBeLessThan(0.05);
+ previous = light;
+ }
+ });
+
+ it('wraps the hour', () => {
+ expect(timeOfDayAt(25).sunDir[1]).toBeCloseTo(timeOfDayAt(1).sunDir[1], 6);
+ expect(timeOfDayAt(-1).sunDir[1]).toBeCloseTo(timeOfDayAt(23).sunDir[1], 6);
+ });
+});
+
+describe('applyTimeToEffects', () => {
+ it('gives the sky the clock\'s sun and the fog the night\'s darkness', () => {
+ const state = timeOfDayAt(1);
+ const effects = new Map<string, BlendedEffect>([
+ ['skyAtmosphere', effect()],
+ ['heightFog', effect({}, { u_fogColor: { r: 0.6, g: 0.7, b: 0.8, a: 1 } })],
+ ['autoExposure', effect({ u_bias: 0.1 })],
+ ]);
+ applyTimeToEffects(effects, state, TimeDrive.All, false);
+ const sky = effects.get('skyAtmosphere')!;
+ expect(sky.uniforms.get('u_followSun')).toBe(0);
+ expect(sky.uniforms.get('u_sunElevation')).toBeCloseTo(state.sunElevation, 6);
+ const fog = effects.get('heightFog')!;
+ expect(fog.colors.get('u_fogColor')!.g).toBeLessThan(0.1);
+ // Without the clock's lights the fog is told where the sun is instead of following a light that is not moving.
+ expect(fog.uniforms.get('u_followSun')).toBe(0);
+ expect(effects.get('autoExposure')!.uniforms.get('u_bias')).toBeGreaterThan(0.5);
+ });
+
+ it('leaves the fog following the light when the clock moves the lights', () => {
+ const effects = new Map<string, BlendedEffect>([['heightFog', effect({}, { u_fogColor: { r: 0.6, g: 0.7, b: 0.8, a: 1 } })]]);
+ applyTimeToEffects(effects, timeOfDayAt(12), TimeDrive.All, true);
+ expect(effects.get('heightFog')!.uniforms.has('u_followSun')).toBe(false);
+ });
+
+ it('touches only what it is asked to drive', () => {
+ const effects = new Map<string, BlendedEffect>([['skyAtmosphere', effect()], ['autoExposure', effect({ u_bias: 0 })]]);
+ applyTimeToEffects(effects, timeOfDayAt(1), TimeDrive.Exposure, false);
+ expect(effects.get('skyAtmosphere')!.uniforms.size).toBe(0);
+ expect(effects.get('autoExposure')!.uniforms.get('u_bias')).toBeGreaterThan(0);
+ });
+});
+
+describe('the weather and the sky', () => {
+ it('is overcast under rain and clear under a clear sky', () => {
+ expect(blendWeather(WEATHER_RAIN, -1, 0).overcast).toBeGreaterThan(0.8);
+ expect(blendWeather(WEATHER_CLEAR, -1, 0).overcast).toBe(0);
+ });
+});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index f61a70766..1b6e5eaf8 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash ef5132d57ac30f0c
+ * @schema_hash 1d33842a5824a059
*/
-#define ES_EDITOR_API_SCHEMA_HASH "ef5132d57ac30f0c"
+#define ES_EDITOR_API_SCHEMA_HASH "1d33842a5824a059"
#include <emscripten/bind.h>
#include <string>
@@ -352,11 +352,16 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"meshShadows","type":"bool","group":"Light"},
{"key":"shadowExtent","type":"float","group":"Light"},
{"key":"followEnvironmentSun","type":"bool","group":"Light"},
+ {"key":"aimFollowedSun","type":"bool","group":"Light"},
{"key":"environment","type":"asset","group":"Light"},
{"key":"environmentRotation","type":"float","group":"Light"},
{"key":"drawEnvironment","type":"bool","group":"Light"},
{"key":"reflectionScale","type":"float","group":"Light"},
{"key":"reflectionSaturation","type":"float","group":"Light"},
+ {"key":"bakedTint.r","type":"color","group":"Light"},
+ {"key":"bakedTint.g","type":"color","group":"Light"},
+ {"key":"bakedTint.b","type":"color","group":"Light"},
+ {"key":"bakedTint.a","type":"color","group":"Light"},
{"key":"enabled","type":"bool","group":"Light"}
])JSON";
} else if (name == "LightProbeVolume") {
@@ -1377,6 +1382,10 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "environmentRotation") { c.environmentRotation = value; }
else if (field == "reflectionScale") { c.reflectionScale = value; }
else if (field == "reflectionSaturation") { c.reflectionSaturation = value; }
+ else if (field == "bakedTint.r") { c.bakedTint.r = value; }
+ else if (field == "bakedTint.g") { c.bakedTint.g = value; }
+ else if (field == "bakedTint.b") { c.bakedTint.b = value; }
+ else if (field == "bakedTint.a") { c.bakedTint.a = value; }
else { return false; }
return true;
} else if (comp == "LightProbeVolume") {
@@ -1908,6 +1917,10 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "environmentRotation") { return c.environmentRotation; }
else if (field == "reflectionScale") { return c.reflectionScale; }
else if (field == "reflectionSaturation") { return c.reflectionSaturation; }
+ else if (field == "bakedTint.r") { return c.bakedTint.r; }
+ else if (field == "bakedTint.g") { return c.bakedTint.g; }
+ else if (field == "bakedTint.b") { return c.bakedTint.b; }
+ else if (field == "bakedTint.a") { return c.bakedTint.a; }
} else if (comp == "LightProbeVolume") {
if (!reg.has<esengine::ecs::LightProbeVolume>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::LightProbeVolume>(entity);
@@ -2837,6 +2850,7 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
auto& c = reg.get<esengine::ecs::Light>(entity);
if (field == "meshShadows") { c.meshShadows = value; }
else if (field == "followEnvironmentSun") { c.followEnvironmentSun = value; }
+ else if (field == "aimFollowedSun") { c.aimFollowedSun = value; }
else if (field == "drawEnvironment") { c.drawEnvironment = value; }
else if (field == "enabled") { c.enabled = value; }
else { return false; }
@@ -3100,6 +3114,7 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::Light>(entity);
if (field == "meshShadows") { return c.meshShadows; }
else if (field == "followEnvironmentSun") { return c.followEnvironmentSun; }
+ else if (field == "aimFollowedSun") { return c.aimFollowedSun; }
else if (field == "drawEnvironment") { return c.drawEnvironment; }
else if (field == "enabled") { return c.enabled; }
} else if (comp == "LightProbeVolume") {
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 98643d7f5..1902f0778 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -626,11 +626,13 @@ struct LightJS {
bool meshShadows;
f32 shadowExtent;
bool followEnvironmentSun;
+ bool aimFollowedSun;
u32 environment;
f32 environmentRotation;
bool drawEnvironment;
f32 reflectionScale;
f32 reflectionSaturation;
+ glm::vec4 bakedTint;
bool enabled;
};
@@ -652,11 +654,13 @@ void lightApplyJS(esengine::ecs::Light& c, const LightJS& js) {
c.meshShadows = js.meshShadows;
c.shadowExtent = js.shadowExtent;
c.followEnvironmentSun = js.followEnvironmentSun;
+ c.aimFollowedSun = js.aimFollowedSun;
c.environment = resource::EnvironmentHandle(js.environment);
c.environmentRotation = js.environmentRotation;
c.drawEnvironment = js.drawEnvironment;
c.reflectionScale = js.reflectionScale;
c.reflectionSaturation = js.reflectionSaturation;
+ c.bakedTint = js.bakedTint;
c.enabled = js.enabled;
}
@@ -685,11 +689,13 @@ LightJS lightToJS(const esengine::ecs::Light& c) {
js.meshShadows = c.meshShadows;
js.shadowExtent = c.shadowExtent;
js.followEnvironmentSun = c.followEnvironmentSun;
+ js.aimFollowedSun = c.aimFollowedSun;
js.environment = c.environment.id();
js.environmentRotation = c.environmentRotation;
js.drawEnvironment = c.drawEnvironment;
js.reflectionScale = c.reflectionScale;
js.reflectionSaturation = c.reflectionSaturation;
+ js.bakedTint = c.bakedTint;
js.enabled = c.enabled;
return js;
}
@@ -1825,11 +1831,13 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("meshShadows", &LightJS::meshShadows)
.field("shadowExtent", &LightJS::shadowExtent)
.field("followEnvironmentSun", &LightJS::followEnvironmentSun)
+ .field("aimFollowedSun", &LightJS::aimFollowedSun)
.field("environment", &LightJS::environment)
.field("environmentRotation", &LightJS::environmentRotation)
.field("drawEnvironment", &LightJS::drawEnvironment)
.field("reflectionScale", &LightJS::reflectionScale)
.field("reflectionSaturation", &LightJS::reflectionSaturation)
+ .field("bakedTint", &LightJS::bakedTint)
.field("enabled", &LightJS::enabled);
value_object<LightProbeVolumeJS>("LightProbeVolume")
@@ -3613,12 +3621,14 @@ static_assert(offsetof(esengine::ecs::Light, shadowDistance) == 68, "ABI offset
static_assert(offsetof(esengine::ecs::Light, meshShadows) == 72, "ABI offset drift: esengine::ecs::Light.meshShadows (EHT expected 72)");
static_assert(offsetof(esengine::ecs::Light, shadowExtent) == 76, "ABI offset drift: esengine::ecs::Light.shadowExtent (EHT expected 76)");
static_assert(offsetof(esengine::ecs::Light, followEnvironmentSun) == 80, "ABI offset drift: esengine::ecs::Light.followEnvironmentSun (EHT expected 80)");
+static_assert(offsetof(esengine::ecs::Light, aimFollowedSun) == 81, "ABI offset drift: esengine::ecs::Light.aimFollowedSun (EHT expected 81)");
static_assert(offsetof(esengine::ecs::Light, environment) == 84, "ABI offset drift: esengine::ecs::Light.environment (EHT expected 84)");
static_assert(offsetof(esengine::ecs::Light, environmentRotation) == 88, "ABI offset drift: esengine::ecs::Light.environmentRotation (EHT expected 88)");
static_assert(offsetof(esengine::ecs::Light, drawEnvironment) == 92, "ABI offset drift: esengine::ecs::Light.drawEnvironment (EHT expected 92)");
static_assert(offsetof(esengine::ecs::Light, reflectionScale) == 96, "ABI offset drift: esengine::ecs::Light.reflectionScale (EHT expected 96)");
static_assert(offsetof(esengine::ecs::Light, reflectionSaturation) == 100, "ABI offset drift: esengine::ecs::Light.reflectionSaturation (EHT expected 100)");
-static_assert(offsetof(esengine::ecs::Light, enabled) == 104, "ABI offset drift: esengine::ecs::Light.enabled (EHT expected 104)");
+static_assert(offsetof(esengine::ecs::Light, bakedTint) == 104, "ABI offset drift: esengine::ecs::Light.bakedTint (EHT expected 104)");
+static_assert(offsetof(esengine::ecs::Light, enabled) == 120, "ABI offset drift: esengine::ecs::Light.enabled (EHT expected 120)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, probes) == 0, "ABI offset drift: esengine::ecs::LightProbeVolume.probes (EHT expected 0)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, halfExtents) == 4, "ABI offset drift: esengine::ecs::LightProbeVolume.halfExtents (EHT expected 4)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, spacing) == 16, "ABI offset drift: esengine::ecs::LightProbeVolume.spacing (EHT expected 16)");
@@ -3891,7 +3901,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "174c991a07d3d3ef";
+static const char* kEsAbiLayoutHash = "8eba82ff470da2d6";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/Light.hpp b/src/esengine/ecs/components/Light.hpp
index a02f2d8cb..bd2a7aa29 100644
--- a/src/esengine/ecs/components/Light.hpp
+++ b/src/esengine/ecs/components/Light.hpp
@@ -168,6 +168,15 @@ struct Light {
tooltip="Take direction and strength from the environment's sun, and light the sky without it.")
bool followEnvironmentSun{false};
+ /** @brief With @ref followEnvironmentSun, aim this light by its own Transform instead of
+ * by where the panorama's sun is. The panorama still gives the light its colour
+ * and strength and still loses its sun in the lighting; only the direction is
+ * the scene's. What a time of day needs: a sun that crosses the sky over a
+ * panorama that was photographed with it in one place. */
+ ES_PROPERTY(shown_when=type:Directional, advanced,
+ tooltip="With Follow Environment Sun: aim by this light's Transform, not by the panorama.")
+ bool aimFollowedSun{false};
+
/** @brief What this Ambient light IS, when it is more than one colour: a baked
* panorama's irradiance and reflection. Without one the light stays the
* flat term it has always been — the same lighting, at order zero.
@@ -207,6 +216,15 @@ struct Light {
tooltip="How much colour baked reflection probes keep (0 = grey).")
f32 reflectionSaturation{1.0f};
+ /** @brief What baked INDIRECT light (a lightmap, a probe volume) is multiplied by. A bake
+ * holds the light of one moment, and a lightmapped surface takes all of its
+ * indirect light from it, so a scene that moves through a day or a weather scales
+ * and tints the bake here — the way it scales this light. 1 = as baked. Read from
+ * the frame's Ambient light. */
+ ES_PROPERTY(shown_when=type:Ambient, advanced,
+ tooltip="Multiply baked indirect light (lightmaps, probe volumes) by this colour (1 = as baked).")
+ glm::vec4 bakedTint{1.0f, 1.0f, 1.0f, 1.0f};
+
/** @brief Disabled lights are skipped during collection. */
ES_PROPERTY()
bool enabled{true};
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 24bbf7208..a529ac5c7 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -1357,6 +1357,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {
if (!tone) tone = &light;
}
if (tone) context_.lights().setReflectionTone(tone->reflectionScale, tone->reflectionSaturation);
+ context_.lights().setBakedTint(tone ? glm::vec3(tone->bakedTint) : glm::vec3(1.0f));
}
const bool sunCast = sunFollowed && sky && sky->hasSun;
if (sunCast) {
@@ -1421,7 +1422,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {
// z=1 flags directional (no attenuation) in the shader; w carries the aim's third
// component, which only a directional light has a use for — point and spot spend
// that slot on their falloff radius.
- const glm::vec3 aim = followsSun ? light_cap_.environmentSunAim
+ const glm::vec3 aim = followsSun && !light.aimFollowedSun ? light_cap_.environmentSunAim
: lightForward(registry.tryGet<ecs::Transform>(entity));
gpu.posDir = glm::vec4(aim.x, aim.y, 1.0f, aim.z);
// A source infinitely far away has no half-extent a map can divide by a
diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hpp
index 5e8ef9fb2..79af22863 100644
--- a/src/esengine/renderer/store/LightConstants.hpp
+++ b/src/esengine/renderer/store/LightConstants.hpp
@@ -191,13 +191,16 @@ struct LightConstants {
/// is the environment and has none — a sky is not somewhere. The shader
/// PROJECTS onto a box, which is what slides a reflection across a wall.
glm::vec4 reflBox[2 * MAX_REFLECTION_PROBES]{};
+ /// rgb = what the BAKED indirect light (a lightmap, a probe volume) is multiplied by: a bake holds one
+ /// moment's light, so a scene that passes through a day or a weather scales and tints it here (1 = as baked).
+ glm::vec4 bakedTint{1.0f};
};
static_assert(sizeof(GpuLight) == 96, "GpuLight must be std140-tight (six vec4s)");
static_assert(sizeof(LightConstants) == 16 + 96 * MAX_LIGHTS + 16
+ 64 * MAX_SHADOW_TILES + 16 * MAX_SHADOW_TILES
+ 16 + 16 * 9 + 16 + 16
- + 16 + 32 * MAX_REFLECTION_PROBES,
+ + 16 + 32 * MAX_REFLECTION_PROBES + 16,
"LightConstants must match the std140 GLSL block layout");
} // namespace esengine
diff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hpp
index 82cc89692..cfe3d9a89 100644
--- a/src/esengine/renderer/store/LightStore.hpp
+++ b/src/esengine/renderer/store/LightStore.hpp
@@ -128,6 +128,12 @@ public:
dirty_ = true;
}
+ /// What baked indirect light is multiplied by this frame: the day's or the weather's say on a bake of one moment.
+ void setBakedTint(const glm::vec3& tint) {
+ data_.bakedTint = glm::vec4(tint, 1.0f);
+ dirty_ = true;
+ }
+
/// Gives light @p slot a channel of the frame's 2D shadow mask, and says the mask
/// exists. A slot nobody names keeps the -1 it was collected with, which is a light
/// that lights without shadowing.
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index aa86868d1..312f62652 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -1137,6 +1137,7 @@ struct LightConstants {
u_envTint : vec4f,
u_reflParams : vec4f,
u_reflBox : array<vec4f, 30>,
+ u_bakedTint : vec4f,
};
@group(0) @binding(2) var<uniform> lc : LightConstants;
fn unpackDepth(c : vec3f) -> f32 {
@@ -1198,6 +1199,7 @@ struct LightConstants {
u_envTint : vec4f,
u_reflParams : vec4f,
u_reflBox : array<vec4f, 30>,
+ u_bakedTint : vec4f,
};
@group(0) @binding(2) var<uniform> lc : LightConstants;
struct ProbeConstants { u_probeIrradiance : array<vec4f, 1000>, u_probeTail : vec4f };
@@ -1478,13 +1480,13 @@ fn bakedIrradiance() -> vec3f {
#endif
fn indirectIrradiance(N : vec3f) -> vec3f {
#ifdef MESH_LIGHTMAP
- if (g_lightmap.z > 0.5) { return bakedIrradiance(); }
+ if (g_lightmap.z > 0.5) { return bakedIrradiance() * lc.u_bakedTint.rgb; }
#endif
let base = clamp(i32(g_probeSlot), 0, 99) * 10;
if (pc.u_probeIrradiance[base].w > 0.5) {
var sh : array<vec4f, 9>;
for (var i = 0; i < 9; i = i + 1) { sh[i] = pc.u_probeIrradiance[base + i]; }
- return max(shIrradiance(sh, N), vec3f(0.0));
+ return max(shIrradiance(sh, N), vec3f(0.0)) * lc.u_bakedTint.rgb;
}
return envIrradiance(N);
}
@@ -2069,6 +2071,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
" highp vec4 u_envTint;\n" // the ambient light's colour, scaling both halves
" highp vec4 u_reflParams;\n" // x = columns in the bound atlas (1 = sky only)
" highp vec4 u_reflBox[30];\n" // [2i] = column i+1's world min, [2i+1] its max
+ " highp vec4 u_bakedTint;\n" // what baked indirect light is multiplied by
"};\n"
// One run of nine per INSTANCE, not one for the draw: a merged draw
// holds objects standing in many places. The flag in w tells "no
@@ -2383,13 +2386,13 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
// it holds every light and bounce that reached this very point.
"highp vec3 indirectIrradiance(in highp vec3 N) {\n"
"#ifdef MESH_LIGHTMAP\n"
- " if (v_lightmap.z > 0.5) return bakedIrradiance();\n"
+ " if (v_lightmap.z > 0.5) return bakedIrradiance() * u_bakedTint.rgb;\n"
"#endif\n"
" highp int base = probeRun();\n"
" if (u_probeIrradiance[base].w > 0.5) {\n"
" highp vec4 sh[9];\n"
" for (int i = 0; i < 9; i++) sh[i] = u_probeIrradiance[base + i];\n"
- " return max(shIrradiance(sh, N), vec3(0.0));\n"
+ " return max(shIrradiance(sh, N), vec3(0.0)) * u_bakedTint.rgb;\n"
" }\n"
" return envIrradiance(N);\n"
"}\n"
@@ -2670,6 +2673,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
" highp vec4 u_envTint;\n"
" highp vec4 u_reflParams;\n"
" highp vec4 u_reflBox[30];\n"
+ " highp vec4 u_bakedTint;\n"
"};\n"
"uniform highp sampler2D u_shadowMap;\n"
"highp float unpackDepth(in highp vec3 c) {\n"
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index 26803f2ef..72cc462dc 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0xd10afae95e4a1476ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0x83e8a5bdeea599a8ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index 2a5fdf295..b4b0e10a6 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xd10afae95e4a1476ULL
+#define ES_ABI_ENGINE_DIGEST 0x83e8a5bdeea599a8ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 6097c5efa..e126bf5ce 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2493,6 +2493,8 @@ export const NOTED = {
{"note":"Skinned meshes are followed by their bones, from the palette they were last drawn with."},
"feat(render): fog follows the scene's sun and can walk the air against its shadow map":
{"note":"Height Fog and Light Shafts follow the scene's own sun, and Height Fog can carry the sun's shadows as volumetric light."},
+ "feat(runtime): a TimeOfDay component moves the sun and the moon across the sky and draws the day, the dusk and the night":
+ {"note":"A TimeOfDay component moves the sun and the moon across the sky, and a Sky Atmosphere effect draws the day, the dusk and the night."},
"feat(runtime): a Weather component puts a scene under a preset, turns between presets and cycles through a sequence":
{"note":"A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself."},
"feat(render): baked reflection probes follow the weather through the ambient light's reflection scale and saturation":