nanoMMO

How to build an MMORPG from scratch in C++

Where the series is going, and a C++ project that is built, tested and documented on each push.

Watch on YouTube

In this first episode, we start building an MMORPG from scratch in C++, and the series is going to focus on the engineering around the game: Docker, CI, benchmarking, Prometheus and Grafana, MySQL, Redis and profiling. We sketch the architecture, and then set up a C++20 project written to Google's style guide, with CMake, GoogleTest, a Docker build, and GitHub Actions checking the style.

Topics: DevOps, Testing

The code

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

  1. 15:00ep001/step-1A CMake projectBrowse
  2. 20:42ep001/step-2A first functionBrowseChanges
  3. 28:20ep001/step-3Unit testsBrowseChanges
  4. 32:36ep001/step-4A bug, caughtBrowseChanges
  5. 33:58ep001/step-5Building in DockerBrowseChanges
  6. 36:29ep001/step-6Running it in DockerBrowseChanges
  7. 39:20ep001/step-7API docsBrowseChanges
  8. 42:36ep001/step-8CI with GitHub ActionsBrowseChanges

Transcript

Intro

0:00 Hello and welcome to the nanommo series, where we're going to build an MMORPG from scratch. My name is Adrian, and I hope we'll have some fun while learning and applying software engineering. AI can help us do more in less time, but human intuition, oversight, intelligence and insight still matter when we're building a complex system with a purpose behind it. I don't want the tool to replace us, and instead, I want us to use it to create a better future. Now, before anything else, let's look at a quick demo of what we're going to have working by episode three.

0:31 Each of these cubes is a player, with a client of its own, and they all share one world. And our server tracks and broadcasts where everyone is, so each player sees the others move.

0:42 And by episode four, we're going to have three hundred bots playing at once. And we will have set up a dashboard that shows us a couple of useful performance metrics.

0:53 So that's where we're heading over the next few episodes, and much more will come after that. We're going to focus somewhat on the gameplay, and try to add some cool little features along the way. Hopefully, some of them are going to be your suggestions. The plan is for this to be an extensive series, which is going to cover a lot of software development topics.

1:13 On the website of the series, you can find more information about the project. The code for the project is open source on GitHub, tagged at each step of each episode, so that you can follow along.

1:25 I've always had an interest in game development, and I've used Unity and Unreal. And over the last ten years, I've had multiple attempts at building my own game engine. As for my background, I studied computer science for my undergrad. Then I worked as a software engineer, for big tech and other large companies, but not as a game developer. And now, I'm doing a PhD in artificial intelligence, specifically in reinforcement learning for improving reasoning in generative models. Since I haven't worked as a game developer, what I want to focus on primarily is what I have direct experience with. That's the software engineering and DevOps side of creating something like this, applied in a domain I love. The purpose is to help you learn what comes into play in a production-like setup, especially if you're at the start of your career. That said, maybe over time, we're going to find ways to apply my research in this project as well.

2:17 For example, there are AI society experiments, where language models play the people living in a world. Say, Generative Agents: Interactive Simulacra of Human Behavior, which is a paper from Stanford. The authors put twenty-five agents, each driven by a language model, in a small town, and let them live their days. Another example is reinforcement learning for animations, where our skeletons could learn to walk on their own, or to interact with the environment. And they'd learn that dynamic behaviour with a neural network.

2:47 As for MMORPGs, my experience is as a player, and I played Cabal Online, Aion and Metin2 back in the day, while I haven't actually played World of Warcraft. And I was quite a fan of purely browser-based text games in general. What fascinates me the most is how advanced the computer science behind these games is, and the people playing them often underappreciate it. And it makes sense why it's like that, as it's all meant to stay behind the scenes. So again, that's the reason I want to create content like this. I want to contribute to showing how much effort humanity has put into the technology that allows all of this to exist. And I want to show how that effort can continue in the age of AI.

3:28 Before we go any further, a quick note on how this series is made. Sometimes, the voice you're hearing is generated with AI, and it's designed to sound like me. The wording follows how I speak, so none of it is left to chance. It's all highly moderated, and many hours go into designing the curriculum, informed by my own experience from industry and from my personal projects. Using AI simply lets me make better quality content, which is my goal. It means I don't necessarily have to aim for a perfect recording. Instead, I can say more of what I realise is meaningful to show you. So it's human effort to a large extent, and I'm leveraging tools that let me scale it. Each part of the project is added deliberately, in order to share knowledge and help you understand complex systems. And a lot of it goes well beyond what you'd naturally do in a personal project.

