API REFERENCE · 2.2.0

wgpu-kit/particles

Four-species particle simulation API; configuration and lifecycle, without preset marketing.

Auxiliary inputs, dispatch counts, managed batches and typed kernels are released in 2.1.0. The original API retains the published npm 2.0.0 declarations and implementation as its historical audit baseline; Additions in 2.1.0 and 2.2.0 are identified on affected APIs and cite src files, without claiming a fresh audit of the entire API. Only actual public exports of this entry point are listed.

Source reference: 1 ↗ 2 ↗ 3 ↗ 4 ↗ 5 ↗ 6 ↗

particlesfunction

Create and initialize a four-species GPU particle simulation.

particles(config?: ParticlesConfig): Promise<ParticlesSim>;

Parameters

NameTypeRequiredDefaultMeaning
configParticlesConfigNo{}Simulation, rendering, and initialization options; all fields are detailed under ParticlesConfig.

Returns

Promise<ParticlesSim> Initialized buffers and compute pipelines, without a render loop or attached canvas.

Behavior & constraints

  • World half-width is fixed by count: sqrt(count/16_000). Initial positions are seeded within ±0.8*worldHalf, velocities start at zero, and species indices are 0..3. No public worldHalf or species-count option exists.
  • The caller owns animation scheduling. tick works without attach for compute-only use. Attach a canvas once if built-in rendering is desired.
  • WebGPU and the shared GpuContext are required. No WebGL or CPU fallback is provided. Resource use depends on count, grid resolution, and device limits.

Errors & failure cases

  • Rejects UsageError(ERR_USAGE) for invalid count/mode and n2 count >32_000. An unknown string force name throws plain Error. Device acquisition, buffer allocation, shader compilation, or pipeline validation can reject.
  • Physical numeric options and custom force-matrix length/range are not comprehensively checked. Invalid numbers can reach GPU code; validate application input.

Examples

Initialize once, render on animation frames, and stop scheduling before destroying.
import { particles } from 'wgpu-kit/particles';
const canvas = document.querySelector<HTMLCanvasElement>('#canvas')!;
const sim = await particles({ count: 4096, mode: 'grid', seed: 'example' });
await sim.attach(canvas);
let raf = 0;
let stopped = false;
function frame() {
  if (stopped) return;
  sim.tick();
  raf = requestAnimationFrame(frame);
}
raf = requestAnimationFrame(frame);
function dispose() {
  stopped = true;
  cancelAnimationFrame(raf);
  sim.destroy();
}

ParticlesConfiginterface

All options are optional; defaults below come from the installed 2.0.0 implementation.

interface ParticlesConfig

Parameters

NameTypeRequiredDefaultMeaning
countnumberNo8192Integer particle count in 1..1_000_000. n2 mode rejects counts above 32_000 (its error text recommends at most 20_000). Device memory limits may be lower.
forcesForcePresetName | 'random' | ForceMatrixNo'cells'One of cells/snakes/orbitals/viruses, seeded random, or a readonly 16-number tuple. Four species use matrix[mySpecies*4+otherSpecies]; custom arrays are not length/range-validated here.
mode'n2' | 'tiled' | 'grid'No'grid'Neighbor algorithm: all-pairs, workgroup-tiled all-pairs, or spatial grid. The declaration comment saying tiled is the default is stale; implementation defaults to grid.
color'species' | 'velocity'No'species'Canvas coloring by four species or speed magnitude. Used when the renderer is attached.
bounds'wrap' | 'clamp'No'wrap'How updated positions remain in the square world: wrap or clamp. Interaction distances/neighborhood searches do not wrap across opposite edges.
seedstring | numberNo'wgpu-kit'Converted to String(seed), then hashed; initializes positions/species and the random force matrix deterministically.
rMaxnumberNo0.12Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution.
betanumberNo0.3Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API.
forceFactornumberNo10Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration.
frictionHalfLifenumberNo0.04Damping time parameter used as exp(-effectiveDt/frictionHalfLife). Despite the name, implementation does not include ln(2), so this is an exponential decay time constant rather than a mathematical half-life. Use a positive finite value.
dtnumberNo0.02Base simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically.
pointSizenumberNo0.004Normalized point-quad half-size used by the attached renderer, approximately in clip coordinates after world scaling. It is not a literal pixel size; shader generation rounds the scaled value to four decimals.
maxNeighborsnumberNo8100Grid-only candidate budget: ceil(maxNeighbors/9) candidates per each of up to 9 neighboring cells (self may count). Use a finite positive number.

