Tải bản đầy đủ (.pdf) (1,262 trang)

opengl superbible comprehensive tutorial and reference

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (15.11 MB, 1,262 trang )

OpenGL
®
SUPERBIBLE
Fourth Edition
This page intentionally left blank
OpenGL
®
SUPERBIBLE
Fourth Edition
Richard S. Wright, Jr.
Benjamin Lipchak
Nicholas Haemel
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Comprehensive Tutorial and Reference
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 omis-
sions. 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 the United States please contact:
International Sales

Visit us on the Web: www.awprofessional.com
Library of Congress Cataloging-in-Publication Data:
Wright, Richard S., 1965-
OpenGL superbible : comprehensive tutorial and reference / Richard S. Wright, Jr.,
Benjamin Lipchak, Nicholas Haemel. — 4th ed.
p. cm.
Includes bibliographical references.
ISBN 0-321-49882-8 (pbk. : alk. paper) 1. Computer graphics. 2. OpenGL. I. Lipchak,
Benjamin. II. Haemel, Nicholas. III. Title.
T385.W728 2007
006.6'6—dc22
2007012602
Copyright © 2007 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, photo-
copying, recording, or likewise. For information regarding
permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047
Portions of the reference pages in Appendix C are Copyright

© 2003-2004 Silicon Graphics, Inc. and licensed under the
SGI Free Software B License. For details, see
/>Portions of the reference pages in Appendix C are Copyright
© 2003-2005 3Dlabs Inc. Ltd. and may be distributed
subject to the terms and conditions set forth in the Open
Publication License, v 1.0, 8 June 1999. For details, see
/>Portions of the reference pages in Appendix C are Copyright
© 2007 The Khronos Group Inc. and licensed under the
Khronos Free Use License. For details, see
/>Portions of the reference pages in Appendix C are Copyright
© 2005 Addison-Wesley and may be distributed subject to
the terms and conditions set forth in the Open
Publication License, v 1.0, 8 June 1999. For details, see
/>ISBN-13: 978-0-321-49882-3
ISBN-10: 0-321-49882-8
Text printed in the United States on recycled paper at
Edwards Brothers, Ann Arbor, Michigan
First printing June 2007
Editor-in-Chief
Mark Taub
Acquisitions Editor
Debra Williams-Cauley
Development Editor
Songlin Qiu
Technical Reviewers
Paul Martz
Brian Collins
Managing Editor
Gina Kanouse
Senior Project Editor

Lori Lyons
Copy Editor
Cheri Clark
Indexer
Erika Millen
Proofreader
Williams Woods
Publishing
Publishing
Coordinator
Kim Boedigheimer
Interior Designer
Gary Adair
Cover Designer
Alan Clements
Composition
Gloria Schurick
This page intentionally left blank
For my wife LeeAnne. A work at home mom, on whose mighty
shoulders my career stands.
To the memory of Richard S. Wright, Sr.
1 Thessalonians 4:16
Thanks, Dad, for just letting me be a nerd.
—Richard S. Wright Jr.
To my daughter, Felicity. Finally, a labor of love that doesn’t
involve pixels. I can’t wait to meet you!
—Benjamin Lipchak
To my wife, Anna, for her enduring patience and support.
And to my parents for providing me with more LEGOs
than I could get my arms around.

—Nicholas Haemel
This page intentionally left blank
Contents at a Glance
Preface xxvii
About the Authors xxxv
Introduction 1
Part I The Old Testament
1 Introduction to 3D Graphics and OpenGL 9
2 Using OpenGL 33
3 Drawing in Space: Geometric Primitives and Buffers 73
4 Geometric Transformations: The Pipeline 127
5 Color, Materials, and Lighting: The Basics 173
6 More on Colors and Materials 229
7 Imaging with OpenGL 251
8 Texture Mapping: The Basics 303
9 Texture Mapping: Beyond the Basics 341
10 Curves and Surfaces 377
11 It’s All About the Pipeline: Faster Geometry Throughput 421
12 Interactive Graphics 457
13 Occlusion Queries: Why Do More Work Than You Need To? 481
14 Depth Textures and Shadows 495
Part II The New Testament
15 Programmable Pipeline: This Isn’t Your Father’s OpenGL 515
16 Vertex Shading: Do-It-Yourself Transform, Lighting, and Texgen 547
17 Fragment Shading: Empower Your Pixel Processing 567
18 Advanced Buffers 601
Part III The Apocrypha
19 Wiggle: OpenGL on Windows 641
20 OpenGL on MacOS X 685
21 OpenGL on Linux 713

