Game design

How to Cheat Physics a Little

Dec 1, 202621 min

Back in 1994 X-COM let you blow out the wall of a building, set its contents on fire and wait for the smoke to blind the aliens sitting inside, I sank a great many hours into the first and second X-COM and every time I was amazed at how carefully the behavior of different objects had been worked out, and the game can still surprise you today. In 2006 I stumbled upon Dwarf Fortress, which was only just getting started, where you could drown several generations of dwarves by badly designing the fortress water supply. Then came Noita, which never reached the depths of the dwarf-fortress-building rabbit hole, but practically every pixel of its game world was given physical properties, after which the number of ways to accidentally kill your own character stopped being measurable.

Games are poorly suited to modeling complex physical processes, because those processes have a habit of eating all the resources and time you give them, and getting carried away writing useless junk is oh so easy. Useless from the point of view of the game world, that is, if it shows up in fewer than 10% of game events, so developers try to “hack” relatively simple representations of the game world, and build the “complex” behavior the player observes out of interactions between individual elements within a small area.

For quite a long time physics in games came down to a handful of objects that were “allowed” to move around the world, while the rest were invited to stand still and play the part of that very world, this is called a “clay world”. With the arrival of physics engines objects learned to fall, collide with each other, tumble down stairs or fly off into the stratosphere when you tried to close a door, but water, fire, smoke and other things that are hard to hand a polygonal model and a transform matrix fared worse.


Water was usually a horizontal polygon with an animated texture, fire was and still is made from a number of sprites drifting upward, and smoke differed from fire mostly in the color of those very sprites. If needed, the water level could be raised and the fire carried over to a neighboring object, provided the level designer had foreseen that possibility and hadn’t forgotten to place the corresponding trigger. Thanks to design decisions like these, the room itself could easily catch fire regardless of what it was built from and whether anything non-flammable stood between the fire source and the room.

Scripted fire looks like a bug on the whole, but for most games it’s quite enough, and a player running past a burning house isn’t especially interested in how the fire spreads inside. But all the scripted crutches poke out very quickly once the player is “suddenly” allowed to open the door, flood the house, take apart a wall, dig a pit under the house and see what comes of it. And soon the number of scripts needed starts to somewhat exceed the number of people willing to write and test them, and the studio gets a “technical environment designer” position, which many people truly dislike, because the work is tedious and you can’t hand it off to an AI, since the “human touch” goes missing.

Worn out by scripts, the designers go to the programmers and ask for some universal model that will let water flow down, fire spread upward or along flammable materials, and smoke fill rooms without the designer having to personally take part in every single object and material. Programmers are a lazy bunch too, and instead of writing a full-fledged simulation model (because it’s hard, and see the point at the beginning) they reach for cellular automata (CA), which aren’t quite the cellular automata mathematicians write dissertations about, but they are cellular automata in the proper sense of the term, as will be explained below, and that’s how cellular physics sneaks into the game.

What cellular physics is

If you open a fluid dynamics textbook (I learned from Godunov and Samarsky), by page one hundred you reach the Navier-Stokes equations, which describe the motion of a viscous fluid, but by the time we get to those equations we’ve already been handed a great deal of math, hard math that modern processors digest with difficulty. You could take these equations head-on, discretize space, set up storage for the velocity field, account for pressure, viscosity and boundary conditions, all to work out how far to displace the polygons in the glass of champagne in the player’s hand. Preferably managing it in a few milliseconds, because the processor in a game engine isn’t reserved for the champagne alone.

There are plenty of places to cut corners here, and game programmers are in an enviable position, since most players have neither the means nor any particular desire to check whether the calculations are correct. For water to be perceived as water, very little is asked of it, it just has to flow down, fill hollows and, if at all possible, not vanish for no visible reason.

If we tweak the physical properties of water a little to get this behavior, the player won’t notice a thing, and if they do notice, after a while they’ll start using those properties to solve in-game problems. That’s what Minecraft does, where a few water sources can be turned into an infinite source, although the law of conservation of mass has nothing good to say about it.

