Falling sand: simple rules, a whole sandbox
A few grains fall straight down. A pile forms, a narrow opening becomes a stream, and a wall changes the pattern. Build the scene yourself, then pick one grain to see how these shapes emerge from local rules.
Video walkthrough
Sand cascade: 2200 grains
A continuous 2:24 simulation with music and no narration. Sand flows through six bowls, a platform lifts it back to the top, and all outlets open in the finale. This film uses a particle model; the interactive sandbox above uses cellular rules.
If the Rutube video is not available yet, choose YouTube.
Start with a funnel
Press Play to let the grains settle in the closed funnel. Move the position slider to the end if you want to skip the wait. Open the gate, then play again: the same grains pour into the lower chamber. The gate changes the field, so this action starts a new history from the current arrangement.
Try the shelves or two passages, or choose an empty box with zero grains. Draw a wall, switch to Add sand and paint above it. The scene is a grid, not a continuous physics simulation: one cell holds a wall, one grain or nothing.
Three rules for one grain
First check the cell immediately below. If it is empty, propose a downward move. Otherwise check the two lower diagonals. A diagonal is available only when its destination is empty and the side cell is not a wall: grains cannot cut through a solid corner. If both diagonals are available, the seed, tick and grain ID determine the choice. If neither is available, stay.
These are proposals, not completed moves. Two grains can propose the same empty cell. The model picks one winner using a deterministic priority based on seed, tick, grain ID and target cell. The loser waits until the next tick; it does not try another diagonal during this update.
Inspect the next move
Click a grain or enter its number and press Inspect. Playback pauses. The panel shows its exact 3 × 3 neighborhood and predicts the next synchronous update. Blue outlines mark the three cells to check, white marks the selected grain, green marks its winning destination, and orange means another grain wins that cell.
For a concrete conflict, place grain #1 at (10, 10) and grain #2 at (12, 10), with coordinates starting at zero. Block the cells below both grains and their outside side cells. Keep (11, 11) empty. Both grains propose that cell. With seed 42 at tick 0, #1 wins and #2 waits. Exactly one grain occupies (11, 11) afterwards.
The panel follows the grain’s identity as you step or seek backwards. Inspection uses an exact snapshot rather than an interpolated drawing. At the last recorded frame, the panel explicitly predicts an extra tick beyond the recording.
Why all grains read the old field
Moving grains directly inside the same array makes the result depend on traversal order. A grain processed later may see a cell vacated earlier in the same update. A careless loop can even move one grain repeatedly in a single pass.
Here every grain reads the same old field. We collect proposals, resolve contested destinations, copy the field, clear the winners’ old cells and fill their targets. Each target was empty in the old snapshot. No winner can overwrite another grain, and each grain moves at most one cell per tick.
What stays unchanged
Between simulation ticks, the number of grains and their unique IDs stay the same. Walls stay fixed. A cell holds at most one grain, the outside boundary remains closed, and old snapshots remain unchanged. Adding grains, drawing walls, erasing and opening the gate are explicit edits, separate from a simulation tick.
Identical captured fields, seeds and tick counts produce identical histories. The speed selector changes presentation timing only. The player records the requested number of ticks. If a completed update moves no grains, the field has settled: any proposed empty destination would have a winner. Without edits, later fields are identical.
Edit, replay and share
The website stores a history of up to 360 updates with up to 512 grains. Grains is the number currently present; Moved in this tick counts only successful moves, including diagonal moves. A losing proposal does not increment it. The default run has 320 grains, seed 42 and 280 ticks; at 1× each tick takes 65 ms.
Painting or opening the gate captures the current field as a new starting state and clears the earlier history. Restart returns to that captured field. The shared link includes this field, seed, tick budget, selected grain, playback position and speed, so edited obstacles are preserved too. It opens paused. Fullscreen and video export use the same scene and timeline.
Time and memory
Let G be the number of grid cells, n the number of grains and T the number of recorded updates. One update scans G cells and resolves n proposals in expected O(G + n) time with Map lookups. Copying the grid also costs O(G). Working storage is O(G + n).
A snapshot stores O(G) cell values and shares its immutable configuration. The website retains T + 1 snapshots, so visualization history costs O(TG), in addition to temporary proposals. Scene projection, ordering visual objects, drawing and optional grain inspection add separate work. The library example also demonstrates lazy generator playback; this website player stores history to support seeking.
How this uses AlgiViz
The cellular rules belong to this application. AlgiViz receives immutable steps, samples the timeline and projects states into visual objects. Each grain has a stable grain:<id> scene identity, so its picture can follow it between cells. The renderer computes geometry from the current viewport.
The same model drives the article, standalone player and video export through the public playback and scene APIs. A tiny local rule becomes a whole picture, while one-grain inspection makes the underlying decision visible.
Code: one synchronous update
The executable listing below matches the interactive model. A state contains config.seed, cells, nextId, tick and moved. Cells use −2 for walls, −1 for empty space and nonnegative unique grain IDs. Start from a valid closed 64 × 54 field. advanceSand returns a new frozen snapshot without changing the input.
Show the executable model
const EMPTY = -1, WALL = -2, C = 64, R = 54;
function sandHash(seed, tick, id, salt = 0) {
let n = (seed ^ Math.imul(tick + 1, 0x9e3779b1) ^ Math.imul(id + 1, 0x85ebca6b) ^ salt) >>> 0;
n = Math.imul(n ^ n >>> 16, 0x7feb352d);
n = Math.imul(n ^ n >>> 15, 0x846ca68b);
return (n ^ n >>> 16) >>> 0;
}
function freezeState(config, cells, nextId, tick = 0, moved = 0) {
return Object.freeze({ config, cells: Object.freeze(cells), nextId, tick, moved });
}
function proposal(state, from) {
const id = state.cells[from], below = from + C;
const choices = [below, below - 1, below + 1];
if (state.cells[below] === EMPTY) return { id, from, to: below, rule: 'fall', choices };
// A diagonal move may not cut through a solid wall at its side.
const available = [below - 1, below + 1].filter(to => state.cells[to] === EMPTY && state.cells[from + Math.sign(to - below)] !== WALL);
if (!available.length) return { id, from, to: from, rule: 'rest', choices };
return { id, from, to: available[sandHash(state.config.seed, state.tick, id) % available.length], rule: 'slide', choices };
}
function planSandTick(state) {
const proposals = [], winners = new Map();
for (let from = 0; from < state.cells.length; from++) if (state.cells[from] >= 0) {
const p = proposal(state, from); proposals.push(p);
if (p.to === from) continue;
const other = winners.get(p.to);
const priority = sandHash(state.config.seed, state.tick, p.id, p.to);
const oldPriority = other && sandHash(state.config.seed, state.tick, other.id, other.to);
if (!other || priority < oldPriority || (priority === oldPriority && p.id < other.id)) winners.set(p.to, p);
}
return { proposals, winners };
}
function advanceSand(state) {
const { winners } = planSandTick(state), cells = [...state.cells];
for (const p of winners.values()) cells[p.from] = EMPTY;
for (const p of winners.values()) cells[p.to] = p.id;
return freezeState(state.config, cells, state.nextId, state.tick + 1, winners.size);
}