22 OpenGL ES – OpenGL on the Small 735
A Appendix A: Further Reading/References 773
B Appendix B: Glossary 777
C Appendix C: API Reference 783
Index 1141
OpenGL SuperBible, Fourth Editionx
Table of Contents
Preface xxvii
About the Authors xxxv
Introduction 1
What’s New in This Edition 1
How This Book Is Organized 2
Part I: The Old Testament 2
Part II: The New Testament 4
Part III: The Apocrypha 4
Conventions Used in This Book 5
About the Companion Web Site 5
Part I The Old Testament 7
1 Introduction to 3D Graphics and OpenGL 9
A Brief History of Computer Graphics 9
Going Electric 10
Going 3D 11
A Survey of 3D Effects 14
Perspective 14
Color and Shading 15
Light and Shadows 15
Texture Mapping 16
Fog 17
Blending and Transparency 18
Antialiasing 18

Common Uses for 3D Graphics 19
Real-Time 3D 19
Non–Real-Time 3D 22
Shaders 22
Basic 3D Programming Principles 23
Immediate Mode and Retained Mode 23
Coordinate Systems 24
Projections: Getting 3D to 2D 28
Summary 30
Contents xi
2 Using OpenGL 33
What Is OpenGL? 33
Evolution of a Standard 34
The API Wars 36
The Future of OpenGL 37
How Does OpenGL Work? 38
Generic Implementations 38
Hardware Implementations 39
The Pipeline 40
OpenGL: An API, Not a Language 41
Standard Libraries and Headers 41
Some Header Customizations 42
API Specifics 43
Data Types 44
Function-Naming Conventions 45
Platform Independence 46
Using GLUT 47
Your First Program 48
Drawing Shapes with OpenGL 53
Animation with OpenGL and GLUT 61

Double Buffering 64
The OpenGL State Machine 65
Saving and Restoring States 66
OpenGL Errors 67
When Bad Things Happen to Good Code 67
Identifying the Version 68
Getting a Clue with glHint 69
Using Extensions 69
Checking for an Extension 69
Whose Extension Is This? 71
Summary 71
3 Drawing in Space: Geometric Primitives and Buffers 73
Drawing Points in 3D 74
Setting Up a 3D Canvas 74
A 3D Point: The Vertex 76
Draw Something! 77
Drawing Points 78
Our First Example 78
OpenGL SuperBible, Fourth Editionxii
Setting the Point Size 81
Drawing Lines in 3D 85
Line Strips and Loops 87
Approximating Curves with Straight Lines 88
Setting the Line Width 89
Line Stippling 91
Drawing Triangles in 3D 94
Triangles: Your First Polygon 94
Winding 95
Triangle Strips 96
Triangle Fans 97

Building Solid Objects 98
Setting Polygon Colors 101
Hidden Surface Removal 102
Culling: Hiding Surfaces for Performance 104
Polygon Modes 107
Other Primitives 107
Four-Sided Polygons: Quads 108
Quad Strips 108
General Polygons 108
Filling Polygons, or Stippling Revisited 109
Polygon Construction Rules 113
Subdivision and Edges 114
Other Buffer Tricks 117
Using Buffer Targets 117
Manipulating the Depth Buffer 119
Cutting It Out with Scissors 119
Using the Stencil Buffer 121
Creating the Stencil Pattern 122
Summary 126
4 Geometric Transformations: The Pipeline 127
Is This the Dreaded Math Chapter? 127
Understanding Transformations 128
Eye Coordinates 129
Viewing Transformations 130
Modeling Transformations 130
The Modelview Duality 132
Projection Transformations 132
Viewport Transformations 134
Contents xiii
The Matrix: Mathematical Currency for 3D Graphics 134

