Reader small image

You're reading from  Game Development with Three.js

Product typeBook
Published inOct 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782168539
Edition1st Edition
Languages
Right arrow
Author (1)
Isaac Sukin
Isaac Sukin
author image
Isaac Sukin

Isaac Sukin has been building games since he was eight years old, when he discovered that Nerf Arena Blast came with a copy of Epic Games' Unreal Editor. At 16, he became co-leader of the Community Bonus Pack team, an international group of game developers for the Unreal Engine that won 49 awards over the next few years. He started learning to code around the same time by developing an open source Facebook-style statuses system that thousands of websites have adopted. Since then, he has been increasingly drawn to interactive JavaScript on the web. He created an open source 2D game engine in early 2012 and then dove into Three.js. As of 2013, he is a senior, studying entrepreneurship and information management at the Wharton school at the University of Pennsylvania. He has worked for Twitter, First Round Capital, and Acquia among others, and was previously a freelance consultant and developer. He is also a founder of Dorm Room Fund, a student-run venture capital fund that invests in student-run startups. You can find him on GitHub and Twitter under the alias IceCreamYou or visit his website at www.isaacsukin.com. He has previously published short stories and poetry, but this is his first book.
Read more about Isaac Sukin

Right arrow

Chapter 5. Design and Development

While other chapters have focused on the Three.js API and how to use it to build games, this chapter discusses how to make good games using Three.js and the Web as a platform. We'll use what we've learned so far as a foundation to explore game design concepts and development processes, investigate performance considerations, and introduce JavaScript-based game networking.

Game design for the Web


Building games based on WebGL that match or exceed console quality should be possible, and doing so is a worthy goal. Additionally, building games for the Web presents an opportunity to take advantage of features that aren't possible for desktop and console games, although there are also a few drawbacks.

For example, you can build mechanics around having game data in URLs. Beyond just indicating save/load points, URLs could encode pickups, locations, random seeds, or other information. Add sharing to the mix and suddenly you have the ability for users to e-mail or tweet a link to their friends and have them drop instantly into the same point in your game. Unlike console games, web games can build on viral dynamics, the ubiquity of browsers, and low barriers to entry to attract more users and introduce new gameplay. You might imagine collaborative puzzle games that require a certain number of players to be completed—a concept that wouldn't be reliable for an expensive...

Performance


In some ways, performance considerations for 3D games in browsers are pretty similar to those for consoles and desktop games. The biggest difference is that all resources must (at least initially) be streamed to the client instead of read from a disk. For complex 3D games with gigabytes of assets, overcoming this limitation for low-bandwidth clients can be a serious challenge.

Tip

As legendary programmer Donald Knuth wrote:

"Premature optimization is the root of all evil."

This section discusses best practices and suggestions to get great performance out of your game, but before expending significant effort, you should measure and test your application to see where the bottlenecks are and whether the effort is worthwhile.

Bandwidth/network constraints


To combat bandwidth constraints, the first thing you should do is apply traditional optimizations which web developers have been using for years: compress the content your server sends with gzip, combine and minify JavaScript to minimize the number of requests the browser has to make to the server, optimize your images, enable the Keep-Alive header, serve assets from a limited number of domains, and use headers to leverage browser caching, among other techniques.

Tip

Optimizing websites in general is a particularly detailed topic, but this section mostly sticks to explaining optimizations specifically for games. If you are interested in learning more about Web Performance Optimization (WPO), start with these rules from Google and Yahoo!:

However, complex games won't be able to rely on browser caching for user return visits because browsers have limits...

Level of detail


Similarly, you can load low-poly meshes and low-resolution textures when the user starts playing the game and replace them with higher-detail assets during gameplay, either when the larger assets are loaded or when the user gets close enough to them to see the improved detail. The latter technique is called Level-of-Detail (LOD), and Three.js has built-in support for it using the THREE.LOD object. For example, we could modify the spinning shape example we built in Chapter 1, Hello, Three.js, to change the detail of our sphere depending on how close to it we are. First we need to change how we add the mesh to the scene:

geometry = [
  [new THREE.IcosahedronGeometry(200, 4), 50],
  [new THREE.IcosahedronGeometry(200, 3), 300],
  [new THREE.IcosahedronGeometry(200, 2), 1000],
  [new THREE.IcosahedronGeometry(200, 1), 2000],
  [new THREE.IcosahedronGeometry(200, 0), 8000],
];
material = new THREE.MeshNormalMaterial();

