Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Hands-On Game Development with WebAssembly
Hands-On Game Development with WebAssembly

Hands-On Game Development with WebAssembly: Learn WebAssembly C++ programming by building a retro space game

eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Hands-On Game Development with WebAssembly

HTML5 and WebAssembly

In this chapter, we will show you how the C code we write to target WebAssembly comes together with HTML5, JavaScript, and CSS to create a web page. We will teach you how to create a new HTML shell file to be used by Emscripten in the creation of our WebAssembly app. We will discuss the Module object and how Emscripten uses it as an interface between our JavaScript and the WebAssembly module. We will show you how to call WebAssembly functions written in C from within JavaScript on our HTML page. We will also show you how to call JavaScript functions from our C code. We will discuss how to use CSS to improve the look of our web page. We will introduce you to the HTML5 Canvas element and show how it is possible to display images to the canvas from within JavaScript. We will briefly discuss moving those images around the canvas from our WebAssembly module. This...

The Emscripten minimal shell file

The first build we created with Emscripten used a default HTML shell file. If you have a website, this is probably not the way you would prefer your web page to look. You would probably prefer to design your look and feel using CSS and HTML5 specific to your design or business needs. For instance, the templates I use for my websites typically include advertisements to the left and right of the game's canvas. That is how traffic to these sites is monetized. You may choose to add a logo for your website above your game's canvas. There is also a text area where Emscripten logs output from printf or other standard IO calls. You may choose to remove this textarea element altogether, or you may keep it, but keep it hidden because it is useful for debugging later.

To build the HTML file based on a new shell file that is not the default Emscripten...

Creating a new HTML shell and C file

In this section, we are going to create a new shell.c file that exposes several functions called from our JavaScript. We will also use EM_ASM to call the InitWrappers function that we will define inside the new HTML shell file that we will be creating. This function will create wrappers inside JavaScript that can call functions defined in the WebAssembly module. Before creating the new HTML shell file, we need to create the C code that will be called by the JavaScript wrappers inside the HTML shell:

  1. Create the new shell.c file as follows:
#include <emscripten.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
printf("Hello World\n");
EM_ASM( InitWrappers() );
printf("Initialization Complete\n");
}

void test() {
printf("button test\n");
}

