Going the Distance with Babylon.js - Josh Elster - E-Book

Going the Distance with Babylon.js E-Book

Josh Elster

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Babylon.js allows anyone to effortlessly create and render 3D content in a web browser using the power of WebGL and JavaScript. 3D games and apps accessible via the web open numerous opportunities for both entertainment and profit. Developers working with Babylon.js will be able to put their knowledge to work with this guide to building a fully featured 3D game.
The book provides a hands-on approach to implementation and associated methodologies that will have you up and running, and productive in no time. Complete with step-by-step explanations of essential concepts, practical examples, and links to fully working self-contained code snippets, you’ll start by learning about Babylon.js and the finished Space-Truckers game. You’ll also explore the development workflows involved in making the game. Focusing on a wide range of features in Babylon.js, you’ll iteratively add pieces of functionality and assets to the application being built. Once you’ve built out the basic game mechanics, you’ll learn how to bring the Space-Truckers environment to life with cut scenes, particle systems, animations, shadows, PBR materials, and more.
By the end of this book, you’ll have learned how to structure your code, organize your workflow processes, and continuously deploy to a static website/PWA a game limited only by bandwidth and your imagination.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 646

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



BABYLON.JS IS AN IMPRINT OF PACKT PUBLISHING

Going the Distance with Babylon.js

Building extensible, maintainable, and attractive browser-based interactive applications using JavaScript

Josh Elster

Going the Distance with Babylon.js

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Bhavya Rao

Senior Editor: Sofi Rogers

Senior Content Development Editor: Rakhi Patel

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Alishon Mendonca

Marketing Coordinator: Anamika Singh and Marylou De Mello

First published: August 2022

Production reference: 2140323

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80107-658-6

www.packt.com

Writing this book would not have been possible without the people that have been important in my life. To my father, for gamely reading each chapter, knowing ahead of time that none of the material is even remotely near his wheelhouse. To my wife, for believing in me even when I didn’t and for putting up with me when I’m cranky. To my brothers, for their unwavering encouragement and faith in this project and in life. To Mitch Gitelman, for indulging in a long walk with me on a fine Washington Spring Day. Finally, this book is dedicated to the memory of Adrian Barcus, a.k.a. “Colonel Ransom.” Regardless of how long or far you might search, a better person will not be found.

– Josh Elster

Foreword

If at that time you had told me that one day someone would be motivated enough to write an actual book about it, I would have laughed a lot. And still, here we are. When Josh told me that he was on the verge of writing a real book about Babylon.js, I barely believed him.

The book that you have in your very hands right now is the culmination of a fantastic journey where people from around the globe joined and contributed to a common project without expecting anything more than a thank you. That fantastic community helped create hundreds of great projects and convince big names such as Microsoft and Adobe to bet on and contribute to a GitHub project for their 3D-based projects.

I know this is probably a really classic cliché to employ, but I genuinely want to thank Josh for having poured his soul into this book in order to help our community to learn our platform.

I encourage you to use this book as a first step to joining the community and participating in our common effort to build a powerful and easy-to-use 3D engine freely available to all.

David Catuhe,

Creator and leader of the Babylon.js open source project, group engineering manager for the Microsoft Stream web client, technical expert on the WebGL/Javacript/TypeScript web technologies

Contributors

About the author

Josh Elster spends most of his days working as a software engineering lead for a technology start-up and his nights patrolling the Babylon.js forums and working on various side projects. Unlike Bruce Wayne, however, he did not have a traumatic childhood incident involving bats.

From his home in the Windy City of Chicago, Josh likes to spend time outdoors, particularly in his woodshop when the weather indicates, and gaming, making music, or reading when it doesn’t. His website is https://www.liquidelectron.com. A limited social media user, he can be found on LinkedIn and Twitter.

A huge thanks to everyone who helped me keep going on this journey. Special thanks are owed to my family, for their faith in me and this project. To Jason Carter and Kaustubh Manglukar, who were there at the conception of this book, Raanan Weber, who put up with my incessant questions (until one day he didn’t), and to Carolina Herbster Mesquita Jorge, for allowing herself to fill that spot – there’s no way that this book would be a worthwhile read without your valuable contributions. To the members of the Babylon.js community – you are the heart and soul of the Babylon.js project. Thank you for being part of and making such an amazing endeavor!

About the reviewers

Reviewers

Jason Carteris humbled by his position and opportunity to lead the incredibly talented Babylon development team at Microsoft, having spent his entire career at the intersection of storytelling and technology. At the start of a career spanning decades, he spent years bringing animated characters and scenes to life at Dreamworks and later Disney Animation. Afterward, he then went on to help make holograms feel real by bringing the HoloLens to life. The latest stage in his career is to ultimately help the world create and share interactive 3D web experiences.

