Sketch · 2026-06-19
Falling sand, four states.
Each cell is one of five things: empty, sand, water, oil, or stone. Every frame, every non-empty cell asks the same question of the cell beneath it and the two diagonals, and maybe swaps. Sand piles into mounds. Water finds the floor. Oil floats up through water. Stone just sits there. The whole sandbox is one short loop over a grid.
What you are seeing
The grid is 180 cells wide and a bit over 110 tall. Each cell holds one of five states. On every update step, the loop runs from the bottom row up. For a sand cell, it looks at the cell directly below: if that cell is empty, or holds a lighter fluid like water or oil, the two swap. If straight down is blocked, the sand tries the two diagonals at random. Water and oil follow the same falling rule, but if they can't fall they try to slide sideways into an empty neighbour. The density ordering — stone, sand, water, oil — falls out of which materials agree to swap with which.
The rule
Bottom-up scan, alternating left-to-right and
right-to-left between frames to keep the field from
drifting. Each non-stone cell tries down, then
down-diagonal, then for fluids: sideways. A flag marks
cells that have already moved this step so nothing gets
shoved twice. Random choices use a small linear PRNG
instead of Math.random so the cost stays low
on a sixteen-thousand-cell grid.
Things to try
Build a stone funnel and pour sand into it. Drop a band of water across the middle, then pour oil from above and watch it bead up at the surface. Make a wall of stone with a single gap and use water to find the gap. Push the steps-per-frame slider to four and you can fill the whole field in a second or two.