4:22 Visually, it's going to be a polygonal, low-poly style of game. As such, we're going to lean on procedural generation, with code building the world and a lot of what's in it. So we're not going to spend much time making assets by hand in tools such as Blender. The main reason is that I'm not that great at it. I've also designed the series with the engineering and the computer science as its main focus. So I'm leaving the rest up to the imagination of those of you who follow along, and want to put some of this into practice.

The series

4:54 There are some really high-quality creators out there who make videos about game development. One of them is The Cherno, who's been making a game engine called Hazel. He goes really in depth into C++, and into how a game engine works behind the scenes. These days, he's the CTO at a robotics company, where he's building a game engine for training AI robots. So if the engine side is what you're after, I'd recommend his channel.

5:20 And then there's Elegon, a new MMORPG inspired by World of Warcraft Classic. It's being built with Godot as the engine, and SpacetimeDB behind it. SpacetimeDB is a database that also runs the server's logic, so it's quite a different take from the one we're going to go with here.

5:37 Besides those, there are a lot of series out there on gameplay development, on modelling, or on building a game engine. And there are others on topics such as monitoring, as a general principle. What I want to explore here is the skillset you need in order to work on games deployed at scale. And more generally, on distributed systems and production software, which several teams have to be able to work on, and which has to last for years. So, besides building the game, its client and its server, we're also going to use Docker, so that it builds and runs on almost any system. And we're going to have automated builds and tests whenever something changes. We're going to benchmark it with simulated players, collect metrics with Prometheus, and have monitoring with Grafana. We're going to talk about our database choices, with Redis for the fast-changing state and MySQL for persistence, along with its migrations. And we're going to go into the nitty-gritty and do some performance optimisations, all the way from the C++ and the graphics to the server communication. Along the way, we're also going to focus on data structures and algorithms, and on building systems that account for scale as much as possible. We won't have the feedback loop that comes with deploying this to tens of thousands of real players. But we're going to do our best to mock it in our performance testing, if nothing else. And it's all going to be open source, so you can play with it and run it.

7:01 For now, the working title of the project is nanoMMO, which takes after nanochat, a repository by Andrej Karpathy. nanochat trains a small ChatGPT-like model and lets you talk to it, end to end, with code that's kept minimal and easy to hack on. And the whole pipeline fits in a fairly small set of files, which you can actually read through. That's what I'm going for here as well, a codebase that covers an MMO from one end to the other. And it's one you can read, run and play with.

7:30 So your takeaway won't necessarily be how to build the best game engine or the best database schema. Instead, it's going to be how to be an end-to-end engineer who understands the whole pipeline. I also want this series to build timeless skills, which hold up as we move to an AI-first world. Debugging, in-depth understanding and understanding how the whole system fits together are going to stay a core need. And I believe society is going to keep rewarding them. However, the expectations are going to be that much higher. It's now much easier for someone without experience to fake it till they make it. But in the long term, that's not going to pay off, compared to someone with real understanding. Someone like that works together with assistive tools, and not as a bystander. So when a problem occurs, you're able to debug it and think critically about what's actually happening behind the scenes.

Architecture

8:22 So, let's look at the architecture, all the way from the player's machine to the database. Players are going to run a native client, written in C++, with raylib for the graphics. It connects to the game server, which is also written in C++. I've written before about keeping business logic out of the UI layer, and it applies here as well, with a heavy bias towards a thin client. As such, the server is going to be authoritative, and it runs the simulation at a fixed tick rate. It takes care of all the brainy stuff, while the client takes care of input and rendering. In a game, this matters even more, as we can't trust a client that's running on someone else's machine. For the messages in between, my proposal is Protocol Buffers. Behind the server, Redis is going to hold the hot state, such as sessions and positions, while MySQL stays the source of truth. I'm not going to go deep on these two today. We're going to bring each of them in once the game actually needs it, so that you see the problem it solves first. Say, once we have a few hundred simulated players, and saving each move directly to the database puts too much load on it. Picking SQL is mainly my preference, as NoSQL databases, such as MongoDB, would also work for a game like ours. So we're going to dig into that when we get there, and we might change our mind by then. And to see what's going on inside, the server exposes metrics, which Prometheus scrapes and Grafana turns into dashboards. Before we write any code, I want to go a bit deeper on protobuf, as it's going to carry each message between the client and the server.

Why Protocol Buffers

