← MAIN
09 // LAB // SOFT-BODY EVOLUTION

EVOLVING WALKERS

Soft creatures start out flailing. Each generation the ones that travel farthest breed and mutate. Nobody teaches them to walk.
— — — —

HOW TO USE

The goal is to watch walking evolve. Each creature is a soft body of nodes and springs, scored by how far its centre of mass travels to the right in 10 simulated seconds.

Let the run go, or press PAUSE to stop it and STEP to run one generation at a time. The FITNESS chart shows the champion's score rising as the population learns.

To test a design, build one in CREATURE LAB, press TEST, then DROP IN to add it to the population. MORE SETTINGS holds the population size, mutation, seed, gravity and friction.

LIVE
0.00 m 0.0 / 10 s
Pink muscles pull and cyan muscles push. Faint ghosts are earlier champions.
FITNESS
SPECIES
LINEAGE
HALL OF FAME
records appear here
0 / 0
Evolution log
RUN
TERRAIN
More settings
POPULATION
MUTATION RATE
SEED
GRAVITY
FRICTION
EVOLVED PRESETS
CHALLENGER
CREATURE LAB
SHARE (a creature as text)

HOW IT WORKS

A soft body is a creature made of nodes, point masses of 1 kg each, joined by springs. Some springs are muscles, whose natural length changes in a rhythm. Each creature is scored by its fitness, which is mainly the distance its centre of mass travels to the right in 10 simulated seconds. A genetic algorithm breeds each new generation from the best creatures: it keeps the fittest, combines pairs with crossover, and makes small random changes, called mutation. Nothing about walking is coded in. The gaits come from selection on the score.

The generation loop

A generation is one cycle over the population, 80 creatures by default. Each creature is simulated for 10 s at 240 steps per second and scored. The creatures are then grouped into species, groups of similar bodies, and the next population is bred from the species' shares of the slots. The first population is 80 random creatures. One cycle is Evolver.step: evaluate, speciate, summarise, then breed1.

23
function NEXT-GENERATION(population):
    for each creature m: SIMULATE and score m                # fitness, see FITNESS below
    SPECIATE(population)
    for each species s:                                       # fitness sharing
        share[s] ← mean over its members of (fitness − lowest + 1)
    for each species s:
        quota[s] ← its share of the P slots, rounded down, with leftovers to the largest parts
    next ← empty list
    for each species s with quota[s] > 0:
        survivors ← the top half of s by fitness
        add the best creature of s unchanged, if s is large or holds the best
        while next has fewer than quota[s] children from s:
            child ← crossover of two tournament winners, or a copy of one
            add MUTATE(child) to next
    return next

The simple version is the cycle: score, group, share the slots, and breed. The full version adds the species representatives, the largest-remainder quotas, the elite rule, and the injection of user creatures. The random draws happen in the same order as in the JavaScript, which is what keeps a seed reproducible in both4.

Genome and encoding

A genome is the creature's recipe: a list of nodes and a list of springs. A node has x and y in metres, relative to the body. A spring has two end indices a and b, a rest length (its natural length, in metres), a stiffness k in newtons per metre, a damping c, a muscle flag, and for a muscle an amplitude, a frequency in hertz and a phase in radians. Each gene is rounded to the 0.0001 grid5.

A genome is written as one line of text, w1|x,y;…|a,b,rest,k,c,muscle,amp,freq,phase;…, and the decoder reads it back to the same genome, in JavaScript and in Python67. That is how a creature is shared.

Bodies have 2 to 12 nodes and at most 40 springs. Random creatures have 3 to 7 nodes8. The repair step runs after every operator9. It clamps each value to its range, drops self-links, out-of-range springs and duplicates, and keeps at least one spring and one muscle. Then it connects the body: while some node cannot be reached from node 0, the lowest-index unreached node is linked to the nearest reached node, and the lowest index wins a tie. The result is always connected, has a muscle, and has no duplicate springs.

Fitness: distance, spin and speed

Fitness is measured from the spawn point. A body is spawned with its centre at x = 2 m and its lowest node 0.45 m above the ground10. Its spine is the pair of nodes farthest apart at spawn. The spin σ is the total turning of that spine, summed step by step, so a body that tumbles accumulates a large spin. Each step adds the magnitude of the 2D cross product of the old and new unit spine vectors, which is the sine of the small turn11.

