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): an emitter can release bursts on a schedule (bursts), and the Cocos burst list, repeat count and burst times map onto it

yhh31c87f94de01
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 36cbb1825..80e96eb61 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -37,6 +37,7 @@ env:
test_bitmap_font test_texture_cache test_material_shader_lifetime test_mesh_recovery test_aot_host test_aot_conformance
test_touch_stream
test_frame_lifecycle
+ test_particle_stretch test_particle_speed_limit test_particle_bursts
jobs:
playable-runtime:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82568b5c3..db90ffc42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ published separately; it ships inside the editor.
- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.
- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.
- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.
+- **Bursts on a schedule.** `ParticleEmitter.bursts` is a list of `{ time, count }`: each releases its particles once the emitter has been emitting for `time` seconds, and a looping emitter repeats the list every `duration`. It runs beside `burstCount`, which still repeats one burst on an interval.
- **A 3D collider can sit off its entity.** `BoxCollider3D`, `SphereCollider3D` and `CapsuleCollider3D` take an optional `center`, the shape's place from the entity origin in world units. The body stays at the entity, so a dynamic body turns about its origin and the shape swings round it.
- **Text can underline, and a box can grow to its text.** `Text.underline` draws a bar under each line, taken from the font's own underscore. `TextOverflow.ResizeHeight` keeps every line and sets the entity's `ContentRect` height to the height they take, so what sits below a paragraph can follow it.
- **An emitter runs on its own clock.** `ParticleEmitter.simulationSpeed` scales how fast that emitter's time runs: 2 plays it twice as fast, 0.5 at half, 0 holds it. Emission, lifetimes and motion all follow it. The default, 1, is the behaviour before.
diff --git a/docs/astro/src/content/docs/world/particles.mdx b/docs/astro/src/content/docs/world/particles.mdx
index f9169fabf..df1d979f1 100644
--- a/docs/astro/src/content/docs/world/particles.mdx
+++ b/docs/astro/src/content/docs/world/particles.mdx
@@ -89,6 +89,7 @@ in degrees.
|---|---|---|---|
| `rate` | number | `10` | Continuous emission, particles per second. `0` = bursts only. |
| `burstCount` | number | `0` | Particles released per burst. `0` disables bursts. |
+| `bursts` | `{ time, count }[]` | `[]` | A schedule of bursts: `count` particles once the emitter has been emitting for `time` seconds (counted from the end of `startDelay`). A looping emitter repeats the schedule every `duration`. Used beside `burstCount`, not instead of it. |
| `burstInterval` | number | `1` | Seconds between bursts. |
| `duration` | number | `5` | Seconds the emitter runs before stopping (see `looping`). |
| `simulationSpeed` | number | `1` | How fast this emitter's own time runs: `2` plays it twice as fast, `0` holds it. Emission, lifetimes and motion all follow it. |
diff --git a/docs/astro/src/content/docs/zh-cn/world/particles.mdx b/docs/astro/src/content/docs/zh-cn/world/particles.mdx
index 81a0f11ba..b331a2af5 100644
--- a/docs/astro/src/content/docs/zh-cn/world/particles.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/particles.mdx
@@ -80,6 +80,7 @@ const spawnEmbers = defineSystem([Commands()], (cmds) => {
|---|---|---|---|
| `rate` | number | `10` | 持续发射,每秒粒子数。`0` = 只用爆发。 |
| `burstCount` | number | `0` | 每次爆发释放的粒子数。`0` 禁用爆发。 |
+| `bursts` | `{ time, count }[]` | `[]` | 一张爆发时间表:发射器发射满 `time` 秒(从 `startDelay` 结束起算)时释放 `count` 颗粒子。循环发射器每过一个 `duration` 重复一遍。与 `burstCount` 并用,不是替代。 |
| `burstInterval` | number | `1` | 两次爆发之间的秒数。 |
| `duration` | number | `5` | 发射器停止前运行的秒数(见 `looping`)。 |
| `simulationSpeed` | number | `1` | 这个发射器自己的时间流速:`2` 是两倍速,`0` 是停住。发射、寿命和运动都跟着它走。 |
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 9aec29a02..c70e528ff 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -462,6 +462,11 @@
"type": "Vec3",
"default": "(0.5, 0.5, 0.5)"
},
+ {
+ "key": "center",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
{
"key": "friction",
"type": "number",
@@ -744,6 +749,11 @@
"default": "0.5",
"range": "≥ 0"
},
+ {
+ "key": "center",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
{
"key": "friction",
"type": "number",
@@ -3911,6 +3921,11 @@
"key": "sizeCurve",
"type": "object",
"default": "{\"keys\":[]}"
+ },
+ {
+ "key": "bursts",
+ "type": "array",
+ "default": "empty"
}
]
},
@@ -5376,6 +5391,11 @@
"default": "0.5",
"range": "≥ 0"
},
+ {
+ "key": "center",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
{
"key": "friction",
"type": "number",
diff --git a/pipeline/src/import/cocos/particle.ts b/pipeline/src/import/cocos/particle.ts
index e985f66d1..eb0492742 100644
--- a/pipeline/src/import/cocos/particle.ts
+++ b/pipeline/src/import/cocos/particle.ts
@@ -236,17 +236,19 @@ export function particleSystem(c: { enabled: boolean; data: Raw }, ctx: Particle
out.shape = 0; // Point
}
- // bursts: the engine repeats one burst on an interval
+ // bursts: each one fires at its time, `repeatCount` times `repeatInterval` apart, and the schedule repeats with the system's loop
const bursts = (Array.isArray(d.bursts) ? d.bursts : []).filter(isObj);
if (bursts.length > 0) {
- const b = bursts[0]!;
- out.burstCount = Math.round(mid(curveRange(b.count, 0, 0)));
- out.burstInterval = Math.max(num(b.repeatInterval, 1), 0.01);
- const at = num(b._time, 0);
- // A system that only bursts has nothing to wait for but its burst: the wait is the emitter's start delay. With a steady rate beside it the
- // delay would hold the rate back too, so that burst's time is counted instead.
- if (at > 0 && bursts.length === 1 && mid(rate) === 0) out.startDelay = Number(out.startDelay ?? 0) + at;
- else if (bursts.length > 1 || at > 0) lose('particle-bursts');
+ const schedule: { time: number; count: number }[] = [];
+ for (const b of bursts) {
+ const count = Math.round(mid(curveRange(b.count, 0, 0)));
+ const repeats = Math.max(1, Math.min(Math.trunc(isObj(b.repeatCount) ? mid(curveRange(b.repeatCount, 1, 1)) : num(b._repeatCount ?? b.repeatCount, 1)), 64));
+ const every = Math.max(num(b.repeatInterval, 1), 0.01);
+ if (count <= 0) continue;
+ for (let i = 0; i < repeats && schedule.length < 64; i++) schedule.push({ time: Math.max(num(b._time, 0), 0) + i * every, count });
+ }
+ schedule.sort((a, c) => a.time - c.time);
+ if (schedule.length > 0) out.bursts = schedule;
}
// a sheet of frames played over a life
diff --git a/pipeline/tests/cocos-particle.test.ts b/pipeline/tests/cocos-particle.test.ts
index 529a7f824..709fb3888 100644
--- a/pipeline/tests/cocos-particle.test.ts
+++ b/pipeline/tests/cocos-particle.test.ts
@@ -73,8 +73,7 @@ describe('a particle system', () => {
const d = convert().out.data as Record<string, any>;
expect(d.maxParticles).toBe(30);
expect(d.looping).toBe(false);
- expect(d.burstCount).toBe(12);
- expect(d.burstInterval).toBe(0.5);
+ expect(d.bursts).toEqual([{ time: 0, count: 12 }]);
expect([d.speedMin, d.speedMax]).toEqual([1, 3]);
expect(d.lifetimeMin).toBe(1);
expect(d.gravity.y).toBeCloseTo(-4.9, 5);
@@ -144,7 +143,7 @@ describe('a particle system', () => {
expect(axes.report.notes['particle-limit-per-axis']?.count).toBe(1);
});
- it('maps simulation speed, turbulence and a trail, and the burst time of a burst-only system as its start delay', () => {
+ it('maps simulation speed, turbulence and a trail, and a burst scheduled at its time', () => {
const { out, report } = convert({
simulationSpeed: 2,
bursts: [{ _time: 0.4, count: constant(5), repeatInterval: 1 }],
@@ -153,7 +152,7 @@ describe('a particle system', () => {
});
const d = out.data as Record<string, any>;
expect(d.simulationSpeed).toBe(2);
- expect(d.startDelay).toBeCloseTo(0.4, 5);
+ expect(d.bursts).toEqual([{ time: 0.4, count: 5 }]);
expect([d.noiseStrength, d.noiseFrequency, d.noiseScrollSpeed, d.noiseOctaves]).toEqual([0.6000000000000001, 0.5, 2, 2]);
expect([d.trailEnabled, d.trailPoints, d.trailWidth, d.trailMinDistance]).toEqual([true, 7, 0.8, 0.1]);
expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });
@@ -161,12 +160,19 @@ describe('a particle system', () => {
expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);
});
- it('counts what the emitter has no field for: several bursts, a trail coloured along its length', () => {
+ it('schedules several bursts and a repeating one, in time order', () => {
+ const { out } = convert({
+ bursts: [{ _time: 1, count: constant(4), repeatInterval: 1 }, { _time: 0, _repeatCount: 3, count: constant(5), repeatInterval: 0.5 }],
+ });
+ expect((out.data as Record<string, any>).bursts).toEqual([
+ { time: 0, count: 5 }, { time: 0.5, count: 5 }, { time: 1, count: 4 }, { time: 1, count: 5 },
+ ]);
+ });
+
+ it('counts what the emitter has no field for: a trail coloured along its length', () => {
const { report } = convert({
- bursts: [{ _time: 0, count: constant(5), repeatInterval: 1 }, { _time: 1, count: constant(5), repeatInterval: 1 }],
_trailModule: { _enable: true, lifeTime: constant(0.3), widthRatio: constant(1), colorOverTrail: { _mode: 1 } },
});
- expect(report.notes['particle-bursts']?.count).toBe(1);
expect(report.notes['particle-trail-colour']?.count).toBe(1);
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3b942e81f..fb74fcdb2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -2600,8 +2600,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## CollisionEnterEvent — interface @experimental
@@ -6386,6 +6386,7 @@ debugNormals: boolean
getAliveCount: (entity: Entity) => number
play: (entity: Entity) => void
reset: (entity: Entity) => void
+setBursts: (entity: Entity, bursts: readonly { time: number; count: number; }[] | null) => void
setCollisionBudget: (budget: Partial<ParticleCollisionBudget>) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
@@ -6475,6 +6476,7 @@ angularVelocityMin: number
blendMode: number
burstCount: number
burstInterval: number
+bursts: { time: number; count: number; }[]
collisionBounce: number
collisionEnabled: boolean
collisionEventBudget: number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f4d3b5cad..7ca9ac5a0 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -2600,8 +2600,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## CollisionEnterEvent — interface @experimental
@@ -6589,6 +6589,7 @@ debugNormals: boolean
getAliveCount: (entity: Entity) => number
play: (entity: Entity) => void
reset: (entity: Entity) => void
+setBursts: (entity: Entity, bursts: readonly { time: number; count: number; }[] | null) => void
setCollisionBudget: (budget: Partial<ParticleCollisionBudget>) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
@@ -6678,6 +6679,7 @@ angularVelocityMin: number
blendMode: number
burstCount: number
burstInterval: number
+bursts: { time: number; count: number; }[]
collisionBounce: number
collisionEnabled: boolean
collisionEventBudget: number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 63f900ce9..1708bf081 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -2595,8 +2595,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## CollisionEnterEvent — interface @experimental
@@ -6381,6 +6381,7 @@ debugNormals: boolean
getAliveCount: (entity: Entity) => number
play: (entity: Entity) => void
reset: (entity: Entity) => void
+setBursts: (entity: Entity, bursts: readonly { time: number; count: number; }[] | null) => void
setCollisionBudget: (budget: Partial<ParticleCollisionBudget>) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
@@ -6470,6 +6471,7 @@ angularVelocityMin: number
blendMode: number
burstCount: number
burstInterval: number
+bursts: { time: number; count: number; }[]
collisionBounce: number
collisionEnabled: boolean
collisionEventBudget: number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index eac5fa468..a422f8d7b 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -2595,8 +2595,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## CollisionEnterEvent — interface @experimental
@@ -6676,6 +6676,7 @@ debugNormals: boolean
getAliveCount: (entity: Entity) => number
play: (entity: Entity) => void
reset: (entity: Entity) => void
+setBursts: (entity: Entity, bursts: readonly { time: number; count: number; }[] | null) => void
setCollisionBudget: (budget: Partial<ParticleCollisionBudget>) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
@@ -6765,6 +6766,7 @@ angularVelocityMin: number
blendMode: number
burstCount: number
burstInterval: number
+bursts: { time: number; count: number; }[]
collisionBounce: number
collisionEnabled: boolean
collisionEventBudget: number
diff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.md
index ff1850e38..a42753f35 100644
--- a/sdk/etc/physics3d.api.md
+++ b/sdk/etc/physics3d.api.md
@@ -90,8 +90,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## Contact3DEvent — interface @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index e26f3200d..7ebc66132 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -400,6 +400,7 @@ particle_collisionStatsCount: (() => number) | undefined
particle_getAliveCount: ((entity: number) => number) | undefined
particle_play: ((registry: CppRegistry, entity: number) => void) | undefined
particle_reset: ((registry: CppRegistry, entity: number) => void) | undefined
+particle_set_bursts: ((entity: number, ptr: number, count: number) => void) | undefined
particle_set_color_lut: ((entity: number, ptr: number, count: number) => void) | undefined
particle_set_size_lut: ((entity: number, ptr: number, count: number) => void) | undefined
particle_set_speed_lut: ((entity: number, ptr: number, count: number) => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 2313811ba..cb7d67161 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -2595,8 +2595,8 @@ shape: Collider3DShape
## Collider3DShape — type @experimental
```
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
- | { kind: 'sphere'; radius: number }
- | { kind: 'capsule'; radius: number; halfHeight: number }
+ | { kind: 'sphere'; radius: number; center?: Vec3 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 }
```
## CollisionEnterEvent — interface @experimental
@@ -6388,6 +6388,7 @@ debugNormals: boolean
getAliveCount: (entity: Entity) => number
play: (entity: Entity) => void
reset: (entity: Entity) => void
+setBursts: (entity: Entity, bursts: readonly { time: number; count: number; }[] | null) => void
setCollisionBudget: (budget: Partial<ParticleCollisionBudget>) => void
setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
@@ -6477,6 +6478,7 @@ angularVelocityMin: number
blendMode: number
burstCount: number
burstInterval: number
+bursts: { time: number; count: number; }[]
collisionBounce: number
collisionEnabled: boolean
collisionEventBudget: number
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 3452c887d..be76dc8da 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -95,6 +95,7 @@ export interface NativeEngineApi {
particle_getAliveCount?(entity: number): number;
particle_play?(registry: unknown, entity: number): void;
particle_reset?(registry: unknown, entity: number): void;
+ particle_set_bursts?(entity: number, ptr: number, count: number): void;
particle_set_color_lut?(entity: number, ptr: number, count: number): void;
particle_set_size_lut?(entity: number, ptr: number, count: number): void;
particle_set_speed_lut?(entity: number, ptr: number, count: number): void;
@@ -431,6 +432,7 @@ export function createNativeEngineApi(
bind('particle_getAliveCount', 'es_particle_getAliveCount', false);
bind('particle_play', 'es_particle_play', true);
bind('particle_reset', 'es_particle_reset', true);
+ bind('particle_set_bursts', 'es_particle_set_bursts', false);
bind('particle_set_color_lut', 'es_particle_set_color_lut', false);
bind('particle_set_size_lut', 'es_particle_set_size_lut', false);
bind('particle_set_speed_lut', 'es_particle_set_speed_lut', false);
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index 96c918196..00e03d3af 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -1215,6 +1215,11 @@ export interface ParticleEmitterData extends ParticleEmitterDataCpp {
* has keys it overrides startSize/endSize + sizeEasing. Empty ⇒ start/end fallback.
*/
sizeCurve: { keys: { t: number; v: number }[] };
+ /**
+ * Bursts on a schedule: `count` particles once the emitter has been emitting for `time` seconds, repeated every
+ * `duration` while it loops. Beside (not instead of) `burstCount`, which repeats one burst on an interval.
+ */
+ bursts: { time: number; count: number }[];
}
/**
@@ -1226,17 +1231,18 @@ export interface ParticleEmitterData extends ParticleEmitterDataCpp {
* @beta
*/
export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',
- metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] }, sizeCurve: { keys: [] } }),
+ metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] }, sizeCurve: { keys: [] }, bursts: [] }),
{
// Most field metadata is authored at the C++ ES_PROPERTY site (categories,
// min/step, and the shape/simulationSpace/easing enum dropdowns via `enum=`).
// Only what an annotation can't express stays here: the blendMode dropdown
// (BlendMode is a renderer enum with no component ES_ENUM), and the two
- // TS-only editor fields (sizeCurve / colorGradient have no C++ member).
+ // TS-only editor fields (sizeCurve / colorGradient / bursts have no C++ member).
fields: {
blendMode: { enum: enumOptions(BlendMode) },
sizeCurve: { curve: true, category: 'Size' },
colorGradient: { gradient: true, category: 'Color' },
+ bursts: { category: 'Emission' },
},
}
);
diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.ts
index 87c63e952..1aa002379 100644
--- a/sdk/src/particle/ParticleAPI.ts
+++ b/sdk/src/particle/ParticleAPI.ts
@@ -91,6 +91,15 @@ export class ParticleAPI {
this.uploadLut(this.module_.particle_set_speed_lut, entity, lut, 1);
}
+ /**
+ * Burst schedule: each burst releases `count` particles once the emitter has been emitting for `time` seconds
+ * (counted from the end of its start delay). A looping emitter repeats the schedule every duration. Null clears.
+ */
+ setBursts(entity: Entity, bursts: readonly { time: number; count: number }[] | null): void {
+ const lut = bursts && bursts.length > 0 ? Float32Array.from(bursts.flatMap((b) => [b.time, b.count])) : null;
+ this.uploadLut(this.module_.particle_set_bursts, entity, lut, 2);
+ }
+
// Copy a Float32Array into the core's heap and hand its offset + element count
// (length / `stride`) to the C++ setter, then free; null/empty clears. The heap
// is wasm linear memory on the web and the host's arena on a device — the same
diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.ts
index e8233ae2e..faa3ee671 100644
--- a/sdk/src/particle/ParticlePlugin.ts
+++ b/sdk/src/particle/ParticlePlugin.ts
@@ -27,6 +27,8 @@ export class ParticlePlugin implements Plugin {
private readonly gradients_ = new Map<number, Gradient>();
/** Entity → authored size-over-life curve (out-of-band; baked to the C++ LUT). */
private readonly sizeCurves_ = new Map<number, Curve>();
+ /** Entity → authored burst schedule (out-of-band; handed to the sim as (time, count) pairs). */
+ private readonly bursts_ = new Map<number, { time: number; count: number }[]>();
private overlay_: string | null = null;
private offDespawn_: (() => void) | null = null;
@@ -53,14 +55,16 @@ export class ParticlePlugin implements Plugin {
// C++ field — carry it out-of-band and bake it into the sim's LUT on load.
const gradients = this.gradients_;
const sizeCurves = this.sizeCurves_;
+ const bursts = this.bursts_;
this.offDespawn_ = app.world.onDespawn((entity) => {
if (gradients.delete(entity)) api.setColorLut(entity, null);
if (sizeCurves.delete(entity)) api.setSizeLut(entity, null);
+ if (bursts.delete(entity)) api.setBursts(entity, null);
});
registerSceneComponentCodec('ParticleEmitter', {
- outOfBandFields: ['colorGradient', 'sizeCurve'],
+ outOfBandFields: ['colorGradient', 'sizeCurve', 'bursts'],
importData: (entity, outOfBand) => {
const g = outOfBand.colorGradient as Gradient | undefined;
api.setColorLut(entity, bakeGradient(g));
@@ -71,12 +75,19 @@ export class ParticlePlugin implements Plugin {
api.setSizeLut(entity, bakeCurve(c));
if (c?.keys?.length) sizeCurves.set(entity, c);
else sizeCurves.delete(entity);
+
+ const b = outOfBand.bursts as { time: number; count: number }[] | undefined;
+ api.setBursts(entity, b ?? null);
+ if (b?.length) bursts.set(entity, b);
+ else bursts.delete(entity);
},
exportData: (entity, data) => {
const g = gradients.get(entity);
if (g) data.colorGradient = g;
const c = sizeCurves.get(entity);
if (c) data.sizeCurve = c;
+ const b = bursts.get(entity);
+ if (b) data.bursts = b;
},
});
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 7d83096cb..d94850433 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -644,6 +644,7 @@ export interface ESEngineModule {
/** Upload/clear an entity's baked size-over-life multiplier LUT. */
particle_set_size_lut?(entity: number, ptr: number, count: number): void;
particle_set_speed_lut?(entity: number, ptr: number, count: number): void;
+ particle_set_bursts?(entity: number, ptr: number, count: number): void;
trail_update?(registry: CppRegistry, dt: number): void;
trail_clear?(registry: CppRegistry, entity: number): void;
springbone_update?(registry: CppRegistry, dt: number): void;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index d02e4f09e..0d8cd53c5 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -659,6 +659,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"category": "Emission",
"min": 0,
},
+ "bursts": {
+ "category": "Emission",
+ },
"collisionBounce": {
"category": "Collision",
"max": 1,
diff --git a/sdk/tests/particle-bursts-wasm.test.ts b/sdk/tests/particle-bursts-wasm.test.ts
new file mode 100644
index 000000000..0f65308a5
--- /dev/null
+++ b/sdk/tests/particle-bursts-wasm.test.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A burst schedule driven through the real core: each burst is born when the emitter's clock reaches its time.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { App } from '../src/app/app';
+import { Transform, ParticleEmitter } from '../src/ecs/component';
+import { Particle, ParticlePlugin } from '../src/particle';
+import type { ESEngineModule } from '../src/wasm';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+let engine: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });
+
+describe.skipIf(!HAS_WASM)('a particle burst schedule through the core', () => {
+ beforeAll(async () => { engine = await loadWasmModule(); });
+
+ const setup = (looping: boolean) => {
+ const app = App.new();
+ apps.push(app);
+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });
+ app.addPlugin(new ParticlePlugin());
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, {});
+ app.world.insert(e, ParticleEmitter, { rate: 0, burstCount: 0, maxParticles: 200, lifetimeMin: 10, lifetimeMax: 10, duration: 1, looping, speedMin: 0, speedMax: 0, gravity: { x: 0, y: 0, z: 0 } });
+ return { app, e, particle: app.getResource(Particle) };
+ };
+
+ it('releases each burst once its time is reached', async () => {
+ const { app, e, particle } = setup(false);
+ particle.setBursts(e, [{ time: 0.1, count: 3 }, { time: 0.3, count: 2 }]);
+ await app.stepFrames(3, 1 / 60);
+ expect(particle.getAliveCount(e)).toBe(0);
+ await app.stepFrames(9, 1 / 60); // 0.2 s: the first burst has passed
+ expect(particle.getAliveCount(e)).toBe(3);
+ await app.stepFrames(12, 1 / 60); // 0.4 s: both
+ expect(particle.getAliveCount(e)).toBe(5);
+ await app.stepFrames(60, 1 / 60); // a one-shot emitter does not repeat them
+ expect(particle.getAliveCount(e)).toBe(5);
+ });
+
+ it('repeats the schedule every duration while the emitter loops', async () => {
+ const { app, e, particle } = setup(true);
+ particle.setBursts(e, [{ time: 0.5, count: 4 }]);
+ await app.stepFrames(90, 1 / 60); // 1.5 s: the 0.5 s burst and the one at 1.5 s
+ expect(particle.getAliveCount(e)).toBeGreaterThanOrEqual(4);
+ expect(particle.getAliveCount(e)).toBeLessThanOrEqual(8);
+ await app.stepFrames(70, 1 / 60); // 2.67 s: passes at 0.5, 1.5 and 2.5
+ expect(particle.getAliveCount(e)).toBe(12);
+ });
+});
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 864fc04bc..c92738fc8 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -923,6 +923,11 @@ void particle_set_speed_lut(u32 entity, uintptr_t ptr, i32 count) {
if (!g_particleSystem) return;
g_particleSystem->setSpeedLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
}
+
+void particle_set_bursts(u32 entity, uintptr_t ptr, i32 count) {
+ if (!g_particleSystem) return;
+ g_particleSystem->setBursts(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
+}
#endif
void trail_update(ecs::Registry& registry, f32 dt) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 4863a7374..df431ccac 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -204,6 +204,8 @@ void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count);
void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count);
/** Speed-over-life multiplier LUT: scales the step, never the forces. */
void particle_set_speed_lut(u32 entity, uintptr_t ptr, i32 count);
+/** Burst schedule: `count` pairs of (seconds, particles) at `ptr`; 0 clears. */
+void particle_set_bursts(u32 entity, uintptr_t ptr, i32 count);
#endif
void trail_update(ecs::Registry& registry, f32 dt);
void trail_clear(ecs::Registry& registry, u32 entity);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 32f434b57..5833ceb91 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -751,6 +751,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);
emscripten::function("particle_set_size_lut", &esengine::particle_set_size_lut);
emscripten::function("particle_set_speed_lut", &esengine::particle_set_speed_lut);
+ emscripten::function("particle_set_bursts", &esengine::particle_set_bursts);
#endif
emscripten::function("trail_update", &esengine::trail_update);
emscripten::function("trail_clear", &esengine::trail_clear);
diff --git a/src/esengine/particle/ParticleBursts.hpp b/src/esengine/particle/ParticleBursts.hpp
new file mode 100644
index 000000000..02d5f9ac7
--- /dev/null
+++ b/src/esengine/particle/ParticleBursts.hpp
@@ -0,0 +1,37 @@
+#pragma once
+
+#include "../core/Types.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <vector>
+
+namespace esengine::particle {
+
+/** @brief One burst of a schedule: `count` particles at `time` seconds after the emitter starts emitting. */
+struct ScheduledBurst {
+ f32 time = 0.0f;
+ u32 count = 0;
+};
+
+/**
+ * @brief How many particles the schedule releases while the emitter's clock goes from `prev` to `cur`.
+ * @details A burst fires once per pass over its time: `prev < time <= cur`. A looping emitter repeats its
+ * schedule every `duration`, so each cycle the clock crossed in this step is checked. `prev` starts
+ * below zero, so a burst at 0 fires on the first step.
+ */
+inline u32 burstsDue(const std::vector<ScheduledBurst>& schedule, f32 prev, f32 cur, f32 duration, bool looping) {
+ u32 total = 0;
+ const bool cycles = looping && duration > 0.0f;
+ const int first = cycles ? static_cast<int>(std::floor(std::max(prev, 0.0f) / duration)) : 0;
+ const int last = cycles ? static_cast<int>(std::floor(cur / duration)) : 0;
+ for (const ScheduledBurst& b : schedule) {
+ for (int k = first; k <= last; ++k) {
+ const f32 at = b.time + static_cast<f32>(k) * duration;
+ if (prev < at && at <= cur) total += b.count;
+ }
+ }
+ return total;
+}
+
+} // namespace esengine::particle
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index b899233dc..f9031522e 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -39,6 +39,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
colorLuts_.erase(entity);
sizeLuts_.erase(entity);
speedLuts_.erase(entity);
+ burstSchedules_.erase(entity);
});
}
@@ -108,6 +109,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
next.emission_accumulator = old.emission_accumulator;
next.elapsed_time = old.elapsed_time;
next.burst_timer = old.burst_timer;
+ next.burst_clock = old.burst_clock;
next.noise_time = old.noise_time;
next.playing = old.playing;
next.first_update = old.first_update;
@@ -173,6 +175,12 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
state.elapsed_time += dt;
}
if (emitting && state.elapsed_time >= startDelay) {
+ if (auto schedule = burstSchedules_.find(entity); schedule != burstSchedules_.end()) {
+ const f32 clock = state.elapsed_time - startDelay;
+ const u32 due = burstsDue(schedule->second, state.burst_clock, clock, emitter.duration, emitter.looping);
+ state.burst_clock = clock;
+ if (due > 0) emit(due, true);
+ }
if (emitter.rate > 0.0f) {
state.emission_accumulator += emitter.rate * dt;
u32 toEmit = static_cast<u32>(state.emission_accumulator);
@@ -265,6 +273,7 @@ void ParticleSystem::reset(Entity entity) {
it->second.emission_accumulator = 0.0f;
it->second.elapsed_time = 0.0f;
it->second.burst_timer = 0.0f;
+ it->second.burst_clock = -1.0f;
it->second.playing = false;
}
}
@@ -298,6 +307,18 @@ void ParticleSystem::setSpeedLut(Entity entity, const f32* values, i32 count) {
for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];
}
+void ParticleSystem::setBursts(Entity entity, const f32* values, i32 count) {
+ if (count <= 0 || values == nullptr) {
+ burstSchedules_.erase(entity);
+ return;
+ }
+ std::vector<ScheduledBurst>& schedule = burstSchedules_[entity];
+ schedule.clear();
+ for (i32 i = 0; i < count && i < 64; ++i) {
+ schedule.push_back({values[i * 2], static_cast<u32>(std::max(values[i * 2 + 1], 0.0f))});
+ }
+}
+
u32 ParticleSystem::aliveCount(Entity entity) const {
auto it = states_.find(entity);
if (it != states_.end()) {
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index 4bdcd4c1b..e145ba6d4 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -9,6 +9,7 @@
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
#include "Particle.hpp"
+#include "ParticleBursts.hpp"
#include "ParticleEasing.hpp"
#include "ParticleShapes.hpp"
@@ -88,6 +89,8 @@ struct EmitterState {
f32 emission_accumulator = 0.0f;
f32 elapsed_time = 0.0f;
f32 burst_timer = 0.0f;
+ /// Where the scheduled bursts last looked: the emitting clock of the previous step, below zero before the first.
+ f32 burst_clock = -1.0f;
// Monotonic clock for the noise field's scroll — advances every update
// regardless of play/stop so the turbulence never snaps when emission pauses.
f32 noise_time = 0.0f;
@@ -178,6 +181,10 @@ public:
* and gravity, damping and noise still accumulate into velocity as before. */
void setSpeedLut(Entity entity, const f32* values, i32 count);
+ /** Set/clear an entity's burst schedule: `count` pairs of (seconds, particles) in `values`. Each fires once per
+ * pass of the emitter's clock over its time, and a looping emitter passes every duration. */
+ void setBursts(Entity entity, const f32* values, i32 count);
+
/// The over-life curves an entity was given, for the GPU kernel to read; null where none was set.
const ColorLut* colorLut(Entity entity) const { auto it = colorLuts_.find(entity); return it == colorLuts_.end() ? nullptr : &it->second; }
const SizeLut* sizeLut(Entity entity) const { auto it = sizeLuts_.find(entity); return it == sizeLuts_.end() ? nullptr : &it->second; }
@@ -240,6 +247,7 @@ private:
std::unordered_map<Entity, ColorLut> colorLuts_;
std::unordered_map<Entity, SizeLut> sizeLuts_;
std::unordered_map<Entity, SizeLut> speedLuts_;
+ std::unordered_map<Entity, std::vector<ScheduledBurst>> burstSchedules_;
std::mt19937 rng_;
bool gpu_available_ = false;
u32 particle_limit_ = 0xffffffffu;
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 03805259b..b0b6dff3a 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -366,6 +366,14 @@ target_include_directories(test_particle_speed_limit PRIVATE
)
add_test(NAME test_particle_speed_limit COMMAND test_particle_speed_limit)
+# Particle burst schedule: each burst fires once per pass of the clock, and a looping emitter passes every duration. Header-only.
+add_executable(test_particle_bursts particle/test_particle_bursts.cpp)
+target_include_directories(test_particle_bursts PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+)
+add_test(NAME test_particle_bursts COMMAND test_particle_bursts)
+
# LOD selection: the projection arithmetic, the hysteresis band and the per-view
# memory. Header-only, so it runs without a device — the pixel gates say which
# level was drawn, this says which of the claims behind it broke.
diff --git a/tests/particle/test_particle_bursts.cpp b/tests/particle/test_particle_bursts.cpp
new file mode 100644
index 000000000..0dfcc7071
--- /dev/null
+++ b/tests/particle/test_particle_bursts.cpp
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file test_particle_bursts.cpp — a burst schedule fires each burst once per pass of the clock, and a looping emitter passes every duration.
+ */
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include <doctest.h>
+
+#include <esengine/particle/ParticleBursts.hpp>
+
+using namespace esengine;
+using namespace esengine::particle;
+
+namespace {
+/// Runs the clock in fixed steps the way the system does, and totals what the schedule released.
+u32 run(const std::vector<ScheduledBurst>& schedule, f32 length, f32 duration, bool looping, f32 dt = 1.0f / 60.0f) {
+ u32 total = 0;
+ f32 prev = -1.0f, clock = 0.0f;
+ while (clock < length) {
+ clock += dt;
+ total += burstsDue(schedule, prev, clock, duration, looping);
+ prev = clock;
+ }
+ return total;
+}
+} // namespace
+
+TEST_CASE("a burst at zero fires on the first step, once") {
+ const std::vector<ScheduledBurst> s{{0.0f, 7}};
+ CHECK(burstsDue(s, -1.0f, 1.0f / 60.0f, 5.0f, false) == 7);
+ CHECK(burstsDue(s, 1.0f / 60.0f, 2.0f / 60.0f, 5.0f, false) == 0);
+}
+
+TEST_CASE("each burst of a schedule fires once as the clock passes it") {
+ const std::vector<ScheduledBurst> s{{0.0f, 5}, {0.5f, 3}, {1.2f, 2}};
+ CHECK(run(s, 4.0f, 5.0f, false) == 10);
+}
+
+TEST_CASE("a burst after the end of a one-shot emitter never fires") {
+ const std::vector<ScheduledBurst> s{{9.0f, 4}};
+ CHECK(run(s, 4.0f, 5.0f, false) == 0);
+}
+
+TEST_CASE("a looping emitter repeats the schedule every duration") {
+ const std::vector<ScheduledBurst> s{{0.5f, 3}};
+ // 2.1 s of a 1 s loop passes 0.5, 1.5 (and starts a third pass at 2.0, not yet at 2.5)
+ CHECK(run(s, 2.1f, 1.0f, true) == 6);
+}
+
+TEST_CASE("a step that spans a whole cycle still releases every burst") {
+ const std::vector<ScheduledBurst> s{{0.25f, 1}, {0.75f, 1}};
+ CHECK(burstsDue(s, 0.0f, 2.0f, 1.0f, true) == 4);
+}
+
+TEST_CASE("an empty schedule releases nothing") {
+ CHECK(burstsDue({}, -1.0f, 3.0f, 1.0f, true) == 0);
+}
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 71a11d2ff..4ff633e27 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(particle): an emitter can release bursts on a schedule (bursts), and the Cocos burst list, repeat count and burst times map onto it':
+ {"note":"Bursts on a schedule."},
'feat(physics3d): a box, sphere or capsule collider can sit off its entity origin (center), and the Cocos BoxCollider centre maps onto it':
{"note":"A 3D collider can sit off its entity."},
'feat(text): Text can underline its lines and grow its box to its text (ResizeHeight), and the Cocos Label maps onto both':