100% found this document useful (9 votes)
104 views75 pages

Introduction To 3D Game Programming and DirectX 10 1st Edition by Frank Luna 1598220535 978-1598220537instant Download

The document provides an overview of 'Introduction to 3D Game Programming with DirectX 10' by Frank D. Luna, detailing its structure and intended audience, which includes intermediate C++ programmers and those familiar with other graphics APIs. It emphasizes the prerequisites for readers, such as understanding high school mathematics and competency in Visual Studio, and outlines the required tools and libraries for programming with Direct3D 10. The book aims to teach the fundamentals of interactive computer graphics and game development using Direct3D, progressing from basic concepts to more advanced techniques and effects.

Uploaded by

bresnyshenna
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 (9 votes)
104 views75 pages

Introduction To 3D Game Programming and DirectX 10 1st Edition by Frank Luna 1598220535 978-1598220537instant Download

The document provides an overview of 'Introduction to 3D Game Programming with DirectX 10' by Frank D. Luna, detailing its structure and intended audience, which includes intermediate C++ programmers and those familiar with other graphics APIs. It emphasizes the prerequisites for readers, such as understanding high school mathematics and competency in Visual Studio, and outlines the required tools and libraries for programming with Direct3D 10. The book aims to teach the fundamentals of interactive computer graphics and game development using Direct3D, progressing from basic concepts to more advanced techniques and effects.

Uploaded by

bresnyshenna
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/ 75

Introduction to 3D Game Programming and DirectX

10 1st edition by Frank Luna 1598220535


978-1598220537 download

https://ebookball.com/product/introduction-to-3d-game-
programming-and-directx-10-1st-edition-by-frank-
luna-1598220535-978-1598220537-25194/

Instantly Access and Download Textbook at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Introduction to 3D Game Programming with DirectX 11 1st edition by


Frank Luna 1937585964 9781937585969

https://ebookball.com/product/introduction-to-3d-game-
programming-with-directx-11-1st-edition-by-frank-
luna-1937585964-9781937585969-25192/

Introduction to 3D Game Programming with DirectX 9 0 1st Edition by


Frank Luna, Rod Lopez ISBN 1556229135 9781556229138

https://ebookball.com/product/introduction-to-3d-game-
programming-with-directx-9-0-1st-edition-by-frank-luna-rod-lopez-
isbn-1556229135-9781556229138-10340/

Introduction to Game Programming Using C and Unity 3D 1st edition by


Vahe Karamian 0997148403 978-0997148404

https://ebookball.com/product/introduction-to-game-programming-
using-c-and-unity-3d-1st-edition-by-vahe-
karamian-0997148403-978-0997148404-25168/

IDG Books WorldWide 1st Edition by DirectX 3D Graphics Programming


Bible ISBN

https://ebookball.com/product/idg-books-worldwide-1st-edition-by-
directx-3d-graphics-programming-bible-isbn-11082/
Introduction to Game Programming with C 1st Edition by Alan Thorn ISBN
1598220322 9781598220322

https://ebookball.com/product/introduction-to-game-programming-
with-c-1st-edition-by-alan-thorn-
isbn-1598220322-9781598220322-25226/

Introduction to Computer Graphics Using Java 2D and 3D Undergraduate


Topics in Computer Science 1st Edition by Frank Klawonn ISBN
1447127323 9781447127321

https://ebookball.com/product/introduction-to-computer-graphics-
using-java-2d-and-3d-undergraduate-topics-in-computer-
science-1st-edition-by-frank-klawonn-
isbn-1447127323-9781447127321-19850/

Delphi Graphics and Game Programming Exposed with DirectX For versions
5 0 7 0 Table of Contents 1st Edition by Delphi Graphics

https://ebookball.com/product/delphi-graphics-and-game-
programming-exposed-with-directx-for-versions-5-0-7-0-table-of-
contents-1st-edition-by-delphi-graphics-11194/

An Introduction to Linear Programming and Game Theory 3rd edition by


Paul Thie, Gerard Keough 1118165454 9781118165454

https://ebookball.com/product/an-introduction-to-linear-
programming-and-game-theory-3rd-edition-by-paul-thie-gerard-
keough-1118165454-9781118165454-25152/

3D Game Programming All in One 1st Edition by Kenneth Finney ISBN


159200136X 9781592001361

https://ebookball.com/product/3d-game-programming-all-in-one-1st-
edition-by-kenneth-finney-isbn-159200136x-9781592001361-23550/
Introduction to 3D Game Programming with DirectX 10

Introduction to 3D Game Programming with DirectX 10

by Frank D. LunaÂ


Wordware Publishing © 2008

Introduction to 3D Game Programming with DirectX 10


Frank D. Luna
Wordware Publishing, Inc.

Library of Congress Cataloging-in-Publication Data

Luna, Frank D.
Introduction to 3D game programming with DirectX 10 / by Frank D. Luna.
p. cm.
Includes bibliographical references and index.
ISBN-13: 978-1-59822-053-7 (pbk.)
ISBN-10: 1-59822-053-5 (pbk.)
1. Computer games—Programming. 2. DirectX. 3. Three-dimensional display
systems. I. Title.
QA76.76.C672L834 2008
794.8’1536—dc22 2008025034

© 2008, Wordware Publishing, Inc.

All Rights Reserved

1100 Summit Avenue, Suite 102


Plano, Texas 75074

No part of this book may be reproduced in any form or by any means without
permission in writing from Wordware Publishing, Inc.

ISBN-13: 9781598220537

ISBN-10: 1-59822-053-5

10 9 8 7 6 5 4 3 2 1
0806

DirectX is a registered trademark of Microsoft Corporation in the United States and


other countries. Other brand names and product names mentioned in this book are
trademarks or service marks of their respective companies. Any omission or misuse
(of any kind) of service marks or trademarks should not be regarded as intent to
infringe on the property of others. The publisher recognizes and respects all marks
used by companies, manufacturers, and developers as a means to distinguish their
products.

This book is sold as is, without warranty of any kind, either express or implied,
respecting the contents of this book and any disks or programs that may accompany
it, including but not limited to implied warranties for the book’s quality, performance,
merchantability, or fitness for any particular purpose. Neither Wordware Publishing,
Inc. nor its dealers or distributors shall be liable to the purchaser or any other person
or entity with respect to any liability, loss, or damage caused or alleged to have
been caused directly or indirectly by this book.

All inquiries for volume purchases of this book should be addressed to Wordware
Publishing, Inc., at the above address. Telephone inquiries may be made by calling:

(972) 423-0090

Dedication

To my parents, Frank and Kathryn

Acknowledgments

