100% found this document useful (1 vote)
128 views63 pages

Essentials of Interactive Computer Graphics Concepts and Implementation Kelvin Sung All Chapter Instant Download

The document provides information about various ebooks related to computer graphics, including titles like 'Essentials of Interactive Computer Graphics' and 'Computer Graphics with OpenGL'. It includes links to download these ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it outlines the contents of the 'Essentials of Interactive Computer Graphics' book, covering topics like event-driven programming, GUI APIs, and 3D applications.

Uploaded by

luciokudicoa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
128 views63 pages

Essentials of Interactive Computer Graphics Concepts and Implementation Kelvin Sung All Chapter Instant Download

The document provides information about various ebooks related to computer graphics, including titles like 'Essentials of Interactive Computer Graphics' and 'Computer Graphics with OpenGL'. It includes links to download these ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it outlines the contents of the 'Essentials of Interactive Computer Graphics' book, covering topics like event-driven programming, GUI APIs, and 3D applications.

Uploaded by

luciokudicoa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.

com

Essentials of Interactive Computer Graphics


Concepts and Implementation Kelvin Sung

https://ebookgate.com/product/essentials-of-interactive-
computer-graphics-concepts-and-implementation-kelvin-sung/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Interactive Computer Graphics A Top Down Approach with


Shader Based OpenGL 6th Edition Edward Angel

https://ebookgate.com/product/interactive-computer-graphics-a-top-
down-approach-with-shader-based-opengl-6th-edition-edward-angel/

ebookgate.com

Fundamentals of Computer Graphics 2nd Edition Shirley P.

https://ebookgate.com/product/fundamentals-of-computer-graphics-2nd-
edition-shirley-p/

ebookgate.com

Foundations of 3D Computer Graphics 1st Edition Steven J.


Gortler

https://ebookgate.com/product/foundations-of-3d-computer-graphics-1st-
edition-steven-j-gortler/

ebookgate.com

Computer Graphics with OpenGL 4th Edition Donald Hearn

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

Computer Graphics with OpenGL 3rd Edition Donald D. Hearn

https://ebookgate.com/product/computer-graphics-with-opengl-3rd-
edition-donald-d-hearn/

ebookgate.com

3D Nanoelectronic Computer Architecture and Implementation


1st Edition D. Crawley

https://ebookgate.com/product/3d-nanoelectronic-computer-architecture-
and-implementation-1st-edition-d-crawley/

ebookgate.com

Mathematics for 3D Game Programming and Computer Graphics


Second Edition Eric Lengyel

https://ebookgate.com/product/mathematics-for-3d-game-programming-and-
computer-graphics-second-edition-eric-lengyel/

ebookgate.com

Non Photorealistic Computer Graphics Modeling Rendering


and Animation 1st Edition Thomas Strothotte

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

Editorial, Sales, and Customer Service Office

A K Peters, Ltd.
888 Worcester Street, Suite 230
Wellesley, MA 02482
www.akpeters.com

Copyright © 2008 by A K Peters, Ltd.

All rights reserved. No part of the material protected by this copyright


notice may be reproduced or utilized in any form, electronic or mechani-
cal, including photocopying, recording, or by any information storage and
retrieval system, without written permission from the copyright owner.

Library of Congress Cataloging-in-Publication Data

Essentials of interactive computer graphics : concepts and implementation / Kelvin


Sung, Peter Shirley, Steven Baer. p. cm.
Includes bibliographical references and index.
ISBN 978-1-56881-257-1
1. Computer graphics. 2. Interactive computer systems. I. Sung, Kelvin, 1964-
II. Shirley, P. (Peter), 1963- III. Baer, Steven.
T385.E38565 2008
006.6--dc22
2008009675

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 father, Y. H. Sung, and in memory of my mother, T. C. Chang; his words


and her care shaped my life
— K. S.

To my wife Danna
— S. B.

i i

i i
i i

i i

Contents

Preface xiii

List of Tutorials xix

Introduction 1

I Elements of Interactive Programs 7

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

2 Working with GUI APIs 37


2.1 Our Application and Existing Libraries . . . . . . . . . . . . . 38
2.2 GUI Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3 Building a GUI Application . . . . . . . . . . . . . . . . . . . 41
2.4 Examples: FLTK and MFC . . . . . . . . . . . . . . . . . . . 43
2.5 Implementation Notes . . . . . . . . . . . . . . . . . . . . . . 45
2.6 Tutorials and Code Base . . . . . . . . . . . . . . . . . . . . . 48

3 A Simple Graphics Program 75


3.1 Coordinate Positions and Vertices . . . . . . . . . . . . . . . . 77
3.2 A Computer Graphics Solution . . . . . . . . . . . . . . . . . 79
3.3 Lessons Learned . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.4 Further Examples . . . . . . . . . . . . . . . . . . . . . . . . 85

4 Working with Graphics APIs 93


4.1 Relationship between Graphics and GUI APIs . . . . . . . . . 95
4.2 Programming Graphics APIs . . . . . . . . . . . . . . . . . . 96
4.3 Understanding Tutorials 3.1 and 3.2 . . . . . . . . . . . . . . . 100
4.4 Abstraction of Graphics API . . . . . . . . . . . . . . . . . . 103

5 The Model-View-Controller Architecture 109


5.1 The Model-View-Controller Framework . . . . . . . . . . . . 110
5.2 Applying MVC to the Ball-Shooting Program . . . . . . . . . 112
5.3 Expanding the Ball-Shooting Program . . . . . . . . . . . . . 118
5.4 Interaction among the MVC Components . . . . . . . . . . . . 120
5.5 Applying the MVC Concept . . . . . . . . . . . . . . . . . . . 121
5.6 Tutorials and Implementations . . . . . . . . . . . . . . . . . 122

6 Applying to Real-World Applications 147


6.1 PowerPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
6.2 Maya . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

II Essential Concepts: Presented in 2D 153

Introduction to Part II 155

7 Attributes and Behaviors of Primitives 157


7.1 Types of Primitives . . . . . . . . . . . . . . . . . . . . . . . 158
7.2 Working with Color . . . . . . . . . . . . . . . . . . . . . . . 162
7.3 Programming Geometric Primitives . . . . . . . . . . . . . . . 163

i i

i i
i i

i i

Contents ix

7.4 Abstraction of Behavior: A Primitive Hierarchy . . . . . . . . 172


7.5 Collisions of Primitives . . . . . . . . . . . . . . . . . . . . . 182
7.6 Collection of Primitives . . . . . . . . . . . . . . . . . . . . . 188

8 Transformation Operators 193