\sigma = \sum_{k} \bigl|\, u_{k-1} \times u_k \,\bigr|, \qquad u \times w = u_x w_y - u_y w_x
1112

Here u_k is the unit vector along the spine after step k, and the cross product is in the plane. The sum is in radians, because the sine of a small turn is almost the turn itself. A body that spins less than one radian in total is not penalised.

F = \Delta x_c \;-\; 1.0\,\max(0,\ \sigma - 1) \;+\; \frac{0.5\ \mathrm{s}\,(x_{\mathrm{end}} - x_{\mathrm{mid}})}{5\ \mathrm{s}}
1314

Here \Delta x_c is the travel of the centre of mass in x, which is the mean node position, measured from the spawn point. The penalty is 1.0 m per radian of spin beyond the first radian. The speed bonus is 0.5 s times the mean forward speed over the second half: the centre of mass moves from x_{\mathrm{mid}} at 5 s to x_{\mathrm{end}} at 10 s. A body whose centre of mass drops below −1.5 m has fallen. Its travel and spin are then frozen where it fell, and it gets no speed bonus. A body whose state becomes NaN is scored 0 and marked exploded.

1314
function FITNESS(creature):
    if creature exploded:
        return 0
    travel ← x of the centre of mass at the end, minus x at spawn   # frozen at the fall
    penalty ← 1.0 · max(0, spin − 1)                                  # spin in radians
    bonus ← 0.5 s · mean forward speed of the second half, or 0 if it fell
    return travel − penalty + bonus

The simple version lists the three terms. The full version separates the fallen case from the standing case, because a fall freezes both the distance and the spin, and removes the bonus. A body that is on its feet keeps its bonus. The spin used in the penalty is the value at the fall for a fallen body, and the value at the end otherwise.

Example. The runner in the results travels 13.72 m in 10 s and scores 14.32, so its speed bonus minus its spin penalty is +0.60 m15.

Springs and muscles

Each spring applies Hooke's law along the line between its two nodes. The force grows in proportion to how far the spring is stretched past its rest length. A damper adds a force that depends on how fast the length changes, which removes energy. A muscle differs in one respect: its rest length is not constant. It swings around the rest length in a rhythm1617.

L = \lVert p_b - p_a \rVert, \qquad n = \frac{p_b - p_a}{L}, \qquad L_0(t) = \begin{cases} \mathrm{rest}\,\bigl(1 + \mathrm{amp}\,\sin(2\pi\,\mathrm{freq}\,t + \phi)\bigr) & \text{muscle} \\ \mathrm{rest} & \text{passive spring} \end{cases}
1618

Here p_a and p_b are the positions of the two end nodes, and L is the current length. In the code L is raised to at least 10^{-9} m before the direction is taken, so the division never divides by zero. The unit vector n points from node a to node b. L_0(t) is the rest length. For a muscle it swings by \pm\mathrm{amp} times the rest length, at \mathrm{freq} hertz, with phase \phi in radians. The code writes the angular speed as 2\pi\,\mathrm{freq}, and it evaluates the sine with the polynomial described at the end of this section.

f = k\,(L - L_0) + c\,\bigl((v_b - v_a)\cdot n\bigr), \qquad F_a \leftarrow F_a + f\,n, \qquad F_b \leftarrow F_b - f\,n
1920

Here k is the stiffness and c the damping. The damping term is the rate of change of the length, (v_b - v_a)\cdot n, so it is positive while the spring is stretching. The spring pulls node a towards b when f is positive, and node b towards a by the same amount. Forces are summed per node over all springs. The arena colours each muscle by its tension: pink when it is stretched past its current rest length, cyan when it is squeezed short of it21.

Each node has mass 1 kg. Gravity pulls every node down with g = 9.8 m/s² by default, and a linear drag of 0.1 per second slows every node's velocity22.

Integration

Time moves forward in fixed steps of \Delta t = 1/240 s. Each step computes all forces from the positions at its start. It then updates the velocities, then the positions, then the ground contact. This is semi-implicit Euler: the new velocity is used to move the position in the same step2324.