So when developing game physics you have to choose between physically correct and “humanly expected” behavior, and the latter is usually much cheaper to compute and easier to explain to the designer and the player. This is where cellular automata take the stage, letting us, instead of computing the state of an entire level-sized physical system, describe the behavior of a small part of it and then see what happens if such parts are loosely “glued” together.

Cellular automata and falling sand

In the simplest case a cellular automaton is a grid, each cell of which has some state. The rules for changing that state depend on the state of the neighboring cells, and as you’ve already guessed, the best-known example is John Conway’s “Game of Life”, where a single bit is enough to store the state of one cell. Complex structures capable of moving across the board and interacting with each other emerge from a few rules that determine under what conditions a cell stays alive.

One bit won’t be enough to model physical processes, of course, but if we start with a two-dimensional model where each cell contains some material, such a world can be represented roughly like this:

enum class Material : uint8_t {
    Empty,
    Sand,
    Water,
    Stone,
    Wood,
    Steam,
    Smoke
};

struct Cell {
    Material material;
};

Cell world[1024][1024];

If sizeof(Cell) equals one byte, storing such a world takes exactly 1 MiB of memory, and so far we have no separately allocated objects, pointers, virtual functions or other such things. But we can already add rules for how materials behave, and they can be fairly simple too:

Sand:
    Try to move down.
    If below is occupied, try the diagonals.

Water:
    Try to move down.
    If below is occupied, try to move sideways.

Smoke:
    Try to move up.
    If above is occupied, try to move sideways.

Stone:
    Do nothing, lie there and enjoy the view of the bustling sand, water and smoke

For sand the corresponding piece of code will look roughly like this:

void update_sand(int x, int y)
{
    if (try_move(x, y, x, y + 1))
        return;

    int dx = random_direction();

    if (try_move(x, y, x + dx, y + 1))
        return;

    try_move(x, y, x - dx, y + 1);
}

try_move() checks whether the material can be moved into the neighboring cell and, if so, carries its contents over, and if the neighboring cell holds a less dense movable material, we can do more than just move the sand, we can swap the contents of the cells, which lets the sand gradually settle to the bottom of a pond.

If you run this function for the cells containing sand, the sand starts pouring down, filling hollows and forming the characteristic piles, even though our model so far has no notion of the angle of repose, the friction coefficient or the interaction of individual grains, and this is a very important point that hundreds of games rely on. There’s no sand physics there, there’s just this update_sand() rule.

A whole family of games and simulators known as Falling Sand Games is built on similar principles, and they became quite widespread as small browser apps where you can paint various materials on the screen and watch the results of their interaction.

Probably the best-known implementation of this idea is Noita, whose developers turned a falling sand simulator into a full-fledged game world, adding character movement, material interactions and simulation of destructible rigid bodies. In his GDC talk Petri Purho said that a significant share of the technical problems during development had less to do with programming and more with coming up with the rules for how materials move. The need to process large chunks of the game world eventually got pushed into shaders and material textures, because the processor was already giving up at 2k*2k pixels.

In what order to process the cells

The first trouble you run into when implementing a cellular automaton comes from the order in which the array is traversed, which suddenly starts influencing the physical laws of the world, even though we built in nothing of the kind. Say we have a one-dimensional array with a grain of sand in the first cell and all the other cells free, and when processing each cell we try to move the sand one position to the right.

[S][ ][ ][ ][ ][ ][ ]

If you traverse the array left to right, then after processing the first cell the particle ends up in the second, which hasn’t been processed yet, after processing the second it’s in the third, and so on, so in a single tick the particle crosses the entire array, whereas traversing right to left it moves just one cell.

For falling sand this problem is solved by traversing the two-dimensional array bottom to top, but we also have water, which moves sideways, and smoke, which moves up, so picking a traversal direction that suits all the materials at once won’t work. After a bit of thought we have to introduce a new field and mark already processed cells with the current tick number:

struct Cell {
    Material material;
    uint32_t last_update;
};

void move_cell(Cell& from, Cell& to, uint32_t tick)
{
    std::swap(from, to);

    from.last_update = tick;
    to.last_update = tick;
}