9:57 Protocol Buffers, or protobuf for short, is a format for serialising structured data, which came out of Google. That means turning a message into bytes that we can send over the network. And the side that receives them turns those bytes back into the message. The docs describe it as being like JSON, but smaller and faster. We describe each message once, in a dot proto file. Each field has a type, a name and a number. On the wire, it's the number that identifies the field, not its name. The proto compiler then generates code from that file, for C++ and a lot of other languages. So the client and the server both compile code generated from one schema, and that schema becomes the contract between them. Neither side writes its own encoding or decoding by hand, so the two can't drift apart. And adding a new field doesn't break older code, as it skips the fields it doesn't know. And unlike JSON, protobuf is a binary format, which means it doesn't spell its messages out as text. Say we have a message with a single number field, and we set it to a hundred and fifty. Protobuf encodes it in three bytes, one that says which field it is, and two for the value. In JSON, it's text, with the field's name in quotes and braces around it, so nine bytes. And the receiver has to parse that text back into a number. With a lot of messages going to a lot of players, many times a second, that adds up. We could also write our own raw binary protocol, which is small and fast. But we'd be writing the encoding and the decoding by hand, on both sides. And we'd have to keep them in step by hand, while adding a field would break older clients. So protobuf gives us most of the size and speed of a raw protocol, along with a contract that both sides compile.

Running it anywhere

11:45 Last, I want to touch on where all of this is going to run. The server is going to ship as a Docker image. And it's going to expose its metrics in Prometheus's format. That's on purpose, as it lets us deploy to AWS, Google Cloud, Microsoft Azure, or any other cloud provider. Each of them has a monitoring stack of its own, such as CloudWatch on AWS, or Azure Monitor. However, they all integrate with Prometheus, and with the other standard tools you'd end up using, such as OpenTelemetry. So my proposal is to plan for monitoring from the start, and to consider what you actually want to monitor and why. Say, the time each tick takes, the number of players online, or how long the database takes to answer. And then lean on an open protocol for it, so that you're not tied to a single provider's tools. That way, the cloud providers have usually done the work for you, and they provide at least their own collectors for structured metrics. They also take deployments as Docker images, which follow an open standard as well, from the Open Container Initiative. And it goes beyond the cloud, as it could be a research cluster at a university, or a custom environment inside a studio, small or large. A small studio is likely to use these standard tools as they are. A big one might have in-house tools instead, but it would still follow similar practices, adjusted to its own needs.

Today's plan

13:08 As for this first episode, we're going to set up the project in a healthy way, such that it's not in our way as we go along. We start with a tiny server and a single function worth testing, written to Google's C++ style guide. CMake is going to build it, and GoogleTest is going to test it. Then we move the whole build into an Ubuntu image, so that it doesn't matter whose machine it runs on. The server gets a small image of its own, which we can run anywhere Docker runs. And we have GitHub Actions run it automatically for us whenever we push, checking the style along the way. And that pipeline is also going to publish documentation, generated from the code. All right, let's get started, and the first step is deciding how our code is going to look.

Google's C++ style

13:52 We settle that before the first line of code, so that the code follows it from the start. We're going to follow Google's C++ style guide, all the way through the series. It's what Google writes its own C++ to, and for each rule, it gives the reasons, often as a list of pros and cons. For example, it decides how we name things, from functions and types to variables. Functions and types start with a capital letter, such as TickInterval, while variables are lower case, with underscores between the words. It says how a header guards against being included twice, with a name made from its path, and in what order the includes go. And it goes deeper than how the code looks, down to which C++ features we use. For example, the guide doesn't use C++ exceptions, as most of Google's code was written without them, and code that throws is hard to mix with it. So a function that can fail returns its error as a value, and our first function is going to do that. Two tools keep us to the guide, and both are going to run whenever we push. Clang-format lays the code out, and cpplint, Google's own checker, catches most of the rest.

A CMake project