I would like to thank Rod Lopez, Jim Leiterman, Hanley Leung, Rick Falck, Tybon
Wu, Tuomas Sandroos, and Eric Sandegren for putting in the time to review this
book for both accuracy and improvements. I want to thank Tyler Drinkard for
building some of the 3D models and textures used in the demo programs of this
book. I also want to thank Dale E. La Force, Adam Hault, Gary Simmons, James
Lambers, and William Chin for their assistance. Lastly, I want to thank the staff at
Wordware Publishing, in particular, Tim McEvoy, Beth Kohler, Martha McCuller, and
Denise McEvoy, and cover designer Alan McCuller.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Introduction
This book presents an introduction to programming interactive computer graphics,
with an emphasis on game development, using Direct3D 10. It teaches the
fundamentals of Direct3D and shader programming, after which the reader will be
prepared to go on and learn more advanced techniques. The book is divided into
three main parts. Part I explains the mathematical tools that will be used throughout
this book. Part II shows how to implement fundamental tasks in Direct3D, such as
initialization, defining 3D geometry, setting up cameras, creating vertex, pixel, and
geometry shaders, lighting, texturing, blending, and stenciling. Part III is largely
about applying Direct3D to implement a variety of interesting techniques and special
effects, such as working with meshes, terrain rendering, picking, particle systems,
environment mapping, normal mapping, shadows, and rendering to textures.

For the beginner, this book is best read front to back. The chapters have been
organized so that the difficulty increases progressively with each chapter. In this
way, there are no sudden jumps in complexity that leave the reader lost. In general,
for a particular chapter, we will use the techniques and concepts previously
developed. Therefore, it is important that you have mastered the material of a
chapter before continuing. Experienced programmers can pick the chapters of
interest.

Finally, you may be wondering what kinds of games you can create after reading
this book. The answer to that question is best obtained by skimming through this
book and seeing the types of applications that are developed. From that you should
be able to visualize the types of games that can be developed based on the
techniques taught in this book and some of your own ingenuity.

Intended Audience
This book was designed with the following three audiences in mind:

Intermediate level C++ programmers who would like an introduction to 3D


programming using the latest iteration of Direct3D.

3D programmers experienced with an API other than DirectX (e.g., OpenGL)


who would like an introduction to Direct3D 10.

Experienced Direct3D 9 programmers wishing to learn the latest iteration of


Direct3D.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Prerequisites
It should be emphasized that this is an introduction to Direct3D 10, shader
programming, and game programming; it is not an introduction to general computer
programming. The reader should satisfy the following prerequisites:

An understanding of high school mathematics: algebra, trigonometry, and


(mathematical) functions, for example.

Competency with Visual Studio: should know how to create projects, add
files, and specify external libraries to link, for example.

Intermediate C++ and data structure skills: comfortable with pointers, arrays,
operator overloading, linked lists, inheritance, and polymorphism, for example.

Familiarity with Windows programming with the Win32 API is helpful, but not
required; we provide a Win32 primer in Appendix A.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Required Development Tools and Hardware


To program Direct3D 10 applications, you will need the DirectX 10 SDK; the latest
version can be downloaded from http://msdn2.microsoft.com/en-
us/xna/aa937788.aspx. Once downloaded, follow the instructions given by the
installation wizard.

As of the March 2008 DirectX SDK release, the SDK will only officially support
versions of Visual Studio 2005 and Visual Studio 2008.

Direct3D 10 requires Direct3D 10-capable hardware. The demos in this book were
tested on a GeForce 8800 GTS.

Online Step-by-step instructions for setting up a Direct3D 10 project in Visual


Studio .NET 2005 and Visual Studio .NET 2008 are provided on this
book’s website (www.d3dcoder.net) and the publisher’s website
(www.wordware.com/files/0535dx10).

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Use of the D3DX Library


Since version 7.0, DirectX has shipped with the D3DX (Direct3D Extension) library.
This library provides a set of functions, classes, and interfaces that simplify common
3D graphics-related operations, such as math operations, texture and image
operations, mesh operations, and shader operations (e.g., compiling and
assembling). That is to say, D3DX contains many features that would be a chore to
implement on your own.

We use the D3DX library throughout this book because it allows us to focus on
more interesting material. For instance, we would rather not spend pages explaining
how to load various image formats (such as BMPs and JPEGs) into a Direct3D
texture interface when we can do it in a single call to the D3DX function
D3DX10CreateTextureFromFile. In other words, D3DX makes us more
productive and lets us focus more on actual content rather than spending time
reinventing the wheel.

Other reasons to use D3DX:

D3DX is general and can be used with a wide range of different types of 3D
applications.

D3DX is fast, at least as fast as general functionality can be.

Other developers use D3DX; therefore, you will most likely encounter code
that uses D3DX. Consequently, whether you choose to use D3DX or not, you
should become familiar with it so that you can read code that uses it.

D3DX already exists and has been thoroughly tested. Furthermore, it


becomes more improved and feature rich with each iteration of DirectX.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Using the DirectX SDK Documentation and SDK Samples


Direct3D is a huge API and we cannot hope to cover all of its details in this one
book. Therefore, to obtain extended information it is imperative that you learn how to
use the DirectX SDK documentation. You can launch the C++ DirectX online
documentation by executing the directx_sdk.chm file in the DirectX
SDK\Documentation\DirectX10 directory, where DirectX SDK is the directory to
which you installed DirectX. In particular, you will want to navigate to the Direct3D
10 section (see Figure 1).

Figure 1: The Direct3D Programming Guide in the DirectX


documentation.

The DirectX documentation covers just about every part of the DirectX API;
therefore it is very useful as a reference, but because the documentation doesn’t go
into much depth, or assumes some previous knowledge, it isn’t the best learning
tool. However, it does get better and better with every new DirectX version released.

As said, the documentation is primarily useful as a reference. Suppose you come


across a DirectX-related type or function, such as the function
D3DXMatrixInverse, for which you would like more information. You simply do a
search in the documentation index and you get a description of the object type or,
in this case, function, as shown in Figure 2.
Figure 2: Index of the DirectX documentation.
Note In this book we may direct you to the documentation for further details from
time to time.

The SDK documentation also contains some introductory tutorials at the URL
/directx_sdk.chm::/d3d10_graphics_tutorials.htm (or just type “tutorial” in the index
search). These tutorials roughly correspond to some of the topics in the first part of
this book. We recommend that you study these tutorials at the same time you read
through the first part of this book so that you can get alternative explanations and
examples.

We would also like to point out the available Direct3D sample programs that ship
with the DirectX SDK. The C++ Direct3D samples are located in the DirectX
SDK\Samples\C++\Direct3D10 directory. Each sample illustrates how to implement a
particular effect in Direct3D. These samples are fairly advanced for a beginning
graphics programmer, but by the end of this book you should be ready to study
them. Examination of the samples is a good “next step” after finishing this book.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Clarity
We want to emphasize that the program samples for this book were written with
clarity in mind and not performance. Thus, many of the samples may be
implemented inefficiently. Keep this in mind if you are using any of the sample code
in your own projects, as you may wish to rework it for better efficiency.

TeamUnknown Release
Introduction
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Sample Programs and Online Supplements


