nanoMMO

MMORPG footstep sounds made from code in C++

Footsteps for our C++ MMORPG, which the client makes from numbers with a small synthesizer of our own, for each kind of ground, timed to the frames where the walk puts each foot down.

Watch on YouTube

Our MMORPG gets its first sound effects, and the raylib client makes them from numbers as it starts, without a single sound file. We build a small synthesizer in C++: noise, a state variable filter, sine waves and envelopes. From those come footsteps for grass, sand, rock, snow, ash, stone and water, in takes that don't repeat back to back, timed to the frames where the walk puts each foot down, and heard by distance and side. A small tool of our own plays each sound outside the game. This is episode 55 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.

Topics: Sound

The code

Each step on screen is a tag in the game's repository. The code at the end of the episode is ep055/end.

  1. 2:27ep055/step-1A small synthesizerBrowseChanges
  2. 29:18ep055/step-2Every groundBrowseChanges
  3. 37:04ep055/step-3Steps in the gameBrowseChanges

Transcript

Intro

0:00 Hi, and welcome to episode fifty-five, where our game gets its first sound effects, starting with footsteps. The client makes each of them from numbers as it starts, without a single sound file. First, a quick look, and a listen, at what we'll have by the end.

0:16 By the end of the episode, each step makes a sound, from what's underfoot. The grass gives way to sand, which hisses, and in the shallows, each step splashes.

0:30 The project's website has more on the series. The code is open source, on GitHub, linked from there, and each episode gets its own page, with the code at each of its steps.

Last time

0:40 Last time, the fx got shards and spikes, solid gems lit like the rest of the world, for Earthsplitter and Frost Nova. Then came lightning that finds a new path each flicker, and a crescent of fire flying out from the player. Those went to Searing Arc and Stormcaller, along with an arc on the server, so a skill can hit a slice in front of us. All of it plays out in silence, apart from the music.

Today

1:05 Today, we're going to give the game its first sound effects, footsteps that change with the ground. Most other games ship their sound effects as files, recorded or bought, and we could do that too. Instead, I want to make them in code, which keeps the repo free of licensed files and lets each sound come out a little different each time. First, a small synthesizer: noise, a filter, sine waves and envelopes. From those come footsteps, a recipe for each kind of ground, from grass to water. Then we play them in the game, when the walk puts a foot down, from where the walker is. Right, let's start with what a sound is, to a computer.

Sound as numbers

1:43 To a sound card, a sound is a long list of numbers, each one where the speaker's cone should be at that moment, from minus one, pulled all the way in, to one, pushed all the way out. We give it forty-four thousand one hundred of them each second, the rate CDs use, which carries frequencies up to about twenty-two kilohertz, past what we can hear. This is the first hundred and fifty milliseconds of a step on grass, as our client makes it. The heel comes down first, with a burst of low noise that dies away, and the rest of the foot follows a few dozen milliseconds later. Played through the speaker, those numbers sound like this. None of it was recorded: each number comes from noise, run through a filter and shaped by an envelope, so let's write those.

A small synthesizer

2:28 Our synthesizer gets a file of its own, synth, and we start with its header file. It needs cstdint, for the thirty-two-bit number our random numbers grow from, and vector, to hold a sound. The rate is the forty-four thousand one hundred samples a second we just saw, as a constexpr, a constant the compiler knows as it builds. Over it goes what a sound is, to us: where the speaker's cone is, from minus one to one, this many times a second. Samples is a using alias, a second name for a vector of floats, so that a sound reads as a sound wherever we pass one around. A float holds the numbers between minus one and one finely enough, at half the size of a double. It's one channel of sound, at that rate, as the game places each sound to the left or the right when it plays it. Our footsteps start from noise, so that's the first class we write. It makes random numbers, which a seed decides, so that a sound made again from its seed comes out as it did before. The game is going to make a few takes of each step as it starts, each from a seed of its own. So when a take sounds wrong, we can make that take again from its seed, and listen to it while we change the recipe. The standard library has random engines too, but its distributions can give different numbers from one compiler to the next, so we write a few lines of our own. The constructor takes the seed, and it's explicit, so a plain number can't turn into noise by accident. Uniform gives a number from zero to one, each as likely as any other, and between gives one from low to high, such as a frequency for a take. And next gives a sample of noise, a number from minus one to one: white noise, a sample at a time. The class defines it right there, as it's a single call. White noise has all frequencies in it, evenly, which we hear as a hiss, like a radio between stations, and our sounds are carved out of it. The noise keeps its state in a thirty-two-bit unsigned number, and moves it on with each number it gives. A filter does the carving: it keeps some frequencies of a sound and turns the others down. A low pass keeps what's below its frequency, like a thud heard through a wall, and a high pass keeps what's above it. A band pass keeps a band around it, which gives noise a pitch, of sorts. This one passes what's below a frequency, around it, or above it, all three at once, from two running sums of what came through. A running sum moves slowly, so it follows a sound's slow swings and smooths over the fast ones, which is how the filter pulls the low apart from the high. The frequency can change from one sample to the next, so that a sound can sweep. Out holds the three, low, band and high, for each sample that goes through. Run takes a sample in, the frequency in hertz, and a q, which is zero point seven unless we pass another. One sample through, and the higher the q, the narrower the band, and the longer it rings. Q says how sharp the filter is around its frequency. At about zero point seven, a low pass is as flat as it gets, without a bump at its frequency. With a higher q, the filter resonates, like a wine glass, so a click through it rings on at that frequency, which is going to give us grit and crackle. Its two running sums start at zero, which is silence. Then the envelope, the shape of a sound's loudness over time. A step comes up in a few milliseconds and dies away in a tenth of a second or so, while a bell dies away over seconds. The envelope is how loud a sound is, t seconds in: up from nothing over the attack, then down by about two thirds each decay seconds. Losing a share of what's left each moment is how a struck thing loses its energy, so a decay like this sounds like one. We think in seconds, and the vectors count samples, so samples in gives us the seconds, as a count of samples. Mix is how a sound gets built out of layers. When two sounds play at once, the air carries both pressures, added up, so mixing them is adding their samples, one by one. The mix comes in by reference, as we change it in place, and the gain multiplies the layer, at one unless we pass another. It adds the sound into the mix, starting at that time and at that gain, making the mix longer, if it needs to be. So the rest of the foot can go in a few dozen milliseconds after the heel, and run on past the end of the heel. Adding layers can push the sum past one, which the sound card can't play, so the top of the wave gets cut flat, and we hear that as a harsh distortion, called clipping. So peak finds the loudest sample, whichever way it goes, as minus zero point nine is as loud as zero point nine. And normalize scales a whole sound, louder or quieter, so that the loudest sample is at the peak we give it. That keeps a sound clear of clipping, however many layers went into it, and lets us set its level with a single number. Last, fade out is for the end of a sound. If one stops while its wave is away from zero, the cone jumps back to the middle in a single sample, and that jump is a click. So this brings the last few milliseconds down to nothing, as a sound cut off mid-wave clicks. The start of a sound doesn't need a fade of its own, as the envelope's attack rises from nothing.