8.1 The Translation Operator . . . . . . . . . . . . . . . . . . . . 194
8.2 The Scaling Operator . . . . . . . . . . . . . . . . . . . . . . 198
8.3 The Rotation Operator . . . . . . . . . . . . . . . . . . . . . . 204
8.4 Affine Transformations . . . . . . . . . . . . . . . . . . . . . 209
8.5 Some Mathematics of the Transform Operators . . . . . . . . . 210
8.6 Tutorials on Transformation Operators . . . . . . . . . . . . . 215

9 Combining Transformation Operators 225


9.1 Concatenation of Operators . . . . . . . . . . . . . . . . . . . 226
9.2 Inverse Transformation . . . . . . . . . . . . . . . . . . . . . 229
9.3 Pivoted Transformations . . . . . . . . . . . . . . . . . . . . . 231
9.4 Programming Transformations with Graphics APIs . . . . . . 236

10 Coordinate Systems 257


10.1 Understanding Tutorial 3.1 . . . . . . . . . . . . . . . . . . . 258
10.2 Device and Normalized Coordinate Systems . . . . . . . . . . 265
10.3 The World Coordinate System . . . . . . . . . . . . . . . . . . 266
10.4 The World Coordinate Window . . . . . . . . . . . . . . . . . 273
10.5 Inverse Transformation . . . . . . . . . . . . . . . . . . . . . 287

11 Hierarchical Modeling 293


11.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
11.2 The SceneNode Class . . . . . . . . . . . . . . . . . . . . . . 299
11.3 Scene Trees and Scene Graphs . . . . . . . . . . . . . . . . . 311
11.4 The Object Coordinate System . . . . . . . . . . . . . . . . . 317
11.5 Simple Animation with the SceneNode Class . . . . . . . . . . 333

12 Making the Applications Interesting 337


12.1 Orientation of Objects . . . . . . . . . . . . . . . . . . . . . . 338
12.2 Alpha Blending and Transparency . . . . . . . . . . . . . . . . 345
12.3 File Texture Mapping . . . . . . . . . . . . . . . . . . . . . . 351

i i

i i
i i

i i

x Contents

III The Third Dimension 365

Introduction to Part III 367

13 A Simple 3D Application 369


13.1 3D Coordinate Systems . . . . . . . . . . . . . . . . . . . . . 371
13.2 The Model and the Scene . . . . . . . . . . . . . . . . . . . . 372
13.3 A Computer Graphics Simulation . . . . . . . . . . . . . . . . 374

14 The Camera 379


14.1 A Computer Graphics Camera . . . . . . . . . . . . . . . . . . 380
14.2 The Visible Volume . . . . . . . . . . . . . . . . . . . . . . . 386
14.3 The Coordinate Transformation Pipeline . . . . . . . . . . . . 396
14.4 The World Transform: OC to WC . . . . . . . . . . . . . . . . 397
14.5 The Eye Transform: WC to EC . . . . . . . . . . . . . . . . . 398
14.6 The Projection Transform: EC to NDC . . . . . . . . . . . . . 402
14.7 3D NDC–to-2D Device Transform . . . . . . . . . . . . . . . 404
14.8 Re-Examining Tutorial 13.1 . . . . . . . . . . . . . . . . . . . 405

15 Working with the Camera 409


15.1 UWBGL Camera Implementation . . . . . . . . . . . . . . . . 413
15.2 Working with Multiple Cameras . . . . . . . . . . . . . . . . . 422
15.3 Manipulating the Camera . . . . . . . . . . . . . . . . . . . . 422
15.4 DC-to-WC Transformation . . . . . . . . . . . . . . . . . . . 436
15.5 2D Versus 3D Coordinate Transformation Pipeline . . . . . . . 444

16 Graphics Programming in 3D 447


16.1 Graphical Primitives for the Third Dimension . . . . . . . . . 448
16.2 Rotation in 3D . . . . . . . . . . . . . . . . . . . . . . . . . . 457
16.3 Orientation in 3D . . . . . . . . . . . . . . . . . . . . . . . . 464
16.4 Simple Scene Graph in 3D . . . . . . . . . . . . . . . . . . . 479
16.5 Scene Graph and Orientation . . . . . . . . . . . . . . . . . . 480
16.6 Collision in 3D . . . . . . . . . . . . . . . . . . . . . . . . . . 485
16.7 Selection in 3D . . . . . . . . . . . . . . . . . . . . . . . . . 487

i i

i i
i i

i i

Contents xi

A Material and Illumination 489

B Vectors 493
B.1 Vector Basics . . . . . . . . . . . . . . . . . . . . . . . . . . 493
B.2 Vector Products . . . . . . . . . . . . . . . . . . . . . . . . . 498
B.3 Vector Examples . . . . . . . . . . . . . . . . . . . . . . . . . 500
B.4 Orthonormal Matrices . . . . . . . . . . . . . . . . . . . . . . 505

C Summary of Library Version Changes 507

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:

If students can only schedule one elective computer graphics course


in their undergraduate education, what should we teach in such a
course?

When answering this question, we strive to achieve two major objectives:

• To provide practical information. The knowledge should be practical


with potential applicability in the students’ chosen field of profession.

• To provide essential information. The knowledge should be essential con-


cepts that support students’ future self-learning in the field of computer
graphics.

xiii

i i

i i
i i

i i

xiv Preface

Tutorials

We approach these objectives by focusing on topics that are relevant to popular


computer graphics applications. To address the “one elective course” time re-
striction, only concepts that are relevant to interactive applications are covered.
To maximize potential applicability, source code for example implementations
(the tutorials) of the concepts is provided. These concept-demonstration tutorials
are implemented using popular APIs. To ensure students learn the associated con-
cepts together with the APIs, each tutorial has an OpenGL version and a DirectX
version. We are in the process of porting the tutorials to the XNA Framework, a
third graphics API.

The UWBGL Libraries

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

We present the concepts associated with interactive graphics applications in three


distinct parts.

1. Part I discusses the issues surrounding designing and implementing inter-


active applications based on a simple graphical user interface (GUI). To
ensure the focus is on user interaction and software design topics, coverage
of computer graphics is minimal in Part I.

2. Part II discusses the fundamental concepts for building graphics applica-


tions: graphical primitives, transformation, and (simple) applied linear al-
gebra. To ensure the context is simple for understanding these concepts, the
presentation is carried out in two dimensions.

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.

Throughout the presentation, the independence of concepts from implementation


is emphasized. The tutorials serve to reinforce this theme, where the same con-
cepts are demonstrated in multiple versions based on competing APIs. Following
this theme, we have chosen to omit the discussion of hardware shading and il-
lumination. This is because the field is currently undergoing rapid changes and
most of the materials involved are highly hardware- and API-dependent. Instead,
implementation with the simple traditional Phong model is demonstrated in Ap-
pendix A. We believe that this field will continue to undergo rapid changes, and
before it settles, the best source of up-to-date information will be online docu-
mentation and manuals.