What Is a Matrix? 134
The Transformation Pipeline 135
The Modelview Matrix 136
The Identity Matrix 140
The Matrix Stacks 142
A Nuclear Example 143
Using Projections 146
Orthographic Projections 147
Perspective Projections 148
A Far-Out Example 151
Advanced Matrix Manipulation 154
Loading a Matrix 156
Performing Your Own Transformations 157
Adding Transformations Together 160
Moving Around in OpenGL Using Cameras and Actors 161
An Actor Frame 161
Euler Angles: “Use the Frame, Luke!” 163
Camera Management 164
Bringing It All Together 165
Summary 171
5 Color, Materials, and Lighting: The Basics 173
What Is Color? 174
Light as a Wave 174
Light as a Particle 175
Your Personal Photon Detector 176
The Computer as a Photon Generator 176
PC Color Hardware 177
PC Display Modes 179
Screen Resolution 179
Color Depth 179

Using Color in OpenGL 180
The Color Cube 180
Setting the Drawing Color 182
Shading 183
Setting the Shading Model 185
OpenGL SuperBible, Fourth Editionxiv
Color in the Real World 186
Ambient Light 187
Diffuse Light 188
Specular Light 188
Putting It All Together 189
Materials in the Real World 190
Material Properties 190
Adding Light to Materials 190
Calculating Ambient Light Effects 190
Diffuse and Specular Effects 191
Adding Light to a Scene 192
Enabling the Lighting 192
Setting Up Cosmic Background Radiation 192
Setting Material Properties 193
Using a Light Source 196
Which Way Is Up? 197
Surface Normals 197
Specifying a Normal 198
Unit Normals 201
Finding a Normal 202
Setting Up a Source 203
Setting the Material Properties 205
Specifying the Polygons 205
Lighting Effects 207

Specular Highlights 207
Specular Light 208
Specular Reflectance 208
Specular Exponent 209
Normal Averaging 211
Putting It All Together 213
Creating a Spotlight 214
Drawing a Spotlight 216
Shadows 221
What Is a Shadow? 222
Squish Code 223
A Shadow Example 223
Sphere World Revisited 227
Summary 227
Contents xv
6 More on Colors and Materials 229
Blending 229
Combining Colors 230
Changing the Blending Equation 234
Antialiasing 234
Multisample 238
Applying Fog 240
Fog Equations 242
Fog Coordinates 244
Accumulation Buffer 244
Other Color Operations 248
Color Masking 248
Color Logical Operations 248
Alpha Testing 249
Dithering 250

Summary 250
7 Imaging with OpenGL 251
Bitmaps 252
Bitmapped Data 253
The Raster Position 256
Pixel Packing 257
Pixmaps 258
Packed Pixel Formats 260
A More Colorful Example 261
Moving Pixels Around 265
Saving Pixels 266
More Fun with Pixels 268
Pixel Zoom 275
Pixel Transfer 277
Pixel Mapping 281
The Imaging “Subset” and Pipeline 283
Color Matrix 288
Color Lookup 289
Proxies 290
Other Operations 291
Convolutions 292
Histogram 297
Minmax Operations 301
Summary 301
OpenGL SuperBible, Fourth Editionxvi
8 Texture Mapping: The Basics 303
Loading Textures 304
Using the Color Buffer 307
Updating Textures 307
Mapping Textures to Geometry 308

Texture Matrix 311
A Simple 2D Example 311
Texture Environment 316
Texture Parameters 318
Basic Filtering 318
Texture Wrap 320
Cartoons with Texture 321
Mipmapping 325
Texture Objects 330
Managing Multiple Textures 331
Summary 339
9 Texture Mapping: Beyond the Basics 341
Secondary Color 341
Anisotropic Filtering 344
Texture Compression 347
Compressing Textures 348
Loading Compressed Textures 349
Texture Coordinate Generation 350
Object Linear Mapping 354
Eye Linear Mapping 355
Sphere Mapping 356
Cube Mapping 357
Multitexture 362
Multiple Texture Coordinates 363
A Multitextured Example 364
Texture Combiners 369
Point Sprites 371
Using Points 372
Texture Application 374
Point Parameters 374