7:45 In the synth, we include its own header file first. Then algorithm, for clamp, min and max, and cmath, for the tangent, the exponential and rounding. And cstddef, for size t, the standard's type for sizes and indices, and numbers, for pi. The noise starts its state from the seed, plus the golden ratio, written as thirty-two bits. The takes' seeds are going to be one, two, three and so on, and a generator like ours, started from neighbours, gives first numbers less than a thousandth apart. So the constructor mixes the seed up before the first number. Above it, we write why: seeds next to each other start far apart, as MurmurHash3's last steps mix each bit of the seed into the others. MurmurHash3 is Austin Appleby's hash, and its last steps are a mixer much like the one at the end of the fx's random numbers. A round folds the state's top half down onto its bottom half, with an exclusive or, and multiplies it by a large odd constant, which carries each low bit up into the bits above it. The second round shifts by thirteen and multiplies by another constant, and a last fold finishes it off. By then, each bit of the seed flips about half the bits of the state, so seeds next to each other start unrelated. A fold and a multiply by an odd number can both be undone, so two different seeds can't land on one state. The mixing turns a zero into a zero, which is why the golden ratio goes in first, so a seed of zero doesn't give a state of zero. The u on each number makes it unsigned, and unsigned maths wraps round past about four billion, which C++ defines, where a signed overflow is undefined. For each number, uniform multiplies the state by one constant and adds another, and lets it wrap round at thirty-two bits. The constants are the ones from Numerical Recipes, and with them the state goes through all four billion or so values before it comes back round. This is a linear congruential generator, whose top bits are the random ones. Its low bits repeat quickly, and the lowest one goes odd, even, odd, even. So we shift the state down by eight bits, which keeps the top twenty-four, as many as a float holds without rounding. Dividing by two to the twenty-four gives a number from zero up to just under one. Between stretches that over a range, from low, by the width of the range times a uniform number. Played as samples, one after another, a second of these numbers is white noise. Then run, which puts a sample through the filter, and that's the brainy stuff of this file. It's a state variable filter, as Andrew Simper solved it for a sample at a time: it stays steady however fast the frequency moves. A state variable filter comes from analogue synthesizers, as a circuit built round two integrators, which are our two running sums: each adds up what comes into it. Simper makes audio plug-ins at Cytomic, and he solved the circuit's equations so that each sample costs a tangent, three divisions and about a dozen multiplies, and a sweep can't make it blow up. First, we clamp the frequency between twenty hertz, about the lowest we hear, and forty-five hundredths of the rate, just under twenty kilohertz. That's up to just under half the rate, the highest it can carry. A wave needs a sample on its way up and one on its way down, at the very least, so half the rate is the highest frequency the samples can hold. G sets how far the running sums move in a sample, and it comes from the frequency, with pi as a float from numbers. Turning a circuit into steps squeezes the frequencies near the top together, so the tangent stretches them back out, and the filter's frequency lands where we asked. That's called pre-warping, and the tangent shoots off to infinity at half the rate, which the clamp keeps us clear of. K is one over q, the damping, so a high q damps the filter less, and the band rings on. Three multipliers come from g and k, and we work them out for each sample, as the frequency can change between samples. Then we take the input, less the second sum, which follows the low part of the sound. The band comes from the first sum and that difference, and the low from the second sum, plus a share of the first sum and the difference. Then each sum moves on, to twice its new output, less what it held. That's the trapezoid rule, which adds up each step as the average of its start and its end, and it's why the filter stays steady. The high pass is what's left: the input, less the damped band, and less the low. And we hand the three back by name, with designated initialisers. Here's our noise through it at a thousand hertz, the low, the band and the high, one after the other. The envelope is silent before its sound starts. Over the attack, it rises in a straight line, which is fine for a few milliseconds, as that's too short to hear much of its shape. After it, the envelope is e to the power of minus the time since the attack, divided by the decay. E to the minus one is about zero point three seven, so with each decay seconds, a sound keeps about a third of its loudness, and loses two thirds. With an attack of two milliseconds and a decay of fifty, a burst of noise becomes a tap. Samples in rounds to the nearest sample, and a negative time counts as none. A float times forty-four thousand one hundred can land a hair under a whole number, and cutting it off would lose a sample. Mix finds the sample where the sound starts. If the mix ends before the sound would, resize makes it longer, with zeros, which are silence. Then each sample of the sound, times the gain, adds onto the mix's sample at that point. Peak goes through the samples, keeping the biggest, and abs makes a sample below zero count as much as one above it. Normalize starts by finding the loudest sample, with peak. If that's zero, the sound is silence, and there's nothing to scale, nor anything to divide by. Otherwise, each sample is multiplied by the peak we want over the peak it has, so the loudest lands on it, and the rest keep their shape. The loop takes each sample by reference, so the change lands in the vector. Fade out works on the last ten milliseconds, four hundred and forty-one samples, or the whole sound, if it's shorter. We tell min to compare the two as size t, in angle brackets, since samples in gives an int. Sample number i, counting back from the end, is scaled by i over the fade's length. So the last sample is zero, and they rise in a straight line to full, ten milliseconds back. That's short enough that we don't hear a fade, and long enough that the jump at the end is gone.

A step on grass

