Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
OpenGL 4.0 Shading Language Cookbook
OpenGL 4.0 Shading Language Cookbook

OpenGL 4.0 Shading Language Cookbook: With over 60 recipes, this Cookbook will teach you both the elementary and finer points of the OpenGL Shading Language, and get you familiar with the specific features of GLSL 4.0. A totally practical, hands-on guide.

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

OpenGL 4.0 Shading Language Cookbook

Chapter 2. The Basics of GLSL Shaders

In this chapter, we will cover:

  • Implementing diffuse, per-vertex shading with a single point light source

  • Implementing per-vertex ambient, diffuse, and, specular (ADS) shading

  • Using functions in shaders

  • Implementing two sided shading

  • Implementing flat shading

  • Using subroutines to select shader functionality

  • Discarding fragments to create a perforated look

Introduction


Shaders were first introduced into OpenGL in version 2.0, introducing programmability into the formerly fixed-function OpenGL pipeline. Shaders give us the power to implement alternative rendering algorithms and a greater degree of flexibility in the implementation of those techniques. With shaders, we can run custom code directly on the GPU, providing us with the opportunity to leverage the high degree of parallelism available with modern GPUs.

Shaders are implemented using the OpenGL Shading Language (GLSL). The GLSL is syntactically similar to C, which should make it easier for experienced OpenGL programmers to learn. Due to the nature of this text, I won't present a thorough introduction to GLSL here. Instead, if you're new to GLSL, reading through these recipes should help you to learn the language by example. If you are already comfortable with GLSL, but don't have experience with version 4.0, you'll see how to implement these techniques utilizing the newer API. However...

Implementing diffuse, per-vertex shading with a single point light source


One of the simplest shading techniques is to assume that the surface exhibits purely diffuse reflection. That is to say that the surface is one that appears to scatter light in all directions equally, regardless of direction. Incoming light strikes the surface and penetrates slightly before being re-radiated in all directions. Of course, the incoming light interacts with the surface before it is scattered, causing some wavelengths to be fully or partially absorbed and others to be scattered. A typical example of a diffuse surface is a surface that has been painted with a matte paint. The surface has a dull look with no shine at all.

The following image shows a torus rendered with diffuse shading.

The mathematical model for diffuse reflection involves two vectors: the direction from the surface point to the light source (s), and the normal vector at the surface point (n). The vectors are represented in the following diagram...

Implementing per-vertex ambient, diffuse, and specular (ADS) shading


The OpenGL fixed function pipeline implemented a default shading technique which is very similar to the one presented here. It models the light-surface interaction as a combination of three components: ambient, diffuse, and specular. The ambient component is intended to model light that has been reflected so many times that it appears to be emanating uniformly from all directions. The diffuse component was discussed in the previous recipe, and represents omnidirectional reflection. The specular component models the shininess of the surface and represents reflection around a preferred direction. Combining these three components together can model a nice (but limited) variety of surface types. This shading model is also sometimes called the Phong reflection model (or Phong shading model), after Bui Tuong Phong.

An example of a torus rendered with the ADS shading model is shown in the following screenshot:

The ADS model is...

Using functions in shaders


The GLSL supports functions that are syntactically similar to C functions. However, the calling conventions are somewhat different. In this example, we'll revisit the ADS shader using functions to help provide abstractions for the major steps.

Getting ready

As with previous recipes, provide the vertex position at attribute location 0 and the vertex normal at attribute location 1. Uniform variables for all of the ADS coefficients should be set from the OpenGL side, as well as the light position and the standard matrices.

How to do it...