lod = new THREE.LOD();
for (var i = 0; i < geometry.length...

Rendering optimizations


Three.js has built-in support for other detail-related optimizations as well in order to make processing faster. Culling, the process of excluding hidden objects from rendering, is a common example. Three.js does view frustum culling based on bounding spheres, meaning it will avoid spending valuable compute time calculating visual information about objects that are off screen. It also does backface culling by default, which hides the back side of mesh faces. However, it doesn't do occlusion culling, meaning it doesn't know not to render an object that is in front of the camera but obscured by another object that is closer to the camera. The implication of these optimizations is that large meshes should often be split into several smaller ones to reduce computation if only part of the large mesh is on the screen, and you don't get any benefits by default from having short viewable distances. This simple change might be sufficient for top-down games where few objects...

Battery life and GPU memory


Although bandwidth/network speed and processing time are the factors that usually affect the performance of Three.js games the most, battery life and memory constraints may also come into play. For hardcore games, you may be able to assume the user is plugged in, but more casual games should be aware that more processing typically equates to more battery drain. On the memory front, the question is less about storage space and more about the graphics card having a limited amount of embedded memory with which it can perform fast computations. The main thing you can do to limit how much of the GPU's onboard memory you consume is to use compressed textures. (Normally, images such as JPGs and PNGs are decompressed before being sent to the GPU, but compressed textures use a special format that allows the GPU to hold them in embedded memory in a compressed state. Since the compression only matters for the GPU, it doesn't actually save network bandwidth.) Three.js supports...

Performance-measuring tools


Finally, there are a number of useful tools for measuring JavaScript performance. Conveniently, the original author of Three.js has written a library called Stats.js (https://github.com/mrdoob/stats.js) for tracking frame rates, the most crucial performance statistic for games. For comprehensive tracing, Google's Web Tracing Framework (http://google.github.io/tracing-framework/index.html) is hard to beat, and it even has an example for tracing a WebGL game. You can also easily get some statistics about onscreen geometry with the RenderStats library from Jerome Etienne (https://github.com/jeromeetienne/threex.rendererstats).

For brute-force debugging, you may also want to try the console-extras library, which makes it easier to log information about things that happen in the main game loop without dumping thousands of messages (https://github.com/unconed/console-extras.js).

Networking and multiplayer


Game networking is hard because the goal of networking is to keep game state in sync across multiple devices, but network latency prevents devices from communicating fast enough to keep that state from being occasionally inconsistent. Additionally, floating point rounding errors create indeterminate results across devices for the same set of input (this is where the timing and movement techniques discussed in Chapter 3, Exploring and Interacting come into play, since small differences in precision can result in huge differences over time). As a result, networking code becomes a process of reconciling differences.

There are basically two different approaches to networking depending on the requirements of the game. RTS and turn-based games usually use an approach called lock-step, which is a peer-to-peer model in which each computer in a match sends its commands to all the other computers in the match. The main strength of this model is that only a small amount of...

Development processes


Whether you're an individual who builds games as a hobby or a developer for a large game publisher, you can benefit from following a number of best practices adopted from JavaScript development for the Web and game development on other platforms. You can also build Three.js-based games without deviating too far from your favorite game development processes.

JavaScript best practices

In previous chapters, we haven't been very concerned with the high-level structure of our code. We wrote some examples as single HTML files, and we split the FPS and CTF projects into separate files, but for polished games we should be more careful, especially when working with teams. General coding lessons apply:

  • Keep assets in folders by file type/purpose. For example, at a high level you might have folders such as css, js, images, models, and sounds. Within the js folder, organize JavaScript files by purpose; keep library, source, and production code separate.

  • Avoid putting code that directly...

Summary


In this chapter, we learned about designing and developing high-quality games for the Web. We covered aspects of game design and development that are unique to the Web, and how Three.js supports them; important performance considerations; and basic client-server and lock-step networking.

You are now prepared to embrace the next generation of gaming. Congratulations!

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Game Development with Three.js
Published in: Oct 2013Publisher: PacktISBN-13: 9781782168539
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Isaac Sukin

Isaac Sukin has been building games since he was eight years old, when he discovered that Nerf Arena Blast came with a copy of Epic Games' Unreal Editor. At 16, he became co-leader of the Community Bonus Pack team, an international group of game developers for the Unreal Engine that won 49 awards over the next few years. He started learning to code around the same time by developing an open source Facebook-style statuses system that thousands of websites have adopted. Since then, he has been increasingly drawn to interactive JavaScript on the web. He created an open source 2D game engine in early 2012 and then dove into Three.js. As of 2013, he is a senior, studying entrepreneurship and information management at the Wharton school at the University of Pennsylvania. He has worked for Twitter, First Round Capital, and Acquia among others, and was previously a freelance consultant and developer. He is also a founder of Dorm Room Fund, a student-run venture capital fund that invests in student-run startups. You can find him on GitHub and Twitter under the alias IceCreamYou or visit his website at www.isaacsukin.com. He has previously published short stories and poetry, but this is his first book.
Read more about Isaac Sukin