14:24 Footsteps get a file of their own, foley, and we start with its header file. Foley is the film sound craft of performing footsteps and other everyday sounds to the picture, named after Jack Foley, who did it for Universal's early sound films. It needs array, for a list of the grounds, cstdint, for the seed, and our synth's header, for samples. Ground is an enum class, with a single kind for now, grass, and the others join it in the next step. A ground is what a foot comes down on, which decides how the step sounds. K grounds lists them all, in a constexpr array, so that code which wants each ground in turn, like the tool we're about to write, can loop over it. Then step makes the samples of a step on a ground, from a seed. One footstep is the heel, then the rest of the foot, and each seed makes one a little different from the others. So the game can have as many takes of a step as it likes, a seed each, and none of them is a file to record or load. In foley, we include cstddef, for size t, which counts the samples. The step's peak is zero point six, how loud the loudest moment of a step is, whatever it's on. Zero point six leaves some room under one, as the steps of a few walkers add up when they play over each other. Seconds turns a sample's index into the time it plays at, as our envelopes take seconds. Pass picks which of the filter's three outputs a layer uses: below its frequency, around it, or above it. Take hands that output back, and it gives us the band at one loudness, whatever its q. In this filter, the band comes out q times as loud as what goes in, at its middle frequency. So a narrow band, at a high q, would be louder than a wide one, and dividing it by q brings it back down, so we can make a layer narrower without it getting louder. The low and the high pass come back as they are. Hiss is the layer most of our sounds are built from. It takes the noise by reference, so each layer carries on with the step's stream of random numbers, and one seed decides the whole step. Then come how long it lasts, the filter's frequency and q, which output we take, and the envelope's attack and decay. It makes room for that many seconds of samples, and a filter of its own, which starts from silence. For each sample, a new random number goes through the filter, and we take the output we picked, times the envelope at that moment. White noise holds all frequencies at once, so the filter decides what we hear: low passed at a few hundred hertz, it's a dull thump, and a band in the thousands is a swish. The envelope's tail gets close to zero without reaching it, so we fade the end out. So hiss is noise through a filter, rising over the attack and dying away over the decay. Crackle makes clicks, from the step's noise, like hiss. It takes how many clicks a second come at the top of the envelope, the frequency they ring at, a q, and the envelope's attack and decay. It makes room for its samples, and a filter of its own, as hiss does. For each sample, the chance of a click is that many a second, shared out over the forty-four thousand one hundred samples of a second, and scaled by the envelope. When a uniform random number falls under that chance, we get a click: a single sample, at a random height, with silence around it. Then each click goes through the filter's band. A single sample, on its own, holds all frequencies, like the noise does, so the band keeps those around its middle, and the filter's running sums swing on at that frequency for a while after the click has gone. That's the ringing we met with the filter's q, like a struck wine glass. An impulse through a narrow band rings quietly, though, so it starts loud, four times over. The end of the crackle fades out, like the hiss's did. Crackle is clicks at random times, about that many a second while the envelope's at its top, and fewer as it dies away, each ringing around its frequency. That makes grit, crunch and crackle, depending on how many there are and how high they ring. At three hundred a second, ringing around two and a half kilohertz, the clicks make this crackle. Now step, which puts the layers together for each ground. Its noise starts from the seed, and all the random numbers in the step come from it, in order, so a seed gives back its take, sample for sample. We pick a random time for the toe, forty to seventy milliseconds in, as the rest of the foot comes down a moment after the heel. The step starts out empty, and each layer we mix in makes it as long as it needs to be. A switch on the ground picks its recipe, and so far there's grass. The heel is a hiss of a hundred and fifty milliseconds, low passed somewhere between two hundred and fifty and four hundred hertz, which leaves a soft, dull thud. It rises in two milliseconds, dies away with a decay of thirty milliseconds, and goes in at the start, at full gain. That's grass: a soft thud, the blades brushing past, and a few snapping. The blades are a band of noise higher up, between two and three and a half kilohertz. It comes in more slowly, over fifteen milliseconds, lasts a little longer, and goes in at a fifth of the gain, as a brush in the background. The snapping is a crackle of about three hundred clicks a second at its top, ringing between two and three kilohertz. Over its short envelope, that comes to a dozen or so clicks, as blades snap under the heel. And the rest of the foot is another thud, a little higher and shorter than the heel's, three to five hundred hertz, mixed in at the toe's time, at sixty percent. Each layer takes its frequency from the seed, within its range, so one take's heel can be a little deeper than the next one's. Last, we normalise the mix to the step's peak. Four layers of noise add up to a different loudness in each take, so this brings each one's loudest sample to zero point six, and no step jumps out louder than the rest. So here's grass, from seeds one, two and three.