Behavior & constraints

  • maxNeighbors=Infinity does not disable the cap in 2.0.0 despite the declaration comment: DataView.setUint32 converts Infinity to 0, and the shader then processes no candidates. Use a sufficiently large finite budget when needed.
  • No package export exists for the internal config/presets file paths. Use public ParticlesConfig and its indexed types, not wgpu-kit/dist/... imports.

Fields & related types

NameTypeRequiredDefaultMeaning
ForcePresetName (supporting, not exported by this entry point)'cells' | 'snakes' | 'orbitals' | 'viruses'——Literal names accepted as force selections. FORCE_PRESETS itself is not a public root or /particles export.
ForceMatrix (supporting, not exported by this entry point)readonly [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number]——A flat 4×4 matrix; lookup is mySpecies*4+otherSpecies. Obtain this type without a private-path import using Exclude<NonNullable<ParticlesConfig["forces"]>, string>.
SimMode (supporting, not exported by this entry point)'n2' | 'tiled' | 'grid'——Obtain through NonNullable<ParticlesConfig["mode"]>.

Examples

Validate configuration and a custom four-species matrix with TypeScript.
import type { ParticlesConfig } from 'wgpu-kit/particles';
const options = {
  count: 2048,
  mode: 'grid',
  color: 'velocity',
  bounds: 'clamp',
  seed: 42,
  rMax: 0.12,
  beta: 0.3,
  forceFactor: 8,
  frictionHalfLife: 0.04,
  dt: 0.02,
  pointSize: 0.004,
  maxNeighbors: 8100,
  forces: [0, 0.4, -0.2, 0, -0.3, 0, 0.4, 0, 0.2, -0.3, 0, 0.4, 0, 0.2, -0.3, 0],
} satisfies ParticlesConfig;

ParticlesSiminterface

Simulation handle returned by particles(); root entry point also exports this type.

interface ParticlesSim

Fields & related types

NameTypeRequiredDefaultMeaning
ForcePresetName (supporting, not exported by this entry point)'cells' | 'snakes' | 'orbitals' | 'viruses'——Literal names accepted as force selections. FORCE_PRESETS itself is not a public root or /particles export.
ForceMatrix (supporting, not exported by this entry point)readonly [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number]——A flat 4×4 matrix; lookup is mySpecies*4+otherSpecies. Obtain this type without a private-path import using Exclude<NonNullable<ParticlesConfig["forces"]>, string>.
SimMode (supporting, not exported by this entry point)'n2' | 'tiled' | 'grid'——Obtain through NonNullable<ParticlesConfig["mode"]>.

configreadonly property

Resolved initialization config, with live force selection updates.

readonly config: ResolvedConfig;

Parameters

NameTypeRequiredDefaultMeaning
countnumberYes—Integer particle count in 1..1_000_000. n2 mode rejects counts above 32_000 (its error text recommends at most 20_000). Device memory limits may be lower.
forcesForceMatrixYes—Resolved 16-number force matrix, updated by setForces().
mode'n2' | 'tiled' | 'grid'Yes—Neighbor algorithm: all-pairs, workgroup-tiled all-pairs, or spatial grid. The declaration comment saying tiled is the default is stale; implementation defaults to grid.
color'species' | 'velocity'Yes—Canvas coloring by four species or speed magnitude. Used when the renderer is attached.
bounds'wrap' | 'clamp'Yes—How updated positions remain in the square world: wrap or clamp. Interaction distances/neighborhood searches do not wrap across opposite edges.
seedstringYes—String(seed), retained from initialization.
rMaxnumberYes—Maximum interaction radius in world units. Use a finite positive number. Also affects grid resolution.
betanumberYes—Piecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API.
forceFactornumberYes—Acceleration scale: summed interactions are multiplied by forceFactor*rMax before integration.
frictionHalfLifenumberYes—Damping time parameter used as exp(-effectiveDt/frictionHalfLife). Despite the name, implementation does not include ln(2), so this is an exponential decay time constant rather than a mathematical half-life. Use a positive finite value.
dtnumberYes—Base simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically.
pointSizenumberYes—Normalized point-quad half-size used by the attached renderer, approximately in clip coordinates after world scaling. It is not a literal pixel size; shader generation rounds the scaled value to four decimals.
maxNeighborsnumberYes—Grid-only candidate budget: ceil(maxNeighbors/9) candidates per each of up to 9 neighboring cells (self may count). Use a finite positive number.
forcesNamestringYes—Selected literal force name, or 'custom'; updated by setForces().
seedHashnumberYes—32-bit hash of the normalized seed string.
frictionnumberYes—Initial exp(-dt/frictionHalfLife); not a live value after setParams or tick multipliers.