Now the cell the material moved into won’t be processed again on the same tick, but to store one byte of material we now need several bytes of tick number, and this is a rather typical situation for cellular simulations, when an algorithm that let us avoid a few conditional branches or slightly simplified the update rules starts costing noticeably more memory than the very data it was written to process. For our simple simulation it’s enough to store just the fact that a cell was processed, and then these flags can be moved into a separate bit array:

bool was_updated(size_t index)
{
    return updated[index / 64] &
           (uint64_t{1} << (index % 64));
}

void mark_updated(size_t index)
{
    updated[index / 64] |=
        uint64_t{1} << (index % 64);
}

Another way to organize updates when modeling continuous quantities like temperature or pressure is to keep two states of the game world, one used strictly for reading and the other for writing the results of the calculations.

std::vector<Cell> current;
std::vector<Cell> next;

void tick()
{
    next = current;

    calculate_transfers(current, next);

    std::swap(current, next);
}

In this case the calculations don’t depend on the order in which we traverse the array, and all the quantities that determine the result are read from the previous state. Everything comes at a price, and what we get is double buffering, which doesn’t solve the problem of update conflicts, since several particles may still want to move into the same cell, and several neighbors want to take more water out of one cell than it held at the start of the tick.

So for continuous physical quantities it’s more convenient to first compute the flows between neighboring cells and only then apply them to the world state, which somewhat increases the amount of data kept in memory but makes life noticeably easier.

The third dimension and its problems

While we were modeling two-dimensional space, the memory requirements looked fairly modest, but on moving to the third dimension you quickly discover that adding one more coordinate badly strains the cellular automaton’s relationship with the RAM and processor the computer actually has. In a full solution with a three-dimensional array of cubic cells you’ll have to decide how literally you take the words “full solution”, because:

 6 neighbors — cells sharing a face.
18 neighbors — cells sharing a face or an edge.
26 neighbors — cells sharing a face, an edge or a vertex.

For most games simple models of matter and heat transfer between six neighbors are enough, and that exchange happens through cell boundaries anyway. If you use diagonal neighbors, you’ll also have to account for the fact that the distance between their centers differs from the distance between the centers of cells sharing a face, and part of the math starts to break.

Now suppose we want to model water, fire and smoke inside a building measuring 100×100×20 meters, and we take 16 bytes to store the properties of one cell (mass of matter, temperature, material and a few flags).

Cell sizeNumber of cellsMemory required
1 m200 0003.05 MiB
50 cm1 600 00024.4 MiB
25 cm12 800 000195.3 MiB
10 cm200 000 0002.98 GiB
5 cm1 600 000 00023.84 GiB

It’s still the very same building, but going from half-meter cells to ten-centimeter ones we gained the ability to model interior walls and vents far more accurately, and found out along the way that our physical model of this small building is now capable of eating practically all the memory available to the game.

Memory is only half the problem here, because the cells also have to be processed periodically, and if we want water to move one cell per tick, then shrinking the cells fivefold may force us to raise the update rate by the same five times, otherwise the physical speed of the water will drop.

And that, actually, is where all dreams of building any more or less honest particle physics on cellular automata come to an end, even though from the level designer’s point of view he merely asked for a little more detail.

A thin wall in a thick cell

This problem was born together with cellular automata, and it doesn’t let you store obstacles inside cells or on the boundaries between them, so you have to add an extra field inside the cell to hold this information. A similar split of geometry was used in the original X-COM, where the floor, the north and west walls and the contents of a tile were represented as separate elements, which made it possible to place walls between cells of the game world without allocating a separate volume of space to each wall.

In our case each cell can store three faces pointing along the positive coordinate axes, since the other three faces belong to the corresponding neighboring cells.

enum FaceFlags : uint8_t {
    BlockPositiveX = 1 << 0,
    BlockPositiveY = 1 << 1,
    BlockPositiveZ = 1 << 2
};

struct Cell {
    uint8_t material;
    uint8_t blocked_faces;
    uint16_t temperature;
    float mass;
};

With this representation a wall can have practically any visual thickness, and from the cellular automaton’s point of view it simply forbids the exchange of matter between two neighboring cells.

