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(particle): add Force Field module

yhh9dd13ce409b9
diff --git a/desktop/public/scenes/particle-forcefield.esscene b/desktop/public/scenes/particle-forcefield.esscene
new file mode 100644
index 000000000..a69d72dbe
--- /dev/null
+++ b/desktop/public/scenes/particle-forcefield.esscene
@@ -0,0 +1,64 @@
+{
+ "version": "1.0",
+ "name": "ParticleForceField",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Vortex",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ { "type": "ParticleForceField", "data": {
+ "type": 2,
+ "strength": 520,
+ "radius": 340,
+ "falloff": true
+ }}
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Sparks",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ { "type": "ParticleEmitter", "data": {
+ "rate": 90,
+ "maxParticles": 500,
+ "lifetimeMin": 2.4,
+ "lifetimeMax": 3.6,
+ "shape": 1,
+ "shapeRadius": 40,
+ "speedMin": 30,
+ "speedMax": 90,
+ "startSizeMin": 5,
+ "startSizeMax": 9,
+ "endSizeMin": 2,
+ "endSizeMax": 3,
+ "sizeEasing": 2,
+ "startColor": { "r": 0.7, "g": 0.85, "b": 1, "a": 1 },
+ "endColor": { "r": 0.8, "g": 0.4, "b": 1, "a": 0 },
+ "simulationSpace": 0,
+ "looping": true,
+ "playOnStart": true,
+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0"
+ }}
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/particle-forcefield.textures.json b/desktop/public/scenes/particle-forcefield.textures.json
new file mode 100644
index 000000000..0acb647eb
--- /dev/null
+++ b/desktop/public/scenes/particle-forcefield.textures.json
@@ -0,0 +1,3 @@
+{
+ "24cb4e0f-7c75-4df4-9a4d-58480ee405c0": "/scenes/particle-demo/textures/particle.png"
+}
diff --git a/docs/astro/src/content/docs/guides/particle.mdx b/docs/astro/src/content/docs/guides/particle.mdx
index ea8f7bbaa..8252ce9f8 100644
--- a/docs/astro/src/content/docs/guides/particle.mdx
+++ b/docs/astro/src/content/docs/guides/particle.mdx
@@ -379,6 +379,43 @@ history per particle (bounded by `trailPoints`) plus ribbon geometry each frame.
`trailPoints` modest (`6`–`8` is plenty) and lower `maxParticles` for heavy trailed
effects.
+## Force fields
+
+Where the [Noise](#noise--turbulence) module is a per-emitter turbulence baked into
+one emitter, a **force field** is an *external* influence you place in the scene: it's
+its own entity with a `ParticleForceField` component, and it acts on the world-space
+particles of **every** emitter within range. Wind gusts, black holes, whirlpools,
+pockets of still air — drop one in and the whole scene's particles respond.
+
+```typescript
+import { ParticleForceField, ForceFieldType } from 'esengine';
+
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(ParticleForceField, {
+ type: ForceFieldType.Vortex,
+ strength: 450, // acceleration (px/s²); negative flips a Point field to a repeller
+ radius: 320, // 0 = affects the whole scene; > 0 = only particles within range
+ falloff: true, // fade the force to 0 at the radius edge
+ });
+```
+
+| Type | Effect |
+|---|---|
+| `Directional` | A constant push along `direction` — wind, updrafts, a current. |
+| `Point` | Pull toward the field (`strength > 0`) or push away (`strength < 0`) — gravity wells, explosions. |
+| `Vortex` | Swirl tangentially around the field — whirlpools, tornadoes, galaxies. |
+| `Drag` | Damp velocity inside the zone — a pocket of still air or water that slows particles. |
+
+Fields are pure-CPU: the sim gathers the active ones each frame and folds them into the
+same velocity integration as gravity, so there is no new subsystem. A `Directional`
+field uses its `direction`; `Point`/`Vortex`/`Drag` derive their direction from the
+field→particle vector and ignore it.
+
+Two caveats: fields act on **world-space** particles only (a `Local` emitter's particles
+move with their emitter and ignore fields), and `strength: 0` or `enabled: false` skips
+a field entirely.
+
## Simulation space
| Value | Particles follow the emitter? | Use for |
diff --git a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx b/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
index f31025ecf..d3a47ad81 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/particle.mdx
@@ -351,6 +351,38 @@ CPU 上生成,走和 `TrailRenderer` 相同的三角带 batch 路径 —— 无
拖尾是可选项,因为它比普通粒子贵:每粒子一小段位置历史(受 `trailPoints` 限制)+ 每帧
ribbon 几何。`trailPoints` 保持适中(`6`–`8` 足够),重拖尾特效请调低 `maxParticles`。
+## 力场
+
+[噪声](#噪声与湍流)模块是烘进单个发射器的自带湍流,而**力场**是你放进场景的*外部*影响:
+它是自己的实体、带 `ParticleForceField` 组件,作用于范围内**每个**发射器的世界空间粒子。
+阵风、黑洞、漩涡、静止的空气团 —— 放一个进去,整个场景的粒子都会响应。
+
+```typescript
+import { ParticleForceField, ForceFieldType } from 'esengine';
+
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(ParticleForceField, {
+ type: ForceFieldType.Vortex,
+ strength: 450, // 加速度(px/s²);Point 场取负值即从吸引变排斥
+ radius: 320, // 0 = 影响整个场景;> 0 = 只影响范围内的粒子
+ falloff: true, // 在半径边缘把力衰减到 0
+ });
+```
+
+| 类型 | 效果 |
+|---|---|
+| `Directional` | 沿 `direction` 的恒定推力 —— 风、上升气流、水流。 |
+| `Point` | 朝力场吸引(`strength > 0`)或排斥(`strength < 0`)—— 引力井、爆炸。 |
+| `Vortex` | 绕力场切向旋绕 —— 漩涡、龙卷、星系。 |
+| `Drag` | 在区域内阻尼速度 —— 减速粒子的静止空气/水团。 |
+
+力场是纯 CPU:模拟每帧收集活跃力场,和重力一样折进同一套速度积分,无新子系统。`Directional`
+用它的 `direction`;`Point`/`Vortex`/`Drag` 从力场→粒子向量推导方向,忽略它。
+
+两个注意:力场只作用于**世界空间**粒子(`Local` 发射器的粒子随发射器移动、忽略力场);
+`strength: 0` 或 `enabled: false` 直接跳过该力场。
+
## 模拟空间
| 取值 | 粒子跟随发射器吗? | 用于 |
diff --git a/examples/particle-demo/README.md b/examples/particle-demo/README.md
index 71fc8b2af..24c61bf87 100644
--- a/examples/particle-demo/README.md
+++ b/examples/particle-demo/README.md
@@ -1,6 +1,6 @@
# Particle Effects
-A gallery of the engine's `ParticleEmitter`. Page through nine composed effects
+A gallery of the engine's `ParticleEmitter`. Page through ten composed effects
with on-screen buttons, and click empty space to throw fireworks.
## Controls
@@ -18,9 +18,10 @@ with on-screen buttons, and click empty space to throw fireworks.
`Snowfall` (a wide, slow drift) · `Sparkles` (a twinkling field) ·
`Bursting Rockets` (**sub-emitter** — rockets that explode into a shell burst on
death) · `Turbulent Smoke` (curl-**noise** flow — smoke that rolls, embers that
-weave) · `Comet Trails` (per-particle **trail** — sparks that drag fading ribbons).
-Each mixes shape, velocity, colour/size-over-life, gravity, spin, blend mode, and
-now noise, sub-emitters and trails — see `src/config.ts`.
+weave) · `Comet Trails` (per-particle **trail** — sparks that drag fading ribbons) ·
+`Vortex Galaxy` (**force fields** — a vortex + point pull swirl sparks into a spiral).
+Each mixes shape, velocity, colour/size-over-life, gravity, spin, blend mode, and now
+noise, sub-emitters, trails and force fields — see `src/config.ts`.
## How it works
@@ -55,7 +56,7 @@ assets/
textures/particle.png # soft radial particle sprite
src/
main.ts # registers the systems
- config.ts # the nine showcases, the firework, spawnShowcase()
+ config.ts # the ten showcases, the firework, spawnShowcase()
components.ts # tags (buttons, TexHolder, ShowcaseEmitter) + Burst
state.ts # the current showcase index
systems/
diff --git a/examples/particle-demo/src/config.ts b/examples/particle-demo/src/config.ts
index f694d7d76..471a54716 100644
--- a/examples/particle-demo/src/config.ts
+++ b/examples/particle-demo/src/config.ts
@@ -1,8 +1,8 @@
import {
- EmitterShape, BlendMode, ParticleEasing, SubEmitterTrigger,
- Transform, ParticleEmitter,
+ EmitterShape, BlendMode, ParticleEasing, SubEmitterTrigger, ForceFieldType,
+ Transform, ParticleEmitter, ParticleForceField,
} from 'esengine';
-import type { ParticleEmitterData, CommandsInstance } from 'esengine';
+import type { ParticleEmitterData, ParticleForceFieldData, CommandsInstance } from 'esengine';
import { ShowcaseEmitter } from './components';
// A showcase is a named set of emitters placed relative to the screen center.
@@ -16,12 +16,20 @@ export interface EmitterSpec {
// particles fire the child's burst on the configured trigger).
sub?: boolean;
}
+// A force field placed in the scene, affecting every emitter's world-space particles.
+export interface FieldSpec {
+ x: number;
+ y: number;
+ data: Partial<ParticleForceFieldData>;
+}
export interface Showcase {
name: string;
emitters: EmitterSpec[];
// Optional sub-emitter template: spawned once, its entity injected as the
// `subEmitter` of every emitter flagged `sub: true`.
child?: EmitterSpec;
+ // Optional force fields placed in the scene alongside the emitters.
+ fields?: FieldSpec[];
}
export const SHOWCASES: Showcase[] = [
@@ -181,6 +189,23 @@ export const SHOWCASES: Showcase[] = [
trailEnabled: true, trailWidth: 12, trailPoints: 8, trailMinDistance: 5 } },
],
},
+ {
+ // Shows off Force Fields: a Vortex swirls the sparks into a spiral while a
+ // gentle Point pull keeps them from flinging out of frame.
+ name: 'Vortex Galaxy',
+ fields: [
+ { x: 0, y: 0, data: { type: ForceFieldType.Vortex, strength: 520, radius: 340, falloff: true } },
+ { x: 0, y: 0, data: { type: ForceFieldType.Point, strength: 55, radius: 340, falloff: true } },
+ ],
+ emitters: [
+ { x: 0, y: 0, data: {
+ rate: 90, maxParticles: 500, lifetimeMin: 2.4, lifetimeMax: 3.6,
+ shape: EmitterShape.Circle, shapeRadius: 40, speedMin: 30, speedMax: 90,
+ startSizeMin: 4, startSizeMax: 8, endSizeMin: 1, endSizeMax: 2,
+ sizeEasing: ParticleEasing.EaseOut,
+ startColor: { r: 0.7, g: 0.85, b: 1, a: 1 }, endColor: { r: 0.8, g: 0.4, b: 1, a: 0 } } },
+ ],
+ },
];
export const SHOWCASE_COUNT = SHOWCASES.length;
@@ -217,6 +242,16 @@ export function spawnShowcase(cmds: CommandsInstance, index: number, texture: nu
.id();
}
+ // Scene force fields (tagged for the same group despawn on switch).
+ if (showcase.fields) {
+ for (const f of showcase.fields) {
+ cmds.spawn()
+ .insert(Transform, { position: { x: f.x, y: f.y, z: 0 } })
+ .insert(ParticleForceField, { ...f.data })
+ .insert(ShowcaseEmitter, {});
+ }
+ }
+
for (const emitter of showcase.emitters) {
const data: Partial<ParticleEmitterData> = { layer: 5, texture, ...emitter.data };
if (emitter.sub && childId) data.subEmitter = childId;
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index 422152fa5..2c110744d 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding } from './wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '12610f4b7cc99ebc';
+export const ABI_LAYOUT_HASH = '1ea8bcc5e5a72cc7';
export interface AssetFieldMeta {
field: string;
@@ -405,6 +405,27 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
trailMinDistance: { min: 0, category: "Trail" },
},
},
+ ParticleForceField: {
+ defaults: {
+ type: 0,
+ strength: 200,
+ radius: 0,
+ direction: { x: 1, y: 0 },
+ falloff: true,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ type: { enum: [{ label: 'Directional', value: 0 }, { label: 'Point', value: 1 }, { label: 'Vortex', value: 2 }, { label: 'Drag', value: 3 }], category: "Field" },
+ strength: { category: "Field" },
+ radius: { min: 0, category: "Field" },
+ direction: { category: "Field" },
+ falloff: { category: "Field" },
+ },
+ },
RigidBody: {
defaults: {
bodyType: 2,
@@ -900,6 +921,15 @@ export interface ParticleEmitterData {
trailMinDistance: number;
}
+export interface ParticleForceFieldData {
+ type: number;
+ strength: number;
+ radius: number;
+ direction: Vec2;
+ falloff: boolean;
+ enabled: boolean;
+}
+
export interface RigidBodyData {
bodyType: number;
gravityScale: number;
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 6b14458c1..8dd24dad9 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -15,7 +15,7 @@ import { COMPONENT_META, type AssetFieldMeta, type SpineFieldMeta } from './comp
import type {
TransformData, SpriteData, ShapeRendererData, Light2DData, ShadowCaster2DData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData,
- TilemapLayerData, BitmapTextData, TrailRendererData,
+ TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData,
CameraData as CameraDataCpp, ParticleEmitterData as ParticleEmitterDataCpp,
Mesh2DData as Mesh2DDataCpp,
} from './component.generated';
@@ -24,7 +24,7 @@ import type {
// C++ enum and the editor dropdowns derive from the same values. ScaleMode's
// canonical values come from CanvasScaleMode (only its Cocos-compat aliases
// ShowAll/NoBorder are TS-side).
-import { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, Light2DType, CanvasScaleMode, ShapeType, ParticleEasing } from './wasm.generated';
+import { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, Light2DType, CanvasScaleMode, ShapeType, ParticleEasing } from './wasm.generated';
import { BlendMode } from './blend';
import { getDefaultContext } from './context';
import type {
@@ -560,7 +560,7 @@ export function ensureBuiltinComponentsRegistered(): void {
// EmitterShape, SimulationSpace, Light2DType and ShapeType are re-exported from the
// generated module; their values and the editor dropdowns built from them now have
// one source.
-export { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, Light2DType, ShapeType };
+export { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, Light2DType, ShapeType };
// Canonical values single-sourced from the C++ CanvasScaleMode enum (generated);
// ShowAll/NoBorder are Cocos-compat aliases with no C++ member.
@@ -586,7 +586,7 @@ export type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];
export type {
TransformData, SpriteData, ShapeRendererData, Light2DData, ShadowCaster2DData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData,
- TilemapLayerData, BitmapTextData, TrailRendererData,
+ TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData,
};
export type LocalTransformData = TransformData;
@@ -736,6 +736,12 @@ export const TrailRenderer = defineBuiltin<TrailRendererData>('TrailRenderer',
metaDefaults<TrailRendererData>('TrailRenderer')
);
+// Particle force field. A scene-placed zone (wind, attractor, vortex, drag) that the
+// C++ ParticleSystem folds into every nearby world-space particle's integration.
+export const ParticleForceField = defineBuiltin<ParticleForceFieldData>('ParticleForceField',
+ metaDefaults<ParticleForceFieldData>('ParticleForceField')
+);
+
export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',
metaDefaults<TilemapLayerData>('TilemapLayer'),
{
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 84ed4a989..4f6841d1f 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -134,6 +134,9 @@ export {
SubEmitterTrigger,
ParticleEasing,
type ParticleEmitterData,
+ ParticleForceField,
+ ForceFieldType,
+ type ParticleForceFieldData,
PostProcessVolume,
type PostProcessVolumeData,
} from './component';
diff --git a/sdk/src/ecs/ptrAccessors.generated.ts b/sdk/src/ecs/ptrAccessors.generated.ts
index ded20d8f0..de1c0e21e 100644
--- a/sdk/src/ecs/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/ptrAccessors.generated.ts
@@ -753,6 +753,50 @@ export function createParticleEmitterData(): ParticleEmitterPtrData {
};
}
+export interface ParticleForceFieldPtrData {
+ type: number;
+ strength: number;
+ radius: number;
+ direction: Vec2;
+ falloff: boolean;
+ enabled: boolean;
+}
+
+export function fillParticleForceField(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: ParticleForceFieldPtrData,
+): void {
+ out.type = u32[ptr >> 2] | 0;
+ out.strength = f32[(ptr + 4) >> 2];
+ out.radius = f32[(ptr + 8) >> 2];
+ const direction_ = out.direction; direction_.x = f32[(ptr + 12) >> 2]; direction_.y = f32[((ptr + 12) >> 2) + 1];
+ out.falloff = u8[ptr + 20] !== 0;
+ out.enabled = u8[ptr + 21] !== 0;
+}
+
+export function writeParticleForceField(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: ParticleForceFieldPtrData,
+): void {
+ u32[ptr >> 2] = data.type | 0;
+ f32[(ptr + 4) >> 2] = data.strength;
+ f32[(ptr + 8) >> 2] = data.radius;
+ f32[(ptr + 12) >> 2] = data.direction.x; f32[((ptr + 12) >> 2) + 1] = data.direction.y;
+ u8[ptr + 20] = data.falloff ? 1 : 0;
+ u8[ptr + 21] = data.enabled ? 1 : 0;
+}
+
+export function createParticleForceFieldData(): ParticleForceFieldPtrData {
+ return {
+ type: 0,
+ strength: 0,
+ radius: 0,
+ direction: { x: 0, y: 0 },
+ falloff: false,
+ enabled: false,
+ };
+}
+
export interface RigidBodyPtrData {
bodyType: number;
gravityScale: number;
@@ -1479,6 +1523,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
Light2D: { fill: fillLight2D, write: writeLight2D, create: createLight2DData },
Mesh2D: { fill: fillMesh2D, write: writeMesh2D, create: createMesh2DData },
ParticleEmitter: { fill: fillParticleEmitter, write: writeParticleEmitter, create: createParticleEmitterData },
+ ParticleForceField: { fill: fillParticleForceField, write: writeParticleForceField, create: createParticleForceFieldData },
RigidBody: { fill: fillRigidBody, write: writeRigidBody, create: createRigidBodyData },
SegmentCollider: { fill: fillSegmentCollider, write: writeSegmentCollider, create: createSegmentColliderData },
ShadowCaster2D: { fill: fillShadowCaster2D, write: writeShadowCaster2D, create: createShadowCaster2DData },
diff --git a/sdk/src/ptrLayouts.generated.ts b/sdk/src/ptrLayouts.generated.ts
index c4a39235a..d7738fb3e 100644
--- a/sdk/src/ptrLayouts.generated.ts
+++ b/sdk/src/ptrLayouts.generated.ts
@@ -204,6 +204,17 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'trailMinDistance', type: 'f32', offset: 236 },
],
},
+ ParticleForceField: {
+ ptrFn: 'getParticleForceFieldPtr',
+ fields: [
+ { name: 'type', type: 'i32', offset: 0 },
+ { name: 'strength', type: 'f32', offset: 4 },
+ { name: 'radius', type: 'f32', offset: 8 },
+ { name: 'direction', type: 'vec2', offset: 12 },
+ { name: 'falloff', type: 'bool', offset: 20 },
+ { name: 'enabled', type: 'bool', offset: 21 },
+ ],
+ },
RigidBody: {
ptrFn: 'getRigidBodyPtr',
fields: [
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 700fe69fe..92657878b 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -87,6 +87,13 @@ export enum FlexWrap {
Wrap = 1,
}
+export enum ForceFieldType {
+ Directional = 0,
+ Point = 1,
+ Vortex = 2,
+ Drag = 3,
+}
+
export enum JustifyContent {
Start = 0,
Center = 1,
@@ -369,6 +376,15 @@ export interface ParticleEmitter {
trailMinDistance: number;
}
+export interface ParticleForceField {
+ type: number;
+ strength: number;
+ radius: number;
+ direction: Vec2;
+ falloff: boolean;
+ enabled: boolean;
+}
+
export interface RigidBody {
bodyType: number;
gravityScale: number;
@@ -596,6 +612,10 @@ export interface Registry {
getParticleEmitter(entity: Entity): ParticleEmitter;
addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
removeParticleEmitter(entity: Entity): void;
+ hasParticleForceField(entity: Entity): boolean;
+ getParticleForceField(entity: Entity): ParticleForceField;
+ addParticleForceField(entity: Entity, component: ParticleForceField): void;
+ removeParticleForceField(entity: Entity): void;
hasRigidBody(entity: Entity): boolean;
getRigidBody(entity: Entity): RigidBody;
addRigidBody(entity: Entity, component: RigidBody): void;
@@ -679,6 +699,7 @@ export interface ESEngineModule {
Mesh2D: new () => Mesh2D;
Parent: new () => Parent;
ParticleEmitter: new () => ParticleEmitter;
+ ParticleForceField: new () => ParticleForceField;
RigidBody: new () => RigidBody;
SegmentCollider: new () => SegmentCollider;
ShadowCaster2D: new () => ShadowCaster2D;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index dee50f499..426413107 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -505,6 +505,42 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"min": 0,
},
},
+ "ParticleForceField": {
+ "direction": {
+ "category": "Field",
+ },
+ "falloff": {
+ "category": "Field",
+ },
+ "radius": {
+ "category": "Field",
+ "min": 0,
+ },
+ "strength": {
+ "category": "Field",
+ },
+ "type": {
+ "category": "Field",
+ "enum": [
+ {
+ "label": "Directional",
+ "value": 0,
+ },
+ {
+ "label": "Point",
+ "value": 1,
+ },
+ {
+ "label": "Vortex",
+ "value": 2,
+ },
+ {
+ "label": "Drag",
+ "value": 3,
+ },
+ ],
+ },
+ },
"ShadowCaster2D": {
"size": {
"min": 0,
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 87e5562b4..6896ca2cd 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 368b777854ab416e
+ * @schema_hash b84b827b8b13d659
*/
-#define ES_EDITOR_API_SCHEMA_HASH "368b777854ab416e"
+#define ES_EDITOR_API_SCHEMA_HASH "b84b827b8b13d659"
#include <emscripten/bind.h>
#include <string>
@@ -21,6 +21,7 @@
#include "../ecs/components/Light2D.hpp"
#include "../ecs/components/Mesh2D.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
+#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/RigidBody.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
@@ -66,6 +67,7 @@ std::vector<std::string> editor_getComponentNames() {
"Mesh2D",
"Parent",
"ParticleEmitter",
+ "ParticleForceField",
"RigidBody",
"SegmentCollider",
"ShadowCaster2D",
@@ -295,6 +297,16 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"trailPoints","type":"int","group":"ParticleEmitter"},
{"key":"trailMinDistance","type":"float","group":"ParticleEmitter"}
])JSON";
+ } else if (name == "ParticleForceField") {
+ return R"JSON([
+ {"key":"type","type":"int","group":"ParticleForceField"},
+ {"key":"strength","type":"float","group":"ParticleForceField"},
+ {"key":"radius","type":"float","group":"ParticleForceField"},
+ {"key":"direction.x","type":"float","group":"ParticleForceField"},
+ {"key":"direction.y","type":"float","group":"ParticleForceField"},
+ {"key":"falloff","type":"bool","group":"ParticleForceField"},
+ {"key":"enabled","type":"bool","group":"ParticleForceField"}
+ ])JSON";
} else if (name == "RigidBody") {
return R"JSON([
{"key":"bodyType","type":"enum","group":"RigidBody","values":["Static","Kinematic","Dynamic"]},
@@ -575,6 +587,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) reg.emplace<esengine::ecs::ParticleEmitter>(entity);
return true;
+ } else if (name == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) reg.emplace<esengine::ecs::ParticleForceField>(entity);
+ return true;
} else if (name == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) reg.emplace<esengine::ecs::RigidBody>(entity);
return true;
@@ -650,6 +665,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Parent>(entity)) { reg.remove<esengine::ecs::Parent>(entity); return true; }
} else if (name == "ParticleEmitter") {
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) { reg.remove<esengine::ecs::ParticleEmitter>(entity); return true; }
+ } else if (name == "ParticleForceField") {
+ if (reg.has<esengine::ecs::ParticleForceField>(entity)) { reg.remove<esengine::ecs::ParticleForceField>(entity); return true; }
} else if (name == "RigidBody") {
if (reg.has<esengine::ecs::RigidBody>(entity)) { reg.remove<esengine::ecs::RigidBody>(entity); return true; }
} else if (name == "SegmentCollider") {
@@ -698,6 +715,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "Mesh2D") return reg.has<esengine::ecs::Mesh2D>(entity);
if (name == "Parent") return reg.has<esengine::ecs::Parent>(entity);
if (name == "ParticleEmitter") return reg.has<esengine::ecs::ParticleEmitter>(entity);
+ if (name == "ParticleForceField") return reg.has<esengine::ecs::ParticleForceField>(entity);
if (name == "RigidBody") return reg.has<esengine::ecs::RigidBody>(entity);
if (name == "SegmentCollider") return reg.has<esengine::ecs::SegmentCollider>(entity);
if (name == "ShadowCaster2D") return reg.has<esengine::ecs::ShadowCaster2D>(entity);
@@ -734,6 +752,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::Mesh2D>(entity)) result.push_back("Mesh2D");
if (reg.has<esengine::ecs::Parent>(entity)) result.push_back("Parent");
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) result.push_back("ParticleEmitter");
+ if (reg.has<esengine::ecs::ParticleForceField>(entity)) result.push_back("ParticleForceField");
if (reg.has<esengine::ecs::RigidBody>(entity)) result.push_back("RigidBody");
if (reg.has<esengine::ecs::SegmentCollider>(entity)) result.push_back("SegmentCollider");
if (reg.has<esengine::ecs::ShadowCaster2D>(entity)) result.push_back("ShadowCaster2D");
@@ -913,6 +932,15 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "trailMinDistance") { c.trailMinDistance = value; }
else { return false; }
return true;
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "strength") { c.strength = value; }
+ else if (field == "radius") { c.radius = value; }
+ else if (field == "direction.x") { c.direction.x = value; }
+ else if (field == "direction.y") { c.direction.y = value; }
+ else { return false; }
+ return true;
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return false;
auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1262,6 +1290,13 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "subEmitterInheritVelocity") { return c.subEmitterInheritVelocity; }
else if (field == "trailWidth") { return c.trailWidth; }
else if (field == "trailMinDistance") { return c.trailMinDistance; }
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "strength") { return c.strength; }
+ else if (field == "radius") { return c.radius; }
+ else if (field == "direction.x") { return c.direction.x; }
+ else if (field == "direction.y") { return c.direction.y; }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1532,6 +1567,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "trailPoints") { c.trailPoints = static_cast<i32>(value); }
else { return false; }
return true;
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "type") { c.type = static_cast<i32>(value); }
+ else { return false; }
+ return true;
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return false;
auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1693,6 +1734,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
else if (field == "subEmitterTrigger") { return static_cast<i32>(c.subEmitterTrigger); }
else if (field == "subEmitter") { return static_cast<i32>(c.subEmitter); }
else if (field == "trailPoints") { return static_cast<i32>(c.trailPoints); }
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "type") { return static_cast<i32>(c.type); }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1827,6 +1872,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "trailEnabled") { c.trailEnabled = value; }
else { return false; }
return true;
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "falloff") { c.falloff = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return false;
auto& c = reg.get<esengine::ecs::RigidBody>(entity);
@@ -1963,6 +2015,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "spriteLoop") { return c.spriteLoop; }
else if (field == "enabled") { return c.enabled; }
else if (field == "trailEnabled") { return c.trailEnabled; }
+ } else if (comp == "ParticleForceField") {
+ if (!reg.has<esengine::ecs::ParticleForceField>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::ParticleForceField>(entity);
+ if (field == "falloff") { return c.falloff; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) return false;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 52c3ecc02..c5f575611 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -21,6 +21,7 @@
#include "../ecs/components/Light2D.hpp"
#include "../ecs/components/Mesh2D.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
+#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/RigidBody.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
@@ -140,6 +141,12 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
.value("NoWrap", esengine::ecs::FlexWrap::NoWrap)
.value("Wrap", esengine::ecs::FlexWrap::Wrap);
+ enum_<esengine::ecs::ForceFieldType>("ForceFieldType")
+ .value("Directional", esengine::ecs::ForceFieldType::Directional)
+ .value("Point", esengine::ecs::ForceFieldType::Point)
+ .value("Vortex", esengine::ecs::ForceFieldType::Vortex)
+ .value("Drag", esengine::ecs::ForceFieldType::Drag);
+
enum_<esengine::ecs::JustifyContent>("JustifyContent")
.value("Start", esengine::ecs::JustifyContent::Start)
.value("Center", esengine::ecs::JustifyContent::Center)
@@ -1124,6 +1131,14 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("trailPoints", &ParticleEmitterJS::trailPoints)
.field("trailMinDistance", &ParticleEmitterJS::trailMinDistance);
+ value_object<esengine::ecs::ParticleForceField>("ParticleForceField")
+ .field("type", &esengine::ecs::ParticleForceField::type)
+ .field("strength", &esengine::ecs::ParticleForceField::strength)
+ .field("radius", &esengine::ecs::ParticleForceField::radius)
+ .field("direction", &esengine::ecs::ParticleForceField::direction)
+ .field("falloff", &esengine::ecs::ParticleForceField::falloff)
+ .field("enabled", &esengine::ecs::ParticleForceField::enabled);
+
value_object<RigidBodyJS>("RigidBody")
.field("bodyType", &RigidBodyJS::bodyType)
.field("gravityScale", &RigidBodyJS::gravityScale)
@@ -1563,6 +1578,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::ParticleEmitter>(entity);
}))
+ // ParticleForceField
+ .function("hasParticleForceField", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::ParticleForceField>(static_cast<Entity>(e));
+ }))
+ .function("getParticleForceField", optional_override([](Registry& r, u32 e) -> esengine::ecs::ParticleForceField& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::ParticleForceField s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::ParticleForceField>(entity)) return s_dummy;
+ return r.get<esengine::ecs::ParticleForceField>(entity);
+ }), allow_raw_pointers())
+ .function("addParticleForceField", optional_override([](Registry& r, u32 e, const esengine::ecs::ParticleForceField& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::ParticleForceField>(entity, c);
+ }))
+ .function("removeParticleForceField", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::ParticleForceField>(entity)) return;
+ r.remove<esengine::ecs::ParticleForceField>(entity);
+ }))
+
// RigidBody
.function("hasRigidBody", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::RigidBody>(static_cast<Entity>(e));
@@ -1881,6 +1917,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("Mesh2D")));
arr.set(i++, val(std::string("Parent")));
arr.set(i++, val(std::string("ParticleEmitter")));
+ arr.set(i++, val(std::string("ParticleForceField")));
arr.set(i++, val(std::string("RigidBody")));
arr.set(i++, val(std::string("SegmentCollider")));
arr.set(i++, val(std::string("ShadowCaster2D")));
@@ -2040,6 +2077,12 @@ static_assert(offsetof(esengine::ecs::ParticleEmitter, trailEnabled) == 224, "AB
static_assert(offsetof(esengine::ecs::ParticleEmitter, trailWidth) == 228, "ABI offset drift: esengine::ecs::ParticleEmitter.trailWidth (EHT expected 228)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, trailPoints) == 232, "ABI offset drift: esengine::ecs::ParticleEmitter.trailPoints (EHT expected 232)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, trailMinDistance) == 236, "ABI offset drift: esengine::ecs::ParticleEmitter.trailMinDistance (EHT expected 236)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, type) == 0, "ABI offset drift: esengine::ecs::ParticleForceField.type (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, strength) == 4, "ABI offset drift: esengine::ecs::ParticleForceField.strength (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, radius) == 8, "ABI offset drift: esengine::ecs::ParticleForceField.radius (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, direction) == 12, "ABI offset drift: esengine::ecs::ParticleForceField.direction (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, falloff) == 20, "ABI offset drift: esengine::ecs::ParticleForceField.falloff (EHT expected 20)");
+static_assert(offsetof(esengine::ecs::ParticleForceField, enabled) == 21, "ABI offset drift: esengine::ecs::ParticleForceField.enabled (EHT expected 21)");
static_assert(offsetof(esengine::ecs::RigidBody, bodyType) == 0, "ABI offset drift: esengine::ecs::RigidBody.bodyType (EHT expected 0)");
static_assert(offsetof(esengine::ecs::RigidBody, gravityScale) == 4, "ABI offset drift: esengine::ecs::RigidBody.gravityScale (EHT expected 4)");
static_assert(offsetof(esengine::ecs::RigidBody, linearDamping) == 8, "ABI offset drift: esengine::ecs::RigidBody.linearDamping (EHT expected 8)");
@@ -2153,7 +2196,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "12610f4b7cc99ebc";
+static const char* kEsAbiLayoutHash = "1ea8bcc5e5a72cc7";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/ParticleForceField.hpp b/src/esengine/ecs/components/ParticleForceField.hpp
new file mode 100644
index 000000000..b968634bb
--- /dev/null
+++ b/src/esengine/ecs/components/ParticleForceField.hpp
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ParticleForceField.hpp
+ * @brief A scene-placed force zone that pushes every world-space particle near it.
+ * @details Where the emitter's Noise module is a per-emitter turbulence, a force
+ * field is an *external* influence: drop one in the scene (wind gust, black
+ * hole, whirlpool, drag pocket) and it acts on the particles of every
+ * emitter within range. Pure CPU — the ParticleSystem gathers the active
+ * fields each frame and folds them into the same velocity integration as
+ * gravity, so there is no new subsystem and nothing platform-specific.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../math/Math.hpp"
+
+namespace esengine::ecs {
+
+// Directional: a constant push along `direction` (wind). Point: pull toward
+// (strength > 0) or push from (strength < 0) the field. Vortex: swirl tangentially
+// around the field. Drag: damp velocity inside the zone (still air / water pocket).
+// NOTE: keep these descriptions here, not as inline `//` comments on the values —
+// the EHT enum parser treats trailing words as extra enum members.
+ES_ENUM()
+enum class ForceFieldType : i32 {
+ Directional = 0,
+ Point = 1,
+ Vortex = 2,
+ Drag = 3,
+};
+
+ES_COMPONENT()
+struct ParticleForceField {
+ ES_PROPERTY(enum=ForceFieldType, category=Field)
+ i32 type{static_cast<i32>(ForceFieldType::Directional)};
+
+ // Directional/Point/Vortex: acceleration magnitude (px/s²). Drag: damping rate
+ // per second. Negative flips a Point field from attractor to repeller.
+ ES_PROPERTY(category=Field)
+ f32 strength{200.0f};
+
+ // 0 = unbounded (affects the whole scene). > 0 = only particles within this world
+ // radius of the field's position are affected.
+ ES_PROPERTY(min=0, category=Field)
+ f32 radius{0.0f};
+
+ // Push direction for a Directional field (normalized at use). Point/Vortex/Drag
+ // derive their direction from the field→particle vector and ignore this.
+ ES_PROPERTY(category=Field)
+ glm::vec2 direction{1.0f, 0.0f};
+
+ // Fade the force linearly to 0 at the radius edge (only meaningful when radius > 0).
+ ES_PROPERTY(category=Field)
+ bool falloff{true};
+
+ ES_PROPERTY()
+ bool enabled{true};
+
+ ParticleForceField() = default;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index 56ebc174b..ac39dc338 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -23,6 +23,27 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
});
}
+ // Flatten the active force fields once so the per-particle loop touches no
+ // components. Fields are world objects, applied to world-space particles.
+ force_fields_.clear();
+ auto ffView = registry.view<ecs::Transform, ecs::ParticleForceField>();
+ for (auto ffEntity : ffView) {
+ const auto& ff = ffView.get<ecs::ParticleForceField>(ffEntity);
+ if (!ff.enabled || ff.strength == 0.0f) continue;
+ auto& ffTransform = ffView.get<ecs::Transform>(ffEntity);
+ ffTransform.ensureDecomposed();
+ f32 dl = std::sqrt(ff.direction.x * ff.direction.x + ff.direction.y * ff.direction.y);
+ ForceFieldInstance inst;
+ inst.type = ff.type;
+ inst.position = glm::vec2(ffTransform.worldPosition.x, ffTransform.worldPosition.y);
+ inst.direction = dl > 1e-6f ? ff.direction / dl : glm::vec2(1.0f, 0.0f);
+ inst.strength = ff.strength;
+ inst.radius = ff.radius;
+ inst.radiusSq = ff.radius * ff.radius;
+ inst.falloff = ff.falloff;
+ force_fields_.push_back(inst);
+ }
+
auto view = registry.view<ecs::Transform, ecs::ParticleEmitter>();
for (auto entity : view) {
const auto& emitter = view.get<ecs::ParticleEmitter>(entity);
@@ -375,6 +396,39 @@ static f32 sampleSizeLut(const SizeLut& lut, f32 t) {
return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));
}
+// Fold one force field into a world-space particle's velocity.
+static void applyForceField(const ForceFieldInstance& ff, Particle& p, f32 dt) {
+ glm::vec2 toField = ff.position - p.position; // field ← particle
+ f32 distSq = toField.x * toField.x + toField.y * toField.y;
+ f32 factor = 1.0f;
+ if (ff.radius > 0.0f) {
+ if (distSq > ff.radiusSq) return; // outside the zone
+ if (ff.falloff) factor = 1.0f - std::sqrt(distSq) / ff.radius;
+ }
+ switch (static_cast<ecs::ForceFieldType>(ff.type)) {
+ case ecs::ForceFieldType::Directional:
+ p.velocity += ff.direction * (ff.strength * factor * dt);
+ break;
+ case ecs::ForceFieldType::Point: {
+ f32 d = std::sqrt(distSq);
+ if (d > 1e-4f) p.velocity += (toField / d) * (ff.strength * factor * dt);
+ break;
+ }
+ case ecs::ForceFieldType::Vortex: {
+ f32 d = std::sqrt(distSq);
+ if (d > 1e-4f) {
+ glm::vec2 radial = -toField / d; // field → particle
+ glm::vec2 perp(-radial.y, radial.x); // tangent (CCW swirl)
+ p.velocity += perp * (ff.strength * factor * dt);
+ }
+ break;
+ }
+ case ecs::ForceFieldType::Drag:
+ p.velocity *= (1.0f - std::min(ff.strength * factor * dt, 1.0f));
+ break;
+ }
+}
+
void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
EmitterState& state, f32 dt,
const ColorLut* colorLut, const SizeLut* sizeLut,
@@ -424,6 +478,9 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,
f32 t = p.age / p.lifetime;
p.velocity += emitter.gravity * dt;
+ if (isWorldSpace && !force_fields_.empty()) {
+ for (const auto& ff : force_fields_) applyForceField(ff, p, dt);
+ }
if (emitter.damping > 0.0f) {
p.velocity *= (1.0f - emitter.damping * dt);
}
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index 3db31821f..31afc89d5 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -7,6 +7,7 @@
#include "../ecs/Registry.hpp"
#include "../ecs/components/Transform.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
+#include "../ecs/components/ParticleForceField.hpp"
#include "Particle.hpp"
#include "ParticleEasing.hpp"
@@ -30,6 +31,18 @@ using SizeLut = std::array<f32, kColorLutSize>;
// how many of these to actually keep.
inline constexpr int kMaxTrailPoints = 12;
+// A scene force field flattened to what the per-particle inner loop needs, gathered
+// once per update() so the hot loop touches no components.
+struct ForceFieldInstance {
+ i32 type = 0;
+ glm::vec2 position{0.0f};
+ glm::vec2 direction{1.0f, 0.0f}; // pre-normalized (Directional only)
+ f32 strength = 0.0f;
+ f32 radius = 0.0f; // 0 = unbounded
+ f32 radiusSq = 0.0f;
+ bool falloff = true;
+};
+
struct EmitterState {
ParticlePool pool;
f32 emission_accumulator = 0.0f;
@@ -113,6 +126,9 @@ private:
std::unordered_map<Entity, SizeLut> sizeLuts_;
std::mt19937 rng_;
std::vector<u32> dead_particle_indices_;
+ // Active scene force fields, rebuilt each update() and applied to world-space
+ // particles during integration.
+ std::vector<ForceFieldInstance> force_fields_;
// RAII: auto-unregisters from the registry's onDestroy when this system is
// destroyed, so a torn-down system never leaves a dangling `this` behind.
Connection destroyConn_;
diff --git a/tests/particle/test_particle.cpp b/tests/particle/test_particle.cpp
index 74ba9c478..fb391aa0b 100644
--- a/tests/particle/test_particle.cpp
+++ b/tests/particle/test_particle.cpp
@@ -519,6 +519,89 @@ TEST_CASE("system_trail_slot_reuse_starts_empty") {
}
}
+// A still emitter (no initial speed, no gravity) — only a force field can move its
+// particles, so any velocity proves the field was applied.
+static Entity makeStillEmitter(ecs::Registry& registry) {
+ Entity e = registry.create();
+ registry.emplace<ecs::Transform>(e);
+ auto& emitter = registry.emplace<ecs::ParticleEmitter>(e);
+ emitter.rate = 1000.0f;
+ emitter.lifetimeMin = emitter.lifetimeMax = 10.0f;
+ emitter.maxParticles = 50;
+ emitter.speedMin = emitter.speedMax = 0.0f;
+ emitter.gravity = glm::vec2(0.0f);
+ emitter.shape = static_cast<i32>(ecs::EmitterShape::Point);
+ emitter.playOnStart = true;
+ return e;
+}
+
+TEST_CASE("system_force_field_directional_pushes_particles") {
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity field = registry.create();
+ registry.emplace<ecs::Transform>(field);
+ auto& ff = registry.emplace<ecs::ParticleForceField>(field);
+ ff.type = static_cast<i32>(ecs::ForceFieldType::Directional);
+ ff.strength = 500.0f;
+ ff.direction = glm::vec2(1.0f, 0.0f); // rightward wind, unbounded
+
+ Entity e = makeStillEmitter(registry);
+ system.update(registry, 0.05f);
+
+ bool pushedRight = false;
+ system.forEachParticle(e, [&](const Particle& p) {
+ if (p.velocity.x > 1.0f && std::abs(p.velocity.y) < 0.5f) pushedRight = true;
+ });
+ CHECK(pushedRight);
+}
+
+TEST_CASE("system_force_field_point_attracts_toward_it") {
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity field = registry.create();
+ auto& ft = registry.emplace<ecs::Transform>(field);
+ // No transform system runs in this harness, so seed the world position directly
+ // (the sim reads worldPosition, which is otherwise computed from the matrix).
+ ft.worldPosition = glm::vec3(400.0f, 0.0f, 0.0f); // to the right of the origin
+ auto& ff = registry.emplace<ecs::ParticleForceField>(field);
+ ff.type = static_cast<i32>(ecs::ForceFieldType::Point);
+ ff.strength = 300.0f; // positive = attract
+
+ Entity e = makeStillEmitter(registry); // particles spawn at the origin
+ system.update(registry, 0.05f);
+
+ bool pulledRight = false;
+ system.forEachParticle(e, [&](const Particle& p) {
+ if (p.velocity.x > 1.0f) pulledRight = true; // toward the field at +x
+ });
+ CHECK(pulledRight);
+}
+
+TEST_CASE("system_force_field_radius_excludes_distant_particles") {
+ ecs::Registry registry;
+ ParticleSystem system;
+
+ Entity field = registry.create();
+ auto& ft = registry.emplace<ecs::Transform>(field);
+ ft.worldPosition = glm::vec3(5000.0f, 0.0f, 0.0f); // far away (seeded directly)
+ auto& ff = registry.emplace<ecs::ParticleForceField>(field);
+ ff.type = static_cast<i32>(ecs::ForceFieldType::Directional);
+ ff.strength = 500.0f;
+ ff.direction = glm::vec2(1.0f, 0.0f);
+ ff.radius = 100.0f; // small zone the origin particles are outside of
+
+ Entity e = makeStillEmitter(registry);
+ system.update(registry, 0.05f);
+
+ bool anyMoved = false;
+ system.forEachParticle(e, [&](const Particle& p) {
+ if (glm::length(p.velocity) > 0.01f) anyMoved = true;
+ });
+ CHECK_FALSE(anyMoved); // out of range → untouched
+}
+
TEST_CASE("system_size_interpolation") {
ecs::Registry registry;
ParticleSystem system;