v \leftarrow \bigl(v + (F - g\,\hat{e}_y)\,\Delta t\bigr)\,(1 - c_d\,\Delta t), \qquad v \leftarrow \mathrm{clamp}_{\pm 30}(v), \qquad x \leftarrow x + v\,\Delta t
2425

Here F is the sum of the spring forces on the node, \hat{e}_y is the upward unit vector, and c_d = 0.1 per second is the drag. Gravity acts only in y. The drag factor is applied after the force and gravity. Each velocity component is then clamped to ±30 m/s. The clamp is counted, and it does not end a run by itself. The position moves with the clamped velocity.

The forces are summed in two passes: every a-end of every spring in spring order, then every b-end. The two languages use this same order, so their floating-point sums agree bit for bit. The sine inside the muscle is a polynomial in basic arithmetic, not a library call, for the same reason26.

Example. The check spring in the known limit below has stiffness 200 N/m and rest length 0.4 m, released 1.0 m long. Its stored energy is ½ · 200 · (1.0 − 0.4)² = 36 J, which the test reads as 35.8 J at its first step27.

Ground contact and friction

The ground is a height function h(x) over the terrain (see Terrains below). A node that ends a step below the surface is moved back onto it. Its velocity into the surface is then reversed with the restitution e, which is the bounce, or stopped. The restitution is 0.2 by default and applies only to impacts faster than 0.5 m/s. Slower impacts are inelastic, so resting feet do not jitter28.

s = -v_n, \qquad e = \begin{cases} e_r & s > 0.5\ \mathrm{m/s} \\ 0 & \text{otherwise} \end{cases}, \qquad v_n \leftarrow -e\,v_n, \qquad \lambda = (1 + e)\,s
v_t \leftarrow \begin{cases} 0 & |v_t| \le \mu_s\,\lambda \\ v_t - \mu_k\,\lambda\,\mathrm{sgn}(v_t) & \text{otherwise} \end{cases}, \qquad \mu_s = 1.2\,\mu_k
2930

Here v_n and v_t are the normal and tangential velocity components relative to the surface, and s is the speed into the surface. e_r is the restitution, and e is the restitution that is actually used, which is zero for a slow impact. \lambda is the limit on the tangential change. Coulomb friction caps the tangential force at the friction coefficient times the normal force, and the code applies that cap to the tangential speed. The kinetic coefficient \mu_k is the friction setting, 0.8 by default. The static coefficient \mu_s is 1.2 times it. A foot whose sideways speed is within \mu_s\lambda sticks. A faster foot slides and loses \mu_k\lambda of its sideways speed in that contact.

The whole step, as the code runs it, is:

3132
function SIMULATE-STEP(creature, t):                        # one step of 1/240 s
    for each spring s = (a, b):
        n ← unit vector from node a to node b
        L₀ ← rest length of s at time t                  # a muscle swings, a passive spring does not
        f ← k · (L − L₀) + c · (rate of change of L)
        push node a along n with f, and node b with −f
    for each node:
        v ← (v + (F − g in y) · Δt) · (1 − drag · Δt)
        x ← x + v · Δt
    for each node below the ground:
        put it back on the ground
        reflect or stop its normal speed, and apply friction to its sideways speed

The simple version is one step: spring forces, velocities, positions, then contact. The full version keeps the code's order, which is what makes the two languages agree: forces are summed in two passes, velocity clamps are counted, a non-finite state freezes the creature, and the centre of mass, spine and fall test are updated after contact. The bookkeeping is skipped for a creature that has already fallen.

Non-obvious. The ground check uses the positions after the velocity update. Contact changes only the velocity of a node that is moving into the ground, but it moves every node below the surface back onto it, even a node that is moving away.

Known limit: nodes pass through each other

Known limit: nodes pass through each other. There is no contact between nodes, so two nodes of one body can cross. A spring's force is k(L - L_0) along the line between its ends. When the ends cross, the length passes through zero and the direction n flips, so the force pushes the wrong way. Undamped, this adds energy. In the test with one spring (stiffness 200 N/m, rest length 0.4 m, released 1.0 m apart, with no gravity, no drag and no damping), the energy rose from 35.8 J to 59.6 J, a gain of 67%27. A spring whose length never comes near zero keeps its energy within about 5%. Drag damps the effect but does not prevent it. The physics has not been changed, because the evolved champions depend on it. A minimum-separation contact would fix it, and would need a new evolution run.