20:28 To hear a step, raylib has to play our samples, so the audio header file gets a class for that. It needs cstddef, for size t, vector, for a list of voices, and our synth's header, for samples. We call it a clip: a sound we made, ready to play, on a few voices that share its samples, so that it can play again before it's over, as steps do. A raylib sound plays one copy at a time, and playing it again starts that copy over from the beginning. A step lasts about a fifth of a second, and the steps of a few walkers can come closer together than that, so a single sound would cut each step off with the next. Load makes a clip from our samples, with a number of voices. Like the track, it takes the audio device without using it, as raylib can't load a sound before the device is open, and that way the compiler checks the order for us. It hands back a plain clip, without a status, as samples already in memory have no file that could be missing. The destructor unloads it, and like the track, a clip can't be copied. Play takes three numbers, which the game is going to set for each step it plays. It plays on the voice that started longest ago: at a volume from zero to one, a pan from minus one for the left to one for the right, and a pitch, where two is an octave up. Pan shares the sound out between the two speakers, which is how we'll hear a walker on our left from the left. An octave up is twice the frequency, and raylib gets there by playing the samples twice as fast, so the sound is half as long too. The constructor is private and explicit, so clips come from load, and it keeps raylib's sound. Next to the sound go the voices: raylib's aliases of the sound, which play its samples without copies. An alias has a position, a volume, a pan and a pitch of its own, and reads its samples from the sound it was made from. Next is the voice that plays next, starting from the first. In audio, load describes our samples to raylib. raylib takes sound in memory as a wave, a struct we fill in with designated initialisers, naming each field as we set it. A frame is one sample for each channel, so with a single channel, the frame count is how many samples we have. The sample rate is ours, and a sample size of thirty-two bits tells raylib that each sample is a float. There's one channel, as our sounds are mono, and the pan places them when they play. The data points at the floats in our vector, where the samples are. The wave's pointer isn't const, as raylib uses that struct for waves it owns too, so const cast takes our const off, and raylib reads the samples without writing to them. raylib copies the samples into its own format as it loads them, so once the clip's loaded, our vector can go. Load sound from wave does that copy, and makes a raylib sound. The constructor is private, so we make the clip with new and hand it to a unique pointer with Abseil's wrap unique, like we did for the track. Then, for each voice, load sound alias makes an alias of the sound. The destructor unloads the aliases first, and the sound after them. The sound owns the samples the aliases read, so unloading it first would leave them reading freed memory. Play does nothing for a clip without voices. Otherwise it takes the next voice, and moves next on by one, back to the first after the last. That's round robin, so the voice we take is the one that started longest ago, and the most likely to have finished. It sets the voice's volume, its pan and its pitch, and plays it. raylib mixes its sounds with miniaudio, on an audio thread of its own, so play returns straight away, and the mixing happens there. To listen to our sounds outside the game, we're going to write a small program next to the client, nanommo sounds. Designing a sound is a loop of changing a number and listening again, many times over. In the game, each change would mean building the client, logging in and walking over to some grass, while this tool plays a new take as soon as we press Space. It's built on raylib, for the window, the keys and the drawing. It holds each sound the game makes, to listen to one at a time, outside the game: up and down pick one, and Space plays a new take of it and draws it. From the standard library, we need algorithm, for min and max, array, and cstddef and cstdint. Then functional, for std function, iostream, to print errors, memory, string and vector. From Abseil, it's status or and str cat, and from the client, audio, foley, the synth and the window. An entry is a sound in the list, with a name, and make, a std function. A std function holds anything we can call with a seed that returns samples, such as a lambda that keeps the ground it steps on. It makes a take of the sound, from its seed. K ground names gives each ground a name for the list, in the enum's order. Entries builds the list, with an entry for each ground. For each ground, the name is step on, then the ground's name, and make is a lambda that captures the ground by value, and calls step with it and the seed it's given. Draw wave takes the samples, a box on the screen to draw them in, and a colour. What it draws is the sound's shape: the highest and lowest sample under each column. A fifth of a second is close to nine thousand samples, and the box is six hundred pixels wide, so each column covers about fifteen of them. A single sample per column would skip the peaks in between, so we draw a line from the lowest to the highest, as audio editors do. It draws the box's outline in grey, and a line across its middle, for silence. Until we've made a take, there are no samples, and that's all it draws. There's a column for each pixel across the box. Each gets its share of the samples, from one index to another, with at least one, for a sound shorter than the box is wide. Low and high start in the middle, at zero, and stretch to the lowest and the highest sample in the column. Then a line goes from one to the other. A sample of one reaches the top of the box, and minus one the bottom, as the screen's y grows downwards. Main opens a window, nine hundred and sixty by five hundred and forty, with our window class, and the tool's name as its title. If it can't, it prints the error, with the tool's name in front, and returns one. Then it opens the audio device, like the client does. Without one, say in a container that has no sound card, it prints why and carries on, so we can still look at the waves. Then come the entries, the one that's picked, the last seed, the samples on show, and the clip that's playing. Each frame, until the window closes, down picks the next sound, round to the top after the last, and up the one before it. Adding the list's size before taking one away keeps the number from going below zero, as in C++, the remainder of a negative number is negative too. Space makes a new take, so each press is a take of its own. It moves the seed on by one, makes the picked sound from it, and keeps the samples to draw. With a device, it loads them as a clip with a single voice, as a new take replaces the one before. The two stars take the device out of the status or, then out of its unique pointer. Putting the new clip in the unique pointer unloads the old one. Then it plays the take at full volume, in the middle, and at its own pitch. Then we draw, on a background that's nearly black. The list of sounds goes down the left side of the window. Each entry's row is twenty-two pixels below the one before, and here says whether it's the one picked. That one gets a red bar behind it, and its name in white, while the others are light grey. The wave goes on the right, in orange, with the sound's name and its take above it, and its length below, which is the count of samples over the rate, in seconds. End drawing puts the frame on the screen. And once the window closes, main returns, and the clip, the device and the window go in the reverse order they were made, so the clip is unloaded before the device closes. In the CMake file, the client's library gets two more sources, the synth and foley, so the game and the tool can both use them. Then nanommo sounds is an executable of its own, from sounds main, which links the client's library. Like the client and its bench, it depends on the client's assets, so building it copies them next to it.

28:50 Let's build it, and listen to what it makes. The window lists the one sound we have so far, and Space plays a new take of it. The first step on grass plays, and the tool draws its shape on the right. Each press is a new seed, so the noise is new, along with each layer's pitch and when the rest of the foot comes down, and each take comes out a little different from the last.

Every ground

