Skip to content
ImagineWorld

Wading into WebAssembly with Rust

node_idnode-book_programming-web-assembly-with-rust_chapter-03-wading-into-webassembly-with-rust
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleWading into WebAssembly with Rust
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Wading into WebAssembly with Rust

Section titled “Chapter 3 — Wading into WebAssembly with Rust”

CHAPTER 3

Wading into WebAssembly with Rust

The first part of this book introduced you to the world of WebAssembly. You learned about its internals and its architecture, what stack machines are, and where WebAssembly fits within the larger world of web applications. You even built a mostly functioning checkers module entirely in wast, the text representation of WebAssembly instructions.

In this part of the book, you will focus not only on increasing your ability to interweave WebAssembly and JavaScript functionality, but you will also go through an introduction to Rust and you will see how you can use it to add strong types, memory safety, and elegant, expressive code to your WebAssembly modules.

In this chapter, you’ll get an introduction to Rust and get your workstation tooling set up to target WebAssembly from Rust. By the end of this chapter, you’ll build a new version of the checkers module entirely in Rust. The Rust language has a longer learning curve than other languages like Go. As such, you might want to start skimming through the official Rust book¹ to get familiar with some of the syntax coming up in the book. It’s not required, but consulting multiple reference sources is never a bad idea.

Introducing Rust

If you’re already well versed in Rust, then feel free to skip to the next section. If you’re new to it or you’d like a refresher on the core concepts of the language, then you may find this section beneficial.

Rust started in 2006 as Graydon Hoare’s personal project while he was working for Mozilla. Mozilla sponsored it in 2009 and announced it in 2010. In the history of each programming language, its genesis moment is when a

[1] doc rust-lang.org/book/ compiler written in that language is able to compile that language—a compiler inception,² if you will. For Rust, this came in 2011 and the first stable 1.0 release came in 2015.

Rust has been gaining in popularity exponentially ever since. In addition to powering Mozilla’s new browser layout engine and showing up in a number of high-visibility systems and networking open source projects, it won the “Most Loved Programming Language” award in 2016, 2017, and 2018,³ sur- passing Kotlin, Python, TypeScript, and even Go. This is Rust’s elevator pitch from the official website:

Rust is a systems programming language that runs blazingly fast, prevents seg-
faults, and guarantees thread safety.

Some of the main characteristics of the Rust language that make it appealing for building applications with WebAssembly include:

Safety

Rust doesn’t have the concept of null. Instead, any data that can be missing is represented as an Option type. This gets rid of an entire class of errors that plagues other systems languages like C and C++ and even many higher-level languages. In addition to lack of nulls, Rust will prevent your code from compiling if it could potentially create a data race, free already deallocated resources, or access something that has gone out of scope.

Expressivity

Despite being labeled as a “systems language,” Rust has a remarkably expressive syntax and includes many features that people typically laud when talking about functional programming: pattern matching, destruc- turing, streams, iterators, and much more. Combined with the concepts of traits and generics, Rust (most of the time) manages to facilitate highly readable and maintainable code.

Performance

Rust binaries are standalone, native binaries. They consume relatively little disk space, have a fairly small memory footprint, and the code gen- erally performs extremely well. Despite all of the additional safety con- straints in the language, Rust doesn’t need a garbage collector, which can often produce raw, C-like performance.

[2] en.wikipedia.org/wiki/Bootstrapping_(compilers) [3] insights.stackoverflow.com/survey/2018/#most-loved-dreaded-and-wanted Installing Rust

It’s time to start writing some Rust. The first thing you’ll need to do is follow the Installation instructions from the official Rust⁴ website. On that site, you’ll find a curl script you can run that will install rustup, the main entry point into the Rust toolchain.

Once you’ve completed the installation appropriate for your system, you should be able to interrogate the version of the Rust compiler:

Terminal window
$ rustc --version
rustc 1.30.1 (1433507eb 2018-11-07)

Rust is on a six-week release cycle for the stable toolchain, so your version will very likely be newer than the one in this book. You need to be able to successfully run rustc and rustup before continuing to the next section.

Building Hello WebAssembly in Rust

Rust’s tools intrinsically support the notion of multiple targets. You can compile for different targets without having to run the compilation on that target machine. For example, you can target an ARM architecture (e.g., Raspberry Pi) from a regular workstation.

WebAssembly manifests as a target in Rust’s toolchain. In addition to the regular six-week releases, Rust also has a nightly build that enables newer language features that haven’t yet stabilized. As of Rust version 1.30, most of the WebAssembly tools and libraries you’ll encounter in this book should build just fine on the stable toolchain.

Installing the WebAssembly Target

If you issue the command, rustup toolchain list, you’ll see a toolchain that looks something like stable-x86_64-unknown-linux-gnu (default) (this will vary by operating system). Next, you can add the WebAssembly target by typing rustup target add wasm32-unknown-unknown. This may also take some time and will get everything set up for that target. If you’re curious about all of the targets Rust supports, you can type rustup target list. This list also shows which targets are installed and which one is the default.

  1. www.rust-lang.org/en-US/install.html

Creating a WebAssembly Project

You can use Cargo, Rust’s project build tool, to create new empty projects. To create one for your first WebAssembly project, type the following:

$ cargo new —lib rustwasmhello Created library rustwasmhello project

This creates a Cargo.toml file in the rustwasmhello directory. Edit this file so that it looks like this:

rustwasmhello/Cargo.toml

[package]
name = "rustwasmhello"
version = "0.1.0"
authors = ["Your Name <[email protected]>"]
[lib]
crate-type = ["cdylib"]
[dependencies]

The only lines in this file that differ from what you get by default from cargo is the indicator that this project will expose a C-style dynamic library, which is then used by other linkers to produce a WebAssembly module:

[lib]
crate-type = ["cdylib"]

Now edit the lib.rs file that cargo created and set its contents to the following:

rustwasmhello/src/lib.rs

#![no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
x + 1
}

This code should look familiar. It’s the same code that you saw in the first chapter when you created a WebAssembly Studio project online. This project should now be ready to compile into a WebAssembly module. The first step is to tell cargo to build it (make sure you’re in the rustwasmhello directory):

Terminal window
$ cargo build --target wasm32-unknown-unknown
Compiling rustwasmhello v0.1.0
(file:///home/kevin/Code/Rust/wasmbook_text/khrust/Book/code/rustwasmhello)
Finished dev [unoptimized + debuginfo] target(s) in 0.24s

This produced a rustwasmhello.wasm file under the target/wasm32-unknown-unknown/debug folder. To see that your release build will produce a Wasm file very similar to something that you’d get building it by hand, first compile in release mode:

Terminal window
$ cargo build --release --target=wasm32-unknown-unknown
Compiling rustwasmhello v0.1.0
(/home/kevin/Code/Rust/wasmbook/khrust/Book/code/rustwasmhello)
Finished release [optimized] target(s) in 0.12s

Now you can verify that the output contains an exported function called add_one by using the wasm-objdump tool:

$ wasm-objdump -x target/wasm32-unknown-unknown/release/rustwasmhello.wasm
rustwasmhello.wasm: file format wasm 0x1

Section Details: Type:

  • type[0] () -> nil
  • type[1] (i32) -> i32 Function:
  • func[0] sig=0 <__wasm_call_ctors>
  • func[1] sig=1 <add_one> Table:
  • table[0] type=anyfunc initial=1 max=1 Memory:
  • memory[0] pages: initial=16 Global:
  • global[0] i32 mutable=1 - init i32=1048576
  • global[1] i32 mutable=0 - init i32=1048576
  • global[2] i32 mutable=0 - init i32=1048576 Export:
  • memory[0] -> “memory”
  • table[0] -> “__indirect_function_table”
  • global[1] -> “__heap_base”
  • global[2] -> “__data_end”
  • func[1] <add_one> -> “add_one” Custom:
  • name: “.debug_info” Custom:
  • name: “.debug_macinfo” Custom:
  • name: “.debug_pubtypes” Custom:
  • name: “.debug_ranges” Custom:
  • name: “.debug_abbrev” Custom:
  • name: “.debug_line” Custom:
  • name: “.debug_str” Custom:
  • name: “.debug_pubnames”

Custom:

  • name: “name”
  • func[0] <__wasm_call_ctors>
  • func[1] <add_one>

You can see that this module comes with a single function table, a default 16-page (16 * 64KB) block of linear memory, some globals, and the add_one() function that we wrote.

Congratulations, you’ve compiled your first Rust WebAssembly module. Now it’s time to learn some cool Rust features while you build out a new checkers module.

Creating Rusty Checkers

This section has a very specific goal: build a new checkers module entirely in Rust WebAssembly that conforms as closely as possible to the interface of the hand-written one from the previous chapter.

Diving into Rust is no small feat, so to keep things from getting too overwhelming, you’re going to be building something you’ve already built. Hopefully, the powerful and expressive syntax of Rust will make the game easier to reason about, and you might even be able to add features and rules that weren’t in the last game.

This new version of checkers will expose the same kinds of functions to the host (JavaScript), but you’ll also be writing some code that determines the list of valid moves, something that was just too excruciatingly painful in raw wast code to write in the previous chapter. The Rust version will also have the same concept of turns so that it can be played from a console or virtually any other kind of client.

To get started, find an empty directory and type the following:

$ cargo new —lib rustycheckers Created library rustycheckers project

Edit the Cargo.toml file in the project’s root directory as you did for the last sample to tell the build system that this is a dynamic library. Once you’ve got that set up, you should be ready to start coding. If you’re using a version of Rust version 1.31.0 or newer, then your default Cargo.toml will come with a line in the package section: edition = “2018”. This indicates the use of the “2018 edition”1 which allows for some newer (and often simpler) syntax, as well as many new features.

Make sure you remove this line from your Cargo.toml. For now, I want to focus on the core parts of Rust required to interact with WebAssembly, and will defer the use of the 2018 edition until the end of the book after you’ve had time to get used to the “regular” Rust syntax. Unless otherwise stated, all Rust samples in this book are designed to run on 1.31.0 or newer, but use the “2015 edition” syntax.

Setting Up the Board

Open up the rustycheckers/src/lib.rs file and empty it. At the bottom of the file, add the following line:

mod board;

Now add a file called rustycheckers/src/board.rs. Rust’s module system is hierarchi- cal. Wherever you add mod [module_name]; in your code, think of that module as being injected at exactly that spot in the hierarchy. This allows you to nest modules, and it fosters some really good isolation and encapsulation practices, but it can be hard to get used to for people who come from languages with implicit or directory-first module hierarchies.

Each Rust library has a single root module, the name of which is specified in the Cargo.toml file (the name setting under the [package] section). By convention the code for the root module is found in the lib.rs file, so by including mod board; in the top of lib.rs, we’re declaring a submodule named board that exists directly under the root. Elements in the board submodule can be referenced from anywhere using the rustycheckers::board prefix.

The Rust 2018 edition2 (not used until the end of this book) has more flexible rules around referring to modules.

To start writing the code to manage the game board, the first thing you’ll want to do is write some code to manage a GamePiece. In the previous chapter, game pieces were just 32-bit integers that could be bitmasked for information. Now that you’ve got a little more power to play with, you can create an enum for piece color and a struct (Rust doesn’t officially have classes, though its structs can often behave like classes) to represent a single piece:

rustycheckers/src/board.rs

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PieceColor {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GamePiece {
pub color: PieceColor,
pub crowned: bool,
}
impl GamePiece {
pub fn new(color: PieceColor) -> GamePiece {
GamePiece {
color,
crowned: false,
}
}
pub fn crowned(p: GamePiece) -> GamePiece {
GamePiece {
color: p.color,
crowned: true,
}
}
}

Don’t worry about the derive macros for now. They just auto-generate some boilerplate code to deal with common things most data structures in Rust need, like the ability to be compared, copied, cloned, and printed out for debug purposes.

This game piece has two functions: new() and crowned(). The first creates a new game piece of a given color, while the second creates a new piece of a given color with a crown on top. The latter function will come in handy when you want to crown a piece on the board.

Next, you can create the concept of a Coordinate. In raw WebAssembly, you didn’t have anything to represent this other than just numbers. Creating a struct for a grid coordinate here should help simplify the code, reduce the number of parameters that get passed around, and generally make things more readable. Also, as you’ll see, it’s a great place to stick some preliminary logic to support game rules:

rustycheckers/src/board.rs
#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Coordinate(pub usize, pub usize);
impl Coordinate {
pub fn on_board(self) -> bool {
let Coordinate(x, y) = self;
x <= 7 && y <= 7
}
}
pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> {
let mut jumps = Vec::new();
let Coordinate(x, y) = *self;
if y >= 2 {
jumps.push(Coordinate(x + 2, y - 2));
}
jumps.push(Coordinate(x + 2, y + 2));
if x >= 2 && y >= 2 {
jumps.push(Coordinate(x - 2, y - 2));
}
if x >= 2 {
jumps.push(Coordinate(x - 2, y + 2));
}
jumps.into_iter()
}
pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> {
let mut moves = Vec::new();
let Coordinate(x, y) = *self;
if x >= 1 {
moves.push(Coordinate(x - 1, y + 1));
}
moves.push(Coordinate(x + 1, y + 1));
if y >= 1 {
moves.push(Coordinate(x + 1, y - 1));
}
if x >= 1 && y >= 1 {
moves.push(Coordinate(x - 1, y - 1));
}
moves.into_iter()
}

① An example of destructuring to pull the x and y values out of a Coordinate structure.

② Produce an iterator of Coordinates of all possible jumps from the given coordinate.

③ Produce an iterator of Coordinates of all possible moves from the given coordinate.

The jump_targets_from() function returns a list of potential jump targets from the given coordinate. The move_targets_from() function returns a list of potential move (adjacent space) targets given the current coordinate location. These functions will be used to calculate a list of valid moves for each turn. Note that in the raw WebAssembly version of checkers, we just did a quick, naive check to verify that a move was valid. We can up the complexity a little here.

The code pub struct Coordinate(pub usize, pub usize) defines what’s called a tuple struct. Rather than this struct having named fields, it instead represents a strongly- typed tuple with public fields. You can access those fields with tuple accessors .0 and .1, but most of the code in this chapter uses destructuring and pattern matching to get at the x and y values in a more human-friendly fashion. In this case, each of the two anonymous fields in this tuple struct are of type usize, which is the data type Rust uses for vector indexes, allowing code to be more safe and portable across 32-bit and 64-bit architectures. Rust’s standard library is replete with usages of this data type.

The list of potential target squares for a checker piece to move is pretty small. The preceding code creates iterators that expose these potential squares to callers. As you’ll see shortly, iterators can be chained with functions like map(), zip(), and filter() to make for some fairly expressive syntax to define game rules.

Finish out the board.rs module by creating a struct that represents a game move. Here you can see one place where it was simpler to access the tuple values as fields rather than using a pattern match:

rustycheckers/src/board.rs

#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Move {
pub from: Coordinate,
pub to: Coordinate,
}
impl Move {
pub fn new(from: (usize, usize), to: (usize, usize)) -> Move {
Move {
from: Coordinate(from.0, from.1),
to: Coordinate(to.0, to.1),
}
}
}

One more thing before getting into the details of writing the game rules: references. In the coordinate code, &self is a reference to the struct. In Rust, any- thing prefixed with & is a reference. Any assignment that isn’t a reference is a move. Unless you explicitly treat something as a reference, ownership will be transferred during an assignment, meaning the value in the “old” variable will no longer be there (and you’ll get a compile error if you try to access it). This “move by default” pattern takes a bit of getting used to when learning Rust, and if the difference between move and reference is a little murky, you

might want to take a minute and do a little background research on Rust’s concept of ownership.7

Writing the Engine Rules

Now for the fun part… open up rustycheckers/src/lib.rs and add the following line of code to the bottom:

mod game;

Create an empty file called rustycheckers/src/game.rs. This will give you a nice clean space to work on the game rules, and it illustrates a pretty common pattern in idiomatic Rust: modularization. I am partial to small, purposeful files that are easy to read and understand, and I feel like I spend more time thinking about modular structure in Rust than I have in other languages I’ve used (which is a good thing).

The first thing you’ll want is a struct to anchor all of the game engine function- ality to the same place, and to give you a spot to maintain game state. If you hadn’t noticed, thus far you haven’t done anything remotely related to WebAssembly, and that’s deliberate. You’ll want to keep the WebAssembly border clear of debris and make sure that you are free to build a game on this side of the Wasm/Rust border with very little crossover or coupling.

Patterns like this where we actively avoid tightly coupling two separate con- cerns allow our code to be easier to read, easier to maintain, and easier to add more features and use for unintended consumers in the future without modification. This kind of tactic is often referred to as a facade or an Anti- Corruption Layer:

rustycheckers/src/game.rs

use super::board::{Coordinate, GamePiece, Move, PieceColor};
pub struct GameEngine {
board: [[Option<GamePiece>; 8]; 8],
current_turn: PieceColor,
move_count: u32,
}
pub struct MoveResult {
pub mv: Move,
pub crowned: bool,
}

In the previous chapter, you managed game state by manipulating bytes with direct memory access. Here, not only do you have a traditional two-dimensional

  1. doc.rust-lang.org/book/ch04-00-understanding-ownership.html array, but the type of the piece is Option. It will make your code eminently more readable when an empty square is represented by the match-friendly keyword None rather than just a 0.

Remembering that the functionality for a struct resides in an impl block, start writing the code to initialize the game engine and its state inside the impl GameEngine block:

rustycheckers/src/game.rs

impl GameEngine {
pub fn new() -> GameEngine {
let mut engine = GameEngine {
board: [[None; 8]; 8],
current_turn: PieceColor::Black,
move_count: 0,
};
engine.initialize_pieces();
engine
}
pub fn initialize_pieces(&mut self) {
[1, 3, 5, 7, 0, 2, 4, 6, 1, 3, 5, 7]
.iter()
.zip([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2].iter())
.map(|(a, b)| (*a as usize, *b as usize))
.for_each(|(x, y)| {
self.board[x][y] = Some(GamePiece::new(PieceColor::White));
});
[0, 2, 4, 6, 1, 3, 5, 7, 0, 2, 4, 6]
.iter()
.zip([5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7].iter())
.map(|(a, b)| (*a as usize, *b as usize))
.for_each(|(x, y)| {
self.board[x][y] = Some(GamePiece::new(PieceColor::Black));
});
}
}

The &mut self parameter to initialize_pieces() indicates that it can only be used by a mutable reference to a game engine. Further, it’s a sign to any developer that this function mutates state. In the engine’s constructor, we create a mutable instance of the GameEngine struct, and then call initialize_pieces() to set the board up for play.

This function might seem confusing if you’re not used to Rust syntax. In the previous chapter, you initialized the board by manually placing every single piece with a different line of code. In the real world, we have tools like iterators and filters that can help us with these tasks.

The iter() function converts an array of known x- or y-coordinate positions into an iterator, which can then be zipped (a function that merges two iterators into an iterator of tuples) with another iterator via the zip() function. Next, the map() function converts the coordinates from i32 to usize (the data type for array indexes in Rust—remember Rust doesn’t have implicit conversions). For each one of the newly zipped (x,y) coordinates, you can set the appropriate black or white piece using Rust’s anonymous function notation.

The next bit of code takes a top-down approach and contains the logic to move pieces on the board. If you enter this by hand right now, it won’t compile because you’re missing a bunch of helper functions. But I think it’s easier to understand what’s happening by looking at this logic first:

rustycheckers/src/game.rs

pub fn move_piece(&mut self, mv: &Move) -> Result<MoveResult, ()> {
let legal_moves = self.legal_moves();
if !legal_moves.contains(mv) {
return Err(());
}
let Coordinate(fx, fy) = mv.from;
let Coordinate(tx, ty) = mv.to;
let piece = self.board[fx][fy].unwrap();
let midpiece_coordinate = self.midpiece_coordinate(fx, fy, tx, ty);
if let Some(Coordinate(x, y)) = midpiece_coordinate {
self.board[x][y] = None; // remove the jumped piece
}
// Move piece from source to dest
self.board[tx][ty] = Some(piece);
self.board[fx][fy] = None;
let crowned = if self.should_crown(piece, mv.to) {
self.crown_piece(mv.to);
true
} else {
false
};
self.advance_turn();
Ok(MoveResult {
mv: mv.clone(),
crowned: crowned,
})
}

The first thing move_piece() does is compute the list of legal moves based on whose turn it is and the state of the game board. If the intended move isn’t in the list of legal moves (this is why you need the derive macros to generate equality tests for the structs), then the function quits early.

There’s a line of code in this function that uses the unwrap() function. Ordinarily we shy away from this, but since we know that accessing that one piece will work because of validation, we can get away with it. In a production application and adhering to defensive coding practices, we would probably validate this instead of calling unwrap().

Next, the engine checks to see if there’s a game piece to jump on the way from the source to the destination coordinate. If there is, the jumped piece is removed from the board. The engine then performs the piece move by setting the old location to None. Finally, the function finishes by checking if it should crown the piece after it moved. Can you imagine how hard it would be to read or write the jump logic code in raw wast?

The move_piece() function returns a Result. Similar to an Option, a Result can have two values: either Ok(…) or Err(…). Using a pattern match on a result is a clean way to handle and propagate errors back up the call stack. Pattern matching against optional values or result types is something that you might be familiar with if you’ve developed with functional programming languages or used functional programming styles.

Computing Legal Moves

Computing the list of legal moves is the most complicated thing this Rust code does. In the following code, legal_moves() loops through every space on the board and then computes a list of valid moves from that position. This way, this function returns a list of every valid move that the current player can make (rusty checkers doesn’t support multi-jumps to try to keep the codebase legible and book-friendly).

rustycheckers/src/game.rs

fn legal_moves(&self) -> Vec<Move> {
let mut moves: Vec<Move> = Vec::new();
for col in 0..8 {
for row in 0..8 {
if let Some(piece) = self.board[col][row] {
if piece.color == self.current_turn {
let loc = Coordinate(col, row);
let mut vmoves = self.valid_moves_from(loc);
moves.append(&mut vmoves);
}
}
}
}
}

moves

}
fn valid_moves_from(&self, loc: Coordinate) -> Vec<Move> {
let Coordinate(x, y) = loc;
if let Some(p) = self.board[x][y] {
let mut jumps = loc
.jump_targets_from()
.filter(|t| self.valid_jump(&p, &loc, &t))
.map(|ref t| Move {
from: loc.clone(),
to: t.clone(),
}).collect::<Vec<Move>>();
let mut moves = loc
.move_targets_from()
.filter(|t| self.valid_move(&p, &loc, &t))
.map(|ref t| Move {
from: loc.clone(),
to: t.clone(),
}).collect::<Vec<Move>>();
jumps.append(&mut moves);
jumps
} else {
Vec::new()
}
}