void int_test( int num ) {
printf("int...

Defining the CSS

Now that we have some basic HTML, we need to create a new shell.css file. Without any CSS styling, our page looks pretty terrible.

A page without styling will be similar to the one shown as follows:

Figure 2.1: The Hello WebAssembly app without a CSS style

Luckily for us, a little bit of CSS goes a long way to make our web page look presentable. Here is what the new shell.css file we are creating looks like:

body {
margin-top: 20px;
}

.input_box {
width: 20%;
display: inline-block;
}
.em_button {
width: 45%;
height: 40px;
background-color: orangered;
color: white;
border: 2px solid white;
font-size: 20px;
border-radius: 8px;
transition-duration: 0.5s;
}

.em_button:hover {
background-color: orange;
color: white;
border: 2px solid white;
}

.em_input {
width: 45%;
height: 20px;
font-size: 20px;
background-color: darkslategray...

HTML5 and game development

Most HTML rendering is done through the HTML Document Object Model (DOM). The DOM is what is known as a retained mode graphical library. Retained mode graphics retain a tree known as a scene graph. This scene graph keeps track of all the graphical elements in our model and how to render them. The nice thing about retained mode graphics is that they are straightforward for a developer to manage. The graphical library does all the heavy lifting and keeps track of our objects for us as well as where they render. The downside is that a retained mode system takes up a lot more memory and provides a lot less control to the developer. When we write HTML5 games, we could take images rendered in the DOM using <IMG> HTML elements and move those elements around using JavaScript or CSS animations to manipulate the positions of those images within the DOM directly...

Adding a canvas to the Emscripten template

In an earlier part of this chapter, we discussed making calls to the Emscripten WebAssembly app from a shell template. Now that you know how to make the interaction work between JavaScript and WebAssembly, we can add a canvas element back into the template and start to manipulate that canvas using the WebAssembly module. We are going to create a new .c file that will call a JavaScript function passing it an x and y coordinate. The JavaScript function will manipulate a spaceship image, moving it around the canvas. We will also create a brand new shell file called canvas_shell.html.

As we did for the previous version of our shell, we will start by breaking this file down into four sections to discuss it at a high level. We will then discuss the essential parts of this file a piece at a time.

  1. The beginning of the HTML file starts with...

Summary

In this chapter, we discussed the Emscripten minimal shell HTML file, what its various components are, and how they work. We also wrote about what parts of the file we can do without, if we are not using our shell to generate canvas code. You learned about the Module object, and how it is the interface that uses the JavaScript glue code to tie the JavaScript in our HTML and our WebAssembly together. We then created a new WebAssembly module that contained functions we exported to allow JavaScript to use Module.cwrap to create JavaScript functions we could then call from our DOM that executes our WebAssembly functions.

We created a brand new HTML shell file that used some of the Module code from the Emscripten minimal shell, but rewrote the HTML and CSS of the original shell almost entirely. We were then able to compile that new C code and HTML shell file into a working...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create a WebAssembly game that implements sprites, animations, physics, particle systems, and other game development fundamentals
  • Get to grips with advanced game mechanics in WebAssembly
  • Learn to use WebAssembly and WebGL to render to the HTML5 canvas element

Description

Within the next few years, WebAssembly will change the web as we know it. It promises a world where you can write an application for the web in any language, and compile it for native platforms as well as the web. This book is designed to introduce web developers and game developers to the world of WebAssembly by walking through the development of a retro arcade game. You will learn how to build a WebAssembly application using C++, Emscripten, JavaScript, WebGL, SDL, and HTML5. This book covers a lot of ground in both game development and web application development. When creating a game or application that targets WebAssembly, developers need to learn a plethora of skills and tools. This book is a sample platter of those tools and skills. It covers topics including Emscripten, C/C++, WebGL, OpenGL, JavaScript, HTML5, and CSS. The reader will also learn basic techniques for game development, including 2D sprite animation, particle systems, 2D camera design, sound effects, 2D game physics, user interface design, shaders, debugging, and optimization. By the end of the book, you will be able to create simple web games and web applications targeting WebAssembly.

Who is this book for?

Web developers and game developers interested in creating applications for the web using WebAssembly. Game developers interested in deploying their games to the web Web developers interested in creating applications that are potentially orders of magnitude faster than their existing JavaScript web apps C/C++ developers interested in using their existing skills to deploy applications to the web

What you will learn

  • Build web applications with near-native performance using WebAssembly
  • Become familiar with how web applications can be used to create games using HTML5 Canvas, WebGL, and SDL
  • Become well versed with game development concepts such as sprites, animation, particle systems, AI, physics, camera design, sound effects, and shaders
  • Deploy C/C++ applications to the browser using WebAssembly and Emscripten
  • Understand how Emscripten HTML shell templates, JavaScript glue code, and a WebAssembly module interact
  • Debug and performance tune your WebAssembly application
Estimated delivery fee Deliver to Japan

Standard delivery 10 - 13 business days

$8.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2019
Length: 596 pages
Edition : 1st
Language : English
ISBN-13 : 9781838644659
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Japan

Standard delivery 10 - 13 business days

$8.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

Publication date : May 31, 2019
Length: 596 pages
Edition : 1st
Language : English
ISBN-13 : 9781838644659
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 131.97
Hands-On Game Development with WebAssembly
$43.99
C++ Game Development By Example
$38.99
Learn WebAssembly
$48.99
Total $ 131.97 Stars icon

Table of Contents

17 Chapters
Introduction to WebAssembly and Emscripten Chevron down icon Chevron up icon
HTML5 and WebAssembly Chevron down icon Chevron up icon
Introduction to WebGL Chevron down icon Chevron up icon
Sprite Animations in WebAssembly with SDL Chevron down icon Chevron up icon
Keyboard Input Chevron down icon Chevron up icon
Game Objects and the Game Loop Chevron down icon Chevron up icon
Collision Detection Chevron down icon Chevron up icon
Basic Particle System Chevron down icon Chevron up icon
Improved Particle Systems Chevron down icon Chevron up icon
AI and Steering Behaviors Chevron down icon Chevron up icon
Designing a 2D Camera Chevron down icon Chevron up icon
Sound FX Chevron down icon Chevron up icon
Game Physics Chevron down icon Chevron up icon
UI and Mouse Input Chevron down icon Chevron up icon
Shaders and 2D Lighting Chevron down icon Chevron up icon
Debugging and Optimization Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(9 Ratings)
5 star 77.8%
4 star 11.1%
3 star 11.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Tim in Colorado Jul 09, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Covers the basics really well, and goes in-depth into how to use the WebAssembly toolchain to write a game.
Amazon Verified review Amazon
Jason A Tucker Jul 09, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I’m primarily a business application developer, so I was not familiar with the technology or the platforms covered in this book. The author’s writing style and methodical approach helped overcome my own knowledge gaps. Kudos to both the author and editor for making a daunting task much less intimidating.
Amazon Verified review Amazon
James Barron Jul 02, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good review of both the burgeoning technology of web assembly and some basics of 2D game development. While this book covers a wide array of subjects from writing C++ and Javascript, Web Assembly, game development, and more, it does not assume a lot of prior knowledge of these topics and does a good job of explaining step-by-step and topic-by-topic everything needed for the book. There is also a nice smattering of enriching notes on the history of web technology and game development to give context to what is presented.Since web assembly is so new, this book explains well where it is rapidly changing, where things are still not developed or is buggy, and how to work around some common issues. It covers how C++ and Javascript interact, how to properly compile and run, and how to debug. All of these have their issues and details which are nicely explained so the reader won't need to struggle with it.All in all, it is a clear, methodical guide for both those with little knowledge and those with more experienced.
Amazon Verified review Amazon
Vivace May 31, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is a great guide into wasm. The accompanying code works well, and i appreciated there being both C and C++ versions of things. The nature of the toolchain, multiple languages, none of which are particularly concise, doesnt especially lend itself to print, yet the authors style of dissecting what is going on piece by piece, before merging it all back together works well. I have been more than a little surprised by what a useful resource this book has been.
Amazon Verified review Amazon
L. G. Sep 23, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Little slow at the beginning then it started a fire in me like when you mix gasoline and styrofoam, light it and throw it but it ends up on your friends shirt only to burn a massive hole in it. Overall a great read and an awesome amount of knowledge included.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela