Maximal Sand is a Game/Art program I wrote that simulates falling sand. It is written in C++ and compiled to WebAssembly using Emscripten. The simulator is written to be multithreaded. But for older browsers that don’t support WebAssembly multithreading, the simulator has a single-threaded version that is loaded automatically. The Simulation is divided into 16x16 chunks, and each chunk can have three states: Clean, Dirty, and Empty.
When sand moves, the chunks it moves to and from are marked as dirty. If a chunk is processed and no sand is moved, the chunk is marked as clean. If no sand is detected, the chunk is marked as empty. To avoid race conditions, threads write to chunks in a checkerboard pattern. This ensures that when a chunk is processing, none of the chunks immediately surrounding it are. This prevents the need for atomics in the simulator’s frame buffer. To handle windows such as the palette window, the simulator includes a full window manager. Windows use a grid layout to scale according to the screen size. The main window is the background window. It contains the sand simulation and the buttons at the top. You can play the simulator by clicking the button below.