Returns

ResolvedConfig Internal supporting type reachable through ParticlesSim["config"]. The property is readonly, not a deeply immutable snapshot.

Behavior & constraints

  • setParams changes a separate internal physics object, so config.rMax/beta/forceFactor/frictionHalfLife/dt/friction may remain initialization values. snapshot() reads the current physics values.

Fields & related types

NameTypeRequiredDefaultMeaning
ResolvedConfig (supporting, not exported by this entry point){ count: number; forces: ForceMatrix; forcesName: string; mode: SimMode; color: "species" | "velocity"; bounds: "wrap" | "clamp"; seed: string; seedHash: number; rMax: number; beta: number; forceFactor: number; friction: number; frictionHalfLife: number; dt: number; pointSize: number; maxNeighbors: number }——All fields are required on resolved output. Do not mutate config directly to control the simulation.

attachmethod

Configure built-in particle rendering on one canvas.

attach(canvas: HTMLCanvasElement): Promise<void>;

Parameters

NameTypeRequiredDefaultMeaning
canvasHTMLCanvasElementYes—Canvas with positive CSS client dimensions, not already acquired by an incompatible drawing backend.

Returns

Promise<void> Resolves when the canvas renderer is ready.

Behavior & constraints

  • Sets backing width/height to max(1, floor(clientSize*min(devicePixelRatio||1,2))). Configures opaque WebGPU rendering. No automatic resize observer is installed.
  • Call once per simulation. A second call replaces the renderer reference without first destroying the previous renderer. attach does not start an animation loop.

Errors & failure cases

  • Rejects if canvas.getContext("webgpu") is null or rendering shader/pipeline initialization fails.

tickmethod

Advance one simulation step, optionally render it, and swap current state buffers.

tick(dtMultiplier?: number): void;

Parameters

NameTypeRequiredDefaultMeaning
dtMultipliernumberNo1Multiplier applied to current dt. 0 freezes physical evolution but still submits work/renders/swaps/counts a tick; fractional values slow simulation.

Returns

void No return value.

Behavior & constraints

  • Submits its own command encoder; this high-level API does not expose prepare/encode/endSubmit. Returns before GPU completion. Skip tick entirely to pause GPU work.
  • Integration uses effectiveDt=dt*dtMultiplier and damping exp(-effectiveDt/frictionHalfLife). It does not adapt to elapsed animation-frame time.

setForcesmethod

Replace the force matrix without recreating the simulation.

setForces(forces: ForcePresetName | 'random' | ForceMatrix): void;

Parameters

NameTypeRequiredDefaultMeaning
forcesForcePresetName | 'random' | ForceMatrixYes—Same force selection types as ParticlesConfig.forces. random reuses the original seed, so repeated calls produce the same matrix.

Returns

void No return value.

Behavior & constraints

  • Queues a write to the 16-f32 matrix buffer and updates config.forces/config.forcesName. It does not reset positions or velocities.

Errors & failure cases

  • Unknown force strings throw plain Error. Custom matrix component count/type issues may propagate from Buffer.write; do not pass arbitrary-length arrays.

setParamsmethod

Patch current physics parameters; omitted fields retain their current values.

setParams(params: {
  rMax?: number;
  beta?: number;
  forceFactor?: number;
  frictionHalfLife?: number;
  dt?: number;
}): void;

Parameters

NameTypeRequiredDefaultMeaning
params{ rMax?: number; beta?: number; forceFactor?: number; frictionHalfLife?: number; dt?: number }Yes—Partial physics update; all nested fields are optional.
params.rMaxnumberNounchanged when omittedMaximum interaction radius in world units. Use a finite positive number. Also affects grid resolution.
params.betanumberNounchanged when omittedPiecewise force-curve breakpoint at normalized distance d/rMax. Meaningful values are between 0 and 1; not validated by this API.
params.forceFactornumberNounchanged when omittedAcceleration scale: summed interactions are multiplied by forceFactor*rMax before integration.
params.frictionHalfLifenumberNounchanged when omittedDamping time parameter used as exp(-effectiveDt/frictionHalfLife). Despite the name, implementation does not include ln(2), so this is an exponential decay time constant rather than a mathematical half-life. Use a positive finite value.
params.dtnumberNounchanged when omittedBase simulation time step per tick, multiplied by the tick argument. The animation callback elapsed time is not measured automatically.