Using This Book in a Course

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

This book can be used to teach building graphics applications to computer


science (CS) major students, as well as non-major students with the appropri-
ate programming background (experience with object-oriented programming).
For CS majors, the course should concentrate on building and improving the
UWBGL library system. For non-CS majors, the course should focus on using
the UWBGL library system in developing applications (instead of developing the
libraries).

Advantages of This Book

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

Tutorial Project Name Description Based on


2.1(p. 49) SimpleDialog Demystify source files -
2.2(p. 55) EchoButtonEvent GUI elements and controls 2.1
2.3(p. 58) SliderControls GUI control variables 2.2
2.4(p. 61) MouseAndTimer Application-defined events 2.3
2.5(p. 63) UpdateGUI Input/output GUI elements 2.4
2.6(p. 66) SliderCtrlWithEcho Extend GUI API with classes 2.5
2.7(p. 67) Library1 Custom GUI library 2.6
2.8(p. 69) GroupControls Grouping GUI elements 2.7
Chapter 2. Tutorials on GUI API.

Tutorial Project Name Description Based on


3.1(p. 79) Rectangles2D Drawing with D3D 2.8
3.2(p. 85) Rectangles2D Drawing with OGL 2.8
3.3(p. 87) RectangleClass Abstraction of drawing (D3D) 3.1
3.4(p. 87) RectangleClass Abstraction of drawing (OGL) 3.2
3.5(p. 90) CircleClass Apply drawing with abstraction 3.3
Chapter 3. Tutorials on drawing with graphics APIs.

Tutorial Project Name Description Based on


4.1(p. 105) GraphicsSystem Abstraction Graphics API (D3D) 3.5
4.2(p. 107) SeparateLibrary Graphics API Interface Lib (D3D) 4.1
4.3(p. 107) GraphicsSystem Abstraction Graphics API (OGL) 3.4
4.4(p. 107) RectangleClass Graphics API Interface Lib (OGL) 4.3
Chapter 4. Tutorials on programming with graphics APIs.

xix

i i

i i
i i

i i

xx List of Tutorials

Tutorial Project Name Description Based on


5.1(p. 123) ModelView WindowHandler abstraction Lib1
5.2(p. 131) MouseInput Mouse input via WindowHandler 5.1+Lib2
5.3(p. 135) SimulateGravity Real-time simulation/update 5.2+Lib2
5.4(p. 138) TwoViews Multiple independent views 5.3+Lib3
5.5(p. 141) MultipleBalls More complex application state 5.4+Lib3
5.6(p. 144) BallShooting Ball-Shooting program 5.5+Lib3
Chapter 5. Tutorials on model-view-controller architecture.

Tutorial Project Name Description Based on


7.1(p. 163) ObjectsAndAttributes Graphical primitives Lib4
7.2(p. 172) ObjectClasses Primitives class hierarchy 7.1+Lib5
7.3(p. 184) Collisions Collision of primitives 7.2+Lib6
7.4(p. 188) ObjectCollections Lists of primitives 7.3+Lib7
7.5(p. 191) BallShoot2 Ball-Shooting with primitive 5.6+Lib7
Chapter 7. Tutorials on attributes and behaviors of graphical primitives.

Tutorial Project Name Description Based on


8.1(p. 216) TranslateSingleObject Translation with one object Lib8
8.2(p. 220) TranslateObjects Translation with two objects Lib8
8.3(p. 222) ScaleObjects Scaling with two objects Lib8
8.4(p. 222) RotateObjects Rotation with two objects Lib8
Chapter 8. Tutorials on transformation operators.

Tutorial Project Name Description Based on


9.1(p. 236) TranslateScaleObj Concatenate translate and scale Lib8
9.2(p. 238) MatrixMultiplyOrder Order of concatenation 9.1+Lib8
9.3(p. 240) MatrixStack Matrix stack 9.2+Lib8
9.4(p. 242) PivotedRotation Pivoted scaling/rotation 9.3+Lib8
9.5(p. 245) PerPrimitiveTrans Pivoted transformation 9.4+Lib8
9.6(p. 250) XformInfo XformInfo class 9.5+Lib9
9.7(p. 251) XformInfoControls XformInfo GUI dialog 9.6+Lib9
9.8(p. 253) BallShoot3 Ball-Shooting with XformInfo 7.5+Lib9
9.9(p. 255) XformList Reference for next chapter 9.6+Lib9
Chapter 9. Tutorials on concatenation of transformation operators.

i i

i i
i i

i i

List of Tutorials xxi

Tutorial Project Name Description Based on


10.1(p. 258) ViewTransform0 World to NDC 3.1
10.2(p. 261) ViewTransform1 Squares in NDC 10.1
10.3(p. 263) ViewTransform2 Circle in NDC 10.2
10.4(p. 263) ViewTransform3 Aspect ratio 10.3
10.5(p. 263) ViewTransform4 Aspect ratio 10.3
10.6(p. 268) XformListCoordSpace World and device space 9.9+Lib9
10.7(p. 270) ChangedCoordinates World and device space 10.6+Lib9
10.8(p. 271) TranslateWC WC window center 10.7+Lib9
10.9(p. 278) WCSupport WC window with Lib10 10.8+Lib10
10.10(p. 280) Panning Moving WC window 10.9+Lib10
10.11(p. 283) Zooming Resizing WC window 10.10+Lib10
10.12(p. 285) AspectRatio Resizing UI drawing area 10.11+Lib10
10.13(p. 289) BadMousePan Mouse click input 10.12+Lib10
10.14(p. 289) MousePan Input with inverse transform 10.12+Lib10
Chapter 10. Tutorials on coordinate transformations.

Tutorial Project Name Description Based on


11.1(p. 295) SimpleArm Arm object Lib10
11.2(p. 297) ParentChild Parent/child group 11.1+Lib10
11.3(p. 303) SceneNode SceneNode class 11.2+Lib11
11.4(p. 305) SceneNodeArm Arm as a SceneNode 11.3+Lib11
11.5(p. 308) SceneNodeMultiPrim Multiple primitives in a node 11.4+Lib11
11.6(p. 312) SceneNodeSiblings Siblings nodes 11.5+Lib11
11.7(p. 327) SceneNodePicking Mouse click selection 11.6+Lib12
11.8(p. 329) SceneNodeCollision Object space collision 11.7+Lib12
11.9(p. 334) SceneNodeAnimation Animation with SceneNode 11.8+Lib12
Chapter 11. Tutorials on hierarchical modeling.

