# effect/particlesystem (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/effect/particlesystem/

Particle system.

## ParticleSystem extends Component

Particle system.
- A component that ports the commonly used parts of Unity's ParticleSystem to 2D.
  Supports emission (rate / burst), shape, start ranges for lifetime / speed / size / rotation / color,
  size / color / rotation over lifetime, gravity / damping, additive blending, and image sprites.
- Usage:
    const particleSystem = node.addComponent(ParticleSystem);
    particleSystem.setEmissionRate(40);
    particleSystem.setStartLifetime(0.6, 1.2);
    particleSystem.setStartSpeed(40, 120);
    particleSystem.setColorOverLifetime([
        { time: 0, color: new Color(1, 0.8, 0.3, 1) },
        { time: 1, color: new Color(1, 0.2, 0, 0) },
    ]);
    particleSystem.play();

Example: Attach to a node and spout flames

```js
import { Engine, EngineConfiguration, Scene, WorldNode, ParticleSystem, ParticleEmitterShape, Color, Vector2 } from "./build/vanilla.js";

class MainScene extends Scene {
	initialize(engine) {
		super.initialize(engine);
		const node = new WorldNode();
		node.setLocalPosition(Vector2.create(320, 300));
		const root = this.getRoot();
		root.addChild(node);
		const particleSystem = node.addComponent(ParticleSystem);
		particleSystem.setEmitterShape(ParticleEmitterShape.cone);
		particleSystem.setShapeRadius(10);
		particleSystem.setConeAngle(0.3);
		particleSystem.setEmissionRate(60);
		particleSystem.setStartLifetime(0.6, 1.2);
		particleSystem.setStartSpeed(40, 120);
		particleSystem.setStartSize(10, 18);
		particleSystem.setSizeOverLifetime(1, 0.2);
		particleSystem.setColorOverLifetime([
			{ time: 0, color: new Color(1, 0.8, 0.3, 1) },
			{ time: 1, color: new Color(1, 0.2, 0, 0) },
		]);
		particleSystem.setAdditive(true);
		particleSystem.play();
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.3.0): Constructor.
- `play()` (method, since 0.3.0): Play / stop.
- `stop(isClearing = false)` (method, since 0.3.0): Stops. (stops emitting, living particles keep moving until their lifetime ends unless isClearing)
  - `isClearing` boolean: If true, also clears living particles.
- `emit(count, worldOffset = null)` (method, since 0.3.0): Emits several at once. (event effects such as button clicks)
  - `count` number: Number to emit. (no more are made once the maximum count is reached)
  - `worldOffset` Vector2 | null: Emission origin offset. (in node local space)
- `tick(timeDelta)` (method, since 0.3.0): Update. (node update, skipped in manual tick mode)
  - `timeDelta` number: Elapsed time. (seconds)
- `simulate(timeDelta)` (method, since 0.3.0): Advances time. (emission + integration, called externally in manual tick mode)
  - `timeDelta` number: Time to advance. (seconds)
- `draw(graphic)` (method, since 0.3.0): Output. (vertex color batching, one draw per system regardless of particle count)
  - circle draws with a soft circle texture, rect / streak with white texture quads.
    image keeps individual draws on the assumption that particle counts are small.
  - `graphic` Graphic: Graphic to draw with.
- `calculateDrawnRect(rect)` (method, since 0.4.0): Calculates the drawn rectangle. (Override: a rectangle enclosing every quad the live particles draw, in node content coordinates)
  - Each particle grows by half its drawn size times √2 (rotated rectangles, images), streak quads enclose head and tail grown by half the width, the wobble amplitude is added left and right, plus one unit of margin.
  - Recalculation is requested whenever the simulation (simulate) runs, on emit and on clearing (stop), and in setters that change how particles are drawn. (Drawing is skipped when off screen while the simulation keeps running in tick)
  - With no particles the size is 0 (nothing is drawn).
  - Unknown when in world space with manual tick. (Moving the node moves where it draws and there is no point at which to recalculate)
  - `rect` Rect: Where to write the drawn rectangle. (origin at the top-left of the node's content area)
  - returns boolean: True if known.

  Example: A rectangle enclosing emitted particles

  ```js
  import { WorldNode, ParticleSystem, Rect } from "./build/vanilla.js";
  
  const node = new WorldNode();
  const particleSystem = node.addComponent(ParticleSystem);
  particleSystem.setStartSpeed(0);
  particleSystem.setStartSize(10);
  particleSystem.emit(3);
  const drawnRect = Rect.zero();
  console.log(particleSystem.calculateDrawnRect(drawnRect), drawnRect.size.x > 0);
  ```

- `setEmissionRate(emissionRate)` (method, since 0.3.0): Sets the emission count per second. (default 20)
  - `emissionRate` number: Emissions per second.
- `setBurstList(burstList)` (method, since 0.3.0): Sets the burst list. (emits all at once at the given times, repeats every duration when looping)
  - `burstList` object[]: [{ time, count }]

  Example: A firework that bursts once and ends

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, ParticleSystem, ParticleEmitterShape, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		super.initialize(engine);
  		const node = new WorldNode();
  		node.setLocalPosition(Vector2.create(320, 180));
  		const root = this.getRoot();
  		root.addChild(node);
  		const particleSystem = node.addComponent(ParticleSystem);
  		particleSystem.setLooping(false);
  		particleSystem.setDuration(0.5);
  		particleSystem.setEmissionRate(0);
  		particleSystem.setBurstList([
  			{ time: 0, count: 40 },
  			{ time: 0.3, count: 20 },
  		]);
  		particleSystem.setEmitterShape(ParticleEmitterShape.circle);
  		particleSystem.setShapeRadius(4);
  		particleSystem.setStartSpeed(80, 200);
  		particleSystem.setGravity(0, 300);
  		particleSystem.play();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `setEmitterShape(emitterShape)` (method, since 0.3.0): Sets the emitter shape. (default point)
  - `emitterShape` string: ParticleEmitterShape value.
- `setShapeRadius(shapeRadius)` (method, since 0.3.0): Sets the emission radius. (pixels, default 0)
  - `shapeRadius` number: circle / cone radius.
- `setConeAngle(coneAngleRadian)` (method, since 0.3.0): Sets the cone half angle. (default 0.5 radians)
  - `coneAngleRadian` number: cone half-angle. (radians)
- `setBoxSize(width, height)` (method, since 0.3.0): Sets the box size. (pixels, default 0, 0)
  - `width` number: box width.
  - `height` number: box size.
- `setEdgeWidth(edgeWidth)` (method, since 0.3.0): Sets the edge length. (pixels, default 0)
  - `edgeWidth` number: edge width.
- `setStartLifetime(minSeconds, maxSeconds = minSeconds)` (method, since 0.3.0): Sets the start lifetime range. (default 1 second)
  - `minSeconds` number: Minimum lifetime. (seconds)
  - `maxSeconds` number: Maximum lifetime. (seconds, the minimum if omitted)
- `setStartSpeed(minSpeed, maxSpeed = minSpeed)` (method, since 0.3.0): Sets the start speed range. (default 60)
  - `minSpeed` number: Minimum speed. (pixels per second)
  - `maxSpeed` number: Maximum speed. (pixels per second, the minimum if omitted)
- `setStartSize(minSize, maxSize = minSize)` (method, since 0.3.0): Sets the start size range. (default 6)
  - `minSize` number: Minimum size. (pixels)
  - `maxSize` number: Maximum size. (pixels, the minimum if omitted)
- `setStartRotation(minRadian, maxRadian = minRadian)` (method, since 0.3.0): Sets the start rotation range. (default 0)
  - `minRadian` number: Minimum rotation. (radians)
  - `maxRadian` number: Maximum rotation. (radians, the minimum if omitted)
- `setStartColor(colorA, colorB = colorA)` (method, since 0.3.0): Sets the start color range. (default white)
  - `colorA` Color | string: Start color. (kept as a copy)
  - `colorB` Color | string: Random between the two.
- `setColorOverLifetime(gradient)` (method, since 0.3.0): Sets the color over lifetime. (multiplied with the start color, linear interpolation between keys)
  - `gradient` object[]: [{ time: 0~1, color }]
- `setSizeOverLifetime(startScale, endScale)` (method, since 0.3.0): Sets the size scale over lifetime. (linear from start to end, default 1, 1)
  - `startScale` number: Size scale at birth.
  - `endScale` number: Size scale at the end of the lifetime.
- `setAngularVelocity(minRadianPerSecond, maxRadianPerSecond = minRadianPerSecond)` (method, since 0.3.0): Sets the angular velocity range. (default 0)
  - `minRadianPerSecond` number: Minimum angular velocity. (radians per second)
  - `maxRadianPerSecond` number: Maximum angular velocity. (radians per second, the minimum if omitted)
- `setGravity(gravityX, gravityY)` (method, since 0.3.0): Sets the gravity. (default 0, 0)
  - `gravityX` number: Horizontal acceleration. (pixels per second added to the velocity every second)
  - `gravityY` number: Vertical acceleration. (pixels per second added to the velocity every second, positive is down)
- `setDamping(damping)` (method, since 0.3.0): Sets the damping. (default 0)
  - `damping` number: Damping coefficient per second. (0 = none)
- `setRenderShape(renderShape)` (method, since 0.3.0): Sets the render shape. (default circle)
  - `renderShape` string: ParticleRenderShape value.
- `setImage(image)` (method, since 0.3.0): Sets the particle image.
  - `image` *: Engine image. (renderShape image only)
- `setAdditive(isAdditive)` (method, since 0.3.0): Sets additive blending.
  - `isAdditive` boolean: Whether additive blending. (sugar for setBlendMode("lighter"))
- `setBlendMode(blendMode)` (method, since 0.3.0): Sets the blend mode. (default "source-over")
  - `blendMode` string: Name accepted by Graphic.setBlendMode. ("source-over" | "lighter" | "multiply" | "screen", etc., the 26 SpriteBlendMode values, shader blend modes draw particles together in groups that do not overlap each other)
- `setAttractor(x, y, strength, swirl = 0)` (method, since 0.3.0): Sets the attractor. (pulls toward or pushes from the center, and spins along the tangent)
  - `x` number: Attractor center x. (node local pixels)
  - `y` number: Attractor center y. (node local pixels)
  - `strength` number: Radial acceleration.
  - `swirl` number: Tangential acceleration.
- `clearAttractor()` (method, since 0.3.0): Removes the attractor.
- `setWobble(amplitude, frequency = 4)` (method, since 0.3.0): Sets the wobble. (sways left and right only when drawing, not added to the motion)
  - `amplitude` number: Wiggle amplitude.
  - `frequency` number: Angular velocity per second.
- `setStreakScale(streakScale)` (method, since 0.3.0): Sets the streak length scale. (default 0.06)
  - `streakScale` number: streak length = speed x this value.
- `setWorldSpace(isWorldSpace)` (method, since 0.3.0): Sets world space. (default false)
  - `isWorldSpace` boolean: If true, unaffected by node movement after emission.
- `setLooping(isLooping)` (method, since 0.3.0): Sets looping emission.
  - `isLooping` boolean: If true, keeps emitting. (default true, if false only during duration)
- `setDuration(duration)` (method, since 0.3.0): Sets the emission duration. (seconds, default 1)
  - `duration` number: Emission duration when looping is off. (burst repeat period)
- `setMaxParticleCount(maxParticleCount)` (method, since 0.3.0): Sets the maximum particle count.
  - `maxParticleCount` number: Maximum number that can be alive. (default 512)
- `applyDescription(description)` (method, since 0.3.0): Applies a description (JSON)., shared by vfx asset loading / the particle editor.
  - All fields are optional and only those given are applied. Colors are [r, g, b, a] arrays.
  - imageDataUrl is the data: URL of the image chosen in the particle editor. That image is set as the particle image (drawn once the browser has decoded it), and the image is cleared if it is empty or null.
  - `description` object: Description object. (looping, duration, maxParticleCount, emissionRate, bursts, shape, shapeRadius, coneAngle, boxSize, edgeWidth, lifetime, speed, size, rotation, angularVelocity, startColorA, startColorB, colorOverLifetime, sizeOverLifetime, gravity, damping, attractor, wobble, renderShape, blendMode, streakScale, worldSpace, imageDataUrl)

  Example: Configure from a JSON description

  ```js
  import { ParticleSystem } from "./build/vanilla.js";
  
  const particleSystem = new ParticleSystem();
  particleSystem.applyDescription({
  	looping: false,
  	duration: 0.2,
  	emissionRate: 50,
  	shape: "box",
  	boxSize: [200, 10],
  	lifetime: [0.5, 1],
  	speed: [20, 40],
  	startColorA: [0.6, 0.8, 1, 1],
  	colorOverLifetime: [
  		{ time: 0, color: [1, 1, 1, 1] },
  		{ time: 1, color: [1, 1, 1, 0] },
  	],
  	gravity: [0, 98],
  	renderShape: "streak",
  });
  particleSystem.simulate(0.1);
  console.log(particleSystem.getParticleCount());
  ```

- `getParticleCount()` (method, since 0.3.0): Returns the living particle count.
  - returns number: Living particle count.
- `getParticlePositionList()` (method, since 0.4.0): List of particle positions. (node local, integrated positions without the wiggle applied. For same-seed comparison and tests)
  - returns Vector2[]: Particle position list. (newly created Vector2s)
- `isPlaying()` (method, since 0.3.0): Returns whether it is emitting.
  - returns boolean: True if emitting. (true right after construction)
- `isFinished()` (method, since 0.4.0): Whether it has finished. (nothing more to emit and no particles left, for disposing of one-shot nodes)
  - If stopped, or not looping with duration elapsed and all bursts emitted, there is nothing to emit.
  - returns boolean: True if everything is finished.
- `setManualTick(isManualTick)` (method, since 0.3.0): Sets manual tick. (if true, advances only through simulate() instead of the node update, the timeline handles time)
  - `isManualTick` boolean: If true, does not advance in the node update. (default false)
- `isManualTick()` (method, since 0.3.0): Returns whether it is manual tick.
  - returns boolean: True if manual tick.
- `setRandomSeed(seed)` (method, since 0.3.0): Sets the random seed. (when set, spawn randomness switches to the seeded random and returns to the seed on every stop(true), for reproducible rewinding)
  - `seed` number: Random seed.

  Example: Repeat the same emission with a seed

  ```js
  import { ParticleSystem } from "./build/vanilla.js";
  
  const particleSystem = new ParticleSystem();
  particleSystem.setManualTick(true);
  particleSystem.setRandomSeed(7);
  particleSystem.setEmissionRate(30);
  particleSystem.simulate(0.5);
  const firstPositionList = particleSystem.getParticlePositionList();
  particleSystem.stop(true);
  particleSystem.play();
  particleSystem.simulate(0.5);
  const secondPositionList = particleSystem.getParticlePositionList();
  console.log(firstPositionList.length, secondPositionList[0].x === firstPositionList[0].x);
  ```

- `getRandomSeed()` (method, since 0.3.0): Returns the random seed.
  - returns number | null: Random seed. (null if not set)
- `randomRange(minValue, maxValue)` (method, since 0.3.0): Random for spawning. (seeded random if a seed is set, otherwise the global random)
  - `minValue` number: Minimum value.
  - `maxValue` number: Maximum value.
  - returns number: A random number between the minimum and maximum.

## ParticleEmitterShape (enum)

Emission shape.
- point: a single point at the node origin.
- circle: random position within the radius, outward direction.
- cone: fan of directions within the angle around up (-y), position within the radius.
- box: random position within a rectangular area, upward direction.
- edge: random position on a horizontal line segment, downward (+y) direction. (for scattering from above like snow / rain)

- `point` = `point`: A random direction from a single point at the node origin.
- `circle` = `circle`: Outward from the center at a random position within the radius.
- `cone` = `cone`: A fan of directions within the half angle around up (-y), at a position within the radius.
- `box` = `box`: Up (-y) from a random position inside the rectangle.
- `edge` = `edge`: Down (+y) from a random position on a horizontal line segment.

## ParticleRenderShape (enum)

Particle render shape.
- circle: soft circle. (default)
- rect: rectangle. (a rotating plate like confetti)
- streak: band stretched along the direction of travel. (rain / meteors)
- image: the image set with setImage.

- `circle` = `circle`: Soft circle. (default)
- `rect` = `rect`: Rectangle. (a rotating plate)
- `streak` = `streak`: A band stretched along the direction of travel.
- `image` = `image`: The image set with setImage.
