WebGPU by Examples
About this Book
Are you ready to take your web graphics to the next level? Look no further than "WebGPU by Examples". This comprehensive guide equips you with all the tools you need to create stunning 3D graphics in your web applications with the help of GPU acceleration.
With this book, you will discover how to design an array of 3D graphics, from basic shapes like cubes, spheres, cylinders, and tori to intricate 3D graphics like wireframes, simple and parametric surfaces, supershapes, implicit surfaces, procedural terrains, volcanoes, Minecraft, voxel terrains, text rendering, and complex function visualization, as well as particle systems made using compute shaders.
The author has simplified the learning process by breaking down the concepts of WebGPU, the cutting-edge graphics API for the Web, so even those with minimal experience can grasp the fundamentals of advanced graphics development.
This book includes:
- Introduce a starter template for graphics programming with WebGPU.
- Create basic 3D shapes like cube, sphere, cylinder, torus, etc.
- Design intricate 3D surface graphics such as wireframes, simple and parametric 3D surfaces, and procedural terrains.
- Simulate light and shadow using different models, including point, directional, and spot light.
- Implement physical-based rendering lighting methods to create realistic graphics.
- Apply colormap and texture techniques to 3D surfaces.
- Generate 3D surfaces and super shapes using compute shaders for improving performance.
- Construct marching cubes for generating 3D implicit surfaces, metaballs, and voxel terrains.
- Create particle systems for 3D graphics applications.
Whether you are a beginner or an experienced developer, this book is the ideal resource to help you design a wide range of graphics applications in WebGPU. So, are you ready to explore next-generation web graphics and compute API? Start your journey with "WebGPU by Examples" today!
Table of Contents
Contents v Introduction 1 Overview 1 What this Book Includes 2 Is this Book for You? 3 What Do You Need to Use this Book? 3 How this Book Is Organized 4 Use Code Examples 5 Customer Support 6 1 Get Started 7 1.1 WebGPU Starter Template 7 1.1.1 Template Structure 8 1.1.2 Package File 10 1.1.3 Configuration Options 11 1.2 Test Starter Template 13 1.2.1 Run App on Local Web Server 13 1.2.2 Live Server 14 1.2.3 WebGPU Information 15 1.2.4 Frame Rates and Rendering Time 16 1.3 WebGPU Basics 18 1.3.1 WebGPU Simplified Library 18 1.3.2 Initialize WebGPU 18 1.3.3 Render Pipelines 20 1.3.4 Render Passes 22 1.4 First WebGPU Example 23 1.4.1 Shader Code 23 1.4.2 TypeScript Code 24 1.5 Triangle Primitives 26 1.5.1 Shader Code 26 1.5.2 TypeScript Code 27 1.6 Create Triangle Using GPU Buffers 28 1.6.1 Helper Functions 29 1.6.2 Shader Code 34 1.6.3 TypeScript Code 34 2 3D Shapes and Wireframes 37 2.1 Common Functions 37 2.2 Create 3D Cube 40 2.2.1 Vertex Data 41 2.2.2 Shader Code 42 2.2.3 TypeScript Code 43 2.3 Cube with Wireframe 46 2.3.1 Shader code 46 2.3.2 TypeScript Code 46 2.4 Cube with MSAA 50 2.5 Sphere with Wireframe 51 2.5.1 Vertex Data 52 2.5.2 Common Code 54 2.5.3 TypeScript Code 57 2.6 Icosphere with Wireframe 59 2.6.1 Vertex Data 60 2.6.2 TypeScript Code 62 2.7 Cylinder with Wireframe 64 2.7.1 Vertex Data 65 2.7.2 TypeScript File 66 2.8 Torus with Wireframe 69 2.8.1 Vertex Data 69 2.8.2 TypeScript Code 71 3 Lighting and Shading 75 3.1 Light Components 75 3.2 Normal Vectors 76 3.2.1 Surface Normal of a Cube 76 3.2.2 Surface Normal of a Sphere 77 3.2.3 Surface Normal of a Cylinder 77 3.2.4 Surface Normal of a Polyhedral Surface 77 3.3 Blinn-Phong Light Model 78 3.3.1 Diffuse Light 78 3.3.2 Specular Light 78 3.3.3 Normal Vector Transformation 79 3.3.4 Shader with Blinn-Phong Model 80 3.4 3D Shapes with Blinn-Phong Lighting 82 3.4.1 Common Code 82 3.4.2 Cube with Lighting 86 3.4.3 Sphere with Lighting 88 3.4.4 Torus with Lighting 90 3.5 Directional Light 93 3.5.1 Instanced Drawing 93 3.5.2 Shader Code 93 3.5.3 Common Code 95 3.5.4 TypeScript Code 98 3.6 Point Light 101 3.6.1 Shader Code 101 3.6.2 TypeScript Code 102 3.7 Spotlight 104 3.7.1 Shader Code 105 3.7.2 TypeScript Code 106 3.8 Soft Edge Spotlight 108 3.8.1 Shader Code 109 3.8.2 TypeScript Code 110 3.9 Fog Effect 113 3.9.1 Shader Code 113 3.9.2 TypeScript Code 115 4 Advanced Lighting 119 4.1 Shadow Mapping 119 4.1.1 Shader Code 120 4.1.2 TypeScript Code 122 4.2 Introduction to PBR 129 4.2.1 Microfacet Model 129 4.2.2 Bidirectional Reflectance Distribution Function 130 4.2.3 Normal Distribution Function 131 4.2.4 Geometry Function 131 4.2.5 Fresnel Equation 131 4.3 PBR Implementation 132 4.3.1 Shader Code 133 4.3.2 TypeScript Code 135 5 Colormap and 3D Surfaces 139 5.1 Color Models 139 5.2 Colormap 140 5.2.1 Colormap Data 140 5.2.2 Color Interpolation 142 5.3 Shaders with Lighting and Vertex Color 143 5.4 Simple 3D Surfaces 144 5.4.1 Vertex Data 144 5.4.2 Math Functions for Simple surfaces 147 5.4.3 TypeScript Code 148 5.5 Parametric 3D Surfaces 155 5.5.1 Vertex Data 155 5.5.2 Math Functions for Parametric Surfaces 158 5.5.3 TypeScript Code 163 5.6 Multiple Surfaces 166 5.6.1 Rendering Multiple Simple Surfaces 167 5.6.2 Rendering Multiple Parametric Surfaces 172 6 Textures 177 6.1 Texture Coordinates 177 6.2 Texture Mapping in WebGPU 179 6.3 Shaders with Texture 180 6.3.1 Vertex Shader 180 6.3.2 Fragment Shader 181 6.4 Common Code 182 6.5 Simple 3D Shapes 185 6.5.1 Cube with Texture 185 6.5.2 Sphere with Texture 189 6.6 3D Surfaces 191 6.6.1 Simple Surfaces with Texture 191 6.6.2 Parametric Surfaces with Texture 194 6.7 Cube with Multiple Textures 197 6.7.1 Shader Code 198 6.7.2 TypeScript Code 199 6.8 Normal Mapping 203 6.8.1 Calculating Tangents and Bitangents 204 6.8.2 Shader Code 207 6.8.3 Cube with Normal Map 209 6.8.4 Sphere with Normal Mapping 214 6.9 Parallax Mapping 215 6.9.1 Shader Code 216 6.9.2 TypeScript Code 217 7 Compute Shaders for Surface Generation 221 7.1 Compute Shaders 221 7.1.1 Compute Space and Workgroups 222 7.1.2 Write and Read Buffer 223 7.2 Simple 3D Surfaces 224 7.2.1 Shader Code for Colormap Data 225 7.2.2 Compute Shader for Generating Indices 231 7.2.3 Shader Code for Math Functions 232 7.2.4 Compute Shader for Vertex Data 233 7.2.5 TypeScript Code 236 7.3 Parametric 3D Surfaces 245 7.3.1 Shader Code for Math Functions 245 7.3.2 Compute Shader for Vertex Data 254 7.3.3 TypeScript Code 257 7.4 Super Shapes 262 7.4.1 Compute Shader for Vertex Data 262 7.4.2 TypeScript Code 265 8 Procedural Terrains 273 8.1 Noise Model 273 8.1.1 Perlin Noise 274 8.1.2 Noise Map 276 8.2 Creating Terrains on CPU 279 8.2.1 Terrain Data 279 8.2.2 Shader Code 280 8.2.3 TypeScript Code 281 8.3 Water Level 285 8.3.1 Colormap for Terrain 286 8.3.2 Terrain Data with Water Level 287 8.3.3 TypeScript Code 288 8.4 Terrain Chunks 292 8.4.1 Level of Detail Algorithm 292 8.4.2 Terrain Chunk Data 293 8.4.3 TypeScript Code 294 8.5 Terrain Instances 299 8.5.1 Shader Code 299 8.5.2 TypeScript Code 299 8.6 Multiple Terrain Chunks 304 8.6.1 Implementation 304 8.6.2 TypeScript Code 305 8.7 Terrain Animation 312 8.8 Creating Terrain on GPU 313 8.8.1 WGSL Code for Noise Model 313 8.8.2 Compute Shader for Terrain data 315 8.8.3 Compute Shader for Indices 317 8.8.4 TypeScript Code 318 8.9 Creating Minecraft on GPU 324 8.9.1 Shader Code 324 8.9.2 TypeScript Code 325 9 Marching Cubes 333 9.1 Marching Cubes Algorithm 333 9.2 Implicit 3D Surfaces 335 9.2.1 Shader Code for Implicit Functions 335 9.2.2 Compute Shader for Values 339 9.2.3 Compute Shader for Implicit Surfaces 340 9.2.4 TypeScript Code 345 9.3 Metaballs 354 9.3.1 Compute Shader for Values 354 9.3.2 Compute Shader for Metaballs 356 9.3.3 TypeScript Code 357 9.4 Voxel Terrains 364 9.4.1 Shader Code for 3D Noise 365 9.4.2 Compute Shader for Values 367 9.4.3 Compute Shader for Voxel Terrain 369 9.4.4 TypeScript Code 370 9.5 Voxel Volcanoes 376 9.5.1 Compute Shader for Values 376 9.5.2 Compute Shader for Volcano 378 9.5.3 TypeScript Code 379 9.6 Voxel Minecraft 385 9.6.1 Vertex Shader 385 9.6.2 Compute Shader for Minecraft 386 9.6.3 TypeScript Code 390 10 Visualizing Complex Functions 399 10.1 Surface Plots on CPU 400 10.1.1 Complex Numbers in TypeScript 400 10.1.2 Surface Data 401 10.1.3 TypeScript Code 404 10.2 Surface Plots on GPU 409 10.2.1 Complex Functions in Shader 409 10.2.2 Compute Shader for Surface Data 411 10.2.3 TypeScript Code 416 10.3 Domain Coloring 422 10.3.1 Color Functions in Shader 423 10.3.2 Compute Shader for Domain Coloring 425 10.3.3 Render Shader 427 10.3.4 TypeScript Code 428 10.4 Domain Coloring for Iterated Functions 432 10.4.1 Compute Shader for iterated functions 432 10.4.2 TypeScript Code 434 11 Particle System 437 11.1 Compute Boids 438 11.1.1 Shader Code 438 11.1.2 TypeScript Code 440 11.2 Particles under Gravity 446 11.2.1 Shader Code 446 11.2.2 TypeScript Code 448 11.3 Firework Simulation 454 11.3.1 Shader Code 454 11.3.2 TypeScript Code 456 11.4 Fire Simulation 459 11.4.1 Shader Code 459 11.4.2 TypeScript Code 461 11.5 Gravity on a 2D Grid 464 11.5.1 Shader Code 464 11.5.2 TypeScript Code 466 11.6 Electric Field 470 11.6.1 Shader Code 470 11.6.2 TypeScript Code 472 11.7 Universe and Stars 474 11.7.1 Shader Code 475 11.7.2 TypeScript Code 477 12 Text Rendering 481 12.1 Canvas Texture 481 12.1.1 Texture on a 2D Quad 482 12.1.2 Texture on a Cube 485 12.2 Bitmap Fonts 488 12.2.1 Shader Code 489 12.2.2 TypeScript Code 492 12.3 Glyph Geometry 494 12.3.1 Vertex Shader 494 12.3.2 Glyph Geometry Data 495 12.3.3 TypeScript Code 499 Index 505
Introduction
        Overview
        What This Book Includes
        Is This Book for You
        What Do You Need to Use This Book
        How This Book is Organized
        Using Code Examples