Tutorial Project Name Description Based on


12.1(p. 338) OrientationIn2D Orientation of objects 11.8+Lib12
12.2(p. 343) SceneNodeOrient Orientation of scene nodes 12.1+Lib12
12.3(p. 350) AlphaBlending Simple alpha blending Lib13
12.4(p. 355) SimpleTexture Simple texture mapping -
12.5(p. 364) TextureMapping Integrate with library 12.3+12.4+Lib13
Chapter 12. Tutorials on more complex and interesting applications.

Tutorial Project Name Description Based on


13.1(p. 374) Rectangles3D Simple 3D scene 3.1
Chapter 13. Tutorial on a simple 3D application.

i i

i i
i i

i i

xxii List of Tutorials

Tutorial Project Name Description Based on


14.1(p. 383) AdjustCamera Camera parameters 13.1
14.2(p. 389) AdjustOrtho Visible volume parameters 14.1
14.3(p. 393) AdjustPersp View frustum parameters 14.1
14.4(p. 395) AdjustDepth Near/far plane settings 14.3
Chapter 14. Tutorials on the computer graphics camera.

Tutorial Project Name Description Based on


15.1(p. 416) CameraLib Integrate into library 14.3+Lib14
15.2(p. 422) TwoCamera Two cameras 15.1+Lib14
15.3(p. 425) CameraMouseUI Interactive camera manipulation 15.2+Lib14
15.4(p. 441) CameraInvXform DC to WC in 3D 15.3+Lib14
Chapter 15. Tutorials on working with the camera.

Tutorial Project Name Description Based on


16.1(p. 455) MeshSupport D3D mesh resource 15.4+Lib15
16.2(p. 456) CompoundMesh Compound mesh Primitives 16.1+Lib15
16.3(p. 461) RotateMatrix Rotation with matrix 16.2+Lib16
16.4(p. 464) RotateQuat Rotation with quaternion 16.3+Lib17
16.5(p. 465) Orientation Working with quaternion 16.4+Lib17
16.6(p. 479) SimpleHierarchy Scene graph in 3D 16.5+Lib17
16.7(p. 480) SceneGraphIn3D Orientation in 3D 16.6+Lib17
16.8(p. 485) CollisionIn3D Collision in 3D 16.7+Lib17
16.9(p. 487) SelectionIn3D Mouse selection in 3D 16.8+Lib17
Chapter 16. Tutorials on working with the third dimension.

Tutorial Project Name Description Based on


A.1(p. 490) SimpleLighting Simple lighting 14.1
A.2(p. 490) Lighting Integrate into library 16.9+Lib18
A.3(p. 491) CustomMesh Working with D3DMesh A.2+Lib18
Appendix A. Tutorials on hardware illumination.

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.

Organization 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/

We are currently working on


chapter_tutorials/Chapter_10/Tutorial_10.1_OnPage258/C#_XNA_UWBGUI/

IDE and APIs


We have chosen the Microsoft Visual Studio 2005 integrated development envi-
ronment (IDE) as our target development environment. All tutorials are provided
as separate Visual Studio projects. For this first edition of the book, we do not
have support for any other IDEs.
The source code for the tutorials is in C++. We have developed two versions
of most tutorials: one based on the OpenGL and the other based on the Microsoft
DirectX Direct3D (D3D) graphics application programming interface (API). For
now, the graphical user interface (GUI) library of most tutorials is based on the
Microsoft Foundation Classes (MFC).
The choices for IDE, programming language, and libraries are based on the
belief that these are probably the most widely available and most familiar envi-
ronments to most of our readers. Our choices do not reflect endorsements for
any of the systems we used. In fact, we believe that the concepts covered in this
book, including implementation and specific skills, are independent of any partic-
ular software system. One should be able to port the learning from this book into
any program or programming language and develop moderately complex interac-
tive graphics programs, based on any modern IDE, object-oriented programming
language, graphics library, and/or GUI library.

Our Libraries and Naming Conventions


UWB and UWBGL. UWB is
In Chapter 2 we introduce a library to help abstract and customize the MFC li- the abbreviation for University
brary. In Chapter 4 we introduce another library to customize and interface to the of Washington, Bothell, the
home institution of the first au-
OpenGL and D3D graphics libraries. From Chapter 5 onwards, we begin to work
thor where most of the design
with the UWBGL libraries. We will work with one GUI library and two graphics and initial development efforts
libraries. The libraries have names of the form took place. “UWBGL” stands
for “UWB Graphics Library.”
UWBGL_API_Type_LibVersion_Number

i i

i i
i i

i i

4 Introduction

where API_Type can be

MFC—Microsoft Foundation Classes (GUI library)


D3D—Microsoft DirectX Direct3D (graphics library)
OGL—OpenGL (graphics library)

and Version_Number is an integer. For example, UWBGL_D3D_Lib1 is the first


D3D library, and UWBGL_OGL_Lib1 is the first OpenGL library we will develop.
As we learn more concepts, we will continue to introduce new classes into each
library, and the Version_Number of the corresponding library will increase.
We have established the following naming conventions to avoid collisions of
identifiers.

• 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.

• File versions. As we refine concepts, the contents of many files (e.g.,


classes) will continue to evolve. A file version number is attached to files to
avoid confusion (e.g., wubgl_D3DCircleGoem1.h and uwbgl_D3DCircle
Geom2.h). Notice that the file’s version number is independent of the li-
brary’s version number. For example, when evolving from UWBGL_D3D
_Lib1 to UWBGL_D3D_Lib2, the file uwbgl_D3DGraphicsSystem1.h did
not change. The same file version 1 file exists in both versions of the li-
braries.

• Classes. Classes have names that begin with the following.

– 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

– UWBMFC. Classes that customize and build on top of MFC function-


ality. For example, the UWBMFC_UIWindow class extends the MFC
window class with customized support for our graphics applications.

• 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.

Library Design Trade-Off


The UWBGL library is designed to present graphics concepts. Although we are
concerned with efficiency issues, execution speed is always of lower priority when
compared with logical organization for presenting graphics concepts. For exam-
ple, our simple organization of resetting/setting all attributes before drawing each
primitive necessarily means that the graphics rendering context must be updated
many times during each redraw. The alternative of collecting similar primitives
and setting the attributes once for all these primitives during redraw would be
much more efficient. However, such organization would introduce complexity
independent of graphics concepts. In all cases, we opted for simplicity at the ex-
pense of efficiency in order to provide clear and simple presentation of graphics
concepts.

Learning with the Provided Source Code