Raanan Weber is the tech lead of the 3D web engine Babylon.js. His first contribution to the framework was back in 2014, and he is not planning to stop any time soon. Among his latest contributions are the WebXR abstraction and the framework’s new build system.

Raanan lives with his wife and son in Berlin, Germany. He spends his weekends walking his wonderful dog and playing as much music as possible.

Carolina Herbster Mesquita Jorge is a computer graphics developer based in Brazil. In her free time, she likes to play video games, crochet, and play with her dog, Courage.

Subject matter experts

Erich Loftis

Andrei Stepanov

Technical experts

Gary Hsu

Cedric Guillemet

“Evgeni_Popov”

Justin Murray

Dave Solares

Patrick Ryan

Table of Contents

Preface

Part 1: Building the Application

1

The Space-Truckers Operation Manual

Introducing the World of Space-Truckers

So, You Wanna be a Space-Trucker?

Space-Truckers: The Video Game Design

Landing

Splash Screen

Menus

Route Planning

Driving and Scoring

Space-Truckers: The Repository

Summary

2

Ramping up on Babylon.js

Technical Requirements

Catching up or Refreshing on Babylon.js

The Basics of BJS

Get Started with Getting Started

Tools for the Toolbox

The Asset Types of BJS

Building the Playground Scene

Establishing the AppStartScene

Animating the Orbits

Putting Spin on the Star and Planets

Making Orbital Motion

Orbit Lines

Shining up with GlowLayer

Extended Topics

Summary

Further Reading

3

Establishing the Development Workflow

Technical Requirements

A Note for TypeScript Users

Setting up the Environment

Preparatory Steps

Initialize All the Things

Scripts and ESLint Configuration

Configuring Webpack

Crafting a PG Snippet

Cleaning up the BABYLON Namespace Prefix

Extracting Magic Strings

Transitioning from the PG to the Application

Creating the Engine Instance

Adding and Importing the StartScene

Exporting and Importing the Start Scene

Constructing the Landing Page

The Concept (Art)

Sticking the Landing

Summary

Extended Topics

4

Creating the Application

Technical Requirements

Adding a Custom Loading UI

Solo Exercise: Refactoring the StartScene to Extract the AstroFactory

The CustomLoadingScreen Type

Enhancing the Loading Screen with Progress Display

Space-Truckers: The State Machine

Logging Interlude

Generators and function* Iterators

The Definition of a State Machine

Space-Truckers: The Application State Diagram

Almost Infinitely Looping State

Adding the Constructor and Supporting Logic

Writing the Initialize logic

Transitioning to the Main Menu

Space-Truckers: The Main Menu

Basic Design

Setting up the Main Menu snippet

Building the Background

Creating the AdvancedDynamicTexture and GUI

Adding the Menu Container and Background

Image Aside: Bringing in External Content

Laying out the Title and Menu Items

Populating the Menu with Items

Adding Menu Item Selection and Indicators

Indicating Selection and Reacting to Change

Visual Improvements and Animating the Selection Idle

Integrating the Main Menu

Entering and Leaving Transitions

Menu Finishing Touches

Summary

Extended Topics

5

Adding a Cut Scene and Handling Input

Technical Requirements

Space-Truckers – the Splash Screen

Storyboarding the Scene

Building the Scene

Integrating the SplashScene

Designing the Input System

Defining the Main Menu Control Scheme

Mapping Input Data

Input Management

Input Processing

Action Handling

Summary

Extended Topics

Part 2: Constructing the Game

6

Implementing the Game Mechanics

Technical Requirements

Helpful Things to Know

Useful Links from the Babylon.js Docs

A Detour into Sound Management

Sounds, SoundTracks, and the AudioEngine

SpaceTruckerSoundManager

Designing the Game Elements of the Route Simulation

An Overview of the Helios System

Actors and Their Behavior

Establishing the Basic Route Planning Screen

Creating the Orbital Mechanics Simulation

Understanding the Physics

Driving the Simulation’s Physics

Configuring the InFlight Physics Simulation

Defining the Rules – Game Mechanics

Controllable Launch Parameters

Going Places and Crashing EVERYWHERE

Supporting Input Controls

Showing Game Information with the GUI

Summary

7

Processing Route Data

Technical requirements

A Detour into Particle Systems

The Disparate Particle Systems of Babylon.js

Loading Particle Systems From Saved Data

