Delta compression for our MMORPG's worlds, in C++. Each world from the server carried everyone near you in full, twenty times a second, so a player standing in a crowd cost as much as one walking through it. Each input now says the newest world the client has whole, the server remembers a second of what it sent each client as a hash of each player's and monster's piece, and anyone who hasn't changed since goes by their id alone, which the client keeps as it has them. The bots send their keys each tick, through a queue of writes, so they say which world they have often enough to help. With forty bots on one machine, measured from the server's Prometheus metrics, each gets roughly half the bytes it did. This is episode 70 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
Topics: Performance, Networking
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep070/end.
Transcript
Intro
0:00 Welcome back to episode seventy, where we're going to make the server send less, by leaving out of each world the players and monsters that haven't changed since a world the client already has, which is what's called delta compression. Nothing changes on screen this time, so we're going to judge it by what the server sends, measured before and after. First, a look at where the numbers end up.
0:21 On this machine, the two panes measure what the server sends each of forty bots over fifteen seconds, read from its metrics. With the game as it stands, on the left, that's around twenty kilobytes a second for each bot, and with today's code, on the right, it's around eleven and a half, a little over half. And the game plays just as it did before today's code.
0:42 You'll find a link to the open source code on the series' website, along with a page for each episode, where you can browse the code at each of its steps.
Last time
0:50 Last time, we smoothed out the other players and the monsters on a network that loses packets. The client holds on to a second of worlds, and works out the server's clock from whichever of them came quickest. Everyone else is drawn a tenth of a second back, between two of those worlds, and when the next ones are lost, they walk on for up to a tenth of a second more before stopping.
Today
1:12 With the stack up in Compose, and forty bots playing on this machine for a little while, let's measure what the server sends each of them as the game stands. Curl asks the world server for its metrics, and awk picks out nanommo bytes sent total, the bytes it has queued for its clients since it started, which goes into a variable called a. Then we wait fifteen seconds, and read it again, into another called b. Awk divides the difference by the fifteen seconds and the forty bots, and by a thousand for kilobytes, which comes to around twenty kilobytes a second for each bot on this run. The counter takes in events, bags and chat too, but with forty bots wandering, most of it is worlds, twenty a second, each with everyone near the bot in full, whether they moved since the last one or not.
1:57 Each world carries everyone near you in full, twenty times a second, so a player standing in a crowd costs the server as much as one running through it. A monster resting between its walks goes out with its place, its facing and its health each tick, and none of them change while it rests. That kind of waste is easy to miss until you measure it, and it grows with the size of the crowd, so I'd fix it before most other things on the network. So first, each input is going to say which world the client has whole, and the server is going to remember a second of what it sent each client. Then anyone who hasn't changed since the world the client has goes by their id alone. Last, the bots are going to say which world they have each tick, as a client does. Right, let's start with what the client says, in the protocol.
Which world came whole
2:47 First, the top CMake file moves the project on to version zero point seventy. In our proto file, the input gets seen, field seventeen, the newest world the client has whole, with all its parts, by when it was sent. The server leaves out of the next worlds what hasn't changed since. Seen is a sixty-four bit integer, like the world's sent, as both are microseconds on the server's clock. Then the world gets still players and still monsters, fields twenty-four and twenty-five. They're the players and monsters near you that haven't changed since the world your client said it has whole, by their ids alone. Repeated numbers are packed in proto3, so an id costs a byte or two, where a player in full is a few dozen bytes, with the items they wear. Next, in the header file of Parts, the class that puts worlds back together, a function called whole hands back when the newest world that came whole was sent, or zero before any has. Parts keeps that time next to sent, the time of the world it's putting together. In parts, the still players of each part go into the set of the players seen in this world. Those that haven't changed since the world we have whole are as we have them, and still here, and the still monsters go into their set as well. So when the world has come whole, and the ones it didn't mention are dropped as gone, the still ones stay. And once each part of a world has arrived, its time is the newest that's come whole.
4:12 The client's connection holds the parts, so in its header file, whole hands on what they say, the newest world that's come whole, by when it was sent, for the client's main to put on its inputs. In the client's main, each numbered input we send, one a tick, carries seen, from the connection. Other inputs, such as a line of chat, leave it at zero. And in the bot, Send takes a copy of the input it's given, to go out with the newest world the bot has whole, as the client does. It sets seen on that copy from the bot's own parts, and frames it. A bot sends an input when it changes its mind, though, about once a second, and up to three seconds apart while it wanders, which we'll come back to.
4:55 Now, a quick test that the still ones stay as they were, and that we know which world came whole. A first world, sent at one, with three players, comes all at once, so it's whole as it arrives, and whole says one. The next one, sent at two, is a whole world with player one in it, moved along by five, and the other two standing as they were, so none of them should go. It names those two as still players, by their ids, and it's added like the first. Then the assembled result has all three players, with the second where he first was, and whole says two.
5:29 After building the tests at this step, we run all nine of parts', which need no databases, so dash dash no deps leaves MySQL and Redis out. Grep keeps the lines of the tests that passed. The still players stay where they were, whole moves on with each world that's arrived whole, and the older tests pass as they did. The server sends no still ones yet, so at this step, the game carries on as before.
Leaving out the still
5:54 Here's what the server is going to do with seen. Each world it sends a client, it remembers for a second, as a hash of each player's and monster's piece, the bytes it serialized for them. A hash is eight bytes, where keeping the pieces would mean a copy of each world for each client. When an input says the client has the world of ten seconds whole, the server hashes this tick's pieces for that client. A piece that has kept its hash since ten seconds, in each world sent since, goes by its id alone. The client may have had any of those worlds too, so a piece that changed and changed back has to go in full. Anything else goes in full, as it did before. The catch is that each client's world is its own now, so the players in a cell no longer share theirs, and the server puts a world together for each of them.
6:43 In the server's header file, we bring in string view, for the pieces, which are views into the bytes each player and monster was serialized to. Delta takes the player's id, the copy of the land they're in, and their view, then the pieces of the players and of the monsters in the land, the world's time, and a string it fills. Over it, we write what it's for: it works out what goes to the player's client in this world, which is the pieces of the players and monsters in view that have changed since the world it has whole. The rest go by their ids, in still, which is one more piece, and it remembers what it sent, for the next. Sent is what one world carried to one client: the copy of the land it was in, as ids are a land's own, and each player's and monster's piece, by its hash. Those go in a map from the key to the hash. History keeps those for each client, in a map by when each world was sent, and seen keeps the newest world each client has whole.
7:40 In the server, the most remembered is twenty, a second of the worlds each client was sent, to leave out of the next what hasn't changed since the one it has. Where an input arrives, a seen newer than the last one we had becomes that client's. Inputs without one say zero, and leave it alone. When a player leaves, their history and their seen go with them, like their queue of inputs. In BroadcastCopy, the pieces used to be gathered once for each cell, so the players in it shared that world, and its datagrams over UDP, and that goes. Now, inside the loop over the players in the cell, each client's world is its own, as each has a different world whole, and what's changed since that one differs. Delta hands back this player's pieces, and still holds the ids of the rest. It's declared out here, as the pieces are views into it, so it has to outlive them. The NPCs go on the end, once a second, as before. Then come the player's own fields, as they were, which Delta doesn't touch. Over UDP, this player's pieces are split into parts of their own, where the cell's parts used to be split once for all of them. Each part goes out with the player's own fields, and its size is counted in the bytes we send, which is the metric we measured. And over TCP, the stamp and the pieces go into a string for this player alone, in a shared pointer as before, so the session can hold on to it while it's written. Now for the body of Delta, which fills in still as it goes, and hands back the pieces this client needs. Delta starts with this player's history, which the map makes the first time we ask. Then it looks for the baseline, the world the client has whole, if we still have what we sent in it, and it was in this copy of the land. The baseline is an iterator into the history, left at the history's end while there's none, so that we can walk on from it to the worlds after it. Someone who went through a gate since then gets everything in full, as a monster's id in one copy means another monster in the next. Then this world joins the history, with its copy, and as a map's iterators stay valid while it grows, the baseline still points at the client's world. Changed is a lambda, capturing everything by reference. It says whether a piece has changed since the world the client has, in which case the client needs all of it, and either way, this world has it. Each world sent since has to have had it unchanged too, as the client may have had those. One that changed and changed back would leave the client with the change, such as a monster stuck mid-swing. It hashes the piece with the standard library's hash for string views, and notes the hash in this world's history. With a baseline, a loop walks from the client's world up to this one, in the order of their times, as the map keeps its keys sorted. It stops at the history's end too, should the clock have stepped back past the client's world. The worlds are stamped with the system clock, which can jump back when it's set, and then this world sits before the baseline in the map. Each world the loop passes has to be in this copy, with this hash under this key. If the piece matches all the way, it returns false. Otherwise the piece goes on the list, and it returns true. Unchanged is a world of nothing but ids. Each player in view goes through changed, with their id as the key, and either their piece goes in full, or their id goes into the still players. Monsters go through it too, under a key with a one shifted past the thirty-two bits of their id, as players and monsters count apart. Player seven and monster seven need keys of their own. If any are still, unchanged is serialized into still, which goes on the list as one more piece. Protobuf reads pieces one after another as one message, so the ids join the world like anything else. Last, the client won't ask about a world older than the one it has, so the history drops those, and past twenty, the oldest go too, as a second of them is plenty.
11:37 Next, we check in the server's suite that it leaves out what hasn't changed since the world the client has. Alice and Bob log in, and we run the test's event loop until Alice sees Bob. We want him in a world without names, as most are. Names go out once a second, so a world with them wouldn't match the ones after it. Both stand still, and Alice's next input says she has that world whole, by its time stamp, without any keys down, so she stays where she is. Then we run the event loop until her world's still players hold Bob's id, and she no longer gets him in full. So Bob comes to her by his id alone.
12:16 This time the test needs MySQL and Redis, as its players log in for real, so Compose starts them, with Consul and the migrations, before the test container. Bob reaches Alice by his id alone, so it passes.
Bots that say so each tick
12:31 With the bots as they are, the server would leave out very little, and the reason is in the bot. A bot says which world it has when it changes its mind, so by the time the server compares, that world is old, or gone from the second it remembers. So in the bot's header file, we bring in deque. Send now writes the input after any still being written. Tick runs each of the server's ticks, as the client does, with the keys as they are, and the newest world the bot has whole. Write puts a frame in line to be written. There's a timer for the ticks, and the outbox, a deque of what's to be written, the one being written first, where a single string used to be. Keys are the keys the bot holds down, as it last sent them. In the bot, we bring in utility, for std move, and the tick timer is made on the bot's io context, like its other timers, which wander and say hello over UDP. Once it's greeted the server, the bot starts ticking, next to wandering. Send keeps the keys of each input it sends: the direction, run, attack and the target, which stay as they are until the bot changes its mind. Then it sets seen as before, and hands the frame to Write. Tick stops once the bot is disconnected, and otherwise it copies the keys alone, so that nothing else the bot did, such as a skill or a line of chat, happens again, sets seen, and writes that. Then the tick timer waits fifty milliseconds and runs Tick again. Write is where the queue comes in, now that two timers send on one stream. Asio's async write on a stream has to finish before the next one starts, or the bytes of the two can interleave, and now a tick's keys and an input from wandering can go at once. So the frame goes on the back of the outbox, and if another is being written, it waits its turn. Otherwise, next writes the frame at the front. A lambda can't refer to its own name, so next takes its own lambda as an argument, self, by reference, through a generic lambda's auto parameter. The write's handler captures a copy of self, which outlives this call to Write, to start the next write once this one's done. When a write ends, its frame comes off the front. An error marks the bot disconnected and empties the outbox, and otherwise, if anything's left, self writes the next. And Stop cancels the tick timer, with the others.
Measuring it
14:48 Now today's code, with the stack and forty bots started the way we did for the first run. Curl and awk read the world server's bytes sent into a, then we wait fifteen seconds, and curl reads the counter a second time, into b. Awk turns the difference into a rate for each bot, which on this run comes to around eleven and a half kilobytes a second, from around twenty, so a little over half. When I measured it while writing the code, it went from sixteen point eight to seven point six, a little under half, so it moves about from run to run. A disclaimer: this is a single machine, with bots that keep walking around. A player who walks changes their place each tick, and so their piece, which goes in full. The ones standing about, and the monsters resting between walks, cost a byte or two each now. And the bots now send twenty inputs a second each, which this counter doesn't see, as it counts what the server sends.
Wrap-up
15:46 Each input now says the newest world the client has whole, and the client keeps the players and monsters a world names by their ids. The server remembers a second of what it sent each client, as a hash of each piece, and leaves out of the next world whoever hasn't changed since, naming them instead. The bots send their keys each tick now, through a queue of writes, and with forty of them, the server sends each about half what it did.
Playing it
17:01 Let me know in the comments what you'd like to see next, and if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.