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(2d): a fog of war remembers what a viewer has seen, and a save can keep it

yhh36ab2a94ca70
diff --git a/desktop b/desktop
index 07bbaadfe..02c5be76c 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 07bbaadfe9e8d5197304533c00478ff6bdf0022f
+Subproject commit 02c5be76c4b29bcf5cd31d95dab145b94bbb464f
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 1153cbf70..3a5dc9989 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -25,6 +25,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `blur` | Gaussian blur | `intensity` |
| `fxaa` | Fast anti-aliasing | `intensity` |
| `mist2d` | Drifting banks of mist laid over the ground in world units. Reads no depth, so a 2D scene can have it; what is lit glows through it | `density`, `coverage`, `scale`, `speed`, `direction`, `glow`, colour |
+| `fog2d` | Fog of war for a scene with no depth: ground never seen is dark, ground seen and left is remembered, dimmed and drained of colour, ground in view is as drawn; needs a `FogOfWar` | remembered brightness and desaturation, unexplored colour |
| `rain2d` | Rain for a scene with no depth: streaks, rings and splashes and puddles on the ground in world units, dry under a `RainShelter` sprite | `intensity`, `wetness`, `puddles`, `puddleScale`, `rippleScale`, `wind`, `speed`, `streakLength`, colour |
| `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 |
diff --git a/docs/astro/src/content/docs/graphics/sprites.mdx b/docs/astro/src/content/docs/graphics/sprites.mdx
index 8fb76880c..9b85d61a9 100644
--- a/docs/astro/src/content/docs/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/graphics/sprites.mdx
@@ -283,7 +283,24 @@ player (an eye) and `SightTarget` on a sprite that should not be seen unless som
A wall that contains the viewer or the target blocks nothing for that pair (standing in a bush you see out of it). A scene with no viewer hides every target. Do not
put a `SightTarget` and a `CoverFade` on one sprite, since each owns the sprite's alpha. `segmentBlocked(from, to, rings)`, `seesPoint` and `currentSightRings()` give
-gameplay the same answer the sprites got. This is what is in view; it does not remember what was seen, so ground the player has left is dark again.
+gameplay the same answer the sprites got. This is what is in view. What was seen and left is the fog of war, below.
+
+### Fog of war
+
+Put `FogOfWar` on an entity with a `Transform` and a `fog2d` effect in the scene's post-process volume. Ground no `SightViewer` has ever seen is dark; ground it has seen and left is
+remembered, dimmed and drained of colour; ground in view is as drawn. Each frame every viewer's field of view is found by casting rays against the same walls (the `ShadowCaster2D`s)
+and painted into two maps over the rectangle the component names: where anyone sees now, and where anyone ever has.
+
+| Field | What it does |
+|---|---|
+| `width`, `height` | The world rectangle the fog covers, centred on the entity. The world has to fit in it. |
+| `texels` | How many texels a side the maps are: finer edges, and more to paint. |
+| `viewRadius` | How far a viewer with no `radius` of its own sees. |
+| `rays` | How many rays each viewer casts: the fineness of its field of view's edge. |
+
+The effect's **Remembered Brightness** and **Remembered Desaturation** say how the remembered ground looks, and **Unexplored Colour** what the unseen is. A save keeps what the player has found:
+`exploredToString()` gives a string and `exploredFromString(text)` puts it back (false for one that does not fit the fog's `texels`), and the fog repaints from it. The same grid is
+what repaints the map after a lost graphics device. A scene with no `FogOfWar` has its `fog2d` effect turned off, not black.
### Depth layers (2.5D)
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 253cc9543..e6808eb91 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
@@ -27,6 +27,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `blur` | 高斯模糊 | `intensity` |
| `fxaa` | 快速抗锯齿 | `intensity` |
| `mist2d` | 按世界坐标铺在地面上的、会飘动的成团薄雾。不读深度,2D 场景也能用;被照亮的东西会在雾里发光 | `density`、`coverage`、`scale`、`speed`、`direction`、`glow`、颜色 |
+| `fog2d` | 给没有深度的场景用的战争迷雾:没见过的地面是黑的,见过又离开的地面被记住并变暗褪色,眼前的地面保持原样;需要 `FogOfWar` | 被记住的亮度与褪色、未探索区域的颜色 |
| `rain2d` | 给没有深度的场景用的雨:雨线、按世界坐标落在地面上的涟漪、溅花和积水,`RainShelter` 精灵下面是干的 | `intensity`、`wetness`、`puddles`、`puddleScale`、`rippleScale`、`wind`、`speed`、`streakLength`、颜色 |
| `distanceFog` | 按到相机的距离做线性雾 | `near`、`far`、`intensity`、颜色 |
| `heightFog` | 指数高度雾,带太阳辉光和朦胧的地平线 | `density`、`heightFalloff`、`baseHeight`、`sunAzimuth`、`sunElevation`、`skyFog`、颜色 |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
index c3081cd23..0d47453bd 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
@@ -241,7 +241,20 @@ world.applyEntityOrder([other, another, card]);
| `hiddenOpacity` | `SightTarget` | 没有任何眼睛看见它时,精灵的透明度占自己的几成。0 是完全隐去。 |
| `fadeTime` | `SightTarget` | 渐变用多少秒,来去相同。 |
-墙若包含了观察者或目标,对这一对就不挡视线(站在灌木里能看到外面)。场景里没有任何观察者时,所有目标都是隐藏的。不要把 `SightTarget` 和 `CoverFade` 放在同一个精灵上,两者都要管它的透明度。`segmentBlocked(from, to, rings)`、`seesPoint` 和 `currentSightRings()` 让玩法代码得到和精灵一样的答案。这里只管"此刻看得见什么",不记忆看过的地方,玩家走开后那片地面又是暗的。
+墙若包含了观察者或目标,对这一对就不挡视线(站在灌木里能看到外面)。场景里没有任何观察者时,所有目标都是隐藏的。不要把 `SightTarget` 和 `CoverFade` 放在同一个精灵上,两者都要管它的透明度。`segmentBlocked(from, to, rings)`、`seesPoint` 和 `currentSightRings()` 让玩法代码得到和精灵一样的答案。这里只管"此刻看得见什么",看过又离开的地方由下面的战争迷雾记住。
+
+### 战争迷雾
+
+给带 `Transform` 的实体加 `FogOfWar`,并在场景的后处理体积里加 `fog2d` 效果。没有任何 `SightViewer` 看过的地面是黑的;看过又离开的地面被记住,变暗并褪去颜色;眼前的地面保持原样。每一帧,每个观察者的视野用射线对着同样的墙(`ShadowCaster2D`)求出,画进组件所指定的矩形范围上的两张图:现在谁看得见,以及谁曾经看见过。
+
+| 字段 | 作用 |
+|---|---|
+| `width`、`height` | 迷雾覆盖的世界矩形,以该实体为中心。整个世界必须放得进去。 |
+| `texels` | 两张图每边的纹素数:越大边缘越细,绘制开销也越大。 |
+| `viewRadius` | 自己没有 `radius` 的观察者能看多远。 |
+| `rays` | 每个观察者投射多少条射线:决定视野边缘的细腻程度。 |
+
+效果上的 **Remembered Brightness** 与 **Remembered Desaturation** 决定被记住的地面长什么样,**Unexplored Colour** 是没见过的地方的颜色。存档能保存玩家已经发现的地方:`exploredToString()` 返回一个字符串,`exploredFromString(text)` 把它放回去(与迷雾的 `texels` 不符时返回 false),迷雾随后据此重绘。显卡设备丢失后,也是靠这张网格重绘。场景里没有 `FogOfWar` 时,`fog2d` 效果会被关掉,而不是整屏变黑。
### 深度层(2.5D)
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 466c69a55..3820423a8 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2683,
+ "experimental": 2689,
"deprecated": 3
},
- "total": 2969,
+ "total": 2975,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index bb98dff81..d92db06e7 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -82,6 +82,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
BakedLighting: { category: 'graphics', summary: 'How this scene is baked — atlas size, density, bounces — and a record of what the last bake read.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
DecalProjector: { category: 'graphics', summary: 'Prints this entity\'s material onto what its box covers — the surface is cut to the box and drawn again, so a decal is lit and shadowed as the surface under it.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
BlobShadow: { category: 'graphics', summary: 'A soft dark disc on the ground under an entity — no shadow map, no light, no extra pass — that fades and shrinks as the entity leaves the ground.', doc: 'graphics/lighting', anchor: 'blob-shadows-a-disc-instead-of-a-shadow-map', anchorZh: '假阴影用一个圆片代替阴影图' },
+ FogOfWar: { category: 'graphics', summary: 'Names the world rectangle a 2D fog of war covers: ground no SightViewer has seen is dark, ground seen and left is remembered, ground in view is clear.', doc: 'graphics/sprites', anchor: 'fog-of-war', anchorZh: '战争迷雾' },
SightViewer: { category: 'graphics', summary: 'An eye: sprites with a SightTarget are seen while some viewer has a clear line to them past the ShadowCaster2D walls.', doc: 'graphics/sprites', anchor: 'what-the-player-can-see', anchorZh: '玩家能看见什么' },
SightTarget: { category: 'graphics', summary: 'Hides the sprite while no SightViewer has a clear line to it, for what is not lit and so is not hidden by the walls' shadows.', doc: 'graphics/sprites', anchor: 'what-the-player-can-see', anchorZh: '玩家能看见什么' },
CoverFade: { category: 'graphics', summary: 'A roof or a tree crown that thins out while a CoverFadeTarget stands under it, so the player is never hidden by what they walked into.', doc: 'graphics/sprites', anchor: 'fading-a-roof-or-a-crown-over-the-player', anchorZh: '屋顶与树冠遮挡淡出' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 231fe0372..ecf71c0a6 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1771,6 +1771,59 @@
"tabIndex"
]
},
+ {
+ "name": "FogOfWar",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "width",
+ "type": "number",
+ "default": "4096",
+ "doc": "The world rectangle the fog covers, centred on this entity.",
+ "range": "≥ 1, step 16"
+ },
+ {
+ "key": "height",
+ "type": "number",
+ "default": "4096",
+ "doc": "The world rectangle the fog covers, centred on this entity.",
+ "range": "≥ 1, step 16"
+ },
+ {
+ "key": "texels",
+ "type": "number",
+ "default": "512",
+ "doc": "How many texels a side the maps are: finer edges, and more to paint.",
+ "range": "32–2048, step 32"
+ },
+ {
+ "key": "viewRadius",
+ "type": "number",
+ "default": "400",
+ "doc": "How far a viewer with no radius of its own sees.",
+ "range": "≥ 1, step 1"
+ },
+ {
+ "key": "rays",
+ "type": "number",
+ "default": "256",
+ "doc": "How many rays are cast from each viewer: the fineness of the field of view's edge.",
+ "range": "16–1024, step 8"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "width",
+ "height",
+ "texels",
+ "viewRadius",
+ "rays"
+ ]
+ },
{
"name": "Foliage",
"source": "ts",
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index e46cda724..3a8abec96 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -86,7 +86,7 @@ export const POST_PROCESS_EFFECT_GROUP: Readonly<Record<string, Subsystem>> = {
chromaticAberration: 'fxBasic', tonemap: 'fxBasic', fxaa: 'fxBasic', lensDistortion: 'fxBasic', pixelate: 'fxBasic',
outline: 'fxBasic', depthOutline: 'fxBasic', edgeOutline: 'fxBasic', lutGrade: 'fxBasic', agx: 'fxBasic', sharpen: 'fxBasic', filmGrain: 'fxBasic',
motionBlur: 'fxBasic', lensFlare: 'fxBasic',
- mist2d: 'fxAtmosphere', rain2d: 'fxAtmosphere', distanceFog: 'fxAtmosphere', skyAtmosphere: 'fxAtmosphere', heightFog: 'fxAtmosphere', rain: 'fxAtmosphere',
+ mist2d: 'fxAtmosphere', rain2d: 'fxAtmosphere', fog2d: 'fxAtmosphere', distanceFog: 'fxAtmosphere', skyAtmosphere: 'fxAtmosphere', heightFog: 'fxAtmosphere', rain: 'fxAtmosphere',
voxelGI: 'fxLighting', ssgi: 'fxLighting', contactShadows: 'fxLighting', lightShafts: 'fxLighting',
autoExposure: 'fxLighting', depthOfField: 'fxLighting', ssao: 'fxLighting', subsurface: 'fxLighting',
gtao: 'fxLighting', ssr: 'fxLighting', taa: 'fxLighting',
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ddeaf0d06..218050815 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1939 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1945 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4046,6 +4046,18 @@ static new <T>(bus: EventBus<T>): EventWriterInstance<T>
static prototype: EventWriterInstance<any>
```
+## ExploredGrid — class @experimental
+```
+cells: Uint8Array<ArrayBufferLike>
+fromString: (text: string) => boolean
+mark: (x: number, y: number, left: number, bottom: number, width: number, height: number) => boolean
+markFan: (origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number) => boolean
+size: number
+toString: () => string
+static new (size: number): ExploredGrid
+static prototype: ExploredGrid
+```
+
## ExternalEntityRef — interface @experimental
```
componentType: string
@@ -4293,6 +4305,21 @@ isFocused: boolean
tabIndex: number
```
+## FogOfWar — const @experimental
+```
+ComponentDef<FogOfWarData>
+```
+
+## FogOfWarData — interface @experimental
+```
+enabled: boolean
+height: number
+rays: number
+texels: number
+viewRadius: number
+width: number
+```
+
## Foliage — const @experimental
```
ComponentDef<FoliageData>
@@ -14223,6 +14250,16 @@ EventBindingPlugin
(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver, deferred?: DeferredRecord[]): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[]; }
```
+## exploredFromString — function @experimental
+```
+(text: string): boolean
+```
+
+## exploredToString — function @experimental
+```
+(): string
+```
+
## extendPlatform — function @experimental
```
(extra: Partial<PlatformAdapter>): void
@@ -14248,6 +14285,11 @@ EventBindingPlugin
(dx: number, dy: number, dz: number): { face: number; u: number; v: number; }
```
+## fanDistances — function @experimental
+```
+(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4854fffd8..1aa1de7e5 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1958 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1964 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4054,6 +4054,18 @@ static new <T>(bus: EventBus<T>): EventWriterInstance<T>
static prototype: EventWriterInstance<any>
```
+## ExploredGrid — class @experimental
+```
+cells: Uint8Array<ArrayBufferLike>
+fromString: (text: string) => boolean
+mark: (x: number, y: number, left: number, bottom: number, width: number, height: number) => boolean
+markFan: (origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number) => boolean
+size: number
+toString: () => string
+static new (size: number): ExploredGrid
+static prototype: ExploredGrid
+```
+
## ExternalEntityRef — interface @experimental
```
componentType: string
@@ -4301,6 +4313,21 @@ isFocused: boolean
tabIndex: number
```
+## FogOfWar — const @experimental
+```
+ComponentDef<FogOfWarData>
+```
+
+## FogOfWarData — interface @experimental
+```
+enabled: boolean
+height: number
+rays: number
+texels: number
+viewRadius: number
+width: number
+```
+
## Foliage — const @experimental
```
ComponentDef<FoliageData>
@@ -14476,6 +14503,16 @@ EventBindingPlugin
(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver, deferred?: DeferredRecord[]): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[]; }
```
+## exploredFromString — function @experimental
+```
+(text: string): boolean
+```
+
+## exploredToString — function @experimental
+```
+(): string
+```
+
## extendPlatform — function @experimental
```
(extra: Partial<PlatformAdapter>): void
@@ -14501,6 +14538,11 @@ EventBindingPlugin
(dx: number, dy: number, dz: number): { face: number; u: number; v: number; }
```
+## fanDistances — function @experimental
+```
+(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a214b0fb0..85450e762 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: 115 public · 161 beta · 1938 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1944 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4041,6 +4041,18 @@ static new <T>(bus: EventBus<T>): EventWriterInstance<T>
static prototype: EventWriterInstance<any>
```
+## ExploredGrid — class @experimental
+```
+cells: Uint8Array<ArrayBufferLike>
+fromString: (text: string) => boolean
+mark: (x: number, y: number, left: number, bottom: number, width: number, height: number) => boolean
+markFan: (origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number) => boolean
+size: number
+toString: () => string
+static new (size: number): ExploredGrid
+static prototype: ExploredGrid
+```
+
## ExternalEntityRef — interface @experimental
```
componentType: string
@@ -4288,6 +4300,21 @@ isFocused: boolean
tabIndex: number
```
+## FogOfWar — const @experimental
+```
+ComponentDef<FogOfWarData>
+```
+
+## FogOfWarData — interface @experimental
+```
+enabled: boolean
+height: number
+rays: number
+texels: number
+viewRadius: number
+width: number
+```
+
## Foliage — const @experimental
```
ComponentDef<FoliageData>
@@ -14218,6 +14245,16 @@ EventBindingPlugin
(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver, deferred?: DeferredRecord[]): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[]; }
```
+## exploredFromString — function @experimental
+```
+(text: string): boolean
+```
+
+## exploredToString — function @experimental
+```
+(): string
+```
+
## extendPlatform — function @experimental
```
(extra: Partial<PlatformAdapter>): void
@@ -14243,6 +14280,11 @@ EventBindingPlugin
(dx: number, dy: number, dz: number): { face: number; u: number; v: number; }
```
+## fanDistances — function @experimental
+```
+(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 951649fac..20a0f1826 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: 115 public · 159 beta · 1960 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1966 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4041,6 +4041,18 @@ static new <T>(bus: EventBus<T>): EventWriterInstance<T>
static prototype: EventWriterInstance<any>
```
+## ExploredGrid — class @experimental
+```
+cells: Uint8Array<ArrayBufferLike>
+fromString: (text: string) => boolean
+mark: (x: number, y: number, left: number, bottom: number, width: number, height: number) => boolean
+markFan: (origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number) => boolean
+size: number
+toString: () => string
+static new (size: number): ExploredGrid
+static prototype: ExploredGrid
+```
+
## ExternalEntityRef — interface @experimental
```
componentType: string
@@ -4288,6 +4300,21 @@ isFocused: boolean
tabIndex: number
```
+## FogOfWar — const @experimental
+```
+ComponentDef<FogOfWarData>
+```
+
+## FogOfWarData — interface @experimental
+```
+enabled: boolean
+height: number
+rays: number
+texels: number
+viewRadius: number
+width: number
+```
+
## Foliage — const @experimental
```
ComponentDef<FoliageData>
@@ -14523,6 +14550,16 @@ EventBindingPlugin
(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver, deferred?: DeferredRecord[]): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[]; }
```
+## exploredFromString — function @experimental
+```
+(text: string): boolean
+```
+
+## exploredToString — function @experimental
+```
+(): string
+```
+
## extendPlatform — function @experimental
```
(extra: Partial<PlatformAdapter>): void
@@ -14548,6 +14585,11 @@ EventBindingPlugin
(dx: number, dy: number, dz: number): { face: number; u: number; v: number; }
```
+## fanDistances — function @experimental
+```
+(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c534aa4ab..f38a997d5 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: 115 public · 159 beta · 1951 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1957 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4041,6 +4041,18 @@ static new <T>(bus: EventBus<T>): EventWriterInstance<T>
static prototype: EventWriterInstance<any>
```
+## ExploredGrid — class @experimental
+```
+cells: Uint8Array<ArrayBufferLike>
+fromString: (text: string) => boolean
+mark: (x: number, y: number, left: number, bottom: number, width: number, height: number) => boolean
+markFan: (origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number) => boolean
+size: number
+toString: () => string
+static new (size: number): ExploredGrid
+static prototype: ExploredGrid
+```
+
## ExternalEntityRef — interface @experimental
```
componentType: string
@@ -4288,6 +4300,21 @@ isFocused: boolean
tabIndex: number
```
+## FogOfWar — const @experimental
+```
+ComponentDef<FogOfWarData>
+```
+
+## FogOfWarData — interface @experimental
+```
+enabled: boolean
+height: number
+rays: number
+texels: number
+viewRadius: number
+width: number
+```
+
## Foliage — const @experimental
```
ComponentDef<FoliageData>
@@ -14250,6 +14277,16 @@ EventBindingPlugin
(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver, deferred?: DeferredRecord[]): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[]; }
```
+## exploredFromString — function @experimental
+```
+(text: string): boolean
+```
+
+## exploredToString — function @experimental
+```
+(): string
+```
+
## extendPlatform — function @experimental
```
(extra: Partial<PlatformAdapter>): void
@@ -14275,6 +14312,11 @@ EventBindingPlugin
(dx: number, dy: number, dz: number): { face: number; u: number; v: number; }
```
+## fanDistances — function @experimental
+```
+(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index ce337dece..8c09b0880 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -25,6 +25,7 @@ import { playModeOnly } from '../ecs/env';
import { installCoverFade } from '../render/coverFade';
import { installRainShelter } from '../render/rainShelter';
import { installSight } from '../render/sight';
+import { installFogOfWar } from '../render/fogOfWar';
import { SystemLabel } from '../ecs/systemLabels';
export class AnimationPlugin implements Plugin {
@@ -59,7 +60,9 @@ export class AnimationPlugin implements Plugin {
const offCoverFade = installCoverFade(app);
const offRainShelter = installRainShelter(app);
const offSight = installSight(app);
- const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); offSight(); };
+ // After the sight system, whose walls it casts rays against.
+ const offFog = installFogOfWar(app);
+ const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); offSight(); offFog(); };
this.despawnCleanups_.set(app, release);
this.latestDespawnCleanup_ = release;
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 3985335d3..8966d3de4 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -347,6 +347,7 @@ export { buildPathGeometry, mergeGeometry, cubicBezier, quadraticBezier, circleP
export type { PathStyle, PathFill, PathStroke, PathColor, LineJoin, LineCap } from './render/vectorPath';
export { setPath, clearPath } from './render/pathRenderer';
export { RainShelter, RainUpright, uprightOf, uprightRects, drynessOf, maskRects, shelterMaskSizeOf, ellipseStripsOf, type RainShelterData, type RainUprightData, type Upright, type Shelter, type MaskRect } from './render/rainShelter';
+export { FogOfWar, ExploredGrid, fanDistances, exploredToString, exploredFromString, type FogOfWarData } from './render/fogOfWar';
export { SightViewer, SightTarget, segmentBlocked, seesPoint, sightRingOf, ringContains, currentSightRings, type SightViewerData, type SightTargetData, type SightRing, type SightPoint } from './render/sight';
export { CoverFade, CoverFadeTarget, coveredGround, coversPoint, stepFade, type CoverFadeData } from './render/coverFade';
export { BlobShadow, setBlobShadowGround, buildBlobMesh, blobAlpha, type BlobShadowData, type BlobShadowGround } from './render/blobShadow';
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 1921d7ecc..408080bca 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { ShaderHandle } from '../render/material';
+import { FOG_UNIFORMS, FOG_EXPLORED_TEXTURE, FOG_VISIBLE_TEXTURE } from './fogOfWarMask';
import { RAIN_SHELTER_UNIFORMS, RAIN_SHELTER_MASK_TEXTURE, RAIN_SHELTER_MASK_SIZE, RAIN_SHELTER_MASK_MIN, RAIN_SHELTER_MASK_MAX } from './rainShelterMask';
import { effectSourcesOf, computeSourceOf } from './effectSources';
import type { basicEffects } from './sources/basic';
@@ -349,6 +350,26 @@ registerEffect({
],
});
+registerEffect({
+ type: 'fog2d',
+ label: 'Fog of War 2D',
+ factory: () => postProcessEffects.createFog2d(),
+ uniforms: [
+ // How bright ground that has been seen and left is, and how much of its colour goes.
+ { name: 'u_forgetLight', label: 'Remembered Brightness', min: 0, max: 1, step: 0.01, defaultValue: 0.4 },
+ { name: 'u_forgetDesat', label: 'Remembered Desaturation', min: 0, max: 1, step: 0.01, defaultValue: 0.7 },
+ // Where the maps sit in the world, written each frame by the fog-of-war system with the maps themselves.
+ ...FOG_UNIFORMS,
+ ],
+ textures: [
+ { name: FOG_EXPLORED_TEXTURE, label: 'Explored Map', internal: true },
+ { name: FOG_VISIBLE_TEXTURE, label: 'Visible Map', internal: true },
+ ],
+ colors: [
+ { name: 'u_unexploredColor', label: 'Unexplored Colour', defaultValue: { r: 0, g: 0, b: 0, a: 1 } },
+ ],
+});
+
registerEffect({
type: 'distanceFog',
label: 'Distance Fog',
@@ -893,7 +914,7 @@ const CATEGORIES: Record<EffectCategory, string[]> = {
lens: ['bloom', 'depthOfField', 'motionBlur', 'lensFlare', 'filmGrain', 'chromaticAberration', 'lensDistortion', 'vignette', 'sharpen'],
color: ['tonemap', 'agx', 'colorGrade', 'lutGrade', 'displayLut', 'autoExposure', 'grayscale'],
light: ['ssao', 'gtao', 'ssgi', 'ssr', 'voxelGI', 'contactShadows', 'lightShafts', 'subsurface'],
- atmosphere: ['mist2d', 'rain2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],
+ atmosphere: ['mist2d', 'rain2d', 'fog2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],
aa: ['fxaa', 'taa'],
stylize: ['blur', 'pixelate', 'outline', 'depthOutline', 'edgeOutline'],
};
diff --git a/sdk/src/postprocess/fogOfWarMask.ts b/sdk/src/postprocess/fogOfWarMask.ts
new file mode 100644
index 000000000..e4dc508d8
--- /dev/null
+++ b/sdk/src/postprocess/fogOfWarMask.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fogOfWarMask.ts
+ * @brief The names the 2D fog of war reads its two maps by, kept apart from its shader so every package can carry the names and only the ones that fog carry the source.
+ */
+import type { EffectUniformDef } from './effects';
+
+/** The samplers the maps are bound to: where a viewer has ever seen, and where one sees now. */
+export const FOG_EXPLORED_TEXTURE = 'u_fogExplored';
+export const FOG_VISIBLE_TEXTURE = 'u_fogVisible';
+
+/** The world rectangle the maps cover: its low corner and its size. Written with the maps each frame, so nobody authors them. */
+export const FOG_UNIFORMS: EffectUniformDef[] = ['L', 'B', 'W', 'H'].map((edge): EffectUniformDef => ({
+ name: `u_fog${edge}`, label: `Fog Map ${edge}`, min: -1e9, max: 1e9, step: 1, defaultValue: 0, internal: true,
+}));
diff --git a/sdk/src/postprocess/sources/atmosphere.ts b/sdk/src/postprocess/sources/atmosphere.ts
index 4065c4714..d93ddcb50 100644
--- a/sdk/src/postprocess/sources/atmosphere.ts
+++ b/sdk/src/postprocess/sources/atmosphere.ts
@@ -8,10 +8,12 @@ import type { ShaderHandle } from '../../render/material';
import { Material } from '../../render/material';
import { registerEffectSources } from '../effectSources';
import { rain2dEffects } from './rain2d';
+import { fog2dEffects } from './fog2d';
import { SSAO_GLSL, SSAO_WGSL, PUDDLE_GLSL, PUDDLE_WGSL, BASIN_GLSL, BASIN_WGSL, GBUFFER_GLSL, GBUFFER_WGSL } from './shared';
export const atmosphereEffects = {
...rain2dEffects,
+ ...fog2dEffects,
/**
* A sky that has a time of day and weather in it: the scattering of the atmosphere, a sun that goes red as it sets, a
* moon, stars, and volumetric clouds that the sun lights.
diff --git a/sdk/src/postprocess/sources/fog2d.ts b/sdk/src/postprocess/sources/fog2d.ts
new file mode 100644
index 000000000..67c1f4d77
--- /dev/null
+++ b/sdk/src/postprocess/sources/fog2d.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fog2d.ts
+ * @brief The fog of war of a 2D scene: ground never seen is dark, ground seen and left is dimmed and drained of colour, ground in view is as drawn.
+ *
+ * @details Two small textures the fog-of-war system paints cover the world rectangle a `FogOfWar` names: where a viewer has EVER seen (kept, drawn
+ * into again each frame and never cleared) and where one sees NOW (cleared and drawn each frame). The red channel of each is the answer.
+ * The picture is found on the ground plane in WORLD units, as the 2D mist and rain find it, so no depth is read.
+ */
+import type { ShaderHandle } from '../../render/material';
+import { Material } from '../../render/material';
+
+const GLSL = `
+/// What is known of a world point: x is how much of it has ever been seen, y how much is seen now. Outside the rectangle nothing is known.
+vec2 fogAt(vec2 w) {
+ if (u_fogW <= 0.0 || u_fogH <= 0.0) return vec2(0.0);
+ vec2 uv = (w - vec2(u_fogL, u_fogB)) / vec2(u_fogW, u_fogH);
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return vec2(0.0);
+ return vec2(textureLod(u_fogExplored, uv, 0.0).r, textureLod(u_fogVisible, uv, 0.0).r);
+}`;
+
+const WGSL = `
+fn fogAt(w : vec2f) -> vec2f {
+ if (mc.u_fogW <= 0.0 || mc.u_fogH <= 0.0) { return vec2f(0.0); }
+ let uv = (w - vec2f(mc.u_fogL, mc.u_fogB)) / vec2f(mc.u_fogW, mc.u_fogH);
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return vec2f(0.0); }
+ // This device's texture rows run the other way from the clip space the maps were drawn in.
+ let p = vec2f(uv.x, 1.0 - uv.y);
+ return vec2f(textureSampleLevel(u_fogExplored, u_fogExplored_s, p, 0.0).r, textureSampleLevel(u_fogVisible, u_fogVisible_s, p, 0.0).r);
+}`;
+
+const SOURCE = `#pragma shader "PP Fog 2D"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_forgetLight float default(0.4) range(0,1)
+#pragma param u_forgetDesat float default(0.7) range(0,1)
+#pragma param u_unexploredColor color default(0,0,0,1)
+#pragma param u_fogL float default(0) range(-1000000000,1000000000)
+#pragma param u_fogB float default(0) range(-1000000000,1000000000)
+#pragma param u_fogW float default(0) range(0,1000000000)
+#pragma param u_fogH float default(0) range(0,1000000000)
+#pragma param u_fogExplored texture default(black)
+#pragma param u_fogVisible texture default(black)
+
+#pragma fragment
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+out vec4 fragColor;
+${GLSL}
+
+void main() {
+ vec4 src = texture(u_texture, v_texCoord);
+ vec2 w = worldFromDepth(v_texCoord, 0.0).xy + u_renderOrigin.xy;
+ vec3 dark = u_unexploredColor.rgb;
+#ifdef ES_LINEAR
+ dark = srgbToLinear(dark);
+#endif
+ vec2 known = fogAt(w);
+ float seen = max(known.x, known.y);
+ // Ground left behind is dimmed and drained of colour: remembered, not watched.
+ float grey = dot(src.rgb, vec3(0.299, 0.587, 0.114));
+ vec3 remembered = mix(src.rgb, vec3(grey), u_forgetDesat) * u_forgetLight;
+ vec3 shown = mix(remembered, src.rgb, smoothstep(0.0, 1.0, known.y));
+ fragColor = vec4(mix(dark, shown, smoothstep(0.0, 1.0, seen)), src.a);
+}
+#pragma end
+
+#pragma fragment wgsl
+${WGSL}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let w = worldFromDepth(v.v_texCoord, 0.0).xy + frame.renderOrigin.xy;
+ var dark = mc.u_unexploredColor.rgb;
+#ifdef ES_LINEAR
+ dark = srgbToLinear(dark);
+#endif
+ let known = fogAt(w);
+ let seen = max(known.x, known.y);
+ let grey = dot(src.rgb, vec3f(0.299, 0.587, 0.114));
+ let remembered = mix(src.rgb, vec3f(grey), mc.u_forgetDesat) * mc.u_forgetLight;
+ let shown = mix(remembered, src.rgb, smoothstep(0.0, 1.0, known.y));
+ return vec4f(mix(dark, shown, smoothstep(0.0, 1.0, seen)), src.a);
+}
+#pragma end
+`;
+
+export const fog2dEffects = {
+ createFog2d(): ShaderHandle {
+ return Material.compileShader(SOURCE);
+ },
+};
diff --git a/sdk/src/postprocess/volumeSystem.ts b/sdk/src/postprocess/volumeSystem.ts
index 09d3168bb..ddec3862c 100644
--- a/sdk/src/postprocess/volumeSystem.ts
+++ b/sdk/src/postprocess/volumeSystem.ts
@@ -16,6 +16,7 @@ import { Material } from '../render/material';
import { applyWeatherToEffects, currentWeather, currentWeatherDrive } from './weather';
import { applyCloudsToFog } from './cloudShafts';
import { applyRainSheltersToRain } from '../render/rainShelter';
+import { applyFogOfWarToFog } from '../render/fogOfWar';
import { runtimeTextureHandle } from './runtimeTextures';
import { applyUnderwaterToEffects, currentUnderwater } from './underwater';
import { applyTimeToEffects, currentTimeOfDay, currentTimeDrive, timeLightsApplied } from './timeOfDay';
@@ -307,6 +308,7 @@ export function effectsAt(volumes: { data: PostProcessVolumeData; tx: VolumeTran
applyCloudsToFog(blended);
// A 2D rain is told where the ground under a roof is dry, by a mask drawn this frame.
applyRainSheltersToRain(blended);
+ applyFogOfWarToFog(blended);
// A camera under water: the effect the water module says it needs.
applyUnderwaterToEffects(blended, currentUnderwater());
return blended;
diff --git a/sdk/src/render/fogOfWar.ts b/sdk/src/render/fogOfWar.ts
new file mode 100644
index 000000000..b70d90d3d
--- /dev/null
+++ b/sdk/src/render/fogOfWar.ts
@@ -0,0 +1,360 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fogOfWar.ts
+ * @brief The fog of war of a 2D scene: ground a `SightViewer` has never seen is dark, ground it has seen and left is remembered, ground in view is clear.
+ *
+ * @details `FogOfWar` goes on an entity with a `Transform` and names the world rectangle the fog covers (centred on the entity) and how many texels a
+ * side the maps are. Each frame every viewer's field of view is found by casting rays against the same walls `SightViewer` is stopped by,
+ * and painted twice: into a map of where anyone sees NOW (cleared each frame) and into one of where anyone has EVER seen (never cleared).
+ * A `fog2d` effect reads both. The same field is marked into a grid on the CPU, which is what survives a lost graphics device, and what
+ * `exploredToString` / `exploredFromString` save and restore: a save file keeps what the player has found.
+ *
+ * One rectangle, one pair of maps: the world has to fit in `width` by `height`. A larger world wants a fog that is paged by chunk, which this is not.
+ */
+import type { App } from '../app/app';
+import type { Entity } from '../types';
+import { defineComponent, Transform, type TransformData } from '../ecs/component';
+import { defineSystem, Schedule } from '../ecs/system';
+import { Query } from '../ecs/query';
+import { isEditor, isPlayMode } from '../ecs/env';
+import { Draw } from './draw';
+import { BlendMode } from './blend';
+import { Renderer } from './renderer';
+import { RenderTexture, type RenderTextureHandle } from './renderTexture';
+import { SightViewer, currentSightRings, type SightPoint, type SightRing, type SightViewerData } from './sight';
+import { log } from '../util/logger';
+import { FOG_EXPLORED_TEXTURE, FOG_VISIBLE_TEXTURE } from '../postprocess/fogOfWarMask';
+import { runtimeTextureRef } from '../postprocess/runtimeTextures';
+import type { BlendedEffect } from '../postprocess/volumeBlending';
+
+/** The fields of the `FogOfWar` component. @experimental */
+export interface FogOfWarData {
+ /** The world rectangle the fog covers, centred on the entity, in world units. */
+ width: number;
+ height: number;
+ /** How many texels a side the maps are. More is finer edges and more to paint. */
+ texels: number;
+ /** How far a viewer with no `radius` of its own sees, in world units. */
+ viewRadius: number;
+ /** How many rays are cast from each viewer: the fineness of the field of view's edge. */
+ rays: number;
+ /** Off: the fog is not painted and the effect draws nothing. */
+ enabled: boolean;
+}
+
+/**
+ * Names the world rectangle a 2D fog of war covers. Put a `fog2d` effect in the scene's post-process volume to draw it.
+ *
+ * @experimental
+ */
+export const FogOfWar = defineComponent<FogOfWarData>('FogOfWar',
+ { width: 4096, height: 4096, texels: 512, viewRadius: 400, rays: 256, enabled: true },
+ {
+ fields: {
+ width: { min: 1, step: 16, unit: 'wu', tooltip: 'The world rectangle the fog covers, centred on this entity.' },
+ height: { min: 1, step: 16, unit: 'wu', tooltip: 'The world rectangle the fog covers, centred on this entity.' },
+ texels: { min: 32, max: 2048, step: 32, tooltip: 'How many texels a side the maps are: finer edges, and more to paint.' },
+ viewRadius: { min: 1, step: 1, unit: 'wu', tooltip: 'How far a viewer with no radius of its own sees.' },
+ rays: { min: 16, max: 1024, step: 8, tooltip: "How many rays are cast from each viewer: the fineness of the field of view's edge." },
+ },
+ },
+);
+
+/**
+ * How far one ray from `origin` goes before a wall stops it, for `rays` rays evenly round the circle, none longer than `radius`. A wall that contains
+ * `origin` stops nothing, as for `SightViewer`: standing in a bush you see out of it.
+ */
+export function fanDistances(origin: SightPoint, radius: number, rings: readonly SightRing[], rays: number): Float32Array {
+ const out = new Float32Array(rays).fill(radius);
+ // Only the walls the circle can touch, and only their edges.
+ const edges: number[] = [];
+ for (const ring of rings) {
+ if (ring.length < 3) continue;
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
+ for (const p of ring) {
+ if (p.x < x0) x0 = p.x;
+ if (p.x > x1) x1 = p.x;
+ if (p.y < y0) y0 = p.y;
+ if (p.y > y1) y1 = p.y;
+ }
+ if (x1 < origin.x - radius || x0 > origin.x + radius || y1 < origin.y - radius || y0 > origin.y + radius) continue;
+ if (containsPoint(ring, origin)) continue;
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) edges.push(ring[j]!.x, ring[j]!.y, ring[i]!.x, ring[i]!.y);
+ }
+ if (edges.length === 0) return out;
+ for (let r = 0; r < rays; r++) {
+ const angle = (r / rays) * Math.PI * 2;
+ const dx = Math.cos(angle), dy = Math.sin(angle);
+ let best = radius;
+ for (let e = 0; e < edges.length; e += 4) {
+ // Ray origin + t * (dx, dy) against the edge a + u * (b - a).
+ const ax = edges[e]!, ay = edges[e + 1]!, ex = edges[e + 2]! - ax, ey = edges[e + 3]! - ay;
+ const denom = dx * ey - dy * ex;
+ if (denom === 0) continue;
+ const wx = ax - origin.x, wy = ay - origin.y;
+ const t = (wx * ey - wy * ex) / denom;
+ const u = (wx * dy - wy * dx) / denom;
+ if (t > 0 && t < best && u >= 0 && u <= 1) best = t;
+ }
+ out[r] = best;
+ }
+ return out;
+}
+
+function containsPoint(ring: SightRing, p: SightPoint): boolean {
+ let inside = false;
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
+ const a = ring[i]!, b = ring[j]!;
+ if ((a.y > p.y) !== (b.y > p.y) && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
+ }
+ return inside;
+}
+
+/** What has been seen, on a grid of cells over the fog's rectangle: the part that survives a lost device and goes into a save. */
+export class ExploredGrid {
+ readonly cells: Uint8Array;
+
+ constructor(readonly size: number) {
+ this.cells = new Uint8Array(size * size);
+ }
+
+ /** Marks the cell holding a world point, given the rectangle's low corner and its edge. True when it was new. */
+ mark(x: number, y: number, left: number, bottom: number, width: number, height: number): boolean {
+ const cx = Math.floor(((x - left) / width) * this.size), cy = Math.floor(((y - bottom) / height) * this.size);
+ if (cx < 0 || cy < 0 || cx >= this.size || cy >= this.size) return false;
+ const i = cy * this.size + cx;
+ if (this.cells[i]) return false;
+ this.cells[i] = 1;
+ return true;
+ }
+
+ /** Marks everything the rays of one viewer reach, a block of cells round each step along each ray. */
+ markFan(origin: SightPoint, distances: Float32Array, left: number, bottom: number, width: number, height: number): boolean {
+ const cell = Math.min(width, height) / this.size;
+ const around = Math.max(1, Math.ceil((Math.PI * 2 * Math.max(...distances)) / distances.length / cell / 2));
+ let changed = false;
+ for (let r = 0; r < distances.length; r++) {
+ const angle = (r / distances.length) * Math.PI * 2;
+ const dx = Math.cos(angle) * cell, dy = Math.sin(angle) * cell;
+ const steps = Math.floor(distances[r]! / cell);
+ for (let s = 0; s <= steps; s++) {
+ const x = origin.x + dx * s, y = origin.y + dy * s;
+ for (let oy = -around + 1; oy < around; oy++) for (let ox = -around + 1; ox < around; ox++) {
+ if (this.mark(x + ox * cell, y + oy * cell, left, bottom, width, height)) changed = true;
+ }
+ }
+ }
+ return changed;
+ }
+
+ /** The grid as a string a save file can hold: run lengths of its cells, in base 36. */
+ toString(): string {
+ const runs: string[] = [];
+ let value = 0, length = 0;
+ for (const c of this.cells) {
+ if (c === value) { length++; continue; }
+ runs.push(length.toString(36));
+ value = c;
+ length = 1;
+ }
+ runs.push(length.toString(36));
+ return `${this.size}:${runs.join(',')}`;
+ }
+
+ /** Takes what {@link toString} wrote. False, leaving the grid as it was, for a string of another size or a damaged one. */
+ fromString(text: string): boolean {
+ const [head, body] = text.split(':');
+ if (Number(head) !== this.size || body === undefined) return false;
+ const next = new Uint8Array(this.cells.length);
+ let at = 0, value = 0;
+ for (const run of body.split(',')) {
+ const length = parseInt(run, 36);
+ if (!Number.isFinite(length) || at + length > next.length) return false;
+ if (value) next.fill(1, at, at + length);
+ at += length;
+ value ^= 1;
+ }
+ if (at !== next.length) return false;
+ this.cells.set(next);
+ return true;
+ }
+}
+
+interface FogState {
+ ref: { explored: string; visible: string };
+ left: number;
+ bottom: number;
+ width: number;
+ height: number;
+}
+
+let fogNow: FogState | null = null;
+let gridNow: ExploredGrid | null = null;
+
+/** What has been seen so far, as a string for a save file; empty when there is no fog. */
+export function exploredToString(): string {
+ return gridNow ? gridNow.toString() : '';
+}
+
+/** Restores what a save kept. The fog repaints its map from it on the next frame. False when there is no fog yet or the string does not fit it. */
+export function exploredFromString(text: string): boolean {
+ if (!gridNow || !gridNow.fromString(text)) return false;
+ repaintRequested = true;
+ return true;
+}
+
+let repaintRequested = false;
+
+/** Hands a `fog2d` effect the maps painted this frame and where they lie; with no fog the effect is turned off, so the whole picture is not black. */
+export function applyFogOfWarToFog(effects: Map<string, BlendedEffect>): void {
+ const fog = effects.get('fog2d');
+ if (!fog || !fog.enabled) return;
+ const state = fogNow;
+ if (!state) { fog.enabled = false; return; }
+ fog.uniforms.set('u_fogL', state.left);
+ fog.uniforms.set('u_fogB', state.bottom);
+ fog.uniforms.set('u_fogW', state.width);
+ fog.uniforms.set('u_fogH', state.height);
+ fog.textures.set(FOG_EXPLORED_TEXTURE, state.ref.explored);
+ fog.textures.set(FOG_VISIBLE_TEXTURE, state.ref.visible);
+}
+
+/** Column-major orthographic projection over a rectangle: what RenderTexture.begin wants. */
+function ortho(l: number, r: number, b: number, t: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 2 / (r - l);
+ m[5] = 2 / (t - b);
+ m[10] = -1;
+ m[12] = -(r + l) / (r - l);
+ m[13] = -(t + b) / (t - b);
+ m[15] = 1;
+ return m;
+}
+
+/** Installs the system that finds each viewer's field of view and paints the fog maps. Returns the function that lets everything go. */
+export function installFogOfWar(app: App): () => void {
+ let explored: RenderTextureHandle | null = null;
+ let visible: RenderTextureHandle | null = null;
+ let grid: ExploredGrid | null = null;
+ let failed = false;
+
+ const release = (): void => {
+ if (explored) RenderTexture.release(explored);
+ if (visible) RenderTexture.release(visible);
+ explored = visible = null;
+ grid = gridNow = null;
+ };
+
+ const system = defineSystem(
+ [Query(FogOfWar, Transform), Query(SightViewer, Transform)],
+ (
+ fogs: Iterable<[Entity, FogOfWarData, TransformData]>,
+ viewers: Iterable<[Entity, SightViewerData, TransformData]>,
+ ) => {
+ fogNow = null;
+ if (failed || (isEditor() && !isPlayMode())) return;
+ let fog: FogOfWarData | null = null, centre: TransformData | null = null;
+ for (const [, data, transform] of fogs) {
+ if (data.enabled && data.width > 0 && data.height > 0) { fog = data; centre = transform; break; }
+ }
+ if (!fog || !centre) { if (explored) release(); return; }
+ try {
+ const texels = Math.min(Math.max(Math.round(fog.texels), 32), 2048);
+ if (explored && explored.width !== texels) release();
+ if (!explored || !visible) {
+ const a = RenderTexture.create({ width: texels, height: texels, depth: false, filter: 'linear' });
+ const b = RenderTexture.create({ width: texels, height: texels, depth: false, filter: 'linear' });
+ // The renderer may not be up yet: try again next frame.
+ if (a.textureId === 0 || a.texture === 0 || b.textureId === 0 || b.texture === 0) { RenderTexture.release(a); RenderTexture.release(b); return; }
+ explored = a;
+ visible = b;
+ grid = gridNow = new ExploredGrid(texels);
+ repaintRequested = true;
+ }
+ const left = centre.worldPosition.x - fog.width / 2, bottom = centre.worldPosition.y - fog.height / 2;
+ const right = left + fog.width, top = bottom + fog.height;
+ const vp = ortho(left, right, bottom, top);
+ const cx = (left + right) / 2, cy = (bottom + top) / 2;
+ const texelWorld = Math.min(fog.width, fog.height) / texels;
+ const rings = currentSightRings();
+
+ // Every viewer's field of view this frame.
+ const fans: Array<{ at: SightPoint; distances: Float32Array; thickness: number }> = [];
+ for (const [, viewer, transform] of viewers) {
+ if (!viewer.enabled) continue;
+ const at = { x: transform.worldPosition.x, y: transform.worldPosition.y };
+ const radius = viewer.radius > 0 ? viewer.radius : fog.viewRadius;
+ const rays = Math.min(Math.max(Math.round(fog.rays), 16), 1024);
+ const distances = fanDistances(at, radius, rings, rays);
+ // Wide enough that neighbouring rays meet at the far end of the longest one.
+ fans.push({ at, distances, thickness: Math.max(((Math.PI * 2 * radius) / rays) * 1.4, texelWorld * 1.5) });
+ grid!.markFan(at, distances, left, bottom, fog.width, fog.height);
+ }
+
+ const lines = (list: typeof fans): void => {
+ Draw.setBlendMode(BlendMode.Lighten);
+ for (const fan of list) {
+ for (let r = 0; r < fan.distances.length; r++) {
+ const angle = (r / fan.distances.length) * Math.PI * 2;
+ const d = fan.distances[r]!;
+ Draw.line(fan.at, { x: fan.at.x + Math.cos(angle) * d, y: fan.at.y + Math.sin(angle) * d }, { r: 1, g: 0, b: 0, a: 1 }, fan.thickness);
+ }
+ }
+ };
+ const pass = (target: RenderTextureHandle, body: () => void): void => {
+ RenderTexture.begin(target, vp);
+ Draw.begin(vp);
+ // Draw.begin resets the viewport to the screen's; the target's own is what this pass is.
+ Renderer.setViewport(0, 0, target.width, target.height);
+ body();
+ Draw.end();
+ RenderTexture.end();
+ RenderTexture.contentDrawn(target);
+ };
+ const clear = (): void => {
+ Draw.setBlendMode(BlendMode.None);
+ Draw.rect({ x: cx, y: cy }, { x: fog!.width, y: fog!.height }, { r: 0, g: 0, b: 0, a: 0 });
+ };
+
+ pass(visible, () => { clear(); lines(fans); });
+ if (repaintRequested || RenderTexture.contentLost(explored)) {
+ // Rebuilt from the grid: what a save restored, or what a lost device took. Runs of cells along a row are one rectangle each.
+ repaintRequested = false;
+ pass(explored, () => {
+ clear();
+ Draw.setBlendMode(BlendMode.Lighten);
+ const size = grid!.size, cellW = fog!.width / size, cellH = fog!.height / size;
+ for (let y = 0; y < size; y++) {
+ let x = 0;
+ while (x < size) {
+ if (!grid!.cells[y * size + x]) { x++; continue; }
+ let end = x;
+ while (end < size && grid!.cells[y * size + end]) end++;
+ Draw.rect({ x: left + ((x + end) / 2) * cellW, y: bottom + (y + 0.5) * cellH }, { x: (end - x) * cellW, y: cellH }, { r: 1, g: 0, b: 0, a: 1 });
+ x = end;
+ }
+ }
+ });
+ }
+ if (fans.length > 0) pass(explored, () => lines(fans));
+
+ fogNow = {
+ ref: { explored: runtimeTextureRef(FOG_EXPLORED_TEXTURE, explored.texture), visible: runtimeTextureRef(FOG_VISIBLE_TEXTURE, visible.texture) },
+ left, bottom, width: fog.width, height: fog.height,
+ };
+ } catch (error) {
+ failed = true;
+ log.warn('fog', `the fog of war cannot be painted on this device: ${String(error)}`);
+ }
+ },
+ { name: 'FogOfWarSystem' },
+ );
+ // After the sight system has read the walls (it is installed first), and before the frame is drawn.
+ app.addSystemToSchedule(Schedule.PostUpdate, system);
+
+ return () => {
+ fogNow = null;
+ release();
+ };
+}
diff --git a/sdk/tests/fog-of-war.test.ts b/sdk/tests/fog-of-war.test.ts
new file mode 100644
index 000000000..1da2323d2
--- /dev/null
+++ b/sdk/tests/fog-of-war.test.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The 2D fog of war: the field of view cast against the walls, the grid of what has been seen and how it is saved, and the effect that draws it.
+ */
+import { describe, expect, it } from 'vitest';
+import { ExploredGrid, applyFogOfWarToFog, exploredFromString, exploredToString, fanDistances } from '../src/render/fogOfWar';
+import { getEffectDef } from '../src/postprocess/effects';
+import { FOG_EXPLORED_TEXTURE, FOG_VISIBLE_TEXTURE } from '../src/postprocess/fogOfWarMask';
+import type { BlendedEffect } from '../src/postprocess/volumeBlending';
+
+/** A wall 20 wide and 200 tall at x = 100, as a ring. */
+const wall = [{ x: 90, y: -100 }, { x: 110, y: -100 }, { x: 110, y: 100 }, { x: 90, y: 100 }];
+
+describe('a viewer\'s rays', () => {
+ it('go the whole radius in the open and stop at a wall', () => {
+ const open = fanDistances({ x: 0, y: 0 }, 300, [], 8);
+ expect([...open]).toEqual(new Array(8).fill(300));
+ const rays = fanDistances({ x: 0, y: 0 }, 300, [wall], 8);
+ // The ray along +x meets the wall's near face at x = 90.
+ expect(rays[0]).toBeCloseTo(90, 4);
+ // The ray along -x goes away from it, and so do the ones that miss it.
+ expect(rays[4]).toBe(300);
+ expect(rays[2]).toBe(300);
+ });
+
+ it('ignores a wall the viewer stands in, and one the circle cannot touch', () => {
+ expect(fanDistances({ x: 100, y: 0 }, 300, [wall], 8)[0]).toBe(300);
+ expect(fanDistances({ x: 0, y: 0 }, 50, [wall], 8)[0]).toBe(50);
+ });
+});
+
+describe('what has been seen', () => {
+ it('marks the cells a fan reaches and tells whether anything was new', () => {
+ const grid = new ExploredGrid(64);
+ const first = grid.markFan({ x: 500, y: 500 }, new Float32Array(32).fill(100), 0, 0, 1000, 1000);
+ expect(first).toBe(true);
+ const marked = grid.cells.reduce((n, c) => n + c, 0);
+ expect(marked).toBeGreaterThan(50);
+ expect(grid.cells[Math.floor(500 / (1000 / 64)) * 64 + Math.floor(500 / (1000 / 64))]).toBe(1);
+ // The same field of view again finds nothing new, and a point outside the rectangle is not a cell.
+ expect(grid.markFan({ x: 500, y: 500 }, new Float32Array(32).fill(100), 0, 0, 1000, 1000)).toBe(false);
+ expect(grid.mark(-5, 500, 0, 0, 1000, 1000)).toBe(false);
+ });
+
+ it('is saved as a string and restored from it, and refuses one that does not fit', () => {
+ const grid = new ExploredGrid(32);
+ grid.markFan({ x: 100, y: 100 }, new Float32Array(16).fill(60), 0, 0, 320, 320);
+ const text = grid.toString();
+ const other = new ExploredGrid(32);
+ expect(other.fromString(text)).toBe(true);
+ expect([...other.cells]).toEqual([...grid.cells]);
+ const wrongSize = new ExploredGrid(16);
+ expect(wrongSize.fromString(text)).toBe(false);
+ expect(other.fromString('32:zz')).toBe(false);
+ expect(other.fromString('32:1,1')).toBe(false);
+ // A refused string leaves the grid as it was.
+ expect([...other.cells]).toEqual([...grid.cells]);
+ // An empty fog is one run.
+ expect(new ExploredGrid(4).toString()).toBe('4:g');
+ });
+
+ it('has nothing to save or restore with no fog in the scene', () => {
+ expect(exploredToString()).toBe('');
+ expect(exploredFromString('4:g')).toBe(false);
+ });
+});
+
+describe('the fog effect', () => {
+ it('is an atmosphere effect that asks for no depth, whose maps and rectangle are written by the engine', () => {
+ const def = getEffectDef('fog2d');
+ expect(def).toBeDefined();
+ expect(def!.category).toBe('atmosphere');
+ expect(def!.uniforms.filter((u) => u.internal).map((u) => u.name)).toEqual(['u_fogL', 'u_fogB', 'u_fogW', 'u_fogH']);
+ expect(def!.textures!.map((t) => t.name)).toEqual([FOG_EXPLORED_TEXTURE, FOG_VISIBLE_TEXTURE]);
+ });
+
+ it('is turned off while there is no fog to read, so the whole picture is not black', () => {
+ const fog: BlendedEffect = { enabled: true, uniforms: new Map(), textures: new Map(), colors: new Map() };
+ applyFogOfWarToFog(new Map([['fog2d', fog]]));
+ expect(fog.enabled).toBe(false);
+ const other: BlendedEffect = { enabled: true, uniforms: new Map(), textures: new Map(), colors: new Map() };
+ applyFogOfWarToFog(new Map([['vignette', other]]));
+ expect(other.enabled).toBe(true);
+ });
+});
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index 718d366d6..835159158 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -43,7 +43,7 @@ const CASES: Array<{ name: string; source: string }> = [
...BUILTIN_SHADER_TEMPLATES.map((t) => ({ name: `template:${t.id}`, source: t.source })),
...embeddedEsshaders('render/filters.ts').map((source, i) => ({ name: `filters.ts[${i}]`, source })),
...embeddedEsshaders('render/spriteFilter.ts').map((source, i) => ({ name: `spriteFilter.ts[${i}]`, source })),
- ...['basic', 'atmosphere', 'lighting', 'rain2d'].flatMap((group) => embeddedEsshaders(`postprocess/sources/${group}.ts`).map(
+ ...['basic', 'atmosphere', 'lighting', 'rain2d', 'fog2d'].flatMap((group) => embeddedEsshaders(`postprocess/sources/${group}.ts`).map(
(source, i) => ({ name: `postProcessEffects.ts[${group}:${i}]`, source }))),
...embeddedEsshaders('camera/editorGridRenderer.ts').map(
(source, i) => ({ name: `editorGridRenderer.ts[${i}]`, source })),
@@ -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(41);
+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(42);
expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);
});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index d9cb3b9b5..2d8ec8897 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -136,6 +136,7 @@ const DISPOSITION = {
// — owed: a creator-facing component nothing in the shipped corpus authors.
// Each reason names where the coverage belongs. —
BlobShadow: ['owed', 'only the blob-shadow render fixture places one; an example for a phone-scale scene that wants a shadow without a shadow map is owed'],
+ FogOfWar: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; it arrives with the top-down example CoverFade is owed'],
SightViewer: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; it arrives with the top-down example CoverFade is owed'],
SightTarget: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; it arrives with the top-down example CoverFade is owed'],
CoverFade: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; an example of a top-down hut whose roof thins as the player walks in is owed'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 518843a68..a726f3b42 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -128,6 +128,9 @@ const DISPOSITION = {
'Terrain.height': ['renders', 'the ground drawn at it is the outline'],
'Terrain.dirtHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
'Terrain.snowHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
+ 'FogOfWar.width': ['owed', 'the rectangle the fog covers is not outlined in the viewport yet'],
+ 'FogOfWar.height': ['owed', 'the rectangle the fog covers is not outlined in the viewport yet'],
+ 'FogOfWar.viewRadius': ['no-place', 'how far a viewer with no radius of its own sees, a limit on the field of view and not a region of the fog entity'],
'Foliage.sizeX': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
'Foliage.sizeZ': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
'Terrain.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],