15:01 We start from an empty repository, and for building it, we're going to use CMake, which is the standard build system when it comes to C++. CMake doesn't actually compile anything, as it generates the build files for a tool such as Make or Ninja instead. That's what lets one project build on a Mac, on Linux or on Windows. The top-level CMakeLists file describes the whole project, and it opens with cmake minimum required, at version 3.28. CMake has changed a lot over the years, so someone with an old version gets a clear error right away, instead of a strange one halfway through the build. Then the project, which we call nanommo, at version zero point one. And we say its language is C++, which CMake writes as C X X. That way, CMake doesn't go looking for a C compiler we don't need. Next, we set the rules for everything inside it, starting with the C++ standard, which we want to be C++20. That's also the version the style guide targets, and it gives us things we're going to lean on later, such as designated initialisers. Those let us name each field as we fill in a struct. And we mark the standard as required, so that a compiler that can't do C++20 stops the build with an error, instead of quietly falling back to an older standard. We turn the compiler extensions off as well, as GCC and Clang each add a few things of their own to the language. We don't want to depend on them by accident, so the code stays portable. Then we export compile commands, which is a file listing how each source file is compiled, with all its flags. Editors and tools such as clang D read it in order to understand our code. The runtime output directory puts all our executables into one folder, bin, inside the build. And we switch on the warnings from day one, with all, extra and pedantic. Pedantic warns whenever the code strays from standard C++, and we turn all three on now, because warnings get more expensive to fix the longer we wait. Last, add subdirectory pulls in the server folder, which gets a CMakeLists of its own. So each part of the project describes its own build, and the client is going to sit next to the server later on. In the server's CMakeLists, add executable declares the server's program, built from main dot c c. The style guide ends C++ source files in dot c c, and headers in dot h. For now, that's all it needs, as the server is a single source file. In main, we include iostream, which is the standard library's header for input and output streams, as we want to print to the terminal. Then the main function, which prints a line saying the server is starting, through standard c out. We end the line with a plain newline character, not standard end L, as that would also flush the output each time, which we don't need here. And main returns zero, which tells whoever started it that it ran fine. It's not much yet, but it lets us check the whole chain, from CMake to a binary we can run. Then a bit of housekeeping, starting with a clang-format file, which tells clang-format which style to lay our code out in. We base it on Google's, so the code is laid out the way the guide asks, and nobody has to format anything by hand. An MIT licence, as it's all open source, so you're free to take this code and build on it. And last, we tell git to ignore the build folder, so that nothing CMake generates ends up in the repository.

18:30 Let's configure the project, which is where CMake writes the build files for us. Dash S tells CMake where the source is, and dash B where the build folder goes, so that everything it generates stays out of the source tree. Dash G picks the generator, and we're going to use Ninja. Ninja is a small build tool, which came out of Google's work on Chrome. It reads the build files CMake generated, and runs the compiler on whatever has changed, as fast as it can. Make does a lot more than that, so it spends longer working out what to do. And Ninja uses all your CPU cores by default, while Make needs to be asked to with dash j. So our builds are quicker, especially when we've changed a single file. We pick the generator once, and after that, CMake knows to run Ninja for us. Then we build it with dash dash build, and run the server from the bin folder.

A first function

19:23 Now for some actual logic, starting with how a game server keeps time. An MMO server doesn't react to each packet the moment it arrives. Instead, it advances the world in fixed steps, called ticks, a set number of times per second. So our first function turns a tick rate into the time between two ticks. And for time, C++ has chrono, which is the standard library's date and time library. What we need from it is a duration, which is how chrono gives us a span of time. That's a count along with its unit, say forty-two seconds. And the unit is part of the duration's type, so the compiler knows a millisecond from a second.

20:01 Our function can also be asked for something that makes no sense, such as zero ticks a second, and it has to be able to say so. For that, we're going to use Abseil, which is Google's open source collection of C++ libraries. And it's the first place the style guide looks for a library. Its status is a result that's either OK, or an error. An error has a code, from a short list such as invalid argument or not found, along with a message for whoever reads it. And a status or holds either a value, or the error that stopped us getting one. So a function hands back its result, or its failure, in one return value, and the caller checks which before using it.