Summary 375
Contents xvii
10 Curves and Surfaces 377
Built-in Surfaces 378
Setting Quadric States 379
Drawing Quadrics 381
Modeling with Quadrics 385
Bézier Curves and Surfaces 388
Parametric Representation 388
Evaluators 391
NURBS 401
From Bézier to B-Splines 402
Knots 402
Creating a NURBS Surface 403
NURBS Properties 404
Defining the Surface 404
Trimming 406
NURBS Curves 409
Tessellation 409
The Tessellator 411
Tessellator Callbacks 412
Specifying Vertex Data 413
Putting It All Together 414
Summary 419
11 It’s All About the Pipeline: Faster Geometry Throughput 421
Display Lists 422
Batch Processing 423
Preprocessed Batches 424
Display List Caveats 426
Converting to Display Lists 426

Vertex Arrays 428
Loading the Geometry 432
Enabling Arrays 432
Where’s the Data? 433
Pull the Data and Draw 434
Indexed Vertex Arrays 435
Vertex Buffer Objects 450
Managing and Using Buffer Objects 450
Back to the Thunderbird! 452
Summary 455
OpenGL SuperBible, Fourth Editionxviii
12 Interactive Graphics 457
Selection 458
Naming Your Primitives 458
Working with Selection Mode 460
The Selection Buffer 461
Picking 464
Hierarchical Picking 466
Feedback 471
The Feedback Buffer 471
Feedback Data 472
Passthrough Markers 473
A Feedback Example 473
Label the Objects for Feedback 473
Step 1: Select the Object 476
Step 2: Get Feedback on the Object 478
Summary 480
13 Occlusion Queries: Why Do More Work Than You Need To? 481
The World Before Occlusion Queries 482
Bounding Boxes 485

Querying the Query Object 490
Best Practices 492
Summary 493
14 Depth Textures and Shadows 495
Be That Light 496
Fit the Scene to the Window 496
No Bells or Whistles, Please 497
A New Kind of Texture 498
Size Matters 499
Draw the Shadows First?! 500
And Then There Was Light 501
Projecting Your Shadow Map: The “Why” 501
Projecting Your Shadow Map: The “How” 503
The Shadow Comparison 505
Two Out of Three Ain’t Bad 509
A Few Words About Polygon Offset 510
Summary 511
Contents xix
Part II The New Testament 513
15 Programmable Pipeline: This Isn’t Your Father’s OpenGL 515
Out with the Old 516
Fixed Vertex Processing 518
Fixed Fragment Processing 520
In with the New 521
Programmable Vertex Shaders 523
Fixed Functionality Glue 524
Programmable Fragment Shaders 525
OpenGL Shading Language: A First Glimpse 526
Managing GLSL Shaders 528
Shader Objects 528

Program Objects 530
Variables 532
Basic Types 532
Structures 534
Arrays 534
Qualifiers 535
Built-In Variables 536
Expressions 537
Operators 537
Array Access 538
Constructors 538
Component Selectors 540
Control Flow 541
Loops 541
if/else 542
discard 542
Functions 542
Summary 545
16 Vertex Shading: Do-It-Yourself Transform, Lighting, and Texgen 547
Getting Your Feet Wet 548
Diffuse Lighting 549
Specular Lighting 551
Improved Specular Lighting 553
Per-Vertex Fog 557
Per-Vertex Point Size 560
OpenGL SuperBible, Fourth Editionxx
Customized Vertex Transformation 561
Vertex Blending 563
Summary 566
17 Fragment Shading: Empower Your Pixel Processing 567

