World in a Bottle
In the spring of 2019 I wrote my patrons a devlog in five episodes about a clockwork world in a bottle: a cellular automaton of earth and water, with tectonic plates and earthquakes, steered by control loops. These are the five episodes as I posted them, lightly edited, with the videos I made along the way. The code is in the borkshop/go repository, which was called borkshop/borkshop at the time.
Progress, problems, plans #
May 20, 2019
Wherein the protagonist toils with a clockwork world simulation.
I’m building a clockwork world in a bottle. This is a status report of some ideas that have worked and some that have not.
At time of writing, my little world is a cellular automaton with two layers: terrain and watershed.
In previous bottle world experiments, I’ve had some success modeling watersheds over terrain. The cellular automaton moves water with high surface elevations to neighboring cells with lower surface elevations. The water surface elevation combines the terrain elevation with the height of the water column. From the algorithm emerge rivers, lakes, and seas, as water settles into the basins.
In that previous experiment, I used multiple “harmonics” of OpenSimplex noise. By harmonics, I mean that each cell’s terrain elevation is the sum of multiple layers of OpenSimplex noise, with a variety of periods and amplitudes. Generally, the amplitude is proportional to the period, or inverse to the frequency. This produces an image with one of the qualities of a fractal (self-similarity) without mucking around with actual fractals. Like a fractal, tuning the amplitudes and frequencies results in a natural appearing, albeit static, terrain. Unlike a fractal, there are no dull areas.
Tessellation #
My bottle world repeats both latitudinally and longitudinally. As when going west you will arrive from where you started from the east, so will you return to where you started if you travel north or south. This eliminates strange artifacts around the edges of the world and keeps the math stupid. I’ll probably revisit this for a bottle world with interesting weather.
To make the noise seamless, meaning that the terrain and all its derivatives are continuous when they meet across opposite edges, I used a neat trick you can use to blend any continuous function.
The trick is to superimpose the image with itself, but shifted. Horizontally, scanning from left to right, the image gradually fades revealing the shifted image. Considering just the horizontal axis, the repeating image g(x) is a function of the non-repeating image f(x) in two terms: the original image (which fades from 100% to 0% scanning left to right) and the shifted image f(x − width) that reveals from left to right (0% to 100%).
g(x) = f(x) × ((width − x) / width) + f(x − width) × (x / width)
Applying this to a two dimensional image results in repetition across the horizontal axis and discontinuity along the top and bottom. To extend the algorithm to repeat both vertically and horizontally is nauseating. Each point is a function of four points from the non-repeating image.
Earthshed #
I’ve begun investigating “cheats” for generating terrain instead of using static noise. By cheating, I mean “not modeling plate tectonics”, because that would be hard™.
I’ve considered creating a cellular automaton with layers that model depth and carry the terrain layer up and down in response to magma convection, a literal lava lamp. Maybe I’ll come back to that.
One guiding principle that has been working for me so far is that beautiful complexity emerges from simple systems following simple rules (what even is a cellular automaton). My hope is to find a solution where the world begins perfectly smooth, where each cell has an independent pseudo random number generator seeded by a function of its coördinate (currently a Hilbert number), so the simulation is embarrassingly parallel.
So, I’m starting simple. Consider randomly moving small amounts of earth between adjacent cells each generation. This should generate noise with no obvious form. To lay form on the randomness, slide earth down slopes until the slopes meet their maximum angle of repose.
The “earthshed” algorithm is, if anything, simpler than the watershed algorithm. In the earth and water model I’m using, the water flows over the earth, but the earth flows over nothing, so I can exchange arbitrary amounts of material between adjacent cells and the only consideration is the relative heights of the resulting columns of soil. Instead of seeking to level the columns absolutely, we preserve the direction of the slope up to the maximum angle of repose.
I got this simple algorithm wrong a few times until I’d worked out enough edge cases for lovely loose pyramids of soil to settle.