20:42 First, we bring Abseil into the build, and we let CMake fetch it for us. In the top-level CMakeLists, include FetchContent loads the CMake module that can download other projects. We set absl propagate C X X standard, so that Abseil builds with our C++20 as well. Then FetchContent declare names the dependency, abseil, and says where to get it, which is the archive of a tagged release on GitHub. Pinning a release means anyone building the project gets that one version, CI too. And moving to a newer one is a change we make on purpose, in a commit. System marks it as someone else's code, so its warnings stay out of our build. And exclude from all means CMake builds the parts of Abseil we link against, and nothing more, as it's a big collection. Then make available downloads it when the project is configured. Now a header, tick dot h, which is where the rest of the code is going to learn about our function, without needing to see how it works. It opens with a header guard, which is how the style guide asks a header to protect against being included twice. A header can end up pulled into one source file more than once, through other headers. So if n def checks for a name, nanommo server tick h, in capitals, and define sets it. The second time round, the name is already set, and the compiler skips the whole header. The name comes from the file's path, so it can't clash with another header's. Next, we include chrono, for the duration our function returns, and Abseil's status or. Then a namespace, called nanommo, which puts our names under a prefix of their own. So our function's full name is going to start with nanommo. That way, it can't clash with a function of that name from a library we pull in later. All the game's code is going to live in it. Then the declaration, where the function takes the number of ticks per second, as an int. And it returns a status or of standard chrono nanoseconds, so it gives back the interval, or an error. Returning a duration, and not a plain integer, means the units can't get mixed up. Say we pass milliseconds to a function that expects seconds. It still compiles, and the server runs a thousand times too slow. With chrono, the compiler converts from one unit to another for us, and a conversion that would lose precision doesn't compile at all. We pick nanoseconds as the unit, as it's fine enough that dividing a second by any sensible tick rate loses next to nothing. And now we go back up, and over it, we write a doc comment. The three slashes mark it as documentation, as this function is going to be our example of a documented API. Like the guide asks, it says what the function does. Returns the time between two simulation ticks, accurate to the nanosecond, when the world is updated ticks per second times a second. Returns an invalid argument error if ticks per second isn't positive. That's the contract for anyone calling the function, written down next to it. The namespace closes with a comment that repeats its name, which clang-format adds for us, so the end of a long namespace is easy to spot. And the guard's end if closes the header, which matches the if n def at the top. Now the source file, tick dot c c, which includes our own header first. If the header forgot to include something it needs, this is where the build breaks, and not in some other file that happens to include things in a luckier order. Then chrono, and Abseil's status, as the guide asks each file to include what it uses. That way, a file doesn't break when a header it leaned on changes what it includes. The exception is a file's own header, which the guide lets it lean on, so status or comes with tick dot h. Chrono comes again anyway, as cpplint checks each file for the standard headers it uses. We open the nanommo namespace again, so this definition goes with the declaration in the header. Then we define tick interval, and the first thing it does is check the rate. A rate of zero or less doesn't make sense, and dividing by zero would crash the server. So we return an invalid argument error, with a message saying ticks per second must be positive. A status or can be made from an error like that, so the caller gets the error in place of an interval. That way, a mistake in the configuration stops the server at startup with a clear error, instead of letting it run with a nonsense interval. And then the actual work, where we return a thousand milliseconds, which is one second, divided by the tick rate. In the server's CMakeLists, the function goes into a library of its own, the server's core, which add library builds from tick dot c c. Target include directories adds the project's root folder to the include path. That's why our include says server slash tick dot h. The guide wants each include to name a file by its path from the project's root, so it's always clear which file it means. The root folder is public, so anything that links against the library gets it too. Then the core links Abseil's status and status or, publicly too, as our header uses them. The server links against the core, and Abseil's time library, for printing the interval. That's private, which means the server uses them for its own build, without passing them on. Soon, the tests are going to link against the core as well. Keeping the logic out of main from the very start means we can test it in isolation. Main now includes chrono, Abseil's status or and time, and our tick header. The guide puts the standard library's headers in a group first, and the rest in a group of their own after them. Then ticks per second, which we set to twenty, the rate our server is going to run at. It's constexpr, which means its value is known when the code compiles, so the compiler can treat it as a constant, and nothing can change it while the server runs. The k at the start of its name is how the guide marks a constant. Then we ask for the interval, and we check that the status or is OK before we use it. If it isn't, main prints the status, which carries the error's code and its message, and returns one, so a script or CI can tell that it failed. Twenty is a sensible rate, so that doesn't happen today. And last, we print the tick rate and the interval. The star reads the value out of the status or, and from chrono turns it into one of Abseil's durations. And format duration writes it out with its unit, such as fifty m s. So the implementation is quite simple, a thousand milliseconds divided by the tick rate. Keep this line in mind, as we're going to come back to it.

27:26 Let's rebuild and run it, which takes a little longer this time, as the build also compiles the parts of Abseil we use. Twenty ticks per second gives us fifty milliseconds per tick, as expected. This number is important, as it's our budget, and everything the server does in a tick has to fit inside those fifty milliseconds. And a good part of this series is going to be about keeping it that way, as more and more players join.

Unit tests

27:51 To test it, we're going to use GoogleTest, which is the most widely used test framework for C++. It's also where GoogleMock lives, which lets a test swap the parts of the code it doesn't care about for fakes. Today, we're going to use two of the features listed in its README. It finds and runs our tests for us, so we don't have to list them anywhere. And it gives us a rich set of assertions, such as checking that two values are equal, or that a condition holds.