While reading this book, it is absolutely important to constantly remember that
the elaborated source code is provided as a tool for learning and demonstrating
the underlying concepts. We believe it is easier to grasp the foundations if readers
can experience and experiment with the concepts in moderately complex environ-
ments. As stated, the other goal of this book is for readers to begin to develop
moderately complex interactive computer graphics applications. The source is
provided as a demo.

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:

• Users of the source code. Readers should be encouraged to start from


Chapter 2, where we demonstrate how to be a programmer of and use the
source code provided to experience concepts and develop applications. You
don’t need to understand every single line of the provided code to be a
proficient user of the library and to program something complex as well as
experience and learn the underlying computer graphics concepts.

• 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

This book is about building interactive computer graphics applications. In Part I,


we concentrate on studying interactivity and the building of applications.

Interactivity. Chapter 1 shows us that interactivity demands the event-driven


programming model and discusses the elements of the event-driven model.
Chapter 2 shows us how to work with specialized graphical user interface
(GUI) application programming interface (API) libraries in implementing
event-driven interactive programs.

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.

Building of applications. Chapter 5 shows us the model-view-controller


(MVC) software architecture and demonstrates how to apply this architec-
ture in organizing the GUI API, the graphics API, and our programming
code to facilitate readability, maintainability, and expandability of our ap-
plication. Chapter 6 uses the MVC architecture to explain the software
structure of some real-world interactive graphics applications.

We will use the development of a simple example to organize our discussion:


a program that allows the user to simulate the shooting of a ball under the in-
fluence of gravity. The user can specify initial velocity, create balls of different

i i

i i
i i

i i

10 Introduction to Part I

(V): Initial velocity

(R): Radius
(A): Initial mouse
click position

(B) Dragging
Dragging

(C) Current
mouse position

Figure I.1. Dragging out a ball.

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.

Details of the Ball-Shooting Program


Our simple program has the following elements and behaviors.

• 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:

– (A): initial mouse-button-click position defines the center of the cir-


cle;
– (B): mouse-button-down and moving the mouse is the dragging ac-
tion;
– (C): current mouse position while dragging allows us to define the
radius and the initial velocity. The radius R (in pixel units) is the dis-

i i

i i
i i

i i

Introduction to Part I 11

Motion trajectory Ball-Shooting Program


Motion
for the next second
Current
Velocity Hero Ball

Dragged
outUser
balls
Slider
Sliderbar Application
numeric echo Status
Velocity (X) 12.48 (Pixel/Sec)

Velocity (Y) 9.12 (Pixel/Sec)

Status: Currently there are 5 balls on screen. QUIT

Figure I.2. The ball-shooting program.

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.

• HeroBall (hero/active object). The user can also right-mouse-button-


click to select a ball to be the current HeroBall. The HeroBall’s velocity
can be controlled by the slider bars (discussed below) where its velocity
is displayed. A newly created ball is by default the current HeroBall.
A right-mouse-button-click on unoccupied space indicates that no current
HeroBall exists.

• 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.

– Ball traveling/collisions (object intrinsic behaviors). A ball knows


how to travel based on its current velocity, and one ball can potentially
collide with another. For simplicity, we will assume that all balls have
identical mass and that all collisions are perfectly elastic.

i i

i i
i i

i i

12 Introduction to Part I

– Gravity (external effects on objects). The velocity of a ball is con-


stantly changing due to the defined gravitational force.
– Status bar (application-state echo). The user can monitor the appli-
cation state by examining the information in the status bar. In our
application, the number of balls currently on the screen is updated in
the status bar.

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

• explains the deficiencies of designing user-interface applications based on


the traditional control-driven programming model;

• introduces the event-driven programming model and examines how this


new model addresses the above deficiencies;

• demonstrates the development of user-interface solutions based on the event-


driven programming model.

After this chapter, you should

• understand the parameters and principles of event-driven programming;

• understand the process for designing an event-driven solution;

• understand, at a conceptual level, the interactions between GUI APIs and


our solution;

• be able to design an event-driven programming solution based on given


specifications.

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

For many of us, when we were first introduced to computer programming, we


learned that the program should always start and end with the main() function—
when the main() function returns, all the work must have been completed and
the program terminates. Since the overall control remains internal to the main()
function during the entire lifetime of the program, this approach to solving prob-
lems is referred to as the control-driven programming or the internal control
model approach. As we will see, an alternative paradigm, event-driven program-
ming or an external control model approach, is the more appropriate way to design
solutions to interactive programs.
In this chapter, we will first formulate a solution to the (2D) ball-shooting pro-
gram based on the perhaps more familiar control-driven programming model. We
will then analyze the solution, identify shortcomings, and describe the motivation
for the external control model or event-driven programming approach.
An event-driven program that interacts with users requires the support of a
graphical user interface (GUI) system. A GUI system implements standard func-
tionality of event-driven user-interactive programs and presents this functionality
as a software library through an application programming interface (API). Exam-
ples of GUI APIs include Java Swing Library, OpenGL Utility ToolKit (GLUT),
The Fast Light ToolKit (FLTK), and Microsoft Foundation Classes (MFC).
Through the discussion in this chapter, we will gain insights into GUI systems.
We will understand the standard functionality of event-driven user-interactive pro-
grams and the functionality that the GUI API must include. In the next chapter,
we will look at examples of popular modern GUI APIs, analyze how these GUI
systems support concepts learned in this chapter, and experiment with implement-
ing programs with these GUI APIs.
The pseudocode that follows is C++/Java-like. We assume typical function-
ality from the operating system (OperatingSystem::) and from a GUI system
(GUISystem::). The purpose of the pseudocode is to assist us in analyzing the
foundation control structure (i.e., if/while/case) of the solution. For this rea-
son, the details of application- and graphics-specific operations are intentionally
glossed over. For example, the details of how to implement UpdateSimulation()
are purposely omitted.

1.1 Control-Driven Programming


The main advantage of control-driven programming is that it is fairly straightfor-
ward to translate a verbal description of a solution to a program control structure.
In this case, we verbalize our solution as follows:

i i

i i
i i

i i

1.1. Control-Driven Programming 15

(A): As long as user is not ready to quit


while UserCommand != Quit

(B): Parse the user command


ParseAndExecute(UserCommand)

(C): Periodically update positions and velocities of the balls


if (OperatingSystem::SufficientClockTimeHasElapesd)
// update the positions and velocities of all the balls
// in AllWorldBalls
UpdateSimulation()

(D): Draw all balls to the computer screen


// all the balls in AllWorldBalls set
DrawBalls(AllWorldBalls)

(E): Set status bar with number of balls


// Sets status bar: number of balls on screen
EchoToStatusBar()