Adapting the Sun Particle System Set

Marking Out the Route

Defining the Encounter Zone

Encounters Overview

Encounter Zones and Encounter Tables

Tracking Intersections

Encounter Zones and Game Data

Selecting Encounters

Summing the Probabilities

Populating CMDF Results

Rolling an Encounter Check

Listening for Encounters

Adding Encounter Visuals

Putting 2D Labels into 3D Space

Animating the Encounter Panel

Clearing Encounter Panels

Summary

Extended Topics

8

Building the Driving Game

Technical Requirements

Prototyping the Driving Phase

Playground Overview

Generating the Driving Path

Loading Assets Asynchronously

Initializing the Driving Phase Scene

Running the Update Loop

Integrating with the Application

Splitting Up the Playground

Transitioning to the Driving Screen

Truck Update and Input Controls

Patching the input map

Adding Encounters

Making the Mini-Map

The GUI Camera

Blip Plotting in Polar Coordinates

Summary

Extended Topics

9

Calculating and Displaying Scoring Results

Technical Requirements

Introducing the Babylon.js GUI Editor

The Advanced Dynamic Texture

UI Design with the GUIE

Integration with the GUIE

Building a Reusable Dialog Box Component

Constructing the DialogBox Class

Handling Button Clicks and Changing Visibility

Prompting Users after Successful Route Planning

Calculating Scores

Scoring System Design

Adding Up and Tallying Scores

Capturing Scoring Data

Creating the Scoring Dialog Using Coroutines

Reviewing Function Generators

Counting Player Scores with a Coroutine

Advanced Coroutine Usage

Summary

Extended Topics

10

Improving the Environment with Lighting and Materials

Technical Requirements

Tools

Glossary of terms (abridged)

Recommended Reading

Materials, Lighting, and the BRDF

Introducing the BRDF

How Light is Modeled in 3D Applications

Materials and Textures

PBR and IBL

Environment Textures and Reflection Textures

Working with PBR Materials and IBL Scenes

Image Formats and File Types

Bit Depth and Dynamic Ranges

Using and Creating Assets for PBR and IBL

Tone Mapping and Basic Post-Processing

Tone Mapping

Post-Processing and the Rendering Pipeline

Summary

Extended Topics

Part 3: Going the Distance

11

Scratching the Surface of Shaders

Technical Requirements

Understanding Shader Concepts

Differences Between a GPU and a CPU

Shaders are GPU Applications

About Shaders

Writing and Using Shaders in Babylon.js

Fragment and Vertex Shaders

Compute Shaders (New to v5!)

Continuing the Shader Code Journey

Shader Programming with the Node Material Editor

Using the NME to Build the Planet Earth Material

Procedural Textures and the NME

Developing Post-Processes with the NME

Summary

Extended Topics

12

Measuring and Optimizing Performance

Technical Requirements

Knowing What To Measure

General Guidelines

Performance-Related Terminology

Measuring Performance and Identifying Bottlenecks

Inspecting the Performance of Route Planning

Real-Time Performance Viewer Metrics

Defining the Testing Procedure

Viewing and Analyzing a Captured Profile

Improving Runtime Performance with the Scene Optimizer

Understanding the Scene Optimizer and its Operating Modes

Creating a Custom Optimization Strategy for the Asteroid Belt

Summary

Extended Topics

13

Converting the Application to a PWA

Technical Requirements

Hosting Requirements

Options for Hosting your PWA

Resources and Reading

Introduction to PWAs

SSL

Service Workers

Web Manifest

Converting the Space-Truckers application into a PWA

Putting the “P” in PWA

Using the PWABuilder Extension

Using IndexedDB to Persist Scores

Learning about IndexedDB

Using IndexedDB

Recap

Storing and Displaying High Scores

The Heist

The Muscle

The Safe Cracker

The Brains

The Job

The Integration

Summary

Extended Topics

14

Extended Topics, Extended

AR and VR with WebXR

An Abridged History of AR/VR on the WWW

Building Tomorrow, Today with the WebXR Experience Helper

Further Reading

A Tour of the Babylon.js Native Project

Choosing Babylon Native

The Evolution of a Babylon Native App

Further Reading

Incorporating 3D Content into a Website

Babylon.js and CMS

Tracing out a Path to Advanced Rendering

Ray Tracing and its History by Erich Loftis

Summary

Index

Other Books You May Enjoy

Preface

The world of 3D application and game development is a vast and actively changing landscape. With all the stunning capabilities of modern GPU hardware exposed to the web browser via WebGL, AAA-quality interactive rendering can be achieved by anyone with some knowledge of JavaScript. Babylon.js is just the right tool to use for an effortless experience and a robust application built using WebGL technologies.

