Vertex and Fragment Shaders for Game Developers978-1-4842-4457-9/1.pdf · Development Vertex and...
Transcript of Vertex and Fragment Shaders for Game Developers978-1-4842-4457-9/1.pdf · Development Vertex and...
Practical Shader Development
Vertex and Fragment Shaders for Game Developers
Kyle Halladay
Practical Shader Development: Vertex and Fragment Shaders for Game Developers
ISBN-13 (pbk): 978-1-4842-4456-2 ISBN-13 (electronic): 978-1-4842-4457-9https://doi.org/10.1007/978-1-4842-4457-9
Copyright © 2019 by Kyle Halladay
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed SpahrAcquisitions Editor: Jonathan GennickDevelopment Editor: Laura BerendsonCoordinating Editor: Jill Balzano
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book's product page, located at www.apress.com/9781484244562. For more detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
Kyle HalladayBristol, UK
To my wife, Sarah.
v
About the Author ��������������������������������������������������������������������������������������������������� xiii
About the Technical Reviewer ���������������������������������������������������������������������������������xv
Acknowledgments �������������������������������������������������������������������������������������������������xvii
Introduction ������������������������������������������������������������������������������������������������������������xix
Table of Contents
Chapter 1: Hello, Game Graphics ������������������������������������������������������������������������������ 1
What Is Rendering? ����������������������������������������������������������������������������������������������������������������������� 1
What Is a Mesh? ��������������������������������������������������������������������������������������������������������������������������� 2
Vectors 101 ����������������������������������������������������������������������������������������������������������������������������������� 4
Defining a Color in Computer Graphics ��������������������������������������������������������������������������������������� 10
The Rendering Pipeline ��������������������������������������������������������������������������������������������������������������� 12
What Is a Shader? ����������������������������������������������������������������������������������������������������������������������� 14
Summary������������������������������������������������������������������������������������������������������������������������������������� 15
Chapter 2: Your First Shaders ��������������������������������������������������������������������������������� 17
Setting Things Up on Windows���������������������������������������������������������������������������������������������������� 18
Setting Up Our Project����������������������������������������������������������������������������������������������������������������� 18
Creating Your First Triangle ��������������������������������������������������������������������������������������������������������� 20
Your First Vertex Shader �������������������������������������������������������������������������������������������������������������� 22
The #version Preprocessor Directive ������������������������������������������������������������������������������������� 23
GLSL’s in Keyword ����������������������������������������������������������������������������������������������������������������� 23
GLSL’s vec Data Types ����������������������������������������������������������������������������������������������������������� 24
Writing to gl_Position ������������������������������������������������������������������������������������������������������������ 24
Normalized Device Coordinates��������������������������������������������������������������������������������������������� 25
vi
Your First Fragment Shader �������������������������������������������������������������������������������������������������������� 27
GLSL’s out Keyword ��������������������������������������������������������������������������������������������������������������� 27
Using Shaders in Our Project ������������������������������������������������������������������������������������������������������ 28
Adding Color with Vertex Attributes �������������������������������������������������������������������������������������������� 30
Introducing Fragment Interpolation �������������������������������������������������������������������������������������������� 33
Introducing Uniform Variables ����������������������������������������������������������������������������������������������������� 34
Summary������������������������������������������������������������������������������������������������������������������������������������� 36
Chapter 3: Using Textures ��������������������������������������������������������������������������������������� 37
Making a Quad ���������������������������������������������������������������������������������������������������������������������������� 38
Introducing UV Coordinates ��������������������������������������������������������������������������������������������������������� 40
Using Textures in Shaders ����������������������������������������������������������������������������������������������������������� 45
Scrolling UV Coordinates ������������������������������������������������������������������������������������������������������������� 48
Adjusting Brightness with a Uniform ������������������������������������������������������������������������������������������ 52
Basic Color Math ������������������������������������������������������������������������������������������������������������������������� 56
Mixing Textures with the “Mix” Instruction ��������������������������������������������������������������������������������� 60
Summary������������������������������������������������������������������������������������������������������������������������������������� 63
Chapter 4: Translucency and Depth ������������������������������������������������������������������������ 65
Example Project Setup ���������������������������������������������������������������������������������������������������������������� 66
Drawing Our Little Green Man ����������������������������������������������������������������������������������������������������� 66
Alpha Testing with Discard ���������������������������������������������������������������������������������������������������������� 69
Building a Scene with Depth Testing ������������������������������������������������������������������������������������������ 70
Creating Clouds with Alpha Blending ������������������������������������������������������������������������������������������ 72
GLSL’s min( ) and max( ) Functions ���������������������������������������������������������������������������������������������� 75
How Alpha Blending Works ��������������������������������������������������������������������������������������������������������� 76
Adding Some Sun with Additive Blending ����������������������������������������������������������������������������������� 78
Animating with Sprite Sheets ����������������������������������������������������������������������������������������������������� 83
Summary������������������������������������������������������������������������������������������������������������������������������������� 87
Table of ConTenTs
vii
Chapter 5: Making Things Move ����������������������������������������������������������������������������� 89
Making Our Character Walk Forward ������������������������������������������������������������������������������������������ 90
Scaling Our Cloud in Shader Code ���������������������������������������������������������������������������������������������� 93
Rotating Objects with a Vertex Shader ���������������������������������������������������������������������������������������� 97
Introducing Transformation Matrices ���������������������������������������������������������������������������������������� 100
Animating a Transformation Matrix ������������������������������������������������������������������������������������������� 105
The Identity Matrix �������������������������������������������������������������������������������������������������������������������� 109
Summary����������������������������������������������������������������������������������������������������������������������������������� 111
Chapter 6: Cameras and Coordinates ������������������������������������������������������������������� 113
Using a View Matrix ������������������������������������������������������������������������������������������������������������������ 114
Transform Matrices and Coordinate Spaces ����������������������������������������������������������������������������� 118
Camera Frustums and Projections �������������������������������������������������������������������������������������������� 124
Summary����������������������������������������������������������������������������������������������������������������������������������� 128
Chapter 7: Your First 3D Project ��������������������������������������������������������������������������� 129
Loading a Mesh ������������������������������������������������������������������������������������������������������������������������� 129
Making a Perspective Camera �������������������������������������������������������������������������������������������������� 132
Summary����������������������������������������������������������������������������������������������������������������������������������� 135
Chapter 8: Diffuse Lighting ����������������������������������������������������������������������������������� 137
Smooth vs� Flat Shading with Normals ������������������������������������������������������������������������������������� 140
World Space Normals and Swizzling ���������������������������������������������������������������������������������������� 142
The Normal Matrix �������������������������������������������������������������������������������������������������������������������� 144
Why Lighting Calculations Need Normals ��������������������������������������������������������������������������������� 146
What’s a Dot Product?��������������������������������������������������������������������������������������������������������������� 146
Shading with Dot Products ������������������������������������������������������������������������������������������������������� 148
Your First Directional Light �������������������������������������������������������������������������������������������������������� 151
Creating a Rim Light Effect ������������������������������������������������������������������������������������������������������� 154
Summary����������������������������������������������������������������������������������������������������������������������������������� 160
Table of ConTenTs
viii
Chapter 9: Your First Lighting Model �������������������������������������������������������������������� 161
Specular Lighting ���������������������������������������������������������������������������������������������������������������������� 161
Your First Specular Shader ������������������������������������������������������������������������������������������������������� 163
Combining Diffuse and Specular Light �������������������������������������������������������������������������������������� 167
Ambient Lighting ����������������������������������������������������������������������������������������������������������������������� 168
The Phong Lighting Model �������������������������������������������������������������������������������������������������������� 169
Blinn-Phong Lighting ���������������������������������������������������������������������������������������������������������������� 172
Using Textures to Control Lighting �������������������������������������������������������������������������������������������� 175
Summary����������������������������������������������������������������������������������������������������������������������������������� 179
Chapter 10: Normal Mapping �������������������������������������������������������������������������������� 181
What Is a Normal Map? ������������������������������������������������������������������������������������������������������������� 182
Introducing Tangent Space ������������������������������������������������������������������������������������������������������� 184
Working with Tangent Vectors ��������������������������������������������������������������������������������������������������� 185
Introducing Cross Products ������������������������������������������������������������������������������������������������������� 186
How Normal Mapping Works ����������������������������������������������������������������������������������������������������� 188
Writing a Water Shader ������������������������������������������������������������������������������������������������������������� 191
There’s More to Normal Mapping���������������������������������������������������������������������������������������������� 199
Summary����������������������������������������������������������������������������������������������������������������������������������� 200
Chapter 11: Cubemaps And Skyboxes ������������������������������������������������������������������ 201
What Is a Cubemap? ����������������������������������������������������������������������������������������������������������������� 201
Loading a Cubemap in openFrameworks���������������������������������������������������������������������������������� 203
Rendering a Cubemap on a Cube ���������������������������������������������������������������������������������������������� 203
Introducing Skyboxes ���������������������������������������������������������������������������������������������������������������� 207
The Perspective Divide�������������������������������������������������������������������������������������������������������������� 209
Skyboxes and the Perspective Divide ��������������������������������������������������������������������������������������� 210
Finishing Our Skybox ���������������������������������������������������������������������������������������������������������������� 210
Creating Cubemap Reflections �������������������������������������������������������������������������������������������������� 212
There’s More to Cubemaps ������������������������������������������������������������������������������������������������������� 215
Summary����������������������������������������������������������������������������������������������������������������������������������� 215
Table of ConTenTs
ix
Chapter 12: Lighting in Depth ������������������������������������������������������������������������������� 217
Directional Lights ���������������������������������������������������������������������������������������������������������������������� 217
Point Lights ������������������������������������������������������������������������������������������������������������������������������� 219
Spot Lights �������������������������������������������������������������������������������������������������������������������������������� 226
Multiple Light Sources �������������������������������������������������������������������������������������������������������������� 233
A More Flexible Multi-light Setup ���������������������������������������������������������������������������������������������� 240
Taking Things Farther ��������������������������������������������������������������������������������������������������������������� 246
Summary����������������������������������������������������������������������������������������������������������������������������������� 247
Chapter 13: Profiling Shaders ������������������������������������������������������������������������������ 249
How to Measure Performance �������������������������������������������������������������������������������������������������� 249
CPU Time vs� GPU Time ������������������������������������������������������������������������������������������������������������� 250
Working Around VSync �������������������������������������������������������������������������������������������������������������� 251
Working Around Your Computer ������������������������������������������������������������������������������������������������ 255
Practical Profiling ���������������������������������������������������������������������������������������������������������������������� 255
Introducing Nsight Graphics ������������������������������������������������������������������������������������������������������ 259
Are We CPU or GPU bound? ������������������������������������������������������������������������������������������������������� 262
A Handy Shortcut ����������������������������������������������������������������������������������������������������������������� 265
Tracking Down A Problem Shader ��������������������������������������������������������������������������������������������� 266
Summary����������������������������������������������������������������������������������������������������������������������������������� 270
Chapter 14: Optimizing Shaders ��������������������������������������������������������������������������� 271
Move Calculations to Vertex Shaders ���������������������������������������������������������������������������������������� 271
Avoid Dynamic Branching ��������������������������������������������������������������������������������������������������������� 273
Get MAD ������������������������������������������������������������������������������������������������������������������������������������ 277
Prefer GLSL Functions over Your Own ��������������������������������������������������������������������������������������� 278
Use Write Masks ����������������������������������������������������������������������������������������������������������������������� 279
Avoid Unnecessary Overdraw ��������������������������������������������������������������������������������������������������� 280
Final Thoughts ��������������������������������������������������������������������������������������������������������������������������� 281
Summary����������������������������������������������������������������������������������������������������������������������������������� 282
Table of ConTenTs
x
Chapter 15: Precision ������������������������������������������������������������������������������������������� 283
What Is Floating-Point Precision ����������������������������������������������������������������������������������������������� 283
Case Study: Animation over Time ���������������������������������������������������������������������������������������������� 288
Working with Lower Precision Variables ����������������������������������������������������������������������������������� 292
Case Study: Point Light Problem ����������������������������������������������������������������������������������������������� 294
Summary����������������������������������������������������������������������������������������������������������������������������������� 298
Chapter 16: Writing Shaders in Unity ������������������������������������������������������������������� 299
Shaders and Materials in Unity ������������������������������������������������������������������������������������������������� 299
Introducing ShaderLab �������������������������������������������������������������������������������������������������������������� 300
A Solid Color Shader ����������������������������������������������������������������������������������������������������������������� 303
Porting Our Blinn-Phong Shader ����������������������������������������������������������������������������������������������� 309
Translucent Shaders in Unity ���������������������������������������������������������������������������������������������������� 317
Handling Multiple Lights ����������������������������������������������������������������������������������������������������������� 319
Passing Data from C# to Shader Code �������������������������������������������������������������������������������������� 323
Next Steps, ShaderGraph, and the Future ��������������������������������������������������������������������������������� 324
Summary����������������������������������������������������������������������������������������������������������������������������������� 325
Chapter 17: Writing Shaders in UE4 ��������������������������������������������������������������������� 327
Shaders, Materials, and Instances (Oh My!)������������������������������������������������������������������������������ 327
Making Things Red ������������������������������������������������������������������������������������������������������������������� 331
UE4 Material Node Graph Fundamentals ���������������������������������������������������������������������������������� 334
Making a Rim Light Material ����������������������������������������������������������������������������������������������������� 337
The Default Lit Material Inputs �������������������������������������������������������������������������������������������������� 340
Vertex Shader or Fragment Shader? ����������������������������������������������������������������������������������������� 342
Working with Different Shading Models ����������������������������������������������������������������������������������� 346
Blend Modes and Texture Sample Nodes ���������������������������������������������������������������������������������� 347
Passing Data from Code to Materials ���������������������������������������������������������������������������������������� 348
How Does All This Relate to Shader Code? ������������������������������������������������������������������������������� 348
Summary����������������������������������������������������������������������������������������������������������������������������������� 349
Table of ConTenTs
xi
Chapter 18: Writing Shaders in Godot ������������������������������������������������������������������ 351
Shaders and Materials �������������������������������������������������������������������������������������������������������������� 352
The Godot Shading Language ��������������������������������������������������������������������������������������������������� 354
Fragment Shader Output Variables ������������������������������������������������������������������������������������������� 356
Making a Custom Rim Light Shader ������������������������������������������������������������������������������������������ 357
Custom Vertex Shaders ������������������������������������������������������������������������������������������������������������� 363
UV Animation ����������������������������������������������������������������������������������������������������������������������������� 364
Translucent Shaders and Blend Modes ������������������������������������������������������������������������������������� 364
Passing Data from Code to Shaders ����������������������������������������������������������������������������������������� 366
The Future: Visual Shader Editing? ������������������������������������������������������������������������������������������� 367
Summary����������������������������������������������������������������������������������������������������������������������������������� 367
Appendix A: Important Code Snippets ������������������������������������������������������������������ 369
Calculating a Mesh’s Tangents �������������������������������������������������������������������������������������������������� 369
The ofxEasyCubemap Class ������������������������������������������������������������������������������������������������������ 370
Index ��������������������������������������������������������������������������������������������������������������������� 375
Table of ConTenTs
xiii
About the Author
Kyle Halladay is a professional game programmer living
in Chicago. He has more than seven years’ experience in
writing shaders and building graphics technology for games
and architectural visualizations.
xv
About the Technical Reviewer
Ben Garney is the founder of The Engine Company, a
technical consulting firm providing services ranging from
implementation to product architecture and development
to fractional CTO. Ben has had exits as key hire, cofounder,
and founder. His work has powered hundreds of millions of
user experiences, been shown on the TED Prime stage, and
used in planetary robotics research. He cowrote a book,
Video Game Optimization, and has done technical review
for a number of others. His areas of expertise include internet video, AR/VR, game
engines, and engineering team leadership. You can read his blog at http://bengarney.
com/ or follow his Twitter account @bengarney.
xvii
Acknowledgments
I have to start by thanking my wife, Sarah, for all the support she’s given me throughout
writing this book. Not only did she read early chapter drafts and offer advice about how
to make things clearer, but she also put up with me through all the weekends I spent
hunched over my computer, and all the mornings when the first thing I wanted to talk
about was the book. I truly appreciate all the love and support that you’ve shown me
throughout this entire process.
My technical reviewer, Ben Garney, also deserves some special recognition. He took
on this project despite barely knowing me, and not only delivered great feedback about
my content, but also sage advice from his experiences with technical writing. It’s safe to
say that the book would not be nearly as complete (or accurate) without him.
Finally, I want to thank the team at Apress for giving me the chance to write an
actual, physical, book! Thank you for all the time you spent guiding me through this
process, providing feedback, and keeping me on schedule.
xix
Introduction
Welcome to Practical Shader Development. This book is intended to be the gentlest
introduction possible to the theory and practice of writing shaders for video games.
Shader writing is a very large topic, and I can remember feeling very lost when I was
starting out. My hope is that this book will help you avoid that same feeling and allow
you to take your first steps into the vast world of shaders and game graphics quickly and
confidently.
This book’s guiding philosophy is: “a carpenter doesn’t need to know how to make
a wrench.” Similarly, you don’t have to know how to build a rendering engine to be able
to use shaders to create beautiful visual effects, especially when you’re just starting out.
This book is all about empowering you to experiment, be creative, make cool things, and
hopefully have some fun in the process. To that end, this book will not attempt to teach
you how to be a graphics programmer or try to give you a systematic math education
(although we’ll cover a bit of math along the way). Instead, we’re going to start at the
very beginning and talk about how modern games put things on a screen, and then jump
straight into writing shaders to make the things we put on screen look the way we want.
There will be lots of example code, lots of pictures, and by the end of the book we’ll have
gone from the very basics of shader writing to writing shaders that use the same lighting
found in some of the most popular games on the market.
If at the end of the book you decide that you’d like to dive deeper into graphics
programming, and maybe even write your own rendering engine, or dive into more
complicated shader techniques, this book will have provided you with a solid set of
fundamentals to prepare you for tackling more complex subject matter.
Who Should Read This BookThis book is for anyone who wants to learn how to use shader code to create visual
effects for games or real time applications. I’m going to assume that you already know
how to write some simple C++, but that’s all you need. I’ll explain all the math that
we’re going to need (and you’ll be surprised at how little of it there is), and break down
xx
every graphics technique we’ll use, starting from what a 3D mesh is. If your C++ skills
are a bit rusty, that’s OK! Since the focus of the book is on shader development, we’re
not going to be writing much C++ at all, and what little we do write is going to be kept
very simple.
How to Use This BookThe book is divided up into three main sections. Chapters 1-12 are concerned with
teaching shader techniques and introducing new graphics concepts. If you’re a complete
beginner, I recommend starting at Chapter 1 and reading everything in order. Each
chapter will build on the information contained in previous ones, so there’s a chance
you’ll end up lost if you skip too far ahead.
If you already have some amount of shader development knowledge, you might
have more fun skipping ahead to the first chapter that talks about something you haven’t
already learned before. If you hit a concept you don’t understand, the index at the back
of the book should be able to point you to when it was originally introduced, and you can
skip back to there to get caught up.
Chapters 13 to 15 are concerned with debugging and optimizing shader code. If
you’re picking this book up because your project is running at 10 fps and you need to fix
it, it might be worth jumping straight to there and dealing with your immediate problem
before reading the first sections; otherwise you might be a bit frustrated by the relaxed
pace of the early chapters.
Chapters 16 to 18 talk about how to implement the concepts taught in this book in
three of the most popular engines being used today: Unity, Unreal Engine 4, and Godot.
I recommend leaving those until the very end, when you’re ready to apply the concepts
taught in this book to your projects.
Finally, there is an Appendix at the end of the book that has a couple of important
code snippets that are needed for some of the examples in the book. These snippets
aren’t shader code, and as such, aren’t explained in depth by the chapter contents.
If you’re reading this book without an Internet connection, you’ll need to consult
there to follow along with the chapter examples in the later chapters. The chapter text
will tell you when to do this, so don’t worry about it right off the bat, you won’t need this
code until the later chapters of Section 1.
InTroduCTIon
xxi
Example Code ConventionsThe book uses a lot of example code. To make it easier to talk about that code, these
examples are annotated with numbered symbols, like the following:
int main(){
return 0; ❶}
Text referring to this example will refer to the return 0; line as “❶.”
Software RequirementsSince we’ll be using an open source coding framework called openFrameworks—
which uses C++14 by default—your life will be easiest if you have a compiler capable of
supporting C++14. We aren’t going to be using any C++14 features, but the framework
needs them under the hood. Your life will also be easier if you’re using an IDE supported
by openFrameworks. Luckily, there are a lot of them, and you’ll be able to select which
one you want when we get everything set up.
Finally, we’ll be using OpenGL to run all our shaders. OpenGL is a “rendering API,”
which is a fancy term for a set of functions that we can use to communicate with our
graphics card (GPU). There are a lot of different APIs to choose from, but OpenGL has
the advantage of running on the widest range of hardware possible and being well
integrated with openFrameworks. You should make sure that your GPU supports at
least OpenGL version 4.1, which is what this book will assume you’re using. As of OS X
High Sierra, Apple has deprecated OpenGL for their desktop PCs, which means that the
examples in the book may not work if you’re following along on a Mac.
InTroduCTIon