Listing 1.1. Programming structure from a verbalized solution.

• while the user does not want to quit (A);

• parse and execute the user’s command (B);

• update the velocities and positions of the balls (C);

• then draw all the balls (D);

• 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).

If we translate this verbal solution into a simple programming structure, we get


something like Listing 1.1. In Listing 1.1 we introduce the set of AllWorldBalls
to represent all the balls that are currently active in the application’s window. The
only other difference between the pseudocode in Listing 1.1 and our verbalized
solution is in the added elapsed time check in Step (C): SufficientClockTime
HasElapsed. (Recall that the velocities are defined in pixels per second.) To
support proper pixel displacements, we must know real elapsed time between
updates.

i i

i i
i i

i i

16 1. Event-Driven Programming

main() {
(A): while ( GUISystem::UserAction != Quit ) {

(B): switch (GUISystem::UserAction) {

// Begins creating a new Hero Ball


(B1): case GUISystem::LeftMouseButtonDown:
// hero not in AllWorldBalls set
HeroBall = CreateHeroBall()
DefiningNewHeroBall = true

// Drags out the new Hero Ball


(B1-1): case GUISystem::LeftMouseButtonDrag:
RefineRadiusAndVelocityOfHeroBall()
SetSliderBarsWithHeroBallVelocity()

// Finishes creating the new Hero Ball


(B1-2): case GUISystem::LeftMouseButtonUp:
InsertHeroBallToAllWorldBalls()
DefiningNewHeroBall = false

// Selects a current hero ball


(B2): case GUISystem::RightMouseButtonDown:
HeroBall = SelectHeroBallBasedOnCurrentMouseXY()
if (HeroBall != null)
SetSliderBarsWithHeroBallVelocity()

// Sets hero velocity with slider bars


(B3): case GUISystem::SliderBarChange:
if (HeroBall != null)
SetHeroBallVelocityWithSliderBarValues()

// Ignores all other user actions


(B4): default:
} // end of switch(userAction)
if (OperatingSystem::SufficientClockTimeHasElapsed)
// Move balls by velocities and remove off-screen ones

Listing 1.2. Programming solution based on the control-driven model.

i i

i i
i i

i i

1.1. Control-Driven Programming 17

(C): UpdateSimulation()
// Draw the new Hero Ball that is currently being defined
(D): DrawBalls(AllWorldBalls)

if (DefiningNewHeroBall)
(D1): DrawBalls(HeroBall)

// Sets Status Bar with number of balls currently on screen


(E): EchoToStatusBar

} // end of while(UserAction != Quit)

} // end of main() function. Program terminates.

Listing 1.2. (cont.)

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

When we examine this solution in the context of supporting user interaction,


we have to concern ourselves with efficiency issues as well as the potential for
increased complexity.

Efficiency concerns. Typically a user interacts with an application in bursts of


activity. These are continuous actions followed by periods of idling. This can be
explained by the fact that as users, we typically perform some tasks in the applica-
tion and then spend time examining the results. For example, when working with
a word processor, our typical work pattern consists of bursts of typing/editing
followed by periods of reading (with no input action). In our example applica-
tion, we can expect the user to drag out some circles and then observe the free
falling of the circles. The continuous while-loop polling of user commands in
the main() function means that when the user is not performing any action, our
program will still be actively running and wasting machine resources. During ac-
tivity bursts, at the maximum, users are capable of generating hundreds of input
actions per second (e.g., mouse-pixel movements). If we compare this rate to the
typical CPU instruction capacities that are measured at 109 per second, the huge
discrepancy indicates that, even during activity bursts, the user command-parsing
switch statement (B) is spending most of the time in the default case not doing
anything.

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

1.2. Event-Driven Programming 19

user-input actions). Furthermore, to integrate interactive applications in sophis-


ticated multiprogramming window environments, it is important that our system
support automatically takes care of mundane and standard user actions. This is
the basic functionality of a modern GUI system.

1.2 Event-Driven Programming


Event-driven programs are typically implemented based on an existing GUI sys-
tem. GUI systems remedy the efficiency and complexity concerns by defining a
default MainEventLoop() function. For event-driven programs, the MainEvent
Loop() replaces the main() function, because all programs start and end in this
function. Just as in the case of the main() function for control-driven program-
ming, when the MainEventLoop() function returns, all work should have been
completed, and the program terminates. The MainEventLoop() function defines
the central control structure for all event-driven programming solutions and typ-
ically cannot be changed by a user application. In this way, the overall control
of an application is actually external to the user’s program code. For this rea-
son, event-driven programming is also referred to as the external control model.
Listing 1.3 shows a typical MainEventLoop() implementation. In this case, our
program is the user application that is based on the MainEventLoop() function.
Structurally, the MainEventLoop() is very similar to the main() function of List-
ing 1.2, with a continuous loop (B) containing a central parsing switch statement
(D). The important differences between the two functions are the following.

• (A) SystemInitialization(). Recall that event-driven programs start and


end in the MainEventLoop() function. SystemInitialization() is a
mechanism defined to invoke the user program from within the MainEvent
Loop(). It is expected that user programs implement the function System
Initialization() to initialize the application state and to register event
service routines (refer to the discussion in (D)).

• (B) Continuous outer loop. Because this is a general control structure to


be shared by all event-driven programs, there is no way to determine the
termination condition. User programs are expected to override appropriate
event service routines and terminate the program from within the service
routine.