28:21 We don't install GoogleTest by hand either, as CMake fetches it for us, like it does with Abseil. FetchContent declare names it, googletest, and points at the archive of a tagged release on GitHub, version 1.18, pinned for the reasons we saw a moment ago. Then make available downloads it when the project is configured, and builds it along with our own code. A package manager such as V C package or Conan would also work. However, for a couple of dependencies, FetchContent keeps it all inside CMake, with nothing else to install. Enable testing then switches on CTest, which is CMake's own test runner, so that it can find and run our tests later on. In the server's CMakeLists, we add a test executable for the server, built from tick test dot c c. The guide keeps a test next to the file it tests, and ends its name in underscore test. It links the core library together with gtest main, which is why we split the function out of main earlier. That way, the tests can link against it without the server's own main. Gtest main gives us a main function that runs all the tests, so we don't have to write one. Then we include CMake's GoogleTest module, and gtest discover tests registers each test case with CTest, one by one. It asks the test binary for its list of tests after each build, so adding a test doesn't mean touching this file. The test file includes our header first, like the source file did. Then chrono, Abseil's status and status or, and gtest dot h, which is GoogleTest's header, for its test macro and its assertions. The tests go into our namespace, and inside it an unnamed one, which keeps them to this file, so they can't clash with anything else. We write each test with GoogleTest's test macro, which takes the name of a suite and the name of the test. All three of ours go into a suite called tick interval, and each name says what the test proves, so a failure reads like a sentence. The first one says twenty ticks is fifty milliseconds, and twenty is the rate our server runs at. So this test pins down the case we've already seen working. We ask for the interval, and assert true checks that it's OK. GoogleTest has two kinds of check, and they differ in what happens when one fails. An assert stops the test right there, while an expect records the failure and carries on with the rest of the test. There's nothing to look inside without an interval, so that check is an assert. Then expect equal compares what's inside with what we expect, fifty standard chrono milliseconds. Both sides are chrono durations, so comparing nanoseconds with milliseconds just works. The second test keeps nanosecond precision, and it runs at sixty ticks per second. Sixty is a common rate for fast-paced games, and it doesn't divide a thousand evenly, which makes it the case most likely to go wrong. Again, we ask for the interval, this time at sixty, and assert that it's there before we look inside it. A thousand milliseconds divided by sixty is sixteen point six six six, so we expect that many nanoseconds, accurate to the nanosecond, as the header comment says. We write the number with digit separators, which are the apostrophes C++14 lets us put between digits, so a long number stays readable. The third test rejects non-positive rates, and it pins down the check at the top of tick interval. So if that check ever goes missing, this test fails, before a server divides by zero. For zero, we check that the status's code is invalid argument. Then we check minus twenty too, because checking zero alone would let a negative rate slip through. Both of these checks are expects, so if zero is caught and minus twenty isn't, a single run still shows us both results.

32:06 The first build also compiles GoogleTest, so it takes a little longer. Then we run the tests, and one of them fails. At sixty ticks per second, we get sixteen milliseconds, when it should be sixteen and two thirds. When we checked the output by eye earlier, it looked fine, as twenty divides a thousand evenly, but sixty doesn't. As such, each tick would come out two thirds of a millisecond short. And the server would run about four percent too fast, without an error anywhere.

A bug, caught

32:36 So, let's see why the second test failed, at sixty ticks per second. When we divide a chrono duration by a number, the result keeps its unit, and its count stays a whole number. As such, a thousand milliseconds divided by sixty is sixteen whole milliseconds, and the remainder is dropped. The conversion to nanoseconds happens after that, when we return, and by then the two thirds are gone. We could switch to a duration with a double inside. However, the interval would then stop being a whole number of nanoseconds, and comparing times would get fuzzy. Instead, we start from one second, converted to nanoseconds, so a billion of them, and then we divide it by the tick rate. Nanoseconds are a finer unit than seconds, so nothing is lost on the way, and chrono converts a duration to a finer unit for us, with no cast. The integer division still rounds, but now it rounds to the nanosecond, which matches the header comment. At sixty ticks per second, we lose two thirds of a nanosecond per tick, so about three and a half milliseconds over a whole day.

33:39 Let's rebuild, and this time run the whole suite through CTest, which is what we're going to rely on from now on. All three tests pass, and that test now guards this line for as long as the project lives. If anyone simplifies it back to milliseconds a few episodes down the line, CI is going to catch it before it reaches the players.

Building in Docker

33:59 Right now, this builds on my Mac, with Apple's compiler. However, the server is going to run on Linux, so that's where it should be built and tested as well. And Docker lets us do that, on almost any machine. A Dockerfile is the recipe for an image, and each step in it adds a layer on top of the one before. Docker caches the layers, so a step whose inputs haven't changed doesn't run again. Ours is going to have three named stages, and the first is the toolchain, which starts from Ubuntu 24.04. That's a long-term support release, so it gets security updates for years, and it's what we're going to run the server on as well. Then a single run step updates the package lists and installs what we need. Dash y answers yes to any question apt would ask, as there's nobody there to type it. And no install recommends skips the extra packages apt would suggest, which keeps the image smaller. Build essential brings in GCC and the basics around it. Then CMake and Ninja, like on my Mac, and the CA certificates, which FetchContent needs in order to download Abseil and GoogleTest over HTTPS. Last, it deletes the package lists, as all they'd do is make the image bigger. We chain all of it with double ampersands inside one run step, so it lands in a single layer. And the lists we delete don't end up stored in any layer. The build stage starts from the toolchain, and work dir sets the folder we work in, which is slash src. Copy brings our source code in, and then we configure a release build, with Ninja again, and compile it. Release turns on the optimiser, which is how the server is going to run for real. The test stage starts from the build and runs CTest. Output on failure prints the output of any test that fails, so we can see why, right in the Docker log. And if a single test fails, CTest returns an error, and the whole Docker build fails with it. The dockerignore keeps the git history and any local builds out of what Docker copies in. So the image doesn't depend on whatever is lying around on my machine. Each stage starts from the one before it, and we can stop at any of them with dash dash target.

