Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Core type is `Module` in `packages/core/src/module.ts`:

- Modules declare:
- `name` (string literal, unique)
- `role`: `ModuleRole.Force` or `ModuleRole.Render`
- `role`: `ModuleRole.Force`, `ModuleRole.Render`, or `ModuleRole.Grid`
- `inputs`: map of input keys to `DataType.NUMBER` or `DataType.ARRAY`
- Modules implement both descriptors:
- `webgpu(): WebGPUDescriptor`
Expand All @@ -78,12 +78,20 @@ Render modules contribute passes:
- WebGPU: `RenderPassKind.Fullscreen` or `RenderPassKind.Compute` (optionally `instanced`)
- CPU: Canvas2D composition via `CPURenderDescriptor`

Grid modules:

- Declare a `gridSpec` (resolution + format + wrap mode) and run in a dedicated grid pipeline.
- Provide `init`/`step`/`post` (CPU + WebGPU WGSL) and can add render passes that read from grid buffers.
- The engine owns `getGrid(name)`/`setGrid(name, data)`; on WebGPU these are GPU readbacks/writes, so avoid in hot paths.
- Interop modules (`GridFieldForce`, `ParticleDepositGrid`) bridge particle ↔ grid workflows.

### Where to look when debugging WebGPU behavior

- Engine orchestrator: `packages/core/src/runtimes/webgpu/engine.ts`
- Resource plumbing: `packages/core/src/runtimes/webgpu/gpu-resources.ts`
- WGSL program build: `packages/core/src/runtimes/webgpu/module-registry.ts`
- Simulation concat/dispatch: `packages/core/src/runtimes/webgpu/simulation-pipeline.ts`
- Grid pipeline: `packages/core/src/runtimes/webgpu/grid-pipeline.ts`
- Local neighborhood query (avoids full readback): `packages/core/src/runtimes/webgpu/local-query.ts`
- Spatial grid: `packages/core/src/runtimes/webgpu/spacial-grid.ts` (typo is in filename/class)

Expand Down Expand Up @@ -131,4 +139,3 @@ If you need deeper narrative docs, start here:
- `docs/maintainer-guide.md` (core internals)
- `docs/playground-user-guide.md` (UI/tools/hotkeys)
- `docs/playground-maintainer-guide.md` (playground patterns)

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ A high-performance particle physics simulation system with interactive playgroun
- **High Performance**: Spatial grid optimization, configurable workgroup sizes, and efficient neighbor queries
- **Modular Force System**: Environment, boundary, collisions, behavior (flocking), fluid dynamics (SPH + PIC/FLIP), sensors, joints, interaction, and grab modules
- **Advanced Rendering**: Trails with decay/diffusion, particle instancing, line rendering, and multiple color modes
- **Grid Simulations**: Built-in grid modules (Game of Life, reaction-diffusion, elementary cellular automata)
- **Playground Sessions**: Save/load/share sessions (module settings, oscillators, and optional particles/joints)
- **Real-time Oscillators**: Animate any module parameter with configurable frequency and bounds
- **Interactive Playground**: React-based interface with undo/redo, hotkeys, and live parameter adjustment
Expand Down
37 changes: 37 additions & 0 deletions docs/maintainer-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ This document explains the internal architecture of the core library for contrib
- [`interfaces.ts`](../packages/core/src/interfaces.ts): `IEngine`, `IParticle`, `AbstractEngine` common logic (view, modules, config, oscillators, export/import, FPS)
- [`module.ts`](../packages/core/src/module.ts): `Module` base class, `ModuleRole`, `DataType`, and uniform plumbing
- [`modules/forces/*`](../packages/core/src/modules/forces/): built-in forces (environment, boundary, collisions, behavior, fluids, sensors, interaction, joints, grab)
- [`modules/grids/*`](../packages/core/src/modules/grids/): built-in grid simulations (Game of Life, reaction-diffusion, elementary CA)
- [`modules/render/*`](../packages/core/src/modules/render/): built-in render modules (particles, trails, lines)
- [`grid/*`](../packages/core/src/grid/): shared grid geometry + `GridStore` utilities used by CPU + WebGPU
- [`runtimes/cpu/*`](../packages/core/src/runtimes/cpu/): CPU engine and helpers (Canvas2D rendering, neighbor queries, descriptors)
- [`runtimes/webgpu/*`](../packages/core/src/runtimes/webgpu/): WebGPU engine and builders (GPU resources, program/pipeline builders, spatial grid, shaders)

Expand Down Expand Up @@ -77,6 +79,41 @@ Parallels the WebGPU phases with pure TypeScript:
- For force modules, both runtimes support the lifecycle hooks; render modules contribute render passes
- Arrays are supported and surfaced in WGSL via `getLength()` and indexed `getUniform()` access

### Grid modules and pipeline

Grid modules (`ModuleRole.Grid`) are for simulations that live on a cell lattice (Conway, reaction-diffusion, cellular automata). They have their own storage and update pipeline, but can interoperate with particles.

Key concepts:

- `gridSpec` lives on the module and describes the lattice:
- `width`/`height` cell resolution.
- `format` determines channel count (e.g. `r`, `rg`, `rgba`). Storage is currently float for both runtimes.
- `wrapMode` controls addressing (`Clamp` or `Repeat`).
- The engine holds one `GridStore` per grid module, with ping-pong buffers for read/write.
- `getGrid(name)` / `setGrid(name, data)` is part of the public engine API.
- On WebGPU these perform GPU ↔ CPU transfers; avoid in hot paths.

Pipeline timing:

- CPU: grid steps run before particle simulation by default. Each module gets:
- `init` (optional one-time seed), `step` (per-frame update), `post` (optional correction).
- `render` callbacks can read the grid for Canvas2D drawing.
- WebGPU: grid steps run in compute passes via `grid-pipeline.ts`:
- `init`/`step`/`post` are WGSL snippets per module.
- Each step ping-pongs read/write storage buffers.
- Grid modules can add render passes (fullscreen/compute) that bind grid buffers.

Interop with particles:

- `GridFieldForce` reads a grid field to apply per-particle forces.
- `ParticleDepositGrid` writes particle data into a grid.
- Interop modules must know which grid they target and attach its spec before WebGPU program build.

Relation to the spatial grid:

- The particle neighbor spatial grid is distinct from grid modules.
- Both share `GridGeometry` helpers for world↔cell conversions to keep math consistent across runtimes.

### Built-in module notes

- Environment: gravity/inertia/friction/damping; inward/outward/custom directions use grid/view transforms per runtime
Expand Down
66 changes: 64 additions & 2 deletions docs/module-author-guide.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
## Module Author Guide

This guide explains how to build your own modules for the engine. There are two public roles you can implement:
This guide explains how to build your own modules for the engine. There are three public roles you can implement:

- **Force**: runs in the simulation pipeline; can add to `acceleration`/`velocity` and perform constraints/corrections
- **Render**: runs in the rendering pipeline; can draw fullscreen, draw per-instance quads, or compute over the scene texture
- **Grid**: runs in the grid pipeline; updates a 2D cell field and may render directly

Modules should support both runtimes when possible:

Expand All @@ -17,7 +18,7 @@ If you only implement one runtime, the other will be unsupported on that module.
Create a TypeScript class extending `Module<Name, Inputs, StateKeys?>` and declare:

- `name`: string literal, globally unique
- `role`: `ModuleRole.Force` or `ModuleRole.Render`
- `role`: `ModuleRole.Force`, `ModuleRole.Render`, or `ModuleRole.Grid`
- `inputs`: a map of input names to `DataType.NUMBER` or `DataType.ARRAY`

The base class provides:
Expand Down Expand Up @@ -133,6 +134,67 @@ Examples in core:
- [`Trails`](../packages/core/src/modules/render/trails.ts): compute-like two-pass effect (decay + blur) or canvas equivalents on CPU
- [`Lines`](../packages/core/src/modules/render/lines.ts): instanced line quads on GPU, stroke lines on CPU

### Grid modules

Grid modules simulate 2D cellular fields (Game of Life, reaction-diffusion, etc.). They declare a `gridSpec` and implement grid lifecycle hooks:

- `init` (optional): initialize grid state
- `step` (required): advance grid state
- `post` (optional): post-process
- `render` (optional): render to the scene (fullscreen or compute pass)

CPU descriptor: `CPUGridDescriptor`
WebGPU descriptor: `WebGPUGridDescriptor`

Grid modules should set:

- `role = ModuleRole.Grid`
- `gridSpec` with:
- `width`/`height`: cell resolution
- `format`: channel layout (`r`, `rg`, or `rgba`) stored as floats
- `wrapMode`: `Clamp` or `Repeat` (addressing at edges)

The engine provides read/write buffers with ping-pong swap semantics.

CPU grid authoring:

- The `step` callback receives typed arrays for `read` and `write`. Treat them as flat arrays where channels are packed per cell.
- The `render` callback (if present) receives the `GridStore` so you can sample cells for Canvas2D drawing.

WebGPU grid authoring:

- The grid pipeline emits helper accessors to read/write grid cells using the module name.
- `init`/`step`/`post` are WGSL snippets executed in a compute pass that matches grid dimensions.
- Render passes can bind grid buffers; use the provided helpers to sample.

Interop with particles:

- If you want particles to read a grid, use `GridFieldForce` as a reference.
- If you want particles to write into a grid, use `ParticleDepositGrid` as a reference.
- Interop modules should expose a way to attach the target grid spec before WebGPU program build.

Performance and correctness:

- Avoid `getGrid()`/`setGrid()` in per-frame CPU hot paths on WebGPU (they trigger GPU ↔ CPU transfers).
- Keep grid sizes reasonable; 512×512×4 floats is already ~4 MB per buffer, and grids are ping-ponged.

### Particle ↔ grid interop modules

Two built-in force modules act as the interop bridge between particles and grids:

- `GridFieldForce`: samples a grid and applies a force to particles (e.g. flow fields, chemotaxis).
- `ParticleDepositGrid`: writes particle data into a grid (e.g. density/ink/temperature deposits).

Common real-world patterns:

- **Agent chemotaxis**: agents deposit a field and steer up its gradient.
- **Ink/smoke**: particles paint a grid and get pushed/repelled by its values.

Authoring notes:

- Interop modules must target a grid by name and attach its `gridSpec` before WebGPU program build.
- Use these modules as templates if you’re authoring a custom particle↔grid coupling module.

### Arrays and large inputs

- Declare array inputs with `DataType.ARRAY` (e.g., index lists for [`Lines`](../packages/core/src/modules/render/lines.ts)/[`Joints`](../packages/core/src/modules/forces/joints.ts)).
Expand Down
10 changes: 10 additions & 0 deletions docs/playground-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,16 @@ The INIT panel controls how particles are spawned when using the Restart button

Each module controls a different aspect of particle physics. Modules can be enabled/disabled and have adjustable parameters.

### Grid Modules

The playground also includes grid-based simulations:

- Game of Life
- Reaction Diffusion
- Elementary Cellular Automata

Enable them in the Modules panel to render grid-based simulations without particles.

### Environment

Global physics affecting all particles:
Expand Down
32 changes: 32 additions & 0 deletions docs/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ engine.play();
- **canvas**: HTMLCanvasElement used for rendering
- **forces**: `Module[]` list of force modules
- **render**: `Module[]` list of render modules
- **grids**: `Module[]` list of grid modules (optional)
- **runtime**: `"cpu" | "webgpu" | "auto"` (use "auto" for best experience)
- Optional: `constrainIterations`, `clearColor`, `cellSize`, `maxNeighbors`, `maxParticles`, `workgroupSize`

Expand All @@ -147,6 +148,7 @@ engine.play();
- **Modules**: `getModule(name)` returns the module instance by name
- **Serialization**: `export()` returns `{ [moduleName]: settings }`; `import(settings)` applies them
- **Oscillators**: see “Oscillators” below
- **Grids**: `getGrid(moduleName)` / `setGrid(moduleName, data)` for explicit grid read/write

Notes

Expand Down Expand Up @@ -209,6 +211,36 @@ Notes:
- `imageData` is required and must be provided synchronously.
- Fully transparent pixels are ignored; particle colors come from the image pixels.

### Grid modules

Grid modules simulate 2D cellular fields (e.g. Game of Life, reaction-diffusion). They can run without particles and render directly.

Built-in grid modules:

- `GameOfLifeGrid`
- `ReactionDiffusionGrid`
- `ElementaryCAGrid`

Interop modules:

- `GridFieldForce` (grid → particles)
- `ParticleDepositGrid` (particles → grid)

Example:

