OpenGL 4 Shading Language Cookbook: Acquiring the skills of OpenGL Shading Language is so much easier with this cookbook. You'll be creating graphics rather than learning theory, gaining a high level of capability in modern 3D programming along the way.
By David Wolff
()
About this ebook
OpenGL Shading Language (GLSL) is a programming language used for customizing parts of the OpenGL graphics pipeline that were formerly fixed-function, and are executed directly on the GPU. It provides programmers with unprecedented flexibility for implementing effects and optimizations utilizing the power of modern GPUs. With Version 4, the language has been further refined to provide programmers with greater power and flexibility, with new stages such as tessellation and compute.
OpenGL 4 Shading Language Cookbook provides easy-to-follow examples that first walk you through the theory and background behind each technique, and then go on to provide and explain the GLSL and OpenGL code needed to implement it. Beginner level through to advanced techniques are presented including topics such as texturing, screen-space techniques, lighting, shading, tessellation shaders, geometry shaders, compute shaders, and shadows.
OpenGL Shading Language 4 Cookbook is a practical guide that takes you from the fundamentals of programming with modern GLSL and OpenGL, through to advanced techniques. The recipes build upon each other and take you quickly from novice to advanced level code.
You'll see essential lighting and shading techniques; examples that demonstrate how to make use of textures for a wide variety of effects and as part of other techniques; examples of screen-space techniques including HDR rendering, bloom, and blur; shadowing techniques; tessellation, geometry, and compute shaders; how to use noise effectively; and animation with particle systems.
OpenGL Shading Language 4 Cookbook provides examples of modern shading techniques that can be used as a starting point for programmers to expand upon to produce modern, interactive, 3D computer graphics applications.
Read more from David Wolff
OpenGL 4 Shading Language Cookbook: Build high-quality, real-time 3D graphics with OpenGL 4.6, GLSL 4.6 and C++17, 3rd Edition Rating: 0 out of 5 stars0 ratings
Related to OpenGL 4 Shading Language Cookbook
Related ebooks
OpenGL 4 Shading Language Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsThree.js Cookbook Rating: 0 out of 5 stars0 ratingsBlender 3D: Characters, Machines, and Scenes for Artists Rating: 0 out of 5 stars0 ratingsLua Game Development Cookbook Rating: 0 out of 5 stars0 ratingsOpenCV 3 Computer Vision Application Programming Cookbook: Recipes to make your applications see Rating: 0 out of 5 stars0 ratingsAway3D 3.6 Cookbook Rating: 0 out of 5 stars0 ratingsInkscape 0.48 Illustrator's Cookbook Rating: 0 out of 5 stars0 ratingsOpenCV Computer Vision Application Programming Cookbook Second Edition Rating: 0 out of 5 stars0 ratingsUnity 5.x Cookbook Rating: 0 out of 5 stars0 ratingsDirect3D Rendering Cookbook Rating: 0 out of 5 stars0 ratingsBlender 3D Cookbook Rating: 5 out of 5 stars5/5Data Visualization with D3 4.x Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsCinder Creative Coding Cookbook Rating: 0 out of 5 stars0 ratingsCryENGINE 3 Cookbook: Over 90 recipes written by Crytek developers for creating third-generation real-time games Rating: 0 out of 5 stars0 ratings3D Printing with RepRap Cookbook Rating: 2 out of 5 stars2/5AndEngine for Android Game Development Cookbook Rating: 0 out of 5 stars0 ratingsDart Cookbook Rating: 0 out of 5 stars0 ratingsGephi Cookbook Rating: 0 out of 5 stars0 ratingsCoffeeScript Application Development Cookbook Rating: 0 out of 5 stars0 ratingsQGIS Python Programming Cookbook Rating: 0 out of 5 stars0 ratingsPlayStation Mobile Development Cookbook: Over 65 recipes that will help you create and develop amazing mobile applications! Rating: 0 out of 5 stars0 ratingsIBM Cognos 10 Report Studio Cookbook, Second Edition Rating: 0 out of 5 stars0 ratingsD Cookbook Rating: 0 out of 5 stars0 ratingsUnreal Engine 4 Scripting with C++ Cookbook Rating: 0 out of 5 stars0 ratingsCocos2d-x Cookbook Rating: 0 out of 5 stars0 ratingsUnreal Development Kit Game Design Cookbook Rating: 0 out of 5 stars0 ratingsUnity 5.x Animation Cookbook Rating: 0 out of 5 stars0 ratings
Applications & Software For You
Logic Pro X For Dummies Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5GarageBand For Dummies Rating: 5 out of 5 stars5/5Power OneNote Rating: 4 out of 5 stars4/5Nostalgia and Videogame Music: A Primer of Case Studies, Theories, and Analyses for the Player-Academic Rating: 0 out of 5 stars0 ratingsFL Studio Cookbook Rating: 4 out of 5 stars4/5Adobe Photoshop: A Complete Course and Compendium of Features Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Tableau Your Data!: Fast and Easy Visual Analysis with Tableau Software Rating: 4 out of 5 stars4/5Digital Filmmaking for Beginners A Practical Guide to Video Production Rating: 0 out of 5 stars0 ratingsAdobe Illustrator: A Complete Course and Compendium of Features Rating: 0 out of 5 stars0 ratingsBlender 3D Basics Beginner's Guide Second Edition Rating: 5 out of 5 stars5/5Sound Design for Filmmakers: Film School Sound Rating: 5 out of 5 stars5/5The Most Concise Step-By-Step Guide To ChatGPT Ever Rating: 3 out of 5 stars3/5Adobe Premiere Pro: A Complete Course and Compendium of Features Rating: 5 out of 5 stars5/5Start Your Own Podcast Business: Your Step-By-Step Guide to Success Rating: 5 out of 5 stars5/5Digital Video Production Handbook Rating: 0 out of 5 stars0 ratingsSix Figure Blogging In 3 Months Rating: 3 out of 5 stars3/5Gray Hat Hacking the Ethical Hacker's Rating: 5 out of 5 stars5/5Photoshop For Beginners: Learn Adobe Photoshop cs5 Basics With Tutorials Rating: 0 out of 5 stars0 ratingsDesign for Hackers: Reverse Engineering Beauty Rating: 4 out of 5 stars4/5Adobe After Effects: A Complete Course and Compendium of Features Rating: 5 out of 5 stars5/5iPhone X Hacks, Tips and Tricks: Discover 101 Awesome Tips and Tricks for iPhone XS, XS Max and iPhone X Rating: 3 out of 5 stars3/5Logic Pro For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for OpenGL 4 Shading Language Cookbook
0 ratings0 reviews
Book preview
OpenGL 4 Shading Language Cookbook - David Wolff
Table of Contents
OpenGL 4 Shading Language Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with GLSL
Introduction
The OpenGL Shading Language
Profiles – Core vs. Compatibility
Using a function loader to access the latest OpenGL functionality
Getting ready
How to do it...
How it works...
There's more...
Generating a C++ loader
No-load styles
Using Extensions
See also
Using GLM for mathematics
Getting ready
How to do it...
How it works...
There's more...
Using the GLM types as input to OpenGL
See also
Determining the GLSL and OpenGL version
How to do it...
How it works...
There's more...
See also
Compiling a shader
Getting ready
How to do it...
How it works...
There's more...
Deleting a Shader Object
See also
Linking a shader program
Getting ready
How to do it...
How it works...
There's more...
Deleting a Shader program
See also
Sending data to a shader using vertex attributes and vertex buffer objects
Getting ready
How to do it...
How it works...
There's more...
Separate attribute format
Fragment shader output
Specifying attribute indexes without using layout qualifiers
Using element arrays
Interleaved arrays
Getting a list of active vertex input attributes and locations
Getting ready
How to do it...
How it works...
There's more...
See also
Sending data to a shader using uniform variables
Getting ready
How to do it...
How it works...
There's more...
See also
Getting a list of active uniform variables
Getting ready
How to do it…
How it works...
There's more...
See also
Using uniform blocks and uniform buffer objects
Getting ready
How to do it...
How it works...
There's more...
Using an instance name with a uniform block
Using layout qualifiers with uniform blocks
See also
Getting debug messages
Getting ready
How to do it...
How it works...
There's more...
Building a C++ shader program class
Getting ready
How to do it...
How it works...
See also
2. The Basics of GLSL Shaders
Introduction
Vertex and fragment shaders
Replicating the old fixed functionality
Implementing diffuse, per-vertex shading with a single point light source
Getting ready
How to do it...
How it works...
There's more...
See also
Implementing per-vertex ambient, diffuse, and specular (ADS) shading
Getting ready
How to do it...
How it works...
There's more...
Using a non-local viewer
Per-vertex versus per-fragment
Directional lights
Light attenuation with distance
See also
Using functions in shaders
Getting ready
How to do it...
How it works...
There's more...
The const qualifier
Function overloading
Passing arrays or structures to a function
See also
Implementing two-sided shading
Getting ready
How to do it...
How it works...
There's more...
Using two-sided rendering for debugging
See also
Implementing flat shading
How to do it...
How it works...
See also
Using subroutines to select shader functionality
Getting ready
How to do it...
How it works...
There's more...
See also
Discarding fragments to create a perforated look
Getting ready
How to do it...
How it works...
See also
3. Lighting, Shading, and Optimization
Introduction
Shading with multiple positional lights
Getting ready
How to do it...
How it works...
See also
Shading with a directional light source
Getting ready
How to do it...
How it works...
There's more...
See also
Using per-fragment shading for improved realism
Getting ready
How to do it...
How it works...
There's more...
See also
Using the halfway vector for improved performance
Getting ready
How to do it...
How it works...
There's more...
See also
Simulating a spotlight
Getting ready
How to do it...
How it works...
See also
Creating a cartoon shading effect
Getting ready
How to do it...
How it works...
There's more...
See also
Simulating fog
Getting ready
How to do it...
How it works...
There's more...
Computing distance from the eye
See also
Configuring the depth test
How to do it...
How it works...
See also
4. Using Textures
Introduction
Applying a 2D texture
Getting ready
How to do it...
How it works...
There's more...
Specifying the sampler binding within GLSL
See also
Applying multiple textures
Getting ready
How to do it...
How it works...
There's more...
See also
Using alpha maps to discard pixels
Getting ready
How to do it...
How it works...
There's more...
See also
Using normal maps
Getting ready
How to do it...
How it works...
See also
Simulating reflection with cube maps
Getting ready
How to do it...
How it works...
There's more...
See also
Simulating refraction with cube maps
Getting ready
How to do it...
How it works...
There's more...
The Fresnel equations
Chromatic aberration
Refracting through both sides of the object
See also
Applying a projected texture
Getting ready
How to do it...
How it works...
There's more...
See also
Rendering to a texture
Getting ready
How to do it...
How it works...
There's more...
See also
Using sampler objects
Getting ready
How to do it...
How it works...
See also
5. Image Processing and Screen Space Techniques
Introduction
Applying an edge detection filter
Getting ready
How to do it...
How it works...
There's more...
Optimization techniques
See also
Applying a Gaussian blur filter
Getting ready
How to do it...
How it works...
There's more...
See also
Implementing HDR lighting with tone mapping
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a bloom effect
Getting ready
How to do it...
How it works...
There's more...
See also
Using gamma correction to improve image quality
How to do it...
How it works...
There's more...
Using multisample anti-aliasing
Getting ready
How to do it...
How it works...
There's more...
Using deferred shading
Getting ready
How to do it...
How it works...
There's more...
See also
Implementing order-independent transparency
Getting ready
How to do it...
How it works...
There's more...
See also
6. Using Geometry and Tessellation Shaders
Introduction
The shader pipeline extended
The geometry shader
The tessellation shaders
Point sprites with the geometry shader
Getting ready
How to do it...
How it works...
There's more...
Drawing a wireframe on top of a shaded mesh
Getting ready
How to do it...
How it works...
There's more...
See also…
Drawing silhouette lines using the geometry shader
Getting ready
How to do it...
How it works...
There's more...
See also
Tessellating a curve
Getting ready
How to do it...
How it works...
There's more...
Tessellating a 2D quad
Getting ready
How to do it...
How it works...
See also
Tessellating a 3D surface
Getting ready
How to do it...
How it works...
See also
Tessellating based on depth
Getting ready
How to do it...
How it works...
There's more...
See also
7. Shadows
Introduction
Rendering shadows with shadow maps
Getting ready
How to do it...
How it works...
There's more...
Aliasing
Rendering back faces only for the shadow map
See also
Anti-aliasing shadow edges with PCF
Getting ready
How to do it...
How it works...
There's more...
See also
Creating soft shadow edges with random sampling
Getting ready
How to do it...
How it works...
There's more...
See also
Creating shadows using shadow volumes and the geometry shader
Getting ready
How to do it...
How it works...
There's more...
See also
8. Using Noise in Shaders
Introduction
See Also…
Creating a noise texture using GLM
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a seamless noise texture
Getting ready
How to do it...
How it works...
See also
Creating a cloud-like effect
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a wood-grain effect
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a disintegration effect
Getting ready
How to do it...
How it works...
See also
Creating a paint-spatter effect
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a night-vision effect
Getting ready
How to do it...
How it works...
There's more...
See also
9. Particle Systems and Animation
Introduction
Animating a surface with vertex displacement
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a particle fountain
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a particle system using transform feedback
Getting ready
How to do it...
How it works...
There's more...
Using layout qualifiers
Querying transform feedback results
Recycling particles
See also
Creating a particle system using instanced particles
Getting ready
How to do it...
How it works...
There's more...
See also
Simulating fire with particles
Getting ready
How to do it...
How it works...
There's more...
See also
Simulating smoke with particles
Getting ready
How to do it...
How it works...
See also
10. Using Compute Shaders
Introduction
Compute space and work groups
Executing the Compute Shader
Implementing a particle simulation with the compute shader
Getting ready
How to do it...
How it works...
See also
Using the compute shader for cloth simulation
Getting ready
How to do it...
How it works...
There's more...
See also
Implementing an edge detection filter with the compute shader
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a fractal texture using the compute shader
Getting ready
How to do it...
How it works...
There's more...
Index
OpenGL 4 Shading Language Cookbook Second Edition
OpenGL 4 Shading Language Cookbook Second Edition
Copyright © 2013 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: July 2011
Second edition: December 2013
Production Reference: 1171213
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-702-0
www.packtpub.com
Cover Image by Aniket Sawant (<[email protected]>)
Credits
Author
David Wolff
Reviewers
Bartłomiej Filipek
Thomas Le Guerroué-Drévillon
Muhammad Mobeen Movania
Dario Scarpa
Javed Rabbani Shah
Acquisition Editors
Gregory Wild
Edward Gordon
Usha Iyer
Lead Technical Editor
Neeshma Ramakrishnan
Technical Editors
Kunal Anil Gaikwad
Jinesh Kampani
Aman Preet Singh
Project Coordinator
Shiksha Chaturvedi
Proofreaders
Elinor Perry-Smith
Chris Smith
Indexer
Mariammal Chettiyar
Graphics
Sheetal Aute
Ronak Dhruv
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
About the Author
David Wolff is an associate professor in the Computer Science and Computer Engineering Department at Pacific Lutheran University (PLU). He received a PhD in Physics and an MS in Computer Science from Oregon State University. He has been teaching computer graphics to undergraduates at PLU for over 10 years, using OpenGL.
About the Reviewers
Bartłomiej Filipek is an experienced software developer with a passion for teaching. He has been leading OpenGL and graphics programming courses at Jagiellonian University in Cracow for around five years now. Additionally he gives lectures and workshops about modern C++ techniques at local universities.
His professional experience focuses mostly on native application development including rendering systems, large-scale software development, game engines, multimedia applications, user interfaces, GPU computing, and even biofeedback.
He shares his programming stories at his blog: http://www.bfilipek.com/.
Thomas Le Guerroué-Drévillon is a freshly graduated software engineer. Having a profound interest in mathematics and drawing, it came easily to him to mix together these two passions in one field: computer graphics.
Originally French, he used up all the opportunities given by his university to study and work all around the world. It allowed him to enjoy his first international experience in Estonia, the second in the prestigious KAIST in South Korea, and finally ending up now in Canada.
Even though his university provided the mathematical background, he got his experience with OpenGL and GLSL on his own. He believes that the link between the well documented API and the shader samples is missing. Thus he naturally accepted to review this cookbook, which for him is the material he would have loved to get a hand on when he started developing interests in OpenGL/GLSL.
Dr. Muhammad Mobeen Movania received his PhD degree in Advance Computer Graphics and Visualization from Nanyang Technological University, Singapore. After finishing his PhD, he joined Institute for Infocomm Research, A-Star, Singapore to work on Augmented Reality based Virtual Tryon and Cloth Simulation systems using GPU and OpenGL. Before joining NTU, he was a junior graphics programmer at Data Communication and Control (DCC) Pvt. Ltd., Karachi, Pakistan. He worked on DirectX and OpenGL API for producing real-time interactive tactical simulators and dynamic integrated training simulators. His research interests include GPU-based volumetric rendering techniques, GPU technologies, real-time soft body physics, real-time dynamic shadows, real-time collision detection and response, and hierarchical geometric data structures. He is also the author of the OpenCloth project (http://code.google.com/p/opencloth), which implements various cloth simulation algorithms in OpenGL. His blog (http://mmmovania.blogspot.com) lists a lot of useful graphics tips and tricks. When not involved with computer graphics, he composes music and is an avid squash player.
Dr. Mobeen has published several conference and journal papers on real-time computer graphics and visualization. Recently, he authored a book on OpenGL (OpenGL Development Cookbook by Packt Publishing, published in 2013) which details several applied recipes using modern OpenGL. He has also authored a book chapter in another book (OpenGL Insights by AK Peters/CRC Press, published in 2012).
Dr. Mobeen is currently an Assistant Professor at DHA Suffa University, Karachi, Pakistan where he is busy nurturing young minds to become outstanding programmers and researchers of tomorrow.
I would like to thank almighty ALLAH for bestowing his countless blessings on me and my family. After that, I would like to extend my gratitude towards my family, my parents (Mr. and Mrs. Abdul Aziz Movania), my wife (Tanveer Taji), my sisters (Mrs. Azra Saleem and Mrs. Sajida Shakir), my brothers (Mr. Khalid Movania and Mr. Abdul Majid Movania), all my nephews/nieces and my daughter (Muntaha Movania).
Dario Scarpa has been coding for fun and profit for the last 15 years, and has no intention to stop. Jumping around among IT jobs as developer/sysadmin, amateur video game programming, and CS exams at the University of Salerno (Italy), he also managed to work with Adventure Productions in building Zodiac, a digital delivery platform focused on adventure games. At the time of reviewing this book, he's about to get his Master's degree, with a thesis on computer graphics that got him working intensively with—guess what—OpenGL.
Javed Rabbani Shah received his degree in Electrical Engineering from the University of Engineering and Technology, Lahore, Pakistan in 2004. He started his professional career by joining Delta Indus Systems (now Vision Master Inc.), where he worked with solder paste inspection systems for statistical process control involving technologies such as Image Processing, 3D Machine Vision, and FPGAs. He then joined the Embedded Systems Division of Mentor Graphics in 2007 and got the opportunity to work with the Nucleus+ real-time operating system, USB 2.0 middleware, WebKit, and OpenGL ES 2.0. He spearheaded the effort to integrate OpenGL ES 2.0 features in Mentor's cross-platform Inflexion 3D user interface engine.
He is currently working at Saffron Digital in central London, where he is involved in work related to cross-platform secure video playback, DRM, and UltraViolet technologies.
In his spare time, he likes to learn emerging technologies like OpenGL ES 3.0 and OpenCL.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
Support files, eBooks, discount offers and morehttp://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Preface
The OpenGL Shading Language (GLSL) is now a fundamental and critical part of programming with OpenGL. It provides us with unprecedented flexibility and power by making the formerly fixed-function graphics pipeline programmable. With GLSL, we can leverage the Graphics Processing Unit (GPU) to implement advanced and sophisticated rendering techniques and even do arbitrary computation. With GLSL 4.x, programmers can do more with the GPU than ever before thanks to new shader stages such as tessellation shaders and compute shaders.
In this book, we cover the full spectrum of GLSL programming. Starting with the basics of shading with the vertex and fragment shaders, we take you from simple to advanced techniques. From textures, shadows, and image processing, to noise and particle systems, we cover practical examples to give you the tools you need to leverage GLSL in your projects. We also cover how to use geometry shaders, tessellation shaders, and the very recent addition to GLSL: compute shaders. With these, you can make use of the GPU for a variety of tasks that go beyond just shading. With geometry and tessellation shaders, we can create additional geometry or modify geometry, and with compute shaders we can do arbitrary computation on the GPU.
For those new to GLSL, it's best to read this book in order, starting with Chapter 1. The recipes will walk you through from basic through to advanced techniques. For someone who is more experienced with GLSL, you might find it better to pick out specific recipes and jump directly there. Most recipes are self-contained, but some may refer to other recipes. The introduction to each chapter provides important general information about the topic, so you might want to read through that as well.
GLSL 4.x makes programming with OpenGL even more rewarding and fun. I sincerely hope that you find this book to be useful and that you use these recipes as a starting point in your own projects. I hope that you find programming in OpenGL and GLSL as enjoyable as I do, and that these techniques inspire you to create beautiful graphics.
What this book covers
Chapter 1, Getting Started with GLSL, explains the steps needed to compile, link, and use GLSL shaders within an OpenGL program. It also covers how to send data to shaders using attributes and uniform variables, and the use of the GLM library for mathematics support. Every modern OpenGL program today requires a function loader. In this chapter, we also cover the use of GLLoadGen, a relatively new and easy-to-use OpenGL loader generator.
Chapter 2, The Basics of GLSL Shaders, introduces you to the basics of GLSL programming with per-vertex shading. In this chapter, you see examples of basic shading techniques such as the ADS (ambient, diffuse, and specular) shading algorithm, two-sided shading, and flat shading. It also covers examples of basic GLSL concepts such as functions and subroutines.
Chapter 3, Lighting, Shading, and Optimization, presents more advanced shading techniques, with a focus on the fragment shader. It introduces you to techniques such as spotlights, per-fragment shading, toon shading, fog, and others. We also discuss several simple optimizations to make your shaders run faster.
Chapter 4, Using Textures, provides a general introduction to using textures in GLSL shaders. Textures can be used for a variety of purposes besides simply pasting
an image onto a surface. In this chapter, we cover the basic application of one or more 2D textures, as well as a variety of other techniques including alpha maps, normal maps, cube maps, projected textures, and rendering to a texture. We also cover sampler objects, a relatively new feature that decouples sampling parameters from the texture object itself.
Chapter 5, Image Processing and Screen Space Techniques, explains common techniques for the post-processing of rendered images and some other screen-space techniques. Image post-processing is becoming a crucially important part of modern game engines and other rendering pipelines. This chapter discusses how to implement some of the more common post-processing techniques such as tone mapping, bloom, blur, gamma correction, and edge detection. We also cover some screen-space rendering techniques such as deferred shading, multisample antialiasing, and order-independent transparency.
Chapter 6, Using Geometry and Tessellation Shaders, covers techniques that demonstrate how to use these new and powerful shader stages. After reading this chapter, you should be comfortable with their basic functionality and understand how to use them. We cover techniques such as geometry-shader-generated point sprites, silhouette lines, depth-based tessellation, Bezier surfaces, and more.
Chapter 7, Shadows, introduces basic techniques for producing real-time shadows. This chapter includes recipes for the two most common shadow techniques: shadow maps and shadow volumes. We cover common techniques for antialiasing shadow maps, as well as how to use the geometry shader to help produce shadow volumes.
Chapter 8, Using Noise in Shaders, covers the use of Perlin noise for creating various effects. The first recipe shows you how to create a wide variety of textures containing noise data using GLM (a powerful mathematics library). Then we move on to recipes that use noise textures for creating a number of effects such as wood grain, clouds, disintegration, paint, and static.
Chapter 9, Particle Systems and Animation, focuses on techniques for creating particle systems. We see how to create a particle system to simulate fire, smoke, and water. We also make use of the OpenGL feature called transform feedback, in order to gain additional efficiency by moving the particle updates onto the GPU.
Chapter 10, Using Compute Shaders, introduces you to several techniques that make use of one of the newest features in OpenGL, the compute shader. The compute shader provides us with the ability to do general computation on the GPU within OpenGL. In this chapter, we discuss how to use the compute shader for particle simulations, cloth simulation, edge detection, and the generation of a procedural fractal texture. After reading this chapter, the reader should have a good feel for how to use the compute shader for arbitrary computational tasks.
What you need for this book
The recipes in this book use some of the latest and greatest features in OpenGL 4.x. Therefore, in order to implement them, you'll need graphics hardware (graphics card or onboard GPU) and drivers that support at least OpenGL 4.3. If you're unsure about what version of OpenGL your setup can support, there are a number of utilities available for determining this information. One option is GLview from Realtech VR, available at: http://www.realtech-vr.com/glview/. If you're running Windows or Linux, drivers are readily available for most modern hardware. However, if you're using MacOS X, unfortunately, you may need to wait. As of this writing, the latest version of MacOS X (10.9 Mavericks) only supports OpenGL 4.1.
Once you've verified that you have the required OpenGL drivers, you'll also need the following:
A C++ compiler. On Linux, the GNU Compiler Collection (gcc, g++, and so on) may already be available, and if not, it should be available through your distribution's package manager. On Windows, Microsoft Visual Studio will work fine, but if you don't have a copy, then the MinGW compiler (available from http://mingw.org/) is a good option.
The GLFW library Version 3.0 or later, available from http://www.glfw.org/. This library provides OpenGL context creation, window support, and support for user input events.
The GLM library Version 0.9.4 or later, available from http://glm.g-truc.net/. This provides mathematics support with classes for matrices, vectors, common transformations, noise functions, and much more.
Who this book is for
The primary focus of this book is the OpenGL Shading Language (GLSL). Therefore, we don't spend any time discussing the basics of programming with OpenGL. In this book I assume that the reader has some experience with programming in OpenGL, and understands basic 3D rendering concepts such as model coordinates, view coordinates, clip coordinates, perspective transforms, and the other associated transformations. There's no assumption of any experience with shader programming, however, so if you're new to GLSL, this is a great place to start.
If you're an OpenGL programmer looking to learn about GLSL programming, then this book is for you. Even if you have some shader programming experience, you will very likely find the recipes in this book to be valuable. We cover a range of simple to advanced techniques, using some of the newest features of OpenGL (such as compute shaders and tessellation shaders). So even experienced GLSL programmers, who are looking to learn how to use these new features, may also find this book to be useful.
In short, this book is for programmers who understand the basics of 3D graphics in OpenGL, and are interested in either learning GLSL, or taking advantage of some of the newest features in modern GLSL 4.x.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The number of work groups are determined by the parameters to glDispatchCompute.
A block of code is set as follows:
void main()
{
Color = VertexColor;
gl_Position = RotationMatrix * vec4(VertexPosition,1.0);
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
void main()
{
Color = VertexColor;
gl_Position = RotationMatrix * vec4(VertexPosition,1.0);
}
Any command-line input or output is written as follows:
Active attributes: 1 VertexColor (vec3) 0 VertexPosition (vec3)
New terms and important words are shown in bold.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Full source code for all of the recipes in this text is available on GitHub at: https://github.com/daw42/glslcookbook.
Downloading the color images of this book
We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: http://www.packtpub.com/sites/default/files/downloads/7020OS_Colorimages.pdf
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Getting Started with GLSL
In this chapter, we will cover the following recipes:
Using a function loader to access the latest OpenGL functionality
Using GLM for mathematics
Determining the GLSL and OpenGL version
Compiling a shader
Linking a shader program
Sending data to a shader using vertex attributes and vertex buffer objects
Getting a list of active vertex input attributes and locations
Sending data to a shader using uniform variables
Getting a list of active uniform variables
Using uniform blocks and uniform buffer objects
Getting debug messages
Building a C++ shader program class
Introduction
The OpenGL Shading Language (GLSL) Version 4 brings unprecedented power and flexibility to programmers interested in creating modern, interactive, and graphical programs. It allows us to harness the power of modern Graphics Processing Units (GPUs) in a straightforward way by providing a simple yet powerful language and API. Of course, the first step towards using GLSL is to create a program that utilizes the latest version of the OpenGL API. GLSL programs don't stand on their own; they must be a part of a larger OpenGL program. In this chapter, we will provide some tips and techniques for getting a basic program up and running. First, let's start with some background.
The OpenGL Shading Language
The GLSL is now a fundamental and integral part of the OpenGL API. Going forward, every program written using the OpenGL API will internally utilize one or several GLSL programs. These mini-programs
are often referred to as shader programs. A shader program usually consists of several components called shaders. Each shader executes within a different section of the OpenGL pipeline. Each shader runs on the GPU, and as the name implies, (typically) implement the algorithms related to the lighting and shading effects of an image. However, shaders are capable of doing much more than just implementing a shading algorithm. They are also capable of performing animation, tessellation, or even generalized computation.
Note
The field of study dubbed GPGPU (General Purpose Computing on Graphics Processing Units) is concerned with utilization of GPUs (often using specialized APIs such as CUDA or OpenCL) to perform general purpose computations such as fluid dynamics, molecular dynamics, cryptography, and so on. With compute shaders, introduced in OpenGL 4.3, we can now do GPGPU within OpenGL.
Shader programs are designed for direct execution on the GPU and are executed in parallel. For example, a fragment shader might be executed once for every pixel, with each execution running simultaneously on a separate GPU thread. The number of processors on the graphics card determines how many can be executed at one time. This makes shader programs incredibly efficient, and provides the programmer with a simple API for implementing highly parallel computation.
The computing power available in modern graphics cards is impressive. The following table shows the number of shader processors available for several models in the NVIDIA GeForce series cards (source: http://en.wikipedia.org/wiki/Comparison_of_Nvidia_graphics_processing_units).
Shader programs are intended to replace parts of the OpenGL architecture referred to as the fixed-function pipeline. Prior to OpenGL Version 2.0, the shading algorithm was hard-coded
into the pipeline and had only limited configurability. This default lighting/shading algorithm was a core part of the fixed-function pipeline. When we, as programmers, wanted to implement more advanced or realistic effects, we used various tricks to force the fixed-function pipeline into being more flexible than it really was. The advent of GLSL will help by providing us with the ability to replace this hard-coded
functionality with our own programs written in GLSL, thus giving us a great deal of additional flexibility and power. For more details on the programmable pipeline, see the introduction to Chapter 2, The Basics of GLSL Shaders.
In fact, recent (core) versions of OpenGL not only provide this capability, but they require shader programs as part of every OpenGL program. The old fixed-function pipeline has been deprecated in favor of a new programmable pipeline, a key part of which is the shader program written in GLSL.
Profiles – Core vs. Compatibility
OpenGL Version 3.0 introduced a deprecation model, which allowed for the gradual removal of functions from the OpenGL specification. Functions or features can be marked as deprecated, meaning that they are expected to be removed from a future version of OpenGL. For example, immediate mode rendering using glBegin/glEnd was marked deprecated in version 3.0 and removed in version 3.1.
In order to maintain backwards compatibility, the concept of compatibility profiles was introduced with OpenGL 3.2. A programmer that is writing code intended to be used with a particular version of OpenGL (with older features removed) would use the so-called core profile. Someone who also wanted to maintain compatibility with older functionality could use the compatibility profile.
Note
It may be somewhat confusing that there is also the concept of a forward compatible context, which is distinguished slightly from the concept of a core/compatibility profile. A context that is considered forward compatible basically indicates that all deprecated functionality has been removed. In other words, if a context is forward compatible, it only includes functions that are in the core, but not those that were marked as deprecated. Some window APIs provide the ability to select forward