The website for this book (www.d3dcoder.net) plays an integral part in getting the
most out of this book. On the website you will find the complete source code and
project files for every sample in this book. In many cases, DirectX programs are too
large to fully embed in a textbook; therefore, we only embed relevant code
fragments based on the ideas being shown. It is highly recommended that the
reader study the corresponding demo code to see the program in its entirety. (We
have aimed to make the demos small and focused for easy study.) As a general
rule, the reader should be able to implement a chapter’s demo(s) on his or her own
after reading the chapter and spending some time studying the demo code. In fact,
a good exercise is trying to implement the samples on your own using the book and
sample code as a reference.

In addition to sample programs, the website also contains a message board. We


encourage readers to communicate with each other and post questions on topics
they do not understand or need clarification on. In many cases, getting alternative
perspectives and explanations to a concept shortens the time it takes to
comprehend it.

And lastly, additional program samples and tutorials may be added to the website
on topics that we could not fit into this book for one reason or another.

TeamUnknown Release
Part I - Mathematical Prerequisites
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Part I: Mathematical Prerequisites


Chapter List
Chapter 1: Vector Algebra
Chapter 2: Matrix Algebra
Chapter 3: Transformations

Part Overview
Video games attempt to simulate a virtual world; however, computers, by their very
nature, crunch numbers. Thus the problem of how to convey a world to a computer
arises. The answer is to describe our worlds, and the interactions therein,
completely mathematically. Consequently, mathematics plays a fundamental role in
video game development.

In this prerequisites part, we introduce the mathematical tools that will be used
throughout this book. The emphasis is on vectors, coordinate systems, matrices,
and transformations, as these tools are used in just about every sample program of
this book. In addition to the mathematical explanations, a survey and demonstration
of the relevant classes and functions from the D3DX math library are provided.

Note that the topics covered here are only those essential to understanding the rest
of this book; it is by no means a comprehensive treatment of video game
mathematics, as entire books are devoted to this topic. For readers desiring a more
complete reference to video game mathematics, we recommend [Verth04] and
[Lengyel02].

Chapter 1, “Vector Algebra”

Vectors are, perhaps, the most fundamental mathematical objects used in computer
games. We use vectors to represent positions, displacements, directions, velocities,
and forces, for example. In this chapter, we study vectors and the operations used
to manipulate them.

Chapter 2, “Matrix Algebra”

Matrices provide an efficient and compact way of representing transformations. In


this chapter, we become familiar with matrices and the operations defined on them.

Chapter 3, “Transformations”

This chapter examines three fundamental geometric transformations: scaling,


rotation, and translation. We use these transformations to manipulate 3D objects in
space. In addition, we explain change of coordinate transformations, which are used
to transform coordinates representing geometry from one coordinate system into
another.

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Chapter 1: Vector Algebra


Overview
Vectors play a crucial role in computer graphics, collision detection, and physical
simulation, all of which are common components in modern video games. Our
approach here is informal and practical; for a book dedicated to 3D game/graphics
math, we recommend [Verth04]. We emphasize the importance of vectors by noting
that they are used in just about every demo program in this book.

Objectives:

To learn how vectors are represented geometrically and numerically.

To discover the operations defined on vectors and their geometric


applications.

To become familiar with the D3DX library’s vector math functions and
classes.

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.1 Vectors
A vector refers to a quantity that possesses both magnitude and direction.
Quantities that possess both magnitude and direction are called vector-valued
quantities. Examples of vector-valued quantities are forces (a force is applied in a
particular direction with a certain strength — magnitude), displacements (the net
direction and distance a particle moved), and velocities (speed and direction). Thus,
vectors are used to represent forces, displacements, and velocities. We also use
vectors to specify pure directions, such as the direction the player is looking in a 3D
game, the direction a polygon is facing, the direction in which a ray of light travels,
or the direction in which a ray of light reflects off a surface.

A first step in characterizing a vector mathematically is geometrically: We graphically


specify a vector by a directed line segment (see Figure 1.1), where the length
denotes the magnitude of the vector and the aim denotes the direction of the
vector. We note that the location in which we draw a vector is immaterial because
changing the location does not change the magnitude or direction (the two
properties a vector possesses). That is, we say two vectors are equal if and only if
they have the same length and they point in the same direction. Thus, the vectors u
and v drawn in Figure 1.1a are actually equal because they have the same length
and point in the same direction. In fact, because location is unimportant for vectors,
we can always translate a vector without changing its meaning (since a translation
changes neither length nor direction). Observe that we could translate u such that it
completely overlaps with v (and conversely), thereby making them indistinguishable
— hence their equality. As a physical example, the vectors u and v in Figure 1.1b
both tell the ants at two different points, A and B, to move north ten meters from
their current location. Again we have that u = v. The vectors themselves are
independent of position; they simply instruct the ants how to move from where they
are. In this example, they tell the ants to move north (direction) ten meters (length).

Figure 1.1: (a) Vectors drawn on a 2D plane. (b) Vectors instructing ants to
move ten meters north.

1.1.1 Vectors and Coordinate Systems


We could now define useful geometric operations on vectors, which can then be
used to solve problems involving vector-valued quantities. However, since the
computer cannot work with vectors geometrically, we need to find a way of
specifying vectors numerically instead. So what we do is introduce a 3D coordinate
system in space, and translate all the vectors so that their tails coincide with the
origin (Figure 1.2). Then we can identify a vector by specifying the coordinates of its
head, and write v = (x, y, z) as shown in Figure 1.3. Now we can represent a
vector with three floats in a computer program.

Figure 1.2: We translate v so that its tail coincides with the origin of the
coordinate system. When a vector’s tail coincides with the origin, we say that it
is in standard position.

Figure 1.3: A vector specified by coordinates relative to a coordinate


system.

Consider Figure 1.4, which shows a vector v and two frames in space. (Note that
we use the terms frame, frame of reference, space, and coordinate system to mean
the same thing in this book.) We can translate v so that it is in standard position in
either of the two frames. Observe, however, that the coordinates of the vector v
relative to frame A are different from the coordinates of the vector v relative to frame
B. In other words, the same vector has a different coordinate representation for
distinct frames.

Figure 1.4: The same vector v has different coordinates when described relative
to different frames.

The idea is analogous to, say, temperature. Water boils at 100º Celsius or 212º
Fahrenheit. The physical temperature of boiling water is the same no matter the
scale (i.e., we can’t lower the boiling point by picking a different scale), but we
assign a different scalar number to the temperature based on the scale we use.
Similarly, for a vector, its direction and magnitude, which are embedded in the
directed line segment, does not change; only the coordinates of it change based on
the frame of reference we use to describe it. This is important because it means
whenever we identify a vector by coordinates, those coordinates are relative to
some frame of reference. Often in 3D computer graphics we will utilize more than
one frame of reference and, therefore, will need to keep track of which frame the
coordinates of a vector are described relative to; additionally, we will need to know
how to convert vector coordinates from one frame to another.