+-------+-------+-------+
|       |       |       |
| AIR   | WATER # AIR   |
|       |       #       |
+-------+-------+-------+
                ^
             thin wall

If we want the wall to let heat through but not water, and to have its own strength, temperature and ability to be destroyed, three bits are no longer enough, so the face gets its own material description, which in its set of properties gradually starts to resemble the description of a full-fledged cell.

struct FaceMaterial {
    float fluid_permeability;
    float gas_permeability;
    float thermal_conductivity;
    float strength;
};

The faces themselves can be stored separately from the main cell array, since most of the space contains no walls at all, and the face material description only needs to be looked up if the corresponding bit in the cell’s mask is set.

Another option is to put the physical wall in a whole cell, but when displaying the game world pretend that the neighboring cells have expanded slightly and occupy the wall’s space. The cellular automaton itself knows nothing about this expansion, since for it all cells are still the same size, and the renderer simply takes the actual placement of the geometry into account when building the water surface.

For the player the difference between the two approaches is completely invisible, since water and smoke have no strictly defined shape, while for the programmer it comes down to either supporting two different kinds of physical entities or telling a small lie about how much space is available to the matter.

If all we need is to model water and smoke inside rooms, there’s no particular need to store the physical characteristics of the walls themselves, it’s enough to convert the geometry at level load into a set of obstacles that forbid the movement of matter between the corresponding cells.

This approach is called a passive environment, and then the cellular automaton knows the wall exists, but the wall itself knows nothing about the physical processes going on next to it, although for opening doors, movable furniture and other dynamic objects you’ll have to provide a way to change the corresponding obstacles.

With an active environment the cellular automaton can already change the state of the wall’s own material, and the graphics and physics engines must somehow react to those changes, for example by updating the visual representation of the damaged wall, removing the corresponding parts of geometry and telling the navigation system that where a wall stood a while ago you can now walk.

So the cost of moving from a passive environment to an active one is determined by the number of other engine systems that will have to be told the environment is no longer static, and by the amount of programmer laziness.

Air that creeps across the cells

Let’s try to model the spread of some gas (we’ll store the mass of matter in each cell), assuming that the volume and temperature of all cells are the same and the difference in masses roughly corresponds to the difference in pressures. In a simple model it’s enough to carry some amount of matter from the cell with the larger mass into the cell with the smaller one (that’s how it’s done in one well-known game, you may even have played it):

float calculate_flow(float a, float b, float k)
{
    return (a - b) * k;
}

If we use double buffering and process each pair of neighboring cells once, the corresponding code will look like this:

void transfer(uint32_t a, uint32_t b)
{
    constexpr float K = 1.0f / 6.0f;

    float flow = (mass[a] - mass[b]) * K;

    next_mass[a] -= flow;
    next_mass[b] += flow;
}

The 1/6 coefficient is chosen here because a cell has six neighbors (the weak physics model), and if none of them holds any matter, then in one tick our cell can give each neighbor no more than one sixth of its mass. With a larger coefficient we risk getting negative mass, after which some rather interesting processes start happening in the neighboring cells, courtesy of the peculiarities of how our numerical method is implemented.

In this model the total mass of gas is conserved, and any amount of matter we subtract from one cell is added to another, and if there’s an obstacle in the direction of some cell, the exchange simply doesn’t happen.

void update_fluxes(int x, int y, int z)
{
    const int a = index(x, y, z);

    if (can_exchange(a, a + 1))
        transfer(a, a + 1);

    if (can_exchange(a, a + StrideY))
        transfer(a, a + StrideY);

    if (can_exchange(a, a + StrideZ))
        transfer(a, a + StrideZ);
}

The resulting model is a simple discrete diffusion, not full-fledged gas dynamics, so you won’t be able to model gas inertia or turbulence with it, but for smoke that should gradually fill rooms, spread through open doors and affect what characters can see, this model gives results that are perfectly usable for gameplay.

Oxygen Not Included

A well-known example of this model in game design is Oxygen Not Included, where mass, temperature, states of matter and the movement of gases and liquids make up a significant part of the gameplay, and yet a single cell of the world can contain only one element.

