Interactive computer graphics A TopDown approach with shaderBased OpenGL®, is the only introduction to computer graphics text for undergraduates that fully integrates OpenGL 3.1 and emphasizes applicationbased programming. Using C and C++, the topdown, programmingoriented approach allows for coverage of engaging 3D material early in the text so readers immediately begin to create their own 3D graphics.
Trang 1Interactive Computer Graphics
FIFTH EDITION
Trang 2To Rose Mary
Trang 4viii Con t e nts
1.7.5 Cl i p p i n g and Primitive Assembly 3 2
1.7.6 Rast e r i z ati on3 3 1.7.7 F r a g men t Processing 33
2.3.3 Th e OpenGL Interface 49
2.4 Pr i m i t ives and Attributes 5 0
2.4.1 Pol y gon Basics 5 2
2.4.2 Pol y gon Types inOpenGL 53 2.4.3 A p p r o x i m ati n g aSphere 55
2.4.4 T ext5 6
2.4.5 Cu r vedObjects 58 2.4.6 A t t r i b u tes5 8
2.7.1 I n te ract i o nwith the Window System 7 1
2.7.2 Asp e ct Ratio and Viewports 72
2.7.3 Th e main, display, andmyinit Functions 742.7.4 Pr o g ram Structure 7 5
Trang 5Contents IX
2.10 T he Three-Dimensional Gasket
2.10.1 U s eof Three-Dimensional Points 8 0
2.10.2 U s e of Polygons inThree Dimensions
2.10.3 H i dde n -Su rface Removal 8 3
3.4.1 Def i n i t i o n and Executionof Display Lists 1 10
3.4.2 Tex t and Display Lists 112
3.8.1 Pi c k i n g and Selection Mode 127
3.9 A Simple CAD Program
142
147
Trang 63.13.1 D r awing Erasable Lines 15 0
3.13.2 XOR and Color 1533.13.3 Cur s o rsandOverlay Planes 1 53
Summary and Notes 154 SuggestedReadings 1 5 5
Exercises 155
TC H A P T E R 4 ^GEOMETRIC OBJECTS AND TRANSFORMATIONS T 59
4.1.1 Geom e t r i c Objects 16 0
4.1.2 Co or d i n ate-F r ee Geometry 161
4.1.3 Th e Mathematical View:Vectorand Affine Spaces 162
4.1.4 Th e Computer Science View 1 634.1.5 Ge om e t r i cADTs 1 63
4.1.6 L i n es1 65 4.1.7 A f f i n eSums 16 5
4.1.8 Con v e x i ty1 66 4.1.9 D o tand CrossProducts 1 664.1.10 Pla n es1 67
4.2 T h r ee-D ime nsional Primitives 16 84.3 Co or d i n ate Systems and Frames 170
4.3.1 Re pres en t ati o nsand N-Tuples 1 7 2
4.3.2 Ch a nge ofCoordinate Systems 172 4.3.3 E x a mp le Change of Representation 1 7 5
4.3.4 H o mogen e o us Coordinates 176 4.3.5 E x a mp le Change in Frames 179
Trang 74.10.1 TheCurrent Transformation Matrix 2 15
4.10.2 Rotati o n ,Translation, and Scaling 2 1 6
4.10.3 Rotatio n About a Fixed Point in OpenGL 2 17
4.12.1 Com ple x Numbers andQuaternions 2 26
4.12r2 Quater n io nsand Rotation 2 2 8
Summary and Notes 2 30
242
Trang 8xii Con t e nts
5.3.1 Posi t i o n i n g of the Camera Frame 24 4
5.3.2 T w oViewing APIs 249 5.3.3 T h e Look-At Function 2 5 2
5.3.4 Oth e r Viewing APIs 253
5.4.1 Per s p ecti v e Projections 254 5.4.2 O r t ho gon a l Projections 2 575.5 Pr oje cti o ns in OpenGL 258
5.5.1 P er s p ecti v e inOpenGL 259
5.5.2 P ar a l l e l Viewing inOpenGL 261
5.6.1 Cu l l i ng2 64 5.7 I n te ract i v e Mesh Displays 264 5.7.1 M e s hes2 6 4
5.7.3 P o l y gon Offset 2 6 8
5.8 Par a l l e l-P roje cti o n Matrices 269 5.8.1 P r oje cti o n Normalization 270
5.8.2 O r t hogon a l - P roj e cti o n Matrices 271 5.8.3 O b l i q ue Projections 27 3
5.9 P e r s pect i v e -P roje cti o n Matrices 27 6 5.9.1 P e r spe cti v e Normalization 276
5.9.2 O p e nGL Perspective Transformations 2 8 0
5.10 P roj e cti o ns and Shadows 2 81
Summary and Notes 284
SuggestedReadings 2 85Exercises 28 5
6.2.1 Col o r Sources 2 946.2.2 A m b i e nt Light 2 9 5 |
Trang 97.6.1 bou n d i n g Boxes and Volumes 3 44
7.6.2 Cu r ves, Surfaces, and Text 34 5
7.6.3 C l i p p i n g inthe Frame Buffer 3 45
7.7 Cl i p p ing in Three Dimensions 346
Trang 1053V Contents
7.10 P o l ygon Rasterization
7.10.1 I n s i d e -Ou tsi d e Testing 354 7.10.2 Ope n GL and ConcavePolygons 3 5 5
7.10.3 F il landSort 3 5 6
7.10.4 Fl o odFill 357 7.10.5 Si n gu l a r i t i es3 57 7.11 H i d den - S u r f a ce Removal
7.11.1 Object - Spaceand Image-Space Approaches
7.11.2 Sor ting and Hidden-Surface Removal 360
7.11 3 Scan L i n eAlgorithms 360
7.11 4 B a c k-Fac eRemoval 3 6 1
7.11.5 Thez-Buffer Algorithm 3 6 2
7.11.6 Scan Conversion with the z-Buffer 3 6 5
7.11.7 Depth Sort and the Painter'sAlgorithm 3 677.12 A n t ial i a s i ng
7.13 Di s p lay Considerations
7.13.2 Th e Color Matrix 375
7.13.3 Gam m a Correction 376 7.13.4 Dith e r ing and Halftoning 3 7 6
Summary and Notes 377 SuggestedReadings 3 79Exercises 37 9
8.3.2 W r i t eswithXOR 391
8.4 B i t and Pixel Operations in OpenGL
8.4.1 Open G L Buffers and the Pixel Pipeline 3 9 2
8.4.2 Bi t ma ps3 9 4
8.4.3 Rast e r Fonts 3 95
8.4.4 Pi x e l s and Images 396
8.4.5 L o o kup Tables 3 978.5 E x a m p les
Trang 118.11.3 Ble n ding and Compositing in OpenGL 4 2 9
8.11.4 An tiali asing Revisited 43 1
8.11.5 B a c k-to-F r o ntand Front-to-Back Rendering 432
8.11.6 Depth Cueing and Fog 43 3
8.13.3 Qua n tiza tion 4 4 6
Summary and Notes 4 47
Trang 129.7.1 S ca li n g Vertex Positions 47 0
9.7.2 M o r p h i n g 4729.7.3 Par t i c l e Systems 474
9.8.1 P h o ngLighting 4 759.8.2 N o n p hotor e a li s t i c Shading 478
Trang 13Contents xvu
10.7 G r a p h ical Objects
10.7.2 ACube Object 5 2 1
10.7.3 Implem e nting the Cube Object 5 2 3
10.7.4 Object sand Hierarchy 5 24
10.7.5 Geom e tri c Objects 525
10.8 S c en e Graphs
10.9 ASimple Scene GraphAPI
10.9.1 The Node Class 528
10.9 2 Geom e try Nodes 530
10.9.3 Ca m e ra Class 532
10.9.4 Lights and Materials 533
10.9.5 Tr a ns fo rm a tio ns5 35
10.9 6 The Robot Figure 5 3 5
10.9.7 I m ple men ti n g the Viewer 537
10.9.8 Imple m e nting a Node 541
10.10 Open SceneGraph
10.11 Graphics and the Internet
10.11 1 Networks and Protocols 546
10.11 2 Hypermedia and HTML 547
10.11 3 Databases and VRML 54 8
10.11.4 Javaand Applets 54 9
10.12 Other Tree Structures
10.12.1CSG Trees 5 5 0
10.12.2 BSPTrees 551
10.12.3Quadtrees and Octrees 5 54
Summary and Notes 555
Trang 14xviii Con t e nts
11.5 1 Colli s io ns5 71 11.5.2 Soft Constraints 573
11.6.1 D isplaying the Particles 57 4
11.6.2 Updati n g Particle Positions 575 11.6.3 In itiali za tion 5 7 5
11.6.4 Colli s io ns5 76 11.6.5 F o r ces5 77
11.6.6Flocki ng5 77 11.7 L a ngu a ge-Ba s ed Models 578
11.8 1 R u l e r s and Length 582
11.8.2 F r actal Dimension 5 8311.8.3 Midpoi n t Divisionand Brownian Motion 5 8411.8.4 F r actal Mountains 5 8 5
11.8.5 TheMandelbrot Set 5 8 6
Summary and Notes 5 94Suggested Readings 5 94Exercises 595
12.1 R e p resen t ati o n of Curves and Surfaces 597
12.1 1 E x plicit Representation 597 12.1.2 I m plicit Representations 599
12.1.3 Par a metri cForm 6 0 0
12.1.4 Par a metri c Polynomial Curves 601
12.1.5 P ar a metri c Polynomial Surfaces 602
12.3 P a r a me t ri c Cubic Polynomial Curves 6 04 12.4 I n te rpol a t ion 6 0512.4.1 B le nding Functions 607
12.4.2 Th e Cubic Interpolating Patch 609
12.5 H e r m ite Curves and Surfaces 611
12.5.1The Hermite Form 6 1 1
12.5.2 Geom e tri c and Parametric Continuity 6 1 3
Trang 15Contents xi x
12.6 2 Bezier Surface Patches 6 17
12.7 1 The Cubic B-Spline Curve 618
12.7.2 B - Splines and Basis 6 2 1
12.9.1 Polyn o m ial Evaluation Methods 629
12.9 2 R e c u rsiv e Subdivision of Bezier Polynomials 630
12.9 3 Re n de ring Other Polynomial Curves by Subdivision 63 3
12.9.4Subdivi s io n of Bezier Surfaces 634
12.11.1 Quadrics 6 38
12.11.2 Rendering of Surfaces by Ray Casting 639
12.11.3Subdivision Curves and Surfaces 640
i';\342\200\242\342\200\242\342\200\242'\342\200\242;Jfer* r;i'\"%^fr-' \302\245f:;,\342\200\242
Trang 1613.5.3Co m puting Form Factors 6 69
13.5.4Ca r rying Out Radiosity 6 72
13.7.2 Sor t-L as t Rendering 677 13.7.3 Sor t-Fi r stRendering 6 80
Trang 17780 781
782
783 784 785 786
786 788 788
Trang 19This
book is an introduction tocomputergraphics, with an emphasis on
appli-cations programming In the first e dition,which was published in 1997,1 noted
that in theseven years sincemy previousgraphicstext, thefieldh adexperienced
enor-mous growth\342\200\224arate of growth that exceededmost people'sexpectations, including
my own.In the 11 years (andfour editions) since, we haveseeneven more changes.
Feature-length computer-animated movieshave p roved tobecommercialand
artis-tic successes Theuse ofcom puter effects inmovies is standard, and itisoften almost
impossibletodistinguish live action from computer-generated effects Recent
hard-ware has blurred the distinction between computers and game boxes.Programmable
graphics processors provide alevelofflexibility in commodity systems that wasnot
available in even themost expensiveworkstations just afewyears ago.
Not only have graphics capabilities increased,but costs have been reduced for
both high- and low-endworkstations Within the last fewyears,th e cost ofa
graph-ics system th atcan generate over 100million three-dimensional polygons per second
with lighting and texture mapping has gonefrom over $100,000 to lesstha n $1000.
The availability ofc ommoditygraphicsboardsfor personalcomputers hasbeen
espe-cially significant These boards provide support for sophisticated three-dimensional
applications, starting at about $100 Onthe software side, OpenGL remainsthe
stan-dard programmer's interface both for writing application programs and developing
high-level products formultiplatform applications. OpenGL supports applications
ranging from large scientific visualizations tocellphon e games.
A Top-Down Approach
Theserecent advances and the successofthe first four editions continue to reinforce
my belief in atop-down, programming-oriented approach tointroductory computer
sup-port more than onecoursein the subject, most studentswill take only asinglecourse.
Such a course is placedin the curriculum after students havealready studied
pro-gramming, datastructures, algorithms, software engineering, andbasicmathematics.
A class in computer graphics allows the instructor tobuild on these topics in away
that can be bothinformative and fun. I want thesestudents to be programming
three-dimensional applications as soon aspossible.Low-levelalgorithms, such as those that
draw lines orfillp olygons,can bedealtwithlater, after students arecreatinggraphics
John Kemeny, a pioneer in computer education, used afamiliar automobile
analogy: You don't have toknow what's under the hood to beliterate, but unless
XXUl
Trang 20xxiv Pr e f ace
you know how to program, you'll be sitting in the back seatinstead of driving. Thatsameanalogy applies to the way we teach computer graphics Oneapproach\342\200\224the
algorithmic approach\342\200\224is to teach everything about what makes acar function: the
engine, the transmission, the combustion process A second approach\342\200\224the survey
approach\342\200\224is to hire achauffeur, sit back, and seethe world asaspectator.Thethird approach\342\200\224the programming approach that I have adopted here\342\200\224is to teach youhowto drive and howto take yourselfwherever you want to go Asthe old auto-rental
commercial used tosay, \"Let us put youin the driver's seat.\"
Programming with OpenGL and C
When I began teaching computer graphics 25 years ago, the greatest impediment to
implementing a programming-oriented course, and to writing a textbook for thatcourse, wasthe lack of awidely accepted graphics library or application program-
mer's interface (API).Difficulties included high cost, limi tedavailability, lack ofgen
-erality, and high complexity.Thedevelopment of OpenGL resolved most ofthe
with thealternative of using home-brewed software.OpenGLtoday is supported on
all platforms It isbundled with Microsoft Windows and the Apple Macintosh
Op-erating System Driversareavailable for virtually allgraphicscards Thereisalso an
OpenGL API calledMesathat is included with most Linux distributions Versions ofOpenGL now exist for embedded systemsand are leading to itsusefor hand-held
devices.
Agraphics classteachesfarmorethan theuse of aparticular API,but a good APImakes it easier to teach key graphics topics,including three-dimensional graphics,
lighting and shading, client-server graphics, modeling, and implementation
algo-rithms. Ibelievethat OpenGL's extensive capabilities and well-defined architecture
lead to astronger foundation for teaching both theoretical and practical aspects of
thefieldan d for teaching advancedconcepts,including texture mapping, ing,and programmable shaders.
composit-Iswitchedmy classes toOpenGLabout 15 years ago, and the results astounded
me Bythemiddleofthesemester, everystudent was ableto write a moderately plexthree-dimensional program that required understanding of three-dimensional
com-viewing and event-driven input In my previous years ofteaching computer
graph-ics, Ihad nevercomeeven closeto this result. That classled me torewrite my previous
book from scratch
Thisbook is atextbook on computer graphics; it isnot an OpenGL manual.Consequendy, I donot cover all aspects ofthe OpenGL API but rather explain only
what is necessary for mastering this book's contents I present OpenGLat a level
that should permit users ofother APIs tohavelitd e difficulty with the material For
students who want more detailon OpenGL,my recentbookOpenGL:A Primer, ThirdEdition, (Addison-Wesley 2008) should be avaluable supplement.
In this edition, I useboth C and C++, with C as the dominant language. There
are two reasonsfor this decision. First, OpenGL isnot object-oriented, so using C++
or Javawould not add significandy tothe basic unless I were to insert
Trang 21Preface x v
an object-oriented geometriclibrary between OpenGL and theuser Ihave n ot taken
this step,despiteits appealing features, because it woulddetract from the graphics
and would make the book lessaccessibletostudents who are good programmers
but unfamiliar with object-oriented languages Second,my experience has been that
object-oriented approachesshield the user from what is going on inside (as they
should), whereasin an introduction tocomputer graphics, I want readers tobeaware
of what ishappening at the lowest levels Although the use ofcomputer graphics isa
wonderful wayto introduce studentsto object-oriented programming, in my view, an
object-oriented approach isnot the most effective way to teach graphics tocomputer
scienceand engineering students. The exception tothisviewiswhen I introduce scene
graphsthat are object oriented andbenefit from the use ofC++.My undergraduate
students use Javaand C++ in their beginning coursesbut have no difficulty in using
the code in this bookwith either C orC++
Intended Audience
This book is suitable for advanced undergraduates andfirst-yearg radu a te students
in computer science and engineering and for students in other disciplines who have
good programming skills The bookalso will be useful tomany professionals. Ihave
taught over 100short courses for professionals; my experiences with these
nontra-ditional students have had agreat influence on what I havechosentoinclude in the
book
Prerequisites for the book are goodprogramming skills in CorC++,an
under-standing ofbas icdata structures (linked lists, trees),and a rudimentary knowledge of
linear algebra and trigonometry I havefound that the mathematical backgrounds of
computer science students, whether undergraduates orgraduates, vary considerably.
Hence, I havechosentointegrate into the text muchofthe linear algebra and
geome-try that isre quiredfor fundamental computer graphics I havealsosummarized this
material inAppendicesBand C.
Thebookisorganized as follows. Chapter 1 providesan overview ofthefielda nd
in-troduces imageformation by optical devices; thus, westart with three-dimensional
concepts immediately Chapter 2introduces programming using OpenGL Although
thefirste x am p leprogram that we develop\342\200\224each chapter has one ormore complete
programming examples\342\200\224is two-dimensional, it isembedded in a three -dimensional
setting and leads to a three-dimensional extension In Chapter 3, we discuss
inter-active graphics in amodern client-serversetting and develop event-driven graphics
programs Chapters 4and 5 concentrate on three-dimensional concepts;Chapter 4
is concerned with defining and manipulating three-dimensional objects,whereas
Chapter 5 isconcerned with viewing them. Chapter 6introduces light-material
in-teractions and shading. These chapters should becoveredin order and canbetaught
in about 10weeks ofa 15-weeksemester.
The next seven chapters canbe readin almost any order All sevenare
some-what open ended and canbe coveredat a survey level, orindividual topics can be
Trang 22xxvi Pr e f ace
pursued in depth. Chapter 7surveys rasterization It gives one ortwo major
algo-rithms foreachoft h ebasic steps,including clipping, line generation, andpolygon fill.
Chapter 8introducesmany of the new discretecapabilities that are now supported in
graphics hardware and by OpenGL.All these techniques involve working with
var-ious buffers. It concludeswith a short discussion ofaliasing problems in computergraphics Chapter 9 isan introduction to programmable shaders using the OpenGL
Shading Language (GLSL),which is now part ofOpenGL.We use programmable
shaders todeveloptechniques, such as bump mapping, that can now be donein real
time. Chapters 8and 9 conclude the discussionofthe standard viewing pipeline used
by all interactive graphics systems
Chapter 10contains a number of topics that fit loosely under the heading of
hierarchical modeling Thetopicsrange from building models that encapsulate the
relationships between the partsof amodel, to high-level approaches tographics over
the Internet Itincludesasimple scene graph API and an introduction to OpenScene Graph.Chapter 12 introduce sanumber of procedural methods, including particlesystems,fractals, and procedural noise Curves and surfaces, including subdivisionsurfaces, are discussedin Chapter 12. Chapter 13surveys alternate approaches torendering It includes expanded discussions of ray tracing and radiosity, and an
introduction to image-based rendering and parallel rendering.
Programs, primarilyfromt h efirstp artofthebook, areincluded in AppendixA.
They arealsoavailable online (see Support Materials) Appendices Band C contain
a review ofthe background mathematics. Appendix D contains a synopsis of theOpenGLfunctions used in the book
Changes from the Fourth Edition
The reaction ofreaders ofthe first four editions ofthis book was overwhelminglypositive, especially tothe use of OpenGL and the top-down approach. But there are
always improvements to be made and recent advances to be covered Theadvent
of programmable graphics processors hasbeen amajor advance, one that Ibelieve
should have a major impact on how we teach computer graphics In the fourth
edition, Iintroduced programmable shaders and the OpenGLShading Language In
addition toforcing a rearrangement ofmaterial from earlier editions,techniques that
were not possible to implement in most systems, and thus werecoveredonly in a
perfunctory manner, arenow routine and arecoveredat a level appropriate fora first
course in computer graphics.An additional benefit of the rearrangement of topics
is that the chapters now follow the OpenGL pipeline more closelythan in previous
editions
Programmable shaders are covered in arewritten Chapter 9using the OpenGL
Shading Language This chapter includes more examplesthan the previous edition.Using programmable shaders, many techniques can now be implementedin real
around Bumpmapping, which was covered with texture mapping in the third
edi-tion, isnowcoveredwithfragments h aders Although some instructors may find this
Trang 23Preface xxv i i
change abit oddat first, Ithink they will see the advantages whenthey st art teaching
vertexand fragment shaders material
Forth e fourth edition, Ieliminated the separate chapters onscientific
visualiza-tion and procedural methods Someof the material on scientific visualization, such
as the marching-squares method, is spread overthe other chapters. However, the
importance ofprocedural methods led me toreintroduce an expanded chapter on
procedural graphics t hatincludes particle systems,fractals, and procedural noise
Readers ofprevious editions will notice that some of the example programs
have been changed.In particular, I replaced the paint program in Chapter 3with
a polygon manipulation program, which I believe illustrates interaction and design
more clearly Chapter 12includesthe code for abasic particle system Chapter9 has
better examples of programmabl eshaders than the fourth edition
Giventhe positive feedback I've received onthe core material in Chapters 1-6,
I'vetried to keep the changes tothose chaptersminor, seeking primarily to improve
the pedagogy I believe that these changes should have only minor effects on the
teaching ofaone-semester introductory course but the newmaterial in the following
chapters should make it easier for instructors to use the book for a two-semester
course
Support Materials
Thesupport for the book is onthe Web, both through theauthor's Web site www.es
.unm.edu/~angel and Addison-Wesley's site www.aw com/cssupport.Support
mate-rial that isavailable to all readers ofthis book includes
\342\200\242 Sources of information onOpenGL
\342\200\242 Instructions on how to getstarted with OpenGL onthemostpopular systems
\342\200\242
Program code
\342\200\242 Solutions to selected exercises
\342\200\242 PowerPoint lectures
Additional support materials, including solutions to allthe nonprogramming
exercises, are available only toinstructors adopting this textbook forclassroom use.
Please contact your school's Addison-Wesleyrepresentative for information on
ob-taining access to this material
Acknowledgments
Ihave been fortunate over the pastfew years to have workedwith wonderful students
atUNM They we re thefirstt o getmeinterested in OpenGL, and I have learned much
from them They include Hue Bumgarner-Kirby (Walker), Ye Cong, Pat Crossno,
Tommie Daniel,Chris Davis, Lisa Desjarlais, Kim Edlund, Lee Ann Fisk, Maria
Gallegos,Brian Jones, Christopher Jordan, MaxHazelrigg, Sheryl Hurley, Thomas
Keller,Ge Li,Pat McCormick, Al McPherson, Ken Moreland, Martin Muller, David
Munich, JimPinkerton, Jim Prewett, Dave Rogers, Hal Smyer, TakeshiHakamata,
Trang 24xxviii Pr e f ace
DaveVick, Brian Wylie, and JinXiong.Many of theexamplesin the color plates were
createdby these students.
The first edition ofthis book was written during my sabbatical; various parts
were written infived iffer en t countries. The experience speakswell for the versatility
of portable computersand the universality of the Internet Nevertheless, the taskwould not have been accomplished without the help of a number of peopleand
institutions that made theirfacilities available to me Iamgreatly indebted to JonasMontilvaand Chris Birkbeck oft heUniversidad de los Andes (Venezuela), toRodrigo
Gallegos and Aristides Novoa ofth e Universidad Tecnologica Equinoccial (Ecuador),
to LongWen Chang oftheNational Tsing Hua University (Taiwan),and to Kin HongWongand Pheng AnnHeng ofthe ChineseUniversity of Hong Kong RamiroJordan
JohnBrayer and Jason Stewart at theUniversity of New Mexico an d Helen Goldstein
at Addison-Wesley somehow managed to get avariety of items to me wherever I
first edition.
This edition waswritten in New Mexico and benefited greatly from the feedback
ofhundreds of instructors and students who used the first four editions and sent
me theircomments.Many of thechangesfrom earlier editions areresponses totheir
requests and comments
DavidKirk and Mark Kilgard atNVIDIA werekind enough to provide cardsfor
testing many ofthe algorithms A number of other people provided significant help.
I thank BenBederson, GonzaloCartagenova, Tom Caudell, Kathi Collins,Kathleen
Danielson, Roger Ehrich, RobertGeist, ChuckHansen,Mark Henne, Bernard Moret,Dick Nordhaus, Helena Saona, Dave Shieiner, Vicki Shreiner, Gwen Sylvan, and
MasonWoo Mark Kilgard, Brian Paul,and Nate Robins areowedagreat debt by theOpenGLcommunity for creating software that enablesOpenGL codet o be developedoveravariety of platforms.
At the University of New Mexico, the Art, Research, Technology, and Science
Laboratory (ARTS Lab) and the Centerfor High Performance Computing have pro
-vided support for many ofmy projects. The Computer Science Department, the
Arts Technology Center in the CollegeofFine Arts, the National Science
Founda-tion, Sandia National Laboratories, andLosAlamos National Laboratory have ported many of my students and research projectsthat led to parts ofthis book.
for the Full Dome Project\342\200\224Sheryl Hurley, Christopher Jordan, LaurelLadwig, Hue
(Bumgarner-Kirby) Walker\342\200\224which provided some ofthe imagesin the color plates
HueWalker has done thewonderful coversfor the last two editions
Reviewers of my manuscript drafts provided avariety of viewpoints on what
I should include and what level ofpresentation I should use These reviewers
in-cludeGur Saran Adhar (University of North Carolina atWilmington), Mario lar (Jacksonville State University), MichaelAnderson (University ofHartford), C.S
Agru-Bauer (University of Central Florida), Marty Barrett (East Tennessee State
Univer-sity), Eric Brown, Robert P.Burton (Brigham Young University), SamBuss
Trang 25Preface xxi x
(Cornell University), Eric Alan Durant (Milwaukee School ofEngineering), David
S. Ebert (Purdue University), Chenyi Hu (University of Central Arkansas), Mark
Kilgard (NVIDIA Corporatio n) ,Lisa B.Lancor (Southern Connecticut State
Univer-sity), Chung Lee (CA PolytechnicUniversity, Pomona), John L.Lowther (Michigan
Technological Univ ersity), R.Marshall (Boston University and Bridgewater State
Col-lege),Bruce A Maxwell (Swathmore College),James R.Miller (University ofKan s as),
Rodrigo Obando (Columbus State University),Han-WeiShen (The Ohio State
Uni-versity), Oliver Staadt (University ofCalifornia, Davis), Stephen L Stepoway
(South-ernMethodist University), Bill Toll (TaylorUniversity), Michael Wainer (Southern
IllinoisUniversity, Carbondale), George Wolberg (CityCollege ofNew York), Yang
Wang (Southe rn Methodist State University), Steve Warren (Kansas State University),
MikeWay (Florida Southern College), and Ying Zhu (Georgia State University).In
addition, the following instructors provided valuable feedback from the fourth
edi-tion: Kabekode V. Bhat (ThePennsylvania State University), Richard R.Eckert
Hills),Hugh C Masterman (University of Massachusetts, Lowell),Andrea Salgian
(The College ofNew Jersey), Lori L.Scarlatos (Brooklyn College, CUNY), Han-Wei
Shen (The OhioState University), Xiaoyu Zhang (California State University San
Marcos), and Ye Zhao (Kent State University). Although thefinal decision smay not
reflect their views\342\200\224which often differed considerably from oneanother\342\200\224each
re-viewer forced me toreflect on every page ofth e manuscript.
Iacknowledgethe entire production team atAddison-Wesley.My edit ors ,Peter
Gordon, MaiteSujarez-Rivas, and Matt Goldstein havebeen apleasure to work with
throughfivee dit i onsofthisbookand theOpenGLprimer Katherine Harutunian has
helped methrough the production process onall my books with Addison-Wesley
Through five editio ns ,Paul Anagnostopoulos atWindfall Software has always been
more th an helpful in assisting mewith TgK problems. Iam especiallygrateful to Lyn
Dupre Iamnot a natural writer Ifthe readerscould seethe original draft ofthe first
edition, they would understand the wonders that Lyndoeswith a manuscript.
My wife,RoseMary Molnar, did thefiguresf or myfirstg raph i csbook, many of
which form the basisfor the figures in thisbook.Probably only other authors can
fully appreciate the effort that goesinto the book production processand the many
contributions and sacrificesour partners make to that effort.Thededication to the
book isa sincerebut inadequate recognition of all ofRoseMary's contributions to
my work
Trang 26Interactive Computer Graphics
FIFTH EDITION
Trang 27thedominant characteristic of this new millennium ishow computer and
communication technologies havebecomedominant forces in our lives.
Activi-ties as wide-ranging asfilmmaking,p u b lish i ng,banking, and education continue to
undergo revolutionary changes asthese technologies alter the ways in which we
con-duct our daily activities Thecombination of computers, networks, and the complex
human visual system,through computer graphics, has led tonew ways of displaying
information, seeingvi r tual worlds,an d communicating with peopleand machines.
Computer graphics isconcernedwith all aspects of producing pictures or
im-agesusing a computer. Thefieldb egan humbly almost 50yearsago,with the display
ofafew lines on acathode-ray tube (CRT); now, we cancreateimages by computer
that are indistinguishable from photographs of real objects.Weroutinely train
pi-lots with simulated airplanes, generating graphicaldisplays of avirtual environment
in real time. Feature-length moviesmadeentirely by compu te r have been successful,
both critically andfinancially.M as siv e multiplayer games caninvolve tens of
thou-sands ofconcurrent participants.
In this chapter, westart our journey with ashort discussion of applications of
computer graphics.Then weoverview graphics systems and imaging Throughout
this book, our approach stressesthe relationships between computer graphics and
image formation byfamiliar methods, such asdrawingby hand and photography We
will see that these relationships can help ust o design application programs, graphics
libraries, and architectures forgraphics systems.
In thisbook, weintroduce a particular graphics software system,OpenGL,which
has become a widely accepted standard for developing graphics applications
Fortu-nately, OpenGL iseasyt o learn, and itpossessesmost ofthe characteristics of other
popular graphics systems Our approach is top-dow n.Wewant you to start writing,
asquickly as possible, application programs that will generate graphical output
Af-ter you begin writing simpleprograms,wewill discuss how the underlying graphics
library and the hardware areimplemented This chapter should giveasufficient
over-view for you toproceedto
v>;^%- k
\"\342\200\242 ,j
Wt
Trang 28Chapter 1 Graphics Systems and Models
The development ofcomputer graphicshasbeendriven both bythe needs ofthe user
community and byadvancesin hardware and software Theapplications of computer
graphics aremany and varied; we can,however, divide them into fourmajor areas:
Classical graphics techniques arose asamedium to convey information amongpe
o-ple.Although spoken and written languagesserve asimilar purpose, the human
vi-sual system is unrivaled both as aprocessor of data and asapattern recognizer More
than 4000 yearsago,the Babylonians displayed floor plans ofbuildings on stones.
More than 2000years ago, the Greeks wereable toconvey their architectural ideasgraphically, eventhough the related mathematics wasnot developed until the Re-
naissance.Today, the same type ofinformation isgenerated byarchitects,mechanical
designers, and draftspeople usingcompute r-ba sed drafting systems
For centuries, cartographers have developed maps todisplay celestial and graphicalinformation Such maps were crucial tonavigators as these people explored
geo-the ends ofthe earth;maps areno less important today infieldss u c h asgeographic
information systems Now, maps canbe developedand manipulated in real timeover
the Internet.
Over thepast 150years, workers in thefieldo fstatisticshave exploredtechniques
for generating plots that aidthe viewer in understanding the information in a set
of data.Now, we have computer plotting packagesthat provide avar iety ofplottingtechniques and color toolsthat can handle multiple large data sets.Nevertheless,it
is still the human's ability to recognize visual patterns that ultimately allows us to
interpret the information contained in the data Thefield of information tion isbecomingincreasingly more important aswe havet o deal with understanding
visualiza-complexphenomena from problems inbioinformatics todetecting security threat s.
Medical imaging posesinteresting and important data-analysis problems ernimaging technologies\342\200\224such as computed tomography (CT),magnetic resonance
Mod-imaging (MRI), ultrasound, and positron-emission tomography (PET)\342\200\224generate
three-dimensional data that mustbe subjectedtoalgorithmic manipulation to videuseful information Color Plate 20shows an image of aperson'sheadin which
pro-the skin is displayed as transparent and the internal structures are displayed as
opaque.Although the data were collected by a medical imaging system,computer
graphics produced the image tha tshowsthe structural information.
Trang 291.1 Applications of Computer Graphics
Supercomputers now allow researchers in many areas to solve previously
in-tractable problems Thefieldo f scientific visualization provides graphical tools that
help theseresearchersinterpret the vast quantity ofdata that they generate In fields
such as fluid flow,molecular biology, and mathematics, images generatedby
conver-sion ofdata togeometricentities that can bedisplayed haveyielded new insights into
complex processes.For example, ColorPlate 19 showsfluidd y nami c sin the mantle
ofthe earth.Thesystem used amathematical model to generatethe data Thefieldo f
information visualization uses compute r graphics t o aid inthe discoveryof
relation-ships in data setsin which there isnophysical tie between the data and how they are
visualized.We presentvarious visualization techniques asexamplesthroughout the
rest ofthetext.
1.1 2 Design
Professions such as engineeri ng and architecture are concerned with design.Starting
with aset ofspecifications, engineers and architects seekacost-effective and esthetic
solution that satisfiesthe specifications Design is an iterative process.Rarely in the
realworld isaproblem specified such that there isaunique optimal solution. Design
problems areeither overdetermined, such that they possess no solution that satisfies
allthe criteria, much lessan optimal solution, or underdetermined, such that they
have multiple solutions that satisfy the design criteria Thus, the designer works
iteratively She generates a possibledesign, tests it, and then usesthe results as the
basisfor exploring other solutions
The powerofthe paradigm of humans interacting with images on the screenof
aCRT was recognized by Ivan Sutherland morethan 40 years ago.Today,the use of
interactive graphicaltoolsin computer-aided design (CAD) pervadesfieldsi n c lud
-ing as architecture, mechanical engineering, the design ofv ery-l arge - s cal eintegrated
(VLSI) circuits, and the creation of charactersfor animations In all these
applica-tions, the graphics are used in a number of distinct ways Forexample,in a VLSI
design, thegraphics provide an interactive interfacebetween the user and thedesign
package, usually by means ofsuch tools as menus and icons.In addition, after the
userproduces apossibledesign, o ther tools analyze thedesign and display the
analy-sis graphically. Color Plates9and 10 show two viewsoft h esamearchitectural design.
Both images weregenerated with the same CAD system.They demonstrate the
im-portance ofhaving the tools available to generatedifferent images ofth esameobjects
at different stages of thedesign process.
Oncegraphics systems evolved to becapable ofgenerating sophisticated images in
realtime, engineersand researchers began to use them assimulators One of the
most important uses has been in the training of pilots. Graphical flight
simula-tors have proved to increasesafety and to reduce training expenses.The useof
spe-cial VLSI chips has led to ageneration of arcade games assophisticated as flight
simulators
Trang 30Chapter 1 Graphics Systemsand Models
ColorPlate 16 shows aphysical robot and the corresponding graphical simulation
Thesimulator can be used fordesigning the robot, planning itspath, and simulating
its behaviorin complex environments.
The success offlight simulators led to the useofcomputer graphics for tion in the television, motion picture, and advertising industries. Entire animated
anima-moviescannow be made by computers at acostlessthan that of movies madewith
traditional hand-animation techniques The useof comp u ter graphicswith hand
an-imation allowsthe creation oftechnical and artistic effects that arenot possiblewith
either alone. Whereascomputer animations have adistinct look, we canalsogenerate
photorealistic images bycomputer Often images that wesee on television, in movies,and in magazines are sorealisticthat we cannot distinguish computer-generated orcomputer-altered imagesfrom photographs In Chapters 6and 9, we discuss many
of the lighting effects usedto produce computer animations Color Plate 13 shows
a scene from a computer-generated video Theartists and engineers who created
this scene used commercially available software The plate demonstrates our ability
to generate realisticenvironments, in this case awelding robot inside a factory. Thesparksdemonstrate the use ofprocedu ra lmethods forspecialeffects.We will discuss
these techniques in Chapter 11.The imagesin Color Plate 31showanother example
of the useofcomputer graphics to generate an effect that, although itlooks realistic,
could not have been created otherwise.Th e images in Color Plates 23and 24 also arerealisticrenderings.
The field ofvirtual reality (VR) has opened many new horizons. Ahu manviewer
can be equipped with a display headset that allowsher to see separate imageswith her
right eye and her left eye, which gives the effect of stereoscopic vision In addition,
her body location and position, possibly including her head andfinger positions, are
tracked by the computer. Shemay have other interactive devicesavailable, including
scene,limited only by the image-generation ability of the computer Forexample,
asurgical intern might be trained to do an operation in this way, or an astronaut
might be trained to work in a weightless environment Color Plate 22 shows oneframe of aVR simujaiion of asimulated patient usedfor remote training of medical
personnel.
Thegraphics to drive interactive videogamesmake heavy use ofboth standard
commodity computers and specialized hardware boxes To a large degree, games
drive the development ofgraphics hardware On the commercial side,the revenue
from video games has surpassed the revenue for commercialfilms The graphics
technology forgames,both in the form ofthe graphics processing units that are on
graphics cards in personal computers and in game boxes such asthe Xbox and thePlayStation, is bein g used for simulation rather than expensive specialized hardware.Color Plate 16 is a frame from an interactive game, showing a robot warrior, that
uses hierarchical methods (Chapter 10),procedural methods for smoke and fire
(Chapter 11), and noisetextures for landscapes (Chapter 11).Theengine that drives
the game usesscenegraphs that we present in Chapter 10.
Trang 311.2 AGraphics System
1.1 4 UserInterfaces
includes windows, icons, menus, and a pointing device, such as a mouse.From
a user's perspective, windowing systems such as the XWindow System, Microsoft
of peoplehave become Internet users Their accessisthrough graphical network
browsers, such asFirefox and Internet Explorer, that use thesesameinterface tools.
We havebecome so accustomedtothis style ofinterface that weoften forget that we
areworking with computer graphics
Although we arefamiliar with the styleofgraphical user interface used on most
workstations,
1
advances in computer graphicshave made possible other formsof
in-terfaces.Color Plate 14shows the interface used with a high-level modeling package
It demonstrates the variety ofthe tools available in suchpackagesand the interactive
devices the user can employin modeling geometric objects
1.2 AGRAPHICS SYSTEM
A computer graphics system is a computer system; as such, it must have all the
components of ageneral-purposecomputer system Let us startwith the high-level
viewof agraphics system, asshown in the block diagram in Figure 1.1.There arefive
major elements inour system:
This model isgen e r alenough to include workstations and personalcomputers,
inter-active game systems, and sophisticated image-generation systems.Although all the
components, with the possible exception ofthe frame buffer, are present in a
stan-dard computer, it is the way eachelement is specializedfor computer graphics that
characterizesthis diagram as aportrait of agraphics system.
Presently, almost allgraphics systems areraster based A picture is produced asan
array\342\200\224ilicraster\342\200\224of picture elements, or pixels, within the graphics system As
we canseefrom Figure 1.2, each pixelcorrespondsto a location, or small area, in
1 Alth o ugh personal computers and workstationsevolved by somewhat different paths, presently,
there isvirtually no fundamental difference between them. Hence,we use the terms
personalcom-and workstation
Trang 32Chapter 1 Graphics Systemsand Models
Processor
Memory
Frame buffer
FIGURE 1.1 Agraphics system
FIGURE 1.2 Pixels, (a) Image of Yetithe cat.(b) Detail of area around
one eyeshowing individual pixels.
the image.Collectively, the pixels are stored in a part ofmemory calledthe frame
buffer. Theframeb uffer canbeviewed as thecore element of agraphics system Its resolution\342\200\224the number of pixels in the framebuffer\342\200\224determines the detail thatyou canseein the image. The depth, orprecision, oftheframeb u ffer ,defined as the
number ofbits that are used foreachpixel,determines properties such ashowmanycolors can be represented onagiven system For example, a 1-bit-deepframe buffer
allows only twocolors,whereas an 8-bit-deep frame buffer allows 28(256) colors.
Infull-color systems,t h ere are24 (ormore) bits per pixel Such systems candisplay
sufficient colors to representmostimages realistically They arealsocalled true-color
Trang 331.2A Graphics System
assigned toeach ofthe three primary colors\342\200\224red, green, and blue\342\200\224used in most
displays
Highdynamic range applications require morethan 24-bit fixed point colorrep
-resentations of RGB colors Somerecentframebuffers store RGB values as
floating-point numbers in standardIEEE forma t. Hence, the term true color should be
inter-pretedasframebu f fersthat have sufficient depth to representcolorsin terms ofRGB
valuesrather than as indices into alimited set of colors Wewill return to this topic
in Chapter 2.
Theframeb ufferusually is implemented with specialtypes of memory chips that
enable fast redisplay ofthe contents of the frame buffer In software-based systems,
suchas those usedfor high-resolution rendering or for generating complex visual
effects that cannot be producedin real time, the frame buffer is part of system
memory.
In a very simple system,the frame buffer holds only the coloredpixelsthat are
displayed on the screen.In most systems, the frame buffer holds far more
informa-tion, such as depth information neededfor creating images from three-dimensional
data.In these systems, theframebuffer comprises multiple buffers, one ormore of
which are color buffers that hold the colored pixels that aredisplayed. For now, we
canuset h etermsframebuffer and colorbuffer synonymously with out confusion
In a simple system, theremaybe onlyoneprocessor, the centralprocessing unit
(CPU) ofthe system, which must doboth the normal processing and the graphical
processing. Themain graphical function ofthe processorist o take specifications of
graphical primitives (such aslines, circles,and polygons) generated by application
programs and to assign values tothe pixels in the frame buffer that best represent
these entities Forexample, atriangle is specified byitsthree vertices, but to display
its outline by the three line segmentsconnecting the vertices, the graphics system
must generate aset of pixelst h at appear as linesegmentstothe viewer The
conver-sionof geometricentities to pixel colors and locations in the frame buffer isknown
as rasterization,or scanconversion In early graphics systems,theframebu f fer was
part of the standard memory that could be directly addressedby the CPU. Today,
vir-tually all graphics systems are characterized by special-purpose graphics processing
units (GPUs),custom-tailoredtocarry out specific graphics functions.The GPUcan
be either on the motherboard ofthe system or on agraphics card The frame buffer
isaccessedthrough the graphics processing unit and maybeincluded in the GPU
1.2.2 Output Devices
For many years, the dominant type of display (or monitor) hasbeenthe
cathode-ray tube (CRT).Although various flat-panel technologies arenow more popular,
the basicfunctioning of the CRT has much in common with these newerdisplays.
phosphor coating on the tube, light isemitted Thedirection oft hebeam is controlled
by two pairs ofdeflectionplates Theoutput of the computer is converted,by
digital-to-analog converters, to voltagesacrossthe x and y deflection plates.
Trang 34Chapter 1 Graphics Systems and Models
ydeflect
Electron gun
FIGURE 1.3 Thecathode-ray tube (CRT).
on the surface of the CRT when asufficiently intense beam ofelectrons is directedat
the phosphor.
If the voltagessteering the beam change ataconstant rate, the beam will trace
a straight line, visible to a viewer Such a deviceisknown as the random-scaa,calligraphic, or vector CRT, becausethe beam can be moved directly from any
position toany other position. Ift heintensity of thebeam isturned off, the beam can
bemoved to anew position without changing any visibledisplay. This configuration
wasthebasis ofearly gr aphics systems that predated the present raster technology
Atypical CRT will emit lightforonly a short time\342\200\224usually, a few milliseconds\342\200\224
after the phosphor is excitedby the electron beam For ahuman to see a steady,
flicker-free image on most CRTdisplays, the same path must be retraced,or
re-freshed, bythe beamat a sufficiently high rate, the refresh rate. In older systems,
the refresh rate isdetermined by t he frequency ofth e power system, 60cycles
persec-ond or 60 Hertz (Hz)in theUnited States and 50Hzinmuch of the rest oftheworld.Modern displays are no longer coupled totheselow frequencies and operate atrates
rows are refreshed alternately Interlaced displays are used in commercial television.
In an interlaced display operating at 60 Hz, the screen isredrawn in its entirety only
30times persecond, although the visual system is tricked into thinking the refreshrate is60 Hzrather than 30 Hz Viewerslocatednearthe screen, however, can tellthe
difference between the interlaced andnoninterlaced displays Noninterlaced displaysarebecomingmore widespread,eventhough these displays process pixelsat twice the
rate ofinterlaced displays.
Color CRTshavethree different colored phosphors (red, green, and blue),
ar-ranged in small groups Onecommon style arranges the phosphors in triangular
called triads, eachtriad of three phosphors, one ofeach
Trang 35FIGURE 1.5 Generic flat-panel display.
MostcolorCRTshave three electron beams, corresponding tothe three types of
phos-phors.In the shadow-mask CRT (Figure 1.4),ametal screen with small holes\342\200\224the
shadow mask\342\200\224ensures that an electron beam excitesonly phosphors ofthe proper
color.
Although CRTs are still the mostcommon display device, they arerapidly
be-ing replaced by flat-screen technologies. Flat-panel monitors are inherently raster.
Although there are multiple technologies available, including light-emitting diodes
(LEDs),liquid-crystal displays (LCDs), and plasma panels,all use atwo-dimensional
grid to addressindividual light-emitting elements. Figure 1.5shows a generic
flat-panel monitor Thetwo outside plates contain parallelgrids of wiresth a tareoriented
perpendicular to each other By sending electrical signals tothe proper wire in each
grid, the electrical field at a location, determined bythe intersection oftwo wires, can
be made strong enough to control the corresponding element in the middle plate.
Themiddle plate in an LEDpanel contains light-emitting diodes that canbeturned
on and off by the electrical signalssent to the grid In an LCDdisplay, the electrical
fieldcon t rolsthe polarization of the liquid crystalsin the middle panel, thus turning
on and off the light passing through the panel Aplasma panelusesthe voltages on
the grids to energizegases embeddedbetween the glass panels holdingthe grids The
energized gas becomesa
Trang 3610 C ha pt e r 1 Graphics Systems and Models
Mostprojection systems are also raster devices Thesesystems use avariety of
technologies,including CRTs and digital light projection (DLP).From a user tive,they act as standard monitors with similar resolutions and precisions Hard-copy devices, such as printers and plotters,are alsoraster based but cannot be refreshed
perspec-Until recently, most displays had a 4:3width to height ratio (oraspect ratio)
that correspondeds to commercial television.In discrete terms, displays startedwith
VGA resolution of 640 x 480pixels,which was consistent with thenumber of lines
displayed inStandardNTSC video.2
Computer displays moved up tothe popular
res-olutions of 1024x 768(XGA) and 1280 x 1024(SXGA) Thenewer High Definition
Television (HDTV)standard uses a 16:9aspectratio, which is between the older
tele-vision aspect ratio and that ofmovies.HDTV monitors display 780 or 1080linesin
either progressive (1080p, 780p) orinterlaced (1080i, 7801) modes Hence,th e most
popular computer display resolutions are now 1920 x 1080and 1280 x 720, whichhavethe HDTV aspect ratio, and 1920x 1024and 1280 x 768, which havethe verti-
cal resolution ofXGA and SXGA displays Atthe high end, there arenow \"4K\" (4096
x 2160)digital projectors that aresuitablefor commercial digital movies
1.2.3 Input Devices
Most graphics systems provide akeyboard and at least one other input device. Themost commoninput devices are the mouse, the joystick, and the data tablet Each
provides positional information tothe system, and each usually is equipped with one
ormorebuttons to provide signals tothe processor Often called pointing devices, these devicesallow a user to indicate aparticular location on the display.Westudy
these devices inChapter3.
Gameconsoles lack keyboards but includeagreater variety ofinpu t devices than
astandard workstation A typical console might have multiple buttons, ajoystick,and dials. Devices suchasth e Nintendo Wii are wirelessand can sense accelerations
in threedimensions.
Games,CAD, and virtual reality applications have all generated the need for
input devices that provide morethan two-dimensional data. Three-dimensional cations onareal-world object can beobtained by a variety ofdevices, including laser rangefindersan d acoustic sensors Higher-dimensional data can be obtained byde-
lo-vicessuch as data gloves, which includemany sensors, and computer visionsystems.
1.3 IMAGES:PHYSICAL AND SYNTHETIC
The traditional pedagogical approach to teaching computer graphics has been cusedon how to construct rasterimages ofsimple two-dimensional geometric en-tities (forexample,points, line segments, and polygons) in the frame buffer Next,
fo-most textbooks discussedhow to define two- and three-dimensional mathematical
2.Outside the United States,thePAL and SECAM systems display more lines b ut use alowerframe
Trang 371.3 Images: Physical and Synthetic 1 1
objects in the computerand image them with the set oftwo-dimensional rasterized
primitives.
This approach worked well for creating simpleimagesofsimple objects In
mod-ern systems,however, we want toexploitthe capabilities ofthesoftware and hardware
to createrealistic images of computer-generated three-dimensional objects\342\200\224atask
that involves many aspects of image formation, such as lighting, shading, and
prop-erties ofmaterials Because such functionality issupported directly by most present
computergraphics systems, we prefer to setthe stage for creating theseimages here,
rather than to expand alimited model later.
Computer-generated imagesaresynthetic or artificial, in the sensethat the
ob-jects beingimagedmay not exist physically In this chapter, we argue that the
pre-ferred method to form computer-generated imagesissimilar to traditional imaging
methods, such as cameras and the human visual system. Hence, before wediscuss
the mechanics ofwriti ng programs togenerateimages,we discussthe way images are
formedby optical systems. We construct a model oft h eimage-formation processthat
we can then uset o understand and developcomputer-generatedimaging systems.
In this chapter, we makeminimal use of mathematics Wewant to establish a
paradigm for creating images and to present a comp u ter architecturefor
implement-ing that paradigm Details arepresented in subsequent chapters, wherewewill derive
the relevant equations
1.3 1 Objects and Viewers
We live in aworld ofthree-dimensional objects The development ofmany branches
of mathematics, including geometry and trigonometry, was in response tothe
de-sire to systematizeconceptually simple ideas, such ast h emeasurement ofthe size of
objects andthe distance between objects Often weseekto representour
understand-ing of such spatial relationships with pictures or images, such as maps, paintings,
andphotographs. Likewise, the development ofmany physical devices\342\200\224including
cameras, microscopes, and telescopes\342\200\224was tied to the desire tovisualize spatial
re-lationships amongobjects Hence,there always has been afundamental link between
the physicsand the mathematics ofimageformation\342\200\224one that we can exploitin our
development ofcomputer image formation.
Two basic entities must bepart of any image-formation process, beit
mathe-matical or physical:objectand viewer The object existsin space independent ofany
image-formation processand of any viewer In computer graphics, where we deal
with synthetic objects, we formobjectsby specifying the positions in spaceofv a riou s
geometric primitives, suchas p oin t s ,lines, and polygons.In most graphics systems,
a set of locations in space, or ofvertices, issufficient to define, orapproximate, most
objects.For example, aline canbe specifiedby two vertices; apolygon canbe specified
byan orderedlistofvertices; and a spherecanbespecifiedbytwoverticesthatgiveits
centerand any point on itscircumference Oneof the main functions ofaCAD
sys-tem is to provide an interface that makes iteasyfor a user tobuildasynthetic model
of theworld.In Chapter 2,weshow how OpenGL allows us tobuild simple objects;
in Chapter 11, welearn to define objects in a manner that incorporates relationships
among objects
Trang 3812 Chapter 1 Graphics Systems and Models
FIGURE 1.6 Image seen by th r ee different viewers, (a)A's view, (b)B's
view, (c) C'sview
FIGURE 1.7 Camera system
Every imagingsystem must provide ameans of form i ng images from objects To
form an image, we must havesomeoneorsomething that isviewing ourobjects, beit
a person, acamera, oradigitizer It isthe viewerthat forms the image ofour objects.
In the human visual system, the image is formed onthe back ofthe eye Ina camera,
the image is formed in thefilmp lan e It iseasy to confuseimagesand objects.We
usuallysee an object fromour singleperspective and forget that otherviewers, located
in other places, will seet he same object differently Figure 1.6(a) shows two viewers
observing the same building Thisimageiswhat is seen by an observerA who is far
enough away from the building tosee both the building and thetwo other viewers,
B and C.From A's perspective, B and C appearasobjects, just asthe buildingdoes.
Figures 1.6(b) and (c) showthe images seen byBand C, respectively. Allthreeimages
contain the same building, butthe image ofthe building isdifferent in all three.\"Figure 1.7shows a camera system viewing abuilding. Here we can observethat
both the object and the viewer exist in a three-dimensional world However, the
image that they define\342\200\224what we find on the filmplane\342\200\224istwo dimensional. The
processby which the specification ofth e object iscombinedwith the specification ofthe viewer to produce atwo-dimensional image is th eessence of image formation,and wewill study itin detail
1.3 2 Light and Images
The precedingdescription of image formation isfar from complete. Forexample,we
have yet to mention light If there werenolight sources, the objectswould be dark,
and therewould be nothing visible in our image Norhave we indicated how colorentersthe picture or what theeffects of the surface properties ofthe objects are.
Taking amorephysical approach, we can startwith the arrangement shown inFigure 1.8,which shows asimple physicalimaging system Again, we seeaphysical
object and aviewer(the camera);now, however, there isalight source inthe scene.
Light from the source strikesvarious surfaces of the object, and aportion of the
reflected light enters the camerathrough the lens. The details of the interaction
between light and the surfaces of the object determine how much light enters the
camera
Trang 391.3 Images: Physical and Synthetic 13
FIGURE 1.8 Acamera system with an object and alight source.
FIGURE 1.9 Theelectromagneticspectrum.
Light is aform ofelectromagneticradiation Electromagnetic energy travels as
waves that can becharacterized by either their wavelengths ortheir frequencies.
3
The
electromagnetic spectrum (Figure 1.9) includes radio waves,infrared (heat), and a
portion that causes aresponse in our visual systems This visible spectrum, which
has wavelengths inthe range of350to 780nanometers (nm), is called (visible)light.
A given light source has a colordetermined by the energy that it emits at various
greeri; those near 450 nmare seenasblue; and those near 650 nm are seenas red.Just
as with arainbow,light at wavelengths between redand green we see asyellow, and
wavelengths shorterthan blue generate violet light
Light sources can emit light eitheras a setofdisc r etefrequencies or continuously.
Alaser,for example, emits light atasingle frequency, whereas an incandescent lamp
Trang 4014 Chapter 1 Graphics Systems and Models
emits energy over arangeof frequencies.Fortunately, in computer graphics, except
for recognizing that distinctfrequenciesa revisible as distinct colors, werarely need
to deal with the physical properties oflight, such asits wave nature
Instead, we canfollow a more traditional paththat is correct when weare
operat-ing with sufficiendy highlightlevels andat a scale where thewave nature oflightis not
asignificant factor Geometric optics modelslight sources as emitters oflight energy,
each ofwhich haveafixedin t ensit y Modeled geometrically, Ught travelsin straight
lines,fromt hesourcesto those objectswith which itinteracts An ideal point source
emits energy from a singlelocation at one or morefrequenciese qu a lly in alltions.More complex sources,such as a light bulb, can be characterized asemitting
direc-light over an areaand by emitting more light in onedirection than another. Apartic
-ular source is characterized bytheintensity oflight that itemitsat eachfrequencyan d
by tha tlight'sdirectionality We consider only point sourcesfor now More complexsources often can be approximated by anumber of carefully placed point sources.
Modeling of light sources isdiscussedin Chapter 6.
1.3.3 Image Formation Models
There are multiple approaches to how we can form imagesfrom aset of objects,
the light-reflecting properties of theseobjects, and the properties ofthe light sources
in the scene.In this section, we introduce two physical approaches. Although these
approaches arenot suitable for the real-time graphics that we ultimately want,they
will give usinsightinto how we canbuild auseful imaging architecture.
We canstart building an imaging modelby following light from asource
Con-sider the scene illustrated in Figure 1.10;it is illuminated by asingle point source. Weincludethe viewer in thefigureb ec au s ewe areinterested in the light that reaches her
eye Theviewer can also be acamera, asshown in Figure 1.11.Aray is asemi-infiniteline that emanatesfrom apoint and travels to infinity in aparticular direction Be- causelight travels in straight lines, we canthink in terms ofraysofligh t emanating in
all directionsfromo urpoint source.A portion oftheseinfinite rays contributes tothe
FIGURE 1.10 Scene with a single point source.