Note We see that both vectors and points can be described by coordinates (x, y, z)
relative to a frame. However, they are not the same; a point represents a
location in 3-space, whereas a vector represents a magnitude and direction.
Points are discussed further in §1.5.

1.1.2 Left-Handed Versus Right-Handed Coordinate Systems


Direct3D uses a so-called left-handed coordinate system. If you take your left hand
and aim your fingers down the positive x-axis, and then curl your fingers toward the
positive y-axis, your thumb points roughly in the direction of the positive z-axis.
Figure 1.5 illustrates the differences between a left-handed and right-handed
coordinate system.

Figure 1.5: On the left we have a left-handed coordinate system. Observe that
the positive z-axis goes into the page. On the right we have a right-handed
coordinate system. Observe that the positive z-axis comes out of the
page.

Observe that for the right-handed coordinate system, if you take your right hand and
aim your fingers down the positive x-axis, and then curl your fingers toward the
positive y-axis, your thumb points roughly in the direction of the positive z-axis.

1.1.3 Basic Vector Operations


We now define equality, addition, scalar multiplication, and subtraction on vectors
using the coordinate representation.

Two vectors are equal if and only if their corresponding components are
equal. Let u = (u x , u y , u z ) and v = (v x , v y , v z ). Then u = v if and only if u x =
v x , u y = v y , and u z = v z .

We add vectors componentwise; as such, it only makes sense to add vectors


of the same dimension. Let u = (u x , u y , u z ) and v = (v x , v y , v z ). Then u + v
= (u x + v x , u y + v y , u z + v z ).

We can multiply a scalar (i.e., a real number) and a vector, and the result is
a vector. Let k be a scalar, and let u = (u x , u y , u z ), then ku = (kux , kuy ,
kuz ). This is called scalar multiplication.
z ). This is called scalar multiplication.

We define subtraction in terms of vector addition and scalar multiplication.


That is, u ! v = u + (!1 ! v) = u + (!v) = (u x ! v x , u y ! v y , u z ! v z ).

Example 1.1

Let u = (1,2,3), v = (1,2,3), w = (3, 0, !2), and k = 2. Then,

u + w = (1, 2, 3) + (3, 0, !2) = (4, 2, 1);

u = v;

u ! v = u + (!v) = (1,2,3) + (!1,!2,!3) = (0, 0, 0) = 0;

kw = 2(3, 0, !2) = (6, 0, !4).

The difference in the third line illustrates a special vector, called the zero-vector,
which has zeros for all of its components and is denoted by 0.

Example 1.2

We’ll illustrate this example with 2D vectors to make the drawings simpler. The
ideas are the same as in 3D; we just work with one less component in 2D.

Let v = (2,1). How do v and !1/2v compare geometrically? We note !1/2v


= (!1,!1/2). Graphing both v and !1/2v (Figure 1.6a), we notice that
!1/2v is in the direction directly opposite of v and its length is 1/2 that of v.
Thus, geometrically, negating a vector can be thought of as “flipping” its
direction, and scalar multiplication can be thought of as scaling the length of
the vector.

Figure 1.6: (a) The geometric interpretation of scalar multiplication. (b)


The geometric interpretation of vector addition. (c) The geometric
interpretation of vector subtraction.

Let u = (2,1/2) and v = (1,2). Then v + u = (3,5/2). Figure 1.6b shows what
vector addition means geometrically: We parallel translate u so that its tail
coincides with the head of v. Then, the sum is the vector originating at the
tail of v and ending at the head of u. (We get the same result if we keep u
fixed and translate v so that its tail coincides with the head of u. In this case,
u + v would be the vector originating at the tail of u and ending at the head
of the translated v.) Observe also that our rules of vector addition agree with
what we would intuitively expect to happen physically when we add forces
together to produce a net force: If we add two forces (vectors) in the same
direction, we get another stronger force (longer vector) in that direction. If we
add two forces (vectors) in opposition to each other, then we get a weaker
net force (shorter vector). Figure 1.7 illustrates these ideas.
Figure 1.7: Forces applied to a ball. The forces are combined using
vector addition to get a net force.

Let u = (2,1/2) and v = (1,2). Then v ! u = (!1,3/2). Figure 1.6c shows what
vector subtraction means geometrically. Essentially, the difference v ! u
gives us a vector aimed from the head of u to the head of v. If we instead
interpret u and v as points, then v ! u gives us a vector aimed from the
point u to the point v; this interpretation is important as we will often want the
vector aimed from one point to another. Observe also that the length of v !
u is the distance from u to v, when thinking of u and v as points.

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.2 Length and Unit Vectors


Geometrically, the magnitude of a vector is the length of the directed line segment.
We denote the magnitude of a vector by double vertical bars (e.g., ||u|| denotes the
magnitude of u). Now, given a vector v = (x, y, z), we wish to compute its
magnitude algebraically. The magnitude of a 3D vector can be computed by
applying the Pythagorean theorem twice; see Figure 1.8.

Figure 1.8: The 3D length of a vector can be computed by applying the


Pythagorean theorem twice.

First, we look at the triangle in the xz-plane with sides x, z, and hypotenuse a.
From the Pythagorean theorem, we have . Now look at the triangle
with sides a, y, and hypotenuse ||u||. From the Pythagorean theorem again, we
arrive at the following magnitude formula:

(1.1)

For some applications, we do not care about the length of a vector because we
want to use the vector to represent a pure direction. For such direction-only vectors,
we want the length of the vector to be exactly one. When we make a vector unit
length, we say that we are normalizing the vector. We can normalize a vector by
dividing each of its components by its magnitude:

(1.2)
To verify that this formula is correct, we can compute the length of û:

So û is indeed a unit vector.

Example 1.3

Normalize the vector v = (!1,3,4). We have .

Thus,

To verify that is indeed a unit vector, we compute its length:

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.3 The Dot Product


The dot product is a form of vector multiplication that results in a scalar value; for
this reason, it is sometimes referred to as the scalar product. Let u = (u x , u y , u z )
and v = (v x , v y , v z ); then the dot product is defined as follows:

(1.3)

In words, the dot product is the sum of the products of the corresponding
components.

The dot product definition does not present an obvious geometric meaning. Using
the law of cosines, we can find the relationship,

(1.4)

where ! is the angle between the vectors u and v such that 0 " ! " # (see Figure
1.9). So, Equation 1.4 says that the dot product between two vectors is the cosine
of the angle between them scaled by the vectors’ magnitudes. In particular, if both u
and v are unit vectors, then u ! v is the cosine of the angle between them (i.e., u !
v = cos !).

Figure 1.9: On the left, the angle ! between u and v is an acute angle. On the
right, the angle ! between u and v is an obtuse angle. When we refer to the
angle between two vectors, we always mean the smallest angle, that is, the
angle ! such that 0 " ! " #.

