An Introduction To OpenGL Programming
An Introduction To OpenGL Programming
OpenGL'Programming!
Ed#Angel## University!of!New!Mexico#
Dave#Shreiner## ARM,!Inc.#
!
Presented!at!SIGGRAPH!2013!
Sunday,!July!21st,!2013!
Anaheim,!CA,!USA!
# #
Contents#
An Introduction to OpenGL Programming .............................................................. 1
What Is OpenGL? ..................................................................................................... 2
Course Ground Rules ................................................................................................ 3
Evolution of the OpenGL Pipeline ............................................................................. 4
In the Beginning … ................................................................................................... 5
Beginnings of The Programmable Pipeline .............................................................. 6
An Evolutionary Change ........................................................................................... 7
The Exclusively Programmable Pipeline .................................................................. 8
More Programmability .............................................................................................. 9
More Evolution – Context Profiles ........................................................................... 10
The Latest Pipelines .................................................................................................. 11
OpenGL ES and WebGL .......................................................................................... 12
OpenGL Application Development ............................................................................ 13
A Simplified Pipeline Model .................................................................................... 14
OpenGL Programming in a Nutshell ........................................................................ 15
Application Framework Requirements ..................................................................... 16
Simplifying Working with OpenGL ......................................................................... 17
Representing Geometric Objects .............................................................................. 18
OpenGL’s Geometric Primitives .............................................................................. 19
A First Program ........................................................................................................... 20
Our First Program ..................................................................................................... 21
Initializing the Cube’s Data ...................................................................................... 22
Initializing the Cube’s Data (cont’d) ........................................................................ 23
Cube Data .................................................................................................................. 24
Cube Data .................................................................................................................. 25
Generating a Cube Face from Vertices ..................................................................... 26
Generating the Cube from Faces ............................................................................... 27
Vertex Array Objects (VAOs) .................................................................................. 28
VAOs in Code ........................................................................................................... 29
Storing Vertex Attributes .......................................................................................... 30
VBOs in Code ........................................................................................................... 31
Connecting Vertex Shaders with Geometric Data .................................................... 32
Vertex Array Code .................................................................................................... 33
Drawing Geometric Primitives ................................................................................. 34
Shaders and GLSL....................................................................................................... 35
GLSL Data Types ..................................................................................................... 36
Operators ................................................................................................................... 37
Components and Swizzling ....................................................................................... 38
Qualifiers ................................................................................................................... 39
Functions ................................................................................................................... 40
Built-in Variables ...................................................................................................... 41
Simple Vertex Shader for Cube Example ................................................................. 42
The Simplest Fragment Shader ................................................................................. 43
Getting Your Shaders into OpenGL.......................................................................... 44
A Simpler Way.......................................................................................................... 45
Associating Shader Variables and Data .................................................................... 46
Determining Locations After Linking....................................................................... 47
Initializing Uniform Variable Values ....................................................................... 48
Finishing the Cube Program ..................................................................................... 49
Cube Program’s GLUT Callbacks ............................................................................ 50
Vertex Shader Examples ........................................................................................... 51
Transformations........................................................................................................... 52
Camera Analogy ....................................................................................................... 53
Transformations ........................................................................................................ 54
Camera Analogy and Transformations ..................................................................... 55
3D Transformations .................................................................................................. 56
Specifying What You Can See.................................................................................. 57
Specifying What You Can See (cont’d) .................................................................... 58
Specifying What You Can See (cont’d) .................................................................... 59
Viewing Transformations ......................................................................................... 60
Creating the LookAt Matrix ...................................................................................... 61
Translation ................................................................................................................ 62
Scale .......................................................................................................................... 63
Rotation ..................................................................................................................... 64
Rotation (cont’d) ....................................................................................................... 65
Vertex Shader for Rotation of Cube ......................................................................... 66
Vertex Shader for Rotation of Cube (cont’d)............................................................ 67
Vertex Shader for Rotation of Cube (cont’d)............................................................ 68
Sending Angles from Application............................................................................. 69
Lighting ......................................................................................................................... 70
Lighting Principles .................................................................................................... 71
Modified Phong Model ............................................................................................. 72
Surface Normals ........................................................................................................ 73
Material Properties .................................................................................................... 74
Adding Lighting to Cube .......................................................................................... 75
Adding Lighting to Cube .......................................................................................... 76
Adding Lighting to Cube .......................................................................................... 77
Fragment Shaders ........................................................................................................ 78
Fragment Shaders ...................................................................................................... 79
Shader Examples ....................................................................................................... 80
Height Fields ............................................................................................................. 81
Displaying a Height Field ......................................................................................... 82
Time Varying Vertex Shader .................................................................................... 83
Mesh Display ............................................................................................................ 84
Adding Lighting ........................................................................................................ 85
Mesh Shader .............................................................................................................. 86
Mesh Shader (cont’d) ................................................................................................ 87
Shaded Mesh ............................................................................................................. 88
Texture Mapping ......................................................................................................... 89
Texture Mapping ....................................................................................................... 90
Texture Mapping and the OpenGL Pipeline ............................................................. 91
Applying Textures..................................................................................................... 92
Texture Objects ......................................................................................................... 93
Texture Objects (cont'd.) ........................................................................................... 94
Specifying a Texture Image ...................................................................................... 95
Mapping a Texture .................................................................................................... 96
Applying the Texture in the Shader .......................................................................... 97
Applying Texture to Cube......................................................................................... 98
Creating a Texture Image .......................................................................................... 99
Texture Object........................................................................................................... 100
Vertex Shader ............................................................................................................ 101
Fragment Shader ....................................................................................................... 102
Resources ...................................................................................................................... 103
Books ........................................................................................................................ 104
Online Resources ...................................................................................................... 105
SIGGRAPH 2013 An Introduction to OpenGL Programming
1
SIGGRAPH 2013 An Introduction to OpenGL Programming
OpenGL is a library of function calls for doing computer graphics. With it, you
can create interactive applications that render high-quality color images
composed of 2D and 3D geometric objects and images.
2
SIGGRAPH 2013 An Introduction to OpenGL Programming
While OpenGL has been around for over 20 years, a lot of changes have
occurred since it was created. This course concentrates on the latest
versions of OpenGL – version 4.3, although we don’t have time to discuss all
the features available. In these modern versions of OpenGL (which we
define as versions starting with version 3.1), OpenGL applications are
entirely shader based. In fact, most of this course will discuss shaders and
the operations they support.
3
SIGGRAPH 2013 An Introduction to OpenGL Programming
4
SIGGRAPH 2013 An Introduction to OpenGL Programming
The initial version of OpenGL was announced in July of 1994. That version
of OpenGL implemented what’s called a fixed-function pipeline, which means
that all of the operations that OpenGL supported were fully-defined, and an
application could only modify their operation by changing a set of input
values (like colors or positions). The other point of a fixed-function pipeline is
that the order of operations was always the same – that is, you can’t reorder
the sequence operations occur.
This pipeline was the basis of many versions of OpenGL and expanded in
many ways, and is still available for use. However, modern GPUs and their
features have diverged from this pipeline, and support of these previous
versions of OpenGL are for supporting current applications. If you’re
developing a new application, we strongly recommend using the techniques
that we’ll discuss. Those techniques can be more flexible, and will likely
preform better than using one of these early versions of OpenGL since they
can take advantage of the capabilities of recent Graphics Processing Units
(GPUs).
5
SIGGRAPH 2013 An Introduction to OpenGL Programming
While many features and improvements were added into the fixed-function
OpenGL pipeline, designs of GPUs were exposing more features than could
be added into OpenGL. To allow applications to gain access to these new
GPU features, OpenGL version 2.0 officially added programmable shaders
into the graphics pipeline. This version of the pipeline allowed an application
to create small programs, called shaders, that were responsible for
implementing the features required by the application. In the 2.0 version of
the pipeline, two programmable stages were made available:
• vertex shading enabled the application full control over manipulation of the
3D geometry provided by the application
• fragment shading provided the application capabilities for shading pixels
(the terms classically used for determining a pixel’s color).
OpenGL 2.0 also fully supported OpenGL 1.X’s pipeline, allowing the
application to use both version of the pipeline: fixed-function, and
programmable.
6
SIGGRAPH 2013 An Introduction to OpenGL Programming
Until OpenGL 3.0, features have only been added (but never removed) from
OpenGL, providing a lot of application backwards compatibility (up to the use
of extensions). OpenGL version 3.0 introduced the mechanisms for
removing features from OpenGL, called the deprecation model. It defines
how the OpenGL design committee (the OpenGL Architecture Review Board
(ARB) of the Khronos Group) will advertise of which and how functionality is
removed from OpenGL.
You might ask: why remove features from OpenGL? Over the 15 years to
OpenGL 3.0, GPU features and capabilities expanded and some of the
methods used in older versions of OpenGL were not as efficient as modern
methods. While removing them could break support for older applications, it
also simplified and optimized the GPUs allowing better performance.
7
SIGGRAPH 2013 An Introduction to OpenGL Programming
OpenGL version 3.1 was the first version to remove deprecated features, and
break backwards compatibility with previous versions of OpenGL. The
features removed from included the old-style fixed-function pipeline, among
other lesser features.
One major refinement introduced in 3.1 was requiring all data to be placed in
GPU-resident buffer objects, which help reduce the impacts of various
computer system architecture limitations related to GPUs.
While many features were removed from OpenGL 3.1, the OpenGL ARB
realized that to make it easy for application developers to transition their
products, they introduced an OpenGL extensions, GL_ARB_compatibility,
that allowed access to the removed features.
8
SIGGRAPH 2013 An Introduction to OpenGL Programming
Until OpenGL 3.2, the number of shader stages in the OpenGL pipeline
remained the same, with only vertex and fragment shaders being supported.
OpenGL version 3.2 added a new shader stage called geometry shading
which allows the modification (and generation) of geometry within the
OpenGL pipeline.
9
SIGGRAPH 2013 An Introduction to OpenGL Programming
In order to make it easier for developers to choose the set of features they
want to use in their application, OpenGL 3.2 also introduced profiles which
allow further selection of OpenGL contexts.
10
SIGGRAPH 2013 An Introduction to OpenGL Programming
The OpenGL 4.X pipeline added another pair of shaders (which work in
tandem, so we consider it a single stage) for supporting dynamic tessellation
in the GPU. Tessellation control and tessellation evaluation shaders were
added to OpenGL version 4.0.
11
SIGGRAPH 2013 An Introduction to OpenGL Programming
12
SIGGRAPH 2013 An Introduction to OpenGL Programming
13
SIGGRAPH 2013 An Introduction to OpenGL Programming
After all the vertices for a piece of geometry are processed, the rasterizer
determines which pixels in the frame buffer are affected by the geometry, and
for each pixel, the fragment processing stage is employed, where the
fragment shader runs to determine the final color of the pixel.
14
SIGGRAPH 2013 An Introduction to OpenGL Programming
You’ll find that a few techniques for programming with modern OpenGL goes
a long way. In fact, most programs – in terms of OpenGL activity – are very
repetitive. Differences usually occur in how objects are rendered, and that’s
mostly handled in your shaders.
There four steps you’ll use for rendering a geometric object are as follows:
1. First, you’ll load and create OpenGL shader programs from shader source
programs you create
2. Next, you will need to load the data for your objects into OpenGL’s
memory. You do this by creating buffer objects and loading data into
them.
3. Continuing, OpenGL needs to be told how to interpret the data in your
buffer objects and associate that data with variables that you’ll use in your
shaders. We call this shader plumbing.
4. Finally, with your data initialized and shaders set up, you’ll render your
objects
We’ll expand on those steps more through the course, but you’ll find that
most applications will merely iterate through those steps.
15
SIGGRAPH 2013 An Introduction to OpenGL Programming
While OpenGL will take care of filling the pixels in your application’s output
window or image, it has no mechanisms for creating that rendering surface.
Instead, OpenGL relies on the native windowing system of your operating
system to create a window, and make it available for OpenGL to render into.
For each windowing system (like Microsoft Windows, or the X Window
System on Linux [and other Unixes]), there’s a binding library that lets
mediates between OpenGL and the native windowing system.
Since each windowing system has different semantics for creating windows
and binding OpenGL to them, discussing each one is outside of the scope of
this course. Instead, we use an open-source library named freeglut that
abstracts each windowing system’s specifics into a simple library. freeglut is
a derivative of an older implementation called GLUT, and we’ll use those
names interchangeably. GLUT will help us in creating windows, dealing with
user input and input devices, and other window-system activities.
16
SIGGRAPH 2013 An Introduction to OpenGL Programming
Just like window systems, operating systems have different ways of working
with libraries. In some cases, the library you link your application exposes
different functions than the library you execute your program with. Microsoft
Windows is a notable example where you compile your application with
a<.lib library, but use a .dll at runtime for finding function definitions. As
such, your application would generally need to use operating-system specific
methods to access functions. In general, this is troublesome and a lot of
work. Fortunately, another open-source library comes to our aid, GLEW, the
OpenGL Extension Wrangler library. It removes all the complexity of
accessing OpenGL functions, and working with OpenGL extensions. We use
GLEW in our examples to simplify the code. You can find details about
GLEW at its website: http://glew.sourceforge.net<
17
SIGGRAPH 2013 An Introduction to OpenGL Programming
18
SIGGRAPH 2013 An Introduction to OpenGL Programming
Total'Ver,ces'for'n'
OpenGL'Primi,ve' Descrip,on'
Primi,ves'
Render'a'single'point'per'vertex'(points'
GL_POINTS* n'
may'be'larger'than'a'single'pixel)'
Connect'each'pair'of'ver,ces'with'a'
GL_LINES* 2n'
single'line'segment.'
Connect'each'successive'vertex'to'the'
GL_LINE_STRIP* n+1'
previous'one'with'a'line'segment.'
Connect'all'ver,ces'in'a'loop'of'line'
GL_LINE_LOOP* n'
segments.'
Render'a'triangle'for'each'triple'of'
GL_TRIANGLES* 3n'
ver,ces.'
Render'a'triangle'from'the'first'three'
ver,ces'in'the'list,'and'then'create'a'
GL_TRIANGLE_STRIP* n+2'
new'triangle'with'the'last'two'rendered'
ver,ces,'and'the'new'vertex.'
Create'triangles'by'using'the'first'vertex'
GL_TRIANGLE_FAN* in'the'list,'and'pairs'of'successive' n+2'
ver,ces.'
19
SIGGRAPH 2013 An Introduction to OpenGL Programming
20
SIGGRAPH 2013 An Introduction to OpenGL Programming
The next few slides will introduce our first example program, one which
simply displays a cube with different colors at each vertex. We aim for
simplicity in this example, focusing on the OpenGL techniques, and not on
optimal performance.
21
SIGGRAPH 2013 An Introduction to OpenGL Programming
Our cube, like any other cube, has six square faces, each of which we’ll draw
as two triangles. In order to sizes memory arrays to hold the necessary
vertex data, we define the constant NumVertices."
"
Addi&onally,"as"we’ll"see"in"our"first"shader,"the"OpenGL"shading"language,"GLSL,"
has"a"built=in"type"called"vec4,"which"represents"a"vector"of"four"floa&ng=point"
values.""We"define"a"C++"class"for"our"applica&on"that"has"the"same"seman&cs"as"
that"GLSL"type.""Addi&onally,"to"logically"associate"a"type"for"our"data"with"what"we"
intend"to"do"with"it,"we"leverage"C++""typedefs"to"create"aliases"for"colors"and"
posi&ons.<
22
SIGGRAPH 2013 An Introduction to OpenGL Programming
23
SIGGRAPH 2013 An Introduction to OpenGL Programming
In our example we’ll copy the coordinates of our cube model into a VBO for
OpenGL to use. Here we set up an array of eight coordinates for the corners
of a unit cube centered at the origin.
You may be asking yourself: “Why do we have four coordinates for 3D data?”
The answer is that in computer graphics, it’s often useful to include a fourth
coordinate to represent three-dimensional coordinates, as it allows numerous
mathematical techniques that are common operations in graphics to be done
in the same way. In fact, this four-dimensional coordinate has a proper
name, a homogenous coordinate. We could also use a point3 type, i.e.
24
SIGGRAPH 2013 An Introduction to OpenGL Programming
Just like our positional data, we’ll set up a matching set of colors for each of
the model’s vertices, which we’ll later copy into our VBO. Here we set up
eight RGBA colors. In OpenGL, colors are processed in the pipeline as
floating-point values in the range [0.0, 1.0]. Your input data can take any for;
for example, image data from a digital photograph usually has values
between [0, 255]. OpenGL will (if you request it), automatically convert those
values into [0.0, 1.0], a process called normalizing values.
25
SIGGRAPH 2013 An Introduction to OpenGL Programming
26
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here we complete the generation of our cube’s VBO data by specifying the
six faces using index values into our original positions and colors arrays.
It’s worth noting that the order that we choose our vertex indices is important,
as it will affect something called backface culling later.
We’ll see later that instead of creating the cube by copying lots of data, we
can use our original vertex data along with just the indices we passed into
quad() here to accomplish the same effect. That technique is very common,
and something you’ll use a lot. We chose this to introduce the technique in
this manner to simplify the OpenGL concepts for loading VBO data.
27
SIGGRAPH 2013 An Introduction to OpenGL Programming
Similarly to VBOs, vertex array objects (VAOs) encapsulate all of the VBO
data for an object. This allows much easier switching of data when rendering
multiple objects (provided the data’s been set up in multiple VAOs).
The process for initializing a VAO is similar to that of a VBO, except a little
less involved.
1. First, generate a name VAO name by calling glGenVertexArrays()"
2. Next,"make"the"VAO"“current”"by"calling"glBindVertexArray().""Similar"to"
what"was"described"for"VBOs,"you’ll"call"this"every"&me"you"want"to"use"or"
update"the"VBOs"contained"within"this"VAO.<
28
SIGGRAPH 2013 An Introduction to OpenGL Programming
The above sequence calls shows how to create and bind a VAO. Since all
geometric data in OpenGL must be stored in VAOs, you’ll use this code idiom
often.
29
SIGGRAPH 2013 An Introduction to OpenGL Programming
While we’ve talked a lot about VBOs, we haven’t detailed how one goes
about creating them. Vertex buffer objects, like all (memory) objects in
OpenGL (as compared to geometric objects) are created in the same way,
using the same set of functions. In fact, you’ll see that the pattern of calls we
make here are similar to other sequences of calls for doing other OpenGL
operations.
In the case of vertex buffer objects, you’ll do the following sequence of
function calls:
1. Generate a buffer’s name by calling glGenBuffers()<
2. Next, you’ll make that buffer the “current” buffer, which means it’s the
selected buffer for reading or writing data values by calling
glBindBuffer(),"with"a"type"of"GL_ARRAY_BUFFER.""There"are"different"
types"of"buffer"objects,"with"an"array"buffer"being"the"one"used"for"storing"
geometric"data."
3. To initialize a buffer, you’ll call glBufferData(), which will copy data
from your application into the GPU’s memory. You would do the same
operation if you also wanted to update data in the buffer
4. Finally, when it comes time to render using the data in the buffer, you’ll
once again call glBindVertexArray() to make it and its VBOs current
again. In fact, if you have multiple objects, each with their own VAO,
you’ll likely call glBindVertexArray() once per frame for each object.
30
SIGGRAPH 2013 An Introduction to OpenGL Programming
31
SIGGRAPH 2013 An Introduction to OpenGL Programming
The final step in preparing you data for processing by OpenGL (i.e., sending
it down for rendering) is to specify which vertex attributes you’d like issued to
the graphics pipeline. While this might seem superfluous, it allows you to
specify multiple collections of data, and choose which ones you’d like to use
at any given time.
Each of the attributes that we enable must be associated with an “in” variable
of the currently bound vertex shader. You retrieve vertex attribute locations
was retrieved from the compiled shader by calling
glGetAttribLocation().<<We discuss this call in the shader section.
32
SIGGRAPH 2013 An Introduction to OpenGL Programming
#define<BUFFER_OFFSET(<offset<)<<<((GLvoid*)<(offset))
<
33
SIGGRAPH 2013 An Introduction to OpenGL Programming
This is the simplest way of rendering geometry in OpenGL Version 3.1. You
merely need to store you vertex data in sequence, and then
glDrawArrays() takes care of the rest. However, in some cases, this won’t
be the most memory efficient method of doing things. Many geometric
objects share vertices between geometric primitives, and with this method,
you need to replicate the data once for each vertex. We’ll see a more
flexible, in terms of memory storage and access in the next slides.
34
SIGGRAPH 2013 An Introduction to OpenGL Programming
35
SIGGRAPH 2013 An Introduction to OpenGL Programming
As with any programming language, GLSL has types for variables. However,
it includes vector-, and matrix-based types to simplify the operations that
occur often in computer graphics.
In addition to numerical types, other types like texture samplers are used to
enable other OpenGL operations. We’ll discuss texture samplers in the
texture mapping section.
36
SIGGRAPH 2013 An Introduction to OpenGL Programming
The vector and matrix classes of GLSL are first-class types, with arithmetic
and logical operations well defined. This helps simplify your code, and
prevent errors.
Note in the above example, overloading ensures that both a*m and m*a are
defined although they will not in general produce the same result.
37
SIGGRAPH 2013 An Introduction to OpenGL Programming
For GLSL’s vector types, you’ll find that often you may also want to access
components within the vector, as well as operate on all of the vector’s
components at the same time. To support that, vectors and matrices (which
are really a vector of vectors), support normal “C” vector accessing using the
square-bracket notation (e.g., “[i]”), with zero-based indexing. Additionally,
vectors (but not matrices) support swizzling, which provides a very powerful
method for accessing and manipulating vector components.
Swizzles allow components within a vector to be accessed by name. For
example, the first element in a vector – element 0 – can also be referenced
by the names “x”, “s”, and “r”. Why all the names – to clarify their usage. If
you’re working with a color, for example, it may be clearer in the code to use
“r” to represent the red channel, as compared to “x”, which make more sense
as the x-positional coordinate
38
SIGGRAPH 2013 An Introduction to OpenGL Programming
39
SIGGRAPH 2013 An Introduction to OpenGL Programming
40
SIGGRAPH 2013 An Introduction to OpenGL Programming
41
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here’s the simple vertex shader we use in our cube rendering example. It
accepts two vertex attributes as input: the vertex’s position and color, and
does very little processing on them; in fact, it merely copies the input into
some output variables (with gl_Position being implicitly declared). The
results of each vertex shader execution are passed further down the OpenGL
pipeline, and ultimately end their processing in the fragment shader.
42
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here’s the associated fragment shader that we use in our cube example.
While this shader is as simple as they come – merely setting the fragment’s
color to the input color passed in, there’s been a lot of processing to this
point. In particular, every fragment that’s shaded was generated by the
rasterizer, which is a built-in, non-programmable (i.e., you don’t write a
shader to control its operation). What’s magical about this process is that if
the colors across the geometric primitive (for multi-vertex primitives: lines and
triangles) is not the same, the rasterizer will interpolate those colors across
the primitive, passing each iterated value into our color variable.
43
SIGGRAPH 2013 An Introduction to OpenGL Programming
Just a with regular programs, a syntax error from the compilation stage, or a
missing symbol from the linker stage could prevent the successful generation
of an executable program. There are routines for verifying the results of the
compilation and link stages of the compilation process, but are not shown
here. Instead, we’ve provided a routine that makes this process much
simpler, as demonstrated on the next slide.
44
SIGGRAPH 2013 An Introduction to OpenGL Programming
45
SIGGRAPH 2013 An Introduction to OpenGL Programming
Other data that a shader may use in processing may be constant across a
draw call, or even all the drawing calls for a frame. GLSL calls those uniform
varialbes, since their value is uniform across the execution of all shaders for
a single draw call.
Each of the shader’s input data variables (ins and uniforms) needs to be
connected to a data source in the application. We’ve already seen
glGetAttribLocation() for retrieving information for connecting vertex data in a
VBO to shader variable. You will also use the same process for uniform
variables, as we’ll describe shortly.
46
SIGGRAPH 2013 An Introduction to OpenGL Programming
47
SIGGRAPH 2013 An Introduction to OpenGL Programming
You’ve already seen how one associates values with attributes by calling
glVertexAttribPointer(). To specify a uniform’s value, we use one of the
glUniform*() functions. For setting a vector type, you’ll use one of the
glUniform*() variants, and for matrices you’ll use a glUniformMatrix *() form.
48
SIGGRAPH 2013 An Introduction to OpenGL Programming
You’ll find that many OpenGL programs look very similar, particularly simple
examples as we’re showing in class. Above we demonstrate the basic
initialization code for our examples. In our main() routine, you can see our
use of the freeglut and GLEW libraries.
49
SIGGRAPH 2013 An Introduction to OpenGL Programming
50
SIGGRAPH 2013 An Introduction to OpenGL Programming
51
SIGGRAPH 2013 An Introduction to OpenGL Programming
52
SIGGRAPH 2013 An Introduction to OpenGL Programming
53
SIGGRAPH 2013 An Introduction to OpenGL Programming
When we want to draw an geometric object, like a chair for instance, we first
determine all of the vertices that we want to associate with the chair. Next,
we determine how those vertices should be grouped to form geometric
primitives, and the order we’re going to send them to the graphics
subsystem. This process is called modeling. Quite often, we’ll model an
object in its own little 3D coordinate system. When we want to add that
object into the scene we’re developing, we need to determine its world
coordinates. We do this by specifying a modeling transformation, which tells
the system how to move from one coordinate system to another.
54
SIGGRAPH 2013 An Introduction to OpenGL Programming
Note that human vision and a camera lens have cone-shaped viewing
volumes. OpenGL (and almost all computer graphics APIs) describe a
pyramid-shaped viewing volume. Therefore, the computer will “see”
differently from the natural viewpoints, especially along the edges of
viewing volumes. This is particularly pronounced for wide-angle “fish-
eye” camera lenses.
55
SIGGRAPH 2013 An Introduction to OpenGL Programming
56
SIGGRAPH 2013 An Introduction to OpenGL Programming
57
SIGGRAPH 2013 An Introduction to OpenGL Programming
In OpenGL, the default viewing frusta are always configured in the same
manner, which defines the orientation of our clip coordinates. Specifically,
clip coordinates are defined with the “eye” located at the origin, looking down
the –z axis. From there, we define two distances: our near and far clip
distances, which specify the location of our near and far clipping planes. The
viewing volume is then completely by specifying the positions of the
enclosing planes that are parallel to the view direction .
58
SIGGRAPH 2013 An Introduction to OpenGL Programming
The images above show the two types of projection transformations that are
commonly used in computer graphics. The orthographic view preserves
angles, and simulates having the viewer at an infinite distance from the
scene. This mode is commonly used in used in engineering and design
where it’s important to preserve the sizes and angles of objects in relation to
each other. Alternatively, the perspective view mimics the operation of the
eye with objects seeming to shrink in size the farther from the viewer they
are.
The each projection, the matrix that you would need to specify is provided.
In those matrices, the six values for the positions of the left, right, bottom,
top, near and far clipping planes are specified by the first letter of the plane’s
name. The only limitations on the values is for perspective projections,
where the near and far values must be positive and non-zero, with near
greater than far.
59
SIGGRAPH 2013 An Introduction to OpenGL Programming
60
SIGGRAPH 2013 An Introduction to OpenGL Programming
Using the values passed into the LookAt() call, the above matrix generates
the corresponding viewing matrix.
61
SIGGRAPH 2013 An Introduction to OpenGL Programming
62
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here we show the construction of a scale matrix, which is used to change the
shape of space, but not move it (or more precisely, the origin). The above
illustration has a translation to show how space was modified, but a simple
scale matrix will not include such a translation.
63
SIGGRAPH 2013 An Introduction to OpenGL Programming
64
SIGGRAPH 2013 An Introduction to OpenGL Programming
The formula for generating a rotation matrix is a bit more complex that for
scales and translations. Naming the axis of rotation v, we begin by
normalizing v and storing the result in the vector u. From there, we create a
3 × 3 matrix M, which is composed of the sum of three terms.
1. The outer product of the vector u with its transpose ut
2. The difference of the identity matrix, I, with u’s outer product, scaled the
by the cosine of the input angle θ
3. Finally, we scale the matrix S which is composed of the elements of the
rotation matrix.
The complete rotation matrix is formed by composing M as the upper 3 × 3
matrix in R.
65
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here’s an example vertex shader for rotating our cube. We generate the
matrices in the shader (as compared to in the application), based on the
input angle theta. It’s useful to note that we can vectorize numerous
computations. For example, we can generate a vectors of sines and cosines
for the input angle, which we’ll use in further computations.
66
SIGGRAPH 2013 An Introduction to OpenGL Programming
67
SIGGRAPH 2013 An Introduction to OpenGL Programming
We complete our shader here by generating the last rotation matrix, and )
and then use the composition of those matrices to transform the input vertex
position. We also pass-thru the color values by assigning the input color to
an output variable.
68
SIGGRAPH 2013 An Introduction to OpenGL Programming
Finally, we merely need to supply the angle values into our shader through
our uniform plumbing. In this case, we track each of the axes rotation angle,
and store them in a vec3 that matches the angle declaration in the shader.
We also keep track of the uniform’s location so we can easily update its
value.
69
SIGGRAPH 2013 An Introduction to OpenGL Programming
70
SIGGRAPH 2013 An Introduction to OpenGL Programming
OpenGL can use the shade at one vertex to shade an entire polygon
(constant shading) or interpolate the shades at the vertices across the
polygon (smooth shading), the default.
The original lighting model that was supported in hardware and OpenGL was
due to Phong and later modified by Blinn.
SIGGRAPH 2013 An Introduction to OpenGL Programming
The lighting normal tells OpenGL how the object reflects light around a
vertex. If you imagine that there is a small mirror at the vertex, the
lighting normal describes how the mirror is oriented, and consequently
how light is reflected.
SIGGRAPH 2013 An Introduction to OpenGL Programming
75
SIGGRAPH 2013 An Introduction to OpenGL Programming
76
SIGGRAPH 2013 An Introduction to OpenGL Programming
Here we complete our lighting computation. The Phong model, which this
shader is based on, uses various material properties as we described before.
Likewise, each light can contribute to those same properties. The
combination of the material and light properties are represented as our
“product” variables in this shader. The products are merely the component-
wise products of the light and objects same material propreties. These
values are computed in the application and passed into the shader.
In the Phong model, each material product is attenuated by the magnitude of
the various vector products. Starting with the most influential component of
lighting, the diffuse color, we use the dot product of the lighting normal and
light vector, clamping the value if the dot product is negative (which
physically means the light’s behind the object). We continue by computing
the specular component, which is computed as the dot product of the normal
and the half-vector raised to the shininess value. Finally, if the light is behind
the object, we correct the specular contribution.
Finally, we compose the final vertex color as the sum of the computed
ambient, diffuse, and specular colors, and update the transformed vertex
position.
77
SIGGRAPH 2013 An Introduction to OpenGL Programming
78
SIGGRAPH 2013 An Introduction to OpenGL Programming
The final shading stage that OpenGL supports is fragment shading which
allows an application per-pixel-location control over the color that may be
written to that location. Fragments, which are on their way to the framebuffer,
but still need to do some pass some additional processing to become pixels.
However, the computational power available in shading fragments is a great
asset to generating images. In a fragment shader, you can compute lighting
values – similar to what we just discussed in vertex shading – per fragment,
which gives much better results, or add bump mapping, which provides the
illusion of greater surface detail. Likewise, we’ll apply texture maps, which
allow us to increase the detail for our models without increasing the
geometric complexity.
79
SIGGRAPH 2013 An Introduction to OpenGL Programming
80
80
SIGGRAPH 2013 An Introduction to OpenGL Programming
The first simple application we’ll look at is rendering height fields, as you
might do when rendering terrain in an outdoor game or flight simulator.
81
SIGGRAPH 2013 An Introduction to OpenGL Programming
We’d first like to render a wire-frame version of our mesh, which we’ll draw a
individual line loops.
To begin, we build our data set by sampling the function f for a particular time
across the domain of points. From there, we build our array of points to
render. Once we have our data and have loaded into our VBOs we render it
by drawing the individual wireframe quadrilaterals.
There are many ways to render a wireframe surface like this – give some
thought of other methods.
82
SIGGRAPH 2013 An Introduction to OpenGL Programming
83
SIGGRAPH 2013 An Introduction to OpenGL Programming
84
SIGGRAPH 2013 An Introduction to OpenGL Programming
While the wireframe version is of some interest, we can create better looking
meshes by adding a few more effects. We’ll begin by creating a solid mesh
by converting each wireframe quadrilateral into a solid quad composed of
two separate triangles. Turns out with our pervious set of points, we can
merely changed our glDrawArrays()<call – or more specifically, the
geometric primitive type – to render a solid surface.
However, if we don’t do some additional modification of one of our shaders,
we’ll get a large back blob. To produce a more useful rendering, we’ll add
lighting computations into our vertex shader, computing a lighting color for
each vertex, which will be passed to the fragment shader.
85
85
SIGGRAPH 2013 An Introduction to OpenGL Programming
Details of lighting model are not important to here. The model includes the
standard modified Phong diffuse and specular terms without distance.
Note that we do the lighting in eye coordinates and therefore must compute
the eye position in this frame.
All the light and material properties are set in the application and are
available through the OpenGL state.
86
86
SIGGRAPH 2013 An Introduction to OpenGL Programming
87
87
SIGGRAPH 2013 An Introduction to OpenGL Programming
88
SIGGRAPH 2013 An Introduction to OpenGL Programming
89
SIGGRAPH 2013 An Introduction to OpenGL Programming
When you want to map a texture onto a geometric primitive, you need
to provide texture coordinates. Valid texture coordinates are between 0
and 1, for each texture dimension, and usually manifest in shaders as
vertex attributes. We’ll see how to deal with texture coordinates
outside the range [0, 1] in a moment.
SIGGRAPH 2013 An Introduction to OpenGL Programming
Just like vertex attributes were associated with data in the application, so too
with textures. In particular, you access a texture defined in your application
using a texture sampler in your shader. The type of the sampler needs to
match the type of the associated texture. For example, you would use a
sampler2D to work with a two-dimensional texture created with
glTexImage2D( GL_TEXTURE_2D, … );
Within the shader, you use the texture() function to retrieve data values from
the texture associated with your sampler. To the texture() function, you pass
the sampler as well as the texture coordinates where you want to pull the
data from.
Note: the overloaded texture() method was added into GLSL version 3.30.
Prior to that release, there were special texture functions for each type of
texture sampler (e.g., there was a texture2D() call for use with the
sampler2D).
97
SIGGRAPH 2013 An Introduction to OpenGL Programming
Similar to our first cube example, if we want to texture our cube, we need to
provide texture coordinates for use in our shaders. Following our previous
example, we merely add an additional vertex attribute that contains our
texture coordinates. We do this for each of our vertices. We will also need to
update VBOs and shaders to take this new attribute into account.
98
SIGGRAPH 2013 An Introduction to OpenGL Programming
99
SIGGRAPH 2013 An Introduction to OpenGL Programming
100
SIGGRAPH 2013 An Introduction to OpenGL Programming
In order to apply textures to our geometry, we need to modify both the vertex
shader and the pixel shader. Above, we add some simple logic to pass-thru
the texture coordinates from an attribute into data for the rasterizer.
101
SIGGRAPH 2013 An Introduction to OpenGL Programming
Continuing to update our shaders, we add some simple code to modify our
fragment shader to include sampling a texture. How the texture is sampled
(e.g., coordinate wrap modes, texel filtering, etc.) is configured in the
application using the glTexParameter*() call.
102
SIGGRAPH 2013 An Introduction to OpenGL Programming
103
SIGGRAPH 2013 An Introduction to OpenGL Programming
All the above books except Angel and Shreiner, Interactive Computer
Graphics (Addison-Wesley), are in the Addison-Wesley Professional series of
OpenGL books.
104
SIGGRAPH 2013 An Introduction to OpenGL Programming
105
SIGGRAPH 2013 An Introduction to OpenGL Programming
106