• (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()

// continuous outer loop


(B): loop forever {

// Program will stop and wait for next event


(C): WaitFor(GUISystem::NextEvent)

// Central parsing switch statement


(D): switch (GUISystem::NextEvent) {
case GUISystem::LeftMouseButtonDown:
if (user application registered for this event)
Execute user defined service routine.
else
Execute default UISystem routine.

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

Listing 1.3. The default MainEventLoop() function.

application process and waits for asynchronous operating-system calls to


re-activate the application process in the presence of relevant user actions.

• (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

1.2. Event-Driven Programming 21

(A) System Initialization:


(A1): Define Application State:
AllWorldBalls: A set of defined Balls, initialze to empty
HeroBall: current active ball, initialize to null

(A2): Register Event Service Routines:


Register for: Left Mouse Button Down Event
Register for: Left Mouse Button Drag Event
Register for: Left Mouse Button Up Event

(D) Events Services:


// We care about these events, inform us if these events happen

// service routine left mouse button click-down


(D1): Left Mouse Button Down
HeroBall = Create a new ball at current mouse position
// Draw all balls (including HeroBall)
DrawAllBalls(AllWorldBalls, HeroBall)

// service routine for left mouse button drag


(D2): Left Mouse Button Drag
RefineRadiusAndVelocityOfHeroBall()
// Draw all balls (including HeroBall)
DrawAllBalls(AllWorldBalls, HeroBall)

// service routine for left mouse button release


(D3): Left Mouse Button Up
InsertHeroBallToAllWorldBalls()
// Draw all balls
DrawAllBalls(AllWorldBalls, null)

Listing 1.4. A simple event-driven program specification.

user applications to override the default behavior. During SystemInitiali


zation(), the user application can register an alternate service routine for
an event by toggling the override.

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

ming solutions are based on an algorithmic organization of control structures in


the main() function, an event-driven programming solution is based on the spec-
ification of events that cause changes to a defined application state. These are
different paradigms for designing programming solutions. The key here is that,
as programmers of an event-driven program, we have no explicit control over the
algorithmic organization of the events: over which, when, or how often an event
Application state. This is should occur.
the collection of information Listing 1.4 shows an event-driven program that implements the left mouse
that describes the computa-
tional purpose of the appli-
button operations for our ball-shooting program. We see that during system ini-
cation. For example, in the tialization (A), the program defines an appropriate application state (A1) and reg-
ball-shooting program, the ap- isters left mouse button (LMB) down/drag/up events (A2). The corresponding
plication is defined to create event service routines (D1, D2, and D3) are also defined. At the end of each event
a HeroBall and simulate the
collection of balls in the ap-
service routine, we redraw all the balls to ensure that the user can see an up-to-
plication window. Thus, these date display at all times. Notice the absence of any control structure organizing
objects are defined at Label the initialization and service routines. Recall that this is an event-driven program:
(A1) in Listing 1.4. the overall control structure is defined in the MainEventLoop(), which is external
to our solution.
Listings 1.5–1.6 show how our program from Listing 1.4 is linked with the
pre-defined MainEventLoop() from the GUI system. The MainEventLoop()
calls the SystemInitialization() function defined in our solution (A). As de-
scribed, after the initialization, our entire program is essentially the three event
service routines (D1, D2, and D3). However, we have no control over the invo-
cation of these routines. Instead, a user performs actions that trigger events that
drive these routines. These routines in turn change the application state. In this
way, an event-driven programming solution is based on specification of events
(LMB events) that cause changes to a defined application state (AllWorldBalls
and HeroBall). Since the user command-parsing switch statement (D in List-
ing 1.5) in the MainEventLoop() contains a case and the corresponding default
behavior for every possible user actions, without any added complexity, our solu-
tion honors the non–application-specific actions in the environment (e.g., iconize,
moving of application window).
In the context of event-driven programming, an event can be perceived as
an asynchronous notification that something interesting has happened. The mes-
senger for the notification is the underlying GUI system. The mechanism for
receiving an event is via overriding the corresponding event service routine.
From the above discussion, we see that the registration for services of appro-
priate events is the core of designing and developing solutions for event-driven
programs. Before we begin developing a complete solution for our ball-shooting
program, let us spend some time understanding events.

i i

i i
i i

i i

1.2. Event-Driven Programming 23

MainEventLoop: We, as GUI programmers, are users of this function. We can-


not change this function.

GUISystem::MainEventLoop() {
// This will call the user defined function
(A): SystemInitialization()

(B): loop forever {

// stop and wait for the next event


(C): WaitFor ( GUISystem::NextEvent) {

(D): switch (GUISystem::NextEvent) {

(D1): case GUISystem::LeftMouseButtonDown:


if (user application registered for this event)
Invoke LeftMouseButtonDownServiceRoutine( currentMousePosition )
else
Execute default GUISystem routine.

(D2): case GUISystem::LeftMouseButtonDrag:


if (user application registered for this event)
Invoke LeftMouseButtonDragServiceRoutine( currentMousePosition )
else
Execute default GUISystem routine.

(D3): case GUISystem::LeftMouseButtonUp:


if (user application registered for this event)
Invoke LeftMouseButtonUpServiceRoutine( currentMousePosition )
else
Execute default GUISystem routine.

// There are many other events that do not concern us


.
.
.

} // end of switch(GUISystem::NextEvent)
} // end of loop forever
} // end of GUISystem::MainEventLoop() function. Program terminates.

Listing 1.5. MainEventLoop() to which our solution links.

i i

i i
i i

i i

24 1. Event-Driven Programming

User solution program: We, as GUI programmer, will program the following.

// will be invoked from the MainEventLoop during initialization.


(A): SystemInitialization() {
(A1): // Defines Application State
AllWorldBalls=NULL; // A set of defined Balls, initialze to empty
HeroBall = null
(A2): // Registers event service routines
GUISystem::RegisterServiceRoutine(GUISystem::LMBDown, LMBDownRoutine)
GUISystem::RegisterServiceRoutine(GUISystem::LMBDrag, LMBDragRoutine)
GUISystem::RegisterServiceRoutine(GUISystem::LMBUp, LMBUpRoutine)
// "LMB": Left Mouse Button
}

// invoked from MainEventLoop when corresponding events are triggered.


(D): Event Service Routines:
D1: LMBDownRoutine( mousePosition ) {
HeroBall = new ball at mousePosition
// Draw all balls (including HeroBall)
DrawAllBalls(AllWorldBalls, HeroBall)
}
D2: LMBDragRoutine( mousePosition ) {
RefineRadiusAndVelocityOfHeroBall( mousePosition )
// Draw all balls (including HeroBall)
DrawAllBalls(AllWorldBalls, HeroBall)
}
D3: LMBUpRoutine( mousePosition ) {
InsertHeroBallToAllWorldBalls()
// Draw all balls
DrawAllBalls(AllWorldBalls, null)
}

Listing 1.6. Our solution that will link to MainEventLoop().

1.3 Triggering and Translation of Events


A typical modern computer comes with two attached input devices: the mouse
and the keyboard. However, our solution for the ball-shooting program requires
input events generated by devices ranging from slider bars (for velocity control)

i i

i i
i i

i i

1.3. Triggering and Translation of Events 25

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.

1.3.1 The Operating System and Window Manager

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.

1.3.2 The GUI API


In-focus GUI element. The
The GUI API defines icons or graphical objects to represent virtual input and in-focus terminology also ap-
output devices. For example, a GUI API may define a 3D-looking rectangle to plies to individual GUI ele-
ments. For example, one can
represent a “button,” or a horizontal line to represent the “range” with a small 3D-
refer to an active slider bar
looking rectangle on top of the line to represent the “slider knob.” These virtual as being the in-focus GUI el-
devices are examples of GUI elements. Notice that the application’s main window ement.

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:

1. Container main window;

2. Drawing area for the balls;

3. Two slider bars;

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

1.4. Categories of Events 27

application. In this case, it would be impossible for our application to determine if


the event was triggered by a user’s action or from the OS. Fortunately, in general
there is no need for our application to be aware of the true triggering origin of an
event.

1.4 Categories of Events


We classify events into three categories: user events, application events, and
GUI/window manager events. In this section, we describe each of these event
category and discuss the application’s role in servicing these events.

1.4.1 The User

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.

• General. These are input actions defined by the windowing environment.


For example, a user clicks and drags in the window title-bar area expecting
to move the entire application window. The servicing of these types of
events requires collaboration between our application and the GUI system.
We will discuss the servicing of these types of events in more detail when
explaining events that originate from the GUI system in Section 1.4.3.

Notice that the meaning of a user’s action is context-sensitive. It depends on


where the action is performed: click and drag in the application screen area vs.
slider bar vs. application window title-bar area. In any case, the underlying GUI
system is responsible for parsing the context and determining which GUI element
should receive a particular event.

i i

i i
i i

i i

28 1. Event-Driven Programming

1.4.2 The Application

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.

1.4.3 The Window Manager and the GUI System

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:

– before resource allocation;


– after resource allocation but before initialization;
– after initialization but before initial drawing.

i i

i i
i i

i i

1.4. Categories of Events 29

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.

• External environment requests attention. These are events indicating


that there are changes in the windowing environment that potentially re-
quire application attention. For example, a user has moved another appli-
cation window to cover a portion of our application window, or a user has
minimized our application window. The GUI system and the windowing
environment typically have appropriate service routines for these types of
events. An application would only choose to service these events when
special actions must be performed. For example, for a real-time simulation
program, the application may choose to suspend the simulation if the appli-
cation window is minimized. In this situation, an application must service
the minimize and maximize events.

• External environment requests application collaboration. These are


typically events requesting the application’s collaboration to complete the
service of some general user actions (see Section 1.4.1). For example, if
a user click-drags the application window’s title bar, the window manager
reacts by letting the user “drag” the entire application window. This “drag”
operation is implemented by continuously erasing and redrawing the entire
application window at the current mouse pointer position on the computer
display. The GUI system has full knowledge of the appearance of the appli-
cation window (e.g., the window frames, the menus), but it has no knowl-
edge of the application window content (e.g., how many free-falling balls
traveling at what velocity). In this case, the GUI system redraws the appli-
cation window frame and generates a Redraw/Paint event for the applica-
tion, requesting assistance in completing the service of the user’s “drag” op-
eration. As an application in a shared window environment, our application
is expected to honor and service these types of events. The most common
events in this category are Redraw/Paint and Resize. Redraw/Paint is
the single most important event that an application must service because
it supports the most common operations a user may perform in a shared
window environment. Resize is also an important event to which the ap-
plication must respond because the application is in charge of GUI element
placement policy (e.g., if window size is increased, how the GUI elements
should be placed in the larger window).

i i

i i
i i

i i

30 1. Event-Driven Programming

1.5 Servicing of Events


As we have seen, event service routines handle events forwarded to our applica-
tion. These routines are the core of our programming solution. In the presence of
relevant events, the MainEventLoop() calls these functions and passes the con-
trol back to our program code. For this reason, these service routines are also
referred to as callback functions.

1.5.1 Registration of Event Service Routines

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.

1.5.2 Characteristics of Event Service Routines

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

1.5. Servicing of Events 31

programming, it is often tempting to anticipate/poll subsequent events with


a control structure in the service routine. For example, when servicing the
left mouse button down event, we know that the mouse drag event will hap-
pen next. After allocating and defining the circle center, we have properly
initialized data to work with the HeroBall object. It may seem easier to
simply include a while-loop to poll and service mouse drag events. How-
ever, because there are other external events that may happen at any time
(e.g., Timer event, external Redraw events), this monopolizing of control
becomes a bad design decision and may cause the program to malfunction.

• An event service routine should be stateless, and individual invocations


should be independent. In terms of implementation, this essentially means
that event service routines should not define local static variables to record
application state information for subsequent invocations. Since the applica-
tion has no control over when or how often events are triggered, it follows
that it is not possible to predict the next invocation of a service routine.
This means when a service routine is invoked, it can be difficult to evalu-
ate the validity of state information stored in the local static variables. The
use of static variables in event service routines can easily lead to disas-
trously and unnecessarily complex solutions. One can always define extra
state variables in the application state to record temporary state informa-
tion that must persist over multiple event services. As we will see in our
final event-driven ball-shooting solution, the DefiningNewHeroBall flag
in Listing 1.7 is one such example.

• An event service routine should check for invocation conditions regard-


less of common sense logical sequence. For example, logically, a mouse
drag event should never happen unless a mouse down event has already oc-
curred. In reality, a user may depress a mouse button from outside of our
application window and then drag the mouse into our application window.
In this case, we will receive a mouse drag event without the correspond-
ing mouse down event. For this reason, the mouse drag service routine
should check the invocation condition that the proper initialization has in-
deed happened. Notice that in Listing 1.7, we do not include proper in-
vocation condition checking. For example, in the LMBDragRoutine(), we
do not verify that LMBDownRotine() has been invoked (by checking the
DefiningNewHeroBall flag). In a real system, this may cause the program
to malfunction and/or crash.

i i

i i
i i

i i

32 1. Event-Driven Programming

1.6 The Event-Driven Ball-Shooting Program


In Section 1.1, we began developing a control-driven programming solution to the
ball-shooting program based on verbalizing the conditions (controls) under which
the appropriate actions should be taken:

while favorable condition, parse the input ...

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

• define the application state;

• describe how user actions change the application state;

• map the user actions to events that the GUI system supports;

• register corresponding event service routines to service the user actions.

The specification from p. 10 detailed the behaviors of our ball-shooting program.


The description is based on actions performed on familiar input devices (e.g.,
slider bars and mouse). These actions change the application state and thus the
appearance of the application window. This specification describes the second and
third items from the above list without explicitly defining the application state.
Our job in designing a solution is to derive the implicitly defined application state
and design the appropriate service routines.
Listing 1.7 presents our event-driven programming solution. As expected, the
application state (A1) is defined in SystemInitialization(). The AllWorld
Balls set and HeroBall can be derived from the specification on p. 10. The
DefiningNewHeroBall flag is a transient (temporary) application state designed
to support user actions across multiple events (click-and-drag). Using transient
application states is a common approach to support consecutive interrelated events.
Listing 1.7 shows the registration of three types of service routines (A2):

1. user-generated application-specific events (A2S1);

2. an application-defined event (A2S2);

3. a GUI system–generated event requesting collaboration (A2S3).

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

You might also like