There’s an interesting pattern used in the valid_moves_from() function that uses the iterator functions created earlier and chains those results through filter(), map(), and collect():

let mut moves = loc
.move_targets_from()
.filter(|t| self.valid_move(&p, &loc, &t))
.map(|ref t| Move {
from: loc.clone(),
to: t.clone(),
}).collect::<Vec<Move>>();

This takes all of the potential move targets and filters them based on whether that target is a valid move for a given game piece, at a given location, for a given target. Then, for each of the valid moves, we convert the coordinate target (indicated by the ref t in the lambda, showing that we’re taking the lambda’s sole parameter by reference) into a Move struct. Finally, the resulting iterator is converted into a vector via collect() and the “turbofish” syntax collect::<Vec>().

[8] doc.rust-lang.org/book/2018-edition/appendix-02-operators.html?highlight=turbo#non-operator-symbols

The valid_moves_from() function produces a list of Move instances that are valid from the given coordinate. In formal checkers, if a player has both a valid jump and a valid move, they must perform the jump. This method is struct- ured to place valid jumps first so that you can add that kind of strict rule checking if you want. You could also add a new property to the Move struct to tag a move as a jump, which might help in adding multi-jump capabilities to the game.

You still haven’t added anything to the code that deals with WebAssembly. In the interest of saving a few trees (or bytes), the full listings for all of the various helper functions like valid_move() aren’t in the book. If you want the full source for board.rs and game.rs, you can grab it from the book’s full example code. You’ll also see several unit tests in the full version of the code that shows how you can test this code without crossing the WebAssembly boundary.

Coding the Rusty Checkers WebAssembly Interface

Section titled “Coding the Rusty Checkers WebAssembly Interface”

So far you’ve been coding in pure Rust without any indication that the game will eventually be available as a WebAssembly module. This is actually a good practice to adopt, and I’m a very big fan of keeping the boundary-crossing code at the edges, leaving the domain-specific code (in our case, checkers) in its own separate module to test in isolation.

You’ll need to do two things to make this code work with a JavaScript host. First, you’ll need to export functions that can be called by the host. Second, you’ll need to import functions that you want to be called by the WebAssembly code on the host. This follows the same pattern as the previous chapter, but with stricter boundaries.

First, add the following two dependencies to your Cargo.toml file:

[dependencies]
mut_static = "5.0.0"
lazy_static = "1.0.2"

Rust is ruthless about its control over shared mutability, and here arises a conflict in philosophies. The previous raw WebAssembly module had global, module-wide state. How can you accomplish the same thing in Rust without violating all of its rules about sharing and mutability?

You’re going to use something called a lazy static to create a globally available instance of the GameEngine struct. This instance will then be used by all of the functions you’re exporting out of the WebAssembly module. The following code creates a lazy static game engine. Put it at the top of lib.rs:

rustycheckers/src/lib.rs

#[macro_use]
extern crate lazy_static;
use board::{Coordinate, GamePiece, Move, PieceColor};
use game::GameEngine;
use mut_static::MutStatic;

lazy_static! {

pub static ref GAME_ENGINE: MutStatic<GameEngine> =
{ MutStatic::from(GameEngine::new()) };
}

In nearly every single case when writing Rust code, I would vehemently and aggressively push against the use of global mutable state. It goes against everything that Rust stands for, is bad for the environment, and makes puppies cry. However, in our edge case, like providing a mutable state store for a WebAssembly module, it is pretty much the only way to make the module work.

If you recall from the previous chapter, you exported a couple of functions out of your wat file to allow the host to query the state of the game: get_piece() and get_current_turn(). You’ll rewrite those now:

rustycheckers/src/lib.rs

#[no_mangle]
pub extern "C" fn get_piece(x: i32, y: i32) -> i32 {
let engine = GAME_ENGINE.read().unwrap();
let piece = engine.get_piece(Coordinate(x as usize, y as usize));
match piece {
Ok(Some(p)) => p.into(),
Ok(None) => -1,
Err(_) => -1,
}
}
#[no_mangle]
pub extern "C" fn get_current_turn() -> i32 {
let engine = GAME_ENGINE.read().unwrap();
GamePiece::new(engine.current_turn()).into()
}

To maintain the safety of the globally mutable game engine, you have to acquire a read or write lock with the read() or write() functions.

Since there’s a chance that acquiring one of these locks can fail, those functions return Results. You have to handle results one way or another, and here calling unwrap() either grabs the value within Ok(…) or crashes the program upon failure. A tip learned from painful experience: in production-grade applications, seek out and destroy all unwrap()s with very few exceptions. Being unable to acquire a read or write lock on your game’s sole source of state is, however, something that is exceptional and should produce a trap for the host.

The raw version of the checkers module you wrote returned the current piece and the current turn owners both as i32 values. As mentioned at the beginning of the chapter, you’ll adhere to this contract wherever possible. If you look at both of these functions, you may notice that they both make use of a function called into().

The into() function shows one of my favorite aspects of Rust in action. Anything that implements the generic trait called Into for a given type can be convert- ed into that type. While Rust doesn’t have implicit conversions, its explicit conversions are quite powerful. To convert a game piece into a 32-bit integer, you just need to implement Into:

rustycheckers/src/lib.rs

const PIECEFLAG_BLACK: u8 = 1;
const PIECEFLAG_WHITE: u8 = 2;
const PIECEFLAG_CROWN: u8 = 4;
impl Into<i32> for GamePiece {
fn into(self) -> i32 {
let mut val: u8 = 0;
if self.color == PieceColor::Black {
val += PIECEFLAG_BLACK;
} else if self.color == PieceColor::White {
val += PIECEFLAG_WHITE;
}
if self.crowned {
val += PIECEFLAG_CROWN;
}
val as i32
}
}

The fact that the self variable here is not a reference means that the GamePiece will be consumed when converted into an integer. In other words, if you try to access a game piece after you convert it into an integer, you’ll get a compi- lation error with a message like “move after use,” and an arrow pointing to the spot where you used it and where it moved. Rust’s compiler errors are some of the most verbose and helpful I’ve ever seen.

There are some cool Rust libraries that help you do bit flags, but aren’t really needed for this sample. Next, add a function to let players move:

rustycheckers/src/lib.rs

#[no_mangle]
pub extern "C" fn move_piece(fx: i32, fy: i32, tx: i32, ty: i32) -> i32 {
let mut engine = GAME_ENGINE.write().unwrap();
let mv = Move::new((fx as usize, fy as usize), (tx as usize, ty as usize));
let res = engine.move_piece(&mv);
match res {
Ok(mr) => {
unsafe {
notify_piecemoved(fx, fy, tx, ty);
}
if mr.crowned {
unsafe {
notify_piececrowned(tx, ty);
}
}
}
Err(_) => 0,
}
}

The move_piece() function (it can’t be called move() because that’s a reserved word in Rust) just forwards the call to the game engine and examines the result. It does, however, call the two notification functions that need to be imported from the host: notify_piecemoved() and notify_piececrowned(). These functions are both wrapped inside an unsafe block because Rust can’t guarantee that the code on the other side of the host-module barrier meets Rust’s standards for safety. Any extern function must be wrapped in an unsafe block to invoke it. It’s a best practice to keep unsafe blocks as small as possible, wrapping only the thing you need to invoke.

Unsafe here shouldn’t instill a sense of fear in you. This kind of unsafe is just an indicator the code you’re invoking is unknown to the Rust compiler, so it can’t give you the safety guarantees that you get from regular compiled Rust code.

Importing functions from a host is done by including their signatures in an extern block:

rustycheckers/src/lib.rs

extern "C" {
fn notify_piecemoved(fromX: i32, fromY: i32,
toX: i32, toY: i32);
fn notify_piececrowned(x: i32, y: i32);
}

Finally, you can compile this code for the WebAssembly target and create the stripped binary file suitable for use with JavaScript. The following commands will build your WebAssembly module and place the trimmed-down, release version in a demo directory (you’ll need to create this directory yourself):

Terminal window
$ cargo build --release --target wasm32-unknown-unknown
Finished release [optimized] target(s) in 0.01s
$ cp target/wasm32-unknown-unknown/release/rustychekers.wasm demo/

At this point, you’ve made a stack (definitely not a heap) of progress. You’ve got a Rust library that compiles to WebAssembly, imports notification functions, and exports functions that will let a host play a game of checkers while maintaining internal state. Next, you’ll see how that works by testing out the game in a JavaScript host.

Playing Rusty Checkers in JavaScript

With just a few minor changes, your new Rust-built checkers WebAssembly module should work the same way as it did before. To get started, copy the index.html from the previous chapter into the demo directory.

Next, create the demo/index.js file and edit its contents to match the following:

rustychekers/demo/index.js fetch(’./rustychekers.wasm’).then(response =>

response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes, {
env: {
notify_piecemoved: (fX, fY, tX, tY) => {
console.log("A piece moved from (" + fX + "," + fY +
") to (" + tX + "," + tY + ")");
},
notify_piececrowned: (x, y) => {
console.log("A piece was crowned at (" + x + "," + y + ")");
}
},
})).then(results => {
instance = results.instance;
console.log("At start, current turn is " +
instance.exports.get_current_turn());
let piece = instance.exports.get_piece(0, 7);
console.log("Piece at 0,7 is " + piece);
let res = instance.exports.move_piece(0, 5, 1, 4); // B
console.log("First move result: " + res);
console.log("Turn after move: " + instance.exports.get_current_turn());
}
export function hello(arg0) {
const ptr0 = passStringToWasm(arg0);
const len0 = WASM_VECTOR_LEN;
try {
return wasm.hello(ptr0, len0);
} finally {
wasm.__wbindgen_free(ptr0, len0 * 1);
}
}

The memory offset and length of the allocated string are returned from a function called passStringToWasm(). This function invokes the generated allocation function inside the WebAssembly module, placing the encoded string in the module’s linear memory and then doing the relevant pointer arithmetic. Having written your own wast code, you should be able to appreciate how great it is to have this code generated on your behalf.

After the hello() function is done, the code will free the previously allocated memory via the __wbindgen_free() function that wasm-bindgen stuffed into the WebAssembly module for us. With the WebAssembly side of this “Hello, World” done, it’s time to move on to the JavaScript side of the house.

Integrating with JavaScript and npm

In order to run this sample in a browser like you did before, you’ll need a web server and some way of serving up your script content that invokes the wasm module. In addition, for this sample, you’re going to set up a webpack configuration. Follow the appropriate instructions to ensure you’re using the latest version of webpack. If you’re a JavaScript pro (unlike myself), then feel free to use whatever tooling feels most comfortable to you.

There are some handy shortcuts you can use with webpack to do things like automatically generate the index.html. To keep things simple and easier to understand, I’m deliberately not optimizing certain things in this book. You could also choose not to use webpack at all.

The real work happens in the index.js file. This is where it really pays to use additional tools. You can see that it looks like simple, clean, idiomatic JavaScript, even though it’s going through a bridge to integrate with a WebAssembly module. It’s truly the best of both worlds—the Rust code targeting WebAssembly looks like idiomatic Rust, and the JavaScript looks like standard, unmodified JavaScript:

jsint_bindgenhello/index.js

const wasm = import('./bindgenhello');

wasm

.then(h => h.hello("world!"))
.catch(console.error);

Next, set up a webpack configuration so that you can use it to manage your JavaScript bundles. Note that the entry point is index.js. Previous versions of this book required some shoe-horning and other shenanigans to get this working, but the WebAssembly ecosystem is always improving, and things are getting simpler every day:

jsint_bindgenhello/webpack.config.js

const path = require('path');
const HtmlWebpackPlugIn = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugIn(),
// Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time.
new webpack.ProvidePlugin({
TextDecoder: ['text-encoding', 'TextDecoder'],
TextEncoder: ['text-encoding', 'TextEncoder']
})
],
mode: 'development'
};

Finally, create a package.json file. In addition to setting up your webpack development web server, you could also use this as a place to automate your build process by calling the build.sh shell script or something similar:

jsint_bindgenhello/package.json