From the real world’s point of view this is a rather odd restriction, since air contains several gases at once, but from the game developer’s point of view it lets you store, instead of an array of different substances, just the identifier of one material and a few quantities describing it.

struct GasCell {
    uint16_t element;
    float mass;
    float temperature;
};

If we wanted to model a mixture of gases, the corresponding structure could look roughly like this:

struct GasCell {
    float oxygen;
    float nitrogen;
    float carbon_dioxide;
    float hydrogen;
    float steam;
    float temperature;
};

And if the number of substances is defined by game data and not known in advance, we’d have to either allocate memory for every possible component of the mixture, most of which are absent from any given cell, or use some kind of sparse containers, which would pretty quickly show up in the time it takes to process a cell.

So the one-substance restriction both reduces the amount of stored data and somewhat simplifies the simulation code, so that a single gas can be moved along simply by swapping the contents of neighboring cells.

But such a world acquires its own laws of physics, and liquids are no longer obliged to mix, different gases start forming sharp boundaries, and a small amount of liquid occupying one cell of the game world can block gas from passing through that cell no matter how convincingly, geometrically speaking, the cell itself is filled, which is exactly what we see in the game.

Oxygen Not Included players use these quirks to build liquid airlocks, gas filters and other engineering contraptions, which within the game’s physical model behave quite predictably.

Water you can compress

Unlike gas, water under normal conditions is practically incompressible, and if every completely filled cell contains exactly one liter of water, then from the state of two neighboring filled cells it’s completely unclear whether there’s any pressure difference between them, even though for modeling communicating vessels that difference would come in rather handy.

That’s why in simple cellular models water is sometimes made compressible, letting cells hold a bit of extra liquid that plays the role of a nominal pressure. In the normal state a cell can hold one nominal unit of water, but for each level of depth we allow an additional 1% of the nominal mass to be squeezed into it:

Surface:      1.00
Level 2:      1.01
Level 3:      1.02
Level 4:      1.03
Level 5:      1.04

Now, if we connect two tanks with a pipe placed below the water surface, the excess mass in the lower cells of one tank will gradually pass to the neighboring cells until the water levels in both tanks even out, and we didn’t have to separately compute the pressure at every point of the pool. For this we need a function that determines the equilibrium distribution of water between two cells stacked one above the other:

constexpr float MaxMass     = 1.0f;
constexpr float MaxCompress = 0.01f;

float stable_bottom_mass(float total)
{
    if (total <= MaxMass)
        return total;

    if (total < 2.0f * MaxMass + MaxCompress) {
        return
            (MaxMass * MaxMass +
             total * MaxCompress) /
            (MaxMass + MaxCompress);
    }

    return (total + MaxCompress) * 0.5f;
}

Depending on the total amount of water we get three cases: either all the water fits into the lower cell, or the lower cell is full and the upper one partially filled, or both cells are full and the lower one should hold a little more water. Knowing the equilibrium state of two cells, we can compute how much water needs to be moved down:

float vertical_flow(float upper, float lower)
{
    float target = stable_bottom_mass(upper + lower);

    return std::clamp(
        (target - lower) * 0.5f,
        -lower,
        upper
    );
}

For horizontal neighbors it’s enough to gradually even out their masses:

float horizontal_flow(float a, float b)
{
    return (a - b) * 0.25f;
}

This model gives you communicating vessels, flooding rooms, water flowing through pipes and overflowing tanks without a separate system for solving pressure equations, although when modeling very deep bodies of water the extra mass piling up in the lower cells becomes noticeable.

Three bits of water level in Dwarf Fortress

That’s what Dwarf Fortress did, only it went even further toward simplifying how liquid is represented. The depth of water and magma in each cell of the world is an integer from 0 to 7, which is enough for building water mills, setting up irrigation and the other pastimes the player uses to keep their dwarves entertained.

0/7 — no liquid.
1/7 — a small amount of liquid.
...
7/7 — a completely filled cell.