Selection and crossover

A parent is chosen by a tournament: three creatures are drawn at random, with replacement, from the survivors of the species, and the fittest wins. A tie keeps the earlier draw. The survivors are the top half of each species, rounded up and never fewer than one3334.

A child is made by crossover with probability 0.6, otherwise it is a copy of one tournament winner. Crossover needs at least two survivors. With fewer, the child is always a copy, and no random number is drawn for the crossover test35.

Crossover aligns the two parents by node index: node i of one parent is node i of the other. The dominant parent is the fitter one, and it sets the node count. A node that both parents have takes the other parent's position with probability 1/2, and otherwise the dominant parent's. A spring that both parents have, with the same pair of end nodes, takes the other parent's genes with probability 1/2. Springs that only the dominant parent has are kept. Springs that only the weaker parent has are dropped. This is the rule NEAT uses for disjoint genes. The child is then repaired.

Mutation

Each node is jittered with probability rate/2, where rate is the mutation setting, 0.5 by default. The jitter moves x and y each by up to ±0.06 m. Each spring is jittered with the same probability: its rest length by up to ±10%, its stiffness and damping by up to ±20%, its amplitude by ±0.05, its frequency by up to ±20%, and its phase by ±0.5 rad. Every value is then clamped to its range36.

Five structural operators then each fire on their own chance, scaled by the rate37. A new node is added with chance 0.15 × rate, up to 12 nodes. It is placed within ±0.3 m of a random node, linked to that node, and linked to its nearest other node. A node is removed with chance 0.10 × rate, down to 2 nodes. A spring is added with chance 0.20 × rate, up to 40 springs, by trying up to 12 random pairs. A spring is removed with chance 0.15 × rate, keeping at least one. A spring is toggled between muscle and passive with chance 0.20 × rate. Every child, including a copy, is mutated and then repaired.

Speciation and compatibility

Speciation keeps new body plans alive. A new shape usually scores below the old champions at first, so without protection it would die out before it could improve. Creatures are grouped into species, and each species is bred with its own share of the slots.

\delta(a, b) = 0.4\,\lvert n_a - n_b \rvert + 0.3\,\lvert s_a - s_b \rvert + \lvert m_a - m_b \rvert + (1 - J), \qquad J = \frac{\lvert E_a \cap E_b \rvert}{\lvert E_a \cup E_b \rvert}
3839

Here n is the node count, s the spring count, and m = \text{muscles} / \text{springs} the muscle fraction. E is the set of end-node pairs of a creature's springs, and J is its Jaccard similarity with another creature, the share of pairs they have in common. A pair is counted once. Two creatures with the same topology have J = 1 and distance 0. When both sets are empty, J is set to 138.

Creatures are assigned in population order. Each joins the first species whose representative is less than 1.2 away, and a creature that matches none founds a new species. Species with no members are dropped. After the grouping, each species draws one random member as its representative for the next generation40.

Fitness sharing and quotas

A species' share of the slots comes from its members' fitness. Fitness can be negative, so each value is first shifted by the population's lowest fitness and by 1, which makes every shifted value at least 1. A species' share is the mean shifted fitness of its members. Dividing the sum by the species size means a large species does not get more slots just for being large.

f'_i = f_i - \min_j f_j + 1, \qquad S_s = \frac{1}{\lvert s \rvert}\sum_{i \in s} f'_i, \qquad q_s = \Bigl\lfloor \frac{P\,S_s}{\sum_t S_t} \Bigr\rfloor
4142

Here f_i is the fitness of creature i, S_s the share of species s, and P the population size. Each species first gets the floor of its exact quota q_s. The slots left over are given one each to the species with the largest fractional parts, with earlier species first on ties. This is the largest-remainder method, and it makes the quotas sum to exactly P.

Within a species, the elite rule copies its best creature unchanged into the next population. The rule applies when the species has at least 5 members, or when it holds the best creature of the generation. Injected user creatures take the last slots of the next population, replacing children34.