29:19 Before the six new grounds, the synth gets one more piece, an oscillator, which makes the purest tone there is, a single frequency with nothing else in it. It's a sine wave whose frequency can glide without a click, as it keeps where it is in its turn. Next gives the wave's next sample, at the frequency we ask for, which can change from one sample to the next. Where the wave is in its cycle is called its phase, and we keep it in turns, from zero at the start of a cycle to one, all the way round. We could work each sample out from the time instead, as the sine of the frequency times the time. But then a change of frequency would jump the wave to another point in its cycle, and a sudden jump of the speaker's cone is a click. In the synth, then, next takes the sine of the phase times two pi, as a full turn is two pi radians. Then it moves the phase on by the frequency over the rate, which is how much of a turn the wave makes in one sample. At four hundred and forty hertz, that's about a hundredth of a turn, so when the frequency changes, the wave carries on from where it was, a little faster or slower. Floor takes the whole turns off, so the phase stays between zero and one, where a float keeps its precision. A phase that kept counting up would, after a few seconds, have too few bits left for steps that small, and the pitch would wander. At four hundred and forty hertz, the oscillator sounds like this. In foley's header file, the ground gets six more kinds next to grass: sand, rock, snow, ash, stone and water. And the list of all the grounds grows to seven, in that order, which is the order the tool shows them in. In foley, we include cmath, the standard library's maths, for a power we need further down. Three helpers come first, starting with click, the snap at the very start of a hit: a few milliseconds of noise, high up. It's a hiss of thirty milliseconds, through a band around the frequency we give it, which rises in half a millisecond and is all but gone after a dozen. How fast a sound starts is much of how we tell how hard the thing that made it is, and a hit on something hard is there at once. Tone is a note with an envelope, for the water's bubbles further down. It's a sine that glides from one frequency to the other over its length, by the one ratio each moment, as we hear pitch. Our ears hear pitch by ratios, so going from two hundred and twenty hertz to four hundred and forty sounds as big a step as from four hundred and forty to eight hundred and eighty. Each of those doubles the frequency, which is an octave. So for each sample, we ask the oscillator for the starting frequency, times the ratio between the two ends, to the power of how far through the tone we are. A glide in a straight line of hertz would rush through the low notes and crawl through the high ones. Then the envelope shapes it, as it does the hiss, and the end fades out. Echo mixes a copy of a sound back into it, later on. That's the sound again, quieter and duller, as it comes back off walls. Walls soak up the high frequencies more than the low ones, so what comes back has lost its top. So the copy goes through a low pass at fifteen hundred hertz, and goes back in after the delay we ask for, at the gain we give it. Now the grounds' recipes, in the step's switch, starting with sand. Its thud goes through a low pass at a hundred and fifty to two hundred and fifty hertz, lower than the grass's, and takes four milliseconds to rise, twice as long. Sand gives under the foot, with a hiss of fine grains. Those grains are a crackle of three thousand clicks a second, up at three to four and a half kilohertz, through a wide band. So many of them blur together into a fine hiss, the way thousands of grains rubbing past each other sound. The rest of the foot adds two thousand more a second, a little quieter, and here are two takes of sand. Snow's thud is lower still, at a hundred and twenty to a hundred and eighty hertz, and a little softer. Snow crunches, as the flakes are pressed together. The crunch is a crackle of fifteen hundred clicks a second, ringing lower than the sand's, with a narrower band, so each one rings a little longer. It takes twenty milliseconds to build, and lasts longer, as the foot presses the snow down, and this is how it crunches. The Ashlands' ash has a thud too, at about the sand's pitch, a little quicker to rise and slower to die away. Ash is cinders, which break with a dry crack. That crack comes from a mere six hundred clicks a second, through a narrow band, with a q of four. So each click rings for a moment at its pitch, around three kilohertz, and we hear separate, brittle cracks, without the wash of the sand's grains. The rest of the foot cracks a few more, a little higher, and the Ashlands' steps come out dry and brittle. Rock is hard, so it starts with a click, at four and a half kilohertz. With it comes a hard knock, and grit rolling off. The knock is a band of noise near a kilohertz, which rises in a millisecond and dies in fifteen. With a q of three, the band is narrow enough to sound almost like a note, which is what a solid thing being hit sounds like. The grit is a few hundred clicks a second, ringing narrowly, from ten milliseconds after the knock. And the rest of the foot knocks again, a little higher and quieter, so on rock, we hear the knock, and then the grit. The stone of the Crypt gets a click as well, a little lower, and a knock that rings, and comes back off the walls. Its knock is lower than the rock's, at six to eight hundred hertz, and with a q of eight, the band is narrow enough to ring, like a slab of stone. The rest of the foot rings again, a little higher, and dies a little sooner. Then come two echoes, sixty and a hundred and thirty milliseconds later. Sound covers about three hundred and forty metres a second, so the first is a wall about ten metres away, there and back. The second echo copies the step with the first echo in it, so the first one comes back again, quieter and duller still, and the Crypt's stone rings back off its walls. Water starts with a splash, a wide band of noise around one and a half kilohertz, which lasts a while. After it come bubbles, each a note that rises as it closes. Under the splash, there's a slosh, below four hundred hertz, which takes twenty milliseconds to rise, as the water takes a moment to get moving. There are three to six bubbles, and the loop declares the count next to the bubble's number, so it's picked once, and lives no longer than the loop. A bubble of air in water rings at a note set by its size, the smaller the higher. As it closes up, the note rises, and a quick rising tone is a well-known trick for a bubble in sound design. So each bubble is a tone of eighty milliseconds, starting from five hundred to thirteen hundred hertz, and rising by a ratio of one point six, at a random moment in the first fifth of a second. Together with the slosh, they make the sea's splash. In the tool, the ground names get the six new ones, in the enum's order, as the list looks a ground's name up by its number.

Steps in the game

36:26 To play a step in the game, we need to know when a foot comes down. We could play one each time a walker covers so many metres, but then the sound drifts away from the feet on screen. Instead, we take those moments from the walk's animation, which moves the feet we see. Our characters walk with a clip from Mixamo, which raylib turns into a pose of the bones sixty times a second, and this is the height of each foot's bone over one loop of it. The left foot comes down a little over a quarter of the way through, and the right a little over three quarters. So, when a character loads, we find those moments in each walk and run, and while one walks, we play a step each time its clip passes one of them.

37:05 To play the right step, we need to know what's underfoot, and the ground's header file decides that already, but as the ground's colour. So we give the surface a name of its own, apart from its colour. Surface is an enum of four, for what the ground is at the height, where the y of the ground's normal is up. That's sand by the sea, snow up high, rock where it's high or steep, and grass elsewhere. Surface at picks one, from the height and how upright the ground is, and ground colour stays, as the surface's colour in the look. In ground, the colour's function becomes surface at, and keeps its checks, returning a surface where it returned a colour. Lower than sixty centimetres above the sea, it's sand, and above nineteen metres, snow. Above the tree line, at twelve metres, or where the y of the normal drops under zero point eight, about thirty-seven degrees of slope, it's rock, and grass elsewhere. Then ground colour, below it, asks surface at, and switches on its answer, with a case for each surface that gives the look's colour for it. After the switch, it gives grass, for a value the enum doesn't name. That way, the colour we see and the step we hear come from one decision, so a slope drawn as rock doesn't sound like grass. In foley's header file, we include the lands' header, for the list of our lands, and the terrain's header, for the heights we need further down. Each land looks its own way, and it should sound its own way too. A land sound is how a land sounds: what each of its surfaces is underfoot, with a ground for each of the four. Then there's one for each of our three lands. The double braces are the array's, around the plain C array inside it, and each land names its fields, so which ground goes with which surface is plain to see. The Meadows, first, sound the way they're drawn. The Ashlands' sand, grass and snow are all ash, while their rock stays rock. And the Crypt's floor is stone, whatever colour it's drawn in. They have to go in the order of the lands, which the compiler can't check for us, so we write that over them. A static assert checks, as it compiles, that there's a land sound for each land, like the looks' check in the atmosphere's header. So a fourth land doesn't build without its sound, where it would otherwise read past the end of this array. Ground at tells us what's underfoot at a point in a land: the water we wade in, or the land's surface. In foley, we include the ground's header, for surface at. Ground at starts from the terrain's height there. Below sea level, a player is wading, as the Meadows let them walk into the sea up to their knees, so it's water. Above it, the surface needs to know how steep the ground is, from the height half a metre either way. Across that metre, dx is how far the ground climbs along x, and dz how far it climbs along z. Up is the y of the slope's normal, the arrow standing straight out of it. That arrow leans back by dx and dz for the metre it goes up, so its y, made a unit long, is that metre over its length. On flat ground, it's one, and the steeper the slope, the smaller it gets, which is what the colour's check reads. Then we look up the land's sound, by the land's number, and the surface at our feet picks which of its grounds we hear. That's the land's sand for sand, its grass for grass, its rock for rock, and its snow for snow. And after the switch, it's grass again, as in the colour's function.

40:33 When a step plays, and how it's heard, goes in a file of its own, the soundscape. Its header file includes raylib, for its vectors and its animation clips, then array, cstdint, map and vector from the standard library. The animator's header gives us the figures, and the synth's header the noise. This file decides when the game's sounds play, and how, kept apart from raylib's audio. Like the jukebox, it's plain logic, which works out what to play without a sound card, while the playing happens elsewhere. Heard is how a sound is heard: how loud, from zero to one, and from which side, from minus one for the left to one for the right. By default, that's full volume, in the middle, and raylib's pan runs from minus one to one too, so ours can go straight to it. Near is four metres, and both of these are in metres: full volume this near, and nothing past far, which is forty metres away. Hear takes a sound at the source, heard by the player, at the ears, with the camera's right to their right. We hear from where the player stands, but we look through the camera, so a step on the left of the screen should come from the left. Past near, it falls as one over the distance, and it fades out to nothing at far. Variety is which take of a sound plays next, and how, so that a sound heard again and again doesn't sound like a machine. So it's not the take that played last, a little higher or lower, and at most a little quieter. Our ears soon pick out one recording played over and over, which game audio calls the machine-gun effect. A take says which of the takes to play, and at what pitch, as a ratio of frequencies, where one is as it was made, and two an octave up. raylib raises a sound's pitch by playing it faster, so a higher take is a little shorter too. And its volume says how loud that take plays. A variety starts from a seed, for its noise, and two spreads, one for the pitch and one for the volume. The pitch can be off by its spread either way, and the volume can go down by up to its spread. Next gives the take to play, out of that many takes. It keeps the noise and the spreads, and the last take it gave, which is minus one before the first. A gait is where a figure is in its walk or run: how many times its clip has looped, and how far into a loop each foot comes down, from zero to one. Loops counts up as the clip plays, so one and a half is halfway through its second time round. And the footfalls are one for each foot, at the start and halfway, until we know better. Footfalls finds them for a clip, from the bones of the left foot and the right. It's how far into the clip each foot comes down, from zero to one: where each foot's bone, left and right, drops to near its lowest. A clip without those bones steps at its start and halfway. Who gives a figure a number to know it by from one frame to the next. It says which figure is which, as players, monsters and NPCs each count their ids from one. And footsteps tells us which figures put a foot down, from how far each has got through its walk or run since the last update. Update is called each frame, with a map of gaits, keyed by who. It returns those figures, by who they are, from each walking or running figure's gait. A figure that's left out has stopped, and starts afresh. To know what's changed, it keeps each figure's loops from the last update, in a map by who. In soundscape, we include raymath, raylib's maths, for the vectors' lengths and dot products. From the standard library come algorithm for min and max, cmath for floor, cstddef for size t, map, utility for move, and vector. The widest pan is zero point eight, as even far to one side, a little reaches the other ear. Our head shades the far ear, but some of the sound gets round it, and a step in one speaker and silence in the other sounds odd, in headphones especially. In hear, away is the way from our ears to the sound, along the ground, leaving out the height, and its length is how far away it is. At forty metres or more, the volume is nothing, and so is the pan. Otherwise, the volume is four over the distance, past four metres, and nearer than that it's capped at one, as a step at our feet would otherwise blow up. That's multiplied by a fade, which stays at one up to four metres, and then goes down in a straight line to nothing at forty. So within four metres, a step plays at full volume. Sound spreads out as it goes, so past near, it falls as one over the distance, and it fades out on the way to far. It spreads over a sphere whose surface grows as the square of the distance, so its power falls as one over the distance squared. Its amplitude, which is what our samples are, falls as one over the distance, so twice as far is half the amplitude. That's about six decibels quieter, on the scale loudness is measured in, which goes by ratios, as our ears do. One over the distance alone is still a tenth at forty metres, which we'd hear, so the fade brings it down to nothing there, and a crowd of figures far off doesn't add up to a murmur. Side is how far to our right the sound is, as the dot product of the way to it with the camera's right, over the distance. Straight ahead or behind, it's zero, and right beside us, one or minus one. At no distance at all, there's no way to it, so the side is zero, and we don't divide by zero. What's right on top of us comes from both sides. So the pan is the side, scaled down to the widest pan, and within a metre, it's scaled down again towards the middle. That way, a step that passes under us slides across, without flipping from one ear to the other. The variety's constructor seeds its noise and keeps the spreads. Next starts from the first take, which is the one there is when there's a single take. With more than one, it draws how far to skip. The skip is one, plus a random share of one fewer than the takes, so with eight takes, it's one to seven. Uniform stays under one, so the skip can't reach the number of takes, which would land on the last take again. That gives one of the others: a step on from the last, by one to all but one. Going on from the last take by that much, and wrapping round past the end, lands on any take but the last, each as likely as the others. Before the first, there's no last take, so it counts from take zero. Drawing again until we get a different take would work too, but this way, it's a single draw each time. Next remembers the take, and the pitch is one, give or take the spread. The volume comes down from one by up to its spread, so the takes vary between full and a little quieter, which keeps it between zero and one, like our other volumes. Footfalls starts from the start and halfway, which is what a clip gets if we can't find its feet. We count one frame fewer than the clip has. The last frame is the first again, so that the loop closes without a jump. With fewer than two frames, or a foot's bone missing, or past the clip's bones, we keep the defaults. Then, for each foot, left and right, a lambda gives the foot bone's height at a frame, from the clip's poses, capturing the clip and the foot by reference. We go through the loop's frames, for the lowest and the highest the foot gets. A planted foot sways a little as the body goes over it, so its very lowest frame could be anywhere while it's on the ground. Instead, down is within a sixth of the way up from its lowest, and the foot comes down on the frame it gets there, on its way down. So we look for the frame where the foot is at or below that, while the frame before it was above, wrapping round, so the first frame's before is the last. That frame, over the frames, is how far into the loop the foot comes down, and we stop at the first one we find. In who, a player's id and a monster's can both be seven, as each kind counts from one. So the kind, zero for players, one for monsters and two for NPCs, goes in the top thirty-two bits, and the id in the bottom thirty-two, so no two figures share a number. Update collects the figures that stepped, and builds this update's loops as it goes. For each figure's gait, unpacked into who and gait with a structured binding, we note its loops, and find what they were last time. A figure we didn't have last time has just started walking, or just come into view, and loops that went down mean its clip started over. A walk that's just started, or started over as a run, has no steps yet. Otherwise, for each foot, we take the footfall off the loops, and floor it, which counts the times the foot's moment has come round. Say the left foot lands at a quarter: at one point two loops, that's zero, and at one point three, it's one. We count it for last time's loops too, and if the count went up, the figure goes on the list of those that stepped. The comparison is whether the foot's moment came round again since the last update. Last, this update's loops replace the old ones, moved, without a copy. So a figure that wasn't in the gaits, as it stopped or we no longer see it, is dropped, and starts afresh.

49:31 Now the characters have to tell us where each figure is in its walk. In the characters' header file, we include our soundscape header, as that's where the gait is defined. Gait of is what the game loop is going to ask of each figure, each frame, to know how far it's got through its walk or run, and where its feet come down. It returns an optional, as a figure that stands, swings or lies dead has no gait at all. Above it, we write where the figure is in its walk or run, and none, if it's doing neither. Each character keeps its footfalls, two numbers for each of the five motions with a clip, the left foot's and the right's, as a fraction of the way through the clip. Most motions keep zeroes, but a slot for each motion lets us look it up by motion, like the clips and the speeds above it. That's where each foot comes down in each motion's clip. In the characters, at the top of the file, we name the bones of the left foot and the right foot, as Mixamo names them, with its mixamorig prefix. As each model loads, the two feet start at minus one, for not found yet. The loop over the bones, which so far looked for the hand, now takes each bone's name once, as a string view, so the three comparisons don't repeat the long path to it. A string view points at the characters raylib already holds, along with their length, so naming it copies nothing. The left foot's bone goes into left foot, and the right foot's into right foot. Then, for the two motions where feet come down, the walk and the run, we work out the footfalls of that motion's clip, from the two bones. The braces make an initialiser list, a small array the compiler builds for us, which a range-based for loop goes through like any container. Footfalls goes over each frame of the clip, so we do it once, here, as the model loads, and not while the game runs. Our two characters come from Mixamo, but the skeleton's legs have no foot bones. So its feet stay at minus one, and it steps at the start of its clip and halfway through. Then comes gait of, which works the gait out from the figure's motion and its time in it. If no characters are loaded, or for a figure that isn't walking or running, it returns nullopt, the empty optional. Otherwise, the characters' for function finds the character the figure is drawn with, ;]] and we take its clip for the motion the figure is in. A loop is one frame short of the clip's keyframe count, as it was in footfalls. The max keeps a clip of a single frame from dividing by zero. That's how frame at plays a clip, sixty frames a second, with the last frame the first again. The loops are the seconds the figure has spent in its motion, times the clip's speed, times sixty frames a second, over the frames in a loop. The speed is one for our characters, and under one for the skeleton, which plays its run slower, and slower still as its walk. Frame at does that sum to pose the figure, wrapping round at the end of each loop, so the gait stays in line with the pose on screen, and a step sounds as we see the foot land. And the gait gets the footfalls of that motion's clip. The renderer's header file declares a gait of as well, since main hands the renderer its figures, and the renderer holds the models each figure is drawn with. It's where the figure is in its walk or run, as its model's clips have it, or none, if it's doing neither. In the renderer, gait of goes just above draw figure, and finds the figure's characters the way draw figure does. A monster is drawn with the models of its kind, which we look up by the kind's id, and a kind without models loaded has no gait, as it's drawn as a plain cube. Players and NPCs share the characters, so anyone else gets their gait from there.

