Building WARoS The WebAssembly Robot System
local graph
Chapter 8 — Building WARoS The WebAssembly Robot System
Section titled “Chapter 8 — Building WARoS The WebAssembly Robot System”CHAPTER 8
Building WARoS— The WebAssembly Robot System
We started this book by going over the fundamentals of what WebAssembly is, how it works, and what its raw text format looks like. In later chapters, you learned how to build WebAssembly modules that can interact with browser hosts and use advanced UI libraries to build full-featured “pure WebAssembly” web applications.
Then we ventured into the realm of non-browser hosts, and you learned how to write Rust code that can load, validate, and interpret a WebAssembly module. We put this into action by writing a console-based checkers host and even a Raspberry Pi host that allowed a WebAssembly module to manipulate LEDs.
In this chapter, you’re going to take everything you’ve learned and apply it to building a Rust host that can load multiple WebAssembly “robots” into a vir- tual arena, pit them against each other, and run all of the game logic. You’ll not only learn how to build this code, but I’ll also illustrate multiple extension points where you can add a ton of cool, cloud-based features to this game.
This chapter will be the heaviest in terms of exposure to advanced Rust topics, like shared, mutable state across threads and some pretty intricate use of borrows and moves. While building the game in this chapter, you’ll learn a lot about Rust, and the game will provide a fun tool you can use to continue learning and exploring Rust and WebAssembly.
An Homage to Crobots
Section titled “An Homage to Crobots”Back in December of 1985, Tom Poindexter released a game called Crobots.¹ This game combined a custom C compiler and a stack-based virtual machine that compiled robot files written in a C-like subset and evaluated combat between multiple robots. This program compiled multiple robots, and then it could either display live results or just give you a summary of the match when it was over. Crobots was ahead of its time and, despite the relative lack of raw computing power of the era, it was, for all intents and purposes, real-time (limited by hardware clock speeds and a couple of other factors).
It wasn’t just a game, however. Crobots’ simplified C syntax and narrowly focused goal (kill your opponents without dying) made it an amazing tool to introduce programming languages and computer science concepts to eager learners. When I was 11 years old, I asked my grandfather if he could teach me C, as I’d just finished learning BASIC. He handed me the Crobots floppy disk and a printed copy of the documentation (complete with dot matrix feeder holes!) and left me to my own devices.
I taught myself C and a number of vital programming concepts by learning to build robots to compete against others. I was instantly entranced by the concepts of virtual worlds, computer programming, and game design theory. The rest, as they say, is history. I quite literally owe much of what I’ve been able to accomplish in my career to my childhood exposure to Tom Poindexter’s creation, and of course, to my grandfather for giving it to me.
The Rules of Crobots
Section titled “The Rules of Crobots”The documentation for the original Crobots game is now available online.² You don’t need to read the original in order to implement the WebAssembly game, but I thoroughly enjoyed reading it for the pure nostalgia value.
Each robot in the game is essentially a tank. It can move in any direction by engaging its drive motor pointing in a direction indicated by a heading angle between 0 and 360 degrees. It also has an independently mounted cannon that can fire in any direction indicated by the same type of heading. Each robot’s compass is calibrated with East pointing to the right, as shown in the figure on page 157.
All of the robots occupy a 1,000m by 1,000m battlefield. The perimeter wall is dangerous and inflicts damage to robots upon collision. Robots colliding
[1] en.wikipedia.org/wiki/Crobots [2] crobots.deepthought.it/html/manual.html#5.
with each other also take damage. If you want your robot to survive and kill all of your opponents, your robot is going to need input.
The most important input is the scanner. All robot scanners have a range of 700m and can scan within an arc your robot specifies, with a maximum spread of 10 degrees. Damage in the game is doled out according to the fol- lowing table:
| Damage | Description |
|---|---|
| 2% | Robot vs. robot or robot vs. wall collision. Also stops the drive motor, setting the speed to 0. |
| 3% | Missile explodes within a 40m radius of robot |
| 5% | Missile explodes within a 20m radius |
| 10% | Missile explodes within a 10m radius |
Other inputs include status information, such as the robot’s current location. There are some subtleties missing from the robot API, and so you’ll need to keep track of some information yourself like your current destination, your last heading, and so on. One final rule is that while every robot has an unlimited supply of missiles, only two missiles can ever be in the air at a given time.
Now that we’ve got the basic rules defined, let’s try and build an API that gives robots the tools they need for real-time combat.
Designing the WARoS API
Section titled “Designing the WARoS API”The original Crobots API was defined by what Poindexter called the Intrinsic Function Library.³ Each of these functions were made available to the original robots to allow them to interact with (and hopefully dominate) their virtual environment. If you’re thinking that this sounds a lot like a list of imports required by a WebAssembly module, you’re right. As soon as I remembered the Crobots intrinsic functions, I knew I had to try and port it to WebAssembly.
[3] crobots.deepthought.it/html/manual.html#8
Let’s take a look at the original list of intrinsic functions:
| Function | Description |
|---|---|
| scan(deg, res) | Invokes the robot’s scanner, pointing it at a specified degree and resolution. Returns 0 if there are no robots in range. Otherwise returns a positive integer indicating the distance to the closest target in that direction. |
| cannon(deg, range) | Fires the cannon at a specified degree and range. Range is limited to 700m. Returns 0 if no missile was fired, 1 if a missile was fired. |
| drive(deg, speed) | Engages the drive motor in the specified direction at the indicated percentage of power. |
| damage() | Returns the percentage of damage currently taken by the robot. |
| speed() | Returns the current speed of the robot as a percent. Check this value as it can differ from the parameter given to drive because of acceleration, deceleration, and collisions |
| loc_x() loc_y() | Returns the current x- or y-coordinate. |
| rand(limit) | Returns a random number between 0 and limit, with a max of 32,767 |
| sqrt(number) | Returns the square root of a number, coerced positive if necessary |
| sin(deg) cos(deg) | Trig functions. In the original Crobots game, in-memory trig tables and a large scale were used to avoid floating-point calculations and roundoff problems. We shouldn’t need to use any of those tricks with our API. |
| tan(deg) atan(deg) | Trig functions. In the original Crobots game, in-memory trig tables and a large scale were used to avoid floating-point calculations and roundoff problems. We shouldn’t need to use any of those tricks with our API. |
Converting the Crobots Intrinsic Functions into a Rust API
When I first went back and looked at the Crobots documentation, I was struck by the elegance of the intrinsic function library. If you take a close look, you’ll see that all of the functions already adhere to the basic rules that we know apply to WebAssembly modules—nothing takes or returns any parameter that isn’t a 32-bit integer, and there are no complex types or tuples used.
WebAssembly has floating-point numbers, but this list of functions has been working quite well for decades, so let’s stick with it and see how well it works out for a modern game. The first step is converting these functions into a list of extern functions.
To start off, let’s create a workspace in a root directory (I called mine waros) and then create a new Rust library project beneath that called warsdk. This will be a library used to wrap extern functions and provide a few other utilities to WebAssembly robot modules.
Ignore the lib.rs for now and create a new file called ffi.rs. FFI stands for Foreign Function Interface, and the extern declarations are part of Rust’s FFI:
waros/warsdk/src/ffi.rs
extern "C" { pub fn scan(angle: i32, resolution: i32) -> i32; pub fn cannon(angle: i32, range: i32) -> i32; pub fn drive(angle: i32, speed: i32) -> i32; pub fn damage() -> i32; pub fn speed() -> i32; pub fn loc_x() -> i32; pub fn loc_y() -> i32; pub fn rand(limit: i32) -> i32; pub fn wsqrt(number: i32) -> i32; pub fn wsin(degree: i32) -> i32; pub fn wcos(degree: i32) -> i32; pub fn wtan(degree: i32) -> i32; pub fn watan(degree: i32) -> i32; pub fn plot_course(tx: i32, ty: i32) -> i32;}Most of this looks identical to Poindexter’s original intrinsic function list, w/ a few minor changes. First, I had to add a prefix to a few of the math function because, after a recent Rust update, functions like sin and cos were made par of a globally visible set of names and wouldn’t link to WebAssembly anymore.
Second, I added a function called plot_course(). This just determines the heading from the robot’s current location to a target location. Nearly every Robot that chooses a destination coordinate will need this function, so I made it part of the API for convenience.
Keeping It Simple
Section titled “Keeping It Simple”While building this sample, I tried computing the heading inside one of the robot’s code. Interestingly, this compiled Wasm module demanded that the host support a function called Math_atan2(). I’d used atan2() in an early version of the code, and instead of preventing my compilation, the compiler decided it should make the host provide that function. As you start adding complexity to your robot modules, you might see something like this happen again.
This looks like a pretty simple API, and it should be easy for developers working in Rust, Go, raw WebAssembly, or any other language to build robots compatible with the host. People building robots in lower-level languages will be thankful for the availability of the trig functions and it also helps us ensure that robots from different languages behave consistently within the same host.
I placed these extern functions in their own FFI module so that the name exposed to the SDK consumers (the robot developers) could have the same names and still wrap the external calls in unsafe. Modify the lib.rs file of the warsdk project to look like this:
waros/warsdk/src/lib.rs
pub fn scan(angle: i32, resolution: i32) -> i32 { unsafe { ffi::scan(angle, resolution) }}pub fn cannon(angle: i32, range: i32) -> i32 { unsafe { ffi::cannon(angle, range) }}pub fn drive(angle: i32, speed: i32) -> i32 { unsafe { ffi::drive(angle, speed) }}pub fn damage() -> i32 { unsafe { ffi::damage() }}pub fn speed() -> i32 { unsafe { ffi::speed() }}pub fn loc_x() -> i32 { unsafe { ffi::loc_x() }}pub fn loc_y() -> i32 { unsafe { ffi::loc_y() }}pub fn rand(limit: i32) -> i32 { unsafe { ffi::rand(limit) }}pub fn wsqrt(number: i32) -> i32 { unsafe { ffi::wsqrt(number) }}pub fn wsin(degree: i32) -> i32 { unsafe { ffi::wsin(degree) }}pub fn wcos(degree: i32) -> i32 { unsafe { ffi::wcos(degree) }}pub fn wtan(degree: i32) -> i32 { unsafe { ffi::wtan(degree) }}
pub fn watan(degree: i32) -> i32 { unsafe { ffi::watan(degree) }}
pub fn plot_course(tx: i32, ty: i32) -> i32 { unsafe { ffi::plot_course(tx, ty) }}
// Utility sample for moving to destination and stopping// Note - does NOT recover from collision en routepub fn go(target_x: i32, target_y: i32) { let course = plot_course(target_x, target_y); drive(course, 20); // at speed 20, it should take 2 ticks from awareness // of the target to stop on it while (target_x - loc_x()).abs() > 40 && (target_y - loc_y()).abs() > 40 && speed() > 0 { // wait till we get to the target } drive(course, 0); // turn off engine while speed() > 0 { // steady on until we stop }}
pub const ANGLE_EAST: i32 = 0;pub const ANGLE_NORTH: i32 = 90;pub const ANGLE_WEST: i32 = 180;pub const ANGLE_SOUTH: i32 = 270;
pub const MAX_X: u32 = 1000;pub const MAX_Y: u32 = 1000;
pub const DAMAGE_COLLISION: u32 = 2;pub const DAMAGE_DIRECTHIT: u32 = 10;pub const DAMAGE_NEARHIT: u32 = 5;pub const DAMAGE_FAR_HIT: u32 = 3;
pub const BLAST_RADIUS: i32 = 40;pub const PROJECTILE_MAX_RANGE: u32 = 200;
mod ffi;Most of this is just simple unsafe wrappers around the extern functions.
However, I've added a handy little utility function called go() that was usefulenough to include in the SDK rather than individual robots. There are alsoa couple of constants available to help robot developers write logic. Be warned,though—these aren’t the constants built into the game engine itself, so there’s a risk of getting them out of sync. This might be an issue if you were publishing this SDK outside of book samples. Each time you want to build a robot in WebAssembly and Rust, you’ll just declare a dependency on this SDK.
Finally, the Cargo.toml can stay the way it came out of the initial creation. Add a line to your workspace’s root Cargo.toml so it looks like this:
[workspace]members = [ "warsdk",]Now everything we’re going to build in this chapter (and there will be a lot) will build to the root-level target directory and you can run test suites at the top level for all of your projects.
Building the WARoS Match Engine
Section titled “Building the WARoS Match Engine”The WARoS match engine will be responsible for the following:
- Provide a host runtime for each WebAssembly module
- Provide a game loop for moving the match forward
- Manage game state
- Complete a match after a given number of cycles
Building a game engine is no small feat. The goal of what we’re building in this chapter isn’t to produce the best game engine. It’s to illustrate how we can host multiple WebAssembly modules simultaneously within a virtual environment and allow their logic to safely interact and manipulate shared state. In the fol- lowing sections, you’ll see how to accomplish all of this with Rust.
Threading, Time Slicing, and the Game Loop
Section titled “Threading, Time Slicing, and the Game Loop”Building games and game engines is loads of fun for certain types of people, like myself, who have often been referred to as masochists due to the depth and complexity of some of the problems that need to be solved in this domain. One of the problems we encounter when building game engines, the game loop, also shows up in a surprising number of other types of software, including big enterprise apps.
In Poindexter’s original implementation, he created his own virtual CPU. This meant that for each robot loaded into memory, he could control the allocation of time. Specifically, he could dole out processing cycles to each robot in turn. This allowed the robot code to be written in a way that felt real-time. The robots all operate within while loops that control their behavior throughout the match.
With WebAssembly, we don’t have that luxury. We aren’t in control of the time-slicing mechanism inside the module, and the WebAssembly standard doesn’t even have any formal definition for internal threading or atomic locking (at the time this book was written). I really wanted to maintain the “robot loop” feel of the original robot code, and so this presented a huge problem—how do I let each WebAssembly module run its own tight, infinite loop without blocking everything, gumming up the works, or worse, running afoul of Rust’s ever-vigilant borrow checker?
As I looked for solutions, I discovered that this type of problem of time sharing among multiple threads shows up in a lot of places. If you spend most of your time working in high-level web or data access frameworks, you’re probably insulated from the solutions to this concurrency problem, but they’re there if you want to look.
My initial solution was to spin up a single Rust thread for each WebAssembly module, in which the module would be allowed to run its infinite loop (triggered by the bot_init() exported function). Then, I’d run a traditional game loop⁴ that ran its own tight loop. Each iteration of my game loop would deal with the state changes and interactions coming from each robot, synchronizing and managing it all. The following diagram shows what this architecture looks like:
On the surface, it looks like this will do the job, but the devil is in the details, as they say. All we need is some kind of mutex that lets us block out other threads long enough for us to make our changes. Seems simple enough, right? Not quite. My first implementation of this literally ground to a halt. Even after
[4] en.wikipedia.org/wiki/Game_programming#Game_structure
Rust’s compiler blessed my code, my core game engine just continued to die in spectacular fashion, over and over again. In the next section, I’ll explain why.
Entities, Components, and Systems
If you’re not familiar with the concept of a game loop, it’s fairly simple. This is a loop that’s always running from the beginning of the match until the end. During each iteration of the loop, it takes care of maintenance of state and other actions.
The game loop in most games will do things like collision detection, inflicting damage, casting spells, depleting fuel from spaceships—all the housekeeping to keep all the individual parts of the game up to date. When I started working on this, I created a single struct called Robot that I figured could hold all that state that I need managed by the game loop. It looked something like this:
#[derive(Debug)]pub struct Robot { pub player_name: String, pub damage: u32, pub status: DamageStatus, pub x: i32, pub y: i32, pub heading: i32, pub origin_x: i32, pub origin_y: i32, pub distance_on_heading: i32, pub speed: i32, pub desired_speed: i32, pub desired_heading: i32, pub accel: i32, pub last_scan_heading: i32, pub cannons: Vec<Cannon>;}I took most of those fields from the original robot struct in Crobots.1 If my game loop was the only thing that needed to manipulate that list of robots and their data, that would probably be fine. But the robots all need query access for their own data, and they have functions as part of the API that write values like desired heading and speed, and they perform actions like firing cannons.
This is where things went horribly wrong. Each iteration of my game loop would acquire a write lock on this list of robots because you can’t acquire a write lock on just one element of a vector. It would then do all of the normal things and move on. Each thread from a running WebAssembly module would
In this situation, the first thread that managed to get a write lock would ring the death bell for the rest of the app. If that thread was the game loop, it would only let go of it for such a short period of time (basically between the end and start of the loop block) and the loop would appear stalled, or the robots would stall. In some variants of this plan, everything stopped, and I felt like I had bitten off more than I could chew. Threading is hard. Shared mutable state is super hard, especially in Rust where you can’t cheat. You can just “hope” you never have a data race.
The solution was to separate out the read concerns from the write concerns. and to narrow the focus of the write concerns down to as small a piece of state as possible. This is where the concept of Entity—Component—System (ECS)⁶ comes in.
First and foremost, this pattern emphasizes composition over inheritance. Since we don’t have classes with inheritance in Rust, this works out nicely. The real goal of ECS architecture is to separate concerns into small tiny pieces. Think of it as applying the microservices approach to a single piece of shared state. In my use of the ECS pattern in the game engine, I diverge from the core definition a little bit to keep the focus on the book and not or game design, but my heart is in the right place.
Entity
Entities are just arbitrary things. In most ECS implementations, an entity is just some form of unique identifier and that’s all. In our case, the entity will be the WebAssembly module name, which doubles as the player name.
Component
A component is raw state for some aspect of an entity. A component labels an entity as “having a particular aspect.” In our case, entities will have motion, damage, projectile, and scanner components.
System
Systems perform logic and take action globally against components under their purview. In our engine, there’s a system responsible for each compo- nent. In traditional ECS implementations, systems are often running in their own background threads, but I’m invoking mine sequentially to keep things as simple as I can while still building a functional game engine.
[6] en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system
With the concerns cut apart into components, and systems being the only things allowed to write to a component, we now have an architecture that can handle large amounts of concurrency without ever creating a situation where anyone is waiting on locks. Read locks are “free,” and we can have as many of them active at a time as we want, but write locks are the ones that “stop the world,” so to speak.
Now, in each iteration of the game loop, for example, the motion system can write to each of the motion components, advancing that component based on its speed, heading, acceleration, etc. The motion system doesn’t care whether that component belongs to a player, a chair, or a doorknob. This narrow focus and division of responsibility is an elegant solution to concurrency that extends far beyond creating game engines with ECS, which is why I wanted to illustrate it in this chapter.
One potentially confusing aspect of a setup like this is that the robot API doesn’t really do much. It makes requests by setting some desired state and then releasing the write lock, allowing the next pass of the relevant system to do the real work. As you’ll see when you dig into the code, when a player launches a missile, the runtime just sets a missile status to ReadyToLaunch, and then the ProjectileSystem performs the actual launching of the missile the next time through the game loop.
Creating the Runtime Host
The first thing we need to do in order to pit WebAssembly robots against each other is load the modules and expose a Runtime for them. In previous chapters you saw how this works with the wasmi crate. Those implementations were pretty simple with only a function or two. Since we’ve got an entire API to support, we’ll need to do a little bit of encapsulation and abstraction to keep the runtime clean.
Create a new library project beneath your workspace root called botengine (remember to also add this to your workspace Cargo.toml). Edit botengine’s Cargo.toml to look like the following:
waros/botengine/Cargo.toml
[package]name = "botengine"version = "0.1.0"edition = "2018"[dependencies]wasm = "0.4.2"rand = "0.6.1"nalgebra = "0.16.11"approx = "0.3.0"Before we get into the runtime host, let’s take a look at botengine/src/lib.rs. This is the root of the engine library, and it’s where we’re going to put the Combatant struct. The combatant is a wrapper around the loading, parsing, and inter- preting of the WebAssembly module, as well as a start():
waros/botengine/src/lib.rs
use std::fmt;use std::sync::Arc;use std::thread;use std::thread::JoinHandle;use wasmi::{HostError, ImportsBuilder, Module, ModuleInstance, ModuleRef};pub use crate::game::{GameState, Gameloop};pub use crate::runtime::{Runtime, BOTINIT_NAME};
pub struct Combatant {}
impl Combatant { pub fn buffer_from_file(path: &str) -> Result<Vec<u8>> { use std::fs::File; use std::io::prelude::*;
let mut file = File::open(path)?; let mut wasm_buf = Vec::new(); let _bytes_read = file.read_to_end(&mut wasm_buf)?; Ok(wasm_buf) } pub fn start( name: &str, buffer: Vec<u8>, game_state: Arc<crate::game::GameState>, ) -> JoinHandle<()> { let n = name.to_string(); thread::spawn(move || { let module = Module::from_buffer(&buffer).unwrap(); let mut runtime = runtime::Runtime::init(game_state, n.clone()); let moduleref = Self::get_module_instance_from_module(&module).unwrap(); let res = moduleref.invoke_export(BOTINIT_NAME, &[], &mut runtime); println!("bot init loop exited for player {} - {:?}", n, res); }) } fn get_module_instance_from_module(module: &Module) -> Result<ModuleRef> { let mut imports = ImportsBuilder::new(); imports.push_resolver("env", &runtime::RuntimeModuleImportResolver);Ok(ModuleInstance::new(module, &imports).expect("Failed to instantiate module").assert_no_start()}① The Arc (Atomically Reference Counted) is what lets us share pointers to the GameState struct.
② This function returns a JoinHandle but since the WebAssembly module is running an infinite loop, calling join() is likely to never return.
③ Creates a new Runtime to host the WebAssembly module and passes it a reference to the game state.
④ Invokes the bot_init() function in the WebAssembly module, starting the robot’s infinite loop.
There are a couple of subtle things happening in this code. First, the Runtime is being instantiated inside the combatant’s thread. This means the runtime doesn’t need to cross thread boundaries, which makes the Rust compiler happy. There’s also a clone happening of the player’s name converting the &str into a String, letting us get away without having to use a lifetime specifier.
The rest of the lib.rs file contains implementations of various error handling traits, as is considered best practice when you’re building a library you expect to expose to the rest of the world as a crate:
waros/botengine/src/lib.rs
/// A botengine error#[derive(Debug)]pub struct Error { kind: Kind,}/// Implements the wasmi HostError traitimpl HostError for Error {}
/// Implement standard error trait for the botengine errorimpl std::error::Error for Error { fn description(&self) -> &str { "A botengine error occurred" }
fn cause(&self) -> Option<&std::error::Error> { None }}
// Ensure that the botengine error can be string formattedimpl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { Kind::InterpreterError(ref we) => fmt::Display::fmt(we, f), Kind::MiscFailure(ref s) => fmt::Display::fmt(s, f), Kind::IoError(ref s) => fmt::Display::fmt(s, f), Kind::ExportResolve(ref s) => fmt::Display::fmt(s, f), } }}
// Creates a botengine error from an I/O Errorimpl From<std::io::Error> for Error { fn from(source: std::io::Error) -> Error { Error { kind: Kind::IoError(source), } }}
impl From<wasmi::Error> for Error { fn from(source: wasmi::Error) -> Error { Error { kind: Kind::InterpreterError(source), } }}
// Indicates the kind of error that occurred.#[derive(Debug)]pub enum Kind { InterpreterError(wasmi::Error), IoError(std::io::Error), ExportResolve(String), MiscFailure(String),}
// A Result where failure is a botengine errorpub type Result<T> = std::result::Result<T, Error>;
mod events;mod game;mod runtime;Next we need to implement the Runtime struct. We will put this in the botengine/src/runtime.rs file. This won’t compile yet because the functions in the runtime all defer to code that’s part of game state, components, or systems —all of which we’ll discuss shortly. There’s a lot of code here, and while I do enjoy typing, I wouldn’t recommend trying to type this all in by hand. Save some time and just grab the whole source for this sample:
waros/botengine/src/runtime.rs
use crate::game::{readlock, scanner::ScannerSystem, writelock};use crate::{Error, Kind};use nalgebra::Point2;use std::sync::Arc;use wasmi::{ Error as InterpreterError, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType,};/// Anchor struct for implementing the ModuleImportResolver traitpub struct RuntimeModuleImportResolver;/// Expose the list of host-provided functions, indexes, and signatures/// to the WASM module(s) managed by this runtimeimpl<'a> ModuleImportResolver for RuntimeModuleImportResolver { fn resolve_func( &self, field_name: &str, _signature: &Signature, ) -> Result<FuncRef, InterpreterError> { println!("Resolving {}", field_name); let func_ref = gen_funcref(field_name); match func_ref { Some(fr) => Ok(fr), None => Err(InterpreterError::Function(field_name.to_string())), } }}const SCAN_NAME: &'static str = "scan";const SCAN_INDEX: usize = 0;const CANNON_NAME: &'static str = "cannon";const CANNON_INDEX: usize = 1;const DRIVE_NAME: &'static str = "drive";const DRIVE_INDEX: usize = 2;const DAMAGE_NAME: &'static str = "damage";const DAMAGE_INDEX: usize = 3;const SPEED_NAME: &'static str = "speed";const SPEED_INDEX: usize = 4;const LOCX_NAME: &'static str = "loc_x";const LOCX_INDEX: usize = 5;const LOCY_NAME: &'static str = "loc_y";const LOCY_INDEX: usize = 6;const RAND_NAME: &'static str = "rand";const RAND_INDEX: usize = 7;const SQRT_NAME: &'static str = "wsqrt";const SQRT_INDEX: usize = 8;const SIN_NAME: &'static str = "wsin";const SIN_INDEX: usize = 9;const COS_NAME: &'static str = "wcos";const COS_INDEX: usize = 10;const TAN_NAME: &'static str = "wtan";const TAN_INDEX: usize = 11;const ATAN_NAME: &'static str = "watan";const ATAN_INDEX: usize = 12;const PLOT_COURSE_NAME: &'static str = "plot_course";const PLOT_COURSE_INDEX: usize = 13;pub const BOTINIT_NAME: &'static str = "botinit";
// Creates a FuncRef based on the name of the functionfn gen_funcref(name: &str) -> Option<FuncRef> { match name { SCAN_NAME => Some(FuncInstance::alloc_host( Signature::new(&[ValueType::I32, ValueType::I32][..], Some(ValueType::I32)), SCAN_INDEX, )), CANNON_NAME => Some(FuncInstance::alloc_host( Signature::new(&[ValueType::I32, ValueType::I32][..], Some(ValueType::I32)), CANNON_INDEX, )), DRIVE_NAME => Some(FuncInstance::alloc_host( Signature::new(&[ValueType::I32, ValueType::I32][..], Some(ValueType::I32)), DRIVE_INDEX, )), DAMAGE_NAME => Some(FuncInstance::alloc_host( Signature::new(&[][..], Some(ValueType::I32)), DAMAGE_INDEX, )), SPEED_NAME => Some(FuncInstance::alloc_host( Signature::new(&[][..], Some(ValueType::I32)), SPEED_INDEX, )), LOCX_NAME => Some(FuncInstance::alloc_host( Signature::new(&[][..], Some(ValueType::I32)), LOCX_INDEX, )), LOCY_NAME => Some(FuncInstance::alloc_host( Signature::new(&[][..], Some(ValueType::I32)), LOCY_INDEX, )), RAND_NAME => Some(FuncInstance::alloc_host( Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), RAND_INDEX, )), }}SQRT_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), SQRT_INDEX,)),SIN_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), SIN_INDEX,)),COS_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), COS_INDEX,)),TAN_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), TAN_INDEX,)),ATAN_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32][..], Some(ValueType::I32)), ATAN_INDEX,)),PLOT_COURSE_NAME => Some(FuncInstance::alloc_host(
Signature::new(&[ValueType::I32, ValueType::I32][..], Some(ValueType::I32)), PLOT_COURSE_INDEX,)),_ => None, }
pub struct Runtime { pub game_state: Arc<super::game::GameState>, pub module_name: String, dead: bool,}impl Externals for Runtime { fn invoke_index( &mut self, index: usize, args: RuntimeArgs, ) -> Result<Option<RuntimeValue>, Trap> { match index { SCAN_INDEX => self.scan(args.nth(0), args.nth(1)), CANNON_INDEX => self.cannon(args.nth(0), args.nth(1)), DRIVE_INDEX => self.drive(args.nth(0), args.nth(1)), DAMAGE_INDEX => self.damage(), SPEED_INDEX => self.speed(), LOCX_INDEX => self.loc_x(), LOCY_INDEX => self.loc_y(), RAND_INDEX => self.rand(args.nth(0)), SQRT_INDEX => self.sqrt(args.nth(0)), } }}SIN_INDEX => self.sin(args.nth(0)), COS_INDEX => self.cos(args.nth(0)), TAN_INDEX => self.tan(args.nth(0)), ATAN_INDEX => self.atan(args.nth(0)), PLOT_COURSE_INDEX => self.plot_course(args.nth(0), args.nth(1)), _ => Err(Trap::from(Error {
kind: Kind::MiscFailure("Invalid export index".to_string()),})),}type WasmRuntimeResult = Result<Option<RuntimeValue>, Trap>;
impl Runtime { pub fn init(game_state: Arc<super::game::GameState>, module_name: String) -> Runtime { game_state.combatant_entered(&module_name); Runtime { game_state, module_name, dead: false, } }
fn is_dead(&mut self) -> bool { if !self.dead { let dcs = self.game_state.damage_components.read().unwrap(); let dc = dcs.get(&self.module_name); match dc { Some(d) => { if let crate::game::damage::DamageStatus::Dead = d.status { self.dead = true } } None => {} } } self.dead }
fn scan(&mut self, angle: i32, resolution: i32) -> WasmRuntimeResult { if self.is_dead() { return Ok(Some(RuntimeValue::from(-1))); } let angle = ScannerSystem::to_real_heading(angle); let resolution = (resolution as f32) .max(0.0) .min(super::game::scanner::RES_LIMIT); let degree = angle as f32;
writelock(self.game_state.scanner_components) .entry(self.module_name.to_string()) .and_modify(|sc| { sc.angle = degree as f32; });let scan_result: i32 = ScannerSystem::scan(self.game_state, self.module_name, degree, resolution);Ok(Some(RuntimeValue::from(ScannerSystem::to_use_heading( scan_result as f32, )))fn cannon(&mut self, angle: i32, range: i32) -> WasmRuntimeResult { if self.is_dead() { return Ok(Some(RuntimeValue::from(0))); } let angle = ScannerSystem::to_real_heading(angle); let mut launch_result = 0; let mc = self.game_state.motion_components.read() .unwrap()[self.module_name]; writelock(self.game_state.projectile_components) .entry(self.module_name.to_string()) .and_modify(|pc| { pc.launch(&mc.position, angle, range as u32); }); Ok(Some(RuntimeValue::from(launch_result)))}fn drive(&mut self, angle: i32, speed: i32) -> WasmRuntimeResult { if self.is_dead() { return Ok(Some(RuntimeValue::from(0))); } let angle = ScannerSystem::to_real_heading(angle); let speed = speed.min(super::game::motion::MAX_ENGINE); writelock(self.game_state.motion_components) .entry(self.module_name.to_string()) .and_modify(|mc| { mc.origin = mc.position.clone(); mc.distance_along_heading = 0; mc.heading = angle; mc.desired_speed = speed; }); Ok(Some(RuntimeValue::from(1_132)))}fn damage(&mut self) -> WasmRuntimeResult { if self.is_dead() { return Ok(Some(RuntimeValue::from(100))); }}fn get_translation(self, game_state: &Gamestate) -> Result<Some(RunTimeValue), FromError> { let Some(target) = self.target else { return Ok(Some(RunTimeValue::from(0.0))); };
let Some(translation) = self.translation else { return Ok(Some(RunTimeValue::from(0.0))); };fn loc_y(&mut self) -> WasmRuntimeResult { Ok( match readlock(&self.game_state.motion_components) .get(&self.module_name) { Some(mc) => Some(RuntimeValue::from(mc.position.y as i32)), None => None, }, )}
fn rand(&mut self, limit: i32) -> WasmRuntimeResult { use rand::Rng; let mut rng = rand::thread_rng(); let n: i32 = rng.gen_range(0, limit);
Ok(Some(RuntimeValue::from(n)))}
fn sqrt(&mut self, number: i32) -> WasmRuntimeResult { let val = (number as f32).sqrt(); Ok(Some(RuntimeValue::from(val as i32)))}
fn sin(&mut self, degree: i32) -> WasmRuntimeResult { Ok(Some(RuntimeValue::from(ScannerSystem::to_user_heading( (degree as f32).to_radians().sin(), ))))}
fn cos(&mut self, degree: i32) -> WasmRuntimeResult { Ok(Some(RuntimeValue::from(ScannerSystem::to_user_heading( (degree as f32).to_radians().cos(), ))))}
fn tan(&mut self, degree: i32) -> WasmRuntimeResult { Ok(Some(RuntimeValue::from(ScannerSystem::to_user_heading( (degree as f32).to_radians().tan(), ))))}
fn atan(&mut self, degree: i32) -> WasmRuntimeResult { Ok(Some(RuntimeValue::from(ScannerSystem::to_user_heading( (degree as f32).to_radians().atan(), ))))}In this file, the gen_funcref() function is one of the most important. This function takes as input the name of a function (one of the imports the WebAssembly modules expect the host to provide) and returns a function reference in the form of an Option
With the mapping between import name and import signature created, next we need to be able to call functions at the request of the modules. As you’ve seen before, we do this through the Externals trait. The invoke_index() function takes the index of a function (returned from our gen_funcref() function) and invokes it.
Finally, you get to the real meat of the Runtime—implementing the functions imported by WebAssembly modules. There’s a lot of code here, but it all pretty much follows two basic patterns—reading from or writing to components. Occasionally we’ll defer a call to a system to do a complex query, but that’s an exception. Remember that the systems are the things tasked with processing, so these functions should do their work and get out of the way of the systems as quickly as possible. Let’s take a look at the code to make a change to a component, like the code from drive():
writelock(&self.game_state.motion_components) .entry(self.module_name.to_string()) .and_modify(|mc| { mc.origin = mc.position.clone(); mc.distance_along_heading = 0; mc.heading = angle; mc.desired_speed = speed; });The writelock() function (defined in the botengine/src/game/mod.rs file) creates a write lock on the self.game_state.motion_components HashMap. Then, the entry()⁷ function is used to grab a reference to a single entry within the hash map. The Entry API is easily one of my favorites within all of Rust, and you owe it to yourself to learn it and exploit all of its power.
Anything inside the closure passed to and_modify() has safe, mutable access to the value within that entry. In this case, it’s a single motion component and we modify it to set a new heading, reset its distance along that heading to 0, and set the desired speed.
The code to read a value from a component looks similar:
match readlock(&self.game_state.damage_components).get(&self.module_name) { Some(dc) => Some(RuntimeValue::from(dc.damage)), None => None,}Here the readlock() function (also a utility defined elsewhere) grabs a read lock on the damage_components HashMap. Instead of calling entry(), we use get() here and
[7] doc.rust-lang.org/std/collections/hash_map/enum.Entry.html match on the result. As long as no other thread is writing to damage_components at that moment, acquiring a read lock is free.
Implementing the Game Loop
The game loop is the core gear that makes everything else in the game work. Without it, nothing happens. The job of this loop is to tell each of the active systems to apply its logic. The loop also keeps track of the number of loops or “cycles” that have occurred. When we discuss replay, you’ll see why this is important.
In more formal ECS frameworks, each system might be operating in its own loop, so you have a bunch of miniature game loops rather than a single all- encompassing one. I opted for the single loop here to keep the sample easier to read and to help with playback:
waros/botengine/src/game/mod.rs
use self::damage::*;use self::motion::*;use self::projectiles::*;use self::scanner::*;use crate::events::GameEvent;use std::collections::HashMap;use std::sync::{mpsc::Sender, Arc, RwLock};use std::sync::{RwLockReadGuard, RwLockWriteGuard};pub struct Gameloop { game_state: Arc<GameState>, systems: Vec<Box<System>>, cycle: u32, max_cycles: u32, num_combatants: usize,}
#[derive(Debug)]pub enum LoopTerminationReason { CycleCountExceeded,}
pub trait System { fn apply(self: &Self, cycle: u32, game_state: &Arc<GameState>);}
impl Gameloop { pub fn new( game_state: Arc<GameState>, max_cycles: u32, num_combatants: usize, logger: Option<Sender<GameEvent>>, ) -> Gameloop { Gameloop {game_state,systems: vec![ Box::new(ScannerSystem::new(logger.clone())), Box::new(MotionSystem::new(logger.clone())), Box::new(ProjectileSystem::new(logger.clone())), Box::new(DamageSystem::new(logger.clone())),],cycle: 0,max_cycles,num_combatants,}}
pub fn start(&mut self) -> LoopTerminationReason { loop { self.systems .iter() .for_each(|s| s.apply(self.cycle, &self.game_state)); self.cycle = self.cycle + 1; if self.cycle >= self.max_cycles { return LoopTerminationReason::CycleCountExceeded; } }}The GameLoop struct’s new() function takes an Arc of the GameState, number or combatants, and a Sender as initial arguments. The Arc is used to allow code to pass multiple safe references to the same source object.
The core loop is very simple—iterate through each system and invoke its apply() function. You’ll see a few of those in the next section. Let’s take a look at how the game state is defined:
waros/botengine/src/game/mod.rs
pub type ReadWriteLocked<T> = Arc<RwLock<T>>;pub type ComponentHash<T> = ReadWriteLocked<HashMap<String, T>>;
#[derive(Debug)]pub struct GameState { pub players: ReadWriteLocked<Vec<String>>, pub motion_components: ComponentHash<MotionComponent>, pub damage_components: ComponentHash<DamageComponent>, pub scanner_components: ComponentHash<ScannerComponent>, pub projectile_components: ComponentHash<ProjectileComponent>,}
impl GameState { pub fn new() -> GameState { GameState { players: Arc::new(RwLock::new(Vec::new())),motion_components: Arc::new(RwLock::new(HashMap::new())), damage_components: Arc::new(RwLock::new(HashMap::new())), scanner_components: Arc::new(RwLock::new(HashMap::new())), projectile_components: Arc::new(RwLock::new(HashMap::new())), }
pub fn combatant_entered(&self, module_name: &str) { self.players.write().unwrap().push(module_name.to_string()); self.motion_components .write() .unwrap() .entry(module_name.to_string()) .or_insert(MotionComponent::new()); self.damage_components .write() .unwrap() .entry(module_name.to_string()) .or_insert(DamageComponent::new()); self.scanner_components .write() .unwrap() .entry(module_name.to_string()) .or_insert(ScannerComponent::new()); self.projectile_components .write() .unwrap() .entry(module_name.to_string()) .or_insert(ProjectileComponent::new());}pub fn readlock<'a, T>( component: &'a ComponentHash<T>) -> RwLockReadGuard<'a, HashMap<String, T>> { component.read().unwrap()}pub fn writelock<'a, T>( component: &'a ComponentHash<T>,) -> RwLockWriteGuard<'a, HashMap<String, T>> { component.write().unwrap()}const MAX_X: f32 = 1000.0;const MAX_Y: f32 = 1000.0;pub mod damage;pub mod motion;mod projectiles;pub mod scanner;First I use a couple of type aliases to keep the “bracket noise” down when nesting generic type parameters in the upcoming function signatures and structs. Each system has a corresponding ComponentHash, which Is a HashMap wrapped by a RwLock and an Arc. In other words, the game state holds an atomically reference counted read-write lock on a hash map for each component.
In the combatant_entered() function, each of the HashMaps is updated to contain a new default entry for the new player. Remember when I said the Entry API was incredibly powerful? Here it is again:
self.motion_components.write().unwrap().entry(module_name.to_string()).or_insert(MotionComponent::new());We can skip the usual ugliness with if statements or pattern matches to check for the existence of an item and just use the or_insert() function to insert a new entry if one doesn’t already exist.
Next, we have what might be considered the most complex Rust syntax that I’ve used in the book so far:
pub fn writelock<'a, T>(component: &'a ComponentHash<T>) -> RwLockWriteGuard<'a, HashMap<String, T>> { component.write().unwrap()}All I’ve done is create a shortcut (I could also have used a macro) for calling .write().unwrap(). Every single access to every component for every system required the use of the RwLock methods, and I got tired of typing them all of the time.
This function signature includes a lifetime specifier (‘a) and a generic type parameter (T). Without getting into too many gory details, this code indicates that the returned RwLockWriteGuard must last as long as the component passed in as a parameter. We use generics here so we can get a RwLockWriteGuard on any of the component HashMaps, even though each map contains values of different types.
Building the Components and Systems
As we went over earlier, a component is a small, discrete piece of state. A system is some set of logic that operates on that state. The separation of components and systems makes code easier to test, and the smaller surface area over which write locks need to be acquired help reduce the risk of “wait blocks” in the game loop.
I won’t show the code for each system in the interest of saving a few trees (and bytes). You can download all of the engine code and check out each system on your own. With a few exceptions, most of the system implementa- tions try and mimic the behavior and spirit of Poindexter’s original Crobots code. Let’s take a look at the core of the damage system:
waros/botengine/src/game/damage.rs
use super::*;use crate::events::log_event;use crate::game::{readlock, writelock};pub struct DamageSystem { logger: Option<Sender<GameEvent>>,}
impl System for DamageSystem { fn apply(&self, cycle: u32, game_state: &Arc<GameState>) { game_state.players.read().unwrap().iter().for_each(|p| { writelock(&game_state.damage_components) .entry(p.to_string()) .and_modify(|dc| self.advance(p, game_state, dc, cycle)); }); }}The apply() function will mutate a damage component for each player in the game by calling the damage system’s advance() function on that mutable refer- ence, acquired from a write lock. Since the damage system is ideally the only part of the game that mutates damage components, we don’t have to worry about blocking other threads to perform these quick mutations.
There is a “breadcrumb” pattern used by multiple systems in the game. Each system sets some value at the end of its apply() loop, leaving it behind to be used by other systems that process next. For example, the collision system leaves values in the collision components indicating detected collisions during that game loop cycle.
The damage system just reads any active collisions and applies damage accordingly. It’s responsible for ensuring that detected collisions only last as long as they should. For example, explosion damage from projectiles actually last a few cycles (also called “ticks”), which means the damage system may apply damage multiple times per explosion.
Let’s take a look at the rest of the code for the damage system to see how it applies collision damage, projectile damage, and then checks to see if players are dead: waros/botengine/src/game/damage.rs
impl DamageSystem { pub fn new(logger: Option<Sender<GameEvent>>) -> DamageSystem { DamageSystem { logger } } pub fn advance( &self, player: &str, game_state: &Arc<GameState>, dc: &mut DamageComponent, cycle: u32, ) { self.apply_collision_damage(player, game_state, dc, cycle); self.apply_projectile_damage(player, game_state, dc, cycle); self.check_death(player, dc, cycle); }
fn check_death(&self, player: &str, dc: &mut DamageComponent, cycle: u32) { if dc.damage >= DAMAGE_MAX && !dc.dead() { dc.damage = DAMAGE_MAX; dc.status = DamageStatus::Dead; log_event( &self.logger, GameEvent::Death { cycle, victim: player.to_string(), }, ); } }
fn apply_collision_damage( &self, player: &str, game_state: &Arc<GameState>, dc: &mut DamageComponent, cycle: u32, ) { let mcs = readlock(&game_state.motion_components); let mc_opt = mcs.get(player); match mc_opt { Some(mc) => match mc.collision { Some(CollisionType::Player(ref p)) => { dc.add_damage(DAMAGE_COLLISION); self.log_damage( cycle, DAMAGE_COLLISION, DamageKind::Collision( CollisionType::Player(p.to_string()), player, ); } } } } }Some(CollisionType::Wall(ref p)) => {
dc.add_damage(DAMAGE_COLLISION); self.log_damage( cycle, DAMAGE_COLLISION, DamageKind::Collision(CollisionType::Wall(p.clone())), player, );}None => {} }, None => {} }
fn apply_projectile_damage( &self, player: &str, game_state: &Arc<GameState>, dc: &mut DamageComponent, cycle: u32,) { let pcs = game_state.projectile_components.read().unwrap(); let pc_opt = pcs.get(player); match pc_opt { Some(pc) => { for x in 0..1 { if pc.projectiles[x].active_hits.contains_key(player) { let dmg: u32 = pc.projectiles[x].active_hits[player]; println!("Doing explosion damage {} to player {}", dmg, player); dc.add_damage(dmg); self.log_damage(cycle, dmg, DamageKind::Projectile, player); } } } None => {} }}
fn log_damage(&self, cycle: u32, amount: u32, kind: DamageKind, victim: &str) { log_event( &self.logger, GameEvent::Damage { cycle, amount, kind, victim: victim.to_string(), }, );}#[derive(Debug)]pub enum DamageStatus { Alive, Dead,}
#[derive(Debug)]pub struct DamageComponent { pub damage: u32, pub status: DamageStatus,}
#[derive(Debug)]pub enum DamageKind { Collision(CollisionType), Projectile,}
impl DamageComponent { pub fn new() -> DamageComponent { DamageComponent { damage: 0, status: DamageStatus::Alive, } }
pub fn dead(&self) -> bool { match self.status { DamageStatus::Dead => true, _ => false, } }
fn add_damage(&mut self, amount: u32) { self.damage += amount; // death will be checked end of this tick }}
const DAMAGE_COLLISION: u32 = 2;pub const DAMAGE_MAX: u32 = 100;The logger you’ve seen in the game loop and the damage system helps support playback, which we’ll discuss next.
Supporting Match Playback
Section titled “Supporting Match Playback”The game engine’s loop runs as fast as it possibly can. This is fine for when we just want to determine who will win the match. But what if we want to watch the match live, or watch a replay of the match? To facilitate this, I’m using a Sender2 to send important game events bound to the cycle/frame
Creating WebAssembly Robots
Now for the fun part: creating WebAssembly robots! We’ve built an engine that can load WebAssembly modules into memory, expose a runtime host for them, and safely allow them to interact with a virtual environment and manipulate shared state. Now it’s time to exercise that engine by building some robots.
First, let’s create a fairly target. I wanted a “read hungry” robot to ensure that no matter how frequently a robot queried its own state, it couldn’t cause a threading dead lock in the system. Create a new library Rust module called ots and add it to the workspace. Its Cargo.toml should look like the following:
waros/ots/Cargo.toml
[package]name = "ots"version = "0.1.0"
[lib]crate-type = ["cdylib"]
[dependencies]warsdk = { path = "../warsdk" }This robot only depends on the SDK we created earlier that exposes the host functions. Let’s take a look at lib.rs:
waros/ots/src/lib.rs
extern crate warsdk;use warsdk::*;
#[no_mangle]pub extern "C" fn botinit() -> i32 { drive(90, 10); loop { damage(); speed(); }}This robot, regardless of its starting position, drives north at a speed of 10%. It then goes into an infinite loop where it continually queries its own state. This robot should eventually collide with the northern wall and stop, where it will keep eagerly consuming its state.
Since we will probably never need to compile this robot for anything other than the wasm32-unknown-unknown target, we can tell Cargo to default to that by creating a .cargo/config file inside the project directory:
waros/otrs/.cargo/config [build] target = “wasm32-unknown-unknown”
Creating the Rook
The Rook, inspired by Poindexter’s original implementation.⁹ is a robot that seeks the middle of the game board. Once there, it will move laterally east and west, scanning for potential targets at the four compass points. Once it finds one, it stops and fires at it until there are no more targets in range.
This is a subtle yet fairly powerful strategy. If an opposing robot is anywhere but the extreme top or bottom of the game board, it will eventually be detected by the rook’s scanners and fired upon. The only escape is to keep moving or to kill the rook.
Create a new library Rust project called rook, add it to the workspace, and set its default compilation target to wasm32-unknown-unknown. Update its Cargo.toml to include a relative path dependency on the warsdk code. Let’s take a look at what the rook looks like written in Rust:
waros/rook/src/lib.rs /* Inspired by https://github.com/tpoindex/crobots/blob/master/src/rook.r *
- Will move to the center of the field and then patrol from East to West,
- scanning all four compass points for targets. If it is hit while scanning
- it will change direction
- Note: this rook ignores incoming fire while on its way to the center of the
- battlefield. */
extern crate warsdk;use warsdk::*;struct State { course: i32,}⁹. github.com/tpoindex/crobots/blob/master/src/rook.r
#[no_mangle]pub extern "C" fn botinit() -> i32 { go(500, 500);
let mut state = State { course: 0 };
loop { look(ANGLE_EAST, &mut state); look(ANGLE_NORTH, &mut state); look(ANGLE_WEST, &mut state); look(ANGLE_SOUTH, &mut state);
if loc_x() > BOUND_X_MAX { reverse(&mut state); }
if loc_x() < BOUND_X_MIN { reverse(&mut state); }
if speed() == 0 { // bumped into something reverse(&mut state); } }}
fn look(angle: i32, state: &mut State) { let mut range = scan(angle, 2);
// Fire at targets in range until we have no targets in range while range > 0 && range < PROJECTILE_MAX_RANGE as i32 { if speed() > 0 { drive(state.course, 0); }
if range > BLAST_RADIUS { // don't want to blow ourselves up! cannon(angle, range); } range = scan(angle, 2); }}
fn reverse(state: &mut State) { if state.course == ANGLE_E{ state.course = ANGLE_WEST; } else { state.course = ANGLE_EAST; }}
const BOUND_X_MIN: i32 = 80;const BOUND_X_MAX: i32 = 920;In this robot’s implementation, you can see we now have our own internal, mutable state. This is a really powerful capability, because it means that the robots can make complex decisions based on observations from previous iterations through their loops. In the case of the rook, it maintains the direction it’s facing so it can reverse it when it reaches a boundary near the eastern or western edges of the game board.
Cry Havoc, and Let Slip the Robots of War!
You’ve got a game engine, and you’ve got a couple of robots (as well as a couple included in the code not listed in the chapter). It’s time to pit them against each other and see what happens. To do this, we’ll create another project in the workspace called consolerunner, a CLI application that loads wasm modules and invokes the engine:
waros/consolerunner/src/main.rs
extern crate botengine;use botengine::{Combatant, Gameloop};use std::sync::mpsc::channel;use std::sync::Arc;use std::thread;use std::time;fn main() { let gs = Arc::new(botengine::GameState::new()); let b1 = botengine::Combatant::buffer_from_file( "./bots/otrs.wasm"); let bot1 = b1.unwrap(); let b2 = botengine::Combatant::buffer_from_file( "./bots/rook.wasm"); let bot2 = b2.unwrap(); let rb = botengine::Combatant::buffer_from_file( "./bots/rabbit.wasm"); let rabbit = rb.unwrap(); let my_gs = gs.clone(); let debug_gs = gs.clone(); let (sender, receiver) = channel(); thread::spawn(move || loop { match receiver.recv() { Ok(ge) => println!("{:?} ", ge), Err(_) => {} } }); let mut gl = Gameloop::new(my_gs, 100_000, 3, Some(sender)); let _handle = Combatant::start("bot-1", bot1, gs.clone());let _handle2 = Combatant::start("rook", bot2, gs.clone());let _handle3 = Combatant::start("rabbit", rabbit, gs.clone());let game_result = gl.start();
thread::sleep(time::Duration::from_secs(1));
println!( "Game loop terminated: {:?}\nState: {:?}", game_result, debug_gs);This code loads three robots from the bots directory (the files were just copied from target output of other modules), creates the GameState, and shares clones of the Arc of that state with instances of the Combatant struct.
When all is ready to go, we invoke start() on the game loop and wait for the match to resolve after 100,000 frames or cycles. You’ll also see that I’ve created a channel and set up a thread where I await events in an infinite loop. This prints them to the console, but you can imagine a whole host of other things we could do with the list of game events.
Run the application either by compiling and running the binary or simply with cargo run. You’ll see a ton of spam that comes from the rook as it launches missiles at the rabbit as the rabbit bounces randomly across the game field. Since the rabbit never spends more than a single frame sitting in a spot, it usually manages to escape every match almost completely unharmed, save for a few unfortunate collisions with walls. Poor otrs heads north, hits a wall, incurs two points of damage, and then spends the rest of the match idle.
Congratulations! You now have a fully functioning game engine inspired by the original Crobots that pits multiple WebAssembly modules against each other. This can be used to teach people how to write Rust WebAssembly modules as well as for a lot of fun and senseless virtual battlefield violence, and to illustrate how to allocate dedicated threads to WebAssembly host runtimes.
Room for Improvement
Section titled “Room for Improvement”There’s plenty more that you could do with this game engine. Most of it, however, has little to do with WebAssembly itself. You could add a new system and component pair that allocates points to players every time they do damage to another player. You could then create yet another system and component pair that can declare victory and terminate a match early when only a single robot is left standing.
I hope you will see places where you can have fun improving this code to continue learning Rust and WebAssembly.
Robots in the Cloud
Section titled “Robots in the Cloud”The WARoS engine is deliberately designed as a module that you can use from any kind of code. If this were published as a public crate on crates.io, you could declare a dependency on it in any application you’re writing and immediately gain the ability to run multi-player WebAssembly combat matches on demand.
If you wanted to expose this as a cloud offering, you’re only a few steps away. You could build a website that allows developers to upload their own robot modules, and then the website could hold randomly chosen matches between stored robots. If you wanted to get really fancy, you could create a logger (just a Receiver half of a channel) that, instead of displaying events to the console, emits them to a message broker like NATS, RabbitMQ, or Kafka. You could then have a web page listening on web sockets for events, rendering matches in real time for live spectators.
The possibilities are endless—leader boards, competitions, prizes, achievements, even different kinds of battlefields with obstacles and barriers other than simple walls at the edge. I would love to spend months coding all of that, but this book is about WebAssembly, so I (and my editor) had to draw the line somewhere.
If you’re as into distributed systems as I am, one could even imagine a cluster in which a match execution service had been deployed, awaiting signals from a message broker to begin a match. As a match begins, it emits events back to the broker, which could be listened to by a scribe service (recording matches for posterity), a projector service (updating live state of each robot and match), and to a real-time spectator service responsible for delivering updates on matches straight to browser clients.
Wrapping Up
Section titled “Wrapping Up”This chapter was arguably the most “rusty” of the chapters. There were a number of core lessons at the heart of this chapter and are the reason for the relatively large amount of code. If you only scratch the surface of Rust, you’ll never fully take advantage of its true power.
In this chapter, first and foremost, you saw an example of how to hide tremendous complexity behind a simple API—the host functions available to the robots in your virtual arena. Next, you saw how to manage complex, shared access to both mutable and immutable data. Finally, you explored some of Rust’s intrinsic support for threads. There are frameworks out there with simpler APIs, but knowing the standard library implementation is invaluable.
The code for this chapter also provides a foundation for further exploration. If you want, you can add things like obstacles in the arena, you can allow players to choose from a variety of weapons instead of giving them all the same gear, you can play with the motion system or convert the whole thing from robots to space ships or dragons.
Conclusion
Throughout this book, you’ve been on a journey. You’ve started at the very basics and foundations of WebAssembly, learning what it is, what it isn’t, and what you can do with it even at the lowest levels writing wat code directly.
From there you learned about how WebAssembly and JavaScript can interact, from the foundational levels of low-level interop to the use of high-level code generation tools that do everything from wrap the JavaScript APIs to expose UI-featured, React-like web application development frameworks.
then took the next step in that journey, learning how to host WebAssembly modules within Rust itself for everything from running a checkers game in the console to controlling LEDs on a Raspberry Pi. And now, you’ve put every ounce of that journey to work for you in order to create a reusable game engine capable of allocating dedicated threads to WebAssembly modules as their internal code navigates the hazards of a virtual battlefield that can be hosted in a console, on the web, in the cloud, or anywhere else.
Hopefully the next step in this journey will involve you continuing to explore, experiment with, and learn from, the combination of the Rust programming language and the emerging and game-changing WebAssembly standard. Nothing would make me happier than hearing about all of the great projects started after being inspired by this book. You should take what you’ve learned in this book and explore, fail, learn, and find the next amazing thing to build, no matter how big or small.
APPENDIX 1
WebAssembly and Serverless
If you’ve been keeping up with your home game of “buzzword bingo,” then you’ve undoubtedly heard of the latest and greatest thing that claims to solve all of our problems—serverless. Since serverless is a topic that already has multiple books on its own, I didn’t want to derail the main journey of the book with a lengthy digression on it.
However, I think it’s important to provide some discussion and perspective around what serverless is, with the hype stripped away, and how WebAssembly development might fit into that rapidly expanding area of innovation.
Serverless 101
Serverless may be more popular on the Internet for those exclaiming, “serverless still has servers!” than for the actual concept. Stripped from the hype, my own view of serverless is that as we continue to build smaller and smaller components, designed to elastically scale and conform to all of the standards for cloud native development, we reach a point where we start to see a pattern emerging.
In this pattern, we start off a microservice with a stack of boilerplate. This boilerplate is responsible for standing up a server, exposing an endpoint—be it REST or RPC or pub/sub or whatever—securing and routing requests to the business logic, responding to callers with some standardized serialized payload. This boilerplate can also include logging, application monitoring, tracing, security, fault tolerance, ad nauseum.
What we often see is that as our services get smaller, so too do the core bits of business logic. At some point we notice that we’ve got more boilerplate than “real code.” When you have hundreds of services in many different clusters and they’re all running duplicated in multiple availability zones, this boilerplate starts to look like a lot of unnecessary overhead.
The way I view serverless is that it takes the core function out of the service and then defers all of the other requirements previously managed by dupli- cated boilerplate to the platform, which is in most cases a cloud provider or some abstraction within a cluster like OpenFaaS (I will talk about that shortly). Serverless is also reactive—a serverless function, stripped of its surrounding onion of boilerplate, awaits an event, performs a task, and gets out of the way.
If you’re still a little fuzzy on the subject, I highly recommend searching for blog posts, use cases, and case studies on when and where serverless is an ideal solution, rather than the technology behind individual serverless implementations like AWS Lambda or Google Cloud Functions.
Intersection of WebAssembly and Serverless
Now that we’re all on the same page with the idea that serverless is just event- driven functions with their ceremonial robes of non-functional requirements delegated to a platform abstraction, let’s talk about what any of that has to do with WebAssembly.
After reading this book, hopefully your perspective on what WebAssembly is and how it can be harnessed has changed. A WebAssembly module is a portable encapsulation of some set of functionality. Where it begins to intersect with serverless is that on their own, WebAssembly modules are helpless. It cannot make HTTP requests from inside a module without an explicit contract with the host allowing it to do so, it can’t listen on endpoints unless the host lets it do it. By and large, WebAssembly modules are more limited than regular serverless functions—and that’s a good thing.
As you’ve seen in this book, if you write your WebAssembly code in a way that conforms to a well-known host interface (like the one provided by a compliant web browser), then your code is truly portable. It can run anywhere that contract is satisfied, whether that’s a Raspberry Pi, a Rust console application, a web browser, or a serverless platform like the ones I’ll discuss next.
WebAssembly in the Cloud
Every big cloud provider today has some form of support for serverless com- puting, or “cloud functions.” They each have their own name for it, and each one of the providers tries to add value in their own unique way to convince customers that their function hosting is better than everyone else’s. Amazon
AWS has Lambda,¹ Google Cloud Platform has Google Cloud Functions,² Microsoft has Azure Functions,³ and Alibaba Cloud has Function Compute.⁴
To the best of my knowledge, none of these serverless platforms has any kind of native support for WebAssembly—yet. I am hopeful that by the end of 2019, at least one of the major providers will allow for some kind of native integration of WebAssembly modules into cloud functions. Just the binary portability alone makes this an appealing offering. Some providers may be waiting for the host interface to get a little more robust (e.g., to allow native string passing so there wouldn’t have to be explicit allocation calls in the host contract).
Today, Amazon Lambda supports a Rust runtime for functions. This means you could take the Rust WebAssembly host code examples from this book and write a host that consumes JSON events, converts them into something suitable for the hosted module, and invokes a function. Is this really worth the overhead, though? Do we actually gain any benefit from creating another nested layer within a cloud function?
In some cases it might be useful. Given the limited abilities of a WebAssembly module, they become notably easier to test. For example, a JavaScript function that makes external HTTP requests would require complicated mocks, injection, or standing up a fake server to test properly. But if the WebAssembly module just invoked a make_http_request() function, then a test harness for the module could easily fake it. Whether this additional degree of indirection is worth it depends on you, your development team, and of course the problem you’re trying to solve. This scenario does gain a bit more traction when you plan on running the same logic both inside and outside of the serverless platform.
As the WebAssembly specification grows and the community of developers creating Wasm-based solutions also grows, I expect a lot of people to notice the potential of combining WebAssembly’s performance, security, and portability with the flexibility and cost-effectiveness of cloud functions.
Serverless WebAssembly in the Wild
There are a number of projects available now where people are experimenting with serverless WebAssembly in one form or another. For example, Geoffrey Couprie has written serverless-wasm,⁵ a framework that starts up an HTTP
[1] aws.amazon.com/lambda [2] cloud.google.com/functions [3] azure.microsoft.com/en-us/services/functions [4] www.alibabacloud.com/product/function-compute [5] github.com/Geal/serverless-wasm server and, through a toml configuration file, can route HTTP requests to different wasm modules. The host contract for this framework looks like this (at the time this book was finished):
mod sys { extern { pub fn log(ptr: *const u8, size: u64); pub fn response_set_status_line(status: u32, ptr: *const u8, size: u64); pub fn response_set_header(name_ptr: *const u8, name_size: u64, value_ptr: *const u8, value_size: u64); pub fn response_set_body(ptr: *const u8, size: u64); pub fn tcp_connect(ptr: *const u8, size: u64) -> i32; pub fn tcp_read(fd: i32, ptr: *mut u8, size: u64) -> i64; pub fn tcp_write(fd: i32, ptr: *const u8, size: u64) -> i64; pub fn db_get(key_ptr: *const u8, key_size: u64, value_ptr: *const u8, value_size: u64) -> i64; }}This framework allows WebAssembly modules to read and write over raw TCP connections as well as make connections to a database back-end. As I mentioned earlier, this contract can be satisfied by anything, including a mock host which makes testing these modules fairly easy. It’s up to you whether you decide to let your modules make external connections.
Colin Eberhardt takes a different approach in his blog post,^6 where the WebAssembly function written in Rust is hosted in AWS’s NodeJS Lambda runtime. This is certainly a far simpler way to host a WebAssembly module than trying to manipulate all of the lower-level Rust APIs you’ve seen in this book to host a module. Using NodeJS as the host runtime means the Rust WebAssembly module developer can take advantage of wasm-bindgen, making it even easier to write modules.
Yet another option available for serverless WebAssembly is the use of Cloudflare Workers. They just recently announced support for WebAssembly workers^7 and you can use the wasm-pack tool to bundle up your WebAssembly code and deploy it to Cloudflare, as illustrated in their blog post^8 covering the subject. This support is still JavaScript-based, so it resembles using a NodeJS runtime in AWS to invoke a WebAssembly module, but this is definitely an indication that the future of serverless WebAssembly is a bright one.
[6] blog.scottlogic.com/2018/10/18/serverless-rust.html [7] https://blog.cloudflare.com/websassembly-on-cloudflare-workers [8] blog.cloudflare.com/cloudflare-workers-as-a-serverless-rust-platform/
Integration with OpenFaaS
OpenFaaS⁹ (Open Functions as a Service) takes a different approach to cloud functions. Where the major cloud providers implement all of the underlying infrastructure for you, OpenFaaS expects you to have that infrastructure available (which could still be AWS, GCP, Azure, etc).
There could be full books written about OpenFaaS as well, so I will try and keep my explanation brief. Unlike the other cloud providers which have different runtimes for each language, OpenFaaS has a single runtime for all functions—docker and the deployed OpenFaaS components.
In OpenFaaS, your function is a compiled binary inside a docker image. This docker image also contains a watchdog process that acts as a proxy between the OpenFaaS gateway and your function. It routes incoming requests for function invocations to your process. The classic gateway communication mode is about as simple as it gets: the request payload is conveyed to your process via stdin and your response is delivered via stdout. There’s also a newer watchdog type¹⁰ that’s faster and uses HTTP.
So while your function process is just a simple binary, OpenFaaS takes care of waking it up and invoking it on demand and deals with the complexities of trying to keep it “warm,” and so on. You could also use a WebAssembly module here. All you’d need is a host process (e.g. a Rust application) that conformed to any of the OpenFaaS watchdog requirements and you could quickly turn your WebAssembly module into a function that could be launched on-demand in a Kubernetes cluster hosted wherever you like.
In this scenario, you could also reap the benefits of knowing the WebAssembly module could never do anything to harm your cluster or OpenFaaS, because the host is in complete control of what the module can and cannot do. You can even verify that the module was deployed by the right people or services—the subject of this book’s second appendix. [1] www.openfaas.com [2] docs.openfaas.com/architecture/watchdog
APPENDIX 2
Securing WebAssembly Modules
I devoted the vast majority of the book to illustrating how WebAssembly modules can be created, hosted, consumed, and integrated. What I didn’t talk about was, once you’ve got a WebAssembly module, what are the security concerns and how do you mitigate them?
This appendix will briefly mention a few things that you should keep in mind when considering the security implications of using WebAssembly. It is by no means an exhaustive reference or guide.
General Security Concerns
The most basic security concern with WebAssembly modules you saw in the “round-trip” compilation sample early on in the book. Anything that you compile into a wasm file can be disassembled and converted back into wast text format, or even other languages capable of targeting WebAssembly.
This means that you should never believe that anything in your module will remain private. Nor should you ever put anything into the WebAssembly module that could be considered a trade secret. In other words, if you wouldn’t want it exposed to the public, don’t put it in a WebAssembly module. This is essentially the same advice given to people writing client-side JavaScript. We’ve got obfuscation and minimization tools, but if someone wants to reverse engineer your logic, they’ll do it.
Browser-Based Attack Vectors
Internally, WebAssembly has a number of features¹ that keep it fairly secure. It has sandboxed memory and a number of common ways of attacking code
[1] webassembly.org/docs/security like forcing invalid jumps or corrupting memory don’t happen inside a WebAssembly sandbox.
That said, there is still a JavaScript communication happening between your module and the client side in the browser. This means that handoff between the module and JavaScript can be hijacked the same way any other client-side code running in the browser can. These days most web applications are built defensively, but it can be easy to let our guard down and think that just because we’re using a binary file instead of script that we’re safe.
Any call that originates from inside your WebAssembly module can also originate from inside a debugger or from inside anything pretending to execute code on your behalf. For this reason, your back-end services supporting your WebAssembly module should be just as secure as they would be supporting regular Angular or React applications. One fairly easy to execute task is to download the WebAssembly module, disassemble it, alter the code, recompile it, and then re-inject it into the browser via proxy. If there’s anything you wouldn’t want executed in this scenario, you’ll want to require credentials or some other form of checking for legitimate requests.
I am not a security expert, so I typically adopt a pattern I refer to as “Paranoia-Driven Development” (PDD). I make the assumption that every asset that can be downloaded from my site can be captured, altered, and used in a malicious or unexpected fashion. There are tools that can be used to ensure that scripts haven’t been modified in transit, but even those can be defeated by people with enough determination and tools.
Signing and Encrypting WebAssembly Modules
Section titled “Signing and Encrypting WebAssembly Modules”In the previous section I talked about taking a paranoia approach to defense against external client tampering with WebAssembly modules. The consequences for module tampering can be far, far worse if you’re distributing and using modules within your data center, cloud, or enterprise.
Let’s say you’ve adopted WebAssembly and you’re running some form of FaaS (Functions as a Service) infrastructure. Everything is great and you’re loving the ease and portability you get, and you love the nearly crash-proof nature of running an interpreter on WebAssembly modules.
What if someone were to manage to slip a bad WebAssembly module into the environment. If your host protocol allows those modules to do things that could corrupt data, download data, or make outbound network calls, you could have all sorts of malicious actors controlling your system. What we need is some way to ensure the digital provenance of WebAssembly modules
—to ensure that they haven’t been tampered with and that they were created by only authorized personnel or processes.
We can use cryptographic signatures to handle this problem. A simple hash of an array of bytes will allow us to tell if a file has been tampered with. We see this pattern used all the time on public downloads when the official sites also publish a checksum so you can verify that the file is legitimate.
A cryptographic signature takes that concept one step further. It produces a value that will not only change if the source file bytes change, but it is entirely dependent on some asymmetric, private key. In other words, you have to be in possession of a very carefully guarded secret in order to produce a valid signature.
Before your host code—whether it’s a browser or a Rust console application or an OpenFaaS container—executes any code in a WebAssembly module, it should verify the signature that accompanies the file. If the verification fails, then the party who signed that file was not in possession of the right key and you should not only reject the file, but probably create some form of alert to trigger an investigation.
There are quite a few techniques to sign an array of bytes, but I am particu- larly partial to using Ed25519² keys. They’re fast, simple, easy to use, and generally less vulnerable to certain types of attacks that have caused havoc in the past. There are more mathematical reasons to like this signature algorithm that I won’t go into here because they make my head hurt.
With the EdDSA signature algorithm, you use a single private key called the seed key to sign an arbitrary binary payload. You can then use public keys generated from the seed to verify that signature. The availability of many public keys for a single binary key often creates some very powerful and ele- gant security solutions.
In this small Rust example (also included with the book code downloads), I illustrate using the signatory and signatory-dalek crates to sign and verify the contents of a WebAssembly file passed as the first argument on the command line:
signer/src/main.rs
use std::env;use std::fs::File;use std::io::prelude::*;use signatory::{ed25519, Encode};use signatory_dalek::{Ed25519Signer, Ed25519Verifier};- tools.ietf.org/html/rfc8032
fn main() -> Result<(), std::io::Error> { let args: Vec<String> = env::args().collect(); let path = &args[1];
let mut file = File::open(path)?; let mut wasm_buf = Vec::new(); let _bytes_read = file.read_to_end(&mut wasm_buf)?; let buf: &[u8] = &wasm_buf;
let seed = ed25519::Seed::generate(); let base64 = signatory::encoding::Base64 {}; println!( "Generated a seed/private key: {}", seed.encode_to_string(&base64).unwrap() ); let signer = Ed25519Signer::from(&seed); let sig = ed25519::sign(&signer, buf).unwrap(); println!( "Signature for {} created: {}", path, sig.encode_to_string(&base64).unwrap() );
let pk = ed25519::public_key(&signer).unwrap(); let verifier = Ed25519Verifier::from(&pk); let verified = ed25519::verify(&verifier, buf, &sig).is_ok(); println!("Signature verified: {}", verified);
Ok(())}Here’s a sample run of the application:
$ target/debug/signer ../checkers/checkers.wasmGenerated a seed/private key: AOdRsk3TwSMO4chzRv4+EvXoGPuP25eMughoBRIGoKw=Signature for ../checkers/checkers.wasm created:wzphNwHoiPJvgooU8j36H0t8M4djJ5Q0jyAbRPmIAmqZw+mBYG2dfCLgvCLd1b66qGncRQk0UfhcAba07oqvBw==Signature verified: trueThe hard part with signing files isn’t really the encryption code—others have already done the hard work for us by writing re-usable libraries. The difficulty with signatures is ensuring that the signature always accompany the file being signed.
There are a number of ways to do this. You could put the signature at the beginning of the binary file and then parse that out as you read it, treating the remainder of the binary file as the regular WebAssembly module. This has an added advantage of ensuring that the signature will never be apart from a file. This works because we know that ed25519 signatures are always 64 bytes, so we can simply read a fixed number of bytes from the beginning of the file.
I’ve coded up a sample (not refactored for cleanliness) that illustrates how to read a WebAssembly file, generate a signature from it, embed that signature in an output file, and then verify that the signature from a file matches the WebAssembly bytes—all of the tasks you would need to know how to do in order to secure the provenance of your modules. I’m only using base 64 encoding so I can print the signature out to the console:
use std::env;use std::fs::File;use std::io::{prelude::*, BufReader};
use signatory::ed25519::{Encode};use signatory_dalek::{Ed25519Signer, Ed25519Verifier};
fn main() -> std::io::Result<()> { let args: Vec<String> = env::args().collect();
let input = args[1]; let output = args[2];
let infile = load_file(input)?; let inbytes: &[u8] = &infile; let base64 = signatory::encoding::Base64 {};
// This seed is a private key - store this in a safe place. // Obviously, you'll want to persist this somewhere instead of // just using it once in memory... let seed = ed25519::Seed::generate(); let signer = Ed25519Signer::from(&seed); let sig = ed25519::sign(&signer, inbytes).unwrap(); let sig_encoded = sig.encode_to_string(&base64).unwrap();
let pk = ed25519::public_key(&signer).unwrap(); let verifier = Ed25519Verifier::from(&pk);
{ let mut out_file = File::create(output)?; out_file.write(sig.as_bytes())?; out_file.write_all(inbytes)?; }
println!( "Embedded signature into {} - output {}", input, output, sig_encoded );};let mut sigbuf = [0; 64];let mut wasmbuf = vec![];{ let in_file = File::open(output)?; let mut br = BufReader::new(in_file); br.read_exact(&mut sigbuf)?; br.read_to_end(&mut wasmbuf)?;}let wasmbytes: &[u8] = &wasmbuf;let insig = ed25519::Signature::new(sigbuf);let verify_res = ed25519::verify(&verifier, wasmbytes, &insig).is_ok();println!("Verification result on new bytes - {}", verify_res);Ok(())}fn load_file(path: &str) -> std::io::Result<Vec<u8>> { let mut file = File::open(path)?; let mut buf = Vec::new(); let _bytes_read = file.read_to_end(&mut buf)?; Ok(buf)}You could also use this same embedding technique to add additional metadata to your WebAssembly file that might come from your build process or developers. Or, you could wrap the WebAssembly module bytes in a protocol buffer³ binary file with fields for both raw bytes and a signature, which would save you the trouble of manually reading and writing custom binary file formats as you could just re-use the protocol buffer libraries available.
[1] developers.google.com/protocol-buffers Index
SYMBOLS ! (exclamation point) for procedural macros, 97 #[wasm_bindgen] macro, 69 () (parentheses), for parameters, 14–15 , (comma) in html! macro, 98 ? (question mark), hosting modules outside of browsers, 117
A A-star pathfinding, 83 ABI (Application Binary Interface), 140 abs(), 36 act(), 80, 83 adding integer examples
with hand-coded wast, 14–17 hosting modules outside of browsers, 117–119 with Rust, 47–50 stack vs. register machines, 8 with WebAssembly Studio, 6alert() binding JavaScript to Rust, 70 Rogue game, 76aliases chat example, 99, 106 type, 181 Alibaba Cloud Function Compute, 195
Amazon AWS Lambda, 195–196 AND, 24, 26, 33 and_modify(), 177 animated indicator, GISM example, 135, 139, 142, 144 anonymous functions, 57 Anti-Corruption Layers, 55, 101, see also services API GISM example, 133 hosted checkers example, 120, 124–128 WARoS, 157–162 Application Binary Interface (ABI), 140 ARC (Atomically Reference Counted), 168, 179 architecture, WebAssembly, understanding, 8–12 ARM devices, see also Raspberry Pi compiler for, 140 conditional compilation, 142, 150 setup for GISM example, 140–141 arrays, linearization, 21–23 AsMut trait, 92, 94 AssemblyScript, 6 assert_no_start(), 118 atomic locking, 163 Atomically Reference Counted (ARC), 168, 179 Azure Functions, 195
B battery indicator, GISM example, 135–139 bindings GISM example, 133 Hello, World example, 67–73 with js_sys crate, 87 Rogue game, 77, 87 with web_sys crate, 88 writing manually, 87 bit flags, 23–30, 62 bit masking, 23, 25–26, 33 bitwise operators, 24–27 Blinkt about, 151 GISM example, battery indicator setup, 135–139 GISM example, hosting, 142–150 timeouts, 144 block, 10, 31 blocks control flow instructions, 10 hand-coded checkers example, 31 board, checker hand-coded, managing state, 21–33 hand-coded, moving players, 35–38 hosted example, 126–129 Rusty version, 51–55 bounds, checking, 32 br, 10 br_if. 10 br_table. 10 branches, control flow instructions, 10 breadcrumb pattern, 182 breakpoints. 16 buffers. protocol, 204 build adding integer example, 48 checkers with Rust, 64 compiling applications for Raspberry Pi, 141 Hello, World example, 73 Bulk, 94 bytes calculating offset for checkers example, 22 calculating offset for hosted checkers example, 127 converting, 127 indexing of linear memory by, 22
C calc_offset(), 127 callback parameters, 76 cargo adding/removing targets, 140 ARM setup for GISM example, 140–141 creating projects, 48, 69 cross-compilation configuration, 140–141 Rust version, 50 serialization support, adding, 84 testing with, 138 updating, 71 cargo-web counter example, 91–99 installing, 91 change(), 90 channels cloning, 146 mpsc, 144 timeouts, 144 WARoS, 190 chat example, 99–112 building Yew service, 101–106 code files, 106 setup, 99–101 user interface, 106–112
ChatEngine building Yew service, 101–106 live chat example, 99–112 setup, 99–101 user interface for chat example, 106–112
checkers code for, 60 data constraints, 20–33 hand-coded, 19–42 hand-coded, bit flags, 23–30 hand-coded, game board state, 21–33, 35–38 hand-coded, imports, 38 hand-coded, players, 32–33, 35–38 hand-coded, setup, 20–21, 38 hand-coded, size, 41 hand-coded, testing, 27–30, 38–41 hosted version, 120–129 hosted version, API, 120, 124–128 hosted version, playing, 128 hosted version, setup, 120–123 rules, general, 19 rules, implementing in Rust version, 52, 55–60 rules, implementing in hand-coded example, 34 Rust, 50–65 Rust, interface for, 60–64 Rust, playing, 64 Rust, setup, 51–55
classes, exporting structs as, 78 cloning, channels, 146 cloud OpenFaaS, 197 Rust support, 195 WARoS in, 191 WebAssembly support, 194–197 Cloudflare, 196 CMake, 12 code, for this book, 60, 106, 151 collect(), 59 comma (.) in html! macro, 98 Common Language Runtime, 4, 8
compiler ARM devices, 140 conditional compilation, 142, 150 configuring for cross-compilation, 140–141 lifetime specifier, 95, 168, 181 release mode, 48 safety with Rust, 46 suggestions for function support, 159 visibility and round-trip compilation, 16
Component trait about, 90 chat example, 106–112 counter example, 92–99
components in Entity, Component, System (ECS), 165 reading values from, 177 WARoS, 165, 181–186
conditional compilation, 142, 150
conflicts, cargo, 71 console hosts, see hosts console variable, 92 ConsoleService, 92 Context struct, 92 control flow, 9
coordinates converting to memory offset, 21–23 creating, 52 Coordinates struct, 52 counter example, 91–99
coupling avoiding, 55 loose, 133
Couprle, Geoffrey, 195 crates, defined, 68 create(), 90, 107 Crobots, see also WARoS about, 156 fields from, 164 intrinsic functions, 157 resources on, 156 rules, 156
cross-site scripting rules, 29 crosscompiledemo, 141 crowning checkers rules, 20, 34 checkers, hosted version, 120 checkers, with Rust, 52 cryptographic signatures, 201-204 ctric crate, 146
D damage system, WARoS, 182-186 data types about, 9 aliasing, 181 converting with into(), 62 managing constraints in checkers example, 20-33 namespace qualifiers, 77 derive macro, 52, 57 deserialization chat example, 103 Rogue game, 83-87 with serde crate, 83 destroy(), 90 destructuring, checkers with Rust, 53 Display class, Rot.js, 77, 80 $distance, 35 docker images, 197 DOM, direct access, 11 draughts, see checkers draw(), Rogue game, 77, 79 drones, 152
E Eberhardt, Colin, 196 ECS (Entity, Component, System), see WARoS ECS (Entity, Component, System) multiple game loops, 178 separation with, 165, 177, 181 EdDSA signatures, 201-204 Elm, 90 else, 10, 31 encapsulation hosted checkers example, 124-128 Rogue game, 80, 86 encrypting modules, 200-204 end, 10 enemies, Rogue game, 74, 80, 82
Engine struct. Rogue game. 77-80, 83 entities In Entity, Component, System (ECS), 165 WARoS, 165 Entity, Component, System (ECS), see also WARoS multiple game loops, 178 separation with, 165, 177, 181 entry(), 177 Entry API, 177, 181 enums, converting to, 126 env, 65 equality tests, 57 errors bounds, 32 conversion, 62 html! macro, 98, 110 lib.rs file, 168 lifetime specifier, 95 references, 54 resolving imports when hosting modules, 120, 122 Rust messages, 62, 96 syntax, 98, 110 events scope, 120 exclamation point (!) for procedural macros, 97 expect(), 118 exports exporting functions explicitly, 16 exporting structs as a class, 78 hand-coded checkers example, 38 host responsibilities, 116 hosting modules outside of browsers, 116, 119 security, 39 extern converting intrinsic functions for WARoS, 158-162 importing functions, 63 wrapping in unsafe block, 63 Externals trait hosting modules, checkers example, 120, 122-123 WARoS, 177
F f32 type, 9 f64 type, 9 facades, 55, 101, see also services FFI (Foreign Function Interface), 159 ffi.rs file, 159 filter(), 59 floating-point numbers data types, 9 WebAssembly support, 158 -force option, 68 Foreign Function Interface (FFI), 159 frame index, 140 frame rates pulsing indicator in GISM example, 134, 139, 142, 144 timeouts, 144 WARoS playback, 185 frame values, 134, 140 frameworks, see also Entity, Component, System (ECS): Yew about, xiv advantages, 91 serverless-wasm, 196 free_cell(), 83 func, 14 FuncRef, 120-122 Function Compute, 195 function index, 120, 122-123 functions adding to hosted modules, 118 anonymous, 57 chaining iterators, 54, 59 compiler support suggestions, 159 exporting explicitly, 16 hosted modules, 120-123 importing, 63 index, 120, 122-123, 177 intrinsic functions for WARoS, 157 mapping in js_sys crate, 87 names, 7, 119, 150 namespace qualifiers, 77 as predicates, 31 referencing with gen_func_ref(), 176
G game loops about, 164 multiple, 178 WARoS, 162–166, 178– 181 games, see checkers; Crobots; Rogue WebAssembly game; WARoS garbage collection, 11, 46 gen_funcr(), 176 generic indicator module sys- tem, see GISM example generics
combining with traits, 94 converting types with in- to(), 62 hosted checkers example, 125 nesting, 181 WARoS, 181genesis moment, 45 get(), 177 GISM example, 131–152
ARM setup, 140–141 hardware for, 150 hosting, 141–150 module contract, 133– 134 module creation, 135– 140 overview, 132 powering, 151 running, 150 running on Raspberry Pi, 151 shutting down, 150 video, 152global variables
chat example with Yew, 101 declaring in wast, 32 specifying mutability, 33go(), 161 Google Cloud Functions, 195 grid points, Rogue game, 78– 80, 84
H heading angle, WARoS, 156 heap corruption, 9 Hello WebAssembly example, see adding integer exam- ples Hello, World example, 67–73
Hoare, Graydon, 45 hosts
checkers game, hosted version, 120–129 GISM example, contract for, 133–134 GISM example, hosting modules on, 141–150 hosting modules, 115– 130 hosting modules, simple example, 117–119 importing functions from, 63 limited to public exports only, 39 module state, 122, 124 pattern, 120 relationship to modules, 3, 5, 115–117 responsibilities and re- quirements, 115–117 suggestions for function support, 159 WARoS, 162, 166–178hot reloading, GISM example, 142–143 HTML chat example, 107–112 html! macro, 97, 110 html! macro, 97, 110 HTTP OpenFaaS, 197 serverless, 196 testing hand-coded checkers example, 29
I I2C, 133 i32 type, 9 i64 type, 9 Idempotent, 25 if, 10, 31 ILASM, 4 Importing
checkers, hand-coded, 38 checkers, with Rust, 63 functions, 63 host responsibilities, 116 hosted modules, 116, 120–122 names and, 65, 120 resolving imports, 120– 122 structs, 77$inRange, 32
Index.js file
counter example with Yew, 98 Hello, World example, 72 Integrating WebAssembly, 72Indexes
frame, 140 function, 120, 122–123, 177 vector, 54indicator system, see GISM example
Installation cargo-web for Yew, 91 Node, 68 Rust, 47 wasm-bindgen command- line tool, 68 WebAssembly Binary Toolkit (wabt), 12 WebAssembly target, 47
integer data types, 9
Internet of Things, 131–154
about, 131 GISM example, 131–152 GISM example, ARM set- up, 140–141 GISM example, hardware for, 150 GISM example, hosting, 141–150 GISM example, module contract, 133–134 GISM example, module creation, 135–140 GISM example, overview, 132 GISM example, running, 150 GISM example, running on Raspberry Pi, 151 GISM example, video, 152ideas for, 152–153 security, 153 testing, 137–139 WebAssembly advan- tages, 5, 131, 137, 153
into(), 62
Intrinsic Function Library, 157
intrinsic functions for WARoS, 157
invoke_export(), 119 invoke_index(), 122–123, 177 iter(), 57
Iterators chaining, 54, 59 checkers with Rust, 54, 57, 59 converting into vectors, 59 zipping, 57
J Java Virtual Machine (JVM), 8 JavaScript checkers, hand-coded, 27-30, 39-41 checkers, with Rust, 60-65 counter example with Yew, 91-99 development of, xiv effect of WebAssembly on, 5 functions mapping in js_sys crate, 87 Hello, World example, 67-73 integrating with, 67-88 integrating with Yew, 89-112 live chat example, 99-112 performance, xiv Rogue game, 73-88 security, 200 JoinHandle, 168 js! macro, 97, 105 js_sys crate, 87 jump, exploitation of, 10 jumps checkers rules, 20, 34 checkers with Rust, 53, 58-60, 65 JVM (Java Virtual Machine), 8
K key down events, Rogue game, 80-83 key frame animation, 139 kings, see crowning
L labels, control flow instructions, 10 Lambda, 195-196 Last In, First Out (LIFO), 8 lazy statics, 60 lazy_static, 60
LEDs about, 132 calculating base value, 136 GISM example, 131-152 GISM example, ARM setup, 140-141 GISM example, hardware for, 150 GISM example, hosting, 141-150 GISM example, module contract, 133-134 GISM example, module creation, 135-140 GISM example, overview, 132 GISM example, running, 150 GISM example, running on Raspberry Pi, 151 GISM example, video, 152 The Legend of Zelda, 32 lib.rs file error handling, 168 root module, 51 libraries, see crates lifetime specifier, 95, 168, 181 LIFO (Last In, First Out), 8 linear memory about, 10-12, 21 index by byte, 22 memory offset, 21-23, 71, 127 security, 9, 11 size of hand-coded checkers example, 41 storing and retrieving values, 30-32 linearization, 21-23 live chat, see chat example load_instance(), 125 local keyword, 35 local variables, 35 locking with Entity, Component, System (ECS), 166, 177, 181 WARoS, 164, 166, 177, 181 WebAssembly support, 163 log(), Rogue game, 76 logger, 185, 191
logging chat example, 103 macros, 103 Rogue game, 76 WARoS, 185, 191 with web_logger crate, 103 loop, 10 loops control flow instructions, 10 game loop, WARoS, 162-166, 178-181 ownership, 79
M machines register, 8 stack-based, 4, 8 macros procedural, 68, 97 serialization, 83 syntax errors, 110 triggering runtime, 69 wasm-bindgen, 68, 77 Yew, 90 map(), 57, 59 mapping chaining iterators, 54 checkers with Rust, 57, 59 functions with js_sys crate, 87 Rogue game, 78-80 source maps, 16 mathematics Rust support, 126 trig functions for WARoS, 158-159 memory about, 10-12, 21 address, 31 allocation in hand-coded checkers example, 21 Hello, World example, 70-71 index by byte, 22 memory offset, 21-23, 71, 127 restricting manually, 32 security, 9, 11 size of hand-coded checkers example, 41 storing and retrieving values, 30-32 memory offsets converting coordinates to, 21-23
Hello, World example, 71 hosted checkers example, 127 Message type, 107 messages channels, 144 chat example, 106-109 counter example with Yew, 93 errors, 62, 96 metadata, 68, 204 method keyword, 77 Microsoft Azure Functions, 195 Mini Black Hat Hack3r, 151 models about, 93 counter example with Yew, 93-99 modularization, 55 module declaration, 14 ModuleImportResolver, 120-129 modules about, 55 contract for GISM exam- ple, 133-134 creating for GISM exam- ple, 135-140 creating instance of, 118 creating module runner thread, 144-150 declaring, 14, 20 declaring exports, 38 hierarchy, 51, 93 hosting, 115-130 hosting, GISM example, 141-150 hosting, checkers game, 120-129 hosting, simple example, 117-119 isolating, 116 monitoring, 143-146 nesting, 51 relationship to hosts, 3, 5, 115-117 reloading, 142-143 root, 51 security, 199-204 separation with, 51, 60, 116 signing and encrypting, 200-204 state, 122, 124 submodules, declaring, 51
move by default pattern, 54 moves checkers, hosted version, 120 checkers, with Rust, 57- 60 validating in hand-coded checkers, 35 Mozilla, 6, 45 mpsc (multi-producer, single- consumer) channels, 144 Msg type, 107 multi-producer, single-con- sumer (mpsc) channels, 144 &mut self, 56 mut_static, 60 mutability global mutable state, 61 mutable references, 56, 92 specifying for global vari- ables, 33
N names exported functions, 119 functions and conditional compilation, 150 functions and no_mangle macro, 7 imports, 65, 120 namespace qualifiers, 77 NET Common Language Runtime, 4, 8 new cargo, 48, 69 Pubnub, 105 WARoS game loop, 179 no_mangle macro, 7 Node cloud hosting WebAssem- bly, 196 Hello, World example, 71 installing, 68 resources on, 68 nop, 10 notation Polish, 9 postfix, 14 prefix, 9, 14 notifications checkers, hand-coded, 38 checkers, with Rust, 63
GISM example, 143-146 Rogue game, 76
npm Hello, World example, 71 installing, 68 resources on, 68 nulls, lack of in Rust, 46
O offsets hosted checkers example, 127 memory, 21-23, 71, 127 unit, 22 Open Functions as a Service (OpenFaaS), 197 open_box(), 82 OpenFaaS (Open Functions as a Service), 197 operators, bitwise, 24-27 Option type, 46, 79 OR, 24 or_insert(), 181 order of instructions in wast, 14 ownership loops, 79 references and, 54 vs. references, 79 Rust, 54
P package.json, Hello, World exam- ple, 73 pages, 11 parameters syntax, 14 using return value from a function as, 31 Paranola-Driven Development (PDD), 200 parentheses (()), for parame- ters, 14-15 Parity Tech, 117 passStringToWasm(), 71 pathfinding, 82-83 pattern matching hosting modules outside of browsers, 119 Result types, 58 patterns breadcrumb, 182 hosting, 120 pattern matching, 58, 119 working with WebAssem- bly and Rust, 7 PDD (Paranola-Driven Devel- opment), 200 performance JavaScript, xlv Rust, 46 permissions, read/write ac- cess, 151 pilhost, creating, 135 Pimoroni, see Blinkt players hand-coded checkers ex- ample, 32–33, 35–38 Rogue game, 80–87 PLCs (Programmable Logic Controllers), 152 Poindexter, Tom, 156 Polish notation, 9 postfix notation, 14 prefix notation, 9, 14 privacy, 199 procedural macros, 68, 97 Programmable Logic Con- trollers (PLCs), 152 property queries, 80 protocol buffers, 204 public key, EdDSA signa- tures, 201 publish key, Pubnub, 100, 105, 111 Pubnub account creation, 99 building Yew service, 101–106 live chat example, 99–112 setup, 99–101 user interface for chat example, 106–112 pulsing indicator, GISM exam- ple, 135, 139, 142, 144 Q question mark (?), hosting modules outside of browsers, 117 Quidditch, 152 R rabbit robot, WARoS, 190 Raspberry Pi about, 131
applications, creating, 142–150 compiling applications for, 141 GISM example, 131–152 GISM example, ARM set- up, 140–141 GISM example, hardware for, 150 GISM example, hosting. 141–150 GISM example, module contract, 133–134 GISM example, module creation, 135–140 GISM example, overview, 132 GISM example, running, 150 GISM example, running on, 151 GISM example, video, 152 Raspbian distribution, 151 version, 140, 150 Raspbian, 151 React, 90 read(), 61 reading permissions in GISM ex- ample, 151 read locks in WARoS, 164, 166, 177, 181 read locks in checkers with Rust, 61 read locks with Entity, Component, System (ECS), 166, 177, 181 readlock(), 177 references converting coordinate targets into structs, 59 with gen_funcref(), 176 mutable, 56, 92 vs. ownership, 79 to services, 92 to structs, 54 using in bindings, 70 register machines, 8 —release option, 48, 64 reloading, modules in GISM example, 142–143 Renderable trait about, 90
chat example, 106, 109– 112 counter example, 92–99 resolve_func(), 120–122 resources for this book Crobots, 156 Node, 68 Rot.js, 74, 76 Rust, 45, 47, 54 WebAssembly, 4 Result type, 58 return, 10 robots, see GISM example: WARoS Rogue WebAssembly game. 73–88 about, 73 adding players. enemies. and treasure, 80–87 engine, 76–80 ideas for, 87 setup, 74–76 statistics, 83–87 rook robot, WARoS, 187–189 root module, 51 Rot.js resources on, 74, 76 Rogue game engine, 76– 80 Rogue game setup, 74– 80 Rogue game, adding players, enemies, trea- sure, 80–87 run_start(), 118 Runtime GISM example, 146–150 hosted checkers example, 120, 122–123 WARoS, 162, 166–178 RuntimeValue, 119 Rust, see also checkers, Rogue WebAssembly game; WARoS about, xvi, 45 adding integer example, 47–50 advantages, xvi, 46 anonymous functions, 57 basics, 45–65 cloud support, 195 creating projects, 6, 48, 69 Hello, World example, 67–73 hosting modules outside of browsers, 115–130 installing, 47 integrating with Java- Script, 67–88 integrating with Java- Script with Yew, 89– 112 lifetime specifier, 95 math support, 126 modularization in, 55 performance, 46 resources on, 45, 47, 54 syntax, 46, 50, 94, 98, 110 versions, 46–47, 50 rustup, 47, 140
S S-expressions, 14 scanners, WARoS, 157 scope events, 120 function-scoped values, 14 temporary variables, 35 security browser-based attacks, 199 control flow, 9 cross-site scripting rules, 29 exports, 39 general, 199 Internet of Things, 153 JavaScript, 200 linear memory, 9, 11 modules, 199–204 privacy, 199 signing and encrypting modules, 200–204 visibility and round-trip compilation, 16 seed keys, EdDSA signatures, 201 self, 62 &self for references, 54 Sender, 185 separation, see also encapsu- lation with Entity, Component, System (ECS), 165, 177, 181 GISM example, 133 guard checking code from state changes, 37 importance of, 74 Internet of Things, 131 module isolation, 116
with modules, 51, 60, 116 Rogue game, 74, 76, 80, 82, 86 serde crate, 83, 103 serialization chat example, 103 Rogue game, 83–87 with serde crate, 83, 103 serverless support, 193–197 serverless-wasm, 196 services about, 93 building for chat exam- ple, 101–106 counter example with Yew, 92–99 mutable references, 92 references to, 92 set_local, 35 SIGINT, GISM example, 142, 146 signatory crate, 201 signatory-dalek crate, 201 signed numbers, 9 signing modules, 200–204 SIGTERM, GISM example, 142, 146 source maps, 16 src directory chat example, 103, 111 counter example of Yew, 92, 96 creating Rust projects, 6 hosted checkers example, 122, 124 Rusty checkers, 51, 55 WARoS, 167 stable toolchain, 47 stack machines, 4, 8 start(), 118 state chat example, 107–109 checkers, hand-coded, 21–33 checkers, hosted exam- ple, 122 checkers, with Rust, 55– 60 game board in hand-cod- ed checkers example, 35–38 global mutable, 61 hosting modules, 122, 124
lazy statics, 60 mutable references, 56, 92 separating changes from guard checking code, 37 WARoS, 162–166, 168, 179–181, 189–190 Yew Component traits, 90 static lifetime specifier, 95 statics, lazy, 60 statistics, Rogue game, 83–87 stats_updated(), 83 status_updated(), 76 stdin, 197 stdout, 197 stdweb crate, 97 strings lack of type in WebAssem- bly, 13 passing, 71, 106 rendering hosted checker board as, 126
structs about, 51 checkers setup, 51 converting coordinate targets into, 59 equality tests, 57 exporting as a class, 78 importing, 77 lazy statics, 60 missing fields and initial- izing, 79 passing with context, 93 references to, 54 tuple, 54 structural keyword, 77 submodules, declaring, 51 subscribe key, Pubnub, 100, 105, 111
systems building, 181–186 in Entity, Component, System (ECS), 165, 177 WARoS, 165, 177, 181– 186
T tables, control flow instruc- tions, 10 targets adding/removing, 140 ARM setup for GISM ex- ample, 140–141 checkers, hosted version, 122 checkers, with Rust, 53 compiling for multiple, 47 converting coordinate targets into structs, 59 Installing WebAssembly, 47 listing, 47 temporary variables, 35 test, 138 testing battery indicator in GISM example, 137–139 checkers game, hand- coded, 27–30, 38–41 cloud functions, 195 equality of structs, 57 threads creating module runner thread, 144–150 GISM example, 143–146 mpsc channels, 144 WARoS, 162–166 WebAssembly support, 163 three-body problem, 144 timeouts, channels, 144 to_u32(), 127 toggling bitwise operators, 26 toolchains, listing, 47 traits about, 90 chat example, 106–112 combining with generics, 94 counter example, 92–99 transpiling, 5 treasure, Rogue game, 74, 78, 80, 82 trigonometry functions for WARoS, 158–159 tuples converting, 126 tuple structs, 54 turbofish syntax, 59 types, see data types
U unit offsets, 22 unsafe block, 63 unsigned numbers, 9 unwrap(), 58, 61 update() (Yew), 90, 107
update (cargo), 71 user Interface, chat example, 106–112 usize, 54
V validations checkers, hand-coded, 30, 35 checkers, with Rust, 53 distance, 35 host responsibilities, 116 values control flow instructions, 10 reading from compo- nents, 177 setting local variables, 35 specifying initial values for global variables, 33 storing and retrieving in hand-coded checkers example, 30–32 using return value from a function as parame- ter, 31
variables global, 32, 101 local, 35 temporary, 35
vectors converting Iterators to, 59 Indexes, 54
version control, 70
versions forcing, 68 Raspberry Pi, 140, 150 Rust, 46–47, 50 wasm-bindgen, 68 Yew, 89
video, GISM example, 152 view(), 90, 110 view_message(), 110 view_user(), 110
virtual machines register, 8 stack-based, 4, 8
W wabt (WebAssembly Binary Toolkit) installing, 12 using, 15–17 WARoS, 155–192 API, 157–162
building components and systems, 181–186 building match engine, 162–186 channels, 190 cloud Ideas, 191 creating robots, 186–189 damage system, 182–186 damage table, 157 game loop, 162–166. 178–181 playback, 185 playing, 189–190 rules, 156 runtime host, 162, 166– 178 separation with Entity. Component. System (ECS). 165, 177, 181 state, 162–166, 168. 179–181, 189–190 wasm. see WebAssembly wasm-bindgen #[wasm_bindgen] macro, 69 about, 68 adding serialization sup- port, 84 Hello. World example. 67–73 installing command-line tool, 68 Rogue game, 77, 87 version, 68
wasm-objdump adding integers example with wast, 15 hand-coded checkers ex- ample, 21 installing, 12
WasmFiddle, 6
wasm i crate adding integers example, 117–119 checkers example, 120– 129
wast (WebAssembly Text For- mat) adding integer example, 14–17 advantages of coding with, 13 checkers game, 19–42 global variables, declar- ing, 32 testing, 27–30, 38–41 wat2wasm adding integers example, 15 hand-coded checkers example, 21 installing, 12
watchdog processes, 197
Web API bindings, 88 web_logger crate, 103 web_sys crate, 88
WebAssembly, see also checkers, hosts; modules; Rogue WebAssembly game; Rust; WARoS; wast (WebAssembly text format) about, xiii, 4–6 advantages, xv, 41 advantages of coding in raw wast, 13 architecture, understanding, 8–12 basics, 3–17 control flow, 9 creating projects, 48, 69
defined, 4 development of, xlv Installing WebAssembly Binary Toolkit (wabt), 12 installing target, 47 products, xv resources on, 4 uses, xv
WebAssembly Binary Toolkit (wabt) installing, 12 using, 15–17
WebAssembly Studio, 6 webpack configuration, Hello, World example, 71 workers, Cloudflare, 196 write(), 61 writelock(), 177
writing permissions in GISM example, 151 read locks in checkers with Rust, 61
write locks in WARoS, 164, 166, 177, 181 write locks with Entity, Component, System (ECS), 166, 177, 181
X -x output option, 15 XOR, 25
Y Yew, 89–112 about, 89–91 advantages, 91 counter example, 91–99 installing cargo-web for Yew, 91 live chat example, 99–112 user interface for chat example, 106–112 version, 89
Z zip(), 57 zipping iterators, 57
Thank you!
How did you enjoy this book? Please let us know. Take a moment and email us at [email protected] with your feedback. Tell us your story and you could win free ebooks. Please use the subject line “Book Feedback.”
Ready for your next great Pragmatic Bookshelf book? Come on over to https://pragprog.com and use the coupon code BUYANOTHER2019 to save 30% on your next ebook.
Void where prohibited, restricted, or otherwise unwelcome. Do not use ebooks near water. If rash persists, see a doctor. Doesn’t apply to The Pragmatic Programmer ebook because it’s older than the Pragmatic Bookshelf itself. Side effects may include increased knowledge and skill, increased marketability, and deep satisfaction. Increase dosage regularly.
And thank you for your continued support.
Andy Hunt, Publisher
Footnotes
Section titled “Footnotes”-
github.com/tpoindex/crobots/blob/master/src/crobots.h#L30 then use a read lock on the entire vector and occasionally try and grab a write lock to modify a robot’s data. ↩
-
doc.rust-lang.org/std/sync/mpsc/struct.Sender.html during which those events occurred. Anything listening on the other end of that channel can store the events in a database, display them on the console, or render them on a website. To show them at a more human-friendly speed, just apply a frame rate delay between events such that each cycle represents some fixed fraction of a second. ↩