WGPU by Examples
About this Book
Are you ready to take your graphics in Rust to the next level? Look no further than "WGPU by Examples". This comprehensive book equips you with all the tools you need to create stunning 3D graphics in your native and 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, super-shapes, 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 wgpu, the cutting-edge graphics API for the Web and native devices, so even those with minimal experience can grasp the fundamentals of advanced graphics development.
This book includes:
- wgpu basics, WGSL shaders, and rendering pipeline.
- 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.
- Create procedural terrains on both the CPU and GPU.
- Construct marching cubes for generating 3D implicit surfaces, metaballs, and voxel terrains.
- Visualize complex functions using 3D plots and domain coloring.
- 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 WGPU. So, are you ready to explore next-generation RUST graphics and compute API? Start your journey with "WGPU by Examples" today!
Table of Contents
Contents v Introduction 1 Overview 1 What this Book Includes 2 Is this Book for You? 2 What Do You Need to Use this Book? 3 How this Book Is Organized 3 Use Code Examples 5 Customer Support 5 1 Get Started 7 1.1 Creating a Rust Application 7 1.2 wgpu initialization 8 1.2.1 wgpu Backends 10 1.2.2 Surface 12 1.3 wgpu Information 13 1.4 wgpu Basics 16 1.4.1 Render Pipelines 16 1.4.2 Render Passes 19 1.5 Triangle with Distinct Vertex Colors 22 1.5.1 Shader Code 22 1.5.2 Common Code 23 1.5.3 Rust Code 26 1.5.4 Run Application 26 1.6 Triangle Primitives 27 1.6.1 Shader Code 27 1.6.2 Rust Code 28 1.6.3 Run Application 29 1.7 Create Triangle Using GPU Buffers 30 1.7.1 Shader Code 30 1.7.2 Rust Code 31 1.7.3 Run Application 35 1.8 Create Lines with MSAA 35 1.8.1 Rust Code 35 1.8.2 Run Application 39 2 3D Shapes and Wireframes 41 2.1 Transformations 41 2.2 Create 3D Cube 44 2.2.1 Vertex Data 44 2.2.2 Shader Code 46 2.2.3 Rust Code 46 2.2.4 Run Application 53 2.3 Cube with Wireframe 53 2.3.1 Shader code 54 2.3.2 Rust Code 54 2.3.3 Run Application 61 2.4 Sphere with Wireframe 61 2.4.1 Vertex Data 63 2.4.2 Rust Code 64 2.4.3 Run Application 66 2.5 Cylinder with Wireframe 67 2.5.1 Vertex Data 68 2.5.2 Rust Code 70 2.5.3 Run Application 72 2.6 Torus with Wireframe 73 2.6.1 Vertex Data 74 2.6.2 Rust Code 75 2.6.3 Run Application 78 3 Lighting and Shading 79 3.1 Light Components 79 3.2 Normal Vectors 80 3.2.1 Surface Normal of a Cube 80 3.2.2 Surface Normal of a Sphere 81 3.2.3 Surface Normal of a Cylinder 81 3.2.4 Surface Normal of a Polyhedral Surface 81 3.3 Blinn-Phong Light Model 82 3.3.1 Diffuse Light 82 3.3.2 Specular Light 82 3.3.3 Normal Vector Transformation 83 3.3.4 Shader with Blinn-Phong Model 84 3.4 3D Shapes with Blinn-Phong Lighting 86 3.4.1 Common Code 86 3.4.2 Cube with Lighting 95 3.4.3 Sphere with Lighting 97 3.4.4 Torus with Lighting 97 3.5 Directional Light 99 3.5.1 Instanced Drawing 99 3.5.2 Shader Code 100 3.5.3 Common Code 101 3.5.4 Rust Code 105 3.5.5 Run Application 113 3.6 Point Light 114 3.6.1 Shader Code 114 3.6.2 Rust Code 115 3.6.3 Run Application 116 3.7 Spotlight 117 3.7.1 Shader Code 117 3.7.2 Rust Code 118 3.7.3 Run Application 119 3.8 Soft Edge Spotlight 119 3.8.1 Shader Code 120 3.8.2 Rust Code 121 3.8.3 Run Application 121 3.9 Fog Effect 122 3.9.1 Shader Code 123 3.9.2 Rust Code 124 3.9.3 Run Application 124 4 Advanced Lighting 127 4.1 Shadow Mapping 127 4.1.1 Shader Code 128 4.1.2 Rust Code 130 4.1.3 Run Application 143 4.2 Introduction to PBR 144 4.2.1 Microfacet Model 144 4.2.2 Bidirectional Reflectance Distribution Function 145 4.2.3 Normal Distribution Function 145 4.2.4 Geometry Function 146 4.2.5 Fresnel Equation 146 4.3 PBR Implementation 147 4.3.1 Shader Code 147 4.3.2 Rust Code 150 4.3.3 Run Application 157 5 Colormap and 3D Surfaces 159 5.1 Color Models 159 5.2 Colormap 160 5.2.1 Colormap Data 160 5.2.2 Color Interpolation 162 5.3 Framerate and FPS 163 5.4 Shaders with Lighting and Vertex Color 164 5.5 Simple 3D Surfaces 165 5.5.1 Vertex Data 165 5.5.2 Math Functions for Simple surfaces 169 5.5.3 Rust Code 170 5.5.4 Run Application 180 5.6 Parametric 3D Surfaces 181 5.6.1 Vertex Data 181 5.6.2 Math Functions for Parametric Surfaces 187 5.6.3 Rust Code 190 5.6.4 Run Application 191 5.7 Multiple Surfaces 192 5.7.1 Rendering Multiple Simple Surfaces 192 5.7.2 Rendering Multiple Parametric Surfaces 196 6 Textures 199 6.1 Texture Coordinates 199 6.2 Texture Mapping in wgpu 201 6.3 Shaders with Texture 203 6.3.1 Vertex Shader 203 6.3.2 Fragment Shader 204 6.4 Common Code 205 6.5 Simple 3D Shapes 207 6.5.1 Cube with Texture 207 6.5.2 Sphere with Texture 216 6.6 3D Surfaces 217 6.6.1 Simple Surfaces with Texture 217 6.6.2 Parametric Surfaces with Texture 219 6.7 Cube with Multiple Textures 221 6.7.1 Shader Code 221 6.7.2 Rust Code 222 6.8 Normal Mapping 230 6.8.1 Calculating Tangents and Bitangents 232 6.8.2 Shader Code 234 6.8.3 Cube with Normal Map 237 6.8.4 Sphere with Normal Mapping 245 6.9 Parallax Mapping 246 6.9.1 Shader Code 247 6.9.2 Rust Code 249 7 Compute Shaders for Surface Generation 251 7.1 Compute Shaders 252 7.1.1 Compute Space and Workgroups 252 7.1.2 Write and Read Buffer 253 7.2 Simple 3D Surfaces 255 7.2.1 Compute Shader for Generating Indices 255 7.2.2 Shader Code for Math Functions 256 7.2.3 Compute Shader for Vertex Data 257 7.2.4 Rust Code 260 7.2.5 Run Application 273 7.3 Parametric 3D Surfaces 275 7.3.1 Shader Code for Math Functions 275 7.3.2 Compute Shader for Vertex Data 283 7.3.3 Rust Code 286 7.3.4 Run Application 290 7.4 Super Shapes 290 7.4.1 Compute Shader for Vertex Data 291 7.4.2 Rust Code 294 7.4.3 Run Application 298 8 Procedural Terrains 301 8.1 Noise Model 301 8.1.1 Perlin Noise 302 8.1.2 Noise Map 302 8.2 Creating Terrains on CPU 305 8.2.1 Terrain Data 305 8.2.2 Shader Code 306 8.2.3 Rust Code 307 8.2.4 Run Application 315 8.3 Water Level 316 8.3.1 Colormap for Terrain 317 8.3.2 Terrain Data with Water Level 318 8.3.3 Rust Code 319 8.3.4 Run Application 319 8.4 Terrain Chunks 321 8.4.1 Level of Detail Algorithm 321 8.4.2 Terrain Chunk Data 322 8.4.3 Rust Code 323 8.4.4 Run Application 324 8.5 Terrain Instances 325 8.5.1 Shader Code 326 8.5.2 Rust Code 326 8.5.3 Run Application 335 8.6 Multiple Terrain Chunks 336 8.6.1 Implementation 336 8.6.2 Rust Code 337 8.6.3 Run Application 347 8.7 Terrain Animation 349 8.8 Creating Terrain on GPU 350 8.8.1 WGSL Code for Noise Model 350 8.8.2 Compute Shader for Terrain data 352 8.8.3 Rust Code 354 8.8.4 Run Application 365 8.9 Creating Minecraft on GPU 366 8.9.1 Shader Code 366 8.9.2 Rust Code 369 8.9.3 Run Application 378 9 Marching Cubes 381 9.1 Marching Cubes Algorithm 381 9.2 Implicit 3D Surfaces 383 9.2.1 Shader Code for Implicit Functions 383 9.2.2 Compute Shader for Values 387 9.2.3 Compute Shader for Implicit Surfaces 388 9.2.4 Rust Code 393 9.2.5 Run Application 406 9.3 Metaballs 407 9.3.1 Compute Shader for Values 407 9.3.2 Compute Shader for Metaballs 409 9.3.3 Rust Code 410 9.3.4 Run Application 423 9.4 Voxel Terrains 424 9.4.1 Shader Code for 3D Noise 425 9.4.2 Compute Shader for Values 427 9.4.3 Compute Shader for Voxel Terrain 428 9.4.4 Rust Code 433 9.4.5 Run Application 444 9.5 Voxel Volcanoes 445 9.5.1 Compute Shader for Values 445 9.5.2 Compute Shader for Volcano 448 9.5.3 Rust Code 449 9.5.4 Run Application 456 9.6 Voxel Minecraft 457 9.6.1 Vertex Shader 457 9.6.2 Compute Shader for Minecraft 458 9.6.3 Rust Code 461 9.6.4 Run Application 473 10 Visualizing Complex Functions 475 10.1 Surface Plots on CPU 476 10.1.1 Complex Numbers in Rust 476 10.1.2 Surface Data 477 10.1.3 Rust Code 481 10.1.4 Run Application 488 10.2 Surface Plots on GPU 489 10.2.1 Complex Functions in Shader 489 10.2.2 Compute Shader for Surface Data 491 10.2.3 Rust Code 495 10.2.4 Run Application 503 10.3 Domain Coloring 504 10.3.1 Color Functions in Shader 505 10.3.2 Compute Shader for Domain Coloring 507 10.3.3 Render Shader 509 10.3.4 Rust Code 510 10.3.5 Run Application 516 10.4 Domain Coloring for Iterated Functions 517 10.4.1 Compute Shader for iterated functions 517 10.4.2 Rust Code 519 10.4.3 Run Application 525 11 Particle System 527 11.1 Compute Boids 528 11.1.1 Shader Code 528 11.1.2 Rust Code 530 11.1.3 Run Application 536 11.2 Particles under Gravity 537 11.2.1 Shader Code 537 11.2.2 Rust Code 539 11.2.3 Run Application 547 11.3 Firework Simulation 549 11.3.1 Shader Code 549 11.3.2 Rust Code 551 11.3.3 Run Application 556 11.4 Fire Simulation 557 11.4.1 Shader Code 557 11.4.2 Rust Code 559 11.4.3 Run Application 565 11.5 Gravity on a 2D Grid 566 11.5.1 Shader Code 566 11.5.2 Rust Code 568 11.5.3 Run Application 573 11.6 Electric Field 575 11.6.1 Shader Code 575 11.6.2 Rust Code 577 11.6.3 Run Application 581 11.7 Universe and Stars 582 11.7.1 Shader Code 582 11.7.2 Rust Code 585 11.7.3 Run Application 589 12 Text Rendering 591 12.1 Bitmap Fonts 591 12.1.1 Shader Code 592 12.1.2 Rust Code 595 12.1.3 Run Application 599 12.2 Glyph Geometry 600 12.2.1 Font Data 600 12.2.2 2D Glyph Text 602 12.2.3 3D Glyph Text 609 Index 619
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
Welcome to WGPU by Examples! This book offers an immersive and practical approach to learning the next-generation graphics API, wgpu. The wgpu API is a cross-platform, safe, pure-Rust graphics API. Although it is based on the WebGPU standard, it can run not only on the web via WebAssembly but also on native devices with various backends such as Vulkan, Metal, DirectX12, DirectX11, and OpenGLES. With our step-by-step real-world examples, you will be able to create high-quality, real-time 3D graphics and GPU computing using this new wgpu graphics API. Whether you are a graphics creator, computer graphics programmer, game developer, or a student interested in the latest graphics development in Rust, this book is designed to help you acquire the skills and knowledge you need to succeed.
To understand the wgpu technology, it is essential 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, optimizing graphics performance on newer hardware architectures became increasingly difficult. This led to the development of newer graphics APIs, including Vulkan, Metal, and DirectX 12, which were designed to take full advantage of modern hardware and software architectures.
Despite the availability of these newer graphics APIs, there is still a need for a unified graphics API that is designed for both the native devices and the Web. Unfortunately, Vulkan has run into trouble 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, dealing 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.
On the other hand, wgpu is a Rust implementation of the WebGPU API specifications. It allows developers to use the WebGPU API outside of web browsers, running natively on various platforms, including Vulkan, Metal, DirectX12, DirectX11, and OpenGLES. Rust’s wgpu enables developers to create cross-platform applications that can take full advantage of modern graphics APIs on native devices, not just limited to the web environment. This means that Rust’s wgpu extends the reach of the WebGPU API to native platforms, providing the benefits of low-level GPU access and performance on a broader range of devices.
Additionally, WebGPU and wgpu introduce a new shading language called WGSL (WebGPU Shading Language). This is because existing shading languages like GLSL and HLSL were not designed with WebGPU and wgpu in mind and lack some features that are important for efficient and safe execution. WGSL is designed specifically for WebGPU and wgpu and take into account the unique security and performance considerations of running graphics code in both native device and browser environments. 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. Having a unified shading language across all platforms makes it easier for developers to write code that can be run across different devices without worrying about compatibility issues.
WGPU by Examples is a comprehensive guide that equips you with all the tools you need to create stunning 3D graphics in your 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 wgpu, the cutting-edge graphics API in Rust, so even graphics 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 wgpu API and shader programs.
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 wgpu and Rust. After reading this book and running the example programs, you will be able to create various sophisticated 3D graphics with GPU acceleration in your graphics 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 wgpu 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, wgpu 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 wgpu and WGSL. Therefore, I do not spend any time discussing the basics of programming with wgpu and Rust. To get the most out of this book, you should have some experience with graphics programming in OpenGL or WebGPU and understand 3D rendering concepts such as model coordinates, view coordinates, perspective transformations, and other associated mathematical background. Some experience in wgpu and WGSL programming will also help, as I do not cover the absolute basics of dealing with code. For those new to wgpu, it is best to first read my introductory book “Practical GPU Graphics with wgpu and Rust”, where I provided step-by-step tutorials for creating simple graphics using wgpu and Rust.
It is worth noting that a significant portion of the information in this book about wgpu 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 using the next-generation wgpu graphics API.
Graphics programmers can use many of the example programs in this book routinely. Throughout the book, I emphasize the usefulness of wgpu graphics programming to real-world 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 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), Rust, and Cargo 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.
Since the wgpu standard is still in development and has not been finalized, its API may change frequently. This book uses version 0.17.1 of wgpu for implementing wgpu applications. If you install other versions of the wgpu 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 wgpu 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 wgpu 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 wgpu 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 wgpu graphics programming, including the structure of a wgpu application and how to initialize wgpu. 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 explains the creation of 3D shapes and wireframes using wgpu. It provides vertex data, shader code, and Rust code for creating a 3D cube, sphere, cylinder, and torus with wireframe, as well as adding multi-sample anti-aliasing (MSAA) to 3D shapes.
Chapter 3, Lighting and Shading
This chapter discusses how to simulate light and shading 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 Rust 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 wgpu. 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 Rust code for generating vertices and indices. Finally, the chapter introduces the concept of super shapes and provides compute shader and Rust 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, Rust 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 Rust 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 wgpu. It begins with an explanation of how to use bitmap fonts, where the chapter provides shader code for text rendering and Rust code for loading bitmap fonts. Next, the glyph geometry is introduced, which involves creating geometry for each character in a font and rendering the text as a regular 2D or 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.