Liquid levels let you represent depth with three bits, but extra rules for modeling pressure had to be added there. Since in certain situations water can move through a chain of filled cells, landing straight in a more distant available cell. Say we have a pipe 100 cells long, completely filled with water, and we add one more unit of liquid at one end. Within a local cellular automaton the state change would have to pass through all hundred cells one after another before the extra water shows up at the other end of the pipe, although from the gameplay point of view it would be far more natural to immediately push some of the water out into an available neighboring area.

For your own implementation you can use a search over the graph of connected filled cells, after which the extra portion of water is moved into one of the available cells on the boundary of the region found:

CellId find_water_outlet(CellId start)
{
    queue.clear();
    visited.clear();

    queue.push(start);
    visited.set(start);

    while (!queue.empty()) {
        CellId cell = queue.pop();

        for (CellId neighbor : neighbors(cell)) {
            if (visited.test(neighbor))
                continue;

            if (!can_flow(cell, neighbor))
                continue;

            if (has_free_capacity(neighbor))
                return neighbor;

            if (is_full_of_water(neighbor)) {
                visited.set(neighbor);
                queue.push(neighbor);
            }
        }
    }

    return InvalidCell;
}

This isn’t the algorithm from Dwarf Fortress, the one there is a bit more complicated, but it’s one possible way of solving a similar problem. If the geometry of the filled region rarely changes, the results of such a search can be cached, or the filled regions can even be merged into separate components. Here we’ve traded a large number of relatively cheap local updates for a periodic but more expensive traversal of a connected region, and which option turns out cheaper will depend mostly on the size of the bodies of water and the nature of the changes in the game world.

Temperature you don’t need to move

To model thermal processes we could do roughly what we did with gas, storing the temperature in the cell and gradually evening it out between neighbors, but temperature isn’t a quantity that has to be conserved during heat exchange, and heating different substances by one degree takes different amounts of energy. Approximate specific heat values for a few substances are as follows:

Water:      4180 J/(kg·K)
Air:        1005 J/(kg·K)
Aluminium:   900 J/(kg·K)
Iron:        450 J/(kg·K)
Copper:      385 J/(kg·K)

So if you take a kilogram of water at 80 °C and a kilogram of iron at 20 °C, once thermal equilibrium is reached the temperature will be about 74 °C, and not 50 °C at all, as it would be after simply averaging the temperatures.

And if we also take equal volumes of water and iron, then because iron is so much denser the total heat capacities of these volumes turn out to be comparable, and we’ll have to account not only for the material but also for the amount of matter actually sitting in the cell.

For a simple heat conduction model you can store mass, temperature and a material identifier in the cells, and move specific heat and thermal conductivity out into a table.

struct ThermalCell {
    float mass;
    float temperature;
    uint16_t material;
};

struct ThermalMaterial {
    float specific_heat;
    float conductivity;
};

Then the amount of energy that has to be transferred from one cell to another to reach thermal equilibrium can be computed with the formula:

Qeq = (Ta − Tb) / (1/Ca + 1/Cb)

where Ca and Cb are the total heat capacities of the cells, obtained by multiplying the mass of the substance by its specific heat. Now, knowing this value, we can cap the amount of energy transferred between cells in one step, so as not to end up with the colder cell having warmed up more than the hotter one managed to cool down.

float calculate_heat_transfer(
    float ta, float tb,
    float ca, float cb,
    float conductance,
    float dt)
{
    if (ca <= 0.0f || cb <= 0.0f)
        return 0.0f;

    float delta = ta - tb;

    float equilibrium =
        delta / (1.0f / ca + 1.0f / cb);

    float requested = delta * conductance * dt;

    return std::clamp(
        requested,
        std::min(0.0f, equilibrium),
        std::max(0.0f, equilibrium)
    );
}

After which the energy is subtracted from one cell and added to the other, taking their heat capacities into account:

a.temperature -= q / capacity_a;
b.temperature += q / capacity_b;

And even if we’ve picked a somewhat larger time step, the final state of the pair of cells stays physically “reasonable”, and if large time intervals need to be handled more carefully, you’ll have to go looking for more sophisticated simulation methods.

Convection and thermal radiation

But in the real world heat spreads not only by conduction, but also by convection and thermal radiation. For modeling fire in a room both of these processes matter, and in that case heated air rises (convection), while red-hot surfaces heat other surfaces (thermal radiation) some distance away from them.