To implement ADS shading using functions, use the following code:

  1. Use the following vertex shader:

    #version 400
    
    layout (location = 0) in vec3 VertexPosition;
    layout (location = 1) in vec3 VertexNormal;
    
    out vec3 LightIntensity;
    
    struct LightInfo {
        vec4 Position; // Light position in eye coords.
        vec3 La;       // Ambient light intensity
        vec3 Ld;       // Diffuse light intensity
        vec3 Ls;       // Specular light intensity...

Implementing two-sided shading


When rendering a mesh that is completely closed, the back faces of polygons are hidden. However, if a mesh contains holes, it might be the case that the back faces would become visible. In this case, the polygons may be shaded incorrectly due to the fact that the normal vector is pointing in the wrong direction. To properly shade those back faces, one needs to invert the normal vector and compute the lighting equations based on the inverted normal.

The following image shows a teapot with the lid removed. On the left, the ADS lighting model is used. On the right, the ADS model is augmented with the two-sided rendering technique discussed in this recipe.

In this recipe, we'll look at an example that uses the ADS model discussed in the previous recipes, augmented with the ability to correctly shade back faces.

Getting ready

The vertex position should be provided in attribute location 0 and the vertex normal in attribute location 1. As in previous examples, the lighting...

Implementing flat shading


Per-vertex shading involves computation of the shading model at each vertex and associating the result (a color) with that vertex. The colors are then interpolated across the face of the polygon to produce a smooth shading effect. This is also referred to as Gouraud shading . In earlier versions of OpenGL, this per-vertex shading with color interpolation was the default shading technique.

It is sometimes desirable to use a single color for each polygon so that there is no variation of color across the face of the polygon, causing each polygon to have a flat appearance. This can be useful in situations where the shape of the object warrants such a technique, perhaps because the faces really are intended to look flat, or to help visualize the locations of the polygons in a complex mesh. Using a single color for each polygon is commonly called flat shading .

The images below show a mesh rendered with the ADS shading model. On the left, Gouraud shading is used. On the...

Using subroutines to select shader functionality


In GLSL, a subroutine is a mechanism for binding a function call to one of a set of possible function definitions based on the value of a variable. In many ways it is similar to function pointers in C. A uniform variable serves as the pointer and is used to invoke the function. The value of this variable can be set from the OpenGL side, thereby binding it to one of a few possible definitions. The subroutine's function definitions need not have the same name, but must have the same number and type of parameters and the same return type.

Subroutines therefore provide a way to select alternate implementations at runtime without swapping shader programs and/or recompiling, or using if statements along with a uniform variable. For example, a single shader could be written to provide several shading algorithms intended for use on different objects within the scene. When rendering the scene, rather than swapping shader programs (or using a conditional...

Discarding fragments to create a perforated look


Fragment shaders can make use of the discard keyword to "throw away" fragments. Use of this keyword causes the fragment shader to stop execution, without writing anything (including depth) to the output buffer. This provides a way to create holes in polygons without using blending. In fact, since fragments are completely discarded, there is no dependence on the order in which objects are drawn, saving us the trouble of doing any depth sorting that might have been necessary if blending was used.

In this recipe, we'll draw a teapot, and use the discard keyword to remove fragments selectively based on texture coordinates. The result will look like the following image:

Getting ready

The vertex position, normal, and texture coordinates must be provided to the vertex shader from the OpenGL application. The position should be provided at location 0, the normal at location 1, and the texture coordinates at location 2. As in previous examples, the lighting...

Left arrow icon Right arrow icon

Key benefits

  • A full set of recipes demonstrating simple and advanced techniques for producing high-quality, real-time 3D graphics using GLSL 4.0
  • How to use the OpenGL Shading Language to implement lighting and shading techniques
  • Use the new features of GLSL 4.0 including tessellation and geometry shaders
  • How to use textures in GLSL as part of a wide variety of techniques from basic texture mapping to deferred shading
  • Simple, easy-to-follow examples with GLSL source code, as well as a basic description of the theory behind each technique

Description

The 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.0, the language has been further refined to provide programmers with greater flexibility, and additional features have been added such as an entirely new stage called the tessellation shader. The OpenGL Shading Language 4.0 Cookbook provides easy-to-follow examples that first walk you through the theory and background behind each technique then go on to provide and explain the GLSL and OpenGL code needed to implement it. Beginning level through to advanced techniques are presented including topics such as texturing, screen-space techniques, lighting, shading, tessellation shaders, geometry shaders, and shadows. The OpenGL Shading Language 4.0 Cookbook is a practical guide that takes you from the basics of programming with GLSL 4.0 and OpenGL 4.0, through basic lighting and shading techniques, to more advanced techniques and effects. It presents techniques for producing basic lighting and shading effects; 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, shadowing, tessellation and geometry shaders, noise, and animation. The OpenGL Shading Language 4.0 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.

Who is this book for?

If you are an OpenGL programmer looking to use the modern features of GLSL 4.0 to create real-time, three-dimensional graphics, then this book is for you. Familiarity with OpenGL programming, along with the typical 3D coordinate systems, projections, and transformations is assumed. It can also be useful for experienced GLSL programmers who are looking to implement the techniques that are presented here.

What you will learn

  • Compile, install, and communicate with shader programs
  • Use new features of GLSL 4.0 such as subroutines and uniform blocks
  • Implement basic lighting and shading techniques such as diffuse and specular shading, per-fragment shading, and spotlights
  • Apply single or multiple textures
  • Use textures as environment maps for simulating reflection or refraction
  • Implement screen-space techniques such as gamma correction, blur filters, and deferred shading
  • Implement geometry and tessellation shaders
  • Learn shadowing techniques including shadow mapping and screen space ambient occlusion
  • Use noise in shaders
  • Use shaders for animation

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2011
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781849514767
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 26, 2011
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781849514767
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 121.97
OpenGL 4.0 Shading Language Cookbook
€41.99
WebGL Beginner's Guide
€37.99
OpenGL Development Cookbook
€41.99
Total 121.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Getting Started with GLSL 4.0 Chevron down icon Chevron up icon
The Basics of GLSL Shaders Chevron down icon Chevron up icon
Lighting, Shading Effects, and Optimizations Chevron down icon Chevron up icon
Using Textures Chevron down icon Chevron up icon
Image Processing and Screen Space Techniques Chevron down icon Chevron up icon
Using Geometry and Tessellation Shaders Chevron down icon Chevron up icon
Shadows Chevron down icon Chevron up icon
Using Noise in Shaders Chevron down icon Chevron up icon
Animation and Particles Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(10 Ratings)
5 star 50%
4 star 40%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Marilee Dec 31, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good book for people familiar with OpenGL but less familiar with the modern versions of OpenGL. This book is particularly useful for OSX users, as OSX requires either the OpenGL 2.1 Compatibility mode or a modern OpenGL 4.1 Core mode. The "Core" version removes a lot of deprecated but useful functions. On the other hand, Linux and Windows programmers tend to have the OpenGL compatibility profile (which allows you to mix and match legacy functions with new ones). I found the examples were well thought out. The chapters build on each other, but each project is useful in its own right, and nicely demonstrates how the chapter's topic can be used in a practical manner. I found this book a great follow-on to Philip Rideout's classic (but slightly dated) iPhone 3D book. Both demonstrate the tools of the trade with artistic and useful examples.
Amazon Verified review Amazon
JamesBedford Jan 09, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really awesome book and incredibly good value. Makes a change to a lot of the really long OpenGL books because you can find the OpenGL nugget you're interested in learning about or using and read the section on that.My only problem with this book is that the formatting for the Table of Contents could be a LOT better for the Kindle version. Whilst all the hyperlinks will take you directly to wherever you need to go, because this book has a set format for each chapter, the sub-sections for each chapter are repeated over and over again which makes it hard to see what the actual chapter is about. For example,Title1ABC2ABC3ABCIt's hard to see the numbers for all the letters!
Amazon Verified review Amazon
Paul T. Miller Oct 01, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers OpenGL Shading Language Core profile 4 and modern OpenGL usage. It does assume some familiarity with OpenGL and C++, which helps to cut down on a lot of introductory boilerplate. It's best to start reading from the beginning, as examples and recipes build on information from previous chapters and Wolff doesn't waste space repeating the same stuff over and over, which I really appreciated.All of the examples use the newer OpenGL APIs, and there is some basic background information on how to use them. I found this useful for people like me who have been using the fixed-function API for so long. The examples also use OpenGL Mathematics (GLM), an Open Source toolkit for working with OpenGL-style vectors and matrices. I had been unaware of this toolkit, and I'll most likely be switching to it for my next project. Wolff's style is short and to the point and keeps things moving along.The meat of the book are the recipes, covering a wide range of shading topics, including emulating the OpenGL 2.0 fixed function pipeline, image processing, soft shadows, synthetic texture generation, and particle systems. There is a lot of information here and it is well written, though it assumes the reader is not a complete novice. Be warned, this is NOT a book for beginners.I had a couple of minor issues with the book. Most of the examples use C++ and the STL but in a few cases Wolff falls back to using malloc/free for temporary buffers. All of the recipes are based on using geometry, and even in the image processing section it is assumed we'll be processing a 3D scene. It would be nice to have some examples focused entirely on doing 2D image processing of images directly.Those points are very minor though and in all I thought the book was exactly what I needed to bring my skills up to the most recent OpenGL and GLSL standards.
Amazon Verified review Amazon
Sol_HSA Nov 25, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got a request from PACKT to review an OpenGL book they've published. It looked like a fun thing to do, so I said okay.First off, this book is perfect for people who already know their way around OpenGL, but may not be too deep into shaders yet, and/or have some legacy bits in their engines.The book does walk you through setting up a shader based application, and explains what kinds of support libraries you're going to need (always managing to pick the "other" lib than the ones I've used - they like glew more than glee, for instance - but the libs they picked still work as advertised, so I'm not saying they're bad choises. Oddly, there's no mention of SDL or SFML though), but knowing how OpenGL generally works as well as how the math generally works is taken for granted.On the positive side you won't have to browse through hundred pages of basic matrix and vector math, or compilation basics, which I feel is a good thing.After the basics the book gets to the fun stuff, explaining lighting, texture use, screen space trickery (like bloom and deferred shading), geometry shaders and tesselation, practical shadows (i.e, shadow mapping and PCT filters, but doesn't waste pages on anything "more advanced"), noise and some particle tricks.All in all I think it's a rather good resource for anyone who wants to upgrade their OpenGL knowledge to more "modern OpenGL", dropping all legacy stuff, but it doesn't mean you don't still have to get your hands on the orange book.
Amazon Verified review Amazon
TechGuyOnAmazon Jan 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found David Wolff's book to be very helpful in learning the foundations of GLSL programming with OpenGL. There are some nice advance techniques covered in this book also. The coding style is good, and the available source code (located on github) was helpful.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.