OpenGL
®
Programming Guide
Seventh Edition
T
he OpenGL graphics system is a software interface to graphics
hardware. (“GL” stands for “Graphics Library.”) It allows you to
create interactive programs that produce color images of moving, three-
dimensional objects. With OpenGL, you can control computer-graphics
technology to produce realistic pictures, or ones that depart from reality
in imaginative ways.
The OpenGL Series from Addison-Wesley Professional comprises
tutorial and reference books that help programmers gain a practical
understanding of OpenGL standards, along with the insight needed to
unlock OpenGL’s full potential.
Visit informit.com/opengl for a complete list of available products
OpenGL
®
Series
OpenGL
®
Programming Guide
Seventh Edition
The Official Guide to
Learning OpenGL
®
, Versions 3.0 and 3.1
Dave Shreiner
The Khronos OpenGL ARB Working Group
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and the publisher was
aware of a trademark claim, the designations have been printed with initial capital letters or
in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales, which may include electronic versions and/or custom covers and
content particular to your business, training goals, marketing focus, and branding interests.
For more information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
For sales outside of the U.S., please contact:
International Sales
Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data
Shreiner, Dave.
OpenGL programming guide : the official guide to learning OpenGL, versions 3.0 and 3.1
/ Dave Shreiner; the Khronos OpenGL ARB Working Group — 7th ed.
p. cm.
Includes index.
ISBN 978-0-321-55262-4 (pbk. : alk. paper)
1. Computer graphics. 2. OpenGL. I. Title.
T385.O635 2009
006.6'6—dc22
2009018793
Copyright © 2010 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax (617) 671-3447
ISBN 13: 978-0-321-55262-4
ISBN 10: 0-321-55262-8
Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan.
First printing, July 2009
For my family—Felicity, Max, Sarah, and Scout.
—JLN
For my family—Ellyn, Ricky, and Lucy.
—TRD
To Tom Doeppner and Andy van Dam, who started me along this path.
—MW
For my family—Vicki, Bonnie, Bob, Phantom, Squiggles, Tuxedo, and Toby.
—DRS
In memory of Phil Karlton, Celeste Fowler, and Ben Cheatham.
This page intentionally left blank
vii
Contents
Figures xxi
Tables xxv
Examples xxix
About This Guide xxxv
What This Guide Contains xxxv
What’s New in This Edition xxxviii
What You Should Know Before Reading This Guide xl
How to Obtain the Sample Code xli
Errata xlii
Style Conventions xlii
Distinguishing Deprecated Features xliii
Acknowledgments xlv
1. Introduction to OpenGL 1
What Is OpenGL? 2
A Smidgen of OpenGL Code 5
OpenGL Command Syntax 7
OpenGL as a State Machine 9
OpenGL Rendering Pipeline 10
Display Lists 11
Evaluators 11
Per-Vertex Operations 12
Primitive Assembly 12
viii Contents
Pixel Operations 13
Texture Assembly 13
Rasterization 14
Fragment Operations 14
OpenGL-Related Libraries 14
Include Files 15
GLUT, the OpenGL Utility Toolkit 17
Animation 22
The Refresh That Pauses 23
Motion = Redraw + Swap 24
OpenGL and Its Deprecation Mechanism 27
OpenGL Contexts 27
Accessing OpenGL Functions 29
2. State Management and Drawing Geometric Objects 31
A Drawing Survival Kit 34
Clearing the Window 34
Specifying a Color 37
Forcing Completion of Drawing 38
Coordinate System Survival Kit 40
Describing Points, Lines, and Polygons 42
What Are Points, Lines, and Polygons? 42
Specifying Vertices 46
OpenGL Geometric Drawing Primitives 47
Basic State Management 53
Displaying Points, Lines, and Polygons 55
Point Details 55
Line Details 56
Polygon Details 60
Normal Vectors 68
Vertex Arrays 70
Step 1: Enabling Arrays 72
Step 2: Specifying Data for the Arrays 73
Step 3: Dereferencing and Rendering 77
Restarting Primitives 83
Instanced Drawing 86
Interleaved Arrays 88
Contents ix
Buffer Objects 91
Creating Buffer Objects 92
Making a Buffer Object Active 93
Allocating and Initializing Buffer Objects with Data 93
Updating Data Values in Buffer Objects 96
Copying Data Between Buffer Objects 101
Cleaning Up Buffer Objects 102
Using Buffer Objects with Vertex-Array Data 102
Vertex-Array Objects 104
Attribute Groups 110
Some Hints for Building Polygonal Models of Surfaces 113
An Example: Building an Icosahedron 115
3. Viewing 123
Overview: The Camera Analogy 126
A Simple Example: Drawing a Cube 129
General-Purpose Transformation Commands 134
Viewing and Modeling Transformations 137
Thinking about Transformations 137
Modeling Transformations 140
Viewing Transformations 146
Projection Transformations 152
Perspective Projection 153
Orthographic Projection 156
Viewing Volume Clipping 158
Viewport Transformation 158
Defining the Viewport 159
The Transformed Depth Coordinate 161
Troubleshooting Transformations 162
Manipulating the Matrix Stacks 164
The Modelview Matrix Stack 167
The Projection Matrix Stack 168
Additional Clipping Planes 168
Examples of Composing Several Transformations 172
Building a Solar System 172
Building an Articulated Robot Arm 175
Reversing or Mimicking Transformations 179
x Contents
4. Color 185
Color Perception 186
Computer Color 188
RGBA versus Color-Index Mode 190
RGBA Display Mode 191
Color-Index Display Mode 193
Choosing between RGBA and Color-Index Mode 195
Changing between Display Modes 196
Specifying a Color and a Shading Model 196
Specifying a Color in RGBA Mode 197
Specifying a Color in Color-Index Mode 199
Specifying a Shading Model 200
5. Lighting 203
A Hidden-Surface Removal Survival Kit 205
Real-World and OpenGL Lighting 207
Ambient, Diffuse, Specular, and Emissive Light 208
Material Colors 209
RGB Values for Lights and Materials 209
A Simple Example: Rendering a Lit Sphere 210
Creating Light Sources 214
Color 216
Position and Attenuation 217
Spotlights 219
Multiple Lights 220
Controlling a Light’s Position and Direction 221
Selecting a Lighting Model 227
Global Ambient Light 228
Local or Infinite Viewpoint 229
Two-Sided Lighting 229
Secondary Specular Color 230
Enabling Lighting 231
Defining Material Properties 231
Diffuse and Ambient Reflection 233
Specular Reflection 234
Emission 234
Contents xi
Changing Material Properties 235
Color Material Mode 237
The Mathematics of Lighting 240
Material Emission 241
Scaled Global Ambient Light 242
Contributions from Light Sources 242
Putting It All Together 244
Secondary Specular Color 245
Lighting in Color-Index Mode 246
The Mathematics of Color-Index Mode Lighting 247
6. Blending, Antialiasing, Fog, and Polygon Offset 249
Blending 251
The Source and Destination Factors 252
Enabling Blending 255
Combining Pixels Using Blending Equations 255
Sample Uses of Blending 258
A Blending Example 260
Three-Dimensional Blending with the Depth Buffer 263
Antialiasing 267
Antialiasing Points or Lines 269
Antialiasing Geometric Primitives with Multisampling 275
Antialiasing Polygons 279
Fog 280
Using Fog 281
Fog Equations 284
Point Parameters 291
Polygon Offset 293
7. Display Lists 297
Why Use Display Lists? 298
An Example of Using a Display List 299
Display List Design Philosophy 302
Creating and Executing a Display List 305
Naming and Creating a Display List 306
What’s Stored in a Display List? 307
xii Contents
Executing a Display List 309
Hierarchical Display Lists 310
Managing Display List Indices 311
Executing Multiple Display Lists 312
Managing State Variables with Display Lists 318
Encapsulating Mode Changes 319
8. Drawing Pixels, Bitmaps, Fonts, and Images 321
Bitmaps and Fonts 323
The Current Raster Position 325
Drawing the Bitmap 327
Choosing a Color for the Bitmap 328
Fonts and Display Lists 329
Defining and Using a Complete Font 331
Images 333
Reading, Writing, and Copying Pixel Data 333
Imaging Pipeline 343
Pixel Packing and Unpacking 346
Controlling Pixel-Storage Modes 347
Pixel-Transfer Operations 351
Pixel Mapping 354
Magnifying, Reducing, or Flipping an Image 356
Reading and Drawing Pixel Rectangles 359
The Pixel Rectangle Drawing Process 359
Using Buffer Objects with Pixel Rectangle Data 362
Using Buffer Objects to Transfer Pixel Data 363
Using Buffer Objects to Retrieve Pixel Data 365
Tips for Improving Pixel Drawing Rates 366
Imaging Subset 367
Color Tables 369
Convolutions 374
Color Matrix 382
Histogram 383
Minmax 387
Contents xiii
9. Texture Mapping 389
An Overview and an Example 395
Steps in Texture Mapping 395
A Sample Program 397
Specifying the Texture 400
Texture Proxy 406
Replacing All or Part of a Texture Image 408
One-Dimensional Textures 412
Three-Dimensional Textures 414
Texture Arrays 419
Compressed Texture Images 420
Using a Texture’s Borders 423
Mipmaps: Multiple Levels of Detail 423
Filtering 434
Texture Objects 437
Naming a Texture Object 438
Creating and Using Texture Objects 438
Cleaning Up Texture Objects 441
A Working Set of Resident Textures 442
Texture Functions 444
Assigning Texture Coordinates 448
Computing Appropriate Texture Coordinates 450
Repeating and Clamping Textures 452
Automatic Texture-Coordinate Generation 457
Creating Contours 458
Sphere Map 463
Cube Map Textures 465
Multitexturing 467
Texture Combiner Functions 472
The Interpolation Combiner Function 477
Applying Secondary Color after Texturing 478
Secondary Color When Lighting Is Disabled 478
Secondary Specular Color When Lighting Is Enabled 479
Point Sprites 479
The Texture Matrix Stack 481
xiv Contents
Depth Textures 483
Creating a Shadow Map 483
Generating Texture Coordinates and Rendering 485
10. The Framebuffer 489
Buffers and Their Uses 492
Color Buffers 493
Clearing Buffers 495
Selecting Color Buffers for Writing and Reading 497
Masking Buffers 499
Testing and Operating on Fragments 501
Scissor Test 502
Alpha Test 502
Stencil Test 504
Depth Test 510
Occlusion Query 511
Conditional Rendering 514
Blending, Dithering, and Logical Operations 515
The Accumulation Buffer 518
Motion Blur 520
Depth of Field 520
Soft Shadows 525
Jittering 525
Framebuffer Objects 526
Renderbuffers 529
Copying Pixel Rectangles 539
11. Tessellators and Quadrics 541
Polygon Tessellation 542
Creating a Tessellation Object 544
Tessellation Callback Routines 544
Tessellation Properties 549
Polygon Definition 554
Deleting a Tessellation Object 557
Tessellation Performance Tips 557
Describing GLU Errors 557
Backward Compatibility 558
Contents xv
Quadrics: Rendering Spheres, Cylinders, and Disks 559
Managing Quadrics Objects 560
Controlling Quadrics Attributes 561
Quadrics Primitives 563
12. Evaluators and NURBS 569
Prerequisites 571
Evaluators 572
One-Dimensional Evaluators 572
Two-Dimensional Evaluators 578
Using Evaluators for Textures 584
The GLU NURBS Interface 586
A Simple NURBS Example 587
Managing a NURBS Object 591
Creating a NURBS Curve or Surface 595
Trimming a NURBS Surface 601
13. Selection and Feedback 605
Selection 606
The Basic Steps 607
Creating the Name Stack 608
The Hit Record 610
A Selection Example 611
Picking 614
Hints for Writing a Program That Uses Selection 625
Feedback 627
The Feedback Array 629
Using Markers in Feedback Mode 630
A Feedback Example 630
14. Now That You Know 635
Error Handling 637
Which Version Am I Using? 639
Utility Library Version 641
Window System Extension Versions 641
Extensions to the Standard 641
Extensions to the Standard for Microsoft Windows (WGL) 643
xvi Contents
Cheesy Translucency 644
An Easy Fade Effect 645
Object Selection Using the Back Buffer 646
Cheap Image Transformation 647
Displaying Layers 649
Antialiased Characters 650
Drawing Round Points 653
Interpolating Images 653
Making Decals 653
Drawing Filled, Concave Polygons Using the Stencil Buffer 655
Finding Interference Regions 656
Shadows 658
Hidden-Line Removal 659
Hidden-Line Removal with Polygon Offset 659
Hidden-Line Removal with the Stencil Buffer 660
Texture Mapping Applications 661
Drawing Depth-Buffered Images 662
Dirichlet Domains 662
Life in the Stencil Buffer 664
Alternative Uses for glDrawPixels() and glCopyPixels() 665
15. The OpenGL Shading Language 667
The OpenGL Graphics Pipeline and Programmable Shading 668
Vertex Processing 670
Fragment Processing 671
Using GLSL Shaders 672
A Sample Shader 672
OpenGL / GLSL Interface 673
The OpenGL Shading Language 681
Creating Shaders with GLSL 681
The Starting Point 681
Declaring Variables 682
Aggregate Types 684
Uniform Blocks 692
Specifying Uniform Variables Blocks in Shaders 693
Accessing Uniform Blocks from Your Application 695
Computational Invariance 701
Contents xvii
Statements 702
Functions 706
Using OpenGL State Values in GLSL Programs 707
Accessing Texture Maps in Shaders 707
Shader Preprocessor 711
Preprocessor Directives 712
Macro Definition 712
Preprocessor Conditionals 713
Compiler Control 713
Extension Processing in Shaders 714
Vertex Shader Specifics 715
Transform Feedback 722
Fragment Shader Specifics 727
Rendering to Multiple Output Buffers 729
A. Basics of GLUT: The OpenGL Utility Toolkit 731
Initializing and Creating a Window 732
Handling Window and Input Events 733
Loading the Color Map 735
Initializing and Drawing Three-Dimensional Objects 735
Managing a Background Process 736
Running the Program 737
B. State Variables 739
The Query Commands 740
OpenGL State Variables 743
Current Values and Associated Data 744
Vertex Array Data State (Not Included in
Vertex Array Object State) 746
Vertex Array Object State 746
Transformation 753
Coloring 755
Lighting 756
Rasterization 758
Multisampling 760
Texturing 761
Pixel Operations 768
xviii Contents
Framebuffer Control 771
Framebuffer Object State 772
Renderbuffer Object State 775
Pixels 776
Evaluators 783
Shader Object State 784
Program Object State 785
Query Object State 789
Transform Feedback State 789
Vertex Shader State 791
Hints 791
Implementation-Dependent Values 792
Implementation-Dependent Pixel Depths 800
Miscellaneous 800
C. Homogeneous Coordinates and Transformation Matrices 803
Homogeneous Coordinates 804
Transforming Vertices 804
Transforming Normals 805
Transformation Matrices 805
Translation 806
Scaling 806
Rotation 806
Perspective Projection 807
Orthographic Projection 808
D. OpenGL and Window Systems 809
Accessing New OpenGL Functions 810
GLEW: The OpenGL Extension Wrangler 811
GLX: OpenGL Extension for the X Window System 812
Initialization 813
Controlling Rendering 814
GLX Prototypes 816
AGL: OpenGL Extensions for the Apple Macintosh 819
Initialization 820
Rendering and Contexts 820
Contents xix
Managing an OpenGL Rendering Context 820
On-Screen Rendering 821
Off-Screen Rendering 821
Full-Screen Rendering 821
Swapping Buffers 821
Updating the Rendering Buffers 821
Using an Apple Macintosh Font 822
Error Handling 822
AGL Prototypes 822
WGL: OpenGL Extension for Microsoft
Windows 95/98/NT/ME/2000/XP 824
Initialization 825
Controlling Rendering 825
WGL Prototypes 827
Glossary 831
Index 857
The following appendices are available online at
/>E. Order of Operations
F. Programming Tips
G. OpenGL Invariance
H. Calculating Normal Vectors
I. Built-In OpenGL Shading Language Variables and Functions
J. Floating-Point Formats for Textures, Framebuffers, and Renderbuffers
K. RGTC Compressed Texture Format
L. std140 Uniform Buffer Layout
This page intentionally left blank
xxi
Figures
Figure 1-1 White Rectangle on a Black Background 6
Figure 1-2 Order of Operations 11
Figure 1-3 Double-Buffered Rotating Square 25
Figure 2-1 Coordinate System Defined by w = 50, h = 50 41
Figure 2-2 Two Connected Series of Line Segments 43
Figure 2-3 Valid and Invalid Polygons 44
Figure 2-4 Nonplanar Polygon Transformed to Nonsimple Polygon 45
Figure 2-5 Approximating Curves 46
Figure 2-6 Drawing a Polygon or a Set of Points 47
Figure 2-7 Geometric Primitive Types 49
Figure 2-8 Stippled Lines 58
Figure 2-9 Wide Stippled Lines 58
Figure 2-10 Constructing a Polygon Stipple Pattern 64
Figure 2-11 Stippled Polygons 65
Figure 2-12 Subdividing a Nonconvex Polygon 67
Figure 2-13 Outlined Polygon Drawn Using Edge Flags 68
Figure 2-14 Six Sides, Eight Shared Vertices 71
Figure 2-15 Cube with Numbered Vertices 79
Figure 2-16 Modifying an Undesirable T-Intersection 114
Figure 2-17 Subdividing to Improve a Polygonal Approximation
to a Surface 118
Figure 3-1 The Camera Analogy 127
Figure 3-2 Stages of Vertex Transformation 128
Figure 3-3 Transformed Cube 129
Figure 3-4 Rotating First or Translating First 138
xxii Figures
Figure 3-5 Translating an Object 141
Figure 3-6 Rotating an Object 142
Figure 3-7 Scaling and Reflecting an Object 143
Figure 3-8 Modeling Transformation Example 144
Figure 3-9 Object and Viewpoint at the Origin 147
Figure 3-10 Separating the Viewpoint and the Object 147
Figure 3-11 Default Camera Position 149
Figure 3-12 Using gluLookAt() 150
Figure 3-13 Perspective Viewing Volume Specified by glFrustum() 154
Figure 3-14 Perspective Viewing Volume Specified
by gluPerspective() 155
Figure 3-15 Orthographic Viewing Volume 157
Figure 3-16 Viewport Rectangle 159
Figure 3-17 Mapping the Viewing Volume to the Viewport 160
Figure 3-18 Perspective Projection and Transformed
Depth Coordinates 161
Figure 3-19 Using Trigonometry to Calculate the Field of View 163
Figure 3-20 Modelview and Projection Matrix Stacks 165
Figure 3-21 Pushing and Popping the Matrix Stack 166
Figure 3-22 Additional Clipping Planes and the Viewing Volume 169
Figure 3-23 Clipped Wireframe Sphere 170
Figure 3-24 Planet and Sun 173
Figure 3-25 Robot Arm 176
Figure 3-26 Robot Arm with Fingers 179
Figure 4-1 The Color Cube in Black and White 189
Figure 4-2 RGB Values from the Bitplanes 191
Figure 4-3 Dithering Black and White to Create Gray 193
Figure 4-4 A Color Map 194
Figure 4-5 Using a Color Map to Paint a Picture 194
Figure 5-1 A Lit and an Unlit Sphere 204
Figure 5-2 GL_SPOT_CUTOFF Parameter 219
Figure 6-1 Creating a Nonrectangular Raster Image 260
Figure 6-2 Aliased and Antialiased Lines 267
Figure 6-3 Determining Coverage Values 268
Figure 6-4 Fog-Density Equations 285
Figures xxiii
Figure 6-5 Polygons and Their Depth Slopes 295
Figure 7-1 Stroked Font That Defines the Characters A, E, P, R, S 314
Figure 8-1 Bitmapped F and Its Data 324
Figure 8-2 Bitmap and Its Associated Parameters 327
Figure 8-3 Simplistic Diagram of Pixel Data Flow 334
Figure 8-4 Component Ordering for Some Data Types
and Pixel Formats 340
Figure 8-5 Imaging Pipeline 343
Figure 8-6 glCopyPixels() Pixel Path 344
Figure 8-7 glBitmap() Pixel Path 345
Figure 8-8 glTexImage*(), glTexSubImage*(), and
glGetTexImage() Pixel Paths 345
Figure 8-9 glCopyTexImage*() and
glCopyTexSubImage*() Pixel Paths 346
Figure 8-10 Byte Swap Effect on Byte, Short, and Integer Data 349
Figure 8-11 *SKIP_ROWS, *SKIP_PIXELS, and
*ROW_LENGTH Parameters 350
Figure 8-12 Drawing Pixels with glDrawPixels() 359
Figure 8-13 Reading Pixels with glReadPixels() 361
Figure 8-14 Imaging Subset Operations 368
Figure 8-15 The Pixel Convolution Operation 375
Figure 9-1 Texture-Mapping Process 391
Figure 9-2 Texture-Mapped Squares 397
Figure 9-3 Texture with Subimage Added 409
Figure 9-4 *IMAGE_HEIGHT Pixel-Storage Mode 418
Figure 9-5 *SKIP_IMAGES Pixel-Storage Mode 419
Figure 9-6 Mipmaps 424
Figure 9-7 Using a Mosaic Texture 431
Figure 9-8 Texture Magnification and Minification 435
Figure 9-9 Texture-Map Distortion 451
Figure 9-10 Repeating a Texture 453
Figure 9-11 Comparing GL_REPEAT to GL_MIRRORED_REPEAT 454
Figure 9-12 Clamping a Texture 454
Figure 9-13 Repeating and Clamping a Texture 454
Figure 9-14 Multitexture Processing Pipeline 467
xxiv Figures
Figure 9-15 Comparison of Antialiased Points and Textured
Point Sprites 480
Figure 9-16 Assignment of Texture Coordinates Based on the
Setting of GL_POINT_SPRITE_COORD_ORIGIN 481
Figure 10-1 Region Occupied by a Pixel 490
Figure 10-2 Motion-Blurred Object 521
Figure 10-3 Jittered Viewing Volume for Depth-of-Field Effects 522
Figure 11-1 Contours That Require Tessellation 543
Figure 11-2 Winding Numbers for Sample Contours 551
Figure 11-3 How Winding Rules Define Interiors 552
Figure 12-1 Bézier Curve 573
Figure 12-2 Bézier Surface 580
Figure 12-3 Lit, Shaded Bézier Surface Drawn with a Mesh 583
Figure 12-4 NURBS Surface 588
Figure 12-5 Parametric Trimming Curves 602
Figure 12-6 Trimmed NURBS Surface 603
Figure 14-1 Antialiased Characters 651
Figure 14-2 Concave Polygon 655
Figure 14-3 Dirichlet Domains 663
Figure 14-4 Six Generations from the Game of Life 664
Figure 15-1 Overview of the OpenGL Fixed-Function Pipeline 668
Figure 15-2 Vertex Processing Pipeline 670
Figure 15-3 Fragment Processing Pipeline 671
Figure 15-4 Shader Creation Flowchart 674
Figure 15-5 GLSL Vertex Shader Input and Output Variables 716
Figure 15-6 Fragment Shader Built-In Variables 727