Although changes in and the evolution of browser software and hardware standards continue at their own pace and on their own schedules, Babylon.js is a framework that prioritizes maintaining backward compatibility. Code written for BJS 2.0 is highly likely to run with little to no modifications in BJS 5.20, so product managers and stakeholders can use BJS with confidence about the long-term stability of the code.

If Babylon.js is the ticket for WebGL, then this book is your ticket to mastering Babylon.js. Well, you probably won’t become a twentieth-level Babylon.js developer by the end of this (let’s be real for a moment), but you’ll certainly learn the key concepts and techniques that will enable you to progress down that path should you so choose!

All of this is starting to become a kind of bad sales pitch, so let’s drop the pretense and talk brass tacks. You want or need to learn about 3D game or app development. As a human being, you also desire entertainment. This book attempts to satisfy both of those needs by avoiding being too boring wherever possible while still delivering the big knowledge bombs. Entertainment and enlightenment, all in one package.

Who this book is for

This book is for artists who avoid coding because they think they’re bad at math (give yourself more credit!), game designers whose fingers long to leave the spreadsheet, and developers dreaming of worlds yet to be made. This book is for students who want to learn outside of their classrooms, teachers who want their students to learn inside their classrooms, and parents who want their teenage kids to learn something, anything at all.

What this book covers

Chapter 1, The Space-Truckers Operation Manual, gives an overview of the world of Space-Truckers and 3D development with Babylon.js.

Chapter 2, Ramping up on Babylon.js, gets us started with (or refreshed on) Babylon.js with a simple 3D animated scene.

Chapter 3, Establishing the Development Workflow, puts a solid design-and-build time experience into place to allow rapid future development.

Chapter 4, Creating the Application, involves building a stateful application that will host the game.

Chapter 5, Adding a Cut Scene and Handling Input, takes us through imperatively creating an animated “cut scene” and learning how to handle user input of different types.

Chapter 6, Implementing the Game Mechanics, starts off the construction of the main route planning phase of the game. Here, we will augment the existing physics with orbital mechanics and simulated gravitational forces.

Chapter 7, Processing Route Data, involves adding random encounter tables that correspond to a space biome.

Chapter 8, Building the Driving Game, takes us through dynamically generating a route and allowing players to drive along it.

Chapter 9, Calculating and Displaying Scoring Results, deals with capturing and showing stats on player performance in a reusable dialog with the help of the GUI Editor.

Chapter 10, Improving the Environment with Lighting and Materials, covers how we can improve the look and feel of the game by enhancing key visual elements.

Chapter 11, Scratching the Surface of Shaders, discusses extended analogies explaining shaders and writing shader code that doesn’t involve writing any shader code.

Chapter 12, Measuring and Optimizing Performance, explains the heuristics and approaches for testing the runtime performance and the strategies for improvement, along with dynamic runtime optimization with the SceneOptimizer tool.

Chapter 13, Converting the Application to a PWA, explores preparing the application for installation as a Progressive Web Application (PWA). We then go through publishing this to a major App Store and adding support for offline usage.

Chapter 14, Extended Topics, Extended, looks at AR/VR with WebXR and Babylon Native before a foray into photorealistic raytracing and Babylon.js in a CMS or e-commerce scenario.

To get the most out of this book

You’ll want to be at least passingly familiar with JavaScript before engaging with the activities in this book, at least to the point where you are not fazed by looking at code that may initially be unfamiliar. Knowing basic 3D concepts and terms is also helpful. If you are new to Babylon.js, JavaScript, or 3D development, then a fantastic place to start is the Babylon.js start page at https://doc.babylonjs.com/journey/theFirstStep.

A web browser with the Mozilla or Chrome rendering engine is recommended, as it has the greatest level of support for various WebGL and WebGPU features. Safari (WebKit) is known to be significantly behind the other engines listed in its support with similar functionality.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

The Babylon.js community is the most valuable resource around for getting help with everything related to BJS.As an Open Source project, Babylon.js is kept alive by its’ dedicated community of contributors. Who can contribute? Anyone. What can be contributed? Almost anything. Join the BJS community on the official forums at https://forum.babylonjs.com and meet the gang!

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/jelster/space-truckers/. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/CGb69.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The createSpinAnimation method is called from createStartScene to make the spinAnim variable available to the rest of the scene’s controlling code.”

A block of code is set as follows:

planets.forEach(p => {     p.animations.push(spinAnim);       scene.beginAnimation(p, 0, 60, true, BABYLON.Scalar.RandomRange(0.1, 3)); });

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

planets.forEach(p => {         glowLayer.addExcludedMesh(p);         p.animations.push(spinAnim);         scene.beginAnimation(p, 0, 60, true, BABYLON.Scalar.RandomRange(0.1, 3));     });

Any command-line input or output is written as follows:

npx webpack –config webpack.common.js

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Clicking Run should now show a nifty-looking starfield in a skybox you can pan around.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Going the Distance with Babylon.js, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Part 1: Building the Application

This first part of the book establishes the important foundations that will be leveraged in future chapters. Starting with a survey of Space-Truckers and Babylon.js, we will construct the main pillars of the game’s hosting application. Although a basic understanding of Babylon.js is recommended, the main requirement is to have some knowledge of JavaScript or a similar programming language.

This section comprises the following chapters:

Chapter 1, The Space-Truckers Operation Manual Chapter 2, Ramping up on Babylon.jsChapter 3, Establishing the Development WorkflowChapter 4, Creating the ApplicationChapter 5, Adding a Cut Scene and Handling Input

1

The Space-Truckers Operation Manual

It’s not considered to be a very emotionally evolved stance to judge a book by its cover, but have you seen the cover of this book? If it’s something you like, then please, by all means, do judge this book by its cover, you counter-culture influencer, you – carry on reading!

If for some reason you don’t like the cover, then bully for you for literally turning over a new page to see what’s inside – unlike some superficial cretins. We’re above that sort of petty judgment, after all.

Note

Sometimes, relevant information will be presented in these Note boxes. Other times, these same boxes will contain completely irrelevant but possibly irreverent information. At all times, or at none (sometimes), should you pay attention to what’s in these boxes.

Regardless of whether you’re on Team Cover or Team Content, it’s clear you’re incredibly smart and well mannered for the simple fact that you’ve started reading this book. We’re about to embark on a journey together over the next 14 chapters. This is not the type of journey that you might encounter flipping through channels while you search for something to watch before bedtime. This is a journey across the wide and vast terrain that is the Babylon.js ecosystem. It isn’t a safari, but it is a sojourn. One thing it is not, however, is an Odyssey. Primarily because you don’t have to actually go anywhere, and you get to go back to your regular life whenever you’re not reading this book, but perhaps for other reasons too.

Important Note

Like its less-distinguished cousin the Note, Important Note boxes will occasionally make an appearance. Generally, these are used for Things You Might Regret Not Knowing About Before…

We are going to cover a huge amount of ground over the course of our sojourn, our journey, but you won’t be traveling unprepared. Our overall objective here is to build a game hosted by and in a generic web application. Over the course of three separate parts, we’re going to progressively do three things:

Create and set up an application and development workflow that gives Space-Truckers: The Video Game! a place to liveLayer on additional functionality to our application (hosting Space-Truckers: The Video Game!)Zoom out on the level of detail to take on a wide range of enhancements and add to our good knowledge

Each chapter will build on the work established in the previous chapter. It’s possible that the code in one chapter will need to be modified in subsequent chapters, and that should be looked at as a reflection of our evolving understanding of how the application needs to be structured to accomplish the goal at hand. Every chapter (save this one) contains links to the game’s code in the same context as the chapter’s text, in addition to live demos and Playground links specific to the content.

While we are building upon the application, we will also be providing fewer and fewer line-by-line code details in favor of providing extra context and/or information relating to how something works “under the hood.” Don’t worry, the code and Playground samples are still there to help you find your way! We’ll be exploring concepts that in themselves can occupy entire texts longer than this not-very-short book, and we’ll be doing so with less room to expand on those same topics. As a result, we will be looking to cover some areas at a high level while others will be discussed to a greater depth.

We’re going to start by walking through the game from the standpoint of the player, then we’ll move on to look at the underlying game and application design. As a finisher, we wrap this first travel segment up with a tour of the Space-Truckers GitHub repository and other online resources. Let’s start with the ending, in classic literary fashion.

Note

For the movie version of this scene, picture a shimmering dissolve with appropriate sound effects as we transition to a different world…

Introducing the World of Space-Truckers

Astronomers recently started receiving a mysterious signal, apparently from outside of our Solar System. Far from being random noise, the signal appears to contain structured data in the form of text, audio, and visual content – an alien transmission! The transmission starts with a basic primer on terminology and math and rapidly works its way up to describing some sort of large plastic disc imprinted with something the message called “multi-media interactive content” that is then connected to a display device and spun around (how ludicrous!) at thousands of RPMs while a laser beam reads grooves burned into the spinning disc. Laser beams. Grooves. Spinning wheels. All ridiculous, but there’s no accounting for alien sensibilities, right?