Returns

void No return value.

Behavior & constraints

  • No runtime numeric validation. Do not explicitly pass undefined for a field, because Object.assign would overwrite it.
  • If rMax changes grid resolution, an asynchronous rebuild starts; only the latest rebuild wins and old grid resources are replaced. No promise or completion callback is exposed; rebuild errors are not caught here.

snapshotmethod

Serialize selected current settings, not simulation state.

snapshot(): string;

Parameters

This call takes no arguments.

Returns

string JSON containing count, forces name, mode, color, bounds, seed, rMax, beta, forceFactor, frictionHalfLife, dt, pointSize.

Behavior & constraints

  • Omits particle buffers, maxNeighbors, and the values of custom force matrices. A custom matrix becomes forces:"custom", which particles() cannot resolve as a named matrix; this is not a complete round-trip checkpoint.

statsmethod

Read tick-frequency and uncaptured-error counters.

stats(): { fps: number; gpuErrors: number };

Parameters

This call takes no arguments.

Returns

{ fps: number; gpuErrors: number } fps starts at 0 and updates when accumulated wall time reaches about 500 ms. gpuErrors counts device uncapturederror events observed by this instance.

Fields & related types

NameTypeRequiredDefaultMeaning
fpsnumber——Ticks per elapsed wall-clock second, not GPU kernel duration or a benchmark score. Long pauses can affect the next sample.
gpuErrorsnumber——Shared-device uncaptured error count; events may originate from other work using that device.

debugGridoptional method

Expose grid-internal buffers for diagnostics only; undefined outside grid mode.

debugGrid?(): {
  partial: Buffer;
  start: Buffer;
  fill: Buffer;
  sortedPos: Buffer;
  sortedSp: Buffer;
  order: Buffer;
};

Parameters

This call takes no arguments.

Returns

{ partial: Buffer; start: Buffer; fill: Buffer; sortedPos: Buffer; sortedSp: Buffer; order: Buffer } Borrowed internal buffers, replaced by a later grid rebuild. Do not destroy them.

Fields & related types

NameTypeRequiredDefaultMeaning
partialBuffer (vec2f, count*9)——Per-particle per-neighbor-cell partial force contributions.
startBuffer (u32, cells)——Inclusive starting slot for each cell.
fillBuffer (u32, cells)——Exclusive end slot after scatter, not raw occupancy count.
sortedPosBuffer (vec2f, count)——Position copy grouped by cell.
sortedSpBuffer (u32, count)——Species indices grouped by cell.
orderBuffer (u32, count)——Original particle index at each sorted slot.

buffersmethod

Get borrowed buffers for the current simulation state.

buffers(): { pos: Buffer; vel: Buffer; species: Buffer };

Parameters

This call takes no arguments.

Returns

{ pos: Buffer; vel: Buffer; species: Buffer } pos/vel are count-element vec2f buffers; species is a count-element u32 buffer.

Behavior & constraints

  • pos and vel alternate after tick; call buffers() again for the latest side. CPU snapshots require await buffer.read(). The simulation owns these buffers.

Fields & related types

NameTypeRequiredDefaultMeaning
posBuffer (vec2f)——Current 2D world positions.
velBuffer (vec2f)——Current 2D velocities.
speciesBuffer (u32)——Species labels 0..3, independent of ping-pong state.

Examples

Obtain the current side after ticking, then read a snapshot.
sim.tick();
const { pos, vel, species } = sim.buffers();
const positions = await pos.read();
console.log(positions);

destroymethod

Release the simulation-owned particle, matrix, uniform, grid, and renderer resources handled by this implementation.

destroy(): void;

Parameters

This call takes no arguments.

Returns

void No return value.

Behavior & constraints

  • Cancel your animation loop and stop using borrowed buffers first. No automatic RAF cancellation, canvas unconfiguration, disposed-state guard, or error-listener removal is provided.
  • Avoid destroying while an asynchronous setParams grid rebuild is pending: 2.0.0 does not expose a way to await or cancel that rebuild.

Search concepts, APIs, and examples