Overview
Welcome to WebGPU by Examples! This book offers an immersive and practical approach to learning the next-generation graphics API, WebGPU, currently under development by the W3C GPU for the Web Community Group. With our step-by-step real-world examples, you will be able to create high-quality, real-time 3D graphics and GPU computing on the Web using the new WebGPU graphics API. Whether you are a web developer, web graphics creator, computer graphics programmer, web game developer, or a student interested in the latest graphics development on the Web, this book is designed to help you acquire the skills and knowledge you need to succeed.
To understand the need for WebGPU, it is important to consider the evolution of graphics APIs. OpenGL has been one of the most popular graphics APIs for decades, but it was not designed for modern hardware and software architectures. As a result, it became increasingly difficult to optimize graphics performance on newer hardware architectures. This led to the development of newer graphics APIs such as WebGL and WebGL2, which were designed specifically for the Web and allowed for the creation of more complex 3D graphics and GPU computing on the Web.
However, with the advent of more powerful hardware, these APIs began to exhibit limitations in terms of performance and functionality. Consequently, newer graphics APIs were developed, including Vulkan, Metal, and DirectX 12, which were designed to take fully advantage of modern hardware and software architectures.
Despite the availability of these newer graphics APIs, there is still a need for a graphics API that is specifically designed for the Web. Unfortunately, Vulkan has run into trouble in achieving true cross-platform reach due to its lack of support on Apple’s MacOS and iOS, which only support Metal. Additionally, Vulkan’s low-level nature, which deals with details such as GPU memory allocators, makes it less suitable for the web platform, where security is a significant concern. This is where WebGPU comes in. WebGPU is designed specifically for the Web, with a high-level approach that makes it usable and secure in a browser, and the ability to be implemented on top of Vulkan, Metal, and DirectX 12. WebGPU is the only truly cross-platform, and modern graphics API for web applications. By using WebGPU, developers can create high-quality, real-time 3D graphics and GPU computing on the Web, enabling users to enjoy a richer and more immersive web experience.
Additionally, WebGPU introduces a new shading language called WGSL (WebGPU Shading Language). This is because existing shading languages like GLSL and HLSL were not designed with WebGPU in mind and lack some features that are important for efficient and safe execution on the web platform. WGSL is designed specifically for WebGPU and takes into account the unique security and performance considerations of running graphics code in a browser environment. Furthermore, WGSL provides a more concise and simplified syntax compared to older shading languages. This makes it easier for developers to write and maintain shaders, especially as graphics programming becomes more complex and powerful. Finally, WGSL is a cross-platform shading language that is designed to work across different devices and platforms, including desktop, mobile, and the Web. By having a unified shading language across all platforms, it makes it easier for developers to write code that can be run across different devices without worrying about compatibility issues.
WebGPU by Examples is a comprehensive guide that equips you with all the tools you need to create stunning 3D graphics in your web applications with the help of GPU acceleration. With this book, you will discover how to design an array of 3D graphics, from basic shapes like cubes, spheres, and cylinders to intricate 3D surface graphics like wireframes, surfaces, procedural terrains, volcanoes, Minecraft, voxel terrains, text rendering, and complex function visualization, and particle systems made using compute shaders. I have simplified the learning process by breaking down the concepts of WebGPU, the cutting-edge graphics API for the Web, so even front-end web developers with minimal experience can grasp the fundamentals of advanced graphics development. This book is an ideal resource to help you design a wide range of 3D graphics applications using the WebGPU API and shader programs.
Furthermore, to simplify the code of the example projects included in the book, I have implemented an npm package called webgpu-simplified. This package is not a renderer or a rendering engine, but simply a collection of helper functions and interfaces. Unlike a rendering engine, this mini library does not alter the code structure and workflow of the original WebGPU applications.
The helper functions contained in the webgpu-simplified package can also help you build your own WebGPU applications quickly and avoid code duplication when creating GPU buffers, render/compute pipelines, render pass, and 3D transformations. This mini package does not do everything, and if you want add more features to it, you can do so by pulling the GitHub repository. In certain cases where a particular feature may not be included in the package, you can always write standard WebGPU code for it, which is much more flexible than a render engine.
What This Book Includes
This book and its sample code listings, which are available for download at my website at https://drxudotnet.com, provide you with
- A complete and in-depth guide to practical 3D graphics programming with WebGPU. After reading this book and running the example programs, you will be able to create various sophisticated 3D graphics with GPU acceleration in your web applications.
- Over 65 ready-to-run example projects that allow you to explore the 3D graphics techniques described in this book. You can use these examples to get better understanding of how the 3D graphics are created using the WebGPU API and shader programs. You can also modify the code or add new features to them to form the basis of your own projects. Some of the example code listings provided with this book are already sophisticated graphics projects, and can be directly used in your own real-world web applications.
- Many functions and components in the sample code listings that you will find useful in your 3D graphics development. These functions and components include 3D transformation, projection, colormaps, lighting models, computer shader code, WebGPU pipeline settings, as well as the other useful utility functions. You can extract these functions and components and plug them into your own web applications.
Is This Book for You
The primary focus of this book is advanced GPU graphics programming with WebGPU and WGSL. Therefore, I do not spend any time discussing the basics of programming with WebGPU. To get the most out of this book, you should have some experience with graphics programming in OpenGL or WebGL and understand 3D rendering concepts such as model coordinates, view coordinates, perspective transformations, and other associated mathematical background. Some experience in WebGPU and WGSL programming will also help, as I do not cover the absolute basics of dealing with code. For those new to WebGPU, it is best to first read my introductory book “Practical WebGPU Graphics”, where I provided step-by-step tutorials for creating simple graphics using WebGPU and WGSL.
It is worth noting that a significant portion of the information in this book about WebGPU programming is not available in other tutorial and reference books. In addition, you can use most of the example programs contained in this book directly in your own real-world application development. This book will provide you with a level of detail, explanation, instruction, and sample program code that will enable you to do just about anything related to modern 3D graphics development for the Web using the next-generation WebGPU graphics API.
Web front-end programmers can use many of the example programs in this book routinely. Throughout the book, I emphasize the usefulness of WebGPU graphics programming to real-world web applications. If you follow the instructions presented in this book closely, you will easily be able to develop a variety of graphics applications with GPU acceleration, from simple 3D shapes to 3D surfaces with powerful colormap, wireframe, and texture mapping. You can build standard procedural terrains as well as voxel-based terrains and volcanoes using marching cubes and compute shaders. You can also create complex particle systems, text rendering, and domain coloring for complex functions using compute shaders. However, I will not spend too much time discussing program style, code tree shaking, and code optimization, as there are already plenty of books dealing with those topics. Most of the example programs you will find in this book omit error handling, which makes the code easier to understand by focusing only on the key concepts and practical applications.
What Do You Need to Use This Book?
You do not need any special equipment to make the most of this book and understand the algorithms presented. This book will take full advantage of open-source frameworks and libraries. The sample programs included with this book can run on various operating systems, including Windows, Linux, iOS, or MacOS. For development, this book uses Visual Studio Code (VS Code), TypeScript, and WebPack as the development environment and tools. VS Code is a lightweight IDE and powerful source code editor that runs on various operating systems, such as Windows, Linux, or MacOS. It has built-in support for JavaScript, TypeScript, and Node.js.
Since the WebGPU standard is still in development and has not been finalized, its API may change frequently. This book uses version 0.1.31 of @webgpu/types for implementing WebGPU applications. However, Chromium-based browsers such as Chrome and Microsoft Edge have started supporting WebGPU by default since version 113. All the examples in this book have been tested on the Chrome 113 web browser.
If you install other versions of the WebGPU API, you may be able to run most of the sample code with few modifications. Please remember, however, that this book is intended for that specific version of the WebGPU API on which all of the example programs were created and tested, so it is best to run the sample code on the same development environment and same version of the WebGPU API.
Additionally, your operating system needs to have a modern GPU, as well as the DirectX 12, Metal, or Vulkan backend support on your graphics card.
How This Book Is Organized
This book is structured into twelve chapters, with each chapter exploring a distinct topic related to modern WebGPU graphics programming. Below is a summary of each chapter to provide an overview of the book’s contents:
Chapter 1, Get Started
This chapter covers the basics of WebGPU graphics programming, including the structure of a WebGPU starter template and how to initialize WebGPU. It also includes step-by-step instructions for creating basic triangle examples using shaders and GPU buffers.
Chapter 2, 3D Shapes and Wireframes
This chapter covers the basics of WebGPU graphics programming, including the structure of a WebGPU starter template and how to initialize WebGPU. It also includes step-by-step instructions for creating basic triangle examples using shaders and GPU buffers.
Chapter 3, Lighting and Shading
This chapter discusses how to simulate light and shadow in computer graphics. It begins by introducing the different components of light, such as ambient, diffuse, and specular light. It then covers how to calculate normal vectors for surfaces, and how to use the Blinn-Phong light model to render 3D shapes. Finally, the chapter explains how to implement directional, point, and spot lights, as well as soft edge spot lights and fog effects.
Chapter 4, Advanced Lighting
This chapter covers advanced lighting techniques, including shadow mapping and physically-based rendering (PBR). It explains the microfacet model, bidirectional reflectance distribution function, and other components that make up PBR. The chapter also provides shader and TypeScript code for implementing both shadow mapping and PBR.
Chapter 5, Colormap and 3D Surfaces
This chapter focuses on creating colormap and 3D surfaces. It begins by discussing color models and colormaps, and then moves on to demonstrate how to create shaders with lighting and vertex colors. The chapter also includes examples of creating simple and parametric 3D surfaces, as well as rendering multiple surfaces.
Chapter 6, Textures
This chapter covers texture mapping in WebGPU. It starts with an explanation of texture coordinates and mapping. Then, the chapter explains how to use textures in shaders, and provides examples of using textures with simple 3D shapes and surfaces. It also discusses advanced topics such as cube with multiple textures, normal mapping, and parallax mapping.
Chapter 7, Compute Shaders for Surface Generation
This chapter focuses on using compute shaders for surface generation. The chapter covers the basics of compute shaders, including compute space, workgroups, and buffer read/write operations. It then demonstrates the creation of simple and parametric 3D surfaces using compute shaders and provides shader and TypeScript code for generating vertices and indices. Finally, the chapter introduces the concept of super shapes and provides compute shader and TypeScript code for generating their vertex data.
Chapter 8, Procedural Terrains
This chapter covers the creation of procedural terrains using noise models. It explains the implementation of terrain chunks, instances, animation, and generation on both the CPU and GPU. Topics covered include Perlin noise, terrain chunks, level of detail algorithms, and the creation of Minecraft-style worlds using shaders. The reader will find WGSL code for the noise model, compute shaders, TypeScript code, and a detailed explanation of the implementation steps.
Chapter 9, Marching Cubes
This chapter focuses on the marching cubes algorithm, which is used to generate 3D surfaces from a volumetric dataset. The chapter covers implicit 3D surfaces, metaballs, voxel terrains, voxel volcanoes, and voxel Minecraft. It includes shader code, compute shader code, and TypeScript code to implement these techniques.
Chapter 10, Visualizing Complex Functions
This chapter discusses visualizing complex functions using surface plots and domain coloring. The chapter first explains complex functions and how to generate surface data on the CPU. Next, the chapter moves on to implementing complex functions in shaders and using compute shaders to generate surface data on the GPU. Finally, domain coloring is introduced as a way to visualize complex functions.
Chapter 11, Particle System
This chapter covers the topic of particle systems and simulations. It begins with a discussion of how to implement the compute boids algorithm using compute shaders. Next, the chapter moves on to particle simulations under gravity. It then covers firework simulations, fire simulations, gravity on a 2D grid, electric field distribution, and universe and star simulations. All of these simulations are performed on the GPU.
Chapter 12,Text Rendering
This chapter covers text rendering techniques in WebGPU. It begins with an explanation of how to use canvas textures for text rendering, including how to place canvas textures on 2D quads and cubes. Next, it moves on to bitmap fonts, where the chapter provides shader code for text rendering and TypeScript code for loading bitmap fonts. Finally, glyph geometry is introduced, which involves creating geometry for each character in a font and rendering the text as a regular 3D object.
Using Code Examples
You may use the code in this book in your own applications and documentation. You do not need to contact the author or the publisher for permission unless you are reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing the example code listings does require permission. Incorporating a significant amount of example code from this book into your applications and documentation also requires permission. Integrating the example code from this book into commercial products is not allowed without written permission of the author.