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 viewer and the walls it cannot see through hide what is not lit

yhhddc0c46f8f9a
diff --git a/desktop b/desktop
index c9cf3a2b6..57b650a11 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c9cf3a2b65ef954de2304c79b033e0b902aeeb36
+Subproject commit 57b650a11de6ffaf886b8d05fb10e818c0c20708
diff --git a/docs/astro/src/content/docs/graphics/sprites.mdx b/docs/astro/src/content/docs/graphics/sprites.mdx
index 2b44d0023..8fb76880c 100644
--- a/docs/astro/src/content/docs/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/graphics/sprites.mdx
@@ -269,6 +269,22 @@ that. Set the effect's **Shelter Mask Size** (`maskSize`, 64 to 2048) for finer
The sprite's rectangle is what is kept clear, so `inset` (world units) shrinks it by that much on every side, to leave the ground at the feet wet. A sprite faded by a
`CoverFade` keeps the rain off it only as much as it shows.
+### What the player can see
+
+A lit sprite behind a wall is already dark: the wall's `ShadowCaster2D` shadows the light that would show it. Anything that is not lit is not: an enemy drawn
+unlit, its health bar, a pickup that glows on its own. `SightViewer` and `SightTarget` read the same walls again, on the CPU, for those. Put `SightViewer` on the
+player (an eye) and `SightTarget` on a sprite that should not be seen unless some viewer has a clear line to it; it eases to `hiddenOpacity` while none has.
+
+| Field | On | What it does |
+|---|---|---|
+| `radius` | `SightViewer` | How far the eye sees, in world units. 0 is no limit: only a wall stops it. |
+| `hiddenOpacity` | `SightTarget` | The sprite's alpha, as a share of its own, while no viewer sees it. 0 is gone. |
+| `fadeTime` | `SightTarget` | Seconds the fade takes, either way. |
+
+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.
+
### Depth layers (2.5D)
Check a layer under **Settings → Project → Rendering → Advanced → Depth-sorted layers** and it
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 a2b240bb9..c3081cd23 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
@@ -231,6 +231,18 @@ world.applyEntityOrder([other, another, card]);
遮雨区的数量没有上限。每一帧,视野里的遮雨区会被画进一张覆盖视野的小遮罩(每个一个矩形,椭圆用几条横带),雨每个像素只读遮罩里的一个纹素,所以一整个村子的屋顶和一间小屋的开销差不多。遮罩默认宽 512 个纹素,遮雨区的边缘大约有"视野尺寸除以 512"那么软。在效果上设置 **Shelter Mask Size**(`maskSize`,64 到 2048)可以换更细的边缘或更便宜的遮罩;画质档位还会把它压得更低:档位的 `shelterMaskSize` 是该档位允许的最大值(低 256、中 512、高 1024,在**项目设置 → 渲染 → 画质**里改)。雨是盖在画好的画面上的,分不出角色和脚下的地面。给站在地上的精灵(角色、树干、箱子)加 `RainUpright`,涟漪、溅花、积水和湿地变暗就不会画在它身上;雨线仍会穿过它,因为雨本来就会落在人身上。被保持干净的是精灵的矩形,`inset`(世界单位)把它四周各缩进这么多,让脚边的地面仍然是湿的。被 `CoverFade` 淡出的精灵,露出多少,雨就让开多少。
+### 玩家能看见什么
+
+墙后面被灯照亮的精灵本来就是暗的:墙的 `ShadowCaster2D` 挡住了照亮它的光。但没被灯照的东西不会这样:不受光的敌人、它的血条、自己发光的拾取物。`SightViewer` 和 `SightTarget` 在 CPU 上再读一遍同样的墙,专门管这些。给玩家加 `SightViewer`(一只眼睛),给"没有任何眼睛看得见时就不该看到"的精灵加 `SightTarget`:没有视线时它会渐隐到 `hiddenOpacity`。
+
+| 字段 | 所在组件 | 作用 |
+|---|---|---|
+| `radius` | `SightViewer` | 眼睛能看多远(世界单位)。0 表示不限,只有墙能挡住。 |
+| `hiddenOpacity` | `SightTarget` | 没有任何眼睛看见它时,精灵的透明度占自己的几成。0 是完全隐去。 |
+| `fadeTime` | `SightTarget` | 渐变用多少秒,来去相同。 |
+
+墙若包含了观察者或目标,对这一对就不挡视线(站在灌木里能看到外面)。场景里没有任何观察者时,所有目标都是隐藏的。不要把 `SightTarget` 和 `CoverFade` 放在同一个精灵上,两者都要管它的透明度。`segmentBlocked(from, to, rings)`、`seesPoint` 和 `currentSightRings()` 让玩法代码得到和精灵一样的答案。这里只管"此刻看得见什么",不记忆看过的地方,玩家走开后那片地面又是暗的。
+
### 深度层(2.5D)
在 **设置 → 项目 → 渲染 → 高级 → 深度排序层** 勾选某个层后,该层完全不再依赖
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index f2cf0726d..466c69a55 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": 2672,
+ "experimental": 2683,
"deprecated": 3
},
- "total": 2958,
+ "total": 2969,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 707e9993f..bb98dff81 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -82,6 +82,8 @@ 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: '假阴影用一个圆片代替阴影图' },
+ 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: '屋顶与树冠遮挡淡出' },
CoverFadeTarget: { category: 'graphics', summary: 'Marks what a CoverFade keeps visible — the player, and anything else that must not be hidden by a roof or a crown.', doc: 'graphics/sprites', anchor: 'fading-a-roof-or-a-crown-over-the-player', anchorZh: '屋顶与树冠遮挡淡出' },
RainUpright: { category: 'graphics', summary: 'Marks a sprite that stands on the ground (a character, a trunk), so the 2D rain draws no rings, splashes or wet darkening over it.', doc: 'graphics/sprites', anchor: 'keeping-the-ground-under-a-roof-dry', anchorZh: '让屋顶下的地面保持干燥' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 18760dc02..231fe0372 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -4683,6 +4683,56 @@
}
]
},
+ {
+ "name": "SightTarget",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "hiddenOpacity",
+ "type": "number",
+ "default": "0",
+ "doc": "The sprite's alpha, as a share of its own, while no viewer sees it.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "fadeTime",
+ "type": "number",
+ "default": "0.15",
+ "doc": "Seconds the fade takes, either way.",
+ "range": "0–5, step 0.05"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "hiddenOpacity",
+ "fadeTime"
+ ]
+ },
+ {
+ "name": "SightViewer",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "0",
+ "doc": "How far this eye sees. 0 is no limit: only a wall stops it.",
+ "range": "≥ 0, step 1"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "radius"
+ ]
+ },
{
"name": "SixDOFJoint3D",
"source": "ts",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 904d6ea3a..ddeaf0d06 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 · 1928 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1939 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9165,6 +9165,40 @@ source: ((id: SideModuleId) => Promise<SideModuleSource | null>) | undefined
BuiltinSideModuleId | (string & {})
```
+## SightPoint — interface @experimental
+```
+x: number
+y: number
+```
+
+## SightRing — type @experimental
+```
+readonly SightPoint[]
+```
+
+## SightTarget — const @experimental
+```
+ComponentDef<SightTargetData>
+```
+
+## SightTargetData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+hiddenOpacity: number
+```
+
+## SightViewer — const @experimental
+```
+ComponentDef<SightViewerData>
+```
+
+## SightViewerData — interface @experimental
+```
+enabled: boolean
+radius: number
+```
+
## Signal — interface @experimental
```
get: () => T
@@ -13764,6 +13798,11 @@ Plugin
(width: number, widest: number): number
```
+## currentSightRings — function @experimental
+```
+(): readonly SightRing[]
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -15754,6 +15793,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## ringContains — function @experimental
+```
+(ring: SightRing, p: SightPoint): boolean
+```
+
## rng — function @experimental
```
(seed: number): () => number
@@ -15884,6 +15928,16 @@ Plugin
(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
```
+## seesPoint — function @experimental
+```
+(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean
+```
+
+## segmentBlocked — function @experimental
+```
+(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
@@ -16189,6 +16243,11 @@ ServicesPlugin
(id: SideModuleId): SideModuleDescriptor | undefined
```
+## sightRingOf — function @experimental
+```
+(caster: ShadowCaster2DData, transform: TransformData): SightRing | null
+```
+
## signal — function @experimental
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d535e8858..4854fffd8 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 · 1947 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1958 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9378,6 +9378,40 @@ source: ((id: SideModuleId) => Promise<SideModuleSource | null>) | undefined
BuiltinSideModuleId | (string & {})
```
+## SightPoint — interface @experimental
+```
+x: number
+y: number
+```
+
+## SightRing — type @experimental
+```
+readonly SightPoint[]
+```
+
+## SightTarget — const @experimental
+```
+ComponentDef<SightTargetData>
+```
+
+## SightTargetData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+hiddenOpacity: number
+```
+
+## SightViewer — const @experimental
+```
+ComponentDef<SightViewerData>
+```
+
+## SightViewerData — interface @experimental
+```
+enabled: boolean
+radius: number
+```
+
## Signal — interface @experimental
```
get: () => T
@@ -14017,6 +14051,11 @@ Plugin
(width: number, widest: number): number
```
+## currentSightRings — function @experimental
+```
+(): readonly SightRing[]
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -16017,6 +16056,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## ringContains — function @experimental
+```
+(ring: SightRing, p: SightPoint): boolean
+```
+
## rng — function @experimental
```
(seed: number): () => number
@@ -16147,6 +16191,16 @@ Plugin
(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
```
+## seesPoint — function @experimental
+```
+(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean
+```
+
+## segmentBlocked — function @experimental
+```
+(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
@@ -16452,6 +16506,11 @@ ServicesPlugin
(id: SideModuleId): SideModuleDescriptor | undefined
```
+## sightRingOf — function @experimental
+```
+(caster: ShadowCaster2DData, transform: TransformData): SightRing | null
+```
+
## signal — function @experimental
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 8d7b2926a..a214b0fb0 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 · 1927 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1938 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9160,6 +9160,40 @@ source: ((id: SideModuleId) => Promise<SideModuleSource | null>) | undefined
BuiltinSideModuleId | (string & {})
```
+## SightPoint — interface @experimental
+```
+x: number
+y: number
+```
+
+## SightRing — type @experimental
+```
+readonly SightPoint[]
+```
+
+## SightTarget — const @experimental
+```
+ComponentDef<SightTargetData>
+```
+
+## SightTargetData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+hiddenOpacity: number
+```
+
+## SightViewer — const @experimental
+```
+ComponentDef<SightViewerData>
+```
+
+## SightViewerData — interface @experimental
+```
+enabled: boolean
+radius: number
+```
+
## Signal — interface @experimental
```
get: () => T
@@ -13759,6 +13793,11 @@ Plugin
(width: number, widest: number): number
```
+## currentSightRings — function @experimental
+```
+(): readonly SightRing[]
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -15759,6 +15798,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## ringContains — function @experimental
+```
+(ring: SightRing, p: SightPoint): boolean
+```
+
## rng — function @experimental
```
(seed: number): () => number
@@ -15889,6 +15933,16 @@ Plugin
(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
```
+## seesPoint — function @experimental
+```
+(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean
+```
+
+## segmentBlocked — function @experimental
+```
+(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
@@ -16194,6 +16248,11 @@ ServicesPlugin
(id: SideModuleId): SideModuleDescriptor | undefined
```
+## sightRingOf — function @experimental
+```
+(caster: ShadowCaster2DData, transform: TransformData): SightRing | null
+```
+
## signal — function @experimental
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index bdd26444a..951649fac 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 · 1949 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1960 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9454,6 +9454,40 @@ source: ((id: SideModuleId) => Promise<SideModuleSource | null>) | undefined
BuiltinSideModuleId | (string & {})
```
+## SightPoint — interface @experimental
+```
+x: number
+y: number
+```
+
+## SightRing — type @experimental
+```
+readonly SightPoint[]
+```
+
+## SightTarget — const @experimental
+```
+ComponentDef<SightTargetData>
+```
+
+## SightTargetData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+hiddenOpacity: number
+```
+
+## SightViewer — const @experimental
+```
+ComponentDef<SightViewerData>
+```
+
+## SightViewerData — interface @experimental
+```
+enabled: boolean
+radius: number
+```
+
## Signal — interface @experimental
```
get: () => T
@@ -14064,6 +14098,11 @@ Plugin
(width: number, widest: number): number
```
+## currentSightRings — function @experimental
+```
+(): readonly SightRing[]
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -16064,6 +16103,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## ringContains — function @experimental
+```
+(ring: SightRing, p: SightPoint): boolean
+```
+
## rng — function @experimental
```
(seed: number): () => number
@@ -16194,6 +16238,16 @@ Plugin
(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
```
+## seesPoint — function @experimental
+```
+(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean
+```
+
+## segmentBlocked — function @experimental
+```
+(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
@@ -16499,6 +16553,11 @@ ServicesPlugin
(id: SideModuleId): SideModuleDescriptor | undefined
```
+## sightRingOf — function @experimental
+```
+(caster: ShadowCaster2DData, transform: TransformData): SightRing | null
+```
+
## signal — function @experimental
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e3feaf7c1..c534aa4ab 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 · 1940 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1951 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9167,6 +9167,40 @@ source: ((id: SideModuleId) => Promise<SideModuleSource | null>) | undefined
BuiltinSideModuleId | (string & {})
```
+## SightPoint — interface @experimental
+```
+x: number
+y: number
+```
+
+## SightRing — type @experimental
+```
+readonly SightPoint[]
+```
+
+## SightTarget — const @experimental
+```
+ComponentDef<SightTargetData>
+```
+
+## SightTargetData — interface @experimental
+```
+enabled: boolean
+fadeTime: number
+hiddenOpacity: number
+```
+
+## SightViewer — const @experimental
+```
+ComponentDef<SightViewerData>
+```
+
+## SightViewerData — interface @experimental
+```
+enabled: boolean
+radius: number
+```
+
## Signal — interface @experimental
```
get: () => T
@@ -13791,6 +13825,11 @@ Plugin
(width: number, widest: number): number
```
+## currentSightRings — function @experimental
+```
+(): readonly SightRing[]
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -15791,6 +15830,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## ringContains — function @experimental
+```
+(ring: SightRing, p: SightPoint): boolean
+```
+
## rng — function @experimental
```
(seed: number): () => number
@@ -15921,6 +15965,16 @@ Plugin
(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
```
+## seesPoint — function @experimental
+```
+(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean
+```
+
+## segmentBlocked — function @experimental
+```
+(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
@@ -16226,6 +16280,11 @@ ServicesPlugin
(id: SideModuleId): SideModuleDescriptor | undefined
```
+## sightRingOf — function @experimental
+```
+(caster: ShadowCaster2DData, transform: TransformData): SightRing | null
+```
+
## signal — function @experimental
```
<T>(initial: T): Signal<T>
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 369ab5c5a..ce337dece 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -24,6 +24,7 @@ import { appRegistryAsset } from '../asset/registryLookup';
import { playModeOnly } from '../ecs/env';
import { installCoverFade } from '../render/coverFade';
import { installRainShelter } from '../render/rainShelter';
+import { installSight } from '../render/sight';
import { SystemLabel } from '../ecs/systemLabels';
export class AnimationPlugin implements Plugin {
@@ -57,7 +58,8 @@ export class AnimationPlugin implements Plugin {
// A roof or a crown with a CoverFade thins out over what stands under it; with none in the scene the system finds nothing and returns.
const offCoverFade = installCoverFade(app);
const offRainShelter = installRainShelter(app);
- const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); };
+ const offSight = installSight(app);
+ const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); offSight(); };
this.despawnCleanups_.set(app, release);
this.latestDespawnCleanup_ = release;
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 2227406f0..3985335d3 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 { 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';
export type { RenderOnDemandOptions } from './render/renderDemand';
diff --git a/sdk/src/render/sight.ts b/sdk/src/render/sight.ts
new file mode 100644
index 000000000..c8315121e
--- /dev/null
+++ b/sdk/src/render/sight.ts
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sight.ts
+ * @brief What a viewer can see in a 2D scene: the walls that block a line, and the things that are hidden while a wall stands between.
+ *
+ * @details A lit sprite behind a wall is already dark, because the wall's `ShadowCaster2D` shadows the light that would show it. Everything that
+ * is not lit is not: an enemy drawn unlit, its health bar, a pickup glowing on its own. So the same walls are read again here as a
+ * test on the CPU, `segmentBlocked`, and two components use it. `SightViewer` is an eye (the player); `SightTarget` goes on a sprite that
+ * should not be seen unless some viewer has a clear line to it, and eases to `hiddenOpacity` while none does. The viewer's own `radius`
+ * is how far it sees (0: as far as the line is clear).
+ *
+ * A caster that contains the viewer or the target blocks nothing for that pair: standing in a bush you see out of it, and a thing in a
+ * wall's own footprint is seen from outside. The test is segment against edge, so its cost is viewers times targets times the edges near
+ * the line, which is what a few hundred targets and a village of walls cost on a phone. It runs in play only.
+ *
+ * A sprite carries one fade: do not put a `SightTarget` and a `CoverFade` on the same sprite.
+ */
+import type { App } from '../app/app';
+import type { Entity } from '../types';
+import { defineComponent, ShadowCaster2D, Sprite, Transform, type ShadowCaster2DData, type SpriteData, type TransformData } from '../ecs/component';
+import { defineSystem, Schedule, GetWorld } from '../ecs/system';
+import { Res, Time, type TimeData } from '../ecs/resource';
+import { Query } from '../ecs/query';
+import type { World } from '../ecs/world';
+import { isEditor, isPlayMode } from '../ecs/env';
+import { stepFade } from './coverFade';
+
+/** The fields of the `SightViewer` component. @experimental */
+export interface SightViewerData {
+ /** How far this eye sees, in world units. 0 is no limit: only a wall stops it. */
+ radius: number;
+ /** Off: this eye sees nothing. */
+ enabled: boolean;
+}
+
+/**
+ * An eye: the sprites with a `SightTarget` are seen while some viewer has a clear line to them.
+ *
+ * @experimental
+ */
+export const SightViewer = defineComponent<SightViewerData>('SightViewer',
+ { radius: 0, enabled: true },
+ { fields: { radius: { min: 0, step: 1, unit: 'wu', tooltip: 'How far this eye sees. 0 is no limit: only a wall stops it.' } } },
+);
+
+/** The fields of the `SightTarget` component. @experimental */
+export interface SightTargetData {
+ /** The sprite's alpha, as a share of its own, while no viewer sees it. 0 is gone. */
+ hiddenOpacity: number;
+ /** Seconds the fade takes, either way. */
+ fadeTime: number;
+ /** Off: the sprite stays as authored. */
+ enabled: boolean;
+}
+
+/**
+ * Hides the sprite on this entity while no `SightViewer` has a clear line to it.
+ *
+ * @experimental
+ */
+export const SightTarget = defineComponent<SightTargetData>('SightTarget',
+ { hiddenOpacity: 0, fadeTime: 0.15, enabled: true },
+ {
+ fields: {
+ hiddenOpacity: { min: 0, max: 1, step: 0.01, tooltip: "The sprite's alpha, as a share of its own, while no viewer sees it." },
+ fadeTime: { min: 0, max: 5, step: 0.05, unit: 's', tooltip: 'Seconds the fade takes, either way.' },
+ },
+ },
+);
+
+/** A point in the world plane. */
+export interface SightPoint {
+ x: number;
+ y: number;
+}
+
+/** One blocker: the outline of a wall, in world units, in order round the shape. */
+export type SightRing = readonly SightPoint[];
+
+/** Whether the open segments a-b and c-d cross. A touch at an end is not a crossing: a viewer standing against a wall is not behind it. */
+function crosses(a: SightPoint, b: SightPoint, c: SightPoint, d: SightPoint): boolean {
+ const d1x = b.x - a.x, d1y = b.y - a.y, d2x = d.x - c.x, d2y = d.y - c.y;
+ const denom = d1x * d2y - d1y * d2x;
+ if (denom === 0) return false;
+ const t = ((c.x - a.x) * d2y - (c.y - a.y) * d2x) / denom;
+ const u = ((c.x - a.x) * d1y - (c.y - a.y) * d1x) / denom;
+ return t > 1e-6 && t < 1 - 1e-6 && u >= 0 && u <= 1;
+}
+
+/** Whether a point lies inside a ring (even-odd). */
+export function ringContains(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;
+}
+
+/**
+ * Whether the line from `from` to `to` runs through a wall. A ring that contains either end blocks nothing for this pair.
+ */
+export function segmentBlocked(from: SightPoint, to: SightPoint, rings: readonly SightRing[]): boolean {
+ const minX = Math.min(from.x, to.x), maxX = Math.max(from.x, to.x);
+ const minY = Math.min(from.y, to.y), maxY = Math.max(from.y, to.y);
+ for (const ring of rings) {
+ if (ring.length < 3) continue;
+ let rx0 = Infinity, rx1 = -Infinity, ry0 = Infinity, ry1 = -Infinity;
+ for (const p of ring) {
+ if (p.x < rx0) rx0 = p.x;
+ if (p.x > rx1) rx1 = p.x;
+ if (p.y < ry0) ry0 = p.y;
+ if (p.y > ry1) ry1 = p.y;
+ }
+ if (rx1 < minX || rx0 > maxX || ry1 < minY || ry0 > maxY) continue;
+ if (ringContains(ring, from) || ringContains(ring, to)) continue;
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
+ if (crosses(from, to, ring[j]!, ring[i]!)) return true;
+ }
+ }
+ return false;
+}
+
+/** A caster's outline in the world: its box or its traced path, scaled, turned and placed by its transform. Null for one that blocks nothing. */
+export function sightRingOf(caster: ShadowCaster2DData, transform: TransformData): SightRing | null {
+ if (!caster.enabled) return null;
+ const local: SightPoint[] = caster.path.length >= 3
+ ? caster.path
+ : [
+ { x: -caster.size.x / 2, y: -caster.size.y / 2 }, { x: caster.size.x / 2, y: -caster.size.y / 2 },
+ { x: caster.size.x / 2, y: caster.size.y / 2 }, { x: -caster.size.x / 2, y: caster.size.y / 2 },
+ ];
+ if (caster.path.length < 3 && (caster.size.x <= 0 || caster.size.y <= 0)) return null;
+ const q = transform.worldRotation;
+ const angle = Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
+ const cos = Math.cos(angle), sin = Math.sin(angle);
+ const s = transform.worldScale, o = transform.worldPosition;
+ return local.map((p) => {
+ const x = p.x * s.x, y = p.y * s.y;
+ return { x: o.x + x * cos - y * sin, y: o.y + x * sin + y * cos };
+ });
+}
+
+/** Whether `viewer` sees `target`: inside its radius (when it has one) and with no wall between. */
+export function seesPoint(viewer: SightPoint, radius: number, target: SightPoint, rings: readonly SightRing[]): boolean {
+ if (radius > 0 && Math.hypot(target.x - viewer.x, target.y - viewer.y) > radius) return false;
+ return !segmentBlocked(viewer, target, rings);
+}
+
+interface Fading {
+ authored: number;
+ shown: number;
+}
+
+let ringsNow: SightRing[] = [];
+
+/** The walls the last frame read, for a game that wants the same answer the sprites got. */
+export function currentSightRings(): readonly SightRing[] {
+ return ringsNow;
+}
+
+/** Installs the system that hides and shows sight targets. Returns the function that puts every sprite back as authored. */
+export function installSight(app: App): () => void {
+ const fading = new Map<Entity, Fading>();
+
+ const put = (world: World, entity: Entity, alpha: number): void => {
+ const sprite = world.get(entity, Sprite) as SpriteData;
+ if (sprite.color.a === alpha) return;
+ world.set(entity, Sprite, { ...sprite, color: { ...sprite.color, a: alpha } });
+ };
+ const restore = (world: World, entity: Entity, state: Fading): void => {
+ if (world.has(entity, Sprite)) put(world, entity, state.authored);
+ fading.delete(entity);
+ };
+
+ // system-access: the sprite's alpha is read and written through the world, per entity, because the fade owns a share of it.
+ const system = defineSystem(
+ [Query(ShadowCaster2D, Transform), Query(SightViewer, Transform), Query(SightTarget, Sprite, Transform), Res(Time), GetWorld()],
+ (
+ casters: Iterable<[Entity, ShadowCaster2DData, TransformData]>,
+ viewers: Iterable<[Entity, SightViewerData, TransformData]>,
+ targets: Iterable<[Entity, SightTargetData, SpriteData, TransformData]>,
+ time: TimeData, world: World,
+ ) => {
+ if (isEditor() && !isPlayMode()) {
+ if (fading.size > 0) for (const [entity, state] of [...fading]) restore(world, entity, state);
+ return;
+ }
+ const eyes: Array<{ at: SightPoint; radius: number }> = [];
+ for (const [, viewer, transform] of viewers) {
+ if (viewer.enabled) eyes.push({ at: { x: transform.worldPosition.x, y: transform.worldPosition.y }, radius: viewer.radius });
+ }
+ const rings: SightRing[] = [];
+ if (eyes.length > 0) {
+ for (const [, caster, transform] of casters) {
+ const ring = sightRingOf(caster, transform);
+ if (ring) rings.push(ring);
+ }
+ }
+ ringsNow = rings;
+
+ const seen = new Set<Entity>();
+ for (const [entity, target, sprite, transform] of targets) {
+ seen.add(entity);
+ let state = fading.get(entity);
+ if (!target.enabled) { if (state) restore(world, entity, state); continue; }
+ if (!state) { state = { authored: sprite.color.a, shown: 1 }; fading.set(entity, state); }
+ const at = { x: transform.worldPosition.x, y: transform.worldPosition.y };
+ // With no viewer at all there is nobody to see: a scene that has not placed its eye yet hides its targets, which is what "seen by none" means.
+ const visible = eyes.some((eye) => seesPoint(eye.at, eye.radius, at, rings));
+ const goal = visible ? 1 : Math.min(Math.max(target.hiddenOpacity, 0), 1);
+ if (state.shown === goal) continue;
+ state.shown = stepFade(state.shown, goal, time.delta, target.fadeTime);
+ put(world, entity, state.authored * state.shown);
+ }
+ for (const [entity, state] of [...fading]) if (!seen.has(entity)) restore(world, entity, state);
+ },
+ { name: 'SightSystem' },
+ );
+ app.addSystemToSchedule(Schedule.PostUpdate, system);
+
+ return () => {
+ ringsNow = [];
+ const world = app.world;
+ for (const [entity, state] of [...fading]) restore(world, entity, state);
+ };
+}
diff --git a/sdk/tests/sight.test.ts b/sdk/tests/sight.test.ts
new file mode 100644
index 000000000..b8f6b9480
--- /dev/null
+++ b/sdk/tests/sight.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a 2D viewer sees: the walls are the shadow casters, and a line through one is blocked, except for a viewer or a target that stands in it.
+ */
+import { describe, expect, it } from 'vitest';
+import { ringContains, seesPoint, segmentBlocked, sightRingOf, type SightRing } from '../src/render/sight';
+import type { ShadowCaster2DData, TransformData } from '../src/ecs/component';
+
+const at = (x: number, y: number, angle = 0, scale = 1): TransformData => ({
+ worldPosition: { x, y, z: 0 }, worldScale: { x: scale, y: scale, z: 1 },
+ worldRotation: { w: Math.cos(angle / 2), x: 0, y: 0, z: Math.sin(angle / 2) },
+}) as TransformData;
+const box = (w: number, h: number): ShadowCaster2DData => ({ size: { x: w, y: h }, path: [], enabled: true });
+
+/** A wall 20 wide and 200 tall at x = 100. */
+const wall: SightRing = sightRingOf(box(20, 200), at(100, 0))!;
+
+describe('the walls a viewer is blocked by', () => {
+ it('takes a box caster as its four corners, placed, scaled and turned by its transform', () => {
+ expect(wall).toEqual([{ x: 90, y: -100 }, { x: 110, y: -100 }, { x: 110, y: 100 }, { x: 90, y: 100 }]);
+ const turned = sightRingOf(box(20, 200), at(0, 0, Math.PI / 2))!;
+ expect(Math.max(...turned.map((p) => Math.abs(p.x)))).toBeCloseTo(100, 6);
+ expect(Math.max(...turned.map((p) => Math.abs(p.y)))).toBeCloseTo(10, 6);
+ expect(sightRingOf(box(20, 200), at(0, 0, 0, 2))![1]).toEqual({ x: 20, y: -200 });
+ });
+
+ it('takes a traced outline over the box, and nothing from a disabled or empty caster', () => {
+ const traced: ShadowCaster2DData = { size: { x: 1, y: 1 }, path: [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 0, y: 10 }], enabled: true };
+ expect(sightRingOf(traced, at(5, 5))).toEqual([{ x: 5, y: 5 }, { x: 15, y: 5 }, { x: 5, y: 15 }]);
+ expect(sightRingOf({ ...box(20, 200), enabled: false }, at(0, 0))).toBeNull();
+ expect(sightRingOf(box(0, 200), at(0, 0))).toBeNull();
+ });
+});
+
+describe('a line through a wall', () => {
+ it('is blocked when it crosses the wall and clear when it goes round or stops short', () => {
+ expect(segmentBlocked({ x: 0, y: 0 }, { x: 200, y: 0 }, [wall])).toBe(true);
+ expect(segmentBlocked({ x: 0, y: 0 }, { x: 80, y: 0 }, [wall])).toBe(false);
+ expect(segmentBlocked({ x: 0, y: 150 }, { x: 200, y: 150 }, [wall])).toBe(false);
+ expect(segmentBlocked({ x: 0, y: 0 }, { x: 200, y: 0 }, [])).toBe(false);
+ });
+
+ it('is not blocked by a wall the viewer or the target stands in', () => {
+ expect(segmentBlocked({ x: 100, y: 0 }, { x: 200, y: 0 }, [wall])).toBe(false);
+ expect(segmentBlocked({ x: 0, y: 0 }, { x: 105, y: 40 }, [wall])).toBe(false);
+ expect(ringContains(wall, { x: 100, y: 0 })).toBe(true);
+ expect(ringContains(wall, { x: 120, y: 0 })).toBe(false);
+ });
+
+ it('is not blocked by a wall it only touches at its own end', () => {
+ expect(segmentBlocked({ x: 0, y: 0 }, { x: 90, y: 0 }, [wall])).toBe(false);
+ });
+});
+
+describe('what a viewer sees', () => {
+ it('sees what is within its radius and not behind a wall, and with no radius sees as far as the line is clear', () => {
+ const eye = { x: 0, y: 0 };
+ expect(seesPoint(eye, 50, { x: 40, y: 0 }, [wall])).toBe(true);
+ expect(seesPoint(eye, 50, { x: 60, y: 0 }, [wall])).toBe(false);
+ expect(seesPoint(eye, 0, { x: 5000, y: 8000 }, [wall])).toBe(true);
+ expect(seesPoint(eye, 0, { x: 200, y: 0 }, [wall])).toBe(false);
+ });
+});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index be2228e29..d9cb3b9b5 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -136,6 +136,8 @@ 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'],
+ 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'],
CoverFadeTarget: ['owed', 'the tag that goes with CoverFade, and owed with it'],
RainUpright: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; it arrives with the top-down rain example RainShelter is owed'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index ab31680bb..518843a68 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -116,6 +116,7 @@ const DISPOSITION = {
'MeshInstances.shadowDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
'Planet.radius': ['renders', 'the sphere drawn at the entity is the outline'],
'BlobShadow.radius': ['renders', 'the disc drawn on the ground is the outline'],
+ 'SightViewer.radius': ['no-place', 'how far an eye sees round the entity, a limit on what it reports and not a region the editor lays out'],
'BlobShadow.fadeHeight': ['no-place', 'a height above the ground at which the disc is gone, not a region of the entity'],
'Planet.collisionDistance': ['no-place', 'how far round each moving body the ground is built for collision, not a region of the entity'],
'Planet.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],