The following is a reconstruction of the content that was recovered from that transmission and burned onto what is now known as the “Dead Sea CD.” Due to the nature of its journey through space and time, parts of the transmission were not received, and the data contained was unrecoverable. At the same time, the connected nature of the data resulted in other parts being corrupted. Consequently, many of the images and still frames you are about to view represent data that has been patched back together using the best tools and resources at our disposal.

Talented teams of professional engineers, scientists, and even sociologists have worked long and hard to bring about this reconstructed image of what we believe the people who left us – or sent to us – this record look like:

Figure 1.1 – Best guess at the appearance of the originators of the Space-Truckers transmission

The next section contains the reconstructed text and image content recovered from the transmission. Because the original message was expressed symbolically and not in any human language, the latest GPT-3 text generation AI was trained on the transmission’s symbols so that it could then produce the content that follows and format it consistently with the rest of this book.

So, You Wanna be a Space-Trucker?

BEGIN TRANSMISSION

Figure 1.2 – Reconstruction of the Space-Truckers transmission. Probably intended as a “day in the life” image

Being a Space-Trucker isn’t for the faint of heart, nor is it for the lonely of mind. There are hazards and dangers to be found in spades – but there’s also the allure of fortune and fame. Ever since legendary Space-Trucker Winchell Chung’s (call sign: Rocket Cat) famous “Grand Tour,” every kid across the system has grown up aspiring to emulate him. After using the last of his reaction mass to deliver his cargo, he saved millions of starving children suffering after the Great Space-Potato Famine. Sadly, that selfless act left his Space-Rig adrift with no way home. Chung’s Space-Truck was lost as it drifted off into the Darkness Beyond the Sun. His last transmission, garbled as it was, contained a single recoverable fragment of text:

“The cold, hard equations care not for starvation or famine. <indecipherable>…[b]ecause we’re Space-Truckers. It’s what we do.”

Space-Trucker Chung is a sterling example of what it means to be a Space-Trucker, but in all fairness, there’s a dark side to the business. What isn’t publicized is the high rate of turnover among Space-Truckers. Some go mad from the experience of being alone among the stars, while others simply refuse to go back out after their run. Others depart from one place never to arrive at their intended destination.

Figure 1.3 – Space-Trucking is dangerous business

Sure, computers can help, and other technologies also contribute to help make Space-Trucking safe and dependable. However, no amount of hardware or software compares to the wetware of the human mind when it comes to dealing with unanticipated situations, and that’s why Space-Truckers need to be behind the wheel of their Space-Rigs.

Before any space wheels can hit the space pavement, our driver needs to know where to go. Space-Dispatch is here to help with Route Planning services, and with their detailed orbital and launch simulation, different potential routes to the cargo’s destination can be evaluated and tried without risk to the Space-Trucker.

Figure 1.4 – Planning a route involves timing the launch as well as properly aiming it. The left-side bar controls the launch impulse – higher is faster

Despite the risks, the potential rewards are quite high. Completing a Space-Haul has a variable payout for the Space-Trucker, with space-bucks being awarded or demerited based on the driver’s performance in the field. Factors from the simulated route include the total transit time, how much fuel (launch force) is consumed, and the total distance traveled.

Figure 1.5 – Space-Trucking pays well when things go well

Many different obstacles can be encountered, and no two routes are the same, but the scoring factors ensure that when it comes to comparing runs, the High Scores board is the ultimate arbiter of the G.O.A.T Space-Truckers.

Note

G.O.A.T. is not referring to any animal in this context. The Greatest of All Time Space-Truckers are a select and elite group – show proper respect!

Timing is of the essence in Space-Trucking, but so is safety. By being mindful of the latter in service of the former, the Space-Trucker stands the best chance of completing their Space-Haul and getting the opportunity to spend their payday on the Space-Beach.

Never forget, Space-Trucker – the cold, hard equations of planetary motion have no concern for whether you’ve got enough air to breathe or heat to stay warm. Keep your slide rule handy in case of instrument failure and go forth to find your fortune slinging cargo!

Figure 1.6 – Recovered image of a “Space-Trucker” and their “Space-Rig.” The Space-Trucker is the small figure in the foreground

END TRANSMISSION

The life of a Space-Trucker certainly must be full of glamorous riches and perilous travels for those folks to send a recruitment leaflet all that distance! Stepping back to the real world is hard, but it’s important that we break down the various elements of how Space-Truckers is designed and put together. Ideally, as you progress through this book, you’ll have this foundation to help you stay grounded with where everything goes and fits together.