53:08 The steps' takes need somewhere to live, and something to play them, so they go on a soundboard, a class in a new file, starting with its header file. It needs map, memory and vector from the standard library, and our audio header, for the clips. Foley gives it the grounds and their steps, and the soundscape gives it how a sound is heard, and the variety. The soundboard class holds all of them, and we write over it what it is: the game's sounds, each made in a few takes as the game starts, and played a take at a time. Each ground's step gets eight takes, a constant of the class. With the variety picking a different take each time, and nudging its pitch and its volume, eight are enough that a walk doesn't settle into a pattern you'd pick out, while the start stays quick. The constructor takes the audio device, as it loads the clips, so a soundboard can't be made before the device is open. Set volume is a plain setter, named in lower case, as the style guide allows for one. It's how loud the sounds are, from the settings, from zero to one. And step plays a step on a ground, as it's heard from where we stand. In the private part, takes is a name for a sound's takes, a vector of clips. Each clip sits behind a unique pointer, as it owns raylib's sound and can't be copied, so the vector moves pointers around as it grows. Play picks one of a sound's takes, with a variety, and plays it. The soundboard keeps the volume, each ground's takes, and a variety for each ground. That way, each ground keeps track of its own last take, so two steps on sand don't repeat, even with a step on grass between them. In the soundboard's source, after its own header, we include memory, for the unique pointers. A step's pitch can be off by up to eight percent, either way, which is a little more than a semitone, the step between two neighbouring keys on a piano. So each step plays a little higher or lower than it was made, and a little quieter. And a step's volume can drop by up to thirty percent. Steps play at sixty percent, about four and a half decibels down, as we hear them all the time, from anyone walking near us, so steps sit under everything else. The constructor makes all the takes, going through the seven grounds. The square brackets make that ground's entry in the map, and we keep a reference to its takes. For each of its eight takes, the seed is the ground's number times eight, plus the take, plus one. A ground is an enum class, which doesn't turn into a number unless we cast it. So the fifty-six takes get the seeds from one to fifty-six, a seed for each take of each ground. Step makes the take's samples, and the clip loads them into raylib, with four voices. We put the namespace in front of step, as inside the soundboard, step on its own would mean the soundboard's step. Four voices let a take start again while it's still sounding, up to four at once, for a few skeletons walking together, and a fifth start takes over the oldest voice. Each ground gets its variety, seeded by the ground's number, with the steps' pitch and volume spreads. Emplace adds it to the map, as the square brackets would first make a variety with a default constructor, which a variety doesn't have. Making all the takes up front costs under a fifth of a second as the game starts, on my machine. Making a step each time a foot lands would run thousands of samples through the filters in the middle of a frame, for each walker in view, and hand raylib a new sound to convert each time. With the takes ready, a step in the game costs a pick and a call to play. Play is where a step gets its take. It gives up on a sound that has no takes, or one too far away to be heard, so a step we can't hear doesn't use up a voice. Otherwise, the variety picks the take, not the one it played last, with a pitch and a volume of its own. The clip plays it at our volume from the settings, times how loud it's heard from here, times the take's volume. Volumes multiply, as each one scales the samples, so a step heard at half volume, on a soundboard at half volume, plays at a quarter. The pan comes from where it's heard, and the pitch from the take. Then step, which the game calls, lowers the step's volume under everything else, by the step level, and plays one of that ground's takes, with that ground's variety. We look them up with at, as square brackets don't compile for the varieties, for the reason we used emplace, and all seven grounds are there. And in the client's CMake file, the soundscape and the soundboard join the core library, next to the synth and foley.

57:41 The steps get a volume of their own in the settings, so that a player can have them louder or quieter than the music, or turn them off and keep the music. In our proto file, the sound message gets an effects field, number four, the next one free. It's optional like the others, so a settings file saved before today, without it, keeps the default, where a plain field would read as zero, and play no sound at all. In the sound header file, the sound settings get the effects, at zero point eight to start with. Through the slider's curve, that's eight decibels down, or about forty percent of full amplitude, a notch louder than the music at zero point seven. It covers the sound effects, apart from the music. In settings, loading reads the effects like it reads the music. When the file has them, and they're a number, they're clamped between nothing and full. A player can write anything into the file by hand, and nan keeps the default, as clamp would let it through. And saving writes the effects, next to the music. In the menu, the settings window gets an Effects slider, under the music's, in percent like the others. The settings compare with a defaulted equals, which takes in the new field, so letting go of the slider saves the file, as it does for the music. In main, we include raymath, raylib's vector maths, for the camera's right, and map from the standard library. Foley gives us the ground under a figure, and the soundboard and the soundscape headers give us the rest. Next to the music, the soundboard starts out empty, as it can't be made until the audio device opens. It's going to hold the steps, made as the game starts. Footsteps sits beside it, and keeps how far each walker had got through their walk, from one frame to the next. Once the device is open, after the music has loaded, or failed to, we make the soundboard, with all its takes. Without a sound card, as in a container, there's no device, so there's no soundboard either, and the game skips the steps, like it skips the music. In the world, once the renderer has this frame's figures, we play the steps, if there's a soundboard. We hear from where we stand, with the camera's right to our right. The camera gives us its eye, and its right is the cross product of where it looks, the target minus the position, with its up. A cross product of two vectors is a third at right angles to both, and in raylib's coordinates, forward crossed with up points to the right. Normalize brings it to a length of one, which is what hear expects. Then we gather the gaits by who, and the walking figures by who too, so that we can find where each one stands once we know who stepped. For each figure, we declare an optional gait in the if, and ask the renderer for it. The if tests the optional in one go, so its body runs when there's a gait, and the name doesn't reach past it. The star takes the gait out of the optional, and it goes in by the figure's who, next to a pointer to the figure, which stays valid while the renderer holds this frame's figures. Footsteps gives back who put a foot down since the last frame, and for each of them, we find where they stand. The step is on the ground under them, in the land we're in, heard from where we stand. So a skeleton walking past on our left sounds from the left, quieter as it goes, and our own steps are heard from right where we are, in the middle, with nothing taken off for distance. At the end of the frame, next to the music's volume, the soundboard gets the effects volume from its slider, through gain, like the music, so the slider moves in decibels. Setting it each frame costs next to nothing, and the steps follow the slider while it's dragged. The master volume covers each sound the game makes, the steps now as well as the music, as raylib's master volume scales everything the device plays. So, let's build the client, and log in as arthur, on the grass a few metres up from a beach.

1:01:39 The Meadows' north shore runs from grass to sand, and then into the sea. On the grass, the steps are soft, then the sand hisses under each one, and in the shallows, the steps splash.

Wrap-up

1:01:56 So, today, the client got a small synthesizer, with noise, a filter that can sweep, sine waves and envelopes, and a tool to listen to what it makes. From those, it makes a step for each kind of ground, a few takes of each, and plays them with a little variety, so a take doesn't play twice in a row. In the game, a step plays when the walk puts a foot down, louder nearby and from the side the walker is on, and the settings got an Effects slider for them.

Playing it

1:03:07 Tell me in the comments which sound you'd like to hear next, or anything else you'd like to see. And if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.