36:12 Let's build the test target, which runs our tests as part of the Docker build. Plain progress prints all the log lines, so we can see what's happening inside the container as it goes. The packages install, GCC compiles the project, and at the end, our three tests pass again, this time on Linux.

Running it in Docker

36:30 So far, Docker builds and tests the server, but it doesn't give us anything we can run. And that's what we want in the end, as an image is what we're going to deploy later on. However, the build image is far too heavy for that. It carries the compiler, CMake, GoogleTest and all the files the build produced. And anything we ship but don't need is more to download, and more that could have a security hole in it. So we add one more stage, called server, which starts again from a clean Ubuntu 24.04. That's the release we built on, so the C++ standard library our binary needs is already in there. We could go smaller still, with a statically linked binary in an empty image. However, a plain Ubuntu keeps a shell around, which helps when we need to look inside a running container. Copy dash dash from takes files out of an earlier stage, not from our source folder. We take nothing but the nanommo server binary, and put it in user local bin, which is on the path. User switches from root to the ubuntu user, which comes with the image. That way, if anyone ever manages to break into the server, they don't get root inside the container. And the entrypoint is the command that runs when the container starts, so running the image means running the server. The binary comes from the test stage, not the build stage. As such, Docker has to run the tests before it can build this image. So if a single test fails, we don't get a server image at all.

37:57 Let's build the server image, and this time, dash dash target picks the new server stage. And dash t gives the image a name, nanommo-server, so that we can refer to it later on. The toolchain comes from Docker's cache, so what gets compiled and tested again is our own code. Then the server stage copies the binary over from the test stage, once the tests pass. Docker run starts a container from the image, and dash dash rm removes the container once the server exits, so that stopped containers don't pile up. The server prints the line we saw earlier on my Mac, this time from inside a Linux container.

API docs

38:34 Next, we're going to generate documentation for the code we've written so far. Doxygen is the standard tool for generating documentation from C++ code. It reads the comments in our source, along with the classes, functions and variables they sit on, and turns them into a website. It can also produce PDF, through LaTeX, as well as XML, but we're going to use HTML, so the docs are a website. Inside a comment, Doxygen has commands such as param, return and brief, which describe a function's parameters and what it returns. Our doc comment says all that in plain sentences, the way the style guide writes them, and Doxygen shows those as they are. It also understands C++ quite well, so it picks up namespaces, classes and templates, and links them to each other.

39:21 CMake already knows how to interface with Doxygen, so we generate the docs in CMakeLists. Find package looks for Doxygen on the machine, and we configure the docs if it's found. That way, a server without Doxygen can still build and test, and simply doesn't get a docs target. However, Doxygen's default look is quite dated, so we fetch a more modern theme, called doxygen awesome. We declare it with FetchContent, pinned to a tagged release like Abseil and GoogleTest, and make available downloads it. Then come the settings, as CMake passes any variable that starts with Doxygen underscore on to Doxygen's own configuration. So we don't have to keep a separate Doxy file in sync with the build. The project name is nanoMMO, and the brief is the name of the series. The output directory goes inside the build folder, along with everything else that's generated. Use md file as main page makes the README the front page, so the docs open on how to build the project. Extract all documents everything, even code that doesn't have comments yet, so a new function shows up in the docs right away. The tree view moves the navigation into a sidebar, as the theme's sidebar layout expects. And it expects the two settings after it as well, disable index and full sidebar. The colour style stays on light, since the theme brings its own dark mode. The extra stylesheets are the theme's two CSS files, from the folder FetchContent downloaded it into. Last, doxygen add docs creates a target called docs, built from the README and the server's sources. In the Dockerfile, Doxygen joins the packages in the toolchain. That changes the toolchain's layer, so the next build installs everything once more, and from then on it comes from the cache. A new docs build stage starts from the build stage, and builds the docs target. Then a final stage, docs, starts from scratch, which in Docker means a completely empty image. It copies in nothing but the HTML, from the docs build stage. We don't need an operating system around a folder of web pages. And an empty image lets us take just the files out of Docker. And let's make sure we document all of this, for our own good. In a few months, we won't remember how each piece fits together, and neither will anyone who clones the repo. So we need to ensure the README explains how to build, run and test the server, and how to generate the docs, with or without Docker. The output folder is called site, and git ignores it, so generated files don't get committed. Docker ignores them as well, as they're not needed in the final image.