Parameters and how they were chosen

ParameterWhat it doesDefault
populationCreatures per generation (UI: 40, 80, 120).80
durationSimulated seconds per creature.10 s
time stepFixed physics step (1/240 s).0.00417 s
mutation rateScales every mutation chance (UI slider).0.50
crossover rateShare of children made by crossover (the rest are copies).0.60
tournament sizeCandidates per parent pick, from the top half of a species.3
survivorsShare of each species that may be parents, rounded up.50%
elite thresholdSpecies of at least this size keep their best unchanged, and so does the species holding the best creature.5
species thresholdCompatibility distance below which creatures share a species.1.2
gravityAcceleration (UI: 2 to 20 m/s²).9.8
frictionKinetic coefficient (UI: 0.1 to 1.5); static is 1.2 times.0.80
restitutionBounce on impacts faster than 0.5 m/s.0.20
dragLinear drag on every node, per second.0.1 /s
velocity clampLargest velocity component allowed in a step, counted but not fatal.30 m/s
spring stiffness kRandom start range (N/m). Mutation keeps it within 20 to 600.60 to 250
spring damping cRandom start range. Mutation keeps it within 0.2 to 10.0.5 to 6
muscle amplitudeRandom start range for the rest-length swing (fraction of rest). Mutation keeps it within 0 to 0.4.0.10 to 0.35
muscle frequencyRandom start range (Hz). Mutation keeps it within 0.4 to 4 Hz.0.8 to 3.0
spin penaltyMetres lost per radian of spine rotation beyond 1 rad. Tumbling must cost more than it earns.1.00
speed bonusSeconds of mean forward speed in the second half added to the score (no bonus after a fall).0.5 s
fall lineCentre-of-mass height below which a body has fallen.−1.5 m

How these were chosen: The physics constants (step, drag, velocity clamp, restitution threshold, fall line) are standard for explicit simulation and were set by hand. None was tuned against the node-crossing limit. The genetic parameters (crossover 0.6, tournament 3, the top half as parents, elites of 5, threshold 1.2, the compatibility weights) follow the usual NEAT-style defaults and were set by hand. The mutation sizes and the speed bonus are judgement calls. The spin penalty began at 0.25 m per radian. A two-node body then tumbled sixteen turns for 99 m and scored 79, so the penalty went to 1.0043. The checks were the 300-generation runs below, and a friction sweep on the inchworm from 0.1 to 1.2, whose figures are quoted in the results file44. Gravity and friction are the UI's to change, and each change alters what evolves.

Terrains

Flat: a plain floor. Hills: a ramp-in from 3 m to 5 m, then two sine waves with 0.35 m and 0.12 m amplitude. Steps: 0.15 m risers every 1.2 m from 3 m, up to eight. Gaps: 0.9 m holes every 3.2 m from 4 m, where a body that falls through is scored where it fell. The start is always 2 m from the origin, on flat ground45.

Results: 300 generations, population 80

RunGen 100Gen 200Gen 300 bestChampion
seed 1, flat2.135.7414.32runner, generation 299: 13.7 m in 10 s, a one-hop skipper at 1.4 m/s
seed 2, flat1.677.1711.7010 nodes at generation 297: 12.9 m in 10 s, gait not characterised in the results
seed 3, flat2.204.8214.07inchworm, generation 300: 15.3 m in 10 s, centre of mass never above 0.31 m
seed 1, hills1.262.553.148 nodes, uneven ground: 3.8 m

Scores in metres, best of each run's population. The per-generation numbers are in the results file46, and the champion code of every generation is in the JSON47. Earlier runs (60 generations, spin penalty 0.25, no speed bonus) are kept in results/walkers_evolution_v1.md48.

Honest results: every flat run climbs from random flailing to bodies that cover 12 m or more in 10 s, with no explosions. The two best bodies are different body plans from different seeds: a 10-node skipper that gets off the ground once, and an 11-node low crawler that never leaves the ground by more than 0.31 m. Neither runs as a clean gait, and no champion hops three times, so there is no hopper preset. The best scores were still rising by about 3 m between generations 250 and 300, so these runs are not converged. The hills runs are much slower to learn. The full numbers and the study command are in the results file49.