Essentials of Interactive Computer Graphics Concepts and Implementation Kelvin Sung All Chapter Instant Download
Essentials of Interactive Computer Graphics Concepts and Implementation Kelvin Sung All Chapter Instant Download
com
https://ebookgate.com/product/essentials-of-interactive-
computer-graphics-concepts-and-implementation-kelvin-sung/
OR CLICK HERE
DOWLOAD NOW
https://ebookgate.com/product/interactive-computer-graphics-a-top-
down-approach-with-shader-based-opengl-6th-edition-edward-angel/
ebookgate.com
https://ebookgate.com/product/fundamentals-of-computer-graphics-2nd-
edition-shirley-p/
ebookgate.com
https://ebookgate.com/product/foundations-of-3d-computer-graphics-1st-
edition-steven-j-gortler/
ebookgate.com
https://ebookgate.com/product/computer-graphics-with-opengl-4th-
edition-donald-hearn/
ebookgate.com
Essentials of Computer Organization and Architecture 6th
Edition Null
https://ebookgate.com/product/essentials-of-computer-organization-and-
architecture-6th-edition-null/
ebookgate.com
https://ebookgate.com/product/computer-graphics-with-opengl-3rd-
edition-donald-d-hearn/
ebookgate.com
https://ebookgate.com/product/3d-nanoelectronic-computer-architecture-
and-implementation-1st-edition-d-crawley/
ebookgate.com
https://ebookgate.com/product/mathematics-for-3d-game-programming-and-
computer-graphics-second-edition-eric-lengyel/
ebookgate.com
https://ebookgate.com/product/non-photorealistic-computer-graphics-
modeling-rendering-and-animation-1st-edition-thomas-strothotte/
ebookgate.com
i i
i i
Essentials of Interactive
Computer Graphics
i i
i i
i i
i i
Essentials of Interactive
Computer Graphics
Concepts and Implementation
Kelvin Sung
Peter Shirley
Steven Baer
A K Peters, Ltd.
Wellesley, Massachusetts
i i
i i
i i
i i
A K Peters, Ltd.
888 Worcester Street, Suite 230
Wellesley, MA 02482
www.akpeters.com
Printed in India
12 11 10 09 08 10 9 8 7 6 5 4 3 2 1
i i
i i
i i
i i
To my wife Danna
— S. B.
i i
i i
i i
i i
Contents
Preface xiii
Introduction 1
Introduction to Part I 9
1 Event-Driven Programming 13
1.1 Control-Driven Programming . . . . . . . . . . . . . . . . . . 14
1.2 Event-Driven Programming . . . . . . . . . . . . . . . . . . . 19
1.3 Triggering and Translation of Events . . . . . . . . . . . . . . 24
1.4 Categories of Events . . . . . . . . . . . . . . . . . . . . . . . 27
1.5 Servicing of Events . . . . . . . . . . . . . . . . . . . . . . . 30
1.6 The Event-Driven Ball-Shooting Program . . . . . . . . . . . 32
1.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
vii
i i
i i
i i
i i
viii Contents
i i
i i
i i
i i
Contents ix
i i
i i
i i
i i
x Contents
i i
i i
i i
i i
Contents xi
B Vectors 493
B.1 Vector Basics . . . . . . . . . . . . . . . . . . . . . . . . . . 493
B.2 Vector Products . . . . . . . . . . . . . . . . . . . . . . . . . 498
B.3 Vector Examples . . . . . . . . . . . . . . . . . . . . . . . . . 500
B.4 Orthonormal Matrices . . . . . . . . . . . . . . . . . . . . . . 505
Index 537
i i
i i
i i
i i
Preface
This book is designed for junior- or senior-level computer science, science, or en-
gineering students with a basic background in linear algebra and experience with
an object-oriented programming language. Working professionals with compara-
ble background should be able to follow this book and learn the essential computer
graphics concepts by themselves.
The technical content and organization of this book represent our answer to
the question:
xiii
i i
i i
i i
i i
xiv Preface
Tutorials
This book uses “the development of comprehensive software libraries suitable for
building popular interactive computer graphics applications” as the central theme
to connect and relate all the tutorials. All tutorials are implemented based on the
UWBGL library system. Initially this library is trivial. As new concepts are in-
troduced, corresponding sample implementation will be discussed and integrated
into the UWBGL. In this way, the complexity of the library builds gradually as more
concepts are presented in the book. There are a total of 18 different versions of
the UWBGL library. This library system increases in complexity throughout the
book and eventually enables fast prototyping of moderately complex interactive
computer graphics applications.
Organization
i i
i i
i i
i i
Preface xv
3. Part III extends the discussion to the third dimension by introducing the
computer graphics camera model and discussing techniques in software im-
plementation.
The book organizes the topics above to support the gradual building of the UWBGL
library system. It is important that the first four chapters of the book are covered
in their given order. These chapters present the foundation and describe the re-
quirements of the application/library that students will be building. Beyond the
first four chapters, the topics can be covered in almost any order. In all cases, as
soon as sufficient computer graphics topics are covered (by around Chapter 10 or
11), students should commence working on a final project based on the library
system. In these final projects, students should demonstrate their knowledge and
understanding by designing and developing an original and significantly complex
application.
At the University of Washington, Bothell, two 10-week quarter courses are
taught based on the contents of this book. The first course is a 2D graphics course
concentrating on software infrastructure, user interaction, coordinate transforma-
tion, and 2D hierarchical modeling. This 2D course covers Parts I and II of the
book. The first half of the second course covers the rest of the book. The sec-
ond half of the second course covers topics in hardware shading and illumination
based on up-to-date online documentation.
For more advanced students with a background in event-driven GUI program-
ming, it is possible to review the topics in Part I with an initial programming
assignment. In this case, Chapters 3 and 4 still need to be covered for an intro-
duction to programming with graphics APIs.
i i
i i
i i
i i
xvi Preface
The major strength of this book is in the presentation of conceptual and practical
insights required for the building of many popular interactive graphics applica-
tions. Essential concepts in interactive graphics application development are cov-
ered, including topics in software engineering, software design patterns, graphi-
cal user interfaces, real-time simulation, application programming interface (API)
models, graphical primitives, coordinate transformations, scene nodes and hierar-
chies, blending, file texturing, and camera models and interaction. These issues
are extremely important issues, especially for students who wish to pursue careers
in computer graphics–related fields. This book offers readers a substantive learn-
ing experience designed to further enhance their computer graphics knowledge.
Software Update
We plan to continue improving and updating the tutorials and to include the sup-
port of additional APIs (e.g., XNA Framework and potentially Java and OpenGL)
in the future. Please refer to http://depts.washington.edu/cmmr/biga/ for up-to-
date source code of the tutorials.
Acknowledgments
First and foremost, thanks to all CSS 450 and CSS 451 students from the Uni-
versity of Washington, Bothell. Over the years, many brilliant students helped
shape the design of the materials presented in this book. In 1999, after the raster-
algorithm–based CSS 450 class, Jeff Wartes was the first to point out: “This
course has been a disappointment. Drawing lines are only so interesting. I still
have no idea how computer graphics relates to the games I play.”
i i
i i
i i
i i
Preface xvii
The development of the materials that eventually became this book was started
in part as a reaction to these sincere comments. During the experimentation in
the earlier years, the 2001 batch of CSS 450 students, especially Steve Baer,
Jennifer Beers, Kazuko Hass, Gabriel Holmes, and Derek Gerstmann, critically
evaluated the design of the library. Having done such a wonderful job, Steve
has become an author of this book. Other significant contributions from stu-
dents include Chris Dannunzio on working with DirectInput, Adam Smith and
Sean Brogan on working with swap chains, Jack Nichols and Alexei Yatskov
on programming in C#, and Peter Yiap and Robert Stone on programming with
XNA. Jordan Phillips worked on the initial pass of the library organization; Ja-
son Pursell, William Frankhouser, and Ethan Verrall developed detailed guides
for the tutorials in Chapter 2; and Adrian Bonar built the documentation sup-
port system. A thank you also goes to colleagues in the community: Steve
Cunningham for his guidance and support for this project, Edward Angel for
the enlightening discussions on different approaches to teaching computer graph-
ics, Charles Jackels for his encouragements, and Frank Cioch for the challeng-
ing pedagogical discussions. The supporting letters from Gladimir Baranoski,
Peng-Ann Heng, Cary Laxer, Bob Lewis, Tiow-Seng Tan, Hung-Chuan Teh, and
Herbert Yang on the initial ideas for this textbook helped secure a grant from the
National Science Foundation that partially funded this project. Rebecca Reed-
Rosenberg worked closely with Kelvin Sung on the evaluation of the materi-
als. Ivan Lumala and John Nordlinger provided critical support toward the end
of the writing of this book. We would like to thank our editors, Alice Peters
and Kevin Jackson-Mead; thank you for the hard work, diligence, and timely
feedback.
Kelvin Sung would like to thank the University of Washington, Bothell, for
the sabbatical support for working on this book. The materials presented are
based upon results from projects supported by the University of Washington,
Bothell, Scholar Award 2004 and the National Science Foundation Grant No.
DUE-0442420.1 Toward the end, many of the tutorials were refined with support
from Microsoft Research under the Computer Gaming Curriculum in Computer
Science RFP, Award Number 15871.
Part I of this book is based liberally on Chapter 18 of the second edition
of Fundamentals of Computer Graphics. Although the contents are reorganized
with additional detail and extensive code examples that integrate smoothly with
the rest of this book, the basic concepts on building interactive applications are
the same.
1 Any opinions, findings, and conclusions or recommendations expressed in this material are those
of the author(s) and do not necessarily reflect the views of the National Science Foundation.
i i
i i
i i
i i
xviii Preface
This book was written using the LaTeX document preparation software in the
WinEdt2 /MiKTeX 3 editing environment. The figures were made by the authors
using Autodesk Maya, Adobe Illustrator, and Jasc Paint Shop Pro. The program
source code documentation is built based on Doxygen.4 The authors would like
to thank the creators of these wonderful programs.
Kelvin Sung
Peter Shirley
Steven Baer
2 http://www.winedt.com/
3 http://www.miktex.org/
4 http//www.doxygen.org/
i i
i i
i i
i i
List of Tutorials
xix
i i
i i
i i
i i
xx List of Tutorials
i i
i i
i i
i i
i i
i i
i i
i i
i i
i i
i i
i i
Introduction
Almost every laptop and desktop computer sold now has both a high-resolution
screen and a mouse. Inside these systems there is usually a central processing
unit (CPU) as well as a graphics processing unit (GPU). The GPU is of similar
overall complexity to the CPU, but it has a very different overall architecture and
purpose. Most of a programmer’s education typically deals with the CPU and
text and file input/output. This book, on the other hand, deals with the screen,
the mouse, and the GPU. These are the essential entities that computer graphics
programs control. Much of “standard” programming applies in graphics, but there
are many additional things to be mastered by a graphics programmer. This book
deals with those additional things.
The rest of this book develops graphics programs one step at a time and in
full detail. This is not a book to sit and read and ponder, as the many mundane
details presented are quite boring. However, they are vital details for actually
doing graphics programming. So, as you read the book, test what you learn by
doing. By the end of the book, you should have in your skill set the ability to
write a simple—even complex—application. We begin with handling user input
to the program, displaying 2D graphics, and then harnessing the full 3D power of
the GPU.
Rather than discussing graphics at a high level, we will dive right in and begin
programming starting with Chapter 2. Thus the rest of this introduction discusses
some details to be aware of when using the book. These are important nuts and
bolts and should not be skipped!
i i
i i
i i
i i
2 Introduction
Although foundation concepts are covered, this book is the how to of com-
puter graphics, rather than the more traditional what is text that usually covers
computer graphics. More specifically, we concentrate on how to build interactive
computer graphics applications. The book ensures sufficient foundation concepts
are covered so that readers can begin coding interactive graphics applications as
they read the text, thus providing readers with proper preparation in order to con-
tinue learning about foundations of computer graphics after finishing this book.
As far as this book is concerned, an application is a computer program. We inter-
change the use of application and program.
The Tutorials
The presentation of the material in this book is tightly integrated with example
programs. We refer to these examples as tutorials, because they are designed
to teach and demonstrate the implementation of concepts. For each topic area,
we typically study the concepts followed by discussion of implementations with
source code snippets. Since the topic areas build on top of each other, so does
the source code for the tutorials. Initially, the tutorials are bare-bones with a
handful of files; as we learn more concepts, the complexity of the tutorials will
also increase. Toward the end, the tutorials will be moderately elaborate software
systems with thousands of lines of source code. It is important that you follow
and understand the source code as you read the text. We have found that one of
the best ways to follow this book is by practicing graphics program development
based on the provided source code. In general, it may be difficult to understand
this book without a good understanding of the tutorials.
The tutorials and source code can be found on the accompanying CD.5 The tuto-
rials for each chapter are grouped under separate folders with the chapter being
the name of the folder. Inside each chapter folder, the source code for each tu-
torial is separated into subfolders, with the tutorial’s number and page number
being the sub-folder’s name. The final folder is named after the API and the pro-
gramming language that the tutorial is implemented in. For example, Chapter 10
Tutorial 10.1 is first introduced on page 258, and there are two implementations
5 Also available online at: http://depts.washington.edu/cmmr/biga/.
i i
i i
i i
i i
Introduction 3
of this tutorial: OpenGL and D3D, both based on C++ and MFC. The source code
for this tutorial is located at
chapter_tutorials/Chapter_10/Tutorial_10.1_OnPage258/C++_D3D_MFC/
chapter_tutorials/Chapter_10/Tutorial_10.1_OnPage258/C++_OGL_MFC/
i i
i i
i i
i i
4 Introduction
• Files. Files have names that begin with uwbgl_API_Type. For exam-
ple, uwbgl_D3DCircleGeom.h or uwbgl_OGLCircleGeom.h. For files that
contain API-independent code, there will be no corresponding API_Type.
For example, uwbgl_Utilitiy.h declares the utility functions (e.g., the
random number functions) for the library.
– UWB. General classes that are common to all Graphics APIs (OGL and
D3D). These classes typically define pure virtual interfaces
that specify functionality. For example, we will discuss the
UWB_WindowHandler interface to the windowing system.
– UWBD3D. Classes that customize and build on top of D3D functionality.
For example, the UWBD3D_CircleGeometry class is built on top of
D3D drawing routines and encapsulates the functionality of a circle.
– UWBOGL. Classes that customize and build on top of OpenGL function-
ality. For example, the UWBOGL_CircleGeometry class is built on top
of OpenGL drawing routines and encapsulates the functionality of a
circle.
i i
i i
i i
i i
Introduction 5
• Utility functions. General utility function names begin with UWB. For ex-
ample, UWB_RandomNumber() returns a random number.
When necessary, we refer to each class/file by its entire identifier string (e.g.,
UWB_RandomNumber()). However, for readability, we refer to the names without
the “UWB_” prefix, (e.g., RandomNumber() instead of UWB_RandomNumber()).
Appendix C summarizes the changes of the library, when necessary, with as-
sociated static class UML diagrams. As new libraries are introduced in the text,
refer to this appendix.
i i
i i
i i
i i
6 Introduction
There are different levels of using the source code and the elaborate libraries
provided. Readers are encouraged to be:
• Evaluators of the source code. For those who can understand the source
system, we encourage you to critically evaluate our solutions to implement-
ing the graphics concepts. We believe we have a pretty good solution, but
as in all design problems, there are no perfect answers. For example, we
believe the IWindowHandler hierarchy (introduced in Chapter 5) is a pretty
solution for abstracting graphics and GUI APIs while supporting view/con-
troller functionality. However, we certainly understand that this is not a
perfect solution, and readers are encouraged to evaluate the merits of our
solution and to seek out alternative ideas.
• Developers of their own systems. From our experience using this source
system in the classroom, the best students often challenge the provided
source code and develop their own libraries while using the provided source
as an example. Many students choose to implement their systems based on
different programming languages with different APIs, for example, Java,
Java Swing, and OpenGL, C++, MFC, and OpenGL, C#, WinForm, and
XNA Framework, and so on.
In all cases, the most important point we hope to make is that readers should avoid
getting bogged down with our implementation and being unable to continue learn-
ing as a result of our source code system. That would be the worst-case scenario.
Always remember: find ways to use the source code and examples to experience
and experiment with the concepts. You don’t have to like the implementation. In
fact, you are welcome to hate it and critically evaluate it; just don’t allow your
attitude toward the source code to hinder your learning of the subject matter.
i i
i i
i i
i i
Elements of Interactive
Programs
i i
i i
i i
i i
Introduction to Part I
Graphics. Chapter 3 shows us how to draw simple geometric shapes with com-
puter graphics. Chapter 4 shows us the principles of working with special-
ized graphics API libraries.
i i
i i
i i
i i
10 Introduction to Part I
(R): Radius
(A): Initial mouse
click position
(B) Dragging
Dragging
(C) Current
mouse position
sizes, shoot the ball, and examine the parabolic free fall of the ball. For clarity,
we avoid graphics-specific complexities in 3D space and confine our discussion
to 2D space. Obviously, our simple program is neither sophisticated nor repre-
sentative of real applications. However, with slightly refined specifications, this
example contains all the essential components and behavioral characteristics of
more complex real-world interactive systems. We will use the design and devel-
opment of the ball-shooting program throughout all chapters in Part I to help us
consolidate the concepts.
• The balls (objects). The user can left-mouse-button-click and drag out a
new ball (circle) anywhere on the screen (see Figure I.1). Dragging out a
ball includes:
i i
i i
i i
i i
Introduction to Part I 11
Dragged
outUser
balls
Slider
Sliderbar Application
numeric echo Status
Velocity (X) 12.48 (Pixel/Sec)
tance to the center defined in (A). The vector from the current position
to the center is the initial velocity V (in units of pixels per second).
Once created, the ball will begin traveling with the defined initial velocity.
• Velocity slider bars (GUI elements). The user can monitor and control
two slider bars (x- and y-directions with magnitudes) to change the velocity
of the HeroBall. When there is no HeroBall, the slider-bar values are
undefined.
• The simulation.
i i
i i
i i
i i
12 Introduction to Part I
Our application starts with an empty screen. The user clicks and drags to
create new balls with different radii and velocities. Once a ball travels off of the
screen, it is removed. To avoid unnecessary details, we do not include the drawing
of the motion trajectories or the velocity vector in our solutions. Notice that a
slider bar communicates its current state to the user in two ways: the position of
the slider knob and the numeric echo (see Figure I.2).
We have now described the behavior of a simple interactive graphics appli-
cation. We can begin learning the concepts that support the implementation of
this type of application. We concentrate on issues concerned with interaction and
software engineering practices.
i i
i i
i i
i i
Event-Driven Programming
This chapter introduces the event driven programming model. This chapter
However, because this chapter does not cover the details of any API, we will not
be able to implement the solutions we have designed. For that, we will wait for
the next chapter.
13
i i
i i
i i
i i
14 1. Event-Driven Programming
i i
i i
i i
i i
• and finally before we poll the user for another command, tell the user what
is going on by echoing current application state to the status bar (E).
i i
i i
i i
i i
16 1. Event-Driven Programming
main() {
(A): while ( GUISystem::UserAction != Quit ) {
i i
i i
i i
i i
(C): UpdateSimulation()
// Draw the new Hero Ball that is currently being defined
(D): DrawBalls(AllWorldBalls)
if (DefiningNewHeroBall)
(D1): DrawBalls(HeroBall)
As we add additional details to parse and execute the user’s commands (B), the
solution must be expanded.The revised solution in Listing 1.2 shows the details
of a central parsing switch statement (B) and the support for all three commands
a user can issue: defining a new HeroBall (B1), selecting a HeroBall (B2), and
adjusting the current HeroBall velocity with the slider bars (B3). Undefined user
actions (e.g., mouse movement with no button pressed) are simply ignored (B4).
Notice that HeroBall creation (B1) involves three user actions: mouse down
(B1), followed by mouse drag (B1-1), and finally mouse up (B1-2). The parsing
of this operation is performed in multiple consecutive passes through the outer
while-loop (A): the first time through, we create the new HeroBall (B1); in the
subsequent passes, we process the actual dragging operation (B1-1). We assume
that mouse drag (B1-1) will never be invoked without the mouse-button-down
(B1) action, and thus the HeroBall is always defined during the dragging opera-
tion. The LeftMouseButtonUp action (B1-2) is an implicit action not defined in
the original specification.
In our implementation, we choose this implicit action to activate the insertion
of the new HeroBall into the AllWorldBalls set. In this way, the HeroBall is
not a member of the AllWorldBalls set until the user has completed the dragging
operation. This delay ensures that the HeroBall’s velocity and position will not
be affected when the UpdateSimulation() procedure updates each ball in the
AllWorldBalls set (C). This means that a user can take the time to drag out a
new HeroBall without worrying that the ball will free fall before the release of the
mouse button. The simple change in the drawing operation (D1) ensures proper
drawing of the new HeroBall before it is inserted into the AllWorldBalls set.
i i
i i
i i
i i
18 1. Event-Driven Programming
Complexity concerns. Notice that our entire solution is in the main() func-
tion. This means that all relevant user actions must be parsed and handled by the
user command-parsing switch statement (B). In a modern multiprogram shared-
window environment, many actions performed by users are not application-
specific. For example, if a user performs a left mouse-button click and drag in
the drawing area of the program window, our application should react by drag-
ging out a new HeroBall. However, if the user performs the same actions in
the title area of the program window, our application must somehow implement
moving the entire program window. As experienced users in window environ-
ments, we understand that there are numerous such operations, and we expect all
applications to honor these actions (e.g., iconize, resize, raise or lower a window).
Following the solution given in Listing 1.2, for every user action that we want to
honor, we must include a matching supporting case in the parsing switch state-
ment (B). This requirement quickly increases the complexity of our solution and
becomes a burden to implementing any interactive applications.
To support the development of efficient interactive applications, we need sys-
tem support where we could remain idle by default (not taking up machine re-
sources) and only become active in the presence of interesting activities (e.g.,
i i
i i
i i
i i
• (C) Stop and wait. Instead of actively polling the user for actions (wast-
ing machine resources), the MainEventLoop() typically stops the entire
i i
i i
i i
i i
20 1. Event-Driven Programming
GUISystem::MainEventLoop() {
// For initialization of application state and
// registration of event service routines
(A): SystemInitialization()
case GUISystem::Iconize:
if (user application registered for this event)
Execute user defined service routine.
else
GUISystem::DefaultIconizeBehavior()
case ...
Every possible event and the default services are included.
} // end of switch(GUISystem::NextEvent)
} // end of loop forever
} // end of GUISystem::MainEventLoop() function. Program terminate
• (D) Events and central parsing switch statement. Included in this state-
ment are all possible actions/events (cases) that a user can perform. Asso-
ciated with each event (case) is a default behavior and a toggle that allows
i i
i i
i i
i i
To develop an event-driven solution, our program must first register event ser-
vice routines with the GUI system. After that, our entire program solution is
based on waiting for and servicing user events. While control-driven program-
i i
i i
i i
i i
22 1. Event-Driven Programming
i i
i i
i i
i i
GUISystem::MainEventLoop() {
// This will call the user defined function
(A): SystemInitialization()
} // end of switch(GUISystem::NextEvent)
} // end of loop forever
} // end of GUISystem::MainEventLoop() function. Program terminates.
i i
i i
i i
i i
24 1. Event-Driven Programming
User solution program: We, as GUI programmer, will program the following.
i i
i i
i i
i i
to buttons (the quit button). On the one hand, we understand that mouse clicks
over “on-screen slider bar area” or “on-screen button area” would result in “slider Event. Event is a highly over-
bar” and “button pressed” events being triggered. On the other hand, we also loaded term in our discipline.
In this chapter, we use event to
understand that clicking on a mouse and pressing a button are two distinct events. mean GUI system events: an
This section briefly discusses the propagation and translation process from the asynchronous notification that
hardware mouse clicks to the slider bar knob position events or button click events something interesting in the
that our application receives. GUI system has happened.
On a typical computer system, the operating system (OS) is responsible for mon-
itoring the physical states of input devices (e.g., keyboard or mouse). When in-
teresting state changes occur on these devices (e.g., key presses or mouse move-
ments), the OS packages and sends this information to the window manager. The
window manager is the system application that is in charge of the entire com-
puter display screen. Just as the OS keeps track of all the processes running on a
machine, the window manager keeps track of all the application windows on the
computer display screen. The window manger is responsible for forwarding rel- In focus. Because all user-
evant information from the OS to the currently active application. The GUI API triggered hardware state
changes are directed toward
that our application is built upon is responsible for receiving information from the currently active window,
the window manager and translating and repackaging any hardware state change an active window is often
information (e.g., mouse click or key press) into semantically meaningful events referred to as being in focus.
(e.g., button click) for our application.
In the Linux OS X Window environment, a user has the option of working
with different window manager programs (e.g., twm, mwm). This is in contrast
with the Microsoft Windows environment, where the OS is tightly coupled with
a single window manager program. However, in both cases the window manager
keeps track of all application windows on the display screen and forwards all
relevant hardware input device state change information to the currently active
window/application.
i i
i i
i i
i i
26 1. Event-Driven Programming
is also an example of a GUI element, where a few rectangles are used to represent
the title bar and work area with a few surrounding lines representing the window
borders. Typical applications first create the main window GUI element and then
place other GUI elements at strategic locations inside the application’s window to
associate semantic meanings with those locations. For example, the ball-shooting
program in Figure I.2 has six GUI elements:
4. Quit button;
5. Status bar.
As we will see in Tutorial 2.8, in general, it is possible to place a window GUI el-
ement within another window GUI element. As the complexity of our application
increases, this is a convenient and powerful way to organize the large number of
GUI elements involved.
After receiving hardware device state change information from the window
manager, the GUI API translates this information into events and forwards the
events to the currently active GUI element. For example, a mouse click on an in-
focus “button GUI element” is translated into a “button-pressed event,” whereas
a mouse click over a “slider bar GUI element” is translated into a “slider bar
position event” with an appropriate scroll values.
Sometimes it is not appropriate/meaningul for the GUI API to translate and
forward hardware state change information. For example, a user performs a
mouse click over the status bar area of Figure I.2. Because the status bar is an
output-only GUI element, it is not capable of receiving any input events. In cases
like this, the GUI API typically allows the application to choose between dis-
carding the event or translating and forwarding the event to the GUI element that
contains the in-focus element. In this case, the main application container window
would receive the mouse click event.
In practice, events have many triggering origins. For example, the user can
trigger input events; the window manager can decide to enter screensaver mode
and trigger events to inform all applications; or the OS can detect hardware ab-
normality and trigger events via the window manager. Ultimately, relevant events
will be sent to our applications. From within our applications, it can be impos-
sible to determine the true origin of an event. For example, a system hardware
failure may result in the window manager sending a “save and quit” event to our
i i
i i
i i
i i
These are events triggered by the actions a user performs on the input devices.
Notice that input devices include actual hardware devices (e.g., mouse, keyboard)
and/or software-simulated GUI elements (e.g., slider bars, combo boxes). Typi-
cally, a user performs actions for two very different reasons.
• Application-specific. These are input actions that are part of the appli-
cation. Clicking and dragging in the application screen area to create a
HeroBall is an example of an action performed on a hardware input de-
vice. Changing the slider bars to control the HeroBall’s velocity is an ex-
ample of an action performed on a software-simulated GUI element. Both
of these actions and the resulting events are application-specific: the appli-
cation (our program) is solely responsible for servicing these events.
i i
i i
i i
i i
28 1. Event-Driven Programming
These are events defined by the application, typically depending on some run-
time conditions. During run time, if and when the condition becomes favorable,
the supporting GUI system triggers the event and conveys the favorable condi-
tions to the application. A straightforward example is a periodic alarm. Modern
GUI systems typically allow an application to define (sometimes multiple) timer
events. Once defined, the GUI system will trigger an event to wake up the appli-
cation when the timer expires. As we will see, this timer event is essential for sup-
porting real-time simulations. Since the application (our program) requested the
generation of these types of events, our program is solely responsible for serving
them. The important distinction between application-defined and user-generated
events is that application-defined events can be predictable and dependable: when
properly defined, these are events that our application can depend on. Even when
the user is not doing anything, our application can depend on application-defined
events to trigger.
These are events that originated from either the window manager or within the
GUI system. These events typically convey state information to the application.
There are typically three reasons for these events.
• Internal GUI states change. These are events signaling an internal state
change of the GUI system. For example, the GUI system typically gener-
ates an event before the creation of the application’s main window. This
provides an opportunity for the application to perform the corresponding
initialization. In some GUI systems (e.g., MFC) the SystemInitializa
tion() functionality is accomplished with these types of events: user ap-
plications are expected to override the appropriate window’s creation event
and initialize the application state. Modern, general-purpose commercial
GUI systems typically define a large number of events signaling detailed
state changes in anticipation of supporting different types of applications
and requirements. For example, for the creation of the application’s main
window, the GUI system may define events for the following states:
i i
i i
i i
i i
A GUI system usually defines meaningful default behaviors for such events.
To program an effective application based on a GUI system, one must un-
derstand the different groups of events and only service the appropriate
selections.
i i
i i
i i
i i
30 1. Event-Driven Programming
An application program registers callback functions with the GUI system by pass-
ing the address of the function to the GUI system. This is the registration mecha-
nism implied in Listing 1.5. Simple GUI systems (e.g., GLUT or FLTK) usually
support this form of registration mechanism. The advantage of this mechanism is
that it is easy to understand, straightforward to program, and often contributes to
a small memory footprint in the resulting program. The main disadvantage of this
mechanism is the lack of organizational structure for the callback functions.
In commercial GUI systems, user applications typically must work with a
large number of events. A structured organization of the service routines can
greatly increase the programmability of the GUI system. Modern commercial
GUI systems often present their APIs through an object-oriented language inter-
face (e.g., C++ for MFC, Java for Java Swing). For these systems, many event
service routines are integrated as methods in the class hierarchies of the GUI sys-
tem. In these cases, registration of event service routines may be implemented as
subclassing and overriding corresponding virtual functions in the GUI system. In
this way, the event service routines are organized according to the functionality of
GUI elements.
The details of the different registration mechanisms will be demonstrated in
Chapter 2 when we examine the implementation details.
Event service routines are simply functions in our program. However, these func-
tions also serve an important role as the server of events. The following are guide-
lines one should take into account when implementing event service routines.
• An event service routine should only service the triggering event and return
the control back to the MainEventLoop() immediately. This may seem to
be a no-brainer. However, because of our familiarity with control-driven
i i
i i
i i
i i
i i
i i
i i
i i
32 1. Event-Driven Programming
As we have seen, with appropriate modifications, we were able to detail the con-
trol structures for our solution.
From the discussion in Section 1.2, we see that to design an event-driven
programming solution, we must
• map the user actions to events that the GUI system supports;
i i
i i
Another Random Document on
Scribd Without Any Related Topics
back
back
back
back
back
back
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com