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): plants of a sway material lean away from a body walking through them

yhhfd8ccf949b38
diff --git a/desktop b/desktop
index 02c5be76c..2a76f952a 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 02c5be76c4b29bcf5cd31d95dab145b94bbb464f
+Subproject commit 2a76f952aef8adbb947279d9627649600f074f2f
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 591a0a8d5..b2b8f0b47 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -27,7 +27,7 @@ creates a material from a built-in template — the same list ships in code as
|---|---|---|
| **Unlit** | `sprite-unlit` | Texture × vertex color × `u_tint`. The plain default. |
| **Lit** | `sprite-lit` | Lit by the scene's 2D lights; `u_tint` + optional `u_normalMap`. |
-| **Sway** | `sprite-sway` | Leans in the wind with the foot fixed and the tip free — grass, reeds, hanging cloth. `u_swayStrength` is the lean as a share of the sprite's width; the weather's `wind` scales it. Lit, with an optional normal map. |
+| **Sway** | `sprite-sway` | Leans in the wind with the foot fixed and the tip free — grass, reeds, hanging cloth. `u_swayStrength` is the lean as a share of the sprite's width; the weather's `wind` scales it. Lit, with an optional normal map. A `SwayPusher` on a character makes the plants lean away from it as it walks through (the eight nearest the camera; `u_swayPushStrength` is how far they lean). |
| **Hit Flash** | `sprite-hit-flash` | Blends toward `u_flashColor` by `u_flash` — drive it from code for damage blinks. |
| **Outline** | `sprite-outline` | Colored silhouette outline (`u_outlineColor`, `u_outlineWidth` in texels). |
| **Dissolve** | `sprite-dissolve` | Noise burn-away with a glowing edge (`u_progress` 0→1). |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index 3ecde61a5..c05a1670e 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -23,7 +23,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
|---|---|---|
| **Unlit** | `sprite-unlit` | 纹理 × 顶点色 × `u_tint`,普通默认。 |
| **Lit** | `sprite-lit` | 被场景 2D 灯光照亮;`u_tint` + 可选 `u_normalMap`。 |
-| **Sway** | `sprite-sway` | 随风倾斜,底部固定、顶部自由——草、芦苇、悬挂的布。`u_swayStrength` 是倾斜幅度占精灵宽度的比例,天气的 `wind` 会放大它。受光照,可带法线贴图。 |
+| **Sway** | `sprite-sway` | 随风倾斜,底部固定、顶部自由——草、芦苇、悬挂的布。`u_swayStrength` 是倾斜幅度占精灵宽度的比例,天气的 `wind` 会放大它。受光照,可带法线贴图。给角色加 `SwayPusher`,它走过时周围的植物会向外倒(取离相机最近的八个;`u_swayPushStrength` 是倒的幅度)。 |
| **Hit Flash** | `sprite-hit-flash` | 按 `u_flash` 混向 `u_flashColor`——代码里驱动它做受击闪白。 |
| **Outline** | `sprite-outline` | 彩色剪影描边(`u_outlineColor`、`u_outlineWidth`,单位纹素)。 |
| **Dissolve** | `sprite-dissolve` | 噪声烧蚀 + 发光边缘(`u_progress` 0→1)。 |
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index dc4794afb..40a3a7e3a 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": 2697,
+ "experimental": 2702,
"deprecated": 3
},
- "total": 2983,
+ "total": 2988,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index d92db06e7..bc1c179eb 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: '假阴影用一个圆片代替阴影图' },
+ SwayPusher: { category: 'graphics', summary: 'A body the plants of a sprite-sway material lean away from as it walks through them: the eight nearest the camera are told to the shader.', doc: 'graphics/materials', anchor: 'built-in-shader-templates', 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: '玩家能看见什么' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index ecf71c0a6..d958fd264 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -5715,6 +5715,35 @@
"plane"
]
},
+ {
+ "name": "SwayPusher",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "48",
+ "doc": "How far from the entity the plants lean away.",
+ "range": "≥ 1, step 1"
+ },
+ {
+ "key": "strength",
+ "type": "number",
+ "default": "1",
+ "doc": "How hard they lean: 1 is the full lean the material's Push Strength says.",
+ "range": "0–2, step 0.01"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "radius",
+ "strength"
+ ]
+ },
{
"name": "SwingTwistJoint3D",
"source": "ts",
@@ -6245,6 +6274,24 @@
"default": "0",
"doc": "Draw layer for a text standing in the WORLD (no UINode) — read like Sprite/ShapeRenderer layer, so a label can sit in front of the content around it. Ignored inside a Canvas, where the UI render order decides."
},
+ {
+ "key": "boxWidth",
+ "type": "number",
+ "default": "0",
+ "doc": "Layout box width for a text with no UINode (0 = no box: the origin is the box). Alignment, wrapping and overflow work inside it. A UINode, if present, decides the box instead."
+ },
+ {
+ "key": "boxHeight",
+ "type": "number",
+ "default": "0",
+ "doc": "Layout box height (0 = none). Vertical alignment and Clip/Ellipsis need it."
+ },
+ {
+ "key": "boxPivot",
+ "type": "Vec2",
+ "default": "(0.5, 0.5)",
+ "doc": "Where the entity origin sits in the box, as a fraction from its left/bottom edge: (0.5, 0.5) is the centre, (0, 1) the top-left corner."
+ },
{
"key": "enabled",
"type": "boolean",
@@ -6275,7 +6322,11 @@
"shadowOffsetX",
"shadowOffsetY",
"renderMode",
- "layer"
+ "layer",
+ "boxWidth",
+ "boxHeight",
+ "boxPivot.x",
+ "boxPivot.y"
]
},
{
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 218050815..e7839cbcc 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 · 1945 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1950 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7758,6 +7758,14 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## PushValue — interface @experimental
+```
+w: number
+x: number
+y: number
+z: number
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -8520,6 +8528,11 @@ readonly SpineVersion[]
StaticBatchLimits
```
+## SWAY_PUSHERS — const @experimental
+```
+8
+```
+
## SafeArea — const @experimental
```
ComponentDef<SafeAreaData>
@@ -10243,6 +10256,18 @@ phase: SubsystemPhase
phaseAgeMs: number
```
+## SwayPusher — const @experimental
+```
+ComponentDef<SwayPusherData>
+```
+
+## SwayPusherData — interface @experimental
+```
+enabled: boolean
+radius: number
+strength: number
+```
+
## SwingTwistJoint3D — const @experimental
```
ComponentDef<SwingTwistJoint3DData>
@@ -10638,6 +10663,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
+boxHeight: number
+boxPivot: Vec2
+boxWidth: number
color: Color
content: string
enabled: boolean
@@ -10665,6 +10693,9 @@ wordWrap: boolean
```
align: TextAlign | undefined
bold: boolean | undefined
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
@@ -15050,6 +15081,11 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
+## nearestPushers — function @experimental
+```
+(bodies: readonly { x: number; y: number; radius: number; strength: number; }[], focus: { x: number; y: number; }): PushValue[]
+```
+
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 1aa1de7e5..8874900c2 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 · 1964 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1969 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7961,6 +7961,14 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## PushValue — interface @experimental
+```
+w: number
+x: number
+y: number
+z: number
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -8733,6 +8741,11 @@ readonly SpineVersion[]
StaticBatchLimits
```
+## SWAY_PUSHERS — const @experimental
+```
+8
+```
+
## SafeArea — const @experimental
```
ComponentDef<SafeAreaData>
@@ -10456,6 +10469,18 @@ phase: SubsystemPhase
phaseAgeMs: number
```
+## SwayPusher — const @experimental
+```
+ComponentDef<SwayPusherData>
+```
+
+## SwayPusherData — interface @experimental
+```
+enabled: boolean
+radius: number
+strength: number
+```
+
## SwingTwistJoint3D — const @experimental
```
ComponentDef<SwingTwistJoint3DData>
@@ -10851,6 +10876,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
+boxHeight: number
+boxPivot: Vec2
+boxWidth: number
color: Color
content: string
enabled: boolean
@@ -10878,6 +10906,9 @@ wordWrap: boolean
```
align: TextAlign | undefined
bold: boolean | undefined
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
@@ -15313,6 +15344,11 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
+## nearestPushers — function @experimental
+```
+(bodies: readonly { x: number; y: number; radius: number; strength: number; }[], focus: { x: number; y: number; }): PushValue[]
+```
+
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 85450e762..921affc6f 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 · 1944 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1949 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7753,6 +7753,14 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## PushValue — interface @experimental
+```
+w: number
+x: number
+y: number
+z: number
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -8515,6 +8523,11 @@ readonly SpineVersion[]
StaticBatchLimits
```
+## SWAY_PUSHERS — const @experimental
+```
+8
+```
+
## SafeArea — const @experimental
```
ComponentDef<SafeAreaData>
@@ -10238,6 +10251,18 @@ phase: SubsystemPhase
phaseAgeMs: number
```
+## SwayPusher — const @experimental
+```
+ComponentDef<SwayPusherData>
+```
+
+## SwayPusherData — interface @experimental
+```
+enabled: boolean
+radius: number
+strength: number
+```
+
## SwingTwistJoint3D — const @experimental
```
ComponentDef<SwingTwistJoint3DData>
@@ -10633,6 +10658,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
+boxHeight: number
+boxPivot: Vec2
+boxWidth: number
color: Color
content: string
enabled: boolean
@@ -10660,6 +10688,9 @@ wordWrap: boolean
```
align: TextAlign | undefined
bold: boolean | undefined
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
@@ -15050,6 +15081,11 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
+## nearestPushers — function @experimental
+```
+(bodies: readonly { x: number; y: number; radius: number; strength: number; }[], focus: { x: number; y: number; }): PushValue[]
+```
+
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 20a0f1826..36506e13a 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 · 1966 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1971 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8047,6 +8047,14 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## PushValue — interface @experimental
+```
+w: number
+x: number
+y: number
+z: number
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -8809,6 +8817,11 @@ readonly SpineVersion[]
StaticBatchLimits
```
+## SWAY_PUSHERS — const @experimental
+```
+8
+```
+
## SafeArea — const @experimental
```
ComponentDef<SafeAreaData>
@@ -10532,6 +10545,18 @@ phase: SubsystemPhase
phaseAgeMs: number
```
+## SwayPusher — const @experimental
+```
+ComponentDef<SwayPusherData>
+```
+
+## SwayPusherData — interface @experimental
+```
+enabled: boolean
+radius: number
+strength: number
+```
+
## SwingTwistJoint3D — const @experimental
```
ComponentDef<SwingTwistJoint3DData>
@@ -10927,6 +10952,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
+boxHeight: number
+boxPivot: Vec2
+boxWidth: number
color: Color
content: string
enabled: boolean
@@ -10954,6 +10982,9 @@ wordWrap: boolean
```
align: TextAlign | undefined
bold: boolean | undefined
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
@@ -15360,6 +15391,11 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
+## nearestPushers — function @experimental
+```
+(bodies: readonly { x: number; y: number; radius: number; strength: number; }[], focus: { x: number; y: number; }): PushValue[]
+```
+
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f38a997d5..0fd8bda5e 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 · 1957 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1962 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7760,6 +7760,14 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## PushValue — interface @experimental
+```
+w: number
+x: number
+y: number
+z: number
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -8522,6 +8530,11 @@ readonly SpineVersion[]
StaticBatchLimits
```
+## SWAY_PUSHERS — const @experimental
+```
+8
+```
+
## SafeArea — const @experimental
```
ComponentDef<SafeAreaData>
@@ -10245,6 +10258,18 @@ phase: SubsystemPhase
phaseAgeMs: number
```
+## SwayPusher — const @experimental
+```
+ComponentDef<SwayPusherData>
+```
+
+## SwayPusherData — interface @experimental
+```
+enabled: boolean
+radius: number
+strength: number
+```
+
## SwingTwistJoint3D — const @experimental
```
ComponentDef<SwingTwistJoint3DData>
@@ -10640,6 +10665,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
+boxHeight: number
+boxPivot: Vec2
+boxWidth: number
color: Color
content: string
enabled: boolean
@@ -10667,6 +10695,9 @@ wordWrap: boolean
```
align: TextAlign | undefined
bold: boolean | undefined
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color | undefined
content: string | undefined
enabled: boolean | undefined
@@ -15087,6 +15118,11 @@ MeshRendererPlugin
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
```
+## nearestPushers — function @experimental
+```
+(bodies: readonly { x: number; y: number; radius: number; strength: number; }[], focus: { x: number; y: number; }): PushValue[]
+```
+
## newMaterialGraph — function @beta
```
(): MaterialGraph
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 8c09b0880..0d740cf5b 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -26,6 +26,7 @@ import { installCoverFade } from '../render/coverFade';
import { installRainShelter } from '../render/rainShelter';
import { installSight } from '../render/sight';
import { installFogOfWar } from '../render/fogOfWar';
+import { installSwayPush } from '../render/swayPush';
import { SystemLabel } from '../ecs/systemLabels';
export class AnimationPlugin implements Plugin {
@@ -62,7 +63,8 @@ export class AnimationPlugin implements Plugin {
const offSight = installSight(app);
// After the sight system, whose walls it casts rays against.
const offFog = installFogOfWar(app);
- const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); offSight(); offFog(); };
+ const offSwayPush = installSwayPush(app);
+ const release = (): void => { offDespawn(); offCoverFade(); offRainShelter(); offSight(); offFog(); offSwayPush(); };
this.despawnCleanups_.set(app, release);
this.latestDespawnCleanup_ = release;
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 8966d3de4..34a1410e3 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 { SwayPusher, nearestPushers, SWAY_PUSHERS, type SwayPusherData, type PushValue } from './render/swayPush';
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';
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index fcaaeb01f..be8f4d6a1 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -148,6 +148,16 @@ const SPRITE_SWAY = `#pragma shader "Sway"
#pragma param u_swaySpeed float default(1.6) range(0,8) ui(slider)
#pragma param u_swayScale float default(260) range(20,2000)
#pragma param u_swayWind float default(1) range(0,4)
+#pragma param u_swayPushStrength float default(0.5) range(0,1) ui(slider)
+// The bodies the plant leans away from, written each frame by the sway-push system (a SwayPusher): x, y where it stands, z how far it reaches, w how hard.
+#pragma param u_swayPush0 vec4 default(0,0,0,0)
+#pragma param u_swayPush1 vec4 default(0,0,0,0)
+#pragma param u_swayPush2 vec4 default(0,0,0,0)
+#pragma param u_swayPush3 vec4 default(0,0,0,0)
+#pragma param u_swayPush4 vec4 default(0,0,0,0)
+#pragma param u_swayPush5 vec4 default(0,0,0,0)
+#pragma param u_swayPush6 vec4 default(0,0,0,0)
+#pragma param u_swayPush7 vec4 default(0,0,0,0)
#pragma fragment
precision mediump float;
@@ -161,13 +171,31 @@ uniform sampler2D u_textures[8];
out vec4 fragColor;
+// How far one body pushes the plant at a point: away from it, fading smoothly to nothing at its reach.
+vec2 swayPush(vec4 body, vec2 at) {
+ vec2 d = at - body.xy;
+ float len = length(d);
+ float f = clamp(1.0 - len / max(body.z, 1e-3), 0.0, 1.0);
+ f = f * f * (3.0 - 2.0 * f) * body.w;
+ return len > 1e-3 ? d / len * f : vec2(0.0);
+}
+
void main() {
// The gust travels across the world, so neighbouring plants lean in turn and not together.
highp float t = u_time.x * u_swaySpeed;
highp float phase = (v_worldPos.x + v_worldPos.y * 0.5) / u_swayScale;
float gust = sin(t + phase) + 0.5 * sin(t * 2.3 + phase * 1.7);
float tip = pow(clamp(v_texCoord.y, 0.0, 1.0), 1.5);
- vec2 uv = vec2(v_texCoord.x - gust * u_swayStrength * u_swayWind * tip, v_texCoord.y);
+ vec2 push = vec2(0.0);
+ push += swayPush(u_swayPush0, v_worldPos);
+ push += swayPush(u_swayPush1, v_worldPos);
+ push += swayPush(u_swayPush2, v_worldPos);
+ push += swayPush(u_swayPush3, v_worldPos);
+ push += swayPush(u_swayPush4, v_worldPos);
+ push += swayPush(u_swayPush5, v_worldPos);
+ push += swayPush(u_swayPush6, v_worldPos);
+ push += swayPush(u_swayPush7, v_worldPos);
+ vec2 uv = vec2(v_texCoord.x - gust * u_swayStrength * u_swayWind * tip - push.x * u_swayPushStrength * tip, v_texCoord.y);
vec4 base = texture(u_textures[0], uv) * v_color * u_tint;
if (uv.x < 0.0 || uv.x > 1.0) base.a = 0.0;
vec3 N = sampleNormal(u_normalMap, uv);
@@ -176,6 +204,15 @@ void main() {
#pragma end
#pragma fragment wgsl
+fn swayPush(body : vec4f, at : vec2f) -> vec2f {
+ let d = at - body.xy;
+ let len = length(d);
+ var f = clamp(1.0 - len / max(body.z, 1e-3), 0.0, 1.0);
+ f = f * f * (3.0 - 2.0 * f) * body.w;
+ if (len > 1e-3) { return d / len * f; }
+ return vec2f(0.0);
+}
+
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
// Taken before any branch: a derivative needs every fragment of its quad.
let duvx = dpdx(v.v_texCoord);
@@ -184,7 +221,16 @@ void main() {
let phase = (v.v_worldPos.x + v.v_worldPos.y * 0.5) / mc.u_swayScale;
let gust = sin(t + phase) + 0.5 * sin(t * 2.3 + phase * 1.7);
let tip = pow(clamp(v.v_texCoord.y, 0.0, 1.0), 1.5);
- let uv = vec2f(v.v_texCoord.x - gust * mc.u_swayStrength * mc.u_swayWind * tip, v.v_texCoord.y);
+ var push = vec2f(0.0);
+ push = push + swayPush(mc.u_swayPush0, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush1, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush2, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush3, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush4, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush5, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush6, v.v_worldPos);
+ push = push + swayPush(mc.u_swayPush7, v.v_worldPos);
+ let uv = vec2f(v.v_texCoord.x - gust * mc.u_swayStrength * mc.u_swayWind * tip - push.x * mc.u_swayPushStrength * tip, v.v_texCoord.y);
var base = textureSampleGrad(t0, s0, uv, duvx, duvy) * v.v_color * mc.u_tint;
if (uv.x < 0.0 || uv.x > 1.0) { base.a = 0.0; }
let N = sampleNormalGrad(u_normalMap, u_normalMap_s, uv, duvx, duvy);
diff --git a/sdk/src/render/swayPush.ts b/sdk/src/render/swayPush.ts
new file mode 100644
index 000000000..9b2530c59
--- /dev/null
+++ b/sdk/src/render/swayPush.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file swayPush.ts
+ * @brief Grass that parts as something walks through it: a `SwayPusher` is a body the plants of a sway material lean away from.
+ *
+ * @details The wind (the `sprite-sway` template) leans a plant by a gust that travels across the world. A body walking through the plants needs the
+ * other half: each plant leaning AWAY from it, more the nearer it stands, and standing up again as it goes. The sway shader takes the bodies
+ * as eight uniforms (where each is, how far it reaches, how hard it pushes) and works the lean out per pixel, so a plant is parted by exactly
+ * the bodies near it and no plant is a component or an entity of its own. This system picks the eight pushers nearest the camera each frame
+ * and writes them to every material that declares them, so a field of grass and a hundred creatures cost eight values.
+ *
+ * More than eight bodies near the camera at once: the farthest go unpushed, which a player sees as grass that did not part for a creature at
+ * the edge of the screen. It runs in play only; in the editor a scene is left as authored.
+ */
+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 { CameraView } from '../camera/Camera';
+import { isEditor, isPlayMode } from '../ecs/env';
+import { Material } from './material';
+
+/** The most bodies the sway shader leans plants away from at once. */
+export const SWAY_PUSHERS = 8;
+
+/** The fields of the `SwayPusher` component. @experimental */
+export interface SwayPusherData {
+ /** How far from the entity the plants lean away, in world units. */
+ radius: number;
+ /** How hard: 1 is the full lean the material's \`u_swayPushStrength\` says, 0 none. */
+ strength: number;
+ /** Off: plants do not lean away from it. */
+ enabled: boolean;
+}
+
+/**
+ * Makes the plants of a `sprite-sway` material lean away from this entity as it walks through them.
+ *
+ * @experimental
+ */
+export const SwayPusher = defineComponent<SwayPusherData>('SwayPusher',
+ { radius: 48, strength: 1, enabled: true },
+ {
+ fields: {
+ radius: { min: 1, step: 1, unit: 'wu', tooltip: 'How far from the entity the plants lean away.' },
+ strength: { min: 0, max: 2, step: 0.01, tooltip: "How hard they lean: 1 is the full lean the material's Push Strength says." },
+ },
+ },
+);
+
+/** One body, as the shader takes it: where it stands, how far it reaches, how hard it pushes. */
+export interface PushValue { x: number; y: number; z: number; w: number }
+
+/** The names of the eight uniforms, in the order the pushers fill them. */
+export const SWAY_PUSH_UNIFORMS: readonly string[] = Array.from({ length: SWAY_PUSHERS }, (_, i) => `u_swayPush${i}`);
+
+/** The eight bodies nearest `focus`, farthest dropped, as the shader's values; an unused one reaches nowhere (radius 0). */
+export function nearestPushers(
+ bodies: readonly { x: number; y: number; radius: number; strength: number }[], focus: { x: number; y: number },
+): PushValue[] {
+ const near = bodies
+ .filter((b) => b.radius > 0 && b.strength > 0)
+ .map((b) => ({ b, d: Math.hypot(b.x - focus.x, b.y - focus.y) }))
+ .sort((a, c) => a.d - c.d)
+ .slice(0, SWAY_PUSHERS);
+ const out: PushValue[] = near.map(({ b }) => ({ x: b.x, y: b.y, z: b.radius, w: b.strength }));
+ while (out.length < SWAY_PUSHERS) out.push({ x: 0, y: 0, z: 0, w: 0 });
+ return out;
+}
+
+/** Installs the system that tells sway materials where the pushers are. Returns the function that puts them back. */
+export function installSwayPush(app: App): () => void {
+ let written = false;
+
+ const clear = (): void => {
+ if (!written) return;
+ written = false;
+ for (const material of Material.materialsDeclaring(SWAY_PUSH_UNIFORMS[0]!)) {
+ for (const name of SWAY_PUSH_UNIFORMS) Material.setUniform(material, name, { x: 0, y: 0, z: 0, w: 0 });
+ }
+ };
+
+ const system = defineSystem(
+ [Query(SwayPusher, Transform)],
+ (pushers: Iterable<[Entity, SwayPusherData, TransformData]>) => {
+ if (isEditor() && !isPlayMode()) { clear(); return; }
+ const bodies: { x: number; y: number; radius: number; strength: number }[] = [];
+ for (const [, pusher, transform] of pushers) {
+ if (!pusher.enabled) continue;
+ bodies.push({ x: transform.worldPosition.x, y: transform.worldPosition.y, radius: pusher.radius, strength: pusher.strength });
+ }
+ if (bodies.length === 0) { clear(); return; }
+ const view = app.hasResource(CameraView) ? app.getResource(CameraView).getWorldBounds() : null;
+ const focus = view ? { x: (view.left + view.right) / 2, y: (view.bottom + view.top) / 2 } : { x: bodies[0]!.x, y: bodies[0]!.y };
+ const values = nearestPushers(bodies, focus);
+ written = true;
+ for (const material of Material.materialsDeclaring(SWAY_PUSH_UNIFORMS[0]!)) {
+ for (let i = 0; i < SWAY_PUSHERS; i++) Material.setUniform(material, SWAY_PUSH_UNIFORMS[i]!, values[i]!);
+ }
+ },
+ { name: 'SwayPushSystem' },
+ );
+ app.addSystemToSchedule(Schedule.PostUpdate, system);
+
+ return () => { clear(); };
+}
diff --git a/sdk/tests/sway-push.test.ts b/sdk/tests/sway-push.test.ts
new file mode 100644
index 000000000..f73827d28
--- /dev/null
+++ b/sdk/tests/sway-push.test.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Plants that part for a body: which eight bodies the sway shader is told of, and that both shader languages lean a plant away from them.
+ */
+import { describe, expect, it } from 'vitest';
+import { SWAY_PUSHERS, SWAY_PUSH_UNIFORMS, nearestPushers } from '../src/render/swayPush';
+import { builtinShaderTemplate } from '../src/render/builtinShaders';
+
+const body = (x: number, y: number, radius = 40, strength = 1) => ({ x, y, radius, strength });
+
+describe('the bodies plants lean away from', () => {
+ it('are the eight nearest the camera, nearest first, the rest left out', () => {
+ const bodies = Array.from({ length: 12 }, (_, i) => body(100 * (i + 1), 0));
+ const values = nearestPushers(bodies, { x: 0, y: 0 });
+ expect(values).toHaveLength(SWAY_PUSHERS);
+ expect(values.map((v) => v.x)).toEqual([100, 200, 300, 400, 500, 600, 700, 800]);
+ expect(values[0]).toEqual({ x: 100, y: 0, z: 40, w: 1 });
+ });
+
+ it('fill the slots they do not use with a body that reaches nowhere', () => {
+ const values = nearestPushers([body(5, 6, 30, 0.5)], { x: 0, y: 0 });
+ expect(values[0]).toEqual({ x: 5, y: 6, z: 30, w: 0.5 });
+ for (const v of values.slice(1)) expect(v).toEqual({ x: 0, y: 0, z: 0, w: 0 });
+ });
+
+ it('leave out a body with no reach or no strength', () => {
+ const values = nearestPushers([body(1, 1, 0), body(2, 2, 40, 0), body(3, 3)], { x: 0, y: 0 });
+ expect(values[0]!.x).toBe(3);
+ expect(values[1]!.z).toBe(0);
+ });
+});
+
+describe('the sway shader', () => {
+ const source = builtinShaderTemplate('sprite-sway')!.source;
+
+ it('declares the eight bodies, and leans a plant away from each in both languages', () => {
+ for (const name of SWAY_PUSH_UNIFORMS) expect(source).toContain(`#pragma param ${name} vec4`);
+ expect(source).toContain('#pragma param u_swayPushStrength');
+ expect((source.match(/push \+= swayPush\(u_swayPush\d, v_worldPos\);/g) ?? []).length).toBe(8);
+ expect((source.match(/push = push \+ swayPush\(mc\.u_swayPush\d, v\.v_worldPos\);/g) ?? []).length).toBe(8);
+ // Away from the body is the way the gust already leans a plant, and the tip moves, not the foot.
+ expect(source).toContain('- push.x * u_swayPushStrength * tip');
+ expect(source).toContain('- push.x * mc.u_swayPushStrength * tip');
+ });
+});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 2d8ec8897..cb417395c 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'],
+ SwayPusher: ['owed', 'only the rainforest-2d probe, kept out of the examples, places one; it arrives with the top-down example CoverFade 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'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index a726f3b42..8e221d290 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'],
+ 'SwayPusher.radius': ['owed', 'how far from the entity plants lean away is not outlined in the viewport yet'],
+ 'Text.boxWidth': ['owed', 'the rectangle a world label wraps and aligns in is not outlined in the viewport yet'],
+ 'Text.boxHeight': ['owed', 'the rectangle a world label wraps and aligns in is not outlined in the viewport yet'],
'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'],