Space-Truckers: The Video Game Design

The basic idea behind Space-Truckers is simple: get stuff from Point A to Point B, in spaaace! (It’s not required to draw out that last word, but it helps set the mood.) As a game, it is separated into several distinct phases or states:

Landing (Home) ScreenSplash ScreenMenus (inc. High Scores)Route PlanningDriving + Scoring

Each of these screens (used as a synonym for “state” here) will be established, then later enhanced over the course of this book along with an underlying application to support and coordinate between them.

Landing

This is the first thing that a player sees when they navigate to space-truckers.com (or the beta testing site, dev.space-truckers.com). It’s an HTML page with a simple Call to Action: “Launch.” Under the hood, however, the HTML page is the host for the main application canvas – the WebGL context onto which all the rendered outputs are painted. It is responsible for loading the packaged web application as well as registration of a Service Worker (see Chapter 13, Converting the Application to a PWA) to manage and pre-fetch assets. As the DOM host, it provides access to the web browser and through it the host machine’s resources, such as the ability to play sound or read input from gamepads or VR hardware. Learn more about this in Chapter 3, Establishing the Development Workflow.

Splash Screen

In music and comedy, a warm-up act precedes the main headline performance as a way to put audiences into a particular frame of mind or mood. After all, it’s much easier to crank things up past 10 on the volume dial when you’re already at 7! The Space-Truckers Splash Screen serves that purpose, as well as giving us an opportunity to showcase the underlying framework and proclaim that this game is Powered by Babylon.js. Once the short, animated content completes, the application enters “attract mode” to entice players to continue.

Menus

The transportation hub of the game, the Main Menu, is where players will start a new game, view high scores, exit back to the landing page, and potentially do more. Sound effects and an animated selection icon bring a bit of motion to a twinkling background. The menu system is initially covered in Space-Truckers: The Main Menu section of Chapter 4, Creating the Application.

Route Planning

One of the two main game phases, the Route Planning Simulation, is where players become content creators. Using a top-down map view, drivers plan their route before embarking on their journey. From an initial starting orbit close to the inner-most planet, players must balance how much launch force is used with aiming and timing to put the simulated cargo on a path to the destination planet. Once launched, the cargo is entirely at the mercy of gravity and Sir Isaac Newton. Pro tip: aim ahead of where you want to end up but be sure to account for the pull of the sun. Because it is a simulation of a route, there are no consequences for failure – the player is free to try as many times as they want to find the perfect route to drive in the next phase.

Driving and Scoring

After planning out the desired route, it’s time for players to then take the wheel and guide their Space-Truck through the transit corridor while avoiding collision with the random events that have been recorded during the route planning phase. The player’s unit drifts in free-fall, so velocity accrued in any given direction will remain unless later canceled out by opposing acceleration. Collision results in damage, and with enough damage, the truck and its cargo are destroyed.

Figure 1.7 – Collisions during the driving phase have consequences

On a brighter note, completing the course results in the player’s score being calculated. Several different factors contribute to the overall total final score. The length of the route, the time it took the simulation to complete the route versus the time the player took, and the initial launch velocity in route planning are all some of the factors involved in scoring. If a player’s score is high enough, then it will displace one of the previous high score holders to place the player’s selected initials into the hall of legends.

This is the game in a nutshell. As with any such high-level overview, it is necessarily lacking in some detail, but it provides a holistic picture of what we’re going to be developing over the course of this book. To get into more detail, we’re going to need to first get an understanding of where we can find those details as well as where and how to pick up supporting context in the GitHub repository for Space-Truckers.

Space-Truckers: The Repository

Exploration is an important learning tactic for the discovery of new knowledge. Its converse, exploitation, is an equally important tactic used to convert passing knowledge into actionable skills. The key to maximizing learning is the proper application of each type of learning at the appropriate level and time. With tight iterative exchanges between the two, it is possible to learn a lot in a little amount of time.

Our journey has many stops and signposts along the way to help assist and guide us toward our destination, and in the spirit of maximizing learning, each chapter represents an evolution toward our goal that includes live, runnable examples (exploration) along with the exact source code for the application at that point of the journey.

Figure 1.8 – View the application source in context with the stage of your journey

We accomplish this in a simple fashion via the use of Git branches – one for each chapter involving the application code. In addition, each chapter may have one or more Playground snippets (see Chapter 2, Ramping up on Babylon.js, for more on the Playground) specific to the content covered in that chapter. Snippets are neat in a lot of ways and one of those is that they can have multiple revisions. Toggling between different revisions of a snippet is a great way to visually see how an example has evolved and can help bring insights as to why a particular piece of code behaves as it does.

