From 2564eea99984f684d96ea82ae6ff24752be20d51 Mon Sep 17 00:00:00 2001 From: Juan Cazala Date: Tue, 27 Jan 2026 22:34:08 -0300 Subject: [PATCH 1/2] feat: add grid module support with Game of Life, Reaction Diffusion, and Elementary Cellular Automata --- AGENTS.md | 11 +- README.md | 1 + docs/maintainer-guide.md | 37 +++ docs/module-author-guide.md | 49 +++- docs/playground-user-guide.md | 10 + docs/user-guide.md | 32 +++ packages/core/src/engine.ts | 7 + packages/core/src/grid/geometry.ts | 88 ++++++ packages/core/src/grid/store.ts | 111 ++++++++ packages/core/src/index.ts | 2 + packages/core/src/interfaces.ts | 13 +- packages/core/src/module.ts | 134 ++++++++- .../core/src/modules/forces/grid-field.ts | 87 ++++++ .../modules/forces/particle-deposit-grid.ts | 122 ++++++++ .../core/src/modules/grids/elementary-ca.ts | 172 ++++++++++++ .../core/src/modules/grids/game-of-life.ts | 177 ++++++++++++ .../src/modules/grids/reaction-diffusion.ts | 252 +++++++++++++++++ packages/core/src/modules/index.ts | 5 + packages/core/src/runtimes/cpu/engine.ts | 222 ++++++++++++--- .../core/src/runtimes/cpu/spatial-grid.ts | 78 +++--- .../src/runtimes/webgpu/builders/program.ts | 54 ++++ .../runtimes/webgpu/builders/render-pass.ts | 44 ++- packages/core/src/runtimes/webgpu/engine.ts | 154 +++++++++- .../core/src/runtimes/webgpu/gpu-resources.ts | 77 ++++- .../core/src/runtimes/webgpu/grid-pipeline.ts | 264 ++++++++++++++++++ .../src/runtimes/webgpu/module-registry.ts | 15 +- .../src/runtimes/webgpu/render-pipeline.ts | 79 +++++- .../runtimes/webgpu/simulation-pipeline.ts | 6 +- .../core/src/runtimes/webgpu/spacial-grid.ts | 47 ++-- .../src/components/ModulesSidebar.tsx | 57 ++++ .../components/modules/ElementaryCAModule.tsx | 20 ++ .../components/modules/GameOfLifeModule.tsx | 51 ++++ .../modules/ReactionDiffusionModule.tsx | 81 ++++++ packages/playground/src/constants/modules.ts | 3 + .../playground/src/contexts/EngineContext.tsx | 6 + .../playground/src/hooks/modules/index.ts | 3 + .../src/hooks/modules/useElementaryCA.ts | 54 ++++ .../src/hooks/modules/useGameOfLife.ts | 76 +++++ .../src/hooks/modules/useReactionDiffusion.ts | 101 +++++++ .../playground/src/hooks/useEngineInternal.ts | 67 +++++ .../src/slices/modules/elementaryCa.ts | 45 +++ .../src/slices/modules/gameOfLife.ts | 60 ++++ .../playground/src/slices/modules/index.ts | 21 ++ .../src/slices/modules/reactionDiffusion.ts | 75 +++++ packages/playground/src/slices/session.ts | 61 ++++ 45 files changed, 2971 insertions(+), 160 deletions(-) create mode 100644 packages/core/src/grid/geometry.ts create mode 100644 packages/core/src/grid/store.ts create mode 100644 packages/core/src/modules/forces/grid-field.ts create mode 100644 packages/core/src/modules/forces/particle-deposit-grid.ts create mode 100644 packages/core/src/modules/grids/elementary-ca.ts create mode 100644 packages/core/src/modules/grids/game-of-life.ts create mode 100644 packages/core/src/modules/grids/reaction-diffusion.ts create mode 100644 packages/core/src/runtimes/webgpu/grid-pipeline.ts create mode 100644 packages/playground/src/components/modules/ElementaryCAModule.tsx create mode 100644 packages/playground/src/components/modules/GameOfLifeModule.tsx create mode 100644 packages/playground/src/components/modules/ReactionDiffusionModule.tsx create mode 100644 packages/playground/src/hooks/modules/useElementaryCA.ts create mode 100644 packages/playground/src/hooks/modules/useGameOfLife.ts create mode 100644 packages/playground/src/hooks/modules/useReactionDiffusion.ts create mode 100644 packages/playground/src/slices/modules/elementaryCa.ts create mode 100644 packages/playground/src/slices/modules/gameOfLife.ts create mode 100644 packages/playground/src/slices/modules/reactionDiffusion.ts diff --git a/AGENTS.md b/AGENTS.md index 5a384c30..f1ab7af6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` @@ -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) @@ -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) - diff --git a/README.md b/README.md index 31b7f0be..e8fec585 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/maintainer-guide.md b/docs/maintainer-guide.md index d9c6a8b2..3b2553ce 100644 --- a/docs/maintainer-guide.md +++ b/docs/maintainer-guide.md @@ -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) @@ -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 diff --git a/docs/module-author-guide.md b/docs/module-author-guide.md index 0d5e0f6f..a1730987 100644 --- a/docs/module-author-guide.md +++ b/docs/module-author-guide.md @@ -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: @@ -17,7 +18,7 @@ If you only implement one runtime, the other will be unsupported on that module. Create a TypeScript class extending `Module` 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: @@ -133,6 +134,50 @@ 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. + ### 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)). diff --git a/docs/playground-user-guide.md b/docs/playground-user-guide.md index ef702c6b..d77be13a 100644 --- a/docs/playground-user-guide.md +++ b/docs/playground-user-guide.md @@ -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: diff --git a/docs/user-guide.md b/docs/user-guide.md index a05b3b25..4e09fcb8 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -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` @@ -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 @@ -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()` diff --git a/packages/core/src/engine.ts b/packages/core/src/engine.ts index b88b5308..da124f98 100644 --- a/packages/core/src/engine.ts +++ b/packages/core/src/engine.ts @@ -12,6 +12,7 @@ export type EngineOptions = { canvas: HTMLCanvasElement; forces: Module[]; render: Module[]; + grids?: Module[]; runtime: "cpu" | "webgpu" | "auto"; constrainIterations?: number; clearColor?: { r: number; g: number; b: number; a: number }; @@ -229,6 +230,12 @@ export class Engine implements IEngine { getParticle(index: number): Promise { return this.engine.getParticle(index); } + getGrid(moduleName: string): Promise { + return this.engine.getGrid(moduleName); + } + setGrid(moduleName: string, data: ArrayBufferView): void { + this.engine.setGrid(moduleName, data); + } getParticlesInRadius( center: { x: number; y: number }, radius: number, diff --git a/packages/core/src/grid/geometry.ts b/packages/core/src/grid/geometry.ts new file mode 100644 index 00000000..1bb043fd --- /dev/null +++ b/packages/core/src/grid/geometry.ts @@ -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 }; + } +} diff --git a/packages/core/src/grid/store.ts b/packages/core/src/grid/store.ts new file mode 100644 index 00000000..e5ce2c75 --- /dev/null +++ b/packages/core/src/grid/store.ts @@ -0,0 +1,111 @@ +import { GridSpec } from "../module"; + +export type GridBuffer = + | Uint8Array + | Int8Array + | Uint16Array + | Int16Array + | Float32Array; + +export function getGridChannelCount(spec: GridSpec): number { + if (spec.channels) return spec.channels; + switch (spec.format) { + case "vec2f": + return 2; + case "vec4f": + return 4; + default: + return 1; + } +} + +export function getGridBufferLength(spec: GridSpec): number { + const channels = getGridChannelCount(spec); + return Math.max(1, spec.width) * Math.max(1, spec.height) * channels; +} + +export function createGridBuffer(spec: GridSpec, length?: number): GridBuffer { + const size = length ?? getGridBufferLength(spec); + switch (spec.format) { + case "u8": + return new Uint8Array(size); + case "i8": + return new Int8Array(size); + case "u16": + return new Uint16Array(size); + case "i16": + return new Int16Array(size); + case "f16": + case "f32": + case "vec2f": + case "vec4f": + default: + return new Float32Array(size); + } +} + +export class GridStore { + readonly spec: GridSpec; + readonly width: number; + readonly height: number; + readonly channels: number; + readBuffer: GridBuffer; + writeBuffer: GridBuffer; + + constructor(spec: GridSpec) { + this.spec = spec; + this.width = Math.max(1, spec.width); + this.height = Math.max(1, spec.height); + this.channels = getGridChannelCount(spec); + const length = this.width * this.height * this.channels; + this.readBuffer = createGridBuffer(spec, length); + this.writeBuffer = createGridBuffer(spec, length); + } + + swap(): void { + const tmp = this.readBuffer; + this.readBuffer = this.writeBuffer; + this.writeBuffer = tmp; + } + + private resolveCoord( + v: number, + max: number, + wrap: GridSpec["wrap"] + ): number { + if (wrap === "repeat") { + const m = ((v % max) + max) % max; + return m; + } + if (wrap === "mirror") { + const period = max * 2; + const m = ((v % period) + period) % period; + return m < max ? m : period - 1 - m; + } + return Math.max(0, Math.min(v, max - 1)); + } + + index(x: number, y: number, channel: number = 0): number { + const wrap = this.spec.wrap ?? "clamp"; + const xx = this.resolveCoord(Math.floor(x), this.width, wrap); + const yy = this.resolveCoord(Math.floor(y), this.height, wrap); + const ch = Math.max(0, Math.min(channel, this.channels - 1)); + return (yy * this.width + xx) * this.channels + ch; + } + + read(x: number, y: number, channel: number = 0): number { + const idx = this.index(x, y, channel); + return (this.readBuffer as any)[idx] ?? 0; + } + + write(x: number, y: number, value: number | number[]): void { + const base = this.index(x, y, 0); + if (Array.isArray(value)) { + for (let c = 0; c < this.channels; c++) { + (this.writeBuffer as any)[base + c] = value[c] ?? 0; + } + return; + } + (this.writeBuffer as any)[base] = value; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3c6e6452..d530b341 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,3 +5,5 @@ export * from "./interfaces"; export * from "./modules"; export * from "./vector"; export * from "./oscillators"; +export * from "./grid/geometry"; +export * from "./grid/store"; diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts index 668198dc..072ab6ac 100644 --- a/packages/core/src/interfaces.ts +++ b/packages/core/src/interfaces.ts @@ -71,6 +71,8 @@ export interface IEngine { radius: number, opts?: GetParticlesInRadiusOptions ): Promise; + getGrid(moduleName: string): Promise; + setGrid(moduleName: string, data: ArrayBufferView): void; clear(): void; getCount(): number; getFPS(): number; @@ -164,6 +166,7 @@ export abstract class AbstractEngine implements IEngine { protected maxParticles: number | null = null; protected view: View; protected modules: Module[]; + protected gridModules: Module[]; protected maxSize: number = 0; protected oscillatorManager: OscillatorManager; @@ -171,13 +174,19 @@ export abstract class AbstractEngine implements IEngine { canvas: HTMLCanvasElement; forces: Module[]; render: Module[]; + grids?: Module[]; constrainIterations?: number; clearColor?: { r: number; g: number; b: number; a: number }; cellSize?: number; maxNeighbors?: number; }) { this.view = new View(options.canvas.width, options.canvas.height); - this.modules = [...options.forces, ...options.render]; + this.gridModules = options.grids ?? []; + this.modules = [ + ...options.forces, + ...options.render, + ...this.gridModules, + ]; this.constrainIterations = options.constrainIterations ?? 5; this.clearColor = options.clearColor ?? { r: 0, g: 0, b: 0, a: 1 }; this.cellSize = options.cellSize ?? 16; @@ -206,6 +215,8 @@ export abstract class AbstractEngine implements IEngine { abstract setParticles(p: IParticle[]): void; abstract getParticles(): Promise; abstract getParticle(index: number): Promise; + abstract getGrid(moduleName: string): Promise; + abstract setGrid(moduleName: string, data: ArrayBufferView): void; abstract getParticlesInRadius( center: { x: number; y: number }, radius: number, diff --git a/packages/core/src/module.ts b/packages/core/src/module.ts index 3edbf11f..675da76d 100644 --- a/packages/core/src/module.ts +++ b/packages/core/src/module.ts @@ -17,6 +17,7 @@ import { View } from "./view"; export enum ModuleRole { Force = "force", Render = "render", + Grid = "grid", } export enum DataType { @@ -24,6 +25,40 @@ export enum DataType { ARRAY = "array", } +export type GridFormat = + | "u8" + | "i8" + | "u16" + | "i16" + | "f16" + | "f32" + | "vec2f" + | "vec4f"; + +export type GridWrapMode = "clamp" | "repeat" | "mirror"; + +export type GridSpec = { + width: number; + height: number; + format: GridFormat; + channels?: 1 | 2 | 4; + cellSize?: number; + origin?: { x: number; y: number }; + wrap?: GridWrapMode; + followView?: boolean; +}; + +export type GridStoreLike = { + spec: GridSpec; + width: number; + height: number; + channels: number; + readBuffer: ArrayBufferView; + writeBuffer: ArrayBufferView; + read: (x: number, y: number, channel?: number) => number; + index: (x: number, y: number, channel?: number) => number; +}; + export abstract class Module< Name extends string = string, Inputs extends Record = Record< @@ -158,6 +193,49 @@ export interface WebGPUForceDescriptor< }) => string; } +export interface WebGPUGridDescriptor< + Inputs extends Record = Record< + string, + number | number[] + > +> { + globals?: (args: { + getUniform: (id: keyof Inputs, index?: number | string) => string; + getLength: (id: keyof Inputs) => string; + }) => string; + init?: (args: { + getUniform: (id: keyof Inputs, index?: number | string) => string; + getLength: (id: keyof Inputs) => string; + gridRead: string; + gridWrite: string; + cellIndexVar: string; + cellCoordVar: string; + widthVar: string; + heightVar: string; + }) => string; + step: (args: { + getUniform: (id: keyof Inputs, index?: number | string) => string; + getLength: (id: keyof Inputs) => string; + gridRead: string; + gridWrite: string; + cellIndexVar: string; + cellCoordVar: string; + widthVar: string; + heightVar: string; + }) => string; + post?: (args: { + getUniform: (id: keyof Inputs, index?: number | string) => string; + getLength: (id: keyof Inputs) => string; + gridRead: string; + gridWrite: string; + cellIndexVar: string; + cellCoordVar: string; + widthVar: string; + heightVar: string; + }) => string; + render?: WebGPURenderDescriptor; +} + export type FullscreenRenderPass< Inputs extends Record = Record< string, @@ -257,7 +335,10 @@ export type WebGPUDescriptor< number | number[] >, StateKeys extends string | number | symbol = string -> = WebGPUForceDescriptor | WebGPURenderDescriptor; +> = + | WebGPUForceDescriptor + | WebGPURenderDescriptor + | WebGPUGridDescriptor; export interface CPUForceDescriptor< Inputs extends Record = Record< @@ -285,6 +366,7 @@ export interface CPUForceDescriptor< width: number, height: number ) => ImageData | null; + getGrid?: (moduleName: string) => GridStoreLike | undefined; }) => void; apply?: (args: { particle: Particle; @@ -305,6 +387,7 @@ export interface CPUForceDescriptor< width: number, height: number ) => ImageData | null; + getGrid?: (moduleName: string) => GridStoreLike | undefined; }) => void; constrain?: (args: { particle: Particle; @@ -325,6 +408,7 @@ export interface CPUForceDescriptor< width: number, height: number ) => ImageData | null; + getGrid?: (moduleName: string) => GridStoreLike | undefined; }) => void; correct?: (args: { particle: Particle; @@ -347,7 +431,47 @@ export interface CPUForceDescriptor< width: number, height: number ) => ImageData | null; + getGrid?: (moduleName: string) => GridStoreLike | undefined; + }) => void; +} + +export interface CPUGridDescriptor< + Inputs extends Record = Record< + string, + number | number[] + > +> { + init?: (args: { + input: Inputs; + dt: number; + width: number; + height: number; + read: (x: number, y: number, channel?: number) => number; + write: (x: number, y: number, value: number | number[]) => void; + sample: (x: number, y: number, channel?: number) => number; + grid: GridStoreLike; + }) => void; + step: (args: { + input: Inputs; + dt: number; + width: number; + height: number; + read: (x: number, y: number, channel?: number) => number; + write: (x: number, y: number, value: number | number[]) => void; + sample: (x: number, y: number, channel?: number) => number; + grid: GridStoreLike; + }) => void; + post?: (args: { + input: Inputs; + dt: number; + width: number; + height: number; + read: (x: number, y: number, channel?: number) => number; + write: (x: number, y: number, value: number | number[]) => void; + sample: (x: number, y: number, channel?: number) => number; + grid: GridStoreLike; }) => void; + render?: CPURenderDescriptor; } export interface CPURenderUtils { @@ -393,6 +517,7 @@ export interface CPURenderDescriptor< clearColor: { r: number; g: number; b: number; a: number }; utils: CPURenderUtils; particles: Particle[]; + grid?: GridStoreLike; }) => void; // Optional per-particle rendering (called for each visible particle with transformed coordinates) @@ -404,6 +529,7 @@ export interface CPURenderDescriptor< screenSize: number; input: Inputs; utils: CPURenderUtils; + grid?: GridStoreLike; }) => void; // Optional teardown phase (called once per frame after all particles) @@ -411,6 +537,7 @@ export interface CPURenderDescriptor< context: CanvasRenderingContext2D; input: Inputs; utils: CPURenderUtils; + grid?: GridStoreLike; }) => void; } @@ -420,4 +547,7 @@ export type CPUDescriptor< number | number[] >, StateKeys extends string | number | symbol = string -> = CPUForceDescriptor | CPURenderDescriptor; +> = + | CPUForceDescriptor + | CPURenderDescriptor + | CPUGridDescriptor; diff --git a/packages/core/src/modules/forces/grid-field.ts b/packages/core/src/modules/forces/grid-field.ts new file mode 100644 index 00000000..18cea3a6 --- /dev/null +++ b/packages/core/src/modules/forces/grid-field.ts @@ -0,0 +1,87 @@ +import { + Module, + ModuleRole, + DataType, + type CPUDescriptor, + type WebGPUDescriptor, + type GridSpec, +} from "../../module"; + +export type GridFieldForceInputs = { + strength: number; +}; + +export type GridFieldForceOptions = { + gridModuleName: string; + strength?: number; +}; + +export class GridFieldForce extends Module< + "gridField", + GridFieldForceInputs +> { + readonly name = "gridField" as const; + readonly role = ModuleRole.Force; + readonly inputs = { + strength: DataType.NUMBER, + } as const; + private gridModuleName: string; + private gridSpec?: GridSpec; + + constructor(options: GridFieldForceOptions) { + super(); + this.gridModuleName = options.gridModuleName; + this.write({ + strength: options.strength ?? 1, + }); + } + + cpu(): CPUDescriptor { + return { + apply: ({ particle, input, getGrid }) => { + const grid = getGrid?.(this.gridModuleName); + if (!grid) return; + const spec = grid.spec; + const cellSize = spec.cellSize ?? 1; + const origin = spec.origin ?? { x: 0, y: 0 }; + const gx = Math.floor((particle.position.x - origin.x) / cellSize); + const gy = Math.floor((particle.position.y - origin.y) / cellSize); + const vx = + grid.read(gx, gy, 0) || 0; + const vy = + grid.channels >= 2 ? grid.read(gx, gy, 1) : vx; + particle.acceleration.x += vx * input.strength; + particle.acceleration.y += vy * input.strength; + }, + }; + } + + webgpu(): WebGPUDescriptor { + const gridSpec = this.gridSpec; + const cellSize = gridSpec?.cellSize ?? 1; + const originX = gridSpec?.origin?.x ?? 0; + const originY = gridSpec?.origin?.y ?? 0; + const channels = + gridSpec?.channels ?? + (gridSpec?.format === "vec2f" ? 2 : gridSpec?.format === "vec4f" ? 4 : 1); + return { + apply: ({ particleVar, getUniform }) => { + return ` +let gx = i32(floor((${particleVar}.position.x - ${originX}) / ${cellSize})); +let gy = i32(floor((${particleVar}.position.y - ${originY}) / ${cellSize})); +let vx = grid_${this.gridModuleName}_read(gx, gy, 0u); +let vy = ${channels >= 2 ? `grid_${this.gridModuleName}_read(gx, gy, 1u)` : `vx`}; +${particleVar}.acceleration += vec2(vx, vy) * ${getUniform("strength")}; +`; + }, + } as WebGPUDescriptor; + } + + getGridModuleName(): string { + return this.gridModuleName; + } + + attachGridSpec(spec: GridSpec): void { + this.gridSpec = spec; + } +} diff --git a/packages/core/src/modules/forces/particle-deposit-grid.ts b/packages/core/src/modules/forces/particle-deposit-grid.ts new file mode 100644 index 00000000..689a9196 --- /dev/null +++ b/packages/core/src/modules/forces/particle-deposit-grid.ts @@ -0,0 +1,122 @@ +import { + Module, + ModuleRole, + DataType, + type CPUDescriptor, + type WebGPUDescriptor, + type GridSpec, +} from "../../module"; + +export type ParticleDepositGridInputs = { + radius: number; + strength: number; + mode: number; // 0 = add, 1 = max, 2 = overwrite +}; + +export type ParticleDepositGridOptions = { + gridModuleName: string; + radius?: number; + strength?: number; + mode?: number; +}; + +export class ParticleDepositGrid extends Module< + "particleDepositGrid", + ParticleDepositGridInputs +> { + readonly name = "particleDepositGrid" as const; + readonly role = ModuleRole.Force; + readonly inputs = { + radius: DataType.NUMBER, + strength: DataType.NUMBER, + mode: DataType.NUMBER, + } as const; + private gridModuleName: string; + private gridSpec?: GridSpec; + + constructor(options: ParticleDepositGridOptions) { + super(); + this.gridModuleName = options.gridModuleName; + this.write({ + radius: options.radius ?? 4, + strength: options.strength ?? 1, + mode: options.mode ?? 0, + }); + } + + cpu(): CPUDescriptor { + return { + apply: ({ particle, input, getGrid }) => { + const grid = getGrid?.(this.gridModuleName); + if (!grid) return; + const spec = grid.spec; + const cellSize = spec.cellSize ?? 1; + const origin = spec.origin ?? { x: 0, y: 0 }; + const gx = Math.floor((particle.position.x - origin.x) / cellSize); + const gy = Math.floor((particle.position.y - origin.y) / cellSize); + const r = Math.max(0, Math.floor(input.radius / cellSize)); + const strength = input.strength; + const mode = Math.floor(input.mode); + for (let dy = -r; dy <= r; dy++) { + for (let dx = -r; dx <= r; dx++) { + const dxw = dx * cellSize; + const dyw = dy * cellSize; + if (dxw * dxw + dyw * dyw > input.radius * input.radius) continue; + const x = gx + dx; + const y = gy + dy; + const idx = grid.index(x, y, 0); + const buf = grid.readBuffer as any; + const prev = buf[idx] ?? 0; + let next = prev; + if (mode === 1) next = Math.max(prev, strength); + else if (mode === 2) next = strength; + else next = prev + strength; + buf[idx] = next; + } + } + }, + }; + } + + webgpu(): WebGPUDescriptor { + const gridSpec = this.gridSpec; + const cellSize = gridSpec?.cellSize ?? 1; + const originX = gridSpec?.origin?.x ?? 0; + const originY = gridSpec?.origin?.y ?? 0; + return { + apply: ({ particleVar, getUniform }) => { + return ` +let gx = i32(floor((${particleVar}.position.x - ${originX}) / ${cellSize})); +let gy = i32(floor((${particleVar}.position.y - ${originY}) / ${cellSize})); +let radius = ${getUniform("radius")}; +let strength = ${getUniform("strength")}; +let mode = i32(${getUniform("mode")}); +let r = i32(max(0.0, floor(radius / ${cellSize}))); +for (var dy: i32 = -r; dy <= r; dy = dy + 1) { + for (var dx: i32 = -r; dx <= r; dx = dx + 1) { + let dxw = f32(dx) * ${cellSize}; + let dyw = f32(dy) * ${cellSize}; + if (dxw * dxw + dyw * dyw > radius * radius) { continue; } + let x = gx + dx; + let y = gy + dy; + let prev = grid_${this.gridModuleName}_read(x, y, 0u); + var next = prev; + if (mode == 1) { next = max(prev, strength); } + else if (mode == 2) { next = strength; } + else { next = prev + strength; } + grid_${this.gridModuleName}_write(x, y, 0u, next); + } +} +`; + }, + } as WebGPUDescriptor; + } + + getGridModuleName(): string { + return this.gridModuleName; + } + + attachGridSpec(spec: GridSpec): void { + this.gridSpec = spec; + } +} diff --git a/packages/core/src/modules/grids/elementary-ca.ts b/packages/core/src/modules/grids/elementary-ca.ts new file mode 100644 index 00000000..07f8cf35 --- /dev/null +++ b/packages/core/src/modules/grids/elementary-ca.ts @@ -0,0 +1,172 @@ +import { + Module, + ModuleRole, + DataType, + type CPUDescriptor, + type WebGPUDescriptor, + RenderPassKind, + CanvasComposition, + type GridSpec, +} from "../../module"; + +export type ElementaryCAInputs = { + rule: number; +}; + +export const DEFAULT_ECA_RULE = 30; + +export type ElementaryCAOptions = { + width: number; + height: number; + rule?: number; +}; + +export class ElementaryCAGrid extends Module<"elementaryCA", ElementaryCAInputs> { + readonly name = "elementaryCA" as const; + readonly role = ModuleRole.Grid; + readonly inputs = { + rule: DataType.NUMBER, + } as const; + readonly gridSpec: GridSpec; + private renderCanvas?: HTMLCanvasElement; + private renderCtx?: CanvasRenderingContext2D; + private imageData?: ImageData; + + constructor(options: ElementaryCAOptions) { + super(); + this.gridSpec = { + width: options.width, + height: options.height, + format: "u8", + wrap: "clamp", + }; + this.write({ + rule: options.rule ?? DEFAULT_ECA_RULE, + }); + } + + cpu(): CPUDescriptor { + return { + init: ({ grid }) => { + const width = grid.width; + const height = grid.height; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const idx = y * width + x; + (grid.writeBuffer as any)[idx] = 0; + } + } + const mid = Math.floor(width / 2); + (grid.writeBuffer as any)[mid] = 1; + }, + step: ({ grid, input }) => { + const width = grid.width; + const height = grid.height; + const rule = Math.max(0, Math.min(128, Math.floor(input.rule))); + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + if (y === 0) { + const left = grid.read(x - 1, 0, 0) > 0 ? 1 : 0; + const center = grid.read(x, 0, 0) > 0 ? 1 : 0; + const right = grid.read(x + 1, 0, 0) > 0 ? 1 : 0; + const idx = (left << 2) | (center << 1) | right; + const bit = (rule >> idx) & 1; + (grid.writeBuffer as any)[x] = bit; + } else { + const above = grid.read(x, y - 1, 0) > 0 ? 1 : 0; + (grid.writeBuffer as any)[y * width + x] = above; + } + } + } + }, + render: { + composition: CanvasComposition.HandlesBackground, + setup: ({ context, grid }) => { + if (!grid) return; + if (!this.renderCanvas) { + this.renderCanvas = document.createElement("canvas"); + this.renderCtx = this.renderCanvas.getContext("2d")!; + } + if ( + this.renderCanvas.width !== grid.width || + this.renderCanvas.height !== grid.height + ) { + this.renderCanvas.width = grid.width; + this.renderCanvas.height = grid.height; + this.imageData = this.renderCtx!.createImageData( + grid.width, + grid.height + ); + } + if (!this.imageData) return; + const data = this.imageData.data; + const buf = grid.readBuffer as any; + const total = grid.width * grid.height; + for (let i = 0; i < total; i++) { + const v = buf[i] > 0 ? 255 : 0; + const idx = i * 4; + data[idx + 0] = v; + data[idx + 1] = v; + data[idx + 2] = v; + data[idx + 3] = 255; + } + this.renderCtx!.putImageData(this.imageData, 0, 0); + context.drawImage( + this.renderCanvas, + 0, + 0, + context.canvas.width, + context.canvas.height + ); + }, + }, + }; + } + + webgpu(): WebGPUDescriptor { + return { + init: ({ cellCoordVar, widthVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +let mid = i32(${widthVar} / 2u); +let v = select(0.0, 1.0, y == 0 && x == mid); +grid_write(x, y, 0u, v); +`; + }, + step: ({ getUniform, cellCoordVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +let rule = u32(${getUniform("rule")}); +if (y == 0) { + let left = grid_read(x - 1, 0, 0u) > 0.5; + let center = grid_read(x, 0, 0u) > 0.5; + let right = grid_read(x + 1, 0, 0u) > 0.5; + let idx = (u32(left) << 2u) | (u32(center) << 1u) | u32(right); + let bit = (rule >> idx) & 1u; + grid_write(x, 0, 0u, f32(bit)); +} else { + let above = grid_read(x, y - 1, 0u); + grid_write(x, y, 0u, above); +} +`; + }, + render: { + passes: [ + { + kind: RenderPassKind.Fullscreen, + bindings: [], + fragment: () => `{ + let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); + let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); + let v = grid_read(gx, gy, 0u); + return vec4(v, v, v, 1.0); +}`, + }, + ], + }, + } as WebGPUDescriptor; + } +} diff --git a/packages/core/src/modules/grids/game-of-life.ts b/packages/core/src/modules/grids/game-of-life.ts new file mode 100644 index 00000000..2895798b --- /dev/null +++ b/packages/core/src/modules/grids/game-of-life.ts @@ -0,0 +1,177 @@ +import { + Module, + ModuleRole, + DataType, + type CPUDescriptor, + type WebGPUDescriptor, + RenderPassKind, + CanvasComposition, + type GridSpec, +} from "../../module"; + +export type GameOfLifeInputs = { + birthMask: number; + surviveMask: number; + seedDensity: number; +}; + +export const DEFAULT_GOL_BIRTH_MASK = 1 << 3; +export const DEFAULT_GOL_SURVIVE_MASK = (1 << 2) | (1 << 3); +export const DEFAULT_GOL_SEED_DENSITY = 0.15; + +export type GameOfLifeOptions = { + width: number; + height: number; + seedDensity?: number; +}; + +export class GameOfLifeGrid extends Module<"gameOfLife", GameOfLifeInputs> { + readonly name = "gameOfLife" as const; + readonly role = ModuleRole.Grid; + readonly inputs = { + birthMask: DataType.NUMBER, + surviveMask: DataType.NUMBER, + seedDensity: DataType.NUMBER, + } as const; + readonly gridSpec: GridSpec; + private renderCanvas?: HTMLCanvasElement; + private renderCtx?: CanvasRenderingContext2D; + private imageData?: ImageData; + + constructor(options: GameOfLifeOptions) { + super(); + this.gridSpec = { + width: options.width, + height: options.height, + format: "u8", + wrap: "clamp", + }; + this.write({ + birthMask: DEFAULT_GOL_BIRTH_MASK, // B3 + surviveMask: DEFAULT_GOL_SURVIVE_MASK, // S23 + seedDensity: options.seedDensity ?? DEFAULT_GOL_SEED_DENSITY, + }); + } + + cpu(): CPUDescriptor { + return { + init: ({ grid, input }) => { + const total = grid.width * grid.height; + for (let i = 0; i < total; i++) { + (grid.writeBuffer as any)[i] = + Math.random() < input.seedDensity ? 1 : 0; + } + }, + step: ({ grid, input }) => { + const width = grid.width; + const height = grid.height; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let count = 0; + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + if (dx === 0 && dy === 0) continue; + const v = grid.read(x + dx, y + dy, 0); + if (v > 0) count++; + } + } + const alive = grid.read(x, y, 0) > 0 ? 1 : 0; + const mask = alive ? input.surviveMask : input.birthMask; + const next = (mask >> count) & 1; + (grid.writeBuffer as any)[(y * width + x)] = next; + } + } + }, + render: { + composition: CanvasComposition.HandlesBackground, + setup: ({ context, grid }) => { + if (!grid) return; + if (!this.renderCanvas) { + this.renderCanvas = document.createElement("canvas"); + this.renderCtx = this.renderCanvas.getContext("2d")!; + } + if ( + this.renderCanvas.width !== grid.width || + this.renderCanvas.height !== grid.height + ) { + this.renderCanvas.width = grid.width; + this.renderCanvas.height = grid.height; + this.imageData = this.renderCtx!.createImageData( + grid.width, + grid.height + ); + } + if (!this.imageData) return; + const data = this.imageData.data; + const buf = grid.readBuffer as any; + const total = grid.width * grid.height; + for (let i = 0; i < total; i++) { + const v = buf[i] > 0 ? 255 : 0; + const idx = i * 4; + data[idx + 0] = v; + data[idx + 1] = v; + data[idx + 2] = v; + data[idx + 3] = 255; + } + this.renderCtx!.putImageData(this.imageData, 0, 0); + context.drawImage( + this.renderCanvas, + 0, + 0, + context.canvas.width, + context.canvas.height + ); + }, + }, + }; + } + + webgpu(): WebGPUDescriptor { + return { + init: ({ cellCoordVar, widthVar, heightVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +let cx = i32(${widthVar} / 2u); +let cy = i32(${heightVar} / 2u); +let alive = select(0.0, 1.0, x == cx && y == cy); +grid_write(x, y, 0u, alive); +`; + }, + step: ({ getUniform, cellCoordVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +var count: u32 = 0u; +for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + if (dx == 0 && dy == 0) { continue; } + let v = grid_read(x + dx, y + dy, 0u); + if (v > 0.5) { count = count + 1u; } + } +} +let alive = grid_read(x, y, 0u) > 0.5; +let birthMask = u32(${getUniform("birthMask")}); +let surviveMask = u32(${getUniform("surviveMask")}); +let mask = select(birthMask, surviveMask, alive); +let bit = (mask >> count) & 1u; +grid_write(x, y, 0u, f32(bit)); +`; + }, + render: { + passes: [ + { + kind: RenderPassKind.Fullscreen, + bindings: [], + fragment: () => `{ + let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); + let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); + let v = grid_read(gx, gy, 0u); + return vec4(v, v, v, 1.0); +}`, + }, + ], + }, + } as WebGPUDescriptor; + } +} diff --git a/packages/core/src/modules/grids/reaction-diffusion.ts b/packages/core/src/modules/grids/reaction-diffusion.ts new file mode 100644 index 00000000..82fc900b --- /dev/null +++ b/packages/core/src/modules/grids/reaction-diffusion.ts @@ -0,0 +1,252 @@ +import { + Module, + ModuleRole, + DataType, + type CPUDescriptor, + type WebGPUDescriptor, + RenderPassKind, + CanvasComposition, + type GridSpec, +} from "../../module"; + +export type ReactionDiffusionInputs = { + feed: number; + kill: number; + diffusionA: number; + diffusionB: number; + dt: number; +}; + +export const DEFAULT_RD_FEED = 0.0367; +export const DEFAULT_RD_KILL = 0.0649; +export const DEFAULT_RD_DIFFUSION_A = 1.0; +export const DEFAULT_RD_DIFFUSION_B = 0.5; +export const DEFAULT_RD_DT = 1.0; + +export type ReactionDiffusionOptions = { + width: number; + height: number; +}; + +export class ReactionDiffusionGrid extends Module< + "reactionDiffusion", + ReactionDiffusionInputs +> { + readonly name = "reactionDiffusion" as const; + readonly role = ModuleRole.Grid; + readonly inputs = { + feed: DataType.NUMBER, + kill: DataType.NUMBER, + diffusionA: DataType.NUMBER, + diffusionB: DataType.NUMBER, + dt: DataType.NUMBER, + } as const; + readonly gridSpec: GridSpec; + private renderCanvas?: HTMLCanvasElement; + private renderCtx?: CanvasRenderingContext2D; + private imageData?: ImageData; + + constructor(options: ReactionDiffusionOptions) { + super(); + this.gridSpec = { + width: options.width, + height: options.height, + format: "vec2f", + wrap: "repeat", + }; + this.write({ + feed: DEFAULT_RD_FEED, + kill: DEFAULT_RD_KILL, + diffusionA: DEFAULT_RD_DIFFUSION_A, + diffusionB: DEFAULT_RD_DIFFUSION_B, + dt: DEFAULT_RD_DT, + }); + } + + cpu(): CPUDescriptor { + return { + init: ({ grid }) => { + const width = grid.width; + const height = grid.height; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const idx = (y * width + x) * grid.channels; + (grid.writeBuffer as any)[idx + 0] = 1; + (grid.writeBuffer as any)[idx + 1] = 0; + } + } + const cx = Math.floor(width / 2); + const cy = Math.floor(height / 2); + const r = Math.max(2, Math.floor(Math.min(width, height) * 0.05)); + for (let y = -r; y <= r; y++) { + for (let x = -r; x <= r; x++) { + if (x * x + y * y > r * r) continue; + const gx = cx + x; + const gy = cy + y; + if (gx < 0 || gx >= width || gy < 0 || gy >= height) continue; + const idx = (gy * width + gx) * grid.channels; + (grid.writeBuffer as any)[idx + 1] = 1; + } + } + }, + step: ({ grid, input }) => { + const width = grid.width; + const height = grid.height; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const a = grid.read(x, y, 0); + const b = grid.read(x, y, 1); + const lapA = + -a + + 0.2 * + (grid.read(x + 1, y, 0) + + grid.read(x - 1, y, 0) + + grid.read(x, y + 1, 0) + + grid.read(x, y - 1, 0)) + + 0.05 * + (grid.read(x + 1, y + 1, 0) + + grid.read(x - 1, y + 1, 0) + + grid.read(x + 1, y - 1, 0) + + grid.read(x - 1, y - 1, 0)); + const lapB = + -b + + 0.2 * + (grid.read(x + 1, y, 1) + + grid.read(x - 1, y, 1) + + grid.read(x, y + 1, 1) + + grid.read(x, y - 1, 1)) + + 0.05 * + (grid.read(x + 1, y + 1, 1) + + grid.read(x - 1, y + 1, 1) + + grid.read(x + 1, y - 1, 1) + + grid.read(x - 1, y - 1, 1)); + + const reaction = a * b * b; + const newA = + a + + (input.diffusionA * lapA - reaction + input.feed * (1 - a)) * + input.dt; + const newB = + b + + (input.diffusionB * lapB + + reaction - + (input.kill + input.feed) * b) * + input.dt; + + const idx = (y * width + x) * grid.channels; + (grid.writeBuffer as any)[idx + 0] = newA; + (grid.writeBuffer as any)[idx + 1] = newB; + } + } + }, + render: { + composition: CanvasComposition.HandlesBackground, + setup: ({ context, grid }) => { + if (!grid) return; + if (!this.renderCanvas) { + this.renderCanvas = document.createElement("canvas"); + this.renderCtx = this.renderCanvas.getContext("2d")!; + } + if ( + this.renderCanvas.width !== grid.width || + this.renderCanvas.height !== grid.height + ) { + this.renderCanvas.width = grid.width; + this.renderCanvas.height = grid.height; + this.imageData = this.renderCtx!.createImageData( + grid.width, + grid.height + ); + } + if (!this.imageData) return; + const data = this.imageData.data; + const buf = grid.readBuffer as any; + const total = grid.width * grid.height; + for (let i = 0; i < total; i++) { + const idx = i * grid.channels; + const a = buf[idx + 0]; + const b = buf[idx + 1]; + const v = Math.max(0, Math.min(1, b - a + 1)); + const c = Math.floor(v * 255); + const di = i * 4; + data[di + 0] = c; + data[di + 1] = c; + data[di + 2] = c; + data[di + 3] = 255; + } + this.renderCtx!.putImageData(this.imageData, 0, 0); + context.drawImage( + this.renderCanvas, + 0, + 0, + context.canvas.width, + context.canvas.height + ); + }, + }, + }; + } + + webgpu(): WebGPUDescriptor { + return { + init: ({ cellCoordVar, widthVar, heightVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +grid_write(x, y, 0u, 1.0); +grid_write(x, y, 1u, 0.0); +let cx = i32(${widthVar} / 2u); +let cy = i32(${heightVar} / 2u); +let dx = x - cx; +let dy = y - cy; +let r = i32(min(${widthVar}, ${heightVar})) / 20; +if (dx * dx + dy * dy <= r * r) { + grid_write(x, y, 1u, 1.0); +} +`; + }, + step: ({ getUniform, cellCoordVar }) => { + return ` +let x = i32(${cellCoordVar}.x); +let y = i32(${cellCoordVar}.y); +let a = grid_read(x, y, 0u); +let b = grid_read(x, y, 1u); +let lapA = + -a + + 0.2 * (grid_read(x + 1, y, 0u) + grid_read(x - 1, y, 0u) + grid_read(x, y + 1, 0u) + grid_read(x, y - 1, 0u)) + + 0.05 * (grid_read(x + 1, y + 1, 0u) + grid_read(x - 1, y + 1, 0u) + grid_read(x + 1, y - 1, 0u) + grid_read(x - 1, y - 1, 0u)); +let lapB = + -b + + 0.2 * (grid_read(x + 1, y, 1u) + grid_read(x - 1, y, 1u) + grid_read(x, y + 1, 1u) + grid_read(x, y - 1, 1u)) + + 0.05 * (grid_read(x + 1, y + 1, 1u) + grid_read(x - 1, y + 1, 1u) + grid_read(x + 1, y - 1, 1u) + grid_read(x - 1, y - 1, 1u)); +let reaction = a * b * b; +let feed = ${getUniform("feed")}; +let kill = ${getUniform("kill")}; +let diffA = ${getUniform("diffusionA")}; +let diffB = ${getUniform("diffusionB")}; +let dt = ${getUniform("dt")}; +let newA = a + (diffA * lapA - reaction + feed * (1.0 - a)) * dt; +let newB = b + (diffB * lapB + reaction - (kill + feed) * b) * dt; +grid_write(x, y, 0u, newA); +grid_write(x, y, 1u, newB); +`; + }, + render: { + passes: [ + { + kind: RenderPassKind.Fullscreen, + bindings: [], + fragment: () => `{ + let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); + let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); + let a = grid_read(gx, gy, 0u); + let b = grid_read(gx, gy, 1u); + let v = clamp(b - a + 1.0, 0.0, 1.0); + return vec4(v, v, v, 1.0); +}`, + }, + ], + }, + } as WebGPUDescriptor; + } +} diff --git a/packages/core/src/modules/index.ts b/packages/core/src/modules/index.ts index b9bc2e96..a42d98ec 100644 --- a/packages/core/src/modules/index.ts +++ b/packages/core/src/modules/index.ts @@ -7,6 +7,11 @@ export * from "./forces/sensors"; export * from "./forces/interaction"; export * from "./forces/joints"; export * from "./forces/grab"; +export * from "./forces/grid-field"; +export * from "./forces/particle-deposit-grid"; export * from "./render/trails"; export * from "./render/lines"; export * from "./render/particles"; +export * from "./grids/game-of-life"; +export * from "./grids/reaction-diffusion"; +export * from "./grids/elementary-ca"; diff --git a/packages/core/src/runtimes/cpu/engine.ts b/packages/core/src/runtimes/cpu/engine.ts index 95798598..35805b7c 100644 --- a/packages/core/src/runtimes/cpu/engine.ts +++ b/packages/core/src/runtimes/cpu/engine.ts @@ -11,10 +11,13 @@ import { CanvasComposition, CPURenderDescriptor, CPUForceDescriptor, + CPUGridDescriptor, + GridSpec, } from "../../module"; import { SpatialGrid } from "./spatial-grid"; import { Particle } from "../../particle"; import { Vector } from "../../vector"; +import { GridStore } from "../../grid/store"; export class CPUEngine extends AbstractEngine { private particles: Particle[] = []; @@ -22,11 +25,14 @@ export class CPUEngine extends AbstractEngine { private grid: SpatialGrid; private animationId: number | null = null; private particleIdToIndex: Map = new Map(); + private gridStores: Map = new Map(); + private gridInitialized: Set = new Set(); constructor(options: { canvas: HTMLCanvasElement; forces: Module[]; render: Module[]; + grids?: Module[]; constrainIterations?: number; clearColor?: { r: number; g: number; b: number; a: number }; cellSize?: number; @@ -41,6 +47,7 @@ export class CPUEngine extends AbstractEngine { } initialize(): Promise { + this.setupGridStores(); return Promise.resolve(); } @@ -97,6 +104,11 @@ export class CPUEngine extends AbstractEngine { // Reset maxSize tracking this.resetMaxSize(); this.particleIdToIndex.clear(); + for (const store of this.gridStores.values()) { + (store.readBuffer as any).fill(0); + (store.writeBuffer as any).fill(0); + } + this.gridInitialized.clear(); } getCount(): number { @@ -159,6 +171,30 @@ export class CPUEngine extends AbstractEngine { return Promise.resolve(this.particles[index]); } + getGrid(moduleName: string): Promise { + const store = this.gridStores.get(moduleName); + if (!store) { + return Promise.reject(new Error(`Grid module not found: ${moduleName}`)); + } + const buffer = store.readBuffer as any; + return Promise.resolve(buffer.slice ? buffer.slice() : buffer); + } + + setGrid(moduleName: string, data: ArrayBufferView): void { + const store = this.gridStores.get(moduleName); + if (!store) return; + const target = store.readBuffer as any; + const src = data as any; + const len = Math.min(target.length ?? 0, src.length ?? 0); + for (let i = 0; i < len; i++) { + target[i] = src[i]; + } + const targetWrite = store.writeBuffer as any; + for (let i = 0; i < len; i++) { + targetWrite[i] = src[i]; + } + } + async getParticlesInRadius( center: { x: number; y: number }, radius: number, @@ -297,6 +333,8 @@ export class CPUEngine extends AbstractEngine { private update(dt: number): void { const effectiveCount = this.getEffectiveCount(); + + this.stepGrids(dt); // Update spatial grid with current particle positions and camera this.grid.setCamera( @@ -368,6 +406,7 @@ export class CPUEngine extends AbstractEngine { index: pi, particles: this.particles, getImageData, + getGrid: (name: string) => this.gridStores.get(name), }); } } @@ -409,6 +448,7 @@ export class CPUEngine extends AbstractEngine { index: pi, particles: this.particles, getImageData, + getGrid: (name: string) => this.gridStores.get(name), }); } } @@ -467,6 +507,7 @@ export class CPUEngine extends AbstractEngine { index: pi, particles: this.particles, getImageData, + getGrid: (name: string) => this.gridStores.get(name), }); } } @@ -521,6 +562,7 @@ export class CPUEngine extends AbstractEngine { index, particles: this.particles, getImageData, + getGrid: (name: string) => this.gridStores.get(name), }); } } @@ -582,25 +624,38 @@ export class CPUEngine extends AbstractEngine { // Check composition requirements of enabled render modules const hasBackgroundHandler = this.modules.some((module) => { - if (!module.isEnabled() || module.role !== ModuleRole.Render) - return false; - const descriptor = module.cpu() as CPURenderDescriptor; - return descriptor.composition === CanvasComposition.HandlesBackground; + if (!module.isEnabled()) return false; + const descriptor = + module.role === ModuleRole.Render + ? (module.cpu() as CPURenderDescriptor) + : module.role === ModuleRole.Grid + ? (module.cpu() as CPUGridDescriptor).render + : undefined; + return descriptor?.composition === CanvasComposition.HandlesBackground; }); // Determine if there are any enabled renderers - const hasEnabledRenderer = this.modules.some( - (module) => module.isEnabled() && module.role === ModuleRole.Render - ); + const hasEnabledRenderer = this.modules.some((module) => { + if (!module.isEnabled()) return false; + if (module.role === ModuleRole.Render) return true; + if (module.role === ModuleRole.Grid) { + return !!(module.cpu() as CPUGridDescriptor).render; + } + return false; + }); // Only clear canvas if no module handles background AND either some module requires clearing // or there are no enabled renderers (to avoid leaving a stale frame on canvas) if (!hasBackgroundHandler) { const needsClearing = this.modules.some((module) => { - if (!module.isEnabled() || module.role !== ModuleRole.Render) - return false; - const descriptor = module.cpu() as CPURenderDescriptor; - return descriptor.composition === CanvasComposition.RequiresClear; + if (!module.isEnabled()) return false; + const descriptor = + module.role === ModuleRole.Render + ? (module.cpu() as CPURenderDescriptor) + : module.role === ModuleRole.Grid + ? (module.cpu() as CPUGridDescriptor).render + : undefined; + return descriptor?.composition === CanvasComposition.RequiresClear; }); if (needsClearing || !hasEnabledRenderer) { @@ -615,9 +670,15 @@ export class CPUEngine extends AbstractEngine { try { // Skip disabled modules if (!module.isEnabled()) continue; - if (module.role === ModuleRole.Render) { - const descriptor = module.cpu() as CPURenderDescriptor; - const render = descriptor; + const isGridModule = module.role === ModuleRole.Grid; + const renderDescriptor = + module.role === ModuleRole.Render + ? (module.cpu() as CPURenderDescriptor) + : module.role === ModuleRole.Grid + ? (module.cpu() as CPUGridDescriptor).render + : undefined; + if (renderDescriptor) { + const render = renderDescriptor; // input const input: Record = {}; for (const key of Object.keys(module.inputs)) { @@ -626,6 +687,7 @@ export class CPUEngine extends AbstractEngine { } // Always add enabled input.enabled = module.isEnabled() ? 1 : 0; + const gridStore = isGridModule ? this.gridStores.get(module.name) : undefined; // Setup phase render.setup?.({ @@ -635,40 +697,44 @@ export class CPUEngine extends AbstractEngine { clearColor: this.clearColor, utils, particles: this.particles, + grid: gridStore, }); - // Render each visible particle - const effectiveCount = this.getEffectiveCount(); - for (let i = 0; i < effectiveCount; i++) { - const particle = this.particles[i]; - if (particle.mass == 0) continue; - - // Transform world position to screen position - const worldX = (particle.position.x - camera.x) * zoom; - const worldY = (particle.position.y - camera.y) * zoom; - const screenX = centerX + worldX; - const screenY = centerY + worldY; - const screenSize = particle.size * zoom; - - // Skip rendering if particle is outside canvas bounds (culling) - if ( - screenX + screenSize < 0 || - screenX - screenSize > size.width || - screenY + screenSize < 0 || - screenY - screenSize > size.height - ) { - continue; - } + if (!isGridModule) { + // Render each visible particle + const effectiveCount = this.getEffectiveCount(); + for (let i = 0; i < effectiveCount; i++) { + const particle = this.particles[i]; + if (particle.mass == 0) continue; + + // Transform world position to screen position + const worldX = (particle.position.x - camera.x) * zoom; + const worldY = (particle.position.y - camera.y) * zoom; + const screenX = centerX + worldX; + const screenY = centerY + worldY; + const screenSize = particle.size * zoom; + + // Skip rendering if particle is outside canvas bounds (culling) + if ( + screenX + screenSize < 0 || + screenX - screenSize > size.width || + screenY + screenSize < 0 || + screenY - screenSize > size.height + ) { + continue; + } - render.render?.({ - context, - particle, - screenX, - screenY, - screenSize, - input, - utils, - }); + render.render?.({ + context, + particle, + screenX, + screenY, + screenSize, + input, + utils, + grid: gridStore, + }); + } } // Teardown phase @@ -676,9 +742,75 @@ export class CPUEngine extends AbstractEngine { context, input, utils, + grid: gridStore, }); } } catch (error) {} } } + + private setupGridStores(): void { + this.gridStores.clear(); + this.gridInitialized.clear(); + for (const module of this.gridModules) { + if (module.role !== ModuleRole.Grid) continue; + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + this.gridStores.set(module.name, new GridStore(spec)); + } + for (const module of this.modules) { + const attach = (module as unknown as { attachGridSpec?: (spec: GridSpec) => void }).attachGridSpec; + const getName = (module as unknown as { getGridModuleName?: () => string }).getGridModuleName; + if (!attach || !getName) continue; + const gridName = getName.call(module); + const store = this.gridStores.get(gridName); + if (store) attach.call(module, store.spec); + } + } + + private stepGrids(dt: number): void { + for (const module of this.gridModules) { + try { + if (!module.isEnabled()) continue; + if (module.role !== ModuleRole.Grid) continue; + const descriptor = module.cpu() as CPUGridDescriptor; + if (!descriptor || !descriptor.step) continue; + const store = this.gridStores.get(module.name); + if (!store) continue; + const input: Record = {}; + for (const key of Object.keys(module.inputs)) { + const value = module.read()[key]; + input[key] = value ?? 0; + } + input.enabled = module.isEnabled() ? 1 : 0; + + const ctx = { + input: input as any, + dt, + width: store.width, + height: store.height, + read: (x: number, y: number, channel?: number) => + store.read(x, y, channel), + write: (x: number, y: number, value: number | number[]) => + store.write(x, y, value), + sample: (x: number, y: number, channel?: number) => + store.read(x, y, channel), + grid: store, + }; + + if (!this.gridInitialized.has(module.name)) { + descriptor.init?.(ctx); + store.swap(); + this.gridInitialized.add(module.name); + } + + descriptor.step(ctx); + store.swap(); + if (descriptor.post) { + descriptor.post(ctx); + store.swap(); + } + } catch (error) {} + } + } } diff --git a/packages/core/src/runtimes/cpu/spatial-grid.ts b/packages/core/src/runtimes/cpu/spatial-grid.ts index 81664b0c..e1f04b1d 100644 --- a/packages/core/src/runtimes/cpu/spatial-grid.ts +++ b/packages/core/src/runtimes/cpu/spatial-grid.ts @@ -1,5 +1,6 @@ import { Particle } from "../../particle"; import { Vector } from "../../vector"; +import { GridGeometry } from "../../grid/geometry"; export interface SpatialGridOptions { width: number; @@ -10,16 +11,13 @@ export interface SpatialGridOptions { export class SpatialGrid { private width: number; private height: number; - private cellSize: number; private cols!: number; private rows!: number; private grid!: Particle[][][]; + private geometry: GridGeometry; + private paddingRatio: number = 0.5; // Dynamic bounds that match current camera view - private minX!: number; - private minY!: number; - private maxX!: number; - private maxY!: number; // Camera tracking private cameraX: number = 0; private cameraY: number = 0; @@ -32,7 +30,9 @@ export class SpatialGrid { constructor(options: SpatialGridOptions) { this.width = options.width; this.height = options.height; - this.cellSize = options.cellSize; + this.geometry = new GridGeometry(options.cellSize, { + paddingRatio: this.paddingRatio, + }); // Initialize with default camera view (canvas coordinates) this.updateBounds(0, 0, 1); @@ -43,29 +43,26 @@ export class SpatialGrid { this.cameraY = cameraY; this.zoom = zoom; - // Calculate visible world bounds - const worldLeft = -cameraX / zoom; - const worldTop = -cameraY / zoom; - const worldRight = (this.width - cameraX) / zoom; - const worldBottom = (this.height - cameraY) / zoom; - - // Add padding around visible area to catch particles just outside view - const padding = (Math.max(this.width, this.height) / zoom) * 0.5; // 50% padding - this.minX = worldLeft - padding; - this.minY = worldTop - padding; - this.maxX = worldRight + padding; - this.maxY = worldBottom + padding; - - // Recalculate grid dimensions (ensure at least 1x1 to avoid undefined rows/cols) - 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)); + this.geometry.updateFromView( + { + width: this.width, + height: this.height, + cx: this.cameraX, + cy: this.cameraY, + zoom: this.zoom, + }, + { paddingRatio: this.paddingRatio } + ); + const dims = this.geometry.getDimensions(); + this.cols = dims.cols; + this.rows = dims.rows; this.initializeGrid(); } setCamera(cameraX: number, cameraY: number, zoom: number): void { // Only update if camera changed significantly to avoid constant grid rebuilding - const threshold = this.cellSize * 0.5; // Half a cell + const threshold = this.geometry.getCellSize() * 0.5; // Half a cell const zoomThreshold = 0.1; if ( @@ -126,12 +123,15 @@ export class SpatialGrid { insert(particle: Particle): void { // Convert world coordinates to grid coordinates with offset - const col = Math.floor((particle.position.x - this.minX) / this.cellSize); - const row = Math.floor((particle.position.y - this.minY) / this.cellSize); + const { col, row } = this.geometry.worldToCell( + particle.position.x, + particle.position.y, + true + ); // Clamp to grid bounds - const clampedCol = Math.max(0, Math.min(col, this.cols - 1)); - const clampedRow = Math.max(0, Math.min(row, this.rows - 1)); + const clampedCol = col; + const clampedRow = row; // Insert particle into grid // Safety: ensure row/col arrays exist (defensive against any transient zero-dimension states) @@ -154,11 +154,12 @@ export class SpatialGrid { ): Particle[] { const neighbors: Particle[] = []; // Convert world coordinates to grid coordinates with offset - const centerCol = Math.floor((point.x - this.minX) / this.cellSize); - const centerRow = Math.floor((point.y - this.minY) / this.cellSize); + const center = this.geometry.worldToCell(point.x, point.y, true); + const centerCol = center.col; + const centerRow = center.row; // Calculate how many cells to check in each direction - const cellRadius = Math.ceil(radius / this.cellSize); + const cellRadius = Math.ceil(radius / this.geometry.getCellSize()); for ( let row = centerRow - cellRadius; @@ -205,20 +206,11 @@ export class SpatialGrid { } getGridDimensions(): { cols: number; rows: number; cellSize: number } { - return { - cols: this.cols, - rows: this.rows, - cellSize: this.cellSize, - }; + return this.geometry.getDimensions(); } getGridBounds(): { minX: number; minY: number; maxX: number; maxY: number } { - return { - minX: this.minX, - minY: this.minY, - maxX: this.maxX, - maxY: this.maxY, - }; + return this.geometry.getBounds(); } getSize(): { width: number; height: number } { @@ -237,11 +229,11 @@ export class SpatialGrid { } getCellSize(): number { - return this.cellSize; + return this.geometry.getCellSize(); } setCellSize(cellSize: number): void { - this.cellSize = cellSize; + this.geometry.setCellSize(cellSize); // Update bounds with new cell size this.updateBounds(this.cameraX, this.cameraY, this.zoom); } diff --git a/packages/core/src/runtimes/webgpu/builders/program.ts b/packages/core/src/runtimes/webgpu/builders/program.ts index 554d094a..deb3df8a 100644 --- a/packages/core/src/runtimes/webgpu/builders/program.ts +++ b/packages/core/src/runtimes/webgpu/builders/program.ts @@ -19,6 +19,7 @@ import { ModuleRole, DataType, WebGPUForceDescriptor, + GridSpec, } from "../../../module"; export const PARTICLE_STRUCT = ` @@ -60,6 +61,7 @@ export interface Program { simState?: { stateBinding: number }; sceneTexture?: { textureBinding: number }; arrays?: Record; // moduleName_arrayKey -> bindings + gridFields?: Record; }; } @@ -308,11 +310,49 @@ export function buildProgram(modules: readonly Module[]): Program { const SIM_STATE_STRIDE_VAL = nextSlot; // Grid and system bindings come after all module bindings (including arrays) + const gridFieldBindings: Record = + {}; + const gridFieldDecls: string[] = []; + const gridFieldHelpers: string[] = []; + for (const module of modules) { + if (module.role !== ModuleRole.Grid) continue; + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + const binding = nextBindingIndex++; + gridFieldBindings[module.name] = { binding, spec }; + gridFieldDecls.push( + `@group(0) @binding(${binding}) var GRID_FIELD_${module.name}: array;` + ); + const channels = + spec.channels ?? + (spec.format === "vec2f" ? 2 : spec.format === "vec4f" ? 4 : 1); + gridFieldHelpers.push(`const GRID_${module.name}_WIDTH: u32 = ${spec.width}u;`); + gridFieldHelpers.push( + `const GRID_${module.name}_HEIGHT: u32 = ${spec.height}u;` + ); + gridFieldHelpers.push( + `const GRID_${module.name}_CHANNELS: u32 = ${channels}u;` + ); + gridFieldHelpers.push( + `fn grid_${module.name}_index(x: i32, y: i32, c: u32) -> u32 { + let xx = max(0, min(x, i32(GRID_${module.name}_WIDTH) - 1)); + let yy = max(0, min(y, i32(GRID_${module.name}_HEIGHT) - 1)); + return (u32(yy) * GRID_${module.name}_WIDTH + u32(xx)) * GRID_${module.name}_CHANNELS + c; +}` + ); + gridFieldHelpers.push( + `fn grid_${module.name}_read(x: i32, y: i32, c: u32) -> f32 { return GRID_FIELD_${module.name}[grid_${module.name}_index(x, y, c)]; }` + ); + gridFieldHelpers.push( + `fn grid_${module.name}_write(x: i32, y: i32, c: u32, v: f32) { GRID_FIELD_${module.name}[grid_${module.name}_index(x, y, c)] = v; }` + ); + } const gridCountsBinding = nextBindingIndex++; const gridIndicesBinding = nextBindingIndex++; const simStateBinding = nextBindingIndex++; const sceneTextureBinding = nextBindingIndex++; const gridDecls = [ + ...gridFieldDecls, `@group(0) @binding(${gridCountsBinding}) var GRID_COUNTS: array>;`, `@group(0) @binding(${gridIndicesBinding}) var GRID_INDICES: array;`, `@group(0) @binding(${simStateBinding}) var SIM_STATE: array;`, @@ -412,6 +452,11 @@ fn neighbor_iter_next(it: ptr, selfIndex: u32) -> u32 { }` ); + if (gridFieldHelpers.length > 0) { + globals.push(`// Grid field helpers`); + globals.push(...gridFieldHelpers); + } + // Optional: allow force modules to inject globals const addGlobal = (module: Module, descriptor: WebGPUForceDescriptor) => { if (module.role !== ModuleRole.Force) return; @@ -637,6 +682,15 @@ fn grid_build(@builtin(global_invocation_id) global_id: vec3) { simState: { stateBinding: simStateBinding }, sceneTexture: { textureBinding: sceneTextureBinding }, arrays: Object.keys(arrayBindings).length > 0 ? arrayBindings : undefined, + gridFields: + Object.keys(gridFieldBindings).length > 0 + ? Object.fromEntries( + Object.entries(gridFieldBindings).map(([name, entry]) => [ + name, + { binding: entry.binding }, + ]) + ) + : undefined, }, }; } diff --git a/packages/core/src/runtimes/webgpu/builders/render-pass.ts b/packages/core/src/runtimes/webgpu/builders/render-pass.ts index 72707e60..de4cdad5 100644 --- a/packages/core/src/runtimes/webgpu/builders/render-pass.ts +++ b/packages/core/src/runtimes/webgpu/builders/render-pass.ts @@ -8,7 +8,7 @@ * Provides helpers to resolve module uniforms (`getUniform`), sample/read/write scene * textures, and injects default vertex logic for instanced vs non-instanced fullscreen draws. */ -import type { FullscreenRenderPass, ComputeRenderPass } from "../../../module"; +import type { FullscreenRenderPass, ComputeRenderPass, GridSpec } from "../../../module"; import { DataType } from "../../../module"; import { ModuleUniformLayout } from "./program"; @@ -145,7 +145,8 @@ export function buildFullscreenPassWGSL< moduleName: string, layout: ModuleUniformLayout, moduleInputs: Record, - clearColor: { r: number; g: number; b: number; a: number } + clearColor: { r: number; g: number; b: number; a: number }, + grid?: { spec: GridSpec; bindingIndex: number } ): string { // build WGSL const struct = buildModuleUniformStruct(moduleName, layout); @@ -217,6 +218,23 @@ export function buildFullscreenPassWGSL< ? `@group(0) @binding(5) var ${moduleName}_arrays: array;` : ""; + const gridDecl = + grid + ? `@group(0) @binding(${grid.bindingIndex}) var grid_buffer: array; +const GRID_WIDTH: u32 = ${grid.spec.width}u; +const GRID_HEIGHT: u32 = ${grid.spec.height}u; +const GRID_CHANNELS: u32 = ${ + grid.spec.channels ?? + (grid.spec.format === "vec2f" ? 2 : grid.spec.format === "vec4f" ? 4 : 1) +}u; +fn grid_index(x: i32, y: i32, c: u32) -> u32 { + let xx = max(0, min(x, i32(GRID_WIDTH) - 1)); + let yy = max(0, min(y, i32(GRID_HEIGHT) - 1)); + return (u32(yy) * GRID_WIDTH + u32(xx)) * GRID_CHANNELS + c; +} +fn grid_read(x: i32, y: i32, c: u32) -> f32 { return grid_buffer[grid_index(x, y, c)]; }` + : ""; + const code = ` struct Particle { position: vec2, velocity: vec2, acceleration: vec2, @@ -228,6 +246,7 @@ struct VertexOutput { @builtin(position) position: vec4, @location(0) uv: v @group(0) @binding(1) var render_uniforms: RenderUniforms; @group(0) @binding(2) var scene_texture: texture_2d; @group(0) @binding(3) var scene_sampler: sampler; +${gridDecl} @vertex fn vs_main(@builtin(vertex_index) i: u32, @builtin(instance_index) inst: u32) -> VertexOutput { var out: VertexOutput; let qpos = array,4>(vec2(-1,-1),vec2(1,-1),vec2(-1,1),vec2(1,1)); @@ -273,7 +292,8 @@ export function buildComputeImagePassWGSL< layout: ModuleUniformLayout, moduleInputs: Record, clearColor: { r: number; g: number; b: number; a: number }, - workgroup: [number, number, number] = [8, 8, 1] + workgroup: [number, number, number] = [8, 8, 1], + grid?: { spec: GridSpec; bindingIndex: number } ): string { // struct and uniform lookup const struct = buildModuleUniformStruct(moduleName, layout); @@ -298,6 +318,23 @@ export function buildComputeImagePassWGSL< ? `@group(0) @binding(3) var ${moduleName}_arrays: array;` : ""; + const gridDecl = + grid + ? `@group(0) @binding(${grid.bindingIndex}) var grid_buffer: array; +const GRID_WIDTH: u32 = ${grid.spec.width}u; +const GRID_HEIGHT: u32 = ${grid.spec.height}u; +const GRID_CHANNELS: u32 = ${ + grid.spec.channels ?? + (grid.spec.format === "vec2f" ? 2 : grid.spec.format === "vec4f" ? 4 : 1) +}u; +fn grid_index(x: i32, y: i32, c: u32) -> u32 { + let xx = max(0, min(x, i32(GRID_WIDTH) - 1)); + let yy = max(0, min(y, i32(GRID_HEIGHT) - 1)); + return (u32(yy) * GRID_WIDTH + u32(xx)) * GRID_CHANNELS + c; +} +fn grid_read(x: i32, y: i32, c: u32) -> f32 { return grid_buffer[grid_index(x, y, c)]; }` + : ""; + // kernel const kernelBody = pass.kernel({ getUniform: getUniformForCompute(uniformExpr, clearColor), @@ -312,6 +349,7 @@ export function buildComputeImagePassWGSL< const code = ` @group(0) @binding(0) var input_texture: texture_2d; @group(0) @binding(1) var output_texture: texture_storage_2d; +${gridDecl} @compute @workgroup_size(${workgroup[0]}, ${workgroup[1]}, ${workgroup[2]}) fn cs_main(@builtin(global_invocation_id) gid: vec3) { let coords = vec2(i32(gid.x), i32(gid.y)); diff --git a/packages/core/src/runtimes/webgpu/engine.ts b/packages/core/src/runtimes/webgpu/engine.ts index 198b9bdc..c1a7ea28 100644 --- a/packages/core/src/runtimes/webgpu/engine.ts +++ b/packages/core/src/runtimes/webgpu/engine.ts @@ -14,7 +14,7 @@ * - Drive per-frame simulation passes and render passes into ping-pong scene textures * - Present the final texture to the canvas, tracking an EMA FPS estimate */ -import type { Module } from "../../module"; +import type { Module, GridSpec } from "../../module"; import { GPUResources } from "./gpu-resources"; import { ParticleStore } from "./particle-store"; import { @@ -28,6 +28,8 @@ import { SpacialGrid } from "./spacial-grid"; import { SimulationPipeline } from "./simulation-pipeline"; import { RenderPipeline } from "./render-pipeline"; import { LocalQuery } from "./local-query"; +import { GridPipeline } from "./grid-pipeline"; +import { getGridChannelCount } from "../../grid/store"; export class WebGPUEngine extends AbstractEngine { private resources: GPUResources; @@ -36,6 +38,9 @@ export class WebGPUEngine extends AbstractEngine { private sim: SimulationPipeline; private render: RenderPipeline; private grid: SpacialGrid; + private gridPipeline: GridPipeline; + private gridStores: Map = new Map(); + private gridSpecs: Map = new Map(); private bufferMaxParticles: number; // Buffer allocation size (separate from effective maxParticles) private workgroupSize: number; private simStrideValue: number = 0; @@ -49,6 +54,7 @@ export class WebGPUEngine extends AbstractEngine { canvas: HTMLCanvasElement; forces: Module[]; render: Module[]; + grids?: Module[]; constrainIterations?: number; clearColor?: { r: number; g: number; b: number; a: number }; cellSize?: number; @@ -67,10 +73,15 @@ export class WebGPUEngine extends AbstractEngine { this.workgroupSize = options.workgroupSize ?? 64; this.resources = new GPUResources({ canvas: options.canvas }); this.particles = new ParticleStore(this.bufferMaxParticles, 12); - this.registry = new ModuleRegistry([...options.forces, ...options.render]); + this.registry = new ModuleRegistry([ + ...options.forces, + ...options.render, + ...(options.grids ?? []), + ]); this.sim = new SimulationPipeline(); this.render = new RenderPipeline(); this.grid = new SpacialGrid(this.cellSize); + this.gridPipeline = new GridPipeline(); this.localQuery = new LocalQuery(); } @@ -82,6 +93,7 @@ export class WebGPUEngine extends AbstractEngine { this.resources.createRenderUniformBuffer(24); // Build program + module uniform buffers + this.attachGridSpecsFromModules(); this.registry.initialize(this.resources); const program = this.registry.getProgram(); if (program.extraBindings.simState) { @@ -99,6 +111,14 @@ export class WebGPUEngine extends AbstractEngine { // Build compute pipelines this.sim.initialize(this.resources, program); + this.setupGridStores(); + this.gridPipeline.initialize( + this.resources, + this.registry, + this.gridModules, + this.gridSpecs + ); + // Ensure scene textures const size = this.view.getSize(); this.resources.canvas.width = size.width; @@ -144,6 +164,12 @@ export class WebGPUEngine extends AbstractEngine { this.animationId = null; } this.localQuery.dispose(); + this.gridStores.forEach((store) => { + store.read.destroy(); + store.write.destroy(); + }); + this.gridStores.clear(); + this.gridSpecs.clear(); await this.resources.dispose(); } @@ -200,6 +226,39 @@ export class WebGPUEngine extends AbstractEngine { this.particles.syncParticleMassToGPU(this.resources, index); } + getGrid(moduleName: string): Promise { + const store = this.gridStores.get(moduleName); + if (!store) { + return Promise.reject(new Error(`Grid module not found: ${moduleName}`)); + } + const channels = getGridChannelCount(store.spec); + const length = store.spec.width * store.spec.height * channels; + const bytes = length * 4; + return this.resources.readBuffer(store.read, bytes).then((buf) => { + return new Float32Array(buf); + }); + } + + setGrid(moduleName: string, data: ArrayBufferView): void { + const store = this.gridStores.get(moduleName); + if (!store) return; + const device = this.resources.getDevice(); + device.queue.writeBuffer( + store.read, + 0, + data.buffer, + data.byteOffset, + data.byteLength + ); + device.queue.writeBuffer( + store.write, + 0, + data.buffer, + data.byteOffset, + data.byteLength + ); + } + /** * Forces GPU-to-CPU synchronization and returns current particle data. * Use this when you need the most up-to-date particle positions from GPU. @@ -244,6 +303,15 @@ export class WebGPUEngine extends AbstractEngine { this.resetMaxSize(); // Sync module uniforms to GPU (important for grab module reset) this.registry.writeAllModuleUniforms(); + this.gridPipeline.reset(); + const device = this.resources.getDevice(); + for (const store of this.gridStores.values()) { + const channels = getGridChannelCount(store.spec); + const length = store.spec.width * store.spec.height * channels; + const zeros = new Float32Array(length); + device.queue.writeBuffer(store.read, 0, zeros); + device.queue.writeBuffer(store.write, 0, zeros); + } } private animate = async (): Promise => { @@ -261,6 +329,10 @@ export class WebGPUEngine extends AbstractEngine { this.registry.getProgram() ); + let gridReadBuffers: + | Map + | undefined = undefined; + // Encode command buffer const encoder = this.resources.getDevice().createCommandEncoder(); @@ -268,6 +340,24 @@ export class WebGPUEngine extends AbstractEngine { if (this.playing) { // Update engine-owned oscillators before simulation uniforms are written this.updateOscillators(dt); + if (this.gridModules.length > 0 && this.gridStores.size > 0) { + this.gridPipeline.run( + encoder, + this.resources, + this.registry, + this.gridModules, + this.gridStores + ); + } + gridReadBuffers = + this.gridStores.size > 0 + ? new Map( + Array.from(this.gridStores.entries()).map(([name, store]) => [ + name, + store.read, + ]) + ) + : undefined; // Update simulation uniforms (dt, count, simStride, maxSize, maxParticles) const actualCount = this.particles.getCount(); this.resources.writeSimulationUniform(this.registry.getProgram(), { @@ -286,6 +376,7 @@ export class WebGPUEngine extends AbstractEngine { gridCellCount: this.grid.getCellCount(), workgroupSize: this.workgroupSize, constrainIterations: this.constrainIterations, + gridBuffers: gridReadBuffers, }); if (this.shouldSyncNextTick) { @@ -306,6 +397,14 @@ export class WebGPUEngine extends AbstractEngine { const particleCount = this.getCount(); // Use effective count // Always run render passes to keep displaying current state + if (!gridReadBuffers && this.gridStores.size > 0) { + gridReadBuffers = new Map( + Array.from(this.gridStores.entries()).map(([name, store]) => [ + name, + store.read, + ]) + ); + } const lastView = this.render.runPasses( encoder, this.registry.getEnabledRenderModules(), @@ -313,7 +412,8 @@ export class WebGPUEngine extends AbstractEngine { this.resources, this.view.getSize(), particleCount, - this.clearColor + this.clearColor, + gridReadBuffers ); this.render.present(encoder, this.resources, lastView); @@ -331,6 +431,54 @@ export class WebGPUEngine extends AbstractEngine { }); } + private setupGridStores(): void { + const device = this.resources.getDevice(); + this.gridStores.clear(); + this.gridSpecs.clear(); + for (const module of this.gridModules) { + if (module.role !== "grid") continue; + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + const channels = getGridChannelCount(spec); + const length = + Math.max(1, spec.width) * Math.max(1, spec.height) * channels; + const sizeBytes = length * 4; + const usage = + GPUBufferUsage.STORAGE | + GPUBufferUsage.COPY_SRC | + GPUBufferUsage.COPY_DST; + const read = device.createBuffer({ size: sizeBytes, usage }); + const write = device.createBuffer({ size: sizeBytes, usage }); + this.gridStores.set(module.name, { spec, read, write }); + this.gridSpecs.set(module.name, spec); + } + for (const module of this.modules) { + const attach = (module as unknown as { attachGridSpec?: (spec: GridSpec) => void }).attachGridSpec; + const getName = (module as unknown as { getGridModuleName?: () => string }).getGridModuleName; + if (!attach || !getName) continue; + const gridName = getName.call(module); + const spec = this.gridSpecs.get(gridName); + if (spec) attach.call(module, spec); + } + } + + private attachGridSpecsFromModules(): void { + const specs = new Map(); + for (const module of this.gridModules) { + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + specs.set(module.name, spec); + } + for (const module of this.modules) { + const attach = (module as unknown as { attachGridSpec?: (spec: GridSpec) => void }).attachGridSpec; + const getName = (module as unknown as { getGridModuleName?: () => string }).getGridModuleName; + if (!attach || !getName) continue; + const gridName = getName.call(module); + const spec = specs.get(gridName); + if (spec) attach.call(module, spec); + } + } + private isWebKitWebGPU(): boolean { // We specifically want WebKit's WebGPU, not Chromium/Blink. // - On iOS, *all* browsers use WebKit, so we treat them as WebKit. diff --git a/packages/core/src/runtimes/webgpu/gpu-resources.ts b/packages/core/src/runtimes/webgpu/gpu-resources.ts index ad521e24..fcaf34e4 100644 --- a/packages/core/src/runtimes/webgpu/gpu-resources.ts +++ b/packages/core/src/runtimes/webgpu/gpu-resources.ts @@ -530,14 +530,15 @@ export class GPUResources { getRenderBindGroupLayout( arrayInputs?: string[], - fragmentParticleAccess?: boolean + fragmentParticleAccess?: boolean, + gridBindingIndex?: number ): GPUBindGroupLayout { // Create a cache key based on array inputs and fragment access const cacheKey = arrayInputs ? `render_${arrayInputs.sort().join("_")}_frag_${ fragmentParticleAccess || false - }` - : `render_basic_frag_${fragmentParticleAccess || false}`; + }_grid_${gridBindingIndex ?? "none"}` + : `render_basic_frag_${fragmentParticleAccess || false}_grid_${gridBindingIndex ?? "none"}`; // Check if we have a cached layout for this configuration if (!this.renderBindGroupLayoutCache) { @@ -586,6 +587,14 @@ export class GPUResources { }); } + if (gridBindingIndex !== undefined) { + entries.push({ + binding: gridBindingIndex, + visibility: GPUShaderStage.FRAGMENT, + buffer: { type: "read-only-storage" }, + }); + } + const layout = this.getDevice().createBindGroupLayout({ entries }); this.renderBindGroupLayoutCache.set(cacheKey, layout); return layout; @@ -637,6 +646,15 @@ export class GPUResources { buffer: { type: "storage" }, }); } + if (compute.extraBindings.gridFields) { + for (const binding of Object.values(compute.extraBindings.gridFields)) { + entries.push({ + binding: binding.binding, + visibility: GPUShaderStage.COMPUTE, + buffer: { type: "storage" }, + }); + } + } if (compute.extraBindings.simState) { entries.push({ binding: compute.extraBindings.simState.stateBinding, @@ -746,12 +764,13 @@ export class GPUResources { getOrCreateFullscreenRenderPipeline( shaderCode: string, arrayInputs?: string[], - fragmentParticleAccess?: boolean + fragmentParticleAccess?: boolean, + gridBindingIndex?: number ): GPURenderPipeline { const arrayKey = arrayInputs?.sort().join("_") || ""; const key = `fs:${this.hashWGSL(shaderCode)}:${arrayKey}:frag_${ fragmentParticleAccess || false - }`; + }:grid_${gridBindingIndex ?? "none"}`; const cached = this.fullscreenPipelines.get(key); if (cached) return cached; const shaderModule = this.getDevice().createShaderModule({ @@ -760,7 +779,11 @@ export class GPUResources { const pipeline = this.getDevice().createRenderPipeline({ layout: this.getDevice().createPipelineLayout({ bindGroupLayouts: [ - this.getRenderBindGroupLayout(arrayInputs, fragmentParticleAccess), + this.getRenderBindGroupLayout( + arrayInputs, + fragmentParticleAccess, + gridBindingIndex + ), ], }), vertex: { module: shaderModule, entryPoint: "vs_main" }, @@ -809,7 +832,9 @@ export class GPUResources { moduleUniformBuffer: GPUBuffer, moduleName: string, arrayInputs?: string[], - fragmentParticleAccess?: boolean + fragmentParticleAccess?: boolean, + gridBuffer?: GPUBuffer, + gridBindingIndex?: number ): GPUBindGroup { const entries: GPUBindGroupEntry[] = [ { binding: 0, resource: { buffer: particleBuffer } }, @@ -831,16 +856,27 @@ export class GPUResources { } } + if (gridBuffer && gridBindingIndex !== undefined) { + entries.push({ + binding: gridBindingIndex, + resource: { buffer: gridBuffer }, + }); + } + return this.getDevice().createBindGroup({ layout: this.getRenderBindGroupLayout( arrayInputs, - fragmentParticleAccess + fragmentParticleAccess, + gridBindingIndex ), entries, }); } - createComputeBindGroup(compute: Program): GPUBindGroup { + createComputeBindGroup( + compute: Program, + gridBuffers?: Map + ): GPUBindGroup { if (!this.computeBindGroupLayout) { throw new Error("Compute bind group layout not built"); } @@ -913,6 +949,18 @@ export class GPUResources { resource: this.getCurrentSceneTextureView(), }); } + if (compute.extraBindings.gridFields && gridBuffers) { + for (const [name, binding] of Object.entries( + compute.extraBindings.gridFields + )) { + const buffer = gridBuffers.get(name); + if (!buffer) continue; + entries.push({ + binding: binding.binding, + resource: { buffer }, + }); + } + } return this.getDevice().createBindGroup({ layout: this.computeBindGroupLayout, entries, @@ -925,7 +973,9 @@ export class GPUResources { writeView: GPUTextureView, moduleUniformBuffer: GPUBuffer, moduleName: string, - arrayInputs?: string[] + arrayInputs?: string[], + gridBuffer?: GPUBuffer, + gridBindingIndex?: number ): GPUBindGroup { const layout = pipeline.getBindGroupLayout(0); const entries: GPUBindGroupEntry[] = [ @@ -946,6 +996,13 @@ export class GPUResources { } } + if (gridBuffer && gridBindingIndex !== undefined) { + entries.push({ + binding: gridBindingIndex, + resource: { buffer: gridBuffer }, + }); + } + return this.getDevice().createBindGroup({ layout, entries, diff --git a/packages/core/src/runtimes/webgpu/grid-pipeline.ts b/packages/core/src/runtimes/webgpu/grid-pipeline.ts new file mode 100644 index 00000000..e1cfee69 --- /dev/null +++ b/packages/core/src/runtimes/webgpu/grid-pipeline.ts @@ -0,0 +1,264 @@ +import type { Module, GridSpec, WebGPUGridDescriptor } from "../../module"; +import type { GPUResources } from "./gpu-resources"; +import type { ModuleRegistry } from "./module-registry"; +import { getGridChannelCount } from "../../grid/store"; + +type GridPipelineEntry = { + layout: GPUBindGroupLayout; + init?: GPUComputePipeline; + step: GPUComputePipeline; + post?: GPUComputePipeline; + workgroupSize: [number, number, number]; + width: number; + height: number; +}; + +export class GridPipeline { + private pipelines: Map = new Map(); + private initialized: Set = new Set(); + + initialize( + resources: GPUResources, + registry: ModuleRegistry, + gridModules: readonly Module[], + gridSpecs: Map + ): void { + const program = registry.getProgram(); + const device = resources.getDevice(); + this.pipelines.clear(); + this.initialized.clear(); + + for (const module of gridModules) { + const spec = gridSpecs.get(module.name); + if (!spec) continue; + const descriptor = module.webgpu() as WebGPUGridDescriptor; + if (!descriptor || !descriptor.step) continue; + + const layout = program.layouts.find((l) => l.moduleName === module.name); + if (!layout) continue; + + const channels = getGridChannelCount(spec); + const workgroupSize: [number, number, number] = [8, 8, 1]; + + const uniformStruct = `struct ${layout.structName} {\n${Array.from( + { length: layout.vec4Count }, + (_, i) => ` v${i}: vec4,` + ).join("\n")}\n}`; + const uniformDecl = `@group(0) @binding(0) var ${layout.uniformsVar}: ${layout.structName};`; + + const gridDecls = [ + `@group(0) @binding(1) var GRID_READ: array;`, + `@group(0) @binding(2) var GRID_WRITE: array;`, + ]; + + const wrapMode = spec.wrap ?? "clamp"; + const wrapFn = + wrapMode === "repeat" + ? `fn grid_wrap(v: i32, max: i32) -> i32 { let m = ((v % max) + max) % max; return m; }` + : wrapMode === "mirror" + ? `fn grid_wrap(v: i32, max: i32) -> i32 { let period = max * 2; let m = ((v % period) + period) % period; return select(m, period - 1 - m, m >= max); }` + : `fn grid_wrap(v: i32, max: i32) -> i32 { return max(0, min(v, max - 1)); }`; + + const helpers = ` +const GRID_WIDTH: u32 = ${spec.width}u; +const GRID_HEIGHT: u32 = ${spec.height}u; +const GRID_CHANNELS: u32 = ${channels}u; + +${wrapFn} + +fn grid_index(x: i32, y: i32, c: u32) -> u32 { + let xx = grid_wrap(x, i32(GRID_WIDTH)); + let yy = grid_wrap(y, i32(GRID_HEIGHT)); + return (u32(yy) * GRID_WIDTH + u32(xx)) * GRID_CHANNELS + c; +} + +fn grid_read(x: i32, y: i32, c: u32) -> f32 { + return GRID_READ[grid_index(x, y, c)]; +} + +fn grid_write(x: i32, y: i32, c: u32, v: f32) { + GRID_WRITE[grid_index(x, y, c)] = v; +} +`; + + const getUniform = (id: string, index?: number | string) => { + const key = String(id); + const map = layout.mapping as Record; + if (index !== undefined) { + return map[`${key}_offset`] + ? `(${map[`${key}_offset`].expr} + ${index})` + : "0.0"; + } + return map[key]?.expr ?? "0.0"; + }; + const getLength = (id: string) => { + const map = layout.mapping as Record; + return map[`${id}_length`]?.expr ?? "0.0"; + }; + + const makeEntry = (name: "init" | "step" | "post", body: string) => ` +@compute @workgroup_size(${workgroupSize[0]}, ${workgroupSize[1]}, ${workgroupSize[2]}) +fn ${name}_${module.name}(@builtin(global_invocation_id) gid: vec3) { + if (gid.x >= GRID_WIDTH || gid.y >= GRID_HEIGHT) { return; } + let cellCoord = vec2(gid.x, gid.y); + let cellIndex = (gid.y * GRID_WIDTH + gid.x) * GRID_CHANNELS; + ${body} +} +`; + + const globals = descriptor.globals + ? descriptor.globals({ getUniform: (id, index) => getUniform(String(id), index), getLength: (id) => getLength(String(id)) }) + : ""; + const initBody = descriptor.init + ? descriptor.init({ + getUniform: (id, index) => getUniform(String(id), index), + getLength: (id) => getLength(String(id)), + gridRead: "GRID_READ", + gridWrite: "GRID_WRITE", + cellIndexVar: "cellIndex", + cellCoordVar: "cellCoord", + widthVar: "GRID_WIDTH", + heightVar: "GRID_HEIGHT", + }) + : ""; + const stepBody = descriptor.step({ + getUniform: (id, index) => getUniform(String(id), index), + getLength: (id) => getLength(String(id)), + gridRead: "GRID_READ", + gridWrite: "GRID_WRITE", + cellIndexVar: "cellIndex", + cellCoordVar: "cellCoord", + widthVar: "GRID_WIDTH", + heightVar: "GRID_HEIGHT", + }); + const postBody = descriptor.post + ? descriptor.post({ + getUniform: (id, index) => getUniform(String(id), index), + getLength: (id) => getLength(String(id)), + gridRead: "GRID_READ", + gridWrite: "GRID_WRITE", + cellIndexVar: "cellIndex", + cellCoordVar: "cellCoord", + widthVar: "GRID_WIDTH", + heightVar: "GRID_HEIGHT", + }) + : ""; + + const code = [ + uniformStruct, + uniformDecl, + ...gridDecls, + helpers, + globals, + initBody ? makeEntry("init", initBody) : "", + makeEntry("step", stepBody), + postBody ? makeEntry("post", postBody) : "", + ].join("\n"); + + const shaderModule = device.createShaderModule({ code }); + const layoutEntries: GPUBindGroupLayoutEntry[] = [ + { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } }, + { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } }, + { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } }, + ]; + const bindGroupLayout = device.createBindGroupLayout({ + entries: layoutEntries, + }); + const pipelineLayout = device.createPipelineLayout({ + bindGroupLayouts: [bindGroupLayout], + }); + + const makePipeline = (entryPoint: string) => + device.createComputePipeline({ + layout: pipelineLayout, + compute: { module: shaderModule, entryPoint }, + }); + + const entry: GridPipelineEntry = { + layout: bindGroupLayout, + init: initBody ? makePipeline(`init_${module.name}`) : undefined, + step: makePipeline(`step_${module.name}`), + post: postBody ? makePipeline(`post_${module.name}`) : undefined, + workgroupSize, + width: spec.width, + height: spec.height, + }; + + this.pipelines.set(module.name, entry); + } + } + + run( + encoder: GPUCommandEncoder, + resources: GPUResources, + registry: ModuleRegistry, + gridModules: readonly Module[], + gridStores: Map + ): void { + if (this.pipelines.size === 0) return; + const device = resources.getDevice(); + const uniformBuffers = resources.getModuleUniformBuffers(); + const program = registry.getProgram(); + + for (const module of gridModules) { + if (!module.isEnabled()) continue; + const entry = this.pipelines.get(module.name); + if (!entry) continue; + const buffers = gridStores.get(module.name); + if (!buffers) continue; + + const layout = program.layouts.find((l) => l.moduleName === module.name); + if (!layout) continue; + const uniformIdx = program.layouts.indexOf(layout); + const uniformBuffer = uniformBuffers[uniformIdx]?.buffer; + if (!uniformBuffer) continue; + + const dispatchX = Math.ceil(entry.width / entry.workgroupSize[0]); + const dispatchY = Math.ceil(entry.height / entry.workgroupSize[1]); + + const makeBindGroup = (read: GPUBuffer, write: GPUBuffer) => + device.createBindGroup({ + layout: entry.layout, + entries: [ + { binding: 0, resource: { buffer: uniformBuffer } }, + { binding: 1, resource: { buffer: read } }, + { binding: 2, resource: { buffer: write } }, + ], + }); + + const runPass = (pipeline: GPUComputePipeline) => { + const pass = encoder.beginComputePass(); + pass.setPipeline(pipeline); + pass.setBindGroup(0, makeBindGroup(buffers.read, buffers.write)); + pass.dispatchWorkgroups(dispatchX, dispatchY, 1); + pass.end(); + }; + + if (!this.initialized.has(module.name) && entry.init) { + runPass(entry.init); + const tmp = buffers.read; + buffers.read = buffers.write; + buffers.write = tmp; + this.initialized.add(module.name); + } + + runPass(entry.step); + { + const tmp = buffers.read; + buffers.read = buffers.write; + buffers.write = tmp; + } + if (entry.post) { + runPass(entry.post); + const tmp = buffers.read; + buffers.read = buffers.write; + buffers.write = tmp; + } + } + + } + + reset(): void { + this.initialized.clear(); + } +} diff --git a/packages/core/src/runtimes/webgpu/module-registry.ts b/packages/core/src/runtimes/webgpu/module-registry.ts index f593e2d8..a4786ea5 100644 --- a/packages/core/src/runtimes/webgpu/module-registry.ts +++ b/packages/core/src/runtimes/webgpu/module-registry.ts @@ -17,6 +17,7 @@ import { Module, ModuleRole, type WebGPURenderDescriptor, + type WebGPUGridDescriptor, DataType, } from "../../module"; @@ -134,12 +135,14 @@ export class ModuleRegistry { getEnabledRenderModules(): Module[] { return this.modules.filter((module, idx) => { if (!module.isEnabled()) return false; - const descriptor = this.modules[idx].webgpu() as WebGPURenderDescriptor; - return !!( - descriptor && - descriptor.passes && - descriptor.passes.length > 0 - ); + const descriptor = this.modules[idx].webgpu() as + | WebGPURenderDescriptor + | WebGPUGridDescriptor; + const passes = + module.role === ModuleRole.Grid + ? (descriptor as WebGPUGridDescriptor).render?.passes + : (descriptor as WebGPURenderDescriptor).passes; + return !!(passes && passes.length > 0); }); } diff --git a/packages/core/src/runtimes/webgpu/render-pipeline.ts b/packages/core/src/runtimes/webgpu/render-pipeline.ts index 25bf2e53..8c531ec8 100644 --- a/packages/core/src/runtimes/webgpu/render-pipeline.ts +++ b/packages/core/src/runtimes/webgpu/render-pipeline.ts @@ -14,11 +14,14 @@ import type { ModuleUniformLayout, Program } from "./builders/program"; import type { GPUResources } from "./gpu-resources"; import { Module, + ModuleRole, ComputeRenderPass, RenderPassKind, DataType, type FullscreenRenderPass, type WebGPURenderDescriptor, + type WebGPUGridDescriptor, + type GridSpec, } from "../../module"; import { buildComputeImagePassWGSL, @@ -90,7 +93,8 @@ export class RenderPipeline { resources: GPUResources, viewSize: { width: number; height: number }, particleCount: number, - clearColor: { r: number; g: number; b: number; a: number } + clearColor: { r: number; g: number; b: number; a: number }, + gridBuffers?: Map ): GPUTextureView { let currentView = resources.getCurrentSceneTextureView(); let otherView = resources.getOtherSceneTextureView(); @@ -99,8 +103,12 @@ export class RenderPipeline { for (let i = 0; i < modules.length; i++) { const module = modules[i]; - const descriptor = module.webgpu() as WebGPURenderDescriptor; - if (!descriptor.passes || descriptor.passes.length === 0) continue; + const descriptor = + module.role === ModuleRole.Grid + ? (module.webgpu() as WebGPUGridDescriptor).render + : (module.webgpu() as WebGPURenderDescriptor); + if (!descriptor || !descriptor.passes || descriptor.passes.length === 0) + continue; for (const pass of descriptor.passes) { // Resolve the uniform layout for this module const layout = program.layouts.find( @@ -119,7 +127,8 @@ export class RenderPipeline { views, resources, particleCount, - clearColor + clearColor, + gridBuffers ); wrote = pass.writesScene ? "current" : null; } @@ -133,7 +142,8 @@ export class RenderPipeline { views, resources, viewSize, - clearColor + clearColor, + gridBuffers ); wrote = pass.writesScene ? "other" : null; } @@ -216,15 +226,23 @@ export class RenderPipeline { }, resources: GPUResources, particleCount: number, - clearColor: { r: number; g: number; b: number; a: number } + clearColor: { r: number; g: number; b: number; a: number }, + gridBuffers?: Map ): void { // Generate WGSL for the fullscreen pass + const isGridModule = module.role === ModuleRole.Grid; + const gridSpec = isGridModule + ? (module as unknown as { gridSpec?: GridSpec }).gridSpec + : undefined; const wgsl = buildFullscreenPassWGSL( pass as FullscreenRenderPass, module.name, layout, module.inputs, - clearColor + clearColor, + gridSpec + ? { spec: gridSpec, bindingIndex: this.getGridBindingIndex(module, module.inputs, true) } + : undefined ); // Get array inputs for this module @@ -232,6 +250,11 @@ export class RenderPipeline { .filter(([_, type]) => type === DataType.ARRAY) .map(([key, _]) => key); + const gridBindingIndex = gridSpec + ? this.getGridBindingIndex(module, module.inputs, true) + : undefined; + const gridBuffer = gridSpec ? gridBuffers?.get(module.name) : undefined; + // Check if this is a non-instanced pass that needs fragment particle access const fragmentParticleAccess = pass.instanced === false; @@ -239,7 +262,8 @@ export class RenderPipeline { const pipeline = resources.getOrCreateFullscreenRenderPipeline( wgsl, arrayInputs, - fragmentParticleAccess + fragmentParticleAccess, + gridBindingIndex ); // Create bind group with particle data, global render uniforms, scene sampler/texture, and module uniforms @@ -253,7 +277,9 @@ export class RenderPipeline { .find((muf) => muf.layout.moduleName === module.name)!.buffer, module.name, arrayInputs, - fragmentParticleAccess + fragmentParticleAccess, + gridBuffer, + gridBindingIndex ); // Begin render pass targeting the current view. Clear only on the very first write @@ -299,21 +325,34 @@ export class RenderPipeline { }, resources: GPUResources, size: { width: number; height: number }, - clearColor: { r: number; g: number; b: number; a: number } + clearColor: { r: number; g: number; b: number; a: number }, + gridBuffers?: Map ): void { // Generate WGSL for the compute pass + const isGridModule = module.role === ModuleRole.Grid; + const gridSpec = isGridModule + ? (module as unknown as { gridSpec?: GridSpec }).gridSpec + : undefined; const wgsl = buildComputeImagePassWGSL( pass as ComputeRenderPass, module.name, layout, module.inputs, - clearColor + clearColor, + pass.workgroupSize ?? [8, 8, 1], + gridSpec + ? { spec: gridSpec, bindingIndex: this.getGridBindingIndex(module, module.inputs, false) } + : undefined ); // Get array inputs for this module const arrayInputs = Object.entries(module.inputs) .filter(([_, type]) => type === DataType.ARRAY) .map(([key, _]) => key); + const gridBindingIndex = gridSpec + ? this.getGridBindingIndex(module, module.inputs, false) + : undefined; + const gridBuffer = gridSpec ? gridBuffers?.get(module.name) : undefined; // Acquire or create a cached compute pipeline const pipeline = resources.getOrCreateImageComputePipeline(wgsl); @@ -327,7 +366,9 @@ export class RenderPipeline { views.otherView, muf.buffer, module.name, - arrayInputs + arrayInputs, + gridBuffer, + gridBindingIndex ); const canvasSize = size; // Compute dispatch size (assuming 8x8 threadgroups) @@ -339,4 +380,18 @@ export class RenderPipeline { cp.dispatchWorkgroups(workgroupsX, workgroupsY); cp.end(); } + + private getGridBindingIndex( + _module: Module, + inputs: Record, + fullscreen: boolean + ): number { + const arrayInputs = Object.entries(inputs) + .filter(([_, type]) => type === DataType.ARRAY) + .map(([key, _]) => key); + if (fullscreen) { + return arrayInputs.length > 0 ? 6 : 5; + } + return arrayInputs.length > 0 ? 4 : 3; + } } diff --git a/packages/core/src/runtimes/webgpu/simulation-pipeline.ts b/packages/core/src/runtimes/webgpu/simulation-pipeline.ts index 4509f839..f4d14137 100644 --- a/packages/core/src/runtimes/webgpu/simulation-pipeline.ts +++ b/packages/core/src/runtimes/webgpu/simulation-pipeline.ts @@ -27,10 +27,14 @@ export class SimulationPipeline { gridCellCount: number; workgroupSize: number; constrainIterations?: number; + gridBuffers?: Map; } ): void { if (!this.program) throw new Error("SimulationPipeline not initialized"); - const bindGroup = resources.createComputeBindGroup(this.program); + const bindGroup = resources.createComputeBindGroup( + this.program, + params.gridBuffers + ); const groups = Math.ceil(params.particleCount / params.workgroupSize); const pipelines = resources.getSimulationPipelines(); diff --git a/packages/core/src/runtimes/webgpu/spacial-grid.ts b/packages/core/src/runtimes/webgpu/spacial-grid.ts index 36aa6a39..c7f07266 100644 --- a/packages/core/src/runtimes/webgpu/spacial-grid.ts +++ b/packages/core/src/runtimes/webgpu/spacial-grid.ts @@ -9,6 +9,7 @@ import type { Program } from "./builders/program"; import type { GPUResources } from "./gpu-resources"; import type { ViewSnapshot } from "../../view"; +import { GridGeometry } from "../../grid/geometry"; export class SpacialGrid { private cols: number = 0; @@ -16,9 +17,11 @@ export class SpacialGrid { private cellSize: number; private maxPerCell: number = 256; private lastView: ViewSnapshot | null = null; + private geometry: GridGeometry; constructor(cellSize: number = 16) { this.cellSize = cellSize; + this.geometry = new GridGeometry(cellSize, { paddingRatio: 0 }); } configure( @@ -26,19 +29,22 @@ export class SpacialGrid { resources: GPUResources, program: Program ): void { - const { minX, minY, maxX, maxY, cols, rows } = this.computeGrid(view); - this.cols = cols; - this.rows = rows; + this.geometry.setCellSize(this.cellSize); + this.geometry.updateFromView(view, { paddingRatio: 0 }); + const bounds = this.geometry.getBounds(); + const dims = this.geometry.getDimensions(); + this.cols = dims.cols; + this.rows = dims.rows; // Recreate storage to match grid dimensions - resources.createGridStorage(cols * rows, this.maxPerCell); + resources.createGridStorage(dims.cols * dims.rows, this.maxPerCell); // Write grid uniforms this.writeUniforms(resources, program, { - minX, - minY, - maxX, - maxY, - cols, - rows, + minX: bounds.minX, + minY: bounds.minY, + maxX: bounds.maxX, + maxY: bounds.maxY, + cols: dims.cols, + rows: dims.rows, cellSize: this.cellSize, maxPerCell: this.maxPerCell, }); @@ -76,30 +82,11 @@ export class SpacialGrid { throw new Error("Cell size must be greater than 0"); } this.cellSize = cellSize; + this.geometry.setCellSize(cellSize); // Clear last view to force reconfiguration on next resizeIfNeeded/configure call this.lastView = null; } - private computeGrid(view: ViewSnapshot): { - minX: number; - minY: number; - maxX: number; - maxY: number; - cols: number; - rows: number; - } { - const zoom = Math.max(view.zoom, 0.0001); - const halfW = view.width / (2 * zoom); - const halfH = view.height / (2 * zoom); - const minX = view.cx - halfW; - const maxX = view.cx + halfW; - const minY = view.cy - halfH; - const maxY = view.cy + halfH; - const cols = Math.max(1, Math.ceil((maxX - minX) / this.cellSize)); - const rows = Math.max(1, Math.ceil((maxY - minY) / this.cellSize)); - return { minX, minY, maxX, maxY, cols, rows }; - } - private writeUniforms( resources: GPUResources, program: Program, diff --git a/packages/playground/src/components/ModulesSidebar.tsx b/packages/playground/src/components/ModulesSidebar.tsx index bf30940a..524e36a0 100644 --- a/packages/playground/src/components/ModulesSidebar.tsx +++ b/packages/playground/src/components/ModulesSidebar.tsx @@ -6,6 +6,9 @@ import { FluidsModule } from "./modules/FluidsModule"; import { BehaviorModule } from "./modules/BehaviorModule"; import { SensorsModule } from "./modules/SensorsModule"; import { JointsModule } from "./modules/JointsModule"; +import { GameOfLifeModule } from "./modules/GameOfLifeModule"; +import { ReactionDiffusionModule } from "./modules/ReactionDiffusionModule"; +import { ElementaryCAModule } from "./modules/ElementaryCAModule"; import { ModuleWrapper } from "./ModuleWrapper"; import { useEngine } from "../hooks/useEngine"; import { useOscillators } from "../hooks/useOscillators"; @@ -19,6 +22,9 @@ import { useBehavior, useSensors, useJoints, + useGameOfLife, + useReactionDiffusion, + useElementaryCA, } from "../hooks/modules"; import { RESTART_AFFECTED_MODULES } from "../constants/modules"; import "./ModulesSidebar.css"; @@ -33,6 +39,9 @@ export function ModulesSidebar() { behavior, sensors, joints, + gameOfLife, + reactionDiffusion, + elementaryCa, isSupported, } = useEngine(); @@ -74,6 +83,21 @@ export function ModulesSidebar() { setEnabled: setJointsEnabled, reset: resetJoints, } = useJoints(); + const { + isEnabled: isGameOfLifeEnabled, + setEnabled: setGameOfLifeEnabled, + reset: resetGameOfLife, + } = useGameOfLife(); + const { + isEnabled: isReactionDiffusionEnabled, + setEnabled: setReactionDiffusionEnabled, + reset: resetReactionDiffusion, + } = useReactionDiffusion(); + const { + isEnabled: isElementaryCAEnabled, + setEnabled: setElementaryCAEnabled, + reset: resetElementaryCA, + } = useElementaryCA(); return (
@@ -101,6 +125,9 @@ export function ModulesSidebar() { resetBehavior(); resetSensors(); resetJoints(); + resetGameOfLife(); + resetReactionDiffusion(); + resetElementaryCA(); // Clear reset flag after a brief delay setTimeout(() => setIsResetting(false), 10); @@ -181,6 +208,36 @@ export function ModulesSidebar() { + + + + + + + + + + + + {/* Interaction controls moved into the Interact tool; module UI removed */}
); diff --git a/packages/playground/src/components/modules/ElementaryCAModule.tsx b/packages/playground/src/components/modules/ElementaryCAModule.tsx new file mode 100644 index 00000000..85ea20fb --- /dev/null +++ b/packages/playground/src/components/modules/ElementaryCAModule.tsx @@ -0,0 +1,20 @@ +import { Slider } from "../ui/Slider"; +import { useElementaryCA } from "../../hooks/modules/useElementaryCA"; + +export function ElementaryCAModule({ enabled = true }: { enabled?: boolean }) { + const { rule, setRule } = useElementaryCA(); + + return ( + `${Math.floor(v)}`} + onChange={(v) => setRule(Math.floor(v))} + disabled={!enabled} + /> + ); +} diff --git a/packages/playground/src/components/modules/GameOfLifeModule.tsx b/packages/playground/src/components/modules/GameOfLifeModule.tsx new file mode 100644 index 00000000..bd54cd41 --- /dev/null +++ b/packages/playground/src/components/modules/GameOfLifeModule.tsx @@ -0,0 +1,51 @@ +import { Slider } from "../ui/Slider"; +import { useGameOfLife } from "../../hooks/modules/useGameOfLife"; + +export function GameOfLifeModule({ enabled = true }: { enabled?: boolean }) { + const { + birthMask, + surviveMask, + seedDensity, + setBirthMask, + setSurviveMask, + setSeedDensity, + } = useGameOfLife(); + + return ( + <> + `${Math.floor(v)}`} + onChange={(v) => setBirthMask(Math.floor(v))} + disabled={!enabled} + /> + `${Math.floor(v)}`} + onChange={(v) => setSurviveMask(Math.floor(v))} + disabled={!enabled} + /> + v.toFixed(2)} + onChange={setSeedDensity} + disabled={!enabled} + /> + + ); +} diff --git a/packages/playground/src/components/modules/ReactionDiffusionModule.tsx b/packages/playground/src/components/modules/ReactionDiffusionModule.tsx new file mode 100644 index 00000000..954fb713 --- /dev/null +++ b/packages/playground/src/components/modules/ReactionDiffusionModule.tsx @@ -0,0 +1,81 @@ +import { Slider } from "../ui/Slider"; +import { useReactionDiffusion } from "../../hooks/modules/useReactionDiffusion"; + +export function ReactionDiffusionModule({ + enabled = true, +}: { + enabled?: boolean; +}) { + const { + feed, + kill, + diffusionA, + diffusionB, + dt, + setFeed, + setKill, + setDiffusionA, + setDiffusionB, + setDt, + } = useReactionDiffusion(); + + return ( + <> + v.toFixed(4)} + onChange={setFeed} + disabled={!enabled} + /> + v.toFixed(4)} + onChange={setKill} + disabled={!enabled} + /> + v.toFixed(2)} + onChange={setDiffusionA} + disabled={!enabled} + /> + v.toFixed(2)} + onChange={setDiffusionB} + disabled={!enabled} + /> + v.toFixed(2)} + onChange={setDt} + disabled={!enabled} + /> + + ); +} diff --git a/packages/playground/src/constants/modules.ts b/packages/playground/src/constants/modules.ts index 4bc45ffb..2ebeabb4 100644 --- a/packages/playground/src/constants/modules.ts +++ b/packages/playground/src/constants/modules.ts @@ -7,6 +7,9 @@ export const RESTART_AFFECTED_MODULES = [ "behavior", "sensors", "interaction", + "gameOfLife", + "reactionDiffusion", + "elementaryCa", ]; export type RestartAffectedModule = (typeof RESTART_AFFECTED_MODULES)[number]; diff --git a/packages/playground/src/contexts/EngineContext.tsx b/packages/playground/src/contexts/EngineContext.tsx index d54204a8..cecbf960 100644 --- a/packages/playground/src/contexts/EngineContext.tsx +++ b/packages/playground/src/contexts/EngineContext.tsx @@ -19,6 +19,9 @@ import { Joints, Lines, Grab, + GameOfLifeGrid, + ReactionDiffusionGrid, + ElementaryCAGrid, } from "@cazala/party"; import { useEngineInternal } from "../hooks/useEngineInternal"; import { useWindowSize } from "../hooks/useWindowSize"; @@ -103,6 +106,9 @@ export interface EngineContextType { joints: Joints | null; lines: Lines | null; grab: Grab | null; + gameOfLife: GameOfLifeGrid | null; + reactionDiffusion: ReactionDiffusionGrid | null; + elementaryCa: ElementaryCAGrid | null; } export const EngineContext = createContext(null); diff --git a/packages/playground/src/hooks/modules/index.ts b/packages/playground/src/hooks/modules/index.ts index de3cba3e..6af188bf 100644 --- a/packages/playground/src/hooks/modules/index.ts +++ b/packages/playground/src/hooks/modules/index.ts @@ -11,3 +11,6 @@ export { useParticles } from "./useParticles"; export { useJoints } from "./useJoints"; export { useLines } from "./useLines"; export { useGrab } from "./useGrab"; +export { useGameOfLife } from "./useGameOfLife"; +export { useReactionDiffusion } from "./useReactionDiffusion"; +export { useElementaryCA } from "./useElementaryCA"; diff --git a/packages/playground/src/hooks/modules/useElementaryCA.ts b/packages/playground/src/hooks/modules/useElementaryCA.ts new file mode 100644 index 00000000..0abb8a02 --- /dev/null +++ b/packages/playground/src/hooks/modules/useElementaryCA.ts @@ -0,0 +1,54 @@ +import { useCallback, useEffect, useMemo } from "react"; +import { useAppDispatch } from "../useAppDispatch"; +import { useAppSelector } from "../useAppSelector"; +import { useEngine } from "../useEngine"; +import { selectModules } from "../../slices/modules"; +import { + selectElementaryCA, + setElementaryCAEnabled, + setElementaryCARule, + resetElementaryCA, +} from "../../slices/modules/elementaryCa"; + +export function useElementaryCA() { + const dispatch = useAppDispatch(); + const { elementaryCa } = useEngine(); + + const modulesState = useAppSelector(selectModules); + const state = useMemo(() => selectElementaryCA(modulesState), [modulesState]); + const isEnabled = state.enabled; + + useEffect(() => { + if (!elementaryCa) return; + elementaryCa.write({ + rule: state.rule, + }); + }, [elementaryCa, state]); + + const setEnabled = useCallback( + (enabled: boolean) => { + dispatch(setElementaryCAEnabled(enabled)); + }, + [dispatch] + ); + + const setRule = useCallback( + (value: number) => { + dispatch(setElementaryCARule(value)); + elementaryCa?.write({ rule: value }); + }, + [dispatch, elementaryCa] + ); + + const reset = useCallback(() => { + dispatch(resetElementaryCA()); + }, [dispatch]); + + return { + ...state, + isEnabled, + setEnabled, + setRule, + reset, + }; +} diff --git a/packages/playground/src/hooks/modules/useGameOfLife.ts b/packages/playground/src/hooks/modules/useGameOfLife.ts new file mode 100644 index 00000000..8bbad75e --- /dev/null +++ b/packages/playground/src/hooks/modules/useGameOfLife.ts @@ -0,0 +1,76 @@ +import { useCallback, useEffect, useMemo } from "react"; +import { useAppDispatch } from "../useAppDispatch"; +import { useAppSelector } from "../useAppSelector"; +import { useEngine } from "../useEngine"; +import { selectModules } from "../../slices/modules"; +import { + selectGameOfLife, + setGameOfLifeEnabled, + setGameOfLifeBirthMask, + setGameOfLifeSurviveMask, + setGameOfLifeSeedDensity, + resetGameOfLife, +} from "../../slices/modules/gameOfLife"; + +export function useGameOfLife() { + const dispatch = useAppDispatch(); + const { gameOfLife } = useEngine(); + + const modulesState = useAppSelector(selectModules); + const state = useMemo(() => selectGameOfLife(modulesState), [modulesState]); + const isEnabled = state.enabled; + + useEffect(() => { + if (!gameOfLife) return; + gameOfLife.write({ + birthMask: state.birthMask, + surviveMask: state.surviveMask, + seedDensity: state.seedDensity, + }); + }, [gameOfLife, state]); + + const setEnabled = useCallback( + (enabled: boolean) => { + dispatch(setGameOfLifeEnabled(enabled)); + }, + [dispatch] + ); + + const setBirthMask = useCallback( + (value: number) => { + dispatch(setGameOfLifeBirthMask(value)); + gameOfLife?.write({ birthMask: value }); + }, + [dispatch, gameOfLife] + ); + + const setSurviveMask = useCallback( + (value: number) => { + dispatch(setGameOfLifeSurviveMask(value)); + gameOfLife?.write({ surviveMask: value }); + }, + [dispatch, gameOfLife] + ); + + const setSeedDensity = useCallback( + (value: number) => { + dispatch(setGameOfLifeSeedDensity(value)); + gameOfLife?.write({ seedDensity: value }); + }, + [dispatch, gameOfLife] + ); + + const reset = useCallback(() => { + dispatch(resetGameOfLife()); + }, [dispatch]); + + return { + ...state, + isEnabled, + setEnabled, + setBirthMask, + setSurviveMask, + setSeedDensity, + reset, + }; +} diff --git a/packages/playground/src/hooks/modules/useReactionDiffusion.ts b/packages/playground/src/hooks/modules/useReactionDiffusion.ts new file mode 100644 index 00000000..a9246217 --- /dev/null +++ b/packages/playground/src/hooks/modules/useReactionDiffusion.ts @@ -0,0 +1,101 @@ +import { useCallback, useEffect, useMemo } from "react"; +import { useAppDispatch } from "../useAppDispatch"; +import { useAppSelector } from "../useAppSelector"; +import { useEngine } from "../useEngine"; +import { selectModules } from "../../slices/modules"; +import { + selectReactionDiffusion, + setReactionDiffusionEnabled, + setReactionDiffusionFeed, + setReactionDiffusionKill, + setReactionDiffusionDiffusionA, + setReactionDiffusionDiffusionB, + setReactionDiffusionDt, + resetReactionDiffusion, +} from "../../slices/modules/reactionDiffusion"; + +export function useReactionDiffusion() { + const dispatch = useAppDispatch(); + const { reactionDiffusion } = useEngine(); + + const modulesState = useAppSelector(selectModules); + const state = useMemo( + () => selectReactionDiffusion(modulesState), + [modulesState] + ); + const isEnabled = state.enabled; + + useEffect(() => { + if (!reactionDiffusion) return; + reactionDiffusion.write({ + feed: state.feed, + kill: state.kill, + diffusionA: state.diffusionA, + diffusionB: state.diffusionB, + dt: state.dt, + }); + }, [reactionDiffusion, state]); + + const setEnabled = useCallback( + (enabled: boolean) => { + dispatch(setReactionDiffusionEnabled(enabled)); + }, + [dispatch] + ); + + const setFeed = useCallback( + (value: number) => { + dispatch(setReactionDiffusionFeed(value)); + reactionDiffusion?.write({ feed: value }); + }, + [dispatch, reactionDiffusion] + ); + + const setKill = useCallback( + (value: number) => { + dispatch(setReactionDiffusionKill(value)); + reactionDiffusion?.write({ kill: value }); + }, + [dispatch, reactionDiffusion] + ); + + const setDiffusionA = useCallback( + (value: number) => { + dispatch(setReactionDiffusionDiffusionA(value)); + reactionDiffusion?.write({ diffusionA: value }); + }, + [dispatch, reactionDiffusion] + ); + + const setDiffusionB = useCallback( + (value: number) => { + dispatch(setReactionDiffusionDiffusionB(value)); + reactionDiffusion?.write({ diffusionB: value }); + }, + [dispatch, reactionDiffusion] + ); + + const setDt = useCallback( + (value: number) => { + dispatch(setReactionDiffusionDt(value)); + reactionDiffusion?.write({ dt: value }); + }, + [dispatch, reactionDiffusion] + ); + + const reset = useCallback(() => { + dispatch(resetReactionDiffusion()); + }, [dispatch]); + + return { + ...state, + isEnabled, + setEnabled, + setFeed, + setKill, + setDiffusionA, + setDiffusionB, + setDt, + reset, + }; +} diff --git a/packages/playground/src/hooks/useEngineInternal.ts b/packages/playground/src/hooks/useEngineInternal.ts index b3c2bd87..ed1aa067 100644 --- a/packages/playground/src/hooks/useEngineInternal.ts +++ b/packages/playground/src/hooks/useEngineInternal.ts @@ -13,6 +13,9 @@ import { Joints, Lines, Grab, + GameOfLifeGrid, + ReactionDiffusionGrid, + ElementaryCAGrid, } from "@cazala/party"; import { useAppDispatch } from "./useAppDispatch"; import { useAppSelector } from "./useAppSelector"; @@ -71,6 +74,9 @@ import { importParticlesSettings, importLinesSettings, importJointsSettings, + importGameOfLifeSettings, + importReactionDiffusionSettings, + importElementaryCASettings, } from "../slices/modules"; export interface UseEngineProps { @@ -112,6 +118,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { const jointsRef = useRef(null); const linesRef = useRef(null); const grabRef = useRef(null); + const gameOfLifeRef = useRef(null); + const reactionDiffusionRef = useRef(null); + const elementaryCaRef = useRef(null); // Local state for engine initialization const [isAutoMode, setIsAutoMode] = useState(true); @@ -184,6 +193,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { particlesRef.current = null; jointsRef.current = null; linesRef.current = null; + gameOfLifeRef.current = null; + reactionDiffusionRef.current = null; + elementaryCaRef.current = null; registerEngine(null); } catch (err) { console.warn("Error cleaning up previous engine:", err); @@ -275,6 +287,30 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { const lines = new Lines({ enabled: false }); const grab = new Grab({ enabled: false }); + const gridWidth = Math.min( + 512, + Math.max(64, Math.floor(canvasWidth)) + ); + const gridHeight = Math.min( + 512, + Math.max(64, Math.floor(canvasHeight)) + ); + const gameOfLife = new GameOfLifeGrid({ + width: gridWidth, + height: gridHeight, + }); + const reactionDiffusion = new ReactionDiffusionGrid({ + width: gridWidth, + height: gridHeight, + }); + const elementaryCa = new ElementaryCAGrid({ + width: gridWidth, + height: gridHeight, + }); + gameOfLife.setEnabled(false); + reactionDiffusion.setEnabled(false); + elementaryCa.setEnabled(false); + // Create particles renderer const particles = new Particles(); @@ -290,12 +326,14 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { grab, ]; const render = [trails, lines, particles]; + const grids = [gameOfLife, reactionDiffusion, elementaryCa]; // Create engine with device-appropriate maxParticles const engine = new Engine({ canvas, forces, render, + grids, runtime: requestedRuntime, maxParticles, }); @@ -331,6 +369,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { jointsRef.current = joints; linesRef.current = lines; grabRef.current = grab; + gameOfLifeRef.current = gameOfLife; + reactionDiffusionRef.current = reactionDiffusion; + elementaryCaRef.current = elementaryCa; // Register engine for thunks registerEngine(engine); @@ -387,6 +428,11 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { dispatch(importJointsSettings(modules.joints)); dispatch(importLinesSettings(modules.lines)); dispatch(importParticlesSettings(modules.particles)); + dispatch(importGameOfLifeSettings(modules.gameOfLife)); + dispatch( + importReactionDiffusionSettings(modules.reactionDiffusion) + ); + dispatch(importElementaryCASettings(modules.elementaryCa)); } } @@ -430,6 +476,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { particlesRef.current = null; jointsRef.current = null; linesRef.current = null; + gameOfLifeRef.current = null; + reactionDiffusionRef.current = null; + elementaryCaRef.current = null; registerEngine(null); }; } catch (err) { @@ -511,6 +560,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { const particles = particlesRef.current; const joints = jointsRef.current; const lines = linesRef.current; + const gameOfLife = gameOfLifeRef.current; + const reactionDiffusion = reactionDiffusionRef.current; + const elementaryCa = elementaryCaRef.current; try { // Apply module enabled/disabled states from Redux to module instances if (environment && environment.setEnabled) { @@ -556,6 +608,15 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { if (lines && lines.setEnabled) { lines.setEnabled(modulesState.lines.enabled); } + if (gameOfLife && gameOfLife.setEnabled) { + gameOfLife.setEnabled(modulesState.gameOfLife.enabled); + } + if (reactionDiffusion && reactionDiffusion.setEnabled) { + reactionDiffusion.setEnabled(modulesState.reactionDiffusion.enabled); + } + if (elementaryCa && elementaryCa.setEnabled) { + elementaryCa.setEnabled(modulesState.elementaryCa.enabled); + } } catch (err) { console.warn("Error applying module states:", err); } @@ -574,6 +635,9 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { modulesState.particles.enabled, modulesState.joints.enabled, modulesState.lines.enabled, + modulesState.gameOfLife.enabled, + modulesState.reactionDiffusion.enabled, + modulesState.elementaryCa.enabled, ]); // Action functions (wrapped thunks) @@ -778,5 +842,8 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { joints: jointsRef.current, lines: linesRef.current, grab: grabRef.current, + gameOfLife: gameOfLifeRef.current, + reactionDiffusion: reactionDiffusionRef.current, + elementaryCa: elementaryCaRef.current, }; } diff --git a/packages/playground/src/slices/modules/elementaryCa.ts b/packages/playground/src/slices/modules/elementaryCa.ts new file mode 100644 index 00000000..8138c4f1 --- /dev/null +++ b/packages/playground/src/slices/modules/elementaryCa.ts @@ -0,0 +1,45 @@ +import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { DEFAULT_ECA_RULE } from "@cazala/party"; + +export interface ElementaryCAModuleState { + enabled: boolean; + rule: number; +} + +const initialState: ElementaryCAModuleState = { + enabled: false, + rule: DEFAULT_ECA_RULE, +}; + +export const elementaryCaSlice = createSlice({ + name: "elementaryCa", + initialState, + reducers: { + setElementaryCAEnabled: (state, action: PayloadAction) => { + state.enabled = action.payload; + }, + setElementaryCARule: (state, action: PayloadAction) => { + state.rule = action.payload; + }, + resetElementaryCA: () => initialState, + importElementaryCASettings: ( + state, + action: PayloadAction> + ) => { + Object.assign(state, action.payload); + }, + }, +}); + +export const { + setElementaryCAEnabled, + setElementaryCARule, + resetElementaryCA, + importElementaryCASettings, +} = elementaryCaSlice.actions; + +export const elementaryCaReducer = elementaryCaSlice.reducer; + +export const selectElementaryCA = (state: { + elementaryCa: ElementaryCAModuleState; +}) => state.elementaryCa; diff --git a/packages/playground/src/slices/modules/gameOfLife.ts b/packages/playground/src/slices/modules/gameOfLife.ts new file mode 100644 index 00000000..9aff53ae --- /dev/null +++ b/packages/playground/src/slices/modules/gameOfLife.ts @@ -0,0 +1,60 @@ +import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { + DEFAULT_GOL_BIRTH_MASK, + DEFAULT_GOL_SURVIVE_MASK, + DEFAULT_GOL_SEED_DENSITY, +} from "@cazala/party"; + +export interface GameOfLifeModuleState { + enabled: boolean; + birthMask: number; + surviveMask: number; + seedDensity: number; +} + +const initialState: GameOfLifeModuleState = { + enabled: false, + birthMask: DEFAULT_GOL_BIRTH_MASK, + surviveMask: DEFAULT_GOL_SURVIVE_MASK, + seedDensity: DEFAULT_GOL_SEED_DENSITY, +}; + +export const gameOfLifeSlice = createSlice({ + name: "gameOfLife", + initialState, + reducers: { + setGameOfLifeEnabled: (state, action: PayloadAction) => { + state.enabled = action.payload; + }, + setGameOfLifeBirthMask: (state, action: PayloadAction) => { + state.birthMask = action.payload; + }, + setGameOfLifeSurviveMask: (state, action: PayloadAction) => { + state.surviveMask = action.payload; + }, + setGameOfLifeSeedDensity: (state, action: PayloadAction) => { + state.seedDensity = action.payload; + }, + resetGameOfLife: () => initialState, + importGameOfLifeSettings: ( + state, + action: PayloadAction> + ) => { + Object.assign(state, action.payload); + }, + }, +}); + +export const { + setGameOfLifeEnabled, + setGameOfLifeBirthMask, + setGameOfLifeSurviveMask, + setGameOfLifeSeedDensity, + resetGameOfLife, + importGameOfLifeSettings, +} = gameOfLifeSlice.actions; + +export const gameOfLifeReducer = gameOfLifeSlice.reducer; + +export const selectGameOfLife = (state: { gameOfLife: GameOfLifeModuleState }) => + state.gameOfLife; diff --git a/packages/playground/src/slices/modules/index.ts b/packages/playground/src/slices/modules/index.ts index 6df7d36f..f02b7f1a 100644 --- a/packages/playground/src/slices/modules/index.ts +++ b/packages/playground/src/slices/modules/index.ts @@ -11,6 +11,15 @@ import { particlesReducer, ParticlesModuleState } from "./particles"; import { jointsReducer, JointsModuleState } from "./joints"; import { linesReducer, LinesModuleState } from "./lines"; import { grabReducer, GrabModuleState } from "./grab"; +import { gameOfLifeReducer, GameOfLifeModuleState } from "./gameOfLife"; +import { + reactionDiffusionReducer, + ReactionDiffusionModuleState, +} from "./reactionDiffusion"; +import { + elementaryCaReducer, + ElementaryCAModuleState, +} from "./elementaryCa"; // Re-export all module types export type { @@ -26,6 +35,9 @@ export type { JointsModuleState, LinesModuleState, GrabModuleState, + GameOfLifeModuleState, + ReactionDiffusionModuleState, + ElementaryCAModuleState, }; // Re-export all module actions and reducers @@ -41,6 +53,9 @@ export * from "./particles"; export * from "./joints"; export * from "./lines"; export * from "./grab"; +export * from "./gameOfLife"; +export * from "./reactionDiffusion"; +export * from "./elementaryCa"; // Re-export combinedReducer for easier imports export interface ModulesState { @@ -56,6 +71,9 @@ export interface ModulesState { joints: JointsModuleState; lines: LinesModuleState; grab: GrabModuleState; + gameOfLife: GameOfLifeModuleState; + reactionDiffusion: ReactionDiffusionModuleState; + elementaryCa: ElementaryCAModuleState; } export const modulesReducer = combineReducers({ @@ -71,6 +89,9 @@ export const modulesReducer = combineReducers({ joints: jointsReducer, lines: linesReducer, grab: grabReducer, + gameOfLife: gameOfLifeReducer, + reactionDiffusion: reactionDiffusionReducer, + elementaryCa: elementaryCaReducer, }); // Global selectors diff --git a/packages/playground/src/slices/modules/reactionDiffusion.ts b/packages/playground/src/slices/modules/reactionDiffusion.ts new file mode 100644 index 00000000..0af2c102 --- /dev/null +++ b/packages/playground/src/slices/modules/reactionDiffusion.ts @@ -0,0 +1,75 @@ +import { createSlice, PayloadAction } from "@reduxjs/toolkit"; +import { + DEFAULT_RD_FEED, + DEFAULT_RD_KILL, + DEFAULT_RD_DIFFUSION_A, + DEFAULT_RD_DIFFUSION_B, + DEFAULT_RD_DT, +} from "@cazala/party"; + +export interface ReactionDiffusionModuleState { + enabled: boolean; + feed: number; + kill: number; + diffusionA: number; + diffusionB: number; + dt: number; +} + +const initialState: ReactionDiffusionModuleState = { + enabled: false, + feed: DEFAULT_RD_FEED, + kill: DEFAULT_RD_KILL, + diffusionA: DEFAULT_RD_DIFFUSION_A, + diffusionB: DEFAULT_RD_DIFFUSION_B, + dt: DEFAULT_RD_DT, +}; + +export const reactionDiffusionSlice = createSlice({ + name: "reactionDiffusion", + initialState, + reducers: { + setReactionDiffusionEnabled: (state, action: PayloadAction) => { + state.enabled = action.payload; + }, + setReactionDiffusionFeed: (state, action: PayloadAction) => { + state.feed = action.payload; + }, + setReactionDiffusionKill: (state, action: PayloadAction) => { + state.kill = action.payload; + }, + setReactionDiffusionDiffusionA: (state, action: PayloadAction) => { + state.diffusionA = action.payload; + }, + setReactionDiffusionDiffusionB: (state, action: PayloadAction) => { + state.diffusionB = action.payload; + }, + setReactionDiffusionDt: (state, action: PayloadAction) => { + state.dt = action.payload; + }, + resetReactionDiffusion: () => initialState, + importReactionDiffusionSettings: ( + state, + action: PayloadAction> + ) => { + Object.assign(state, action.payload); + }, + }, +}); + +export const { + setReactionDiffusionEnabled, + setReactionDiffusionFeed, + setReactionDiffusionKill, + setReactionDiffusionDiffusionA, + setReactionDiffusionDiffusionB, + setReactionDiffusionDt, + resetReactionDiffusion, + importReactionDiffusionSettings, +} = reactionDiffusionSlice.actions; + +export const reactionDiffusionReducer = reactionDiffusionSlice.reducer; + +export const selectReactionDiffusion = (state: { + reactionDiffusion: ReactionDiffusionModuleState; +}) => state.reactionDiffusion; diff --git a/packages/playground/src/slices/session.ts b/packages/playground/src/slices/session.ts index 2050814a..bf2ff26e 100644 --- a/packages/playground/src/slices/session.ts +++ b/packages/playground/src/slices/session.ts @@ -63,6 +63,15 @@ import { setLinesEnabled, importGrabSettings, setGrabEnabled, + resetGameOfLife, + importGameOfLifeSettings, + setGameOfLifeEnabled, + resetReactionDiffusion, + importReactionDiffusionSettings, + setReactionDiffusionEnabled, + resetElementaryCA, + importElementaryCASettings, + setElementaryCAEnabled, } from "./modules"; import { initReducer, selectInitState } from "./init"; import { engineReducer } from "./engine"; @@ -153,6 +162,35 @@ const loadModuleSettings = ( } } + if (RESTART_AFFECTED_MODULES.includes("gameOfLife")) { + dispatch(resetGameOfLife()); + if (sessionData.modules?.gameOfLife) { + dispatch(importGameOfLifeSettings(sessionData.modules.gameOfLife)); + } else { + dispatch(setGameOfLifeEnabled(false)); + } + } + + if (RESTART_AFFECTED_MODULES.includes("reactionDiffusion")) { + dispatch(resetReactionDiffusion()); + if (sessionData.modules?.reactionDiffusion) { + dispatch( + importReactionDiffusionSettings(sessionData.modules.reactionDiffusion) + ); + } else { + dispatch(setReactionDiffusionEnabled(false)); + } + } + + if (RESTART_AFFECTED_MODULES.includes("elementaryCa")) { + dispatch(resetElementaryCA()); + if (sessionData.modules?.elementaryCa) { + dispatch(importElementaryCASettings(sessionData.modules.elementaryCa)); + } else { + dispatch(setElementaryCAEnabled(false)); + } + } + // Handle joints separately since quickload doesn't restore joints connections if (includeJoints) { dispatch(resetJoints()); @@ -458,6 +496,29 @@ const applyFullSessionLoad = async ( dispatch(setSensorsEnabled(false)); } + dispatch(resetGameOfLife()); + if (sessionData.modules?.gameOfLife) { + dispatch(importGameOfLifeSettings(sessionData.modules.gameOfLife)); + } else { + dispatch(setGameOfLifeEnabled(false)); + } + + dispatch(resetReactionDiffusion()); + if (sessionData.modules?.reactionDiffusion) { + dispatch( + importReactionDiffusionSettings(sessionData.modules.reactionDiffusion) + ); + } else { + dispatch(setReactionDiffusionEnabled(false)); + } + + dispatch(resetElementaryCA()); + if (sessionData.modules?.elementaryCa) { + dispatch(importElementaryCASettings(sessionData.modules.elementaryCa)); + } else { + dispatch(setElementaryCAEnabled(false)); + } + dispatch(resetJoints()); if (sessionData.modules?.joints) { dispatch(importJointsSettings(sessionData.modules.joints)); From c20c1803007fb896d181424e20af17d206f59387 Mon Sep 17 00:00:00 2001 From: Juan Cazala Date: Wed, 28 Jan 2026 19:21:59 -0300 Subject: [PATCH 2/2] fixes --- docs/module-author-guide.md | 17 ++ packages/core/src/engine.ts | 3 + packages/core/src/grid/store.ts | 44 ++++++ packages/core/src/interfaces.ts | 5 + packages/core/src/module.ts | 8 +- .../core/src/modules/grids/elementary-ca.ts | 46 +++++- .../core/src/modules/grids/game-of-life.ts | 51 +++++- .../src/modules/grids/reaction-diffusion.ts | 67 +++++++- packages/core/src/runtimes/cpu/engine.ts | 120 +++++++++++++- packages/core/src/runtimes/webgpu/engine.ts | 146 +++++++++++++++++- .../core/src/runtimes/webgpu/gpu-resources.ts | 3 + .../core/src/runtimes/webgpu/grid-pipeline.ts | 16 +- .../src/runtimes/webgpu/module-registry.ts | 17 +- .../components/modules/ElementaryCAModule.tsx | 37 +++-- .../components/modules/GameOfLifeModule.tsx | 13 ++ .../modules/ReactionDiffusionModule.tsx | 13 ++ .../playground/src/contexts/EngineContext.tsx | 1 + .../src/hooks/modules/useElementaryCA.ts | 17 +- .../src/hooks/modules/useGameOfLife.ts | 17 +- .../src/hooks/modules/useReactionDiffusion.ts | 17 +- .../tools/individual-tools/useBrushTool.ts | 16 +- .../tools/individual-tools/useShapeTool.ts | 5 +- .../tools/individual-tools/useSpawnTool.ts | 12 +- .../playground/src/hooks/useEngineInternal.ts | 120 ++++++++++++++ .../src/slices/modules/elementaryCa.ts | 8 +- .../src/slices/modules/gameOfLife.ts | 7 + .../src/slices/modules/reactionDiffusion.ts | 7 + 27 files changed, 787 insertions(+), 46 deletions(-) diff --git a/docs/module-author-guide.md b/docs/module-author-guide.md index a1730987..3ed38138 100644 --- a/docs/module-author-guide.md +++ b/docs/module-author-guide.md @@ -178,6 +178,23 @@ 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)). diff --git a/packages/core/src/engine.ts b/packages/core/src/engine.ts index da124f98..8d5853ad 100644 --- a/packages/core/src/engine.ts +++ b/packages/core/src/engine.ts @@ -287,6 +287,9 @@ export class Engine implements IEngine { import(settings: Record>): void { this.engine.import(settings); } + notifyModuleSettingsChanged(): void { + this.engine.notifyModuleSettingsChanged(); + } // Configuration getters and setters getClearColor(): { r: number; g: number; b: number; a: number } { diff --git a/packages/core/src/grid/store.ts b/packages/core/src/grid/store.ts index e5ce2c75..406160f9 100644 --- a/packages/core/src/grid/store.ts +++ b/packages/core/src/grid/store.ts @@ -44,6 +44,50 @@ export function createGridBuffer(spec: GridSpec, length?: number): GridBuffer { } } +export function resampleGridBuffer( + source: ArrayBufferView, + sourceSpec: GridSpec, + targetSpec: GridSpec, + opts: { forceFloat?: boolean } = {} +): GridBuffer | Float32Array { + const srcWidth = Math.max(1, sourceSpec.width); + const srcHeight = Math.max(1, sourceSpec.height); + const srcChannels = getGridChannelCount(sourceSpec); + const dstWidth = Math.max(1, targetSpec.width); + const dstHeight = Math.max(1, targetSpec.height); + const dstChannels = getGridChannelCount(targetSpec); + + const dst = opts.forceFloat + ? new Float32Array(dstWidth * dstHeight * dstChannels) + : createGridBuffer(targetSpec, dstWidth * dstHeight * dstChannels); + + const src = source as any; + const maxSrcX = Math.max(0, srcWidth - 1); + const maxSrcY = Math.max(0, srcHeight - 1); + const maxDstX = Math.max(1, dstWidth - 1); + const maxDstY = Math.max(1, dstHeight - 1); + const channelCopyCount = Math.min(srcChannels, dstChannels); + + for (let y = 0; y < dstHeight; y++) { + const v = maxDstY === 0 ? 0 : y / maxDstY; + const sy = Math.min(maxSrcY, Math.max(0, Math.round(v * maxSrcY))); + for (let x = 0; x < dstWidth; x++) { + const u = maxDstX === 0 ? 0 : x / maxDstX; + const sx = Math.min(maxSrcX, Math.max(0, Math.round(u * maxSrcX))); + const srcBase = (sy * srcWidth + sx) * srcChannels; + const dstBase = (y * dstWidth + x) * dstChannels; + for (let c = 0; c < channelCopyCount; c++) { + (dst as any)[dstBase + c] = src[srcBase + c] ?? 0; + } + for (let c = channelCopyCount; c < dstChannels; c++) { + (dst as any)[dstBase + c] = 0; + } + } + } + + return dst; +} + export class GridStore { readonly spec: GridSpec; readonly width: number; diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts index 072ab6ac..71e61ada 100644 --- a/packages/core/src/interfaces.ts +++ b/packages/core/src/interfaces.ts @@ -78,6 +78,7 @@ export interface IEngine { getFPS(): number; export(): Record>; import(settings: Record>): void; + notifyModuleSettingsChanged(): void; // Configuration getters and setters getClearColor(): { r: number; g: number; b: number; a: number }; @@ -404,6 +405,10 @@ export abstract class AbstractEngine implements IEngine { this.onModuleSettingsChanged(); } + notifyModuleSettingsChanged(): void { + this.onModuleSettingsChanged(); + } + // Protected helper methods protected updateFPS(dt: number): void { if (dt > 0) { diff --git a/packages/core/src/module.ts b/packages/core/src/module.ts index 675da76d..ebededf5 100644 --- a/packages/core/src/module.ts +++ b/packages/core/src/module.ts @@ -1,5 +1,5 @@ import { Particle } from "./particle"; -import { View } from "./view"; +import { View, type ViewSnapshot } from "./view"; /** * Module descriptors and base Module class @@ -450,6 +450,8 @@ export interface CPUGridDescriptor< write: (x: number, y: number, value: number | number[]) => void; sample: (x: number, y: number, channel?: number) => number; grid: GridStoreLike; + particles: Particle[]; + view: ViewSnapshot; }) => void; step: (args: { input: Inputs; @@ -460,6 +462,8 @@ export interface CPUGridDescriptor< write: (x: number, y: number, value: number | number[]) => void; sample: (x: number, y: number, channel?: number) => number; grid: GridStoreLike; + particles: Particle[]; + view: ViewSnapshot; }) => void; post?: (args: { input: Inputs; @@ -470,6 +474,8 @@ export interface CPUGridDescriptor< write: (x: number, y: number, value: number | number[]) => void; sample: (x: number, y: number, channel?: number) => number; grid: GridStoreLike; + particles: Particle[]; + view: ViewSnapshot; }) => void; render?: CPURenderDescriptor; } diff --git a/packages/core/src/modules/grids/elementary-ca.ts b/packages/core/src/modules/grids/elementary-ca.ts index 07f8cf35..858f6c7a 100644 --- a/packages/core/src/modules/grids/elementary-ca.ts +++ b/packages/core/src/modules/grids/elementary-ca.ts @@ -8,17 +8,23 @@ import { CanvasComposition, type GridSpec, } from "../../module"; +import type { IParticle } from "../../interfaces"; +import type { ViewSnapshot } from "../../view"; export type ElementaryCAInputs = { rule: number; + cellSize: number; }; export const DEFAULT_ECA_RULE = 30; +export const DEFAULT_ECA_CELL_SIZE = 2; export type ElementaryCAOptions = { width: number; height: number; rule?: number; + cellSize?: number; + followView?: boolean; }; export class ElementaryCAGrid extends Module<"elementaryCA", ElementaryCAInputs> { @@ -26,6 +32,7 @@ export class ElementaryCAGrid extends Module<"elementaryCA", ElementaryCAInputs> readonly role = ModuleRole.Grid; readonly inputs = { rule: DataType.NUMBER, + cellSize: DataType.NUMBER, } as const; readonly gridSpec: GridSpec; private renderCanvas?: HTMLCanvasElement; @@ -39,15 +46,50 @@ export class ElementaryCAGrid extends Module<"elementaryCA", ElementaryCAInputs> height: options.height, format: "u8", wrap: "clamp", + cellSize: options.cellSize ?? DEFAULT_ECA_CELL_SIZE, + followView: options.followView ?? true, }; this.write({ rule: options.rule ?? DEFAULT_ECA_RULE, + cellSize: options.cellSize ?? DEFAULT_ECA_CELL_SIZE, }); } + private seedFromParticles( + particles: IParticle[], + view: ViewSnapshot, + buffer: Float32Array + ): boolean { + if (!particles || particles.length === 0) return false; + const width = this.gridSpec.width; + const height = this.gridSpec.height; + buffer.fill(0); + const centerX = view.width / 2; + for (const particle of particles) { + if (particle.mass === 0) continue; + const screenX = centerX + (particle.position.x - view.cx) * view.zoom; + const gx = Math.floor((screenX / view.width) * width); + if (gx < 0 || gx >= width) continue; + buffer[gx] = 1; + } + // Only seed the first row; remaining rows stay zero. + return true; + } + + seedFromParticlesBuffer( + particles: IParticle[], + view: ViewSnapshot + ): Float32Array | null { + const total = this.gridSpec.width * this.gridSpec.height; + const buffer = new Float32Array(total); + return this.seedFromParticles(particles, view, buffer) ? buffer : null; + } + cpu(): CPUDescriptor { return { - init: ({ grid }) => { + init: ({ grid, particles, view }) => { + const buf = grid.writeBuffer as Float32Array; + if (this.seedFromParticles(particles, view, buf)) return; const width = grid.width; const height = grid.height; for (let y = 0; y < height; y++) { @@ -158,6 +200,8 @@ if (y == 0) { { kind: RenderPassKind.Fullscreen, bindings: [], + instanced: false, + writesScene: true, fragment: () => `{ let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); diff --git a/packages/core/src/modules/grids/game-of-life.ts b/packages/core/src/modules/grids/game-of-life.ts index 2895798b..74a0963c 100644 --- a/packages/core/src/modules/grids/game-of-life.ts +++ b/packages/core/src/modules/grids/game-of-life.ts @@ -8,21 +8,27 @@ import { CanvasComposition, type GridSpec, } from "../../module"; +import type { IParticle } from "../../interfaces"; +import type { ViewSnapshot } from "../../view"; export type GameOfLifeInputs = { birthMask: number; surviveMask: number; seedDensity: number; + cellSize: number; }; export const DEFAULT_GOL_BIRTH_MASK = 1 << 3; export const DEFAULT_GOL_SURVIVE_MASK = (1 << 2) | (1 << 3); export const DEFAULT_GOL_SEED_DENSITY = 0.15; +export const DEFAULT_GOL_CELL_SIZE = 2; export type GameOfLifeOptions = { width: number; height: number; seedDensity?: number; + cellSize?: number; + followView?: boolean; }; export class GameOfLifeGrid extends Module<"gameOfLife", GameOfLifeInputs> { @@ -32,6 +38,7 @@ export class GameOfLifeGrid extends Module<"gameOfLife", GameOfLifeInputs> { birthMask: DataType.NUMBER, surviveMask: DataType.NUMBER, seedDensity: DataType.NUMBER, + cellSize: DataType.NUMBER, } as const; readonly gridSpec: GridSpec; private renderCanvas?: HTMLCanvasElement; @@ -45,21 +52,57 @@ export class GameOfLifeGrid extends Module<"gameOfLife", GameOfLifeInputs> { height: options.height, format: "u8", wrap: "clamp", + cellSize: options.cellSize ?? DEFAULT_GOL_CELL_SIZE, + followView: options.followView ?? true, }; this.write({ birthMask: DEFAULT_GOL_BIRTH_MASK, // B3 surviveMask: DEFAULT_GOL_SURVIVE_MASK, // S23 seedDensity: options.seedDensity ?? DEFAULT_GOL_SEED_DENSITY, + cellSize: options.cellSize ?? DEFAULT_GOL_CELL_SIZE, }); } + private seedFromParticles( + particles: IParticle[], + view: ViewSnapshot, + buffer: Float32Array + ): boolean { + if (!particles || particles.length === 0) return false; + const width = this.gridSpec.width; + const height = this.gridSpec.height; + buffer.fill(0); + const centerX = view.width / 2; + const centerY = view.height / 2; + for (const particle of particles) { + if (particle.mass === 0) continue; + const screenX = centerX + (particle.position.x - view.cx) * view.zoom; + const screenY = centerY + (particle.position.y - view.cy) * view.zoom; + const gx = Math.floor((screenX / view.width) * width); + const gy = Math.floor((screenY / view.height) * height); + if (gx < 0 || gy < 0 || gx >= width || gy >= height) continue; + buffer[gy * width + gx] = 1; + } + return true; + } + + seedFromParticlesBuffer( + particles: IParticle[], + view: ViewSnapshot + ): Float32Array | null { + const total = this.gridSpec.width * this.gridSpec.height; + const buffer = new Float32Array(total); + return this.seedFromParticles(particles, view, buffer) ? buffer : null; + } + cpu(): CPUDescriptor { return { - init: ({ grid, input }) => { + init: ({ grid, input, particles, view }) => { + const buf = grid.writeBuffer as Float32Array; + if (this.seedFromParticles(particles, view, buf)) return; const total = grid.width * grid.height; for (let i = 0; i < total; i++) { - (grid.writeBuffer as any)[i] = - Math.random() < input.seedDensity ? 1 : 0; + buf[i] = Math.random() < input.seedDensity ? 1 : 0; } }, step: ({ grid, input }) => { @@ -163,6 +206,8 @@ grid_write(x, y, 0u, f32(bit)); { kind: RenderPassKind.Fullscreen, bindings: [], + instanced: false, + writesScene: true, fragment: () => `{ let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); diff --git a/packages/core/src/modules/grids/reaction-diffusion.ts b/packages/core/src/modules/grids/reaction-diffusion.ts index 82fc900b..4cbca05c 100644 --- a/packages/core/src/modules/grids/reaction-diffusion.ts +++ b/packages/core/src/modules/grids/reaction-diffusion.ts @@ -8,6 +8,8 @@ import { CanvasComposition, type GridSpec, } from "../../module"; +import type { IParticle } from "../../interfaces"; +import type { ViewSnapshot } from "../../view"; export type ReactionDiffusionInputs = { feed: number; @@ -15,6 +17,7 @@ export type ReactionDiffusionInputs = { diffusionA: number; diffusionB: number; dt: number; + cellSize: number; }; export const DEFAULT_RD_FEED = 0.0367; @@ -22,10 +25,13 @@ export const DEFAULT_RD_KILL = 0.0649; export const DEFAULT_RD_DIFFUSION_A = 1.0; export const DEFAULT_RD_DIFFUSION_B = 0.5; export const DEFAULT_RD_DT = 1.0; +export const DEFAULT_RD_CELL_SIZE = 2; export type ReactionDiffusionOptions = { width: number; height: number; + cellSize?: number; + followView?: boolean; }; export class ReactionDiffusionGrid extends Module< @@ -40,6 +46,7 @@ export class ReactionDiffusionGrid extends Module< diffusionA: DataType.NUMBER, diffusionB: DataType.NUMBER, dt: DataType.NUMBER, + cellSize: DataType.NUMBER, } as const; readonly gridSpec: GridSpec; private renderCanvas?: HTMLCanvasElement; @@ -53,6 +60,8 @@ export class ReactionDiffusionGrid extends Module< height: options.height, format: "vec2f", wrap: "repeat", + cellSize: options.cellSize ?? DEFAULT_RD_CELL_SIZE, + followView: options.followView ?? true, }; this.write({ feed: DEFAULT_RD_FEED, @@ -60,12 +69,54 @@ export class ReactionDiffusionGrid extends Module< diffusionA: DEFAULT_RD_DIFFUSION_A, diffusionB: DEFAULT_RD_DIFFUSION_B, dt: DEFAULT_RD_DT, + cellSize: options.cellSize ?? DEFAULT_RD_CELL_SIZE, }); } + private seedFromParticles( + particles: IParticle[], + view: ViewSnapshot, + buffer: Float32Array + ): boolean { + if (!particles || particles.length === 0) return false; + const width = this.gridSpec.width; + const height = this.gridSpec.height; + const channels = 2; + buffer.fill(0); + const total = width * height; + for (let i = 0; i < total; i++) { + buffer[i * channels + 0] = 1; + buffer[i * channels + 1] = 0; + } + const centerX = view.width / 2; + const centerY = view.height / 2; + for (const particle of particles) { + if (particle.mass === 0) continue; + const screenX = centerX + (particle.position.x - view.cx) * view.zoom; + const screenY = centerY + (particle.position.y - view.cy) * view.zoom; + const gx = Math.floor((screenX / view.width) * width); + const gy = Math.floor((screenY / view.height) * height); + if (gx < 0 || gy < 0 || gx >= width || gy >= height) continue; + const idx = (gy * width + gx) * channels; + buffer[idx + 1] = 1; + } + return true; + } + + seedFromParticlesBuffer( + particles: IParticle[], + view: ViewSnapshot + ): Float32Array | null { + const total = this.gridSpec.width * this.gridSpec.height * 2; + const buffer = new Float32Array(total); + return this.seedFromParticles(particles, view, buffer) ? buffer : null; + } + cpu(): CPUDescriptor { return { - init: ({ grid }) => { + init: ({ grid, particles, view }) => { + const buf = grid.writeBuffer as Float32Array; + if (this.seedFromParticles(particles, view, buf)) return; const width = grid.width; const height = grid.height; for (let y = 0; y < height; y++) { @@ -133,9 +184,11 @@ export class ReactionDiffusionGrid extends Module< (input.kill + input.feed) * b) * input.dt; + const clampedA = Math.max(0, Math.min(1, newA)); + const clampedB = Math.max(0, Math.min(1, newB)); const idx = (y * width + x) * grid.channels; - (grid.writeBuffer as any)[idx + 0] = newA; - (grid.writeBuffer as any)[idx + 1] = newB; + (grid.writeBuffer as any)[idx + 0] = clampedA; + (grid.writeBuffer as any)[idx + 1] = clampedB; } } }, @@ -227,8 +280,10 @@ let diffB = ${getUniform("diffusionB")}; let dt = ${getUniform("dt")}; let newA = a + (diffA * lapA - reaction + feed * (1.0 - a)) * dt; let newB = b + (diffB * lapB + reaction - (kill + feed) * b) * dt; -grid_write(x, y, 0u, newA); -grid_write(x, y, 1u, newB); +let clampedA = clamp(newA, 0.0, 1.0); +let clampedB = clamp(newB, 0.0, 1.0); +grid_write(x, y, 0u, clampedA); +grid_write(x, y, 1u, clampedB); `; }, render: { @@ -236,6 +291,8 @@ grid_write(x, y, 1u, newB); { kind: RenderPassKind.Fullscreen, bindings: [], + instanced: false, + writesScene: true, fragment: () => `{ let gx = i32(floor(frag_coord.x / render_uniforms.canvas_size.x * f32(GRID_WIDTH))); let gy = i32(floor(frag_coord.y / render_uniforms.canvas_size.y * f32(GRID_HEIGHT))); diff --git a/packages/core/src/runtimes/cpu/engine.ts b/packages/core/src/runtimes/cpu/engine.ts index 35805b7c..7575d977 100644 --- a/packages/core/src/runtimes/cpu/engine.ts +++ b/packages/core/src/runtimes/cpu/engine.ts @@ -17,7 +17,7 @@ import { import { SpatialGrid } from "./spatial-grid"; import { Particle } from "../../particle"; import { Vector } from "../../vector"; -import { GridStore } from "../../grid/store"; +import { GridStore, resampleGridBuffer } from "../../grid/store"; export class CPUEngine extends AbstractEngine { private particles: Particle[] = []; @@ -27,6 +27,8 @@ export class CPUEngine extends AbstractEngine { private particleIdToIndex: Map = new Map(); private gridStores: Map = new Map(); private gridInitialized: Set = new Set(); + private lastGridResizeAt = 0; + private gridResizeCooldownMs = 150; constructor(options: { canvas: HTMLCanvasElement; @@ -272,6 +274,14 @@ export class CPUEngine extends AbstractEngine { // No additional state to update on CPU when max particles changes } + protected onModuleSettingsChanged(): void { + this.updateGridStoresForView(); + } + + protected onViewChanged(): void { + this.updateGridStoresForView(); + } + private animate = (): void => { const dt = this.getTimeDelta(); this.updateFPS(dt); @@ -334,6 +344,7 @@ export class CPUEngine extends AbstractEngine { private update(dt: number): void { const effectiveCount = this.getEffectiveCount(); + this.updateGridStoresForView(); this.stepGrids(dt); // Update spatial grid with current particle positions and camera @@ -752,11 +763,16 @@ export class CPUEngine extends AbstractEngine { private setupGridStores(): void { this.gridStores.clear(); this.gridInitialized.clear(); + const view = this.view.getSnapshot(); for (const module of this.gridModules) { if (module.role !== ModuleRole.Grid) continue; const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; if (!spec) continue; - this.gridStores.set(module.name, new GridStore(spec)); + const resolved = this.resolveGridSpec(spec, view); + if (resolved !== spec) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + } + this.gridStores.set(module.name, new GridStore(resolved)); } for (const module of this.modules) { const attach = (module as unknown as { attachGridSpec?: (spec: GridSpec) => void }).attachGridSpec; @@ -796,6 +812,8 @@ export class CPUEngine extends AbstractEngine { sample: (x: number, y: number, channel?: number) => store.read(x, y, channel), grid: store, + particles: this.particles, + view: this.view.getSnapshot(), }; if (!this.gridInitialized.has(module.name)) { @@ -813,4 +831,102 @@ export class CPUEngine extends AbstractEngine { } catch (error) {} } } + + private resolveGridSpec( + spec: GridSpec, + view: { width: number; height: number; zoom: number } + ) { + if (!spec.followView) return spec; + const cellSize = spec.cellSize; + if (!cellSize || cellSize <= 0) return spec; + const width = Math.max(1, Math.ceil(view.width / cellSize)); + const height = Math.max(1, Math.ceil(view.height / cellSize)); + if ( + width === spec.width && + height === spec.height && + cellSize === spec.cellSize + ) { + return spec; + } + return { ...spec, width, height, cellSize }; + } + + private updateGridStoresForView(): void { + if (this.gridModules.length === 0) return; + const view = this.view.getSnapshot(); + const now = performance.now(); + const allowResize = now - this.lastGridResizeAt >= this.gridResizeCooldownMs; + let resized = false; + let specChanged = false; + for (const module of this.gridModules) { + if (module.role !== ModuleRole.Grid) continue; + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + const input = module.read() as Record; + const inputCellSize = + typeof input.cellSize === "number" && input.cellSize > 0 + ? input.cellSize + : undefined; + const cellSizeChanged = + inputCellSize !== undefined && inputCellSize !== spec.cellSize; + const baseSpec = cellSizeChanged + ? { ...spec, cellSize: inputCellSize } + : spec; + if (!cellSizeChanged && !allowResize) continue; + const resolved = this.resolveGridSpec(baseSpec, view); + if (resolved === spec) continue; + const sizeChanged = + resolved.width !== spec.width || resolved.height !== spec.height; + if (cellSizeChanged) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + this.gridStores.set(module.name, new GridStore(resolved)); + this.gridInitialized.delete(module.name); + resized = true; + continue; + } + if (!sizeChanged) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + const store = this.gridStores.get(module.name); + if (store) { + (store as any).spec = resolved; + } + specChanged = true; + continue; + } + const prev = this.gridStores.get(module.name); + const newStore = prev + ? (() => { + const buffer = resampleGridBuffer(prev.readBuffer, prev.spec, resolved); + const store = new GridStore(resolved); + (store.readBuffer as any).set(buffer as any); + (store.writeBuffer as any).set(buffer as any); + return store; + })() + : new GridStore(resolved); + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + this.gridStores.set(module.name, newStore); + if (prev) { + this.gridInitialized.add(module.name); + } else { + this.gridInitialized.delete(module.name); + } + resized = true; + } + if (!resized && !specChanged) return; + if (resized) { + this.lastGridResizeAt = now; + } + for (const module of this.modules) { + const attach = (module as unknown as { + attachGridSpec?: (spec: GridSpec) => void; + }).attachGridSpec; + const getName = (module as unknown as { + getGridModuleName?: () => string; + }).getGridModuleName; + if (!attach || !getName) continue; + const gridName = getName.call(module); + const store = this.gridStores.get(gridName); + if (store) attach.call(module, store.spec); + } + } } diff --git a/packages/core/src/runtimes/webgpu/engine.ts b/packages/core/src/runtimes/webgpu/engine.ts index c1a7ea28..4da2ff41 100644 --- a/packages/core/src/runtimes/webgpu/engine.ts +++ b/packages/core/src/runtimes/webgpu/engine.ts @@ -29,7 +29,7 @@ import { SimulationPipeline } from "./simulation-pipeline"; import { RenderPipeline } from "./render-pipeline"; import { LocalQuery } from "./local-query"; import { GridPipeline } from "./grid-pipeline"; -import { getGridChannelCount } from "../../grid/store"; +import { getGridChannelCount, resampleGridBuffer } from "../../grid/store"; export class WebGPUEngine extends AbstractEngine { private resources: GPUResources; @@ -41,6 +41,8 @@ export class WebGPUEngine extends AbstractEngine { private gridPipeline: GridPipeline; private gridStores: Map = new Map(); private gridSpecs: Map = new Map(); + private lastGridResizeAt = 0; + private gridResizeCooldownMs = 150; private bufferMaxParticles: number; // Buffer allocation size (separate from effective maxParticles) private workgroupSize: number; private simStrideValue: number = 0; @@ -118,6 +120,7 @@ export class WebGPUEngine extends AbstractEngine { this.gridModules, this.gridSpecs ); + this.seedGridsFromParticles(); // Ensure scene textures const size = this.view.getSize(); @@ -193,6 +196,7 @@ export class WebGPUEngine extends AbstractEngine { this.resources, this.registry.getProgram() ); + this.updateGridStoresForView(); } setParticles(p: IParticle[]): void { @@ -340,6 +344,7 @@ export class WebGPUEngine extends AbstractEngine { if (this.playing) { // Update engine-owned oscillators before simulation uniforms are written this.updateOscillators(dt); + this.seedGridsFromParticles(); if (this.gridModules.length > 0 && this.gridStores.size > 0) { this.gridPipeline.run( encoder, @@ -435,13 +440,18 @@ export class WebGPUEngine extends AbstractEngine { const device = this.resources.getDevice(); this.gridStores.clear(); this.gridSpecs.clear(); + const view = this.view.getSnapshot(); for (const module of this.gridModules) { if (module.role !== "grid") continue; const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; if (!spec) continue; - const channels = getGridChannelCount(spec); + const resolved = this.resolveGridSpec(spec, view); + if (resolved !== spec) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + } + const channels = getGridChannelCount(resolved); const length = - Math.max(1, spec.width) * Math.max(1, spec.height) * channels; + Math.max(1, resolved.width) * Math.max(1, resolved.height) * channels; const sizeBytes = length * 4; const usage = GPUBufferUsage.STORAGE | @@ -449,8 +459,8 @@ export class WebGPUEngine extends AbstractEngine { GPUBufferUsage.COPY_DST; const read = device.createBuffer({ size: sizeBytes, usage }); const write = device.createBuffer({ size: sizeBytes, usage }); - this.gridStores.set(module.name, { spec, read, write }); - this.gridSpecs.set(module.name, spec); + this.gridStores.set(module.name, { spec: resolved, read, write }); + this.gridSpecs.set(module.name, resolved); } for (const module of this.modules) { const attach = (module as unknown as { attachGridSpec?: (spec: GridSpec) => void }).attachGridSpec; @@ -479,6 +489,131 @@ export class WebGPUEngine extends AbstractEngine { } } + private resolveGridSpec( + spec: GridSpec, + view: { width: number; height: number; zoom: number } + ) { + if (!spec.followView) return spec; + const cellSize = spec.cellSize; + if (!cellSize || cellSize <= 0) return spec; + const width = Math.max(1, Math.ceil(view.width / cellSize)); + const height = Math.max(1, Math.ceil(view.height / cellSize)); + if ( + width === spec.width && + height === spec.height && + cellSize === spec.cellSize + ) { + return spec; + } + return { ...spec, width, height, cellSize }; + } + + private updateGridStoresForView(): void { + if (this.gridModules.length === 0) return; + const view = this.view.getSnapshot(); + const now = performance.now(); + const allowResize = now - this.lastGridResizeAt >= this.gridResizeCooldownMs; + let resized = false; + let specChanged = false; + const regenerate = new Set(); + const previousStores = new Map(this.gridStores); + for (const module of this.gridModules) { + if (module.role !== "grid") continue; + const spec = (module as unknown as { gridSpec?: GridSpec }).gridSpec; + if (!spec) continue; + const input = module.read() as Record; + const inputCellSize = + typeof input.cellSize === "number" && input.cellSize > 0 + ? input.cellSize + : undefined; + const cellSizeChanged = + inputCellSize !== undefined && inputCellSize !== spec.cellSize; + const baseSpec = cellSizeChanged + ? { ...spec, cellSize: inputCellSize } + : spec; + if (!cellSizeChanged && !allowResize) continue; + const resolved = this.resolveGridSpec(baseSpec, view); + if (resolved === spec) continue; + const sizeChanged = + resolved.width !== spec.width || resolved.height !== spec.height; + if (cellSizeChanged) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + regenerate.add(module.name); + resized = true; + continue; + } + if (!sizeChanged) { + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + const store = this.gridStores.get(module.name); + if (store) { + store.spec = resolved; + this.gridSpecs.set(module.name, resolved); + } + specChanged = true; + continue; + } + (module as unknown as { gridSpec?: GridSpec }).gridSpec = resolved; + resized = true; + } + if (!resized && !specChanged) return; + if (!resized) { + this.attachGridSpecsFromModules(); + return; + } + this.lastGridResizeAt = now; + this.setupGridStores(); + this.gridPipeline.initialize( + this.resources, + this.registry, + this.gridModules, + this.gridSpecs + ); + for (const module of this.gridModules) { + if (regenerate.has(module.name)) continue; + const prev = previousStores.get(module.name); + const next = this.gridStores.get(module.name); + if (!prev || !next) continue; + const prevSpec = prev.spec; + const prevChannels = getGridChannelCount(prevSpec); + const readBytes = + Math.max(1, prevSpec.width) * + Math.max(1, prevSpec.height) * + prevChannels * + 4; + this.resources.readBuffer(prev.read, readBytes).then((buf) => { + const src = new Float32Array(buf); + const resampled = resampleGridBuffer(src, prevSpec, next.spec, { + forceFloat: true, + }) as Float32Array; + this.setGrid(module.name, resampled); + this.gridPipeline.markInitialized(module.name); + }); + } + } + + private seedGridsFromParticles(): void { + if (this.gridModules.length === 0 || this.gridStores.size === 0) return; + const particles = this.particles.getParticles(); + if (particles.length === 0) return; + const view = this.view.getSnapshot(); + + for (const module of this.gridModules) { + if (!module.isEnabled()) continue; + if (this.gridPipeline.isInitialized(module.name)) continue; + const seed = (module as unknown as { + seedFromParticlesBuffer?: ( + particles: IParticle[], + view: { width: number; height: number; cx: number; cy: number; zoom: number } + ) => Float32Array | null; + }).seedFromParticlesBuffer; + if (!seed) continue; + const data = seed.call(module, particles, view); + if (!data) continue; + this.setGrid(module.name, data); + this.gridPipeline.markInitialized(module.name); + } + } + private isWebKitWebGPU(): boolean { // We specifically want WebKit's WebGPU, not Chromium/Blink. // - On iOS, *all* browsers use WebKit, so we treat them as WebKit. @@ -536,6 +671,7 @@ export class WebGPUEngine extends AbstractEngine { // Override onModuleSettingsChanged to sync to GPU protected onModuleSettingsChanged(): void { this.registry.writeAllModuleUniforms(); + this.updateGridStoresForView(); } // Handle configuration changes diff --git a/packages/core/src/runtimes/webgpu/gpu-resources.ts b/packages/core/src/runtimes/webgpu/gpu-resources.ts index fcaf34e4..80be8c17 100644 --- a/packages/core/src/runtimes/webgpu/gpu-resources.ts +++ b/packages/core/src/runtimes/webgpu/gpu-resources.ts @@ -149,12 +149,15 @@ export class GPUResources { // Step 2: Request device with timeout // Request the maximum buffer size limit to avoid buffer size errors const maxBufferSize = this.adapter.limits.maxBufferSize || this.adapter.limits.maxStorageBufferBindingSize; + const maxStorageBuffersPerShaderStage = + this.adapter.limits.maxStorageBuffersPerShaderStage; this.device = await withTimeout( this.adapter.requestDevice({ requiredFeatures: this.requiredFeatures || [], requiredLimits: { maxStorageBufferBindingSize: this.adapter.limits.maxStorageBufferBindingSize, maxBufferSize: maxBufferSize, + maxStorageBuffersPerShaderStage: maxStorageBuffersPerShaderStage, }, }), 5000, diff --git a/packages/core/src/runtimes/webgpu/grid-pipeline.ts b/packages/core/src/runtimes/webgpu/grid-pipeline.ts index e1cfee69..66e91758 100644 --- a/packages/core/src/runtimes/webgpu/grid-pipeline.ts +++ b/packages/core/src/runtimes/webgpu/grid-pipeline.ts @@ -54,10 +54,10 @@ export class GridPipeline { const wrapMode = spec.wrap ?? "clamp"; const wrapFn = wrapMode === "repeat" - ? `fn grid_wrap(v: i32, max: i32) -> i32 { let m = ((v % max) + max) % max; return m; }` + ? `fn grid_wrap(v: i32, maxv: i32) -> i32 { let m = ((v % maxv) + maxv) % maxv; return m; }` : wrapMode === "mirror" - ? `fn grid_wrap(v: i32, max: i32) -> i32 { let period = max * 2; let m = ((v % period) + period) % period; return select(m, period - 1 - m, m >= max); }` - : `fn grid_wrap(v: i32, max: i32) -> i32 { return max(0, min(v, max - 1)); }`; + ? `fn grid_wrap(v: i32, maxv: i32) -> i32 { let period = maxv * 2; let m = ((v % period) + period) % period; return select(m, period - 1 - m, m >= maxv); }` + : `fn grid_wrap(v: i32, maxv: i32) -> i32 { return max(0, min(v, maxv - 1)); }`; const helpers = ` const GRID_WIDTH: u32 = ${spec.width}u; @@ -184,10 +184,18 @@ fn ${name}_${module.name}(@builtin(global_invocation_id) gid: vec3) { height: spec.height, }; - this.pipelines.set(module.name, entry); + this.pipelines.set(module.name, entry); } } + markInitialized(moduleName: string): void { + this.initialized.add(moduleName); + } + + isInitialized(moduleName: string): boolean { + return this.initialized.has(moduleName); + } + run( encoder: GPUCommandEncoder, resources: GPUResources, diff --git a/packages/core/src/runtimes/webgpu/module-registry.ts b/packages/core/src/runtimes/webgpu/module-registry.ts index a4786ea5..a934c1fa 100644 --- a/packages/core/src/runtimes/webgpu/module-registry.ts +++ b/packages/core/src/runtimes/webgpu/module-registry.ts @@ -133,7 +133,7 @@ export class ModuleRegistry { * Includes any module that provides render passes in its descriptor, regardless of role. */ getEnabledRenderModules(): Module[] { - return this.modules.filter((module, idx) => { + const renderables = this.modules.filter((module, idx) => { if (!module.isEnabled()) return false; const descriptor = this.modules[idx].webgpu() as | WebGPURenderDescriptor @@ -144,6 +144,21 @@ export class ModuleRegistry { : (descriptor as WebGPURenderDescriptor).passes; return !!(passes && passes.length > 0); }); + + // Render grid modules first so particle passes overlay them. + const grids: Module[] = []; + const renders: Module[] = []; + const others: Module[] = []; + for (const module of renderables) { + if (module.role === ModuleRole.Grid) { + grids.push(module); + } else if (module.role === ModuleRole.Render) { + renders.push(module); + } else { + others.push(module); + } + } + return [...grids, ...renders, ...others]; } /** Get all modules. */ diff --git a/packages/playground/src/components/modules/ElementaryCAModule.tsx b/packages/playground/src/components/modules/ElementaryCAModule.tsx index 85ea20fb..82dbc68a 100644 --- a/packages/playground/src/components/modules/ElementaryCAModule.tsx +++ b/packages/playground/src/components/modules/ElementaryCAModule.tsx @@ -2,19 +2,32 @@ import { Slider } from "../ui/Slider"; import { useElementaryCA } from "../../hooks/modules/useElementaryCA"; export function ElementaryCAModule({ enabled = true }: { enabled?: boolean }) { - const { rule, setRule } = useElementaryCA(); + const { rule, cellSize, setRule, setCellSize } = useElementaryCA(); return ( - `${Math.floor(v)}`} - onChange={(v) => setRule(Math.floor(v))} - disabled={!enabled} - /> + <> + `${Math.floor(v)}`} + onChange={(v) => setRule(Math.floor(v))} + disabled={!enabled} + /> + v.toFixed(1)} + onChange={setCellSize} + disabled={!enabled} + /> + ); } diff --git a/packages/playground/src/components/modules/GameOfLifeModule.tsx b/packages/playground/src/components/modules/GameOfLifeModule.tsx index bd54cd41..2bb48b7c 100644 --- a/packages/playground/src/components/modules/GameOfLifeModule.tsx +++ b/packages/playground/src/components/modules/GameOfLifeModule.tsx @@ -6,9 +6,11 @@ export function GameOfLifeModule({ enabled = true }: { enabled?: boolean }) { birthMask, surviveMask, seedDensity, + cellSize, setBirthMask, setSurviveMask, setSeedDensity, + setCellSize, } = useGameOfLife(); return ( @@ -46,6 +48,17 @@ export function GameOfLifeModule({ enabled = true }: { enabled?: boolean }) { onChange={setSeedDensity} disabled={!enabled} /> + v.toFixed(1)} + onChange={setCellSize} + disabled={!enabled} + /> ); } diff --git a/packages/playground/src/components/modules/ReactionDiffusionModule.tsx b/packages/playground/src/components/modules/ReactionDiffusionModule.tsx index 954fb713..bc9b90a4 100644 --- a/packages/playground/src/components/modules/ReactionDiffusionModule.tsx +++ b/packages/playground/src/components/modules/ReactionDiffusionModule.tsx @@ -12,11 +12,13 @@ export function ReactionDiffusionModule({ diffusionA, diffusionB, dt, + cellSize, setFeed, setKill, setDiffusionA, setDiffusionB, setDt, + setCellSize, } = useReactionDiffusion(); return ( @@ -76,6 +78,17 @@ export function ReactionDiffusionModule({ onChange={setDt} disabled={!enabled} /> + v.toFixed(1)} + onChange={setCellSize} + disabled={!enabled} + /> ); } diff --git a/packages/playground/src/contexts/EngineContext.tsx b/packages/playground/src/contexts/EngineContext.tsx index cecbf960..4226fd4e 100644 --- a/packages/playground/src/contexts/EngineContext.tsx +++ b/packages/playground/src/contexts/EngineContext.tsx @@ -91,6 +91,7 @@ export interface EngineContextType { isSupported: (module: any) => boolean; getCount: () => number; getFPS: () => number; + stampGridsAtWorldPositions: (positions: Array<{ x: number; y: number }>) => void; // Module references engine: Engine | null; diff --git a/packages/playground/src/hooks/modules/useElementaryCA.ts b/packages/playground/src/hooks/modules/useElementaryCA.ts index 0abb8a02..7e4f161b 100644 --- a/packages/playground/src/hooks/modules/useElementaryCA.ts +++ b/packages/playground/src/hooks/modules/useElementaryCA.ts @@ -7,12 +7,13 @@ import { selectElementaryCA, setElementaryCAEnabled, setElementaryCARule, + setElementaryCACellSize, resetElementaryCA, } from "../../slices/modules/elementaryCa"; export function useElementaryCA() { const dispatch = useAppDispatch(); - const { elementaryCa } = useEngine(); + const { elementaryCa, engine } = useEngine(); const modulesState = useAppSelector(selectModules); const state = useMemo(() => selectElementaryCA(modulesState), [modulesState]); @@ -22,8 +23,10 @@ export function useElementaryCA() { if (!elementaryCa) return; elementaryCa.write({ rule: state.rule, + cellSize: state.cellSize, }); - }, [elementaryCa, state]); + engine?.notifyModuleSettingsChanged?.(); + }, [elementaryCa, engine, state]); const setEnabled = useCallback( (enabled: boolean) => { @@ -40,6 +43,15 @@ export function useElementaryCA() { [dispatch, elementaryCa] ); + const setCellSize = useCallback( + (value: number) => { + dispatch(setElementaryCACellSize(value)); + elementaryCa?.write({ cellSize: value }); + engine?.notifyModuleSettingsChanged?.(); + }, + [dispatch, elementaryCa, engine] + ); + const reset = useCallback(() => { dispatch(resetElementaryCA()); }, [dispatch]); @@ -49,6 +61,7 @@ export function useElementaryCA() { isEnabled, setEnabled, setRule, + setCellSize, reset, }; } diff --git a/packages/playground/src/hooks/modules/useGameOfLife.ts b/packages/playground/src/hooks/modules/useGameOfLife.ts index 8bbad75e..e005e974 100644 --- a/packages/playground/src/hooks/modules/useGameOfLife.ts +++ b/packages/playground/src/hooks/modules/useGameOfLife.ts @@ -9,12 +9,13 @@ import { setGameOfLifeBirthMask, setGameOfLifeSurviveMask, setGameOfLifeSeedDensity, + setGameOfLifeCellSize, resetGameOfLife, } from "../../slices/modules/gameOfLife"; export function useGameOfLife() { const dispatch = useAppDispatch(); - const { gameOfLife } = useEngine(); + const { gameOfLife, engine } = useEngine(); const modulesState = useAppSelector(selectModules); const state = useMemo(() => selectGameOfLife(modulesState), [modulesState]); @@ -26,8 +27,10 @@ export function useGameOfLife() { birthMask: state.birthMask, surviveMask: state.surviveMask, seedDensity: state.seedDensity, + cellSize: state.cellSize, }); - }, [gameOfLife, state]); + engine?.notifyModuleSettingsChanged?.(); + }, [gameOfLife, engine, state]); const setEnabled = useCallback( (enabled: boolean) => { @@ -60,6 +63,15 @@ export function useGameOfLife() { [dispatch, gameOfLife] ); + const setCellSize = useCallback( + (value: number) => { + dispatch(setGameOfLifeCellSize(value)); + gameOfLife?.write({ cellSize: value }); + engine?.notifyModuleSettingsChanged?.(); + }, + [dispatch, gameOfLife, engine] + ); + const reset = useCallback(() => { dispatch(resetGameOfLife()); }, [dispatch]); @@ -71,6 +83,7 @@ export function useGameOfLife() { setBirthMask, setSurviveMask, setSeedDensity, + setCellSize, reset, }; } diff --git a/packages/playground/src/hooks/modules/useReactionDiffusion.ts b/packages/playground/src/hooks/modules/useReactionDiffusion.ts index a9246217..52ccc1cf 100644 --- a/packages/playground/src/hooks/modules/useReactionDiffusion.ts +++ b/packages/playground/src/hooks/modules/useReactionDiffusion.ts @@ -11,12 +11,13 @@ import { setReactionDiffusionDiffusionA, setReactionDiffusionDiffusionB, setReactionDiffusionDt, + setReactionDiffusionCellSize, resetReactionDiffusion, } from "../../slices/modules/reactionDiffusion"; export function useReactionDiffusion() { const dispatch = useAppDispatch(); - const { reactionDiffusion } = useEngine(); + const { reactionDiffusion, engine } = useEngine(); const modulesState = useAppSelector(selectModules); const state = useMemo( @@ -33,8 +34,10 @@ export function useReactionDiffusion() { diffusionA: state.diffusionA, diffusionB: state.diffusionB, dt: state.dt, + cellSize: state.cellSize, }); - }, [reactionDiffusion, state]); + engine?.notifyModuleSettingsChanged?.(); + }, [reactionDiffusion, engine, state]); const setEnabled = useCallback( (enabled: boolean) => { @@ -83,6 +86,15 @@ export function useReactionDiffusion() { [dispatch, reactionDiffusion] ); + const setCellSize = useCallback( + (value: number) => { + dispatch(setReactionDiffusionCellSize(value)); + reactionDiffusion?.write({ cellSize: value }); + engine?.notifyModuleSettingsChanged?.(); + }, + [dispatch, reactionDiffusion, engine] + ); + const reset = useCallback(() => { dispatch(resetReactionDiffusion()); }, [dispatch]); @@ -96,6 +108,7 @@ export function useReactionDiffusion() { setDiffusionA, setDiffusionB, setDt, + setCellSize, reset, }; } diff --git a/packages/playground/src/hooks/tools/individual-tools/useBrushTool.ts b/packages/playground/src/hooks/tools/individual-tools/useBrushTool.ts index 4a7a437e..63008445 100644 --- a/packages/playground/src/hooks/tools/individual-tools/useBrushTool.ts +++ b/packages/playground/src/hooks/tools/individual-tools/useBrushTool.ts @@ -36,7 +36,8 @@ function cellKey(cx: number, cy: number) { const f32 = (v: number) => Math.fround(v); export function useBrushTool(isActive: boolean) { - const { engine, screenToWorld, zoom, addParticle } = useEngine(); + const { engine, screenToWorld, zoom, addParticle, stampGridsAtWorldPositions } = + useEngine(); const { particleSize, colors } = useInit(); const { recordCommand } = useHistory(); @@ -215,6 +216,7 @@ export function useBrushTool(isActive: boolean) { const mass = pinned ? -1 : calculateMassFromSize(r); let spawned = 0; + const stamped: Array<{ x: number; y: number }> = []; // Safety cap to avoid freezing the UI with extremely tiny particles + large radius. // Still high enough to fill the circle for common settings (e.g. size=1, radius=200px). const MAX_SPAWN_PER_APPLY = truncatedQueryRef.current ? 4000 : 50000; @@ -261,13 +263,22 @@ export function useBrushTool(isActive: boolean) { if (typeof createdIndex === "number" && createdIndex >= 0) { spawnedRef.current.push({ index: createdIndex, particle: p }); } + stamped.push({ x: px, y }); // Update index immediately so subsequent candidates/moves don't overlap. insertIntoIndex({ x: px, y, r }); spawned++; - if (spawned >= MAX_SPAWN_PER_APPLY) return; + if (spawned >= MAX_SPAWN_PER_APPLY) { + if (stamped.length > 0) { + stampGridsAtWorldPositions(stamped); + } + return; + } } } + if (stamped.length > 0) { + stampGridsAtWorldPositions(stamped); + } }, [ isActive, @@ -278,6 +289,7 @@ export function useBrushTool(isActive: boolean) { particleSize, overlapsAny, insertIntoIndex, + stampGridsAtWorldPositions, ] ); diff --git a/packages/playground/src/hooks/tools/individual-tools/useShapeTool.ts b/packages/playground/src/hooks/tools/individual-tools/useShapeTool.ts index 92272e5b..d006e36f 100644 --- a/packages/playground/src/hooks/tools/individual-tools/useShapeTool.ts +++ b/packages/playground/src/hooks/tools/individual-tools/useShapeTool.ts @@ -20,7 +20,8 @@ const MIN_RADIUS = 20; const MAX_RADIUS = 200; export function useShapeTool(isActive: boolean) { - const { engine, screenToWorld, addParticle } = useEngine(); + const { engine, screenToWorld, addParticle, stampGridsAtWorldPositions } = + useEngine(); const joints = useJoints(); const lines = useLines(); const { particleSize, colors } = useInit(); @@ -96,6 +97,7 @@ export function useShapeTool(isActive: boolean) { | undefined; holders[i].idx = (particles?.length ?? 1) - 1; } + stampGridsAtWorldPositions(vertices); // Create joints after all indices are resolved if (!joints.enabled) joints.setEnabled(true); if (!lines.enabled) lines.setEnabled(true); @@ -147,6 +149,7 @@ export function useShapeTool(isActive: boolean) { joints, lines, executeCommand, + stampGridsAtWorldPositions, ] ); diff --git a/packages/playground/src/hooks/tools/individual-tools/useSpawnTool.ts b/packages/playground/src/hooks/tools/individual-tools/useSpawnTool.ts index 7134ba82..b78f8ff3 100644 --- a/packages/playground/src/hooks/tools/individual-tools/useSpawnTool.ts +++ b/packages/playground/src/hooks/tools/individual-tools/useSpawnTool.ts @@ -60,7 +60,8 @@ const spawnToolState: SpawnToolState = { }; export function useSpawnTool(isActive: boolean) { - const { screenToWorld, addParticle, zoom } = useEngine(); + const { screenToWorld, addParticle, zoom, stampGridsAtWorldPositions } = + useEngine(); const { beginTransaction, appendToTransaction, commitTransaction } = useHistory(); const { particleSize, colors } = useInit(); @@ -112,6 +113,7 @@ export function useSpawnTool(isActive: boolean) { timestamp: Date.now(), do: async (ctx: { engine: any }) => { addParticle({ position: worldPos, velocity, size, mass, color }); + stampGridsAtWorldPositions([{ x: worldPos.x, y: worldPos.y }]); // Resolve created index from engine after it applies if (ctx.engine?.getParticles) { const particles = await ctx.engine.getParticles(); @@ -129,7 +131,13 @@ export function useSpawnTool(isActive: boolean) { } as unknown as Command; appendToTransaction(cmd); - }, [addParticle, screenToWorld, zoom, appendToTransaction]); + }, [ + addParticle, + screenToWorld, + zoom, + appendToTransaction, + stampGridsAtWorldPositions, + ]); // Calculate dynamic streaming rate based on particle size and velocity const calculateStreamingRate = useCallback(() => { diff --git a/packages/playground/src/hooks/useEngineInternal.ts b/packages/playground/src/hooks/useEngineInternal.ts index ed1aa067..b66b3577 100644 --- a/packages/playground/src/hooks/useEngineInternal.ts +++ b/packages/playground/src/hooks/useEngineInternal.ts @@ -295,17 +295,24 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { 512, Math.max(64, Math.floor(canvasHeight)) ); + const gridCellSize = 2; const gameOfLife = new GameOfLifeGrid({ width: gridWidth, height: gridHeight, + cellSize: gridCellSize, + followView: true, }); const reactionDiffusion = new ReactionDiffusionGrid({ width: gridWidth, height: gridHeight, + cellSize: gridCellSize, + followView: true, }); const elementaryCa = new ElementaryCAGrid({ width: gridWidth, height: gridHeight, + cellSize: gridCellSize, + followView: true, }); gameOfLife.setEnabled(false); reactionDiffusion.setEnabled(false); @@ -787,6 +794,118 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { return engineRef.current?.getFPS() || 0; }, []); + const gridStampQueueRef = useRef>([]); + const gridStampScheduledRef = useRef(false); + + const stampGridsAtWorldPositions = useCallback( + (positions: Array<{ x: number; y: number }>) => { + if (!positions.length) return; + gridStampQueueRef.current.push(...positions); + if (gridStampScheduledRef.current) return; + gridStampScheduledRef.current = true; + requestAnimationFrame(() => { + gridStampScheduledRef.current = false; + const queued = gridStampQueueRef.current.splice( + 0, + gridStampQueueRef.current.length + ); + if (queued.length === 0) return; + const engine = engineRef.current; + if (!engine || !engine.getGrid || !engine.setGrid) return; + const size = engine.getSize(); + const camera = engine.getCamera(); + const zoom = engine.getZoom(); + const centerX = size.width / 2; + const centerY = size.height / 2; + const view = { + width: size.width, + height: size.height, + cx: camera.x, + cy: camera.y, + zoom, + }; + + const modules = [ + gameOfLifeRef.current, + reactionDiffusionRef.current, + elementaryCaRef.current, + ].filter(Boolean) as Array<{ + name: string; + gridSpec?: { + width: number; + height: number; + format: string; + channels?: number; + }; + isEnabled?: () => boolean; + }>; + + const stampModule = async (mod: { + name: string; + gridSpec?: { + width: number; + height: number; + format: string; + channels?: number; + }; + }) => { + const spec = mod.gridSpec; + if (!spec) return; + const width = spec.width; + const height = spec.height; + if (width <= 0 || height <= 0) return; + const channels = + spec.channels ?? + (spec.format === "vec2f" ? 2 : spec.format === "vec4f" ? 4 : 1); + let data: ArrayBufferView; + try { + data = await engine.getGrid(mod.name); + } catch { + return; + } + const buffer = + data instanceof Float32Array + ? data + : new Float32Array( + data.buffer, + data.byteOffset, + data.byteLength / 4 + ); + + for (const pos of queued) { + const screenX = centerX + (pos.x - view.cx) * view.zoom; + const screenY = centerY + (pos.y - view.cy) * view.zoom; + const gx = Math.floor((screenX / view.width) * width); + const gy = Math.floor((screenY / view.height) * height); + if (gx < 0 || gy < 0 || gx >= width || gy >= height) continue; + + if (mod.name === "elementaryCA") { + const idx = gx; + buffer[idx] = 1; + continue; + } + + const idx = (gy * width + gx) * channels; + if (mod.name === "reactionDiffusion" && channels >= 2) { + buffer[idx + 0] = 1; + buffer[idx + 1] = 1; + } else { + buffer[idx] = 1; + } + } + + engine.setGrid(mod.name, buffer); + }; + + modules.forEach((mod) => { + if (mod.isEnabled && !mod.isEnabled()) return; + stampModule(mod); + }); + }); + }, + [] + ); + return { // State values (from Redux selectors) isAutoMode, @@ -827,6 +946,7 @@ export function useEngineInternal({ canvasRef, initialSize }: UseEngineProps) { isSupported, getCount, getFPS, + stampGridsAtWorldPositions, // Module references (direct access to engine instances) engine: engineRef.current, diff --git a/packages/playground/src/slices/modules/elementaryCa.ts b/packages/playground/src/slices/modules/elementaryCa.ts index 8138c4f1..2121a35e 100644 --- a/packages/playground/src/slices/modules/elementaryCa.ts +++ b/packages/playground/src/slices/modules/elementaryCa.ts @@ -1,14 +1,16 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { DEFAULT_ECA_RULE } from "@cazala/party"; +import { DEFAULT_ECA_RULE, DEFAULT_ECA_CELL_SIZE } from "@cazala/party"; export interface ElementaryCAModuleState { enabled: boolean; rule: number; + cellSize: number; } const initialState: ElementaryCAModuleState = { enabled: false, rule: DEFAULT_ECA_RULE, + cellSize: DEFAULT_ECA_CELL_SIZE, }; export const elementaryCaSlice = createSlice({ @@ -21,6 +23,9 @@ export const elementaryCaSlice = createSlice({ setElementaryCARule: (state, action: PayloadAction) => { state.rule = action.payload; }, + setElementaryCACellSize: (state, action: PayloadAction) => { + state.cellSize = action.payload; + }, resetElementaryCA: () => initialState, importElementaryCASettings: ( state, @@ -34,6 +39,7 @@ export const elementaryCaSlice = createSlice({ export const { setElementaryCAEnabled, setElementaryCARule, + setElementaryCACellSize, resetElementaryCA, importElementaryCASettings, } = elementaryCaSlice.actions; diff --git a/packages/playground/src/slices/modules/gameOfLife.ts b/packages/playground/src/slices/modules/gameOfLife.ts index 9aff53ae..868c4f6b 100644 --- a/packages/playground/src/slices/modules/gameOfLife.ts +++ b/packages/playground/src/slices/modules/gameOfLife.ts @@ -3,6 +3,7 @@ import { DEFAULT_GOL_BIRTH_MASK, DEFAULT_GOL_SURVIVE_MASK, DEFAULT_GOL_SEED_DENSITY, + DEFAULT_GOL_CELL_SIZE, } from "@cazala/party"; export interface GameOfLifeModuleState { @@ -10,6 +11,7 @@ export interface GameOfLifeModuleState { birthMask: number; surviveMask: number; seedDensity: number; + cellSize: number; } const initialState: GameOfLifeModuleState = { @@ -17,6 +19,7 @@ const initialState: GameOfLifeModuleState = { birthMask: DEFAULT_GOL_BIRTH_MASK, surviveMask: DEFAULT_GOL_SURVIVE_MASK, seedDensity: DEFAULT_GOL_SEED_DENSITY, + cellSize: DEFAULT_GOL_CELL_SIZE, }; export const gameOfLifeSlice = createSlice({ @@ -35,6 +38,9 @@ export const gameOfLifeSlice = createSlice({ setGameOfLifeSeedDensity: (state, action: PayloadAction) => { state.seedDensity = action.payload; }, + setGameOfLifeCellSize: (state, action: PayloadAction) => { + state.cellSize = action.payload; + }, resetGameOfLife: () => initialState, importGameOfLifeSettings: ( state, @@ -50,6 +56,7 @@ export const { setGameOfLifeBirthMask, setGameOfLifeSurviveMask, setGameOfLifeSeedDensity, + setGameOfLifeCellSize, resetGameOfLife, importGameOfLifeSettings, } = gameOfLifeSlice.actions; diff --git a/packages/playground/src/slices/modules/reactionDiffusion.ts b/packages/playground/src/slices/modules/reactionDiffusion.ts index 0af2c102..66ffb785 100644 --- a/packages/playground/src/slices/modules/reactionDiffusion.ts +++ b/packages/playground/src/slices/modules/reactionDiffusion.ts @@ -5,6 +5,7 @@ import { DEFAULT_RD_DIFFUSION_A, DEFAULT_RD_DIFFUSION_B, DEFAULT_RD_DT, + DEFAULT_RD_CELL_SIZE, } from "@cazala/party"; export interface ReactionDiffusionModuleState { @@ -14,6 +15,7 @@ export interface ReactionDiffusionModuleState { diffusionA: number; diffusionB: number; dt: number; + cellSize: number; } const initialState: ReactionDiffusionModuleState = { @@ -23,6 +25,7 @@ const initialState: ReactionDiffusionModuleState = { diffusionA: DEFAULT_RD_DIFFUSION_A, diffusionB: DEFAULT_RD_DIFFUSION_B, dt: DEFAULT_RD_DT, + cellSize: DEFAULT_RD_CELL_SIZE, }; export const reactionDiffusionSlice = createSlice({ @@ -47,6 +50,9 @@ export const reactionDiffusionSlice = createSlice({ setReactionDiffusionDt: (state, action: PayloadAction) => { state.dt = action.payload; }, + setReactionDiffusionCellSize: (state, action: PayloadAction) => { + state.cellSize = action.payload; + }, resetReactionDiffusion: () => initialState, importReactionDiffusionSettings: ( state, @@ -64,6 +70,7 @@ export const { setReactionDiffusionDiffusionA, setReactionDiffusionDiffusionB, setReactionDiffusionDt, + setReactionDiffusionCellSize, resetReactionDiffusion, importReactionDiffusionSettings, } = reactionDiffusionSlice.actions;