Cellular automata have a “stencil”, the pattern of neighboring cells that each cell takes into account. I’ve been gradually simplifying my stencil down to the cell and the next cell horizontally and vertically, since those two are sufficient for modeling this kind of physical simulation. I expect most simulations can reduce to this stencil by collecting information about the neighborhood in layers through diffusion.
My algorithm decides whether to smooth latitudinally or longitudinally in each cell, favoring the dimension that has a discrepancy, or the dimension with the greater discrepancy, or resorting to a coin toss (but local and deterministic!) if the magnitude of the slope is the same.
So that works.
Quakes #
Going from zero to interesting requires some jostling. In the beginning, there is a uniform sea over a uniform terrain. The water volume is fixed. The area of dry land is not. Applying random quakes, then smoothing the earth and water by their own terms, may result in no dry land or a few very deep wells in which all the water hides.
To tackle this problem, I decided to try out a PID controller that governs the probability and magnitude of quakes (moving soil between adjacent cells, sometimes upsetting the angle of repose), to affect the amount of dry land.
A well-tuned PID controller can compensate for lag. In this case, changes to the terrain cause changes to the watershed, which in turn causes some land to eventually become dry and others to get soggy. The general trend is that the terrain smoothing algorithm will tend to submerge the dry land (in the degenerate case, the world is perfectly smooth and uniformly submerged).
I fiddled with this a bunch, and while each component was doing what it was supposed to (level the mountains, flow the water, cause cataclysms of varying scales), it never arrived at obvious mountains, rivers, and lakes. Even the slightest and least frequent earthquake caused too much jostling for too little effect, while the earthshed was entirely too effective, and the watershed could never stabilize.
An interesting statistic for the cellular automaton is how much water and earth flowed in the previous generation. Playing with these values, sometimes as parameters of the PID controller, or dampeners on their effects, was fun but inconclusive.
Next steps #
In a future set of experiments, I might try to cheat at plate tectonics more directly. Consider a cellular automaton with a layer that identifies the cell’s momentum vector. Each turn, an amount of earth travels approximately in that direction, like the quaking algorithm, but based on the underlying layer.
To be interesting, regions, preferably large and few in number, share a momentum vector. So, perhaps there are five teams in the substrata. These teams can conquer neighboring cells by more traditional rules of cellular automata, except that every cell is not alive or dead, but alive and on a particular team. To die is to join another team. The earth travels over each team based on their momentum vector. Mountains and trenches emerge on the boundaries between teams. Boundaries between teams wander with each win or loss. Natural automata like erosion smooth over emergent irregularities at the edges.
We could alternately reuse that Hilbert curve and randomly walk the boundaries of each subregion along that curve. There might emerge some strange artifacts. It might be possible to obscure those artifacts by moving the origin of the Hilbert space randomly.
So clearly, there is too much fun left to be had.
A step backward and a step forward #
May 26, 2019
I’ve taken a step backward and a step forward this week.
Last weekend, I realized that what looked like a system that might be working was effectively generating noise. I was only able to discern that there was a problem when I took my bottle world apart and ran each automaton individually on a static background with a predictable behavior.
To that end, I’ve refactored the bottle world to be more malleable. This will allow me to play more, before I start worrying seriously about performance. The automaton now has separate components for setting up the world, evolving the world, and viewing the world. I can also stack each type of component, so I can run the watershed and mudslides together.
I brought back the OpenSimplex noise as one of the options for setting up the world. This provides a good backdrop for debugging both the mudslide and watershed systems. Note that the terrain noise is the sum of a series of noises, each scaled, amplified, and tessellated with different parameters. This is more clear since I also refactored out a float64map2 package.
With these components separated, I debugged the watershed and mudslide independently, then took another run at controlling something in this simulation with a control system. I decided to take another run at controlling the portion of the world covered in water. Instead of manipulating earthquakes, I decided to take the more direct approach of just adding and removing water from individual cells, probabilistically.
My early attempt oscillated wildly forever.
This turned out to be a problem with the resolution of the tunable probability of adding or removing water from each cell. I needed a much larger domain of probabilities. I also needed to use much, much larger proportional gain. In fact, none of the gain values need to be fractions.
I’ve learned a lesson about trying to work with numbers that make direct sense. I will probably start using very large numbers for everything and represent them in percentages relative to the breadth of their range.
The video above is a snapshot of the simulation when you go run borkshop/ansimata at the linked commit.
So, next steps.
Now that I’ve got the simulation cut in a way I can work on components individually, I will begin a new experiment to model plate tectonics. I’ll be creating a new layer where each cell has a plate number. The simulation will be a more traditional automaton, where the cell will look to its neighbors to decide which plate it will participate in for the next turn.
The aesthetic I’m striving for is some small number of plates that tend to coalesce and also tend to occupy a fair and interesting portion of the world. To do this, cells will need to tend to adopt the “color” of their neighbors, but also be able to adopt any color. There also needs to be a tendency for colors that are poorly represented to have a higher chance of emerging.
To this end, I’m planning for each cell to hold a contest each round, where every color is a possible outcome. Every color will have a fixed constant number of tickets in the lottery, plus some number of tickets for neighbors of the same color, plus the total number of cells in the previous generation with other colors, possibly with a multiplier. The last term may even be unnecessary to obtain interesting results.
Each color will correspond to a direction that earth will tend to move over that particular plate. This will cause rifts where plates move apart and mountains where they converge, or just scars where they drift past each other. With an odd number of plates and a bunch of weirdness from chance, this should result in a familiar wrinkled landscape, with long, level flood plains between the heights, and lakes of trapped water among the jagged peaks.
A world of constant quaking will probably not settle, so I plan to use another PID controller to control the spread between the highest and lowest terrain elevations by increasing the probability that earth will move over the plates.
I’m unreasonably excited about this approach, so I’ll be getting back to trying to make this happen.
Coälescing continents #
May 27, 2019
I’ve an idea for a cellular automaton that will render aesthetically convincing mountain ranges. Yes, it involves modeling plate tectonics. But, since this is an art project and not an attempt to model real-world phenomena, I can take liberties.
I’ve been avoiding plate tectonics. It seems like there are two ways to make them. You either model strata with all their rollings over and rollings under, or you try modeling magma convection like a world-sized lava lamp under a tumbling crust.
Both of these are hard to model. The latter is probably possible but involves modeling many invisible layers of data in a thick third dimension. The former isn’t really a cellular automaton, and if it is, it probably lacks that musical quality of embarrassing parallelism.
This automaton requires three components.
- A cellular automaton that classifies every cell as being a participant in a particular tectonic plate. The automaton should converge on large contiguous plates with stable but randomly wavering edges. Plates should tend to remain about the same size and plates should not disappear.
- A cellular automaton that will move earth in a general direction, based on a vector assigned to each plate. If there are 17 plates, divide 360º into 17 directions, one for each plate. Since this is a two-dimensional cellular automaton, decompose each vector into its lateral and longitudinal components and use these to weigh the probability of moving earth laterally or longitudinally. Like a syneth, I’ll hereafter refer to tectonic plates interchangeably by hue of color (360º) or their lateral motion vectors (conveniently also, possibly even the same value on 360º).
- A control loop that attempts to maintain the spread between the lowest and highest terrain elevations. This control loop governs the probability of moving earth in the prior automaton.
The second automaton will tend to cause ripples of various kinds depending on how plates are moving earth relative to each other. There’ll be upthrust in some places and trenches in others. The mudslide automaton will counteract some of these effects, ensuring that earth piles into mountains and fills valleys rather than forming walls and steep pits.
Today, I managed to produce the first algorithm, a new cellular automaton that divides the world into tectonic plates.
First, seed the world with random plate numbers on every cell. This produces a baseline with probable representation from every plate.
Then, create a visualization of tectonic plates, where the plate number is represented with the hue of each cell. I’ve used HSLuv, a favorite introduced to me by my colleague, Josh Corbin. This is a color space that divides hue evenly by perception. HSLuv gives the programmer the developer experience of HSL, but with the hidden sophistication of a complex color space related to CIE.
Third step is applying a rule rigorously on each cell of each generation. For this algorithm, I’ve used an algorithm shaped more like Conway’s Game of Life. Instead of living or dead, each cell attempts to conquer neighboring cells.
My first, naïve attempt rocked my faith in this approach. The algorithm surveyed the cell and either four or eight of its neighbors in the previous generation (the “read stencil”). It then constructed a histogram, counting how many of each kind of neighbor there were. The algorithm then conducted a lottery and assigned the color of the winning plate to the cell in the next generation.
This resulted in noise. Plates did not emerge from the chaos after any amount of time.
I took a break to be alone and miserable with my empty soul and returned to the problem with a willingness to fiddle until a good idea came around. I tried fiddling with the stencil size to no avail. I tried staring at it with a variety of facial expressions. I played with adding a fixèd constant to each bucket (opposite of desirable effect).
The plates started to coälesce when I squared the weights. They coälesced faster if I cubed the weights. The game was afoot! I had a working simulation that caused contiguous blocks to emerge.
Of course, it takes money to make money, the powerful tend to have the means to become more powerful, and eventually the whole world inevitably became one solid colorèd continent. I had anticipated this, so I was armed with a counter-measure: bias each color by multiplying it by its relative scarcity: the number of cells from the previous generation that were any other color. With this system in place, continents tend to stabilize over time, and rarely do continents go extinct, though they will tend to if you have too many continents for the area of the simulation.
Another investigation may reveal a way to bootstrap a new continent if one dies, perhaps by dividing the cells of the largest continent in the prior generation between its current color and the color of the dead continent.
Until then, I’m happy to report that I’ve
modeled plates.
Check it out on GitHub and give it a run with go run borkshop/ansimata.
The next step is to hook up the plate motor to the elevation spread controller. After that, the next steps are either modeling erosion, improving the rendering of water to include some sweet line art for rivers, moving on to weather to sustain the evaporation and precipitation cycle (ensuring that erosion continues to occur), adding a flora automaton, or…
Earthquake controller #
May 31, 2019
A brief update following our last report on plate tectonics: you may recall that I planned to add earthquakes and a quake controller to the world in a bottle.
To recap: measure the spread between the lowest and highest elevations in the world. Run a PID controller for the probability that earth will move for any given cell in the world. If the earth does move, move it generally in the direction assigned to the cell’s underlying tectonic plate.
There are some minor details. I chose to move earth in one direction per turn on each cell. I created an integer vector for every plate. Choosing whether to go horizontally or laterally was a lottery, where each gets tickets based on the absolute horizontal or lateral component of the quake’s motion vector.
The PID controller governs the probability that any individual cell moves. This turns out to be important, to give the PID controller sufficient resolution that it notices that the earth elevations have spread before the whole world is shaking.
If you watch the video to the end, you’ll notice an important facet of the simulation: it stops! This is a desirable outcome. Once the world settles in, quakes should be very occasional, only necessary to counteract the forces of erosion that would eventually weather the whole world down to a flat plane and a thin doldrum of ocean covering it.
So, the next step for bottle world is to introduce evaporation, precipitation, and erosion. The plan for erosion is to make the angle of repose for each cell a function of how much water flowed over it in the previous generation. This should cause canyons to emerge!
First, however, it’s time to take a step back and refactor. After giving this some thought, and conversation with our mutual friend Josh Corbin, I’ve realized that I can make the implementation significantly more compact and fast by modeling each layer of the simulation as a separate, homogenous vector, as one would if they were doing this with a GPU shader. I’m working on a cool approach where each step of the simulation is a function of one or more vectors that writes over a vector. I’m also eliminating the computation of Hilbert curves from the hot path by pre-computing the offsets of every neighboring cell in the “stencil”, assuming that these vectors are laid out along a Hilbert curve. The results in my working copy are exciting, having faithfully recreated the plate tectonics layer so far!