Equation 1.4 provides us with some useful geometric properties of the dot product:

If u ! v = 0, then u $ v (i.e., the vectors are orthogonal).


If u ! v > 0, then the angle ! between the two vectors is less than 90º (i.e.,
the vectors make an acute angle).

If u ! v < 0, then the angle ! between the two vectors is greater than 90º
(i.e., the vectors make an obtuse angle).

Note The word “orthogonal” can be used as a synonym for “perpendicular.”


Example 1.4

Let u = (1, 2, 3) and v = (%4, 0, %1). Find the angle between u and v. First we
make the following computations:

Now, applying Equation 1.4 and solving for theta, we get:

Example 1.5

Consider Figure 1.10. Given v and the unit vector n, find a formula for p using the
dot product.

Figure 1.10: The orthogonal projection of v on n.

First, observe from the figure that there exists a scalar k such that p=kn; moreover,
since we assumed ||n|| = 1, we have ||p|| = ||kn|| = ||k||||n|| = |k|. (Note that k may
be negative if and only if p and n aim in opposite directions.) Using trigonometry, we
have that k = ||v|| cos !; therefore, p = kn = (||v|| cos !)n. However, because n is a
unit vector, we can say this in another way:

In particular, this shows k = v ! n, and this illustrates the geometric interpretation of


v ! n when n is a unit vector. We call p the orthogonal projection of v on n, and it is
commonly denoted by

If we interpret v as a force, p can be thought of as the portion of the force v that


acts in the direction n. Likewise, the vector w = v % p is the portion of the force v
that acts orthogonal to the direction n. Observe that v = p + w, which is to say we
have decomposed the vector v into the sum of two orthogonal vectors p and w.

If n is not of unit length, we can always normalize it first to make it unit length.
Replacing n by the unit vector gives us the more general projection formula:

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.4 The Cross Product


The second form of multiplication vector math defines is the cross product. Unlike
the dot product, which evaluates to a scalar, the cross product evaluates to another
vector; moreover, the cross product is only defined for 3D vectors (in particular,
there is no 2D cross product). Taking the cross product of two 3D vectors u and v
yields another vector, w that is mutually orthogonal to u and v. By that we mean w
is orthogonal to u, and w is orthogonal to v (see Figure 1.11). If u = (u x , u y , u z )
and v = (v x , v y , v z ), then the cross product is computed like so:

(1.5)

Figure 1.11: The cross product of two 3D vectors, u and v, yields another
vector, w, that is mutually orthogonal to u and v. If you take your left hand and
aim the fingers in the direction of the first vector u, and then curl your fingers
toward v along an angle 0 ! " ! #, then your thumb roughly points in the
direction of w = u ! v; this is called the left-hand-thumb rule.
Example 1.6

Let u = (2, 1, 3) and v = (2, 0, 0). Compute w = u ! v and z = v ! u, and then


verify that w is orthogonal to u and that w is orthogonal to v. Applying Equation 1.5
we have,

and
This result makes one thing clear, generally speaking: u ! v $ v ! u. Therefore, we
say that the cross product is anti-commutative. In fact, it can be shown that u ! v =
%v ! u. You can determine the vector returned by the cross product by the left-
hand-thumb rule. If you curve the fingers of your left hand from the direction of the
first vector toward the second vector (always take the path with the smallest angle),
your thumb points in the direction of the returned vector, as shown in Figure 1.11.

To show that w is orthogonal to u and that w is orthogonal to v, we recall from §1.3


that if u " v = 0, then u & v (i.e., the vectors are orthogonal). Because

and

we conclude that w is orthogonal to u and that w is orthogonal to v.

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.5 Points
So far we have been discussing vectors, which do not describe positions. However,
we will also need to specify positions in our 3D programs; for example, the position
of 3D geometry and the position of the 3D virtual camera. Relative to a coordinate
system, we can use a vector in standard position (see Figure 1.12) to represent a
3D position in space; we call this a position vector. In this case, the location of the
tip of the vector is the characteristic of interest, not the direction or magnitude. We
will use the terms “position vector” and “point” interchangeably since a position
vector is enough to identify a point.

Figure 1.12: The position vector, which extends from the origin to the point,
fully describes the location of the point relative to the coordinate
system.

One side effect of using vectors to represent points, especially in code, is that we
can do vector operations that do not make sense for points; for instance,
geometrically, what should the sum of two points mean? On the other hand, some
operations can be extended to points. For example, we define the difference of two
points q ! p to be the vector from p to q. Also, we define a point p plus a vector v
to be the point q obtained by displacing p by the vector v. Conveniently, because
we are using vectors to represent points relative to a coordinate system, no extra
work needs to be done for the point operations just discussed as the vector algebra
framework already takes care of them (see Figure 1.13).
Figure 1.13: (a) The difference q ! p between two points is defined as the
vector from p to q. (b) A point p plus the vector v is defined to be the point q
obtained by displacing p by the vector v.
Note Actually there is a geometrically meaningful way to define a special sum of
points, called an affine combination, which is like a weighted average of
points. However, we do not use this concept in this book.

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.6 D3DX Vectors


In this section, we spend some time becoming familiar with the D3DXVECTOR3
class, which is the class we often use to store the coordinates of both points and
vectors in code relative to some coordinate system. Its class definition is:

typedef struct D3DXVECTOR3 : public D3DVECTOR