41:57 With dash dash output, Docker copies the files of the final stage out of the build, and doesn't produce an image. What we get is a folder of plain HTML, which we can host anywhere we like.

42:10 The README has become the front page, so we do not need to maintain separate instructions for the project. We get search and navigation in the sidebar for free, which is great. Our lonely function has its own entry, under the nanommo namespace. Its description comes from the doc comment in our header, along with its signature, status or and all. And since the docs are generated from the code whenever we build, they stay up to date with it.

CI with GitHub Actions

42:37 Finally, continuous integration, which means each push gets built and tested automatically, on a machine that isn't ours. Before the workflow, one more Docker stage, called lint, which checks that the code follows the style guide. It starts from a slim Python image, not from our toolchain, as both tools it needs come from pip, Python's package installer. And we pin both of them: clang-format 18.1.3, which is the version Ubuntu 24.04 ships, and cpplint 2.0.2. The work dir is called nanommo, and the comment over it says why. Cpplint names each header guard after the path from the folder above this one. So the folder is named after the project, to give us nanommo server tick h. Then this copy command brings the code in, and find lists all the C++ sources and headers in the server folder. X args hands that list over to clang-format, and dash dash dry run reports what it would change. And dash dash W error turns any difference into an error, so the stage fails if even a single file isn't laid out the way our style file says. Then cpplint goes through the server folder, recursively, with the folder above as its root, and quiet prints nothing but the problems. It checks what clang-format can't see, such as the header guards, the order of the includes and where each one points. If either tool finds a problem, the stage fails, and so does the Docker build. Next to it goes a small file, CPPLINT dot cfg, which is where cpplint reads its settings, for all the folders under it. Filter, with a minus in front, turns one of its checks off, legal slash copyright. That check looks for a copyright line, with the year and the owner's name, in each C++ source and header. Above it, we write down why: the licence is in the LICENSE file, at the top of the repo. So the files don't each start with a copy of it. Cpplint picks these settings up on its own, so the command in our Dockerfile doesn't need another flag. GitHub Actions picks up workflows from the workflows folder under dot github, and they're written in YAML. Ours is called CI, and the on section says when it runs, which is on pushes to main, on pull requests, and on demand. On demand is what workflow dispatch means, and it adds a button on GitHub to run it by hand. Then come the jobs, starting with the build job, which runs on GitHub's latest Ubuntu machine. Its first step checks out the code, with GitHub's own checkout action. Then come the commands a developer would run by hand, each as a named step, so the log on GitHub reads like a checklist. We check the code style first, as it's the quickest to fail. Then the Docker test build, and then the server image, which CI builds again from nothing, so we know it still builds on a clean machine. And then the docs, with dash dash output into the site folder. And at the end, upload pages artifact packs that site folder up and hands it over to the next job. That second job, docs, deploys the docs to GitHub Pages, and it runs on main, after the build job. And it gets no more permissions than it needs, which here means two of them. Pages write lets it publish to Pages, and ID token write lets it prove its identity to GitHub while doing so. The environment is GitHub Pages, and its URL is the address the deploy step reports, so GitHub shows a link to the docs next to each run. The deploy step is GitHub's deploy pages action, which publishes the folder the build job uploaded. We document the new check in the README too, so that we remember to run it before we push. And a short section says it plainly: the code follows Google's C++ style guide, clang-format lays it out, and cpplint checks the rest. So, the docs job has two conditions, and first, it needs the build to pass, so broken code doesn't get its docs published. And it runs on main and nowhere else, so a pull request can't publish docs for code that isn't merged yet. As such, the published docs match the code of the latest episode. And CI runs nothing more than the Docker builds you'd run on your machine. So when CI fails, you can reproduce it locally, and you don't have to guess what went wrong.

Wrap-up

46:59 So, from now on, each change is going to be built, tested and documented automatically, whether on GitHub, a server or a new dev machine. And that's our project set up in a more scalable way, even if it is a solo project for now. And we are ready to start working on the fun parts, now that many of the logistics are out of the way.

47:19 This is going to be an evolving project, so I'd love to hear from you. Let me know in the comments which direction you'd like the game to take, and which parts of the engineering you'd like us to go deeper on. And if you want to follow along as the project grows, subscribe to the channel. I hope you find this useful, and thanks for watching.