```ts
import { Engine, GameOfLifeGrid } from "@cazala/party";

const grid = new GameOfLifeGrid({ width: 256, height: 256 });
const engine = new Engine({
canvas,
forces: [],
render: [],
grids: [grid],
runtime: "auto",
});
```

#### Engine methods and lifecycles

- `initialize()`
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type EngineOptions = {
canvas: HTMLCanvasElement;
forces: Module<string, any>[];
render: Module<string, any>[];
grids?: Module<string, any>[];
runtime: "cpu" | "webgpu" | "auto";
constrainIterations?: number;
clearColor?: { r: number; g: number; b: number; a: number };
Expand Down Expand Up @@ -229,6 +230,12 @@ export class Engine implements IEngine {
getParticle(index: number): Promise<IParticle> {
return this.engine.getParticle(index);
}
getGrid(moduleName: string): Promise<ArrayBufferView> {
return this.engine.getGrid(moduleName);
}
setGrid(moduleName: string, data: ArrayBufferView): void {
this.engine.setGrid(moduleName, data);
}
getParticlesInRadius(
center: { x: number; y: number },
radius: number,
Expand Down Expand Up @@ -280,6 +287,9 @@ export class Engine implements IEngine {
import(settings: Record<string, Record<string, number>>): void {
this.engine.import(settings);
}
notifyModuleSettingsChanged(): void {
this.engine.notifyModuleSettingsChanged();
}

// Configuration getters and setters
getClearColor(): { r: number; g: number; b: number; a: number } {
Expand Down
88 changes: 88 additions & 0 deletions packages/core/src/grid/geometry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import type { ViewSnapshot } from "../view";

export type GridGeometryOptions = {
paddingRatio?: number;
};

export class GridGeometry {
private cellSize: number;
private paddingRatio: number;
private minX: number = 0;
private minY: number = 0;
private maxX: number = 0;
private maxY: number = 0;
private cols: number = 1;
private rows: number = 1;

constructor(cellSize: number, options: GridGeometryOptions = {}) {
this.cellSize = Math.max(0.0001, cellSize);
this.paddingRatio = options.paddingRatio ?? 0;
}

setCellSize(cellSize: number): void {
this.cellSize = Math.max(0.0001, cellSize);
}

getCellSize(): number {
return this.cellSize;
}

updateFromView(view: ViewSnapshot, options: GridGeometryOptions = {}): void {
const paddingRatio =
options.paddingRatio !== undefined
? options.paddingRatio
: this.paddingRatio;
const zoom = Math.max(view.zoom, 0.0001);
const halfW = view.width / (2 * zoom);
const halfH = view.height / (2 * zoom);
const padding = (Math.max(view.width, view.height) / zoom) * paddingRatio;

this.minX = view.cx - halfW - padding;
this.maxX = view.cx + halfW + padding;
this.minY = view.cy - halfH - padding;
this.maxY = view.cy + halfH + padding;

this.cols = Math.max(1, Math.ceil((this.maxX - this.minX) / this.cellSize));
this.rows = Math.max(1, Math.ceil((this.maxY - this.minY) / this.cellSize));
}

getBounds(): { minX: number; minY: number; maxX: number; maxY: number } {
return {
minX: this.minX,
minY: this.minY,
maxX: this.maxX,
maxY: this.maxY,
};
}

getDimensions(): { cols: number; rows: number; cellSize: number } {
return {
cols: this.cols,
rows: this.rows,
cellSize: this.cellSize,
};
}

worldToCell(
x: number,
y: number,
clamp: boolean = true
): { col: number; row: number } {
const col = Math.floor((x - this.minX) / this.cellSize);
const row = Math.floor((y - this.minY) / this.cellSize);
if (!clamp) return { col, row };
const clampedCol = Math.max(0, Math.min(col, this.cols - 1));
const clampedRow = Math.max(0, Math.min(row, this.rows - 1));
return { col: clampedCol, row: clampedRow };
}

cellToWorld(
col: number,
row: number,
center: boolean = true
): { x: number; y: number } {
const x = this.minX + col * this.cellSize + (center ? this.cellSize * 0.5 : 0);
const y = this.minY + row * this.cellSize + (center ? this.cellSize * 0.5 : 0);
return { x, y };
}
}
Loading
Loading