{
public:
D3DXVECTOR3() {};
D3DXVECTOR3( CONST FLOAT * );
D3DXVECTOR3( CONST D3DVECTOR& );
D3DXVECTOR3( CONST D3DXFLOAT16 * );
D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

// casting
operator FLOAT* ();
operator CONST FLOAT* () const;

// assignment operators
D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
D3DXVECTOR3& operator *= ( FLOAT );
D3DXVECTOR3& operator /= ( FLOAT );

// unary operators
D3DXVECTOR3 operator + () const;
D3DXVECTOR3 operator - () const;

// binary operators
D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
D3DXVECTOR3 operator * ( FLOAT ) const;
D3DXVECTOR3 operator / ( FLOAT ) const;

friend D3DXVECTOR3 operator * (FLOAT, CONST struct


D3DXVECTOR3& );

BOOL operator == ( CONST D3DXVECTOR3& ) const;


BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;
Note that D3DXVECTOR3 inherits its coordinate data from D3DVECTOR, which is
defined as:

typedef struct _D3DVECTOR {


float x;
float y;
float z;
} D3DVECTOR;

Also observe that the D3DXVECTOR3 overloads the arithmetic operators to do vector
addition, subtraction, and scalar multiplication.

In addition to the above class, the D3DX library includes the following useful vector-
related functions:

FLOAT D3DXVec3Length( // Returns ||v||


CONST D3DXVECTOR3 *pV); // Input v

FLOAT D3DXVec3LengthSq( // Returns ||v||2


CONST D3DXVECTOR3 *pV); // Input v

FLOAT D3DXVec3Dot( // Returns v1 ! v2


CONST D3DXVECTOR3 *pV1, // Input v1
CONST D3DXVECTOR3 *pV2); // Input v2

D3DXVECTOR3 *D3DXVec3Cross(
D3DXVECTOR3 *pOut, // Returns v1 " v2
CONST D3DXVECTOR3 *pV1, // Input v1
CONST D3DXVECTOR3 *pV2); // Input v2

D3DXVECTOR3 *WINAPI D3DXVec3Normalize(


D3DXVECTOR3 *pOut, // Returns v / ||v||
CONST D3DXVECTOR3 *pV, // Input v

Note Remember to link the d3dx10.lib (or d3dx10d.lib for debug builds) library file
with your application to use any D3DX code; moreover, you will also need to
#include <d3dx10.h>.

The following short code provides some examples on how to use the D3DXVECTOR3
class and four of the five functions listed above.

#include <d3dx10.h>
#include <iostream>
using namespace std;

// Overload the "<<" operators so that we can use cout to


// output D3DXVECTOR3 objects.

ostream& operator<<(ostream& os, D3DXVECTOR3& v)


{
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}

int main()
{
// Using constructor, D3DXVECTOR3(FLOAT x, FLOAT y, FLOAT z);
D3DXVECTOR3 u(1.0f, 2.0f, 3.0f);

// Using constructor, D3DXVECTOR3(CONST FLOAT *);


float x[3] = {-2.0f, 1.0f, -3.0f};
D3DXVECTOR3 v(x);

// Using constructor, D3DXVECTOR3() {};


D3DXVECTOR3 a, b, c, d, e;

// Vector addition: D3DXVECTOR3 operator +


a = u + v;

// Vector subtraction: D3DXVECTOR3 operator -


b = u - v;

// Scalar multiplication: D3DXVECTOR3 operator *


c = u * 10;

// ||u||
float L = D3DXVec3Length(&u);

//d = u / ||u||
D3DXVec3Normalize(&d, &u);

// s = u dot v
float s = D3DXVec3Dot(&u, &v);

// e = u x v
D3DXVec3Cross(&e, &u, &v);
cout << "u = " << u << endl;
cout << "v = " << v << endl;
cout << "a = u + v = " << a << endl;
cout << "b = u - v = " << b << endl;
cout << "c = u * 10 = " << c << endl;
cout << "d = u / ||u|| = " << d << endl;
cout << "e = u x v = " << e << endl;
cout << "L = ||u|| = " << L << endl;
cout << "s = u.v = " << s << endl;

return 0;
}

Figure 1.14: Output for the above program.


While we’re on the subject of working with vectors on a computer, we should be
aware of the following. When comparing floating-point numbers, care must be taken
due to floating-point imprecision. Two floating-point numbers that we expect to be
equal may differ slightly. For example, mathematically, we’d expect a normalized
vector to have a length of 1, but in a computer program, the length will only be
approximately 1. Moreover, mathematically, 1 p = 1 for any real number p, but when
we only have a numerical approximation for 1, we see that the approximation raised
to the pth power increases the error; thus, numerical error also accumulates. The
following short program illustrates these ideas:

#include <iostream>
#include <d3dx10.h>
using namespace std;

int main()
{
cout.precision(8);

D3DXVECTOR3 u(1.0f, 1.0f, 1.0f);


D3DXVec3Normalize(&u, &u);

float LU = D3DXVec3Length(&u);

// Mathematically, the length should be 1. Is it numerically?


cout << LU << endl;
if( LU == 1.0f )
cout << "Length 1" << endl;
else
cout << "Length not 1" << endl;

// Raising 1 to any power should still be 1. Is it?


float powLU = powf(LU, 1.0e6f);
cout << "LU^(10^6) = " << powLU << endl;
}

Figure 1.15: Output for the above program.

To compensate for floating-point imprecision, we test if two floating-point numbers


are approximately equal. We do this by defining an EPSILON constant, which is a
very small value we use as a “buffer.” We say two values are approximately equal if
their distance is less than EPSILON. In other words, EPSILON gives us some
tolerance for floating-point imprecision. The following function illustrates how
EPSILON can be used to test if two floating-point values are equal:

const float EPSILON = 0.001f;


bool Equals(float lhs, float rhs)
{
// Is the distance between lhs and rhs less than EPSILON?
return fabs(lhs - rhs) < EPSILON ? true : false; }
TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.7 Summary
Vectors are used to model physical quantities that possess both magnitude
and direction. Geometrically, we represent a vector with a directed line
segment. A vector is in standard position when it is translated parallel to itself
so that its tail coincides with the origin of the coordinate system. A vector in
standard position can be described numerically by specifying the coordinates
of its head relative to a coordinate system.

If u = (u x , u y , u z ) and v = (v x , v y , v z ), then we have the following vector


operations:

Addition: u + v = (u x + v x , u y + v y , u z + v z )

Subtraction: u ! v = (u x ! v x , u y ! v y , u z ! v z )

Scalar multiplication: ku = (kux , kuy , kuz )

Length:

Normalization:

Dot product: u ! v = ||u|| ||v||cos " = u x v x + u y u y + u z v z

Cross product: u " v = (u y v z ! u z v y , u z v x ! u x v z , u x v y ! u y v x )

The D3DXVECTOR3 class is used to describe a 3D vector in code. This class


contains three float data members for representing the x-, y-, and z-
coordinates of a vector relative to some coordinate system. The
D3DXVECTOR3 class overloads the arithmetic operators to do vector addition,
subtraction, and scalar multiplication. Moreover, the D3DX library provides
the following useful functions for computing the length of a vector, the
squared length of a vector, the dot product of two vectors, the cross product
of two vectors, and normalizing a vector:

FLOAT D3DXVec3Length(CONST D3DXVECTOR3 *pV);


FLOAT D3DXVec3LengthSq(CONST D3DXVECTOR3 *pV);
FLOAT D3DXVec3Dot(CONST D3DXVECTOR3 *pV1, CONST D3DXVECTOR3 *pV2);
D3DXVECTOR3* D3DXVec3Cross(D3DXVECTOR3 *pOut,
CONST D3DXVECTOR3 *pV1, CONST D3DXVECTOR3 *pV2);
D3DXVECTOR3* WINAPI D3DXVec3Normalize(D3DXVECTOR3 *pOut,
CONST D3DXVECTOR3 *pV);

TeamUnknown Release
Chapter 1 - Vector Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

1.8 Exercises
1. Let u = (1,2) and v = (3,!4). Perform the following computations and draw
the vectors relative to a 2D coordinate system:

a. u + v

b. u ! v

c. 2u + 1/2v

d. !2u + v

2. Let u = (!1, 3, 2) and v = (3, !4, 1). Perform the following computations:

a. u + v

b. u ! v

c. 3u + 2v

d. !2u + v

3. This exercise shows that vector algebra shares many of the nice properties of
real numbers (this is not an exhaustive list). Assume u = (u x , u y , u z ), v =
(v x , v y , v z ), and w = (w x , w y , w z ). Also assume that c and k are scalars.
Prove the following vector properties:

a. u + v = v + u (Commutative property of addition)


b. u + (v + w) = (u + v) (Associative property of addition)
+w
c. (ck)u = c(ku) (Associative property of scalar
multiplication)
d. k(u + v) = ku + kv (Distributive property 1)
e. u(k + c) = ku + cu (Distributive property 2)

Hint: Just use the definition of the vector operations and the properties of real
numbers. For example,
4. Solve the equation 2((1, 2, 3) ! x) ! (!2, 0, 4) = !2(1, 2, 3) for x.

5. Let u = (!1, 3, 2) and v = (3, !4, 1). Normalize u and v.

6. Let k be a scalar and let u = (u x , u y , u z ). Prove that ||ku|| = |k|||u||.

7. Is the angle between u and v orthogonal, acute, or obtuse?

a. u = (1, 1, 1), v = (2, 3, 4)

b. u = (1, 1, 0), v = (!2, 2, 0)

c. u = (!1, !1, !1), v = (3, 1, 0)

8. Let u = (!1, 3, 2) and v = (3, !4, 1). Find the angle " between u and v.

9. Let u = (u x , u y , u z ), v = (v x , v y , v z ), and w = (w x , w y , w z ). Also let c and k


be scalars. Prove the following dot properties:

a. u ! v = v ! u

b. u ! (v + w) = u ! v + u ! w

c. k(u ! v) = (ku) ! v = u ! (kv)

d. v ! v = ||v||2

e. 0 ! v = 0

Hint: Just use the definition, for example,

10. Use the law of cosines (c 2 = a 2 + b 2 = 2abcos ", where a, b, and c are the
lengths of the sides of a triangle and " is the angle between sides a and b)
to show:
Hint: Consider Figure 1.9 and set c 2 = ||u ! v||, a 2 = ||u||2 , and b 2 = ||v||2 ,
and use the dot product properties from the previous exercise.

11. Let n = (!2, 1). Decompose the vector g = (0, !9.8) into the sum of two
orthogonal vectors, one parallel to n and the other orthogonal to n. Also,
draw the vectors relative to a 2D coordinate system.

12. Let u = (!2, 1, 4) and v = (3, !4, 1). Find w = u " v, and show w ! u = 0
and w ! v = 0.

13. Let the following points define a triangle relative to some coordinate system:
A = (0, 0, 0), B = (0, 1, 3), and C = (5, 1, 0). Find a vector orthogonal to this
triangle.

Hint: Find two vectors on two of the triangle’s edges and use the cross
product.

14. Prove that ||u " v|| = ||u||||v|| sin". Hint: Start with ||u||||v||sin " and use the
trigonometric identity ; then apply
Equation 1.4.

15. Prove that ||u " v|| gives the area of the parallelogram spanned by u and v
(see Figure 1.16).

Figure 1.16: Parallelogram spanned by two 3D vectors u and v; the


parallelogram has base ||v|| and height h.

16. Give an example of 3D vectors u, v, and w such that u " (v " w) # (u " v)
" w. This shows the cross product is generally not associative. Hint:
Consider combinations of the simple vectors i = (1, 0, 0), j = (0, 1, 0), and k
= (0, 0, 1).

17. Prove that the cross product of two nonzero parallel vectors results in the null
vector; that is, u " ku = 0. Hint: Just use the cross product definition.

18. The D3DX library also provides the D3DXVECTOR2 and D3DXVECTOR4
classes for working with 2D and 4D vectors. We will later use 2D vectors to
describe 2D points on texture maps. The purpose of 4D vectors will make
more sense after reading the next chapter when we discuss homogeneous
coordinates. Rewrite the program in §1.6 twice, once using 2D vectors
(D3DXVECTOR2) and a second time using 4D vectors (D3DXVECTOR4). Note
that there is no 2D cross product function, so you can skip that. (Hint:
Search the index for these keywords in the DirectX SDK documentation:
D3DXVECTOR2, D3DXVECTOR4, D3DXVec2, and D3DXVec4.)

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

Chapter 2: Matrix Algebra


Overview
In 3D computer graphics, we use matrices to compactly describe geometric
transformations such as scaling, rotation, and translation, and also to change the
coordinates of a point or vector from one frame to another. This chapter explores
the mathematics of matrices.

Objectives:

To obtain an understanding of matrices and the operations defined on them.

To discover how a vector-matrix multiplication can be viewed as a linear


combination.

To learn what the identity matrix is, and what the transpose and inverse of a
matrix are.

To become familiar with the subset of classes and functions provided by the
D3DX library used for matrix mathematics.

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.1 Definition
An m ! n matrix M is a rectangular array of real numbers with m rows and n
columns. The product of the number of rows and columns gives the dimensions of
the matrix. The numbers in a matrix are called elements or entries. We identify a
matrix element by specifying the row and column of the element using a double
subscript notation Mij, where the first subscript identifies the row and the second
subscript identifies the column.

Example 2.1

Consider the following matrices:

Matrix A is a 4!4 matrix; matrix B is a 3!2 matrix; matrix u is a 1!3 matrix;


and matrix v is a 4!1 matrix.

We identify the element in the fourth row and second column of matrix A by
A42 =!5. We identify the element in the second row and first column of
matrix B by B21 .

Matrices u and v are special matrices in the sense that they contain a single
row or column, respectively. We sometimes call these kinds of matrices row
vectors or column vectors because they are used to represent a vector in
matrix form (e.g., we can freely interchange the vector notations (x, y, z) and
[x, y, z]). Observe that for row and column vectors, it is unnecessary to use a
double subscript to denote the elements of the matrix — we only need one
subscript.

Occasionally we like to think of the rows of a matrix as vectors. For example, we


might write:
where A 1,* = [A11 , A12 , A13 ], A 2,* = [A21 , A22 , A23 ], and A 3,* = [A31 , A32 , A33 ]. In
this notation, the first index specifies the row, and we put an asterisk (*) in the
second index to indicate that we are referring to the entire row vector. Likewise, we
can do the same thing for the columns:

where

In this notation, the second index specifies the column, and we put an asterisk (*) in
the first index to indicate that we are referring to the entire column vector.

We now define equality, addition, scalar multiplication, and subtraction on matrices:

Two matrices are equal if and only if their corresponding elements are equal;
as such, two matrices must have the same number of rows and columns in
order to be compared.

We add two matrices by adding their corresponding elements; as such, it


only makes sense to add matrices that have the same number of rows and
columns.

We multiply a scalar and a matrix by multiplying the scalar with every


element in the matrix.

We define subtraction in terms of matrix addition and scalar multiplication.


That is, A ! B = A + (!1 " B) = A + (!B).

Example 2.2

Let

Then,
TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.2 Matrix Multiplication


The next section defines how to multiply two matrices together. We will see in
Chapter 3 that matrix multiplication is used to transform points and vectors and to
concatenate transformations.

2.2.1 Definition
If A is an m!n matrix and B is an n!p matrix, then the product AB is defined and is
an m!p matrix C, where the ijth entry of the product C is given by taking the dot
product of the ith row vector in A with the jth column vector in B, that is,

(2.1)

So note that in order for the matrix product AB to be defined, we require that the
number of columns in A be equal to the number of rows in B, which is to say, we
require that the dimension of the row vectors in A equal the dimension of the
column vectors in B. If these dimensions did not match, then the dot product in
Equation 2.1 would not make sense.

Example 2.3

Let

The product AB is not defined since the row vectors in A have a dimension of 2
and the column vectors in B have a dimension of 3. In particular, we cannot take
the dot product of the first row vector in A with the first column vector in B because
we cannot take the dot product of a 2D vector with a 3D vector.

Example 2.4

Let
We first point out that the product AB is defined (and is a 2!3 matrix) because the
number of columns of A equals the number of rows of B. Applying Equation 2.1
yields:

Observe that the product BA is not defined because the number of columns in B
does not equal the number of rows in A. This demonstrates that, in general, matrix
multiplication is not commutative; that is, AB ! BA.

2.2.2 Vector-Matrix Multiplication


Consider the following vector-matrix multiplication:

Observe that uA evaluates to a 1!3 row vector in this case. Now, applying Equation
2.1 gives:

Thus,

(2.2)

Equation 2.2 is an example of a linear combination, and it says that the vector-
matrix product uA is equivalent to a linear combination of the row vectors of the
matrix A with scalar coefficients x, y, and z given by the vector u. Note that,
although we show this for a 1!3 row vector and a 3!3 matrix, the result is true in
general. That is, for a 1!n row vector u and an n!m matrix A, we have that uA is a
linear combination of the row vectors in A with scalar coefficients given by u:

(2.3)

2.2.3 Associativity
Matrix multiplication has some nice algebraic properties. For example, matrix
multiplication distributes over addition: A(B + C) = AB + AC. In particular, however,
we will use the associative law of matrix multiplication from time to time, which
allows us to choose the order in which we multiply matrices:

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.3 The Transpose of a Matrix


The transpose of a matrix is found by interchanging the rows and columns of the
matrix. Thus the transpose of an m!n matrix is an n!m matrix. We denote the
transpose of a matrix M as MT.

Example 2.5

Find the transpose for the following three matrices:

The transposes are found by interchanging the rows and columns, thus

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.4 The Identity Matrix


There is a special matrix called the identity matrix. The identity matrix is a square
matrix that has zeros for all elements except along the main diagonal; the elements
along the main diagonal are all ones.

For example, below are 2!2, 3!3, and 4!4 identity matrices.

The identity matrix acts as a multiplicative identity; that is, if A is an m!n matrix, B
is an n!p matrix, and I is the n!n identity matrix, then

In other words, multiplying a matrix by the identity matrix does not change the
matrix. The identity matrix can be thought of as the number 1 for matrices. In
particular, if M is a square matrix, then multiplication with the identity matrix is
commutative:

Example 2.6

Let and let . Verify that MI = IM = M.

Applying Equation 2.1 yields:

and
Thus it is true that MI = IM = M.

Example 2.7

Let u = [!1, 2] and let . Verify that uI = u.

Applying Equation 2.1 yields:

Note that we cannot take the product Iu because the matrix multiplication is not
defined.

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.5 The Inverse of a Matrix


Matrix algebra does not define a division operation, but it does define a
multiplicative inverse operation. The following list summarizes the important
information about inverses:

Only square matrices have inverses; therefore, when we speak of matrix


inverses we assume we are dealing with a square matrix.

The inverse of an n!n matrix M is an n!n matrix denoted as M"1 .

Not every square matrix has an inverse. A matrix that does have an inverse
is said to be invertible, and a matrix that does not have an inverse is said to
be singular.

The inverse is unique when it exists.

Multiplying a matrix with its inverse results in the identity matrix: MM"1 =
M"1 M = I. Note that multiplying a matrix with its own inverse is a case when
matrix multiplication is commutative.

Matrix inverses are useful for solving for other matrices in a matrix equation. For
example, suppose that we are given the matrix equation p! = pM. Further suppose
that we are given p! and M, and want to solve for p. Assuming that M is invertible
(i.e., M"1 exists), we can solve for p like so:

p! = pM

p!M"1 = pMM " 1 Multiply both sides of the equation by M"1 .

p!M"1 = pI MM"1 = I, by definition of inverse.


p!M"1 = p pI = p, by definition of the identity matrix.

Techniques for finding inverses are beyond the scope of this book, but they are
described in any linear algebra textbook (it is not difficult; it is just not worth
digressing into the procedure here). In §2.6 we will learn about a D3DX function that
will find the inverse of a matrix for us, and in the next chapter we will simply give
the inverses of the important types of matrices that we will work with in this book.

To conclude this section on inverses, we present the following useful algebraic


property for the inverse of a product:
This property assumes both A and B are invertible and that they are both square
matrices of the same dimension. To prove that B "1 A "1 is the inverse of AB, we
must show (AB)(B "1 A "1 ) = I and (B "1 A "1 )(AB) = I. This is done as follows:

TeamUnknown Release
Chapter 2 - Matrix Algebra
Introduction to 3D Game Programming with DirectX
10
by Frank D. LunaÂ
Wordware Publishing © 2008

2.6 D3DX Matrices


For transforming points and vectors, we use 1!4 row vectors and 4!4 matrices. The
reason for this will be explained in the next chapter. For now, we just concentrate
on the D3DX class used to represent 4!4 matrices.

To represent 4!4 matrices in D3DX, we use the D3DXMATRIX class, which is


defined as follows:

typedef struct D3DXMATRIX : public D3DMATRIX


{
public:
D3DXMATRIX() {};
D3DXMATRIX( CONST FLOAT * );
D3DXMATRIX( CONST D3DMATRIX& );
D3DXMATRIX( CONST D3DXFLOAT16 * );
D3DXMATRIX(FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44);

// access grants
FLOAT& operator () ( UINT Row, UINT Col );
FLOAT operator () ( UINT Row, UINT Col ) const;

// casting operators
operator FLOAT* ();
operator CONST FLOAT* () const;

// assignment operators
D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
D3DXMATRIX& operator *= ( FLOAT );
D3DXMATRIX& operator /= ( FLOAT );

// unary operators
D3DXMATRIX operator + () const;
D3DXMATRIX operator - () const;

// binary operators
D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
D3DXMATRIX operator * ( FLOAT ) const;
Other documents randomly have
different content
back
back
back
back
back
back
back
back
back
back
back
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!

ebookball.com

You might also like