{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"text-encoding": "^0.7.0",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.11.1",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}

Now you should be able to execute a build script to produce the WebAssembly module and the generated JavaScript files, then npm run serve to start the webpack server. Pointing your WebAssembly-enabled browser at your local host on port 8080 should then pop up a JavaScript alert dialog box. Try this out on your own and bask in the glow of autogenerated JavaScript interop goodness.

With this “Hello, World” project template in hand, it’s time to move on to building something a little more powerful with the help of wasm-bindgen.

Back in the days before the Internet filled up with pictures of kittens, animated memes, and ubiquitous social networking, university students had to walk three miles uphill in the snow to computer labs so they could play games on monochrome monitors tethered to Unix servers.

One of these games was an incredible creation called Rogue.³ Remember when I suggested that constraints are often good for innovation? Rogue is a fantastic example of that. Fed up with text games that you could only play once, Rogue’s creators managed to let players hack and slash their way through procedurally generated dungeons in a simple 80 column by 24 row terminal.

For this code sample, you’ll be taking a JavaScript library for creating Rogue-like games and building a game with it. The point of this exercise isn’t to build a game (though that is a fun side effect), but rather to illustrate some possible

[3] www.gamasutra.com/view/feature/4013/the_history_of_rogue_have_you_.php?print=1 ways for WebAssembly to interact with your JavaScript code and third-party JavaScript libraries. We want to examine strategies for spreading code and logic across the boundary between Rust (WebAssembly) and JavaScript.

It’s important to prepare for our decision about where to draw those bound- aries and how to spread the code to be wrong. We will make an attempt, see how it plays, see what the code looks like, and then decide how to refactor it from there. Perfect software isn’t created, it comes from iteration and the deliberate choice of an imperfect starting point.

In the Rogue WebAssembly game, your objective is to find and open all of the treasure chests. Inside one of these chests is a WebAssembly module. You will have to find this module before the dreaded Rust Borrow Checker captures you!

Getting Started with Rot.js

Before getting started, you might want to take a few minutes to familiarize yourself with the Rot.js⁴ library. You don’t need to become an expert. Just take a look at some of the basic documentation. In short, Rot.js injects a vir- tual 80x24 (you can resize it) terminal window into an HTML canvas. With that in place, you can use methods like draw() to place characters on the map, and hook up a turn-based actor system. This library has far more functional- ity than you’ll use for this simple example (but plenty of goodies to play with if you want to add on later).

You can get started by making a new copy of the better “Hello, World” from the previous section. I called my new directory roguewasm, but you can call yours whatever you like. Make sure you’ve got a build script that builds the wasm module and invokes the wasm-bindgen CLI. You can do this with a shell script or with changes to package.json. You won’t need to add a reference to Rot.js for npm. Instead, add that reference to the index.html file, where it will be clear that this is a traditional, client-side JavaScript dependency. There are other ways to rely on these kinds of dependencies, but this isn’t a JavaScript book so I will steer clear of them.

The game screen consists of the canvas area managed by Rot.js, a header for the game title, and a sidebar that will serve as an area to display the player’s statistics. Here’s a very simple index.html file that uses CSS flex grid to create those regions (it may be difficult to tell, but I am not a designer): [1] ondras.github.io/rot.js/manual/#intro jsint_roguewasm/index.html

<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<title>Rogue WebAssembly</title>
<script src="https://cdn.jsdelivr.net/npm/rot-js@2/dist/rot.js"></script>
<style>
.row {

display: flex;

}
.row_cell {
flex: 1
}
</style>
</head>
<body>
<div class="row">
<div class="row_cell" style="text-align:center;">
<h1>Rogue WebAssembly</h1>
</div>
</div>
<div class="row">
<div class="row_cell" id="rogueCanvas">
</div>
<div class="row_cell" id="statsContainer" style="padding:15px;"
<div class="row_cell" style="text-align:center;">
<h2>Stats</h2>
</div>
<p>
<span>
<b>HitPoints:</b>
</span>&nbsp;
<span id="hitpoints">0</span>&nbsp;/&nbsp;
<span id="max_hitpoints">0</span>
</p>
<p>
<span>
<b>Moves:</b>
</span>&nbsp;
<span id="moves">0</span>
</p>
</div>
</div>
<script src='./bootstrap.js'></script>
</body>
</html>

The next decision you need to make is the hardest: what code will be in your JavaScript (e.g., index.js) and what code will be in the WebAssembly module? The right answer isn’t always to put everything inside WebAssembly or Rust just because that’s what’s new and shiny. There are a couple of things that Rot.js does quite well, like implementing pathfinding and random dungeon generation, that you’re not going to want to reinvent in WebAssembly.

Instead, you’ll want to invoke that functionality from wherever it’s most appropriate. Using wasm-bindgen, you can allow JavaScript classes to manifest in Rust and you can let Rust structs with functions appear as classes in JavaScript. To get started, let’s work on the game engine’s core logic and see how much of it can be implemented in Rust.

Before moving on to creating the game engine, you might want to have a look at the Rot.js tutorial.1 This tutorial walks you through creating the all-JavaScript game on which Rogue WebAssembly is based. Skimming through this might help provide some context as to what you are building in the next section.

Creating the Game Engine

The game engine is subservient to the JavaScript in index.js. If you took a look at the Rot.js documentation, you may have noticed that the random dungeon generation works by taking a callback parameter. While there are a number of dungeon types available, the one we’ll be using in this game is a digger.

Each time Rot.js digs a piece out of raw map material, it invokes the callback. This callback contains the x- and y-coordinates of the spot, and a value integer. The meaning of this field varies between dungeon types. In the case of Rogue WebAssembly, we only care about the 0-values (open space).

First you’re going to want to set up some code blocks to hold your imports and exports. Because I’m either clairvoyant or I’ve written this sample multiple times, I know that you’re going to need access to the alert() and console.log() JavaScript functions, as well as eventually a stats_updated() function for notifying the UI when a player’s stats change:

jsint_roguewasm/src/lib.rs

#[macro_use]
extern crate serde_derive;
extern crate wasm_bindgen;
use std::collections::HashMap;
use wasm_bindgen::prelude::*;
  1. www.roguebasin.com/index.php?title=Rot_js_tutorial
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
#[wasm_bindgen(module = "./index")]
fn stats_updated(stats: JsValue);
pub type Display;
#[wasm_bindgen(method, structural, js_namespace = ROT)]
fn draw(this: &Display, x: i32, y: i32, ch: &str);
#[wasm_bindgen(method, structural, js_name = draw, js_namespace = ROT)]
fn draw_color(this: &Display, x: i32, y: i32, ch: &str, color: &str);
}

With the log() function, notice that you can import functions from specific JavaScript namespaces (e.g., console). You can tell wasm-bindgen which JavaScript module contains the function you’re going to import, as we do with the stats_updated() function.

Next is where some of this tooling starts to really shine. Rot.js contains a class called Display in the ROT namespace. By declaring the Display type inside the extern block, wasm-bindgen makes that type available to your code and generates everything necessary to communicate with it. Notice that we didn’t put a namespace qualifier on the Display type, only the functions. wasm-bindgen builds types from the functions, which do have a namespace qualifier.

You will want access to two overloads of the draw() method: one that just renders a character in the default colors and the other that renders a character with an explicit color code. There’s a lot going on here, so make sure you spend a few minutes taking in all of the code generation happening on your behalf.

By using the structural and method keywords in the wasm_bindgen macro, we are telling the macro and JavaScript boilerplate to take the method accessed on the Display type and call the decorated function in the WebAssembly module.

If in JavaScript you had wanted to call ROT.Display.draw(4,5,”@”), you can invoke the Rust function display.draw(4,5,”@”) where display is a Rust variable that behaves like a struct with methods. As you’ll see, your JavaScript code can pass in a reference to an initialized ROT.Display and your Rust code can use whatever methods on it you declare in your extern block.

To create an instance of a Rot.js display and pass it to an instance of our game engine, we’re first going to need the Engine class. This is a struct we define in Rust (you’ll see it shortly), and, thanks to the wasm-bindgen macro, we can import it as though it was just another JavaScript class:

import { Engine, PlayerCore } from ’./jsint_roguewasm’;

Here, roguewasm is a JavaScript file produced when we run the wasm-bindgen CLI tool. PlayerCore is another struct-exported-as-class that you’ll see shortly. The JavaScript code to create an instance of a Rot.js display and pass it to an instance of the game engine looks like this:

jsint_roguewasm/index.js

// this.display = new ROT.Display();

this.display = new ROT.Display({ width: 125, height: 40 })

document.getElementById("rogueCanvas").appendChild(this.display.getContainer());
this.engine = new Engine(this.display);

With some of that connective tissue set up, it’s time to create the game engine. The foundation of the game is map generation and map rendering, and Rot.js uses the dig() callback to allow your game engine to produce the game map. Here’s the Rust code for the engine that handles the dig callback, updates its state, and renders an entire map:

#[wasm_bindgen]
pub struct Engine {
display: Display,
points: HashMap<GridPoint, String>,
prize_location: Option<GridPoint>,
}
#[wasm_bindgen]
impl Engine {
#[wasm_bindgen(constructor)]
pub fn new(display: Display) -> Engine {
Engine {
display,
points: HashMap::new(),
prize_location: None,
}
}
pub fn on_dig(&mut self, x: i32, y: i32, val: i32) {
if val == 0 {
let pt = GridPoint { x, y };
self.points.insert(pt, ".".to_owned());
}
}
pub fn draw_map(&self) {
for (k, v) in &self.points {
self.display.draw(k.x, k.y, &v);
}

The Engine struct owns a reference to the following: a ROT Display instance, a hash that maps grid coordinates to renderable characters, and the location of the hidden WebAssembly module. The constructor illustrates an important point: Rust structs cannot be initialized with missing fields. To deal with something that could be missing like the prize location (you’ll write that code in a bit), we make use of Rust’s Option type.

on_dig() adds the supplied grid coordinates to the points field. The draw_map() function may look a little strange to you if you’re not used to Rust. In Rust, by default, for loops take ownership of the items over which they iterate. This means if you just casually loop over a collection, you can’t just dish out references to those items to other functions (because you no longer own them). If you don’t want to own (many in the community may also call this consuming) the collection, you can iterate over references to the items as indicated by the & sign.

Lastly, the draw_map() function invokes the draw() function on the Display instance. Rust knows that this opaque thing provided by the host (in our case, provided by JavaScript) has a three-parameter draw() function on it because we specified that in our extern block.

With some map-related engine functions available on the Engine struct, you can write some code in a JavaScript Game class that invokes the Rot.js map digger:

jsint_roguewasm/index.js

generateMap: function () {
var digger = new ROT.Map.Digger();
var freeCells = [];
var digCallback = function (x, y, value) {
if (!value) {
var key = x + "," + y;
freeCells.push(key);
}
this.engine.on_dig(x, y, value);
}
digger.create(digCallback.bind(this));
this.generateBoxes(freeCells);
this.engine.draw_map();
this.player = this._createBeing(Player, freeCells);
this.enemy = this._createBeing(Checko, freeCells);
},

① Invoke the on_dig() function on the Rust Engine struct.

② Invoke the draw_map() function on the Rust Engine struct.

③ Here this refers to the Game class instance and we call a utility function to create an instance of either a player or an enemy to put on the map.

The aging JavaScript syntax to add functions to the Game class is to avoid using translators and to keep the code samples as simple and portable as possible. Feel free to convert this to your favorite syntax and use Babel or its ilk to transpile the code.

Now that the map rendering and storage of grid points is taken care of, it’s time to move on to adding players, enemies, and the cherished hidden treasure: the WebAssembly module.

Adding Players, Enemies, and Treasure

As you’ve seen, one strategy for separating the implementation between Rust and JavaScript is to assign responsibilities by expertise or to avoid limitations. For example, it makes a lot of sense for the top-level JavaScript to initiate the game and any dependencies and then call into the WebAssembly module for whatever remains.

In this section, you’re going to add support for the player, an enemy, and obtaining the treasure that might be hidden within the boxes (* on the map canvas). Here you’ll see another strategy for separating the two worlds: encapsulation.

Using encapsulation allows you to create a class called Player in JavaScript, and then have a private member inside that class that’s an instance of the Rust-based player core. With this strategy, it becomes easy to have JavaScript handle things like keyboard input and configure the callbacks for use with Rot.js, all while deferring logic and other processing to the internal WebAssembly module.

This also lets you have a Player and Enemy class both share the functionality of the Rust-exported PlayerCore class. The JavaScript player class will handle subscribing to the key down browser event, exposing the Rot.js scheduler callback function act(), and exposing property queries and self-rendering functions. Let’s take a look at the player abstraction in JavaScript:

jsint_roguewasm/index.js

var Player = function (x, y) {
this._core = new PlayerCore(x, y, "@", "#ff0", Game.display);
this._core.draw();
}

Player.prototype.act = function () {

Game.rotengine.lock();
window.addEventListener("keydown", this);
}

Player.prototype.handleEvent = function (e) {

var keyMap = {};
keyMap[38] = 0;
keyMap[33] = 1;
keyMap[39] = 2;
keyMap[34] = 3;
keyMap[40] = 4;
keyMap[35] = 5;
keyMap[37] = 6;
keyMap[36] = 7;
var code = e.keyCode;
if (code == 13 || code == 32) {
Game.engine.open_box(this._core, this._core.x(), this._core.y());
return;
}
/* one of numpad directions? */
if (!(code in keyMap)) { return; }
/* is there a free space? */
var dir = ROT.DIRS[8][keyMap[code]];
var newX = this._core.x() + dir[0];
var newY = this._core.y() + dir[1];
if (!Game.engine.free_cell(newX, newY)) { return; };
Game.engine.move_player(this._core, newX, newY);
window.removeEventListener("keydown", this);
Game.rotengine.unlock();
}

Player.prototype.getX = function () { return this._core.x(); } Player.prototype.getY = function () { return this._core.y(); }

The first interesting piece of JavaScript is this:

this._core = new PlayerCore(x, y, "@", "#ff0", Game.display);
this._core.draw();

This creates an instance of the PlayerCore class, which is actually a Rust struct you’ll write shortly that, through the power of wasm_bindgen, looks to JavaScript like an ordinary class. This constructor also takes an instance of a ROT.Display object, which gives the player core access to the map canvas.

If the key pressed by the player is a directional key, then Rot.js provides a convenience array (ROT.DIRS[8]) to help in computing the x- and y-coordinates of the direction indicated by a key press. In the following code, you can see the elements of the resulting direction array being added to the location state being managed by the player core:

var dir = ROT.DIRS[8][keyMap[code]];
var newX = this._core.x() + dir[0];
var newY = this._core.y() + dir[1];

This is a perfect example of some code better left in JavaScript. Rot.js already has facilities for direction calculation and, as you’ll see, pathfinding, so there’s no need to reinvent those in Rust.

If the key pressed isn’t a movement key, but it’s instead either the carriage return (code 13) or the space bar (code 32), then the player will try to open a box. This code defers to the WebAssembly module by invoking the Rust open_box() function on the Engine struct.

With the player’s basic behavior defined, it’s time to create the enemy. In this game, the player’s arch-nemesis is the cruel, evil, heartless borrow checker, a villain responsible for ensuring your code can never be compiled unless it is memory safe! Let’s call him Checko.

jsint_roguewasm/index.js

// Checko the Borrow Checker! Run away!
var Checko : function (x, y) {
s_core = new PlayerCore(x, y, "B", "red", Game.display);
ore.draw();
utotype.act = function () {
x = Game.player.getX();
y = Game.player.getY();
var passableCallback = function (x, y) {
return Game.engine.free_cell(x, y);
}
var aStar = new ROT.Path.AStar(x, y, passableCallback, { topology: 4 });
var path = [];
var pathCallback = function (x, y) {
path.push([x, y]);
}
aStar.compute(this._core.x(), this._core.y(), pathCallback);
path.shift();
if (path.length <= 1) {
Game.rotengine.lock();
alert("Game over - you were captured by the Borrow Checker!!");
} else { x = path[0][0];
y = path[0][1];
Game.engine.move_player(this._core, x, y);
}

Where the player’s act() callback (invoked by the Rot.js scheduler) handles keyboard input and subsequent movement, Checko the Borrow Checker’s act() callback uses Rot.js’s A-star pathfinding to compute a path to the player. It then finds the first step in that path and moves in that direction. If the path indicates that the player is about to be caught by Checko, the game is over. (Game.rotengine.lock() stops all schedulers.)

Again, you can see where the PlayerCore struct is maintaining Checko’s current position. These coordinates are passed as initialization parameters to the A-star pathfinding algorithm. This calculation requires a callback, where the boolean indicator of whether a coordinate is traversable is deferred to the free_cell() function on the Engine struct (dots and asterisks are traversable):

pub fn free_cell(&self, x: i32, y: i32) -> bool {
let g = GridPoint { x, y };
match self.points.get(&g) {
Some(v) => v == "." || v == "*",
None => false,
}
}

Earlier in this section, you saw some code at the top of the lib.rs file that looked like this:

#[macro_use]
extern crate serde_derive;

This is a reference to the serde crate (serde refers to serialization/de-serialization). Serde is one of the most commonly used Rust crates in the entire ecosystem and contains functionality for manually performing raw serialization as well as macros for automatically deriving serialization and de-serialization implementations for your structs and enums.

As a reminder, the stats_updated() function provided by the browser host to be invoked by our game engine is declared as follows:

#[wasm_bindgen(module = "./index")]
fn stats_updated(stats: JsValue);

When the game engine invokes the stats_updated() callback, it’s sending a raw JSON value rather than attempting to marshal a struct that exists on both

If the key pressed by the player is a directional key, then Rot.js provides a convenience array (ROT.DIRS[8]) to help in computing the x- and y-coordinates of the direction indicated by a key press. In the following code, you can see the elements of the resulting direction array being added to the location state being managed by the player core:

var dir = ROT.DIRS[8][keyMap[code]];
var newX = this._core.x() + dir[0];
var newY = this._core.y() + dir[1];

This is a perfect example of some code better left in JavaScript. Rot.js already has facilities for direction calculation and, as you’ll see, pathfinding, so there’s no need to reinvent those in Rust.

If the key pressed isn’t a movement key, but it’s instead either the carriage return (code 13) or the space bar (code 32), then the player will try to open a box. This code defers to the WebAssembly module by invoking the Rust open_box() function on the Engine struct.

With the player’s basic behavior defined, it’s time to create the enemy. In this game, the player’s arch-nemesis is the cruel, evil, heartless borrow checker, a villain responsible for ensuring your code can never be compiled unless it is memory safe! Let’s call him Checko.

jsint_roguewasm/index.js

// Checko the Borrow Checker! Run away!
var Checko = function (x, y) {
this._core = new PlayerCore(x, y, "B", "red", Game.display);
this._core.draw();
Checko.prototype.act = function () {
var x = Game.player.getX();
var y = Game.player.getY();
var passableCallback = function (x, y) {
return Game.engine.free_cell(x, y);
}
var astar = new ROT.Path.AStar(x, y, passableCallback, { topology: 4 });
var path = [];
var pathCallback = function (x, y) {
path.push([x, y]);
}
astar.compute(this._core.x(), this._core.y(), pathCallback);
path.shift();
if (path.length <= 1) {
Game.rotengine.lock();
alert("Game over - you were captured by the Borrow Checker!!");
} else {
x = path[0][0];
y = path[0][1];
Game.engine.move_player(this._core, x, y);
}
}

Where the player’s act() callback (invoked by the Rot.js scheduler) handles keyboard input and subsequent movement, Checko the Borrow Checker’s act() callback uses Rot.js’s A-star pathfinding to compute a path to the player. It then finds the first step in that path and moves in that direction. If the path indicates that the player is about to be caught by Checko, the game is over. (Game.rotengine.lock() stops all schedulers.)

Again, you can see where the PlayerCore struct is maintaining Checko’s current position. These coordinates are passed as initialization parameters to the A-star pathfinding algorithm. This calculation requires a callback, where the boolean indicator of whether a coordinate is traversable is deferred to the free_cell() function on the Engine struct (dots and asterisks are traverseable):

pub fn free_cell(&self, x: i32, y: i32) -> bool {
let g = GridPoint { x, y };
match self.points.get(&g) {
Some(v) => v == "." || v == "*",
None => false,
}
}

Earlier in this section, you saw some code at the top of the lib.rs file that looked like this:

#[macro_use]
extern crate serde_derive;

This is a reference to the serde crate (serde refers to serialization/de-serialization). Serde is one of the most commonly used Rust crates in the entire ecosystem and contains functionality for manually performing raw serialization as well as macros for automatically deriving serialization and de-serialization implementations for your structs and enums.

As a reminder, the stats_updated() function provided by the browser host to be invoked by our game engine is declared as follows:

#[wasm_bindgen(module = "./index")]
fn stats_updated(stats: JsValue);

When the game engine invokes the stats_updated() callback, it’s sending a raw JSON value rather than attempting to marshal a struct that exists on both sides of the barrier. This makes the stats notification faster and consume less resources because you don’t need the generated boilerplate to make the Stats struct appear as a JavaScript class.

For this kind of serialization code to compile, you’ll need to customize your Cargo.toml slightly so that the wasm-bindgen reference includes serialization support:

jsint_roguewasm/Cargo.toml

[package]
name = "roguewasm"
version = "0.1.0"
authors = ["Your Name <[email protected]>"]
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = "^1.0.59"
serde_derive = "^1.0.59"
[dependencies.wasm-bindgen]
version = "^0.2"
features = ["serde-serialize"]

Now let’s write the code for the player core and show some of the other important structs like Stats and GridPoint:

jsint_roguewasm/src/lib.rs

#[derive(Serialize)]
pub struct Stats {
pub hitpoints: i32,
pub max_hitpoints: i32,
pub moves: i32,
}
#[derive(PartialEq, Eq, PartialOrd, Clone, Debug, Hash)]
struct GridPoint {
pub x: i32,
pub y: i32,
}
#[wasm_bindgen]
pub struct PlayerCore {
loc: GridPoint,
moves: i32,
display: Display,
hp: i32,
max_hp: i32,
icon: String,
color: String,
}
#[wasm_bindgen]
impl PlayerCore {
#[wasm_bindgen(constructor)]
pub fn new(x: i32, y: i32, icon: &str,
color: &str, display: Display) -> PlayerCore {
PlayerCore {
loc: GridPoint { x, y },
display,
moves: 0,
max_hp: 100,
hp: 100,
icon: icon.to_owned(),
color: color.to_owned(),
}
}
pub fn x(&self) -> i32 {
self.loc.x
}
pub fn y(&self) -> i32 {
self.loc.y
}
pub fn draw(&self) {
&self
.display
.draw_color(self.loc.x, self.loc.y, &self.icon, &self.color);
}
pub fn move_to(&mut self, x: i32, y: i32) {
self.loc = GridPoint { x, y };
self.draw();
self.moves += 1;
self.emit_stats();
}
pub fn emit_stats(&self) {
let stats = Stats {
hitpoints: self.hp,
max_hitpoints: self.max_hp,
moves: self.moves,
};
stats_updated(JsValue::from_serde(&stats).unwrap());
}
pub fn take_damage(&mut self, hits: i32) -> i32 {
self.hp = self.hp - hits;
self.emit_stats();
self.hp
}
}

The first arrow shows that every instance of a PlayerCore maintains the current location, icon, and icon color of the player (or enemy) that it supports. The second highlight shows internal state being converted into a struct that will be serialized as a raw JSON value and sent to the JavaScript host

I’m not just showing my preference for encapsulation over inheritance with this implementation — but also illustrating a good pattern for hiding the seams between JS and WebAssembly. To make sure you’ve got a fully working version of the game to play with, download it from this book’s resources. In the project directory type

npminstallnpm install npm run serve

@ serve /home/kevin/Code/Rust/wasmbook/khrist/Book/code/point-roguewasm webpack dev server

With your WebAssembly module compiled and processed, you can now open your browser and visit the above URL and see a page that looks similar to this:

Rogue WebAssembly

Rogue WebAssembly

Congratulations — you’ve just created a fully playable version of one of the most classic and influential games of all time using WebAssembly modules. Before continuing to the next section of this chapter, you should take a moment to bask in the glory of your own success and play the game. Keep

  1. rust-lang-nursery.github.io/edition-guide/rust-2018/index.html ↩ ↩2

  2. rust-lang-nursery.github.io/edition-guide/rust-2018/module-system/index.html ↩