We already have a gas movement model, and convection can be roughly reproduced by making vertical movement depend on the temperature and density of the substance, but then we’d have to update a fairly large volume of air around the heated object, whereas for gameplay we may only need the smoke to rise and the burning sections of a wall to heat the sections above them.

Then we can get by with a simpler model, describing separately the preferred direction of hot gas movement and an approximate heat transfer, and the parameters of this behavior will be dictated by the need to get a convincing and predictable result in a particular game.

Thermal radiation is trickier, because cells that aren’t neighbors at all can interact, so on top of the local cellular automaton you’ll need either to trace rays or to precompute visibility and the characteristics of the surrounding geometry.

With static geometry part of this data can be computed while the level is being prepared, using methods similar to baking lightmaps, but if the environment can be destroyed, that data starts going stale, and we end up with yet another system that has to be kept up to date.

Fire as a material state

In the classic implementation fire is a particle emitter, some light source and a trigger that changes the state of whatever objects wander into it. All three entities can exist independently of each other, and for most staged scenes that’s quite enough.

With cellular physics you have to represent fire as a process of changing the state of materials, and then derive from the state of those materials the information the renderer, the sound system and the game logic need.

struct MaterialProperties {
    float density;
    float heat_capacity;
    float conductivity;

    float ignition_temperature;
    float fuel_capacity;
    float game_burn_rate;

    Material residue;
};

Rough interaction rules might look like this:

Heated wood           → burning wood
Burning wood          → heat, smoke, residue
Burning material without fuel → non-flammable residue
Water and burning material  → change in burning state

And to figure out what exactly needs to be drawn, the renderer no longer has to know how a particular object caught fire, whether it was set alight by a script, heated up from another object or simply ended up next to a heat source, since all the necessary information is contained in the current state of the cells.

You can spawn flame particles over the corresponding patches of surface, create smoke, change the material’s color and add light sources, and if the material has stopped burning in the simulation, gradually remove the corresponding visual effects.

However, as new materials are added it quickly turns out that things don’t stop at a single fire update function, and different materials interact with each other in different ways, and the result of an interaction can depend on temperature, the amount of matter and its state.

In Terraria such interactions are directly part of the game mechanics, and when water meets lava obsidian appears, while other liquid combinations produce other materials. The player can perfectly well set up the corresponding processes on their own, without waiting for the level designer to place an obsidian-spawning trigger in the right spot.

In Noita there are far more such interactions, and their combinations make up a significant part of the gameplay, and changing one small patch of the world can set off a chain of events, each of which is the result of relatively simple local rules.

This kind of behavior is called “emergent gameplay”, although during development it’s rather hard to tell in advance which combinations of rules players will consider an interesting game mechanic and which will end up in the bug tracker, and sometimes you only find out after yet another bug video gets posted.

You don’t have to update the whole game world

In their talk on the technical side of Noita the developers described using 64×64-pixel chunks, each of which stores a dirty rectangle bounding the region of cells that need to be processed on the next tick.

The idea is that most parts of the game world settle into some stable state fairly quickly, and if a 64×64 chunk contains a small puddle of water taking up about 10×10 cells, there’s little point running physics calculations for the remaining four thousand cells, and if the water has stopped moving, after a while you can stop updating that chunk altogether.

struct DirtyRect {
    int min_x;
    int min_y;
    int max_x;
    int max_y;
};

struct Chunk {
    Cell cells[64 * 64];

    DirtyRect current_dirty;
    DirtyRect next_dirty;
};

When a cell’s state changes, it and its neighbors have to be marked as needing further updates, since a stationary cell can start moving because the state of a cell next to it has changed.

It’s also more convenient to keep the current and next dirty rectangles separately, otherwise the update region may start growing right in the middle of the traversal, and the number of cells processed per tick will once again depend on the direction in which the array is traversed, so sometimes it’s handier to split the chunk into small blocks and store a bitmask of active blocks.

Dynamic update rate

If you look at how different materials move, you’ll notice that far from all physical processes need to be updated at the same rate. For example, water in a still pool can stay practically unchanged for several seconds, or the temperature of a massive metal structure changes even more slowly, while actively moving liquids and gases need much more frequent updates.

