Our C++ MMORPG's client runs in a web browser, built as WebAssembly with Emscripten. A web CMake preset builds the client with Emscripten, with protoc built for the computer, as WebAssembly can't run there, and leaves out what needs sockets, which a page can't open. Then three things a browser does differently stop it on the way: a loop that never hands the browser its turn, shaders in desktop GLSL that WebGL 2 won't take, and reading a texture back in a format WebGL doesn't have. After those, the login screen draws in a tab. This is episode 76 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
Topics: Graphics
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep076/end.
Transcript
Intro
0:00 A proper grey Manchester day on Oxford Road, so a good one to stay in and write some code!
0:06 Welcome back to episode seventy-six, where our game's client goes somewhere new: a web browser, built as WebAssembly. A browser does a few things quite differently from a computer, and we're going to bump into three of them on the way. But first, here's where we'll be by the end.
0:22 Our client, the game's own C++ code, runs in a browser tab, built as WebAssembly, with the login screen we know from a computer. Logging in can't work yet, as a page has no way to reach our servers, but the rest of the client is all there.
0:38 The game's code is open source, and the series' website links to it on GitHub, with a page for each episode, where you can browse the code at each step.
Last time
0:46 A quick reminder of where we left off, first. The red-team client learnt to trade last time, and tried to keep what it gave away. Swap moved its sword once its partner was ready, and run left the moment the trade went through, and each turned two swords into three. Now, what's offered stays where it is until the trade's over, and the trade checks it's all still there before it gives anything, and both bags are saved together, in one Redis transaction.
Today
1:13 Today, the client is a window on a computer, which raylib draws with OpenGL. It logs in over TLS, and plays the world over TCP and UDP. A page in a browser can't open a TCP or a UDP socket, and it draws with WebGL, a cut-down OpenGL of its own, so a few things have to give.
1:33 Emscripten compiles C and C++ to WebAssembly, which all the major browsers run, and gives us the C and C++ standard libraries, and OpenGL ES on top of the browser's WebGL. I think it's quite a remarkable piece of work. Our build runs protoc, which has to run on this machine, while everything else becomes WebAssembly. A page can't open sockets, so the client leaves out what talks to the servers, for now. Then the browser gets in the way three times: a loop that doesn't hand it a turn, shaders written for desktop OpenGL, and a texture read back in a format WebGL doesn't have. All right, let's get started, with the build and its preset.
A web preset
2:12 We start in CMake presets, where the web build gets a preset of its own, beside the ones from episode seventy-three. It's called web, and its display name says what it's for: the client in a browser, configured through emcmake. Emcmake is Emscripten's wrapper for CMake, which hands CMake Emscripten's toolchain file, so the preset doesn't need to know where Emscripten lives on each machine. It builds with Ninja, into a build web folder, like the presets other than release, and as a release build, as whatever we build, a browser has to download before the game can start. Its one cache variable of our own says where to find protoc: the one the release preset builds, in the build folder, for this machine, which we'll come back to in a moment. And a build preset of that name builds the client, as that's all a browser runs. In the top CMake file, the version goes up to zero point seventy-six. Emscripten's toolchain file sets the variable emscripten, so that's what the build checks. For a browser, raylib's platform is the web, drawing with OpenGL ES three, which is what WebGL two is. Both are raylib's own cache variables, and we force them. With Emscripten, raylib picks the web on its own, but with OpenGL ES two, which is WebGL one, so we ask for three. Then protobuf: built with Emscripten, protoc, the compiler that turns our proto file into C++, would be WebAssembly too, and the machine doing the build couldn't run it. So the web build leaves out protoc, protobuf's runtime written in C, which we don't use, and protobuf's tests. Protobuf generate still needs a protoc, though, to make the C++ for our messages. In its place, there's a cache variable for a protoc built for this machine, which the preset points at the release build's, as that one comes from the protobuf we fetch here. If there's no file there, configuring stops, with a message that says to build the release preset first. Otherwise, it becomes protobuf colon colon protoc, an imported executable at that path. That's the target protobuf generate runs, so its call in the protocol's CMake file works as it did, which I quite like. Next, what the servers and the tools need goes inside if not emscripten: Tracy, Prometheus, hiredis, the JSON and HTTP libraries, MySQL's client, sodium and OpenSSL, down to OpenSSL's find package. The bot, the red-team client and the cinema tool build on a computer and nowhere else, and so do the API docs.
4:43 Next, the libraries the client links, and what each of them leaves out in a browser. In the protocol's CMake file, logging in and TLS come out of the library's list of sources, and what's left is what a browser can build. They go back in on a computer, along with OpenSSL, as they need sockets, which a page can't open. The rest of what the library links, protobuf, Abseil and asio among them, stays for both. In a browser, the file stops before the protocol's tests, which run on this machine. The server's CMake file starts with the two libraries the client shares with the server, the bag's rules and walking, so in a browser, it stops after those, before the servers. In the client's, the connection comes out of the core library's sources. In a browser, the core gets servers web, which we're going to write in a minute, and on a computer, the connection and the servers, over the network. Which of those files gets built decides which servers the client has, so the client's code doesn't need an if of its own. Then, below the client's program, a block for the browser and nowhere else. For a browser, the client's suffix is dot HTML, so Emscripten writes a page around it, with the JavaScript that starts it and the WebAssembly module beside it. The client reads its content, its fonts and its models from folders beside the program, and a page has no folders, so each of them is preloaded. They're packed into a data file, which the page loads into a file system of its own, at the paths the client reads them from. Each one starts with shell colon, as CMake would otherwise take the repeated flag for a duplicate, and keep the first. The music is licensed, so it stays out. The link options give raylib Emscripten's GLFW, and WebGL two and no other version, with full ES three, which fills in what OpenGL ES three has and WebGL two leaves out. Then memory that can grow, a stack of a megabyte, and the preloads. After those, the file stops, as the sound player, the benchmark and the tests run on this machine.
Behind two interfaces
6:47 Now, on to the client's own code, starting with its world. Main keeps the connection to its world server in a variable, and reads everything from it, so the seam goes there: a header file called link. We bring in c std int, deque, optional and vector, and our protocol. A link is where the client's world comes from, and where what the player does goes. Today there's one kind, a world server over the network, in the connection. It's an interface, so it gets a virtual destructor, and each of its functions is pure virtual. Poll takes in whatever's arrived, without waiting, send sends the player's input, and connected says whether we still are. World is the newest world, chat is the newest lines said in it, oldest first. Whole says which world came whole last, by when it was sent, for the server to leave out what hasn't changed since, as in episode seventy. Move is where the world's instance told us to go, when it hands its players over. Then our bag, what we carry and wear, as the world last sent it. Our quests come next, the ones we've taken and how far along each one is, our guild, with an empty name for none, and our trade, from the last two episodes, with nobody in it for none. Take events hands over what happened near us since the last time, oldest first, such as a blow or a death, as each event comes once. And take invite hands over the guild that asked us to join since the last time, once. That's everything the connection had in public, apart from how it's made, so main won't be able to tell what's behind a link. The connection is still made with create, over TLS, which stays with the connection. In the connection's header file, we include the link, and the connection becomes one, final, as nothing derives from it. Above it, we write what it is: a world server, over TLS, with the worlds over UDP or TCP. Its create function stays as it is, as how a connection is made doesn't belong in a link. Then each of its functions stays as it was, marked override, so the compiler checks that it overrides one of the link's, and stops the build if a name or a type drifts apart from the interface. Their comments go up to the link, which is where someone reading the client will look for them first, so the connection's header gets a lot shorter, with a line for each function.
9:09 What logs in and enters a world goes behind an interface too, in a header file called servers. It brings in memory and string, Abseil's status or, the link and our protocol. Servers are the login server and the worlds it lists, over the network. In a browser, which gives us no sockets, each of them says why it can't be reached. Create makes the servers, with the login server at a host, and the worlds sent over UDP or TCP, or returns why not, such as a certificate that won't load. Which servers it makes depends on the source file the build links, so main doesn't need an if around it. Then the virtual destructor, and ask, which sends the login server a request, to log in, to make an account or a character, or to enter a world, and returns its answer, or why there's none. Enter takes us into a world, from the login server's list, as the character a token's for, and returns its link. Move goes to the world's instance that the last one handed us over to, when a world moves its players to a new instance. Each returns a status or, as the guide we follow doesn't use exceptions, so an error comes back as a value, with words the login screen can show. In a browser, servers web is the whole of it. In an unnamed namespace, no servers is the servers for a page, which can't open a socket, so there's no server to reach from one. Ask returns unreachable, whatever the request it's given. Enter does too, whatever world it's asked for, and so does move, whatever the instance. Their parameters go unnamed, as none of them is used. Unreachable is a private, static function, which returns an unavailable error, saying that a browser has no way to the servers yet. Unavailable is Abseil's code for a service that can't be reached right now, which is also what logging in gets on a computer when the server's down. And create, in a browser, makes no servers, ignoring the host and the transport, as there's nothing to reach.
11:06 On a computer, the servers' source file has the code main had, moved over, so not much in it is new. It brings in what it uses: Abseil's status and str cat, asio's TLS context, the connection, our login client, the settings and TLS, most of which main brought in before. The login server's port moves here, and so does this machine, which says whether a host is the machine it's said on, by its name or its address. Network servers are what a computer gets, the servers over the network. The constructor takes the login server's host, whether the worlds come over UDP, and the TLS context, and keeps them. Ask logs in over TLS, to the login server's port, as main did. Enter creates a connection to the world, at the host and port the login server listed for it, with the TLS context, the token and the transport. If that fails, it keeps the hint main gave, as a world started without its public host says it's at localhost, which from another machine is that machine, and not the world's. So the error starts with why the connection failed, in the words of its status. If the world it's entering says it's on this machine, while the login server's host isn't, it adds the world's name and where it says it is. Then it says that its server should start with nanommo public host, set to the login server's host. That goes back as an unavailable error, for the login screen to show. Otherwise, the connection goes back as a link. Move is a lot like it, without the hint, as the instance we move to is wherever the world said. It creates a connection to the new instance, at its host and port, with the token the move came with, and returns the error if it can't, the way enter does. In private, network servers keep the host, the transport and the TLS context, and last comes create, for a computer. It loads the client's TLS context, as main did, which trusts the game's certificate authority, from its setting, or from the file in the TLS folder, and returns the error if it can't. Then it makes the network servers with that context, and hands them back.
13:10 Then main, which brings in the link and the servers' header, in place of the connection, the login client and TLS. The login server's port goes, and so do the helpers for logging in, for telling whether a host is this machine, and for entering a world, as that's the job of the network's code now. At the start, where main loaded the TLS context, it creates the servers, with the host and whether the worlds come over UDP, and stops with the error if it can't, as it did for TLS. The connection we play through, and the next one while we move between instances, become links, which on a computer are connections. Entering a world prints which one and as whom, as the helper did, then asks the servers. It keeps the link they hand back, or shows why not on the login screen, with the words the helper used, and we stay there. A move to another instance asks the servers for its link too, which on a computer is the next connection. And the login screen's requests go to the servers' ask, whose error is shown the way it was, before the screen looks at the answer. Last, the window, which asks raylib for all the pixels of a high-DPI screen, so a Retina display gets a sharp picture. In a browser, raylib draws a high-DPI canvas into a quarter of it, which on a Retina screen leaves the game in one corner, so there the page draws at its own size, and the browser scales it up. On a computer, the flag goes on as it always has. In a browser, the canvas then has as many pixels as its size, which looks a little softer on a Retina screen, and I think that's a fair price for a game that draws the whole picture.
14:42 Let's build it and see what happens, with the release build first. With protoc built for this machine, emcmake configures the web build, and it builds the client as WebAssembly, along with Abseil, protobuf and raylib, which takes a few minutes the first time. What a page loads is four files: the WebAssembly module, the JavaScript that starts it, the page, and the data file with the content, the fonts and the models the client reads.
15:08 Let's open it in a browser, served from the build folder. The page stops before it draws anything, with an exception, and sends us to the JavaScript console. There, Emscripten asks us to compile the program with async support, to use asynchronous operations such as emscripten sleep. Our main loop runs until the window closes, and a browser doesn't draw anything until the page's code hands control back to it.
Three things a browser does differently
15:30 Emscripten has a way to keep the loop as it is: Asyncify, which lets the code pause where raylib waits for the next frame, hand the browser its turn, and carry on from there. raylib's web platform already calls emscripten sleep in window should close, once a frame, and that's the call the console named. So two link flags are enough: Asyncify, and sixty-four kilobytes for the call stack it saves while the browser has its turn. The loop stays readable, at the price of a larger module.
15:58 Now the login screen draws, as the loop gives the browser its turns. Under it, the page prints raylib's log, and each of our shaders fails to compile, with an invalid version directive. They're written for OpenGL three point three, and WebGL two takes GLSL ES three hundred, which needs its own version line, and a precision for its floats.
16:19 The two languages are close enough that one helper does it, in a header file called glsl, which brings in raylib, for its shader type. It declares load GLSL, which takes a vertex and a fragment source, written in GLSL three thirty, as all of ours are, and returns the shader. In a browser, each source gets the version line and the precisions WebGL two wants. A null source is raylib's own, as with load shader from memory, which our post processing uses for its vertex shaders. In the source file, we bring in raylib, optional, string and string view, and start with a function of our own in an unnamed namespace, which works on a single source. For this GPU takes a source and returns it the way this GPU takes it. A null source stays null, as an empty optional. Otherwise, we copy it into a string, and when Emscripten is the one compiling it, we look for the desktop version line, version three thirty, at the start of the source. That line becomes version three hundred E S, followed by a high precision for floats and for ints. A fragment shader in GLSL ES has no precision for floats unless it says one, and won't compile without it. The rest of our eighteen shader sources is valid GLSL ES as it stands, so that's all it changes, and on a computer, each source goes back as it was. Load GLSL runs both of its sources through it, the vertex one and the fragment one, and hands them to raylib's load shader from memory, with null for either one that was null. Then each place that loads a shader goes through it, starting with the renderer, which brings in the new header. Its four shaders are the lit one that most of the world is drawn with, the skinned one for the characters, and the two for the outlines, still and skinned. Each is loaded with load GLSL now, where it said load shader from memory. Next, the skills' effects, whose light shader goes through it too. The post processing has four, bright, spread, combine and FXAA, each a fragment shader on raylib's own vertex shader, so their vertex sources stay null. Then the sea, which has one shader, for its waves and its colour, and the sky, with a shader for its dome, loaded through it now in the sky's constructor, and another one for its clouds. And the client's core library builds the new file, beside the others, in the client's CMake file, so all of the client's shaders load through it now.
18:42 The shaders compile now, in the browser too, and raylib's log under the canvas has no more errors in it. The browser's console has one, though: an invalid format and type combination, as the client loads the trees. It reads the tree model's texture back from the GPU to colour each face, and raylib asks for the texture's own format, which desktop OpenGL allows, while WebGL two wants these pixels read back as RGBA.
19:10 raylib already has a switch for this, in its OpenGL layer: it can read a texture back as RGBA bytes, whatever the texture's own format. So in a browser, the top CMake file turns it on, as a definition for raylib alone, and the client's code stays as it is.
19:28 And the client starts as it does on a computer. Its log has one warning left, about the music, which the browser's build leaves out, as its licence doesn't let us hand the file out to anyone who opens the page. It can't log in, as there are no servers it can reach from a page, but I think it's pretty cool to see our own C++ drawing in a browser tab.
Writing it down
19:50 Last, the game's docs, where a new page says how to build the client for a browser and how to serve it. It also says what to do about the errors you're most likely to meet, from a missing protoc to a page opened as a file. And the choice gets its decision record, number twenty-nine: the client in a browser, with Emscripten and WebGL two.
Wrap-up
20:09 Today, the client got a web preset, built with Emscripten, with protoc from this machine, and the code that reaches the servers behind two interfaces. Asyncify lets its loop hand the browser its turns, its shaders load as GLSL ES, and the trees' colours read back as RGBA, so the login screen draws in a tab.
Playing it
21:20 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.