I am hopeful that erosion will allow the world to converge on a more stable and aesthetically compelling eventual state. One of the desired emergent phenomena is large fluvial plains between sea and mountains. The mountains should be sharp and the plains long and gentle. This is possible if the world is large enough, the angle of repose for mountains sharp enough, and the plains gradual enough. It also requires the quake generator to kick in after the tectonic plates have finished coälescing. At the moment, we get some initial land formation while the world’s plates are random, and that suppresses the quake generator later. With erosion, we should start to see the mountains occur only on the boundaries of the consolidated plates.
Vector rewrite #
June 1, 2019
A brief progress report. I’ve rewritten the World in a Bottle cellular automaton. The new implementation more closely resembles a shader. I pivoted the model from being “row-oriented” to “column-oriented”.
Instead of World contains Cells. Cells contain Values (Earth, Water), the new implementation is modeled like World contains Vectors. Vectors (Earth, Air) contain Values.
Apart from plotting an intercept course for hardware acceleration (with another, more direct rewrite), this has made a number of components more reusable and maybe also faster. The simulation no longer computes Hilbert numbers for points at runtime. It also enforces unidirectional dataflow.
There are a bunch of ways to order the values in an array to correspond with points in a two dimensional array. Often, we use “raster order”, the order you would read words on a page. Left to right, top to bottom. There’s also Z-order, which improves cache locality with a relatively cheap algorithm that interleaves the bits of the X and Y coördinate of each point. Then there’s the Hilbert order, where every cell is guaranteed to be adjacent to two out of four of its neighbors.
I’ve been using a Hilbert curve because I suspect (but have not verified!) that the order reduces cache faults. But, the previous incarnation of this automaton spent a great deal of time recomputing Hilbert numbers.
So, I’ve been using the Hilbert order for cells, and now use the same order for values in a bunch of independent vectors, one for each layer of the automaton: earth, water, tectonic plate, &c.
However, to find the value for all of a cell’s neighbors requires first figuring out the point that corresponds to the position (decoding the Hilbert number), then computing the coördinates of all the cell’s neighbors (its “stencil”), then reëncoding those points to Hilbert numbers. These are the offsets in the same array for all the cell’s neighbors in 2-space. The resulting table is not obvious. From the test, for a world four cells on a side, the Hilbert number of every cell in the comment, and for each cell, the offsets of its neighbors to the east and south:
length := 4
area := length * length
table := make([][2]int, area)
WriteHilbertStencil3Table(table, length)
assert.Equal(t, [][2]int{
// 0 1 E F
// 3 2 D C
// 4 7 8 B
// 5 6 9 A
{1, 3}, // 0
{14, 2}, // 1
{13, 7}, // 2
{2, 4}, // 3
{7, 5}, // 4
{6, 0}, // 5
{9, 1}, // 6
{8, 6}, // 7
{11, 9}, // 8
{10, 14}, // 9
{5, 15}, // 10
{4, 10}, // 11
{3, 11}, // 12
{12, 8}, // 13
{15, 13}, // 14
{0, 12}, // 15
}, table)
Each of these algorithms like watershed, mudslide, plate coälescing, read from the neighborhood and write back to the neighborhood. If you’ve done everything right, you never read something you wrote in the same pass. Information flows only forward through time.
This is a little tricky to enforce and I doubt I obeyed the rule to the letter.
However, with this rewrite, I’m pretty confident that information flows through time properly. The trick is to split every cell into a read stencil vector or join every stencil vector back to an array of cells. The watershed and mudslide algorithms read and write a 3-cell stencil vector. A neat thing that falls out of this approach is that this algorithm can run without knowing anything about the topology (square cells? hexagonal cells?) or layout of the array (Z-order? Hilbert? raster?). It just operates on each individual stencil.
In particular, the mudslide algorithm reads a cell and its two neighbors. It then decides the direction and amount of earth to move between that cell and its neighbors, based on the gradient. Then, it copies the level from the previous generation to the next generation, plus or minus some earth that has moved, and then writes the opposite plus or minus value (without the constant) in the write stencil for the neighboring cell.
This takes into account how each of these individual decisions is going to result in an independent offset for the two neighbors. The “join” algorithm takes each of the overlapping but non-adjacent write stencils and merges the sums of these values into their corresponding offsets in the one dimensional write array:
func AddInt64VectorStencil3(dst []int64, src [][3]int64, table [][2]int) {
for i, stencil := range table {
e, s := stencil[0], stencil[1]
dst[i] += src[i][0]
dst[e] += src[i][1]
dst[s] += src[i][2]
}
}
Suffice it to say, the implementation is considerably more succinct and pliable after this rewrite. The next step is to make the angle of repose a function of the watershed, so rivers can carve canyons, then introduce a water cycle so erosion will continue at a pace after the mountains and seas have fully formed.
Afterword #
That was the last episode. The repository carries the story a little further. Josh Corbin ported the rewrite to WebAssembly the same day, so the bottle ran in a browser, and in the week after he built it a user interface and began a WebGL renderer. On June 30, 2019, I added erosion and continuous precipitation, the next step the last episode names, and the last change to the automaton was a view of the watershed’s gradient, on July 5.
As of 2026, I have yet to carve canyons with a cellular automaton to my satisfaction, and it is still on my mind.
First published on Patreon in five parts, May 20 to June 1, 2019.
- Previous: The Quaffle House
- Next: Peruácru