So for many states you can use an octree to organize their update rates, so that when a parent node doesn’t need processing you can safely skip all its descendants without touching the memory they occupy at all.

On top of that, the physics algorithms now have to account for the actual time elapsed since the previous update, and to exchange matter between regions with different intervals you need to either update the boundary flows separately or accumulate the changes until the corresponding region gets processed.

In a simpler implementation you can assume that switching to the active state immediately wakes up all the necessary neighboring blocks, and use different update rates only for relatively stable regions, which somewhat shrinks the gain from the optimization but spares you a good share of the headaches with asynchronous exchange of matter.

Factorio and the physics nobody computes

Another interesting example of how cellular automata evolve is the gradual retreat from overly detailed physical simulation. In the original fluid system individual pipeline elements had their own state, and the fluid gradually moved between them.

As a result, pipe throughput depended on the length of the pipeline, its layout and even the order in which individual elements were built, which was explained by how the local algorithm itself worked, but that didn’t make life any easier for a player trying to keep several factories supplied.

The developers later decided to stop simulating fluid moving step by step through pipelines, merging connected pipes and tanks into segments within which the amount of fluid is a single shared state. If the previous model could be pictured conceptually roughly like this:

for (Pipe& pipe : pipes) {
    update_flow_between_neighbors(pipe);
}

then the new model largely boils down to working with one shared reservoir:

struct FluidSegment {
    float total_capacity;
    float current_volume;

    FluidType fluid;
};

And now fluid added to one part of a segment becomes available to the other devices connected to it without having to simulate its step-by-step movement through each pipe. Of course, inside the real engine everything is more complicated than this pseudocode, and pumps, segment size limits and network topology are taken into account, but the very idea of moving from a large number of locally interacting physical elements to one aggregated entity shows that you can give up exact simulation in favor of a fast one without hurting the game.

This works if the physics of fluid moving through pipes isn’t an important game mechanic in its own right, and in Factorio the player mostly cares whether a production building gets the required amount of fluid, not how that fluid travels through each of the two thousand pipes between the oil refinery and the consumer.

So instead of optimizing several thousand fluid movement operations, the developers effectively changed the model of the game world, and now a large share of those operations is simply no longer needed, while the behavior of pipelines has at the same time become easier for players to understand.

How much physics does a game even need

If you look at the various games that use models of physical processes, it’s easy to see that the choice of model is determined not so much by what the hardware can do as by the role the physical processes play and how much they affect gameplay.

GameRepresentation of the physical world
X-COM: UFO DefenseTile-based environment, fire, smoke, destructible elements
Dwarf FortressDiscrete liquid depth and extra pressure rules
MinecraftSource blocks and liquid spread levels
TerrariaPartially filled tiles and liquid interactions
Oxygen Not IncludedMaterial, mass, temperature and state of matter per cell
NoitaPer-pixel material simulation and destructible rigid bodies
FactorioAggregated fluid state in pipeline segments

What’s more, even within a single game you can use several completely different ways of modeling water at once, for example for an ocean the player can’t substantially change (an animated surface is enough), or for a river, where you may need a velocity field (it lets you carry floating objects along), separately for a flooding dungeon (this is where a cellular automaton comes in handy), and for a small tank an ordinary number will do just fine.

There’s no particular need to keep the physical model equally detailed across every part of the game world, and where the player can interact with substances directly it makes sense to use smaller cells, while for distant areas you can store an aggregated state of the matter or even compute how that state changed analytically when the player comes back.

The evolution of a cellular simulation from the original array with a one-byte material identifier into a system with sparse chunks, several state buffers, flow arrays, a task scheduler and its own integration with the physics engine shows that most of the code we’ve written isn’t busy simulating the physical processes themselves, but organizing the computations needed to make those processes simulatable at all within the time a frame has to spare.

And the most significant optimizations of such systems often lie not even in speeding up individual physics calculations, but simply in reducing the amount of physics that has to be computed. That’s games for you, there’s always a chance to fool the player somewhere...

More on the topic

All articles