Maybe things were going OK but then you’ve found yourself stuck on something that you just can’t figure out. That’s OK too – there are places you can go for help! Create a post or add to an existing one in the Discussions board over at https://github.com/jelster/space-truckers/discussions for questions, comments, or concerns about content in the repository and/or book. Questions more general to BJS can be posted over at the BJS community forums – https://forum.babylonjs.com. Creating an account for both GitHub and the BJS Forums can be relatively quick and painless.

Tip

If you are planning to create both a BJS Forum and a GitHub account login, save yourself half the effort by signing up for GH first. Then, when you create your forum account, you can select the Login With GitHub option, supplying the information for your newly created GH account.

The Space-Truckers repository has more than just the source code and discussions, though. It also hosts the Issue Tracker for the game (https://github.com/jelster/space-truckers/issues), which is where people can request a new feature or file a bug report – it’s also where folks looking to contribute to the project can peek to find something suitable to their abilities.

Tip

Another pro-tip offered pro rata via the cost of this book: Scan through issues with the labels good-first-issue and needs-help. Those are ones the repository’s maintainers either need assistance with or feel that the issue represents a gentle introduction to the code base.

Community contributions are what Open-Source Software (OSS) is all about, but because they are largely volunteer-driven, there’s always more work than there are people that can get that work done. Consequently, most maintainers are thrilled whenever somebody submits a Pull Request – a set of changes to be incorporated into the code base – to the project that resolves an existing issue!

Tip

Getting tired of these yet? Fair enough. Final tip: Even projects like BJS with many maintainers working full time on it have this problem. The maintainers might not be having to scrounge donations to keep servers on, but they do have to scrounge for the time to accomplish everything that we want them to!

It can be difficult to synthesize and learn new things when it feels like you’re in drinking all the newness through a firehose. That’s why the Space-Truckers code base is branched by chapter. Though an individual chapter won’t necessarily resemble the current, final game as represented in the main or develop branches (production and beta environments, respectively), each branch has as much complexity as it needs to have for that point in the book and no more. To put it differently, the evolution of the application will mirror the evolution of our journey as it unfolds.

Summary

The next thirteen chapters each represent their own signpost denoting the progress of our journey, and there is much yet to see and accomplish. Pulling onto the Space-Highway, it can appear like the space-road ahead is stretching out toward infinity. The truth is every road seems that way at the start of a trip. By keeping the focus on what’s immediately ahead, the infinite can become finite, and overwhelming complexity becomes manageable tasks.

Much like this book is separated into sections and chapters, Space-Truckers is separated into distinct phases or states. The Landing Page is the launchpad (pun intended) for starting the game, while the Splash Screen prepares the audience and sets the mood. Meanwhile, the Main Menu Screen serves as a navigation hub between the main gameplay states and the others.

There are two(ish) phases to the gameplay. Route Planning is where players use an orbital mechanics simulation to plot a course for their Space-Cargo to get from the origin to the destination planets. The direction and force of the launch are set by the player prior to launch, with the timing of the launch also a major factor in how players dictate their route.

Having planned a route, the next game phase sees that route being used to create a tunnel filled with obstacles (random encounters) that the player now must navigate their Space-Truck through to reach the end point. Time matters, but so does bringing the cargo to its destination in as good a condition as possible. Once the destination has been reached, a third, pseudo-game phase enters the stage.

Scoring is done using several factors that will be outlined in detail as part of Chapter 9, Calculating and Displaying Scoring Results. Players’ decisions from Route Planning impact the final scores in multiple ways ranging from time goals to fuel costs. Only the top scores get persisted into the High Score Screen, a feature available in both the web and PWA versions of the application.

The place where all the work around Space-Truckers is tracked and managed is in Space-Truckers: The GitHub Repository. Additionally, each chapter of the book (with a few exceptions) has its own branch in the source code. This allows you to view the state of the overall application in context with the content of the corresponding chapter. Additional assistance can be found by posting in either Space-Truckers: The Discussion Boards or on the BJS official community forums.

Next, we’ll start by gradually building some momentum through a back-to-basics review of the BJS framework and ecosystem. We’ll look at some of the tools, resources, and techniques and if necessary (re)introduce ourselves to how rendering in BJS works. We’ll learn about the Playground and begin the process of building our application by creating a simple loading animation. Buckle up, Space-Trucker – we’re hitting the road!