Color Conversion 568
Grayscale 568
Sepia Tone 569
Inversion 570
Heat Signature 571
Per-Fragment Fog 572
Image Processing 574
Blur 575
Sharpen 577
Dilation and Erosion 578
Edge Detection 580
Lighting 582
Diffuse Lighting 582
Multiple Specular Lights 585
Procedural Texture Mapping 587
Checkerboard Texture 588
Beach Ball Texture 592
Toy Ball Texture 595
Summary 600
18 Advanced Buffers 601
Pixel Buffer Objects 601
How to Use PBOs 602
The Benefits of PBOs 603
PBOs in Action 604
Oh, Where Is the Home Where the PBOs Roam? 608
Framebuffer Objects 608
How to Use FBOs 609
Offscreen Rendering 613
Rendering to Textures 615
Multiple Render Targets 619

Floating-Point Textures 622
High Dynamic Range 622
OpenEXR File Format 623
Tone Mapping 626
Contents xxi
Making Your Whites Whiter and Your Brights Brighter 630
Drawing the Scene 630
Bright Pass 633
Gaussian Blur with a Little Help 634
The Sum Is Greater Than Its Parts 636
PBOs Make a Comeback 638
Summary 638
Part III The Apocrypha 639
19 Wiggle: OpenGL on Windows 641
OpenGL Implementations on Windows 642
Generic OpenGL 642
Installable Client Driver 642
Mini-Client Driver 643
Mini-Driver 643
OpenGL on Vista 644
Extended OpenGL 644
Basic Windows Rendering 645
GDI Device Contexts 646
Pixel Formats 647
The OpenGL Rendering Context 654
Putting It All Together 655
Creating the Window 655
Using the OpenGL Rendering Context 660
Other Windows Messages 664
OpenGL and Windows Fonts 666

3D Fonts and Text 666
2D Fonts and Text 669
Full-Screen Rendering 671
Creating a Frameless Window 672
Creating a Full-Screen Window 672
Multithreaded Rendering 675
OpenGL and WGL Extensions 676
Simple Extensions 677
Using New Entrypoints 678
Auto-Magic Extensions 679
WGL Extensions 680
Summary 684
OpenGL SuperBible, Fourth Editionxxii
20 OpenGL on Mac OS X 685
GLUT 686
Setting Up a GLUT Project 686
Application Frameworks 687
Ditching Cocoa 688
OpenGL with Carbon 689
Setting Up for OpenGL 689
Bitmap Fonts 697
OpenGL with Cocoa 699
Creating a Cocoa Program 699
Wiring It All Together 703
Hang on a Second There! 705
Full-Screen Rendering 706
Managing the Display 706
AGL Full-Screen Support 708
Summary 711
21 OpenGL on Linux 713

The Basics 713
Setup 714
Setting Up Mesa 715
Setting Up Hardware Drivers 715
More Setup Details 715
Setting Up GLUT 716
Building OpenGL Apps 716
GLUT 717
GLX—Dealing with the X Windows Interface 718
Displays and X 718
Config Management and Visuals 719
Windows and Render Surfaces 723
Context Management 724
Synchronization 726
GLX Strings 727
The Rest of GLX 727
Putting It All Together 729
Summary 734
Contents xxiii
22 OpenGL ES: OpenGL on the Small 735
OpenGL on a Diet 735
What’s the ES For? 735
A Brief History 736
Which Version Is Right for You? 738
ES 1.0 739
ES 1.1 742
ES 2.0 746
ES SC 752
The ES Environment 754
Application Design Considerations 754

Dealing with a Limited Environment 755
Fixed-Point Math 756
EGL: A New Windowing Environment 757
EGL Displays 758
Creating a Window 759
Context Management 763
Presenting Buffers and Rendering Synchronization 764
More EGL Stuff 765
Negotiating Embedded Environments 766
Popular Operating Systems 766
Embedded Hardware 766
Vendor-Specific Extensions 767
For the Home Gamer 767
Putting OpenGL ES into Action 767
Setting Up the Environment 768
Setting Up OpenGL ES State 769
Rendering 770
Cleaning Up 771
Summary 772
A Further Reading/References 773
Other Good OpenGL Books 773
3D Graphics Books 773
Web Sites 774
OpenGL SuperBible, Fourth Editionxxiv

×