HO_Voorbeeldhoofdstuk_Mathematics for Game Creators

Page 1

Chapter 1

1.1 Purpose

The unit circle is a basic building block of trigonometry. The unit circle will be the starting point to explain the concepts of:

• angle: what is an angle and how can you measure an angle?

• sine, cosine and tangent of an angle

• The arc functions, which are the inverse of the sine, cosine, and tangent functions.

In this course, you will use the sine and cosine to create timed animations, lighting calculations, and transformations. Sine and cosine also play an important role when solving right triangles (a triangle where one of the internal angles is 90°). We end the chapter with the conversion between radians and degrees and vice versa, and the general formula to convert a value from one range to another.

1.2 The Unit Circle

In this first part of the chapter, you will explore all the concepts related to the unit circle. You will start by learning about angles in radians and degrees and understand how they connect to the unit circle.

A circle

The unit circle is defined a s the collection of points that are at unit distance from a central point ( M1 in the figure below). As you move the point P1 along the circumference of this unit circle, the distance between P1 and M1 is always exactly one unit, which is the definition of the radius of a circle.

The Unit Circle PROEFVERSIE@VANIN

-1 0 1 -1 1 1 1 Chapter 1 The Unit Circle 11

An arc on the unit circle

An arc is defined as a part of a curve, and more specifically a part of a circle. The following figure demonstrates an arc on the unit circle:

PROEFVERSIE@VANIN

Think of an arc as a flexible piece of string lying along the curve of the circle. If you straighten this string, its length can be measured. This length, when compared to the circle’s radius, is an important element when measuring angles.

A chord on the unit circle

A chord is defined as a segment that connects two points on the circumference of a circle. The following figure shows a few of examples of chords:

Chords that are horizontal or vertical will have a relationship with the sine and cosine functions we will see later on.

-1 0 1 -1 1
Chapter 1 The Unit Circle 12

1.3 Cartesian axis system

A two-dimensional (2D) axis system is used to locate points and vectors in space. Typically, the horizontal axis is called the X-axis, and the vertical axis is called the Y-axis.

A cartesisan axis system with the axises X  and Y and two points.

A point in 2D is written as (x y) and you can write the location of point A and B as follows:

• A = (3  1)

• B = (–2  –3)

Other examples are some points on the unit circle with the following coordinates:

• P1 = (1  0)

• P2 = (0  1)

• P 3 = (–1  0)

• P 4 = (0  –1)

You will use this notation extensively in the chapters about vectors and transformations.

-6 -5 -4-3 -2 -1 0 1 2 34 5 -6 -5 -4 -3 -2 -1 1 2 3 4 5 ⃗ ⃗
⃗ ⃗ 1 2 3 4
13 Chapter 1 The Unit Circle
PROEFVERSIE@VANIN

1.4 Angles

An angle is formed by two lines that start at the same point, also called the vertex.

A segment is defined as the part of the line between two points that are on that line. The notation of a segment typically uses the names of these two points with a line on top, e.g. A1B1 is the segment from point A1 to B1

In the following figure, the two lines are the segments A1B1 and A1C1, and the vertex is the point A1.

PROEFVERSIE@VANIN

An angle is defined by how much you need to turn or rotate one segment around the vertex to align it with the other segment. In the figure that angle α equals 45.5°, which means that if you turn the segment A1B1 with A1 as centre of rotation over 45.5°, the segment A1B1 will be perfectly aligned with the segment A1C1.

1 1 1
Chapter 1 The Unit Circle 14

Most students learn to work with a protractor in high school, which allows them to measure angles in 2D figures. In the figure the angle β equals 36° which is the value you will also find when aligning the protractor with one of the two segments.

When developing games, however, you need to use mathematical tools to measure angles. For this calculation you first need the trigonometric formulas within a right triangle. As not all triangles are right triangles, it is also important to discuss the law of cosines. Finally, the concept of vectors will offer a generalised way to calculate angles with the dot product formula.

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 2 2 2
Chapter 1 The Unit Circle 15
PROEFVERSIE@VANIN

1.5 Angles - Icosahedron

An interesting shape is the icosahedron. This shape is used in Dungeons & Dragons games, which is a popular pastime for students and teachers alike. An icosahedron is made out of equilateral triangles (which are triangles where all the sides have equal length). The interior angles of such triangles are necessarily 60°. You can create an icosahedron by cutting out the following shape. Fold the dotted lines and glue the triangles together:

PROEFVERSIE@VANIN

The scientific term for an arrangement of triangles that can be folded into a 3D shape is a net After glueing everything together you should get the following icosahedron. If you use cardboard you could even use it as 20 sided die:

Chapter 1 The Unit Circle 16

This shape is used a lot in 3D editors such as Maya, Blender, 3 ds Max, Houdini, ... because it has nice properties with regards to rendering and texturing. There are also interesting mathematical questions to ask about this shape:

• If we construct this shape, will all the vertices (corner points) lie on a sphere ?

• Will this be a fair die? In other words, does every side have an equal chance to be thrown?

The answers to these questions will probably still be elusive for you right now. With the introduction of the concept of vectors we will revisit these problems.

PROEFVERSIE@VANIN

1.6 The Unit Circle

Angles

Within the unit circle we can now define an angle α which is formed by the points M1, P1, and U x. Within the unit circle the point M1 will always be the vertex and the segments OP1 and OU x form the two lines that define the angle α.

U x is a reference point in the unit circle. This point is located on the X-axis and all the angles within a unit circle are relative to this point.

In the following figure the point P1 together with the reference point U x defines an angle α equal to 45°. Note that a positive angle indicates a counter clockwise direction.

Another example is the angle β which is defined by the segments M1P2 and M1Ux and again the vertex M1. This angle is again defined in a counter clockwise direction and is equal to 113°

1 1
Chapter 1 The Unit Circle 17

PROEFVERSIE@VANIN

1.7 Unit Circle Quadrants

The unit circle can be divided into four quadrants, again number in counter clockwise fashion. Usually these quadrants are indicated with roman numerals.

The first quadrant (Q I) contains angles in the range of [0°, 90°].

The second quadrant (Q II) defines angles in the range of [90°, 180°].

The third quadrant (Q III) defines angles in the range of [180°, 270°].

The fourth and last quadrant (Q IV) defines angles in the range of [270°, 360°].

1 2
Chapter 1 The Unit Circle 18

1.8 Radians

So far all the angles were expressed in degrees, which is a unit that is easy to understand. You can also define angles in the radians unit which corresponds to the arclength on the unit circle. To illustrate what this means you can take a look at the following figure where we imagine what would happen if you straighten out a part of the unit circle. Try to predict or devine from the figure how long a piece of rope would need to be if you wrap it around the unit circle for a given angle.

Radians expressed with π

The figure now shows various multiples and parts of π on the Y-axis

The radians value is a physical value that corresponds to the length of the arc on the unit circle

The angle that is shown on the figure corresponds to 180° or π rad. The radians value of π or 3.14159 is also the length of a piece of string that you need to make half a circle with a radius of 1

-1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 (a) = 0 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 (b) = 40 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 (c) = 80 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 (d) = 120 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 (e) = 160
-1/2 -1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 1 1 (a) = 1 -1/2 -1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 1 1 (b) = 21 -1/2 -1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 1 1 (c) = 41 -1/2 -1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 1 1 (d) = 61 -1/2 -1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 1 1 (e) = 81 Chapter 1 The Unit Circle 19 PROEFVERSIE@VANIN

Radians as angle unit

A full rotation around the unit circle corresponds to an angle of 2π in radians

An angle α can be any value, even a negative one. For example, an angle with a value of 3π would be described as 2π + π and results in a angle of π.

Similarly, an angle of – π/3 corresponds to a positive angle of –5π/3. A negative angle on the unit circle means that the angle is defined in a clockwise direction. On the following figure you can see this negative angle.

The maximum value of the angle in radians is 2π. The radians value corresponds to the arc length of the arc on the unit circle.

For a full circle, this arc corresponds to the circumference of the circle which is given by the following formula:

For the unit circle the radius equals 1.

This leads to a maximum value for the radians of 2π.

1
2π * radius
Chapter 1 The Unit Circle 20
PROEFVERSIE@VANIN

1.9 Projection

A projection is a transformation which projects a point on another geometric object, typically a line. This projection is typically perpendicular, which means that the projection line needs to make an angle of 90° with the second line.

In the figure, the point A will be projected onto the line which goes through L.

The point B is the projection of A onto the line.

PROEFVERSIE@VANIN

Notice that the projection line is perpendicular to the line through L, and the angle is indeed:

90°

= 90∘
α =
Chapter 1 The Unit Circle 21

1.10 The Cosine Function

The cosine function is the first mathematical and trigonometric function that we discuss. You should understand what the process is to construct the cosine of an angle. The following sets of figures demonstrate this relationship.

We start with a point P1 which defines an angle α on the unit circle.

The cosine of α is the value of the projection of the point P1 on the X-axis, in other words, a projection in the vertical direction on the X-axis. The cos(α) is now the signed length of this segment.

For an angle 0.785 in radians or 45°, the value of cos(α) = 0.707

PROEFVERSIE@VANIN

= 45∘ 1 = 45∘ 1 = 45∘ 1
Chapter 1 The Unit Circle 22

1.11 The Sine Function

The sine of α is the value of the projection of the point P1 on the Y-axis, in other words, a projection in the horizontal direction.

We start again with a point P1 which defines an angle α on the unit circle.

PROEFVERSIE@VANIN

The sine of α is the value of the projection of the point P1 on the Y-axis, in other words, a projection in the horizontal direction on the Y-axis.

The sin(α) is now the signed length of this projection.

For an angle 0.7854 in radians or 45°, the value of sin(α) = 0.7071

= 45∘ 1 = 45∘ 1 = 45∘ 1
Chapter 1 The Unit Circle 23

1.12 Geometric Interpretation of the Tangent

The tangent of an angle is found by extending the segment OP to where it intersects with the tangent line. The tangent of an angle can be negative. The tangent of α is the result of the division of the sin(α) and cos(α) The formula to calculate the tangent therefore is:

PROEFVERSIE@VANIN

For an angle 0.7854 in radians or 45°, the value of tan(α) = 1

= 45∘ ′
=
.
Chapter 1 The Unit Circle 24

1.13 Tangent - Derivation

A first triangle has sides with lengths sin(α), cos(α) and 1, and an angle α.

PROEFVERSIE@VANIN

The second triangle has sides with lengths x, 1, and also an angle α

The two triangles are similar because they share the angle α, and both triangles have an angle of 90°. If two angles are the same, then by definition, the third angle is also the same.

1 1 1 1 1
Chapter 1 The Unit Circle 25

If two triangles are similar, the only differences between the triangles is the scale

PROEFVERSIE@VANIN

We can write:

1 1 1 1
1 = or: = =tan( ) Chapter 1 The Unit Circle 26

1.14 Conversions as Interpolation

How to convert values from one unit to another

A common problem in computer graphics is the need to convert one unit of measurement to another unit of measurement. Examples are:

• Conversion from degrees to radians

PROEFVERSIE@VANIN

• Conversion from radians to degrees

• Conversions from a color in the range of [0,1] to a range of [0,255]

The following figure shows you how to interpret this conversion graphically. The top segment has a range defined as [2, 3], while the bottom segment has a range defined as [0.5, 4].

The problem is then to start with the value of s which is equal to 1.5 and project s on the second segment to calculate the value of d which will be 2.25

Example: Converting from radians to degrees

A typical application of this concept is the conversion between radians and degrees. The radians value is shown in the picture below. The range of an angle in radians is [0, 2π] and the range in degrees is [0°, 360°]. This makes the conversion process easier as both ranges start with 0.

-1 0 1 2 34 5 = 1.5 = 2.25
Chapter 1 The Unit Circle 27

The radians value shown above is converted to the degrees value in the picture below. We do this in two steps. First we divide the value in radians by the maximum value of the radians unit (which is 2π ):

PROEFVERSIE@VANIN

The next step is to multiply this t value with the maximum value of the degrees unit:

Remember that this process only works if both ranges have a minimum value of 0. You will discover the full formula for any conversion in the next sections.

Graphical interpretation

The t value can be understood as a normalized value in the range [0, 1].

-1/4 0 1/4 1/2 3/4 5/4 3/2 7/4 2 9/4 5/2 =
= 2 ∗ = 1.047 2 ∗ = 0.167
α = t*360° = 60° 0∘ 45∘ 90∘ 135∘ 180∘ 225∘ 270∘ 315∘ 360∘ 405∘ =60∘
0 1/4 1/2 3/4 5/4 3/2 7/4 2 =1 Chapter 1 The Unit Circle 28

The formula to calculate t is:

From the t-value you can now calculate the new value in radians:

deg = t *360° = 57°

PROEFVERSIE@VANIN

When converting from one range to another you always convert the first range to a normalised range of [0, 1] and as a final step convert this range to the new desired range:

1. Check the range of the value you want to convert. [0,2π]

2. Convert this range to a range of [0,1]. In this case this means dividing by 2π.

3. Convert this new range to the desired range of [0,360°], which means you need to multiply by 360°.

Finally, you can combine this into one formula:

= 2 ∗ = 0.16 00.10.20.30.40.50.60.70.80.9 1 1.1
=0.16
0∘ 45∘ 90∘ 135∘ 180∘ 225∘ 270∘ 315∘ 360∘ 405∘ =57∘
α
= ∗ 360 2 ∗ = ∗ 180 Chapter 1 The Unit Circle 29

1.15 General conversion

A more general example is shown below. The values for the old range are: oldmin = 100 and oldmax = 300

The t value is 0.25 and the formula to calculate t is:

A value in this range is converted into a value in a new range with the following parameters: newmin = 50 and newmax = 100

The new value can then be calculated:

The radians value shown above is converted to the new range value in the picture below:

= = 0.25
result = newmin + t * ( newmax – newmin) = 62.5 result = newmin + 0.25 * ( newmax – newmin) = 62.5 Old range 50 100150200250300 350 = 150 New range
40 5060708090100 110 = 62.5 Chapter 1 The Unit Circle 30 PROEFVERSIE@VANIN

Chapter 2

Trigonometry

Trigonometry deals with the calculation of angles and distances within triangles.

Most of the concepts are derived from the definitions of sine, cosine and tangent in the unit circle. It is, therefore, very important to see the link between the trigonometry concepts and the concepts of the unit circle.

PROEFVERSIE@VANIN

We will start with the definition of a right triangle and continue with the relationship between any right triangle and a triangle within the unit circle.

2.1 Trigonometry

Given a right triangle defined by points A, B, and C. An important point to make is that you will label the sides as seen from point A. As visualised by the protractor, the angle at point C in this triangle equals 90°.

• hypotenuse: this is the longest side in a right triangle. The angles that are connected to this side are always smaller than 90°.

• opposite: this side is opposite to point A.

• adjacent: this side is adjacent to point A

A right triangle is defined as a triangle where one of the angles is 90°, as shown in the picture where the angle ɣ is 90°. The sum of angles in a triangle is always 180°.

△ 40 50 60 70 80 90 100 110 120 130 140 150 160 170 opposite hypotenuse adjacent △ opposite hypotenusa adjacent △
Chapter 2 Trigonometry 31

2.2 Sum of Angles

It is easy to claim that the sum of angles in any triangle is 180°. However, you can create visual proof of this statement:

The triangle shown here does not have a right angle.

PROEFVERSIE@VANIN

As a first step you extend the segment AC, because the trick is to try to move all the angles around point A

△ △
Chapter 2 Trigonometry 32

Next, you create a line parallel to segment BC and paste it onto point A Thus, you get a new segment B’A

PROEFVERSIE@VANIN

As a final step, we can find the angle β between the new angle ɣ and the original angle α. You can now see that the sum of these angles equals 180° .

△ ′ △ ′
Chapter 2 Trigonometry 33

2.3 Pythagoras

The Pythagorean formula in a right triangle is the well known formula:

a 2 + b 2 = c 2

Where

• c is the hypotenuse or the longest side in a right triangle.

• a and b are the short sides of the triangle.

PROEFVERSIE@VANIN

This formula is frequently used in game development to calculate distances between points and to calculate the length of a vector.

c b a △
Chapter 2 Trigonometry 34

2.4 Pythagoras Proof

Proof

There is a nice visual proof of the Pythagorean formula. You start again with a right triangle with sides a, b, and c

PROEFVERSIE@VANIN

The hypotenuse is c and the angle ɣ equals 90° .

You can now create a square where all the lengths are equal to a + b

As a next step you create four copies of this triangle. Because of the way the triangles are arranged there is an empty spot in the centre with an area of exactly c 2 .

a b c △ a b c △ a b c △ △ △ △ △
Chapter 2 Trigonometry 35

You can now rearrange two of the triangles and the segments above to show another way to calculate the empty area which is: a 2 + b 2

PROEFVERSIE@VANIN

Since you did not create an additional empty area, the two empty areas must be equal and you have now proven the Pythagorean formula: a 2 + b 2 = c 2

a b c △ △ △ △ △ a b c △ △ △ △ △
.
Chapter 2 Trigonometry 36

2.5 Right Triangle Formulas

To derive the formulas for a right triangle we take another look at the unit circle:

You start with a point P on the unit circle, which defines an angle on the unit circle. The segment c has a length of 1 because P is a point on the unit circle.

PROEFVERSIE@VANIN

Next you project downwards from point P to find the cosine of the angle α . This projection makes a right angle with the horizontal axis, visualised by angle ɣ

= )
Chapter 2 Trigonometry 37

Next you project horizontally on the vertical axis to find the sine of the angle α

PROEFVERSIE@VANIN

Finally, you move this last segment to the right to create a triangle within the unit circle. Because the cosine and sine functions work with perpendicular projections, the lengths of side a and side b equals the cosine and sine of the angle α

In a right triangle where the hypotenuse has a length of 1 the sides of the triangle correspond to |cos (α)| and |sin(α)|. Within the unit circle it is easy to discern which one of the two sides is the cosine of the angle and which one is the sine of the angle. However, if the triangle is rotated, you need to carefully consider which side is the adjacent, and hence the cosine of the angle, and which side is opposite, and hence the sine of the angle.

= ) = ) △ = ) = )
Chapter 2 Trigonometry 38

2.6 Scaling up the Unit Circle

Compared to the unit circle in the previous section you can now apply a scaling transform on the triangle.

The scaling transform multiplies all the sides of the triangle with the same number. In game development this is typically referred to as a uniform scale. An important property of this transform is that the angles within the triangles will remain the same.

In the following figure the scale that you apply is the radius r which is equal to 3.

PROEFVERSIE@VANIN

=3

The segment c has a length of 3 because P is a point on a circle with radius = 3 The right triangle’s other two sides are also scaled up by a factor of r = 3 in this figure.

=3

Consider again that if you start from the centre of the circle in the figure, we can label the sides of the triangle as follows:

• a: adjacent side

• b: opposite side

• c: the hypotenuse. This side is also equal to the radius r in this circle.

In any right triangle we can then state:

△ =
=
=
=
)
)
=
=
=
=3
)
)
• a = c: cos (α) ⇒ cos (α) = • b = c: sin(α) ⇒ sin(α) = • = ) ) = ) ) = tan(α) Chapter 2 Trigonometry 39

2.7 Right Triangle Formulas

When confronted with a right triangle problem it is very important to label the sides of the triangle correctly. In the following figure we look at the problem from the perspective of point A. =hypotenuse = adjacent = opposite

You can use the following thought process to label the sides of the right triangle:

• Starting with the sides that are connected to point A the longest side will always be the hypotenuse or the segment c.

PROEFVERSIE@VANIN

• The other side that is connected to point A can only be segment a or the adjacent side.

• Finally, the side that is not connected to point A must be segment b or the opposite side.

The right triangle forααmulas for the sine, cosine and tangent of the angle α are:

) = ) = ) =
Chapter 2 Trigonometry 40

2.8 Polar Coordinates

An interesting application of sine and cosine is that they allow you to define a point with an angle and a radius.

On the unit circle

The sine and cosine of an angle can now be used to calculate a 2D coordinate.

PROEFVERSIE@VANIN

For an angle 0.7854 in radians or 45°, the value of P1 = (0.7071 0.7071).

1 1
Chapter 2 Trigonometry 41

1 1

You can calculate this point with the following formula:

P1 = (cos(α) sin(α)).

PROEFVERSIE@VANIN

With the actual value of α filled in, the formula is:

P1 = ( cos(0.7854) sin(0.7854) )

Note: in most programming languages the radians value is used for calculations, so you had better get used to this convention.

Chapter 2 Trigonometry 42

2.9 Breaking out of the Unit Circle

Now we use the cosine and sine of an angle together with a radius to calculate a point on an arbitrary circle.

PROEFVERSIE@VANIN

For an angle 1.0472 in radians or 60° , and a radius of 2.5, the value of P1 = (1.25 2.1651).

Polar
1 ) ) 1
coordinates
Chapter 2 Trigonometry 43

You can calculate this point with the following formula:

P1 = ( , {&yr} ).

PROEFVERSIE@VANIN

With the actual value of α filled in, the formula is:

P1 = (2.5 cos(1.0472), 2.5 sin(1.0472 ))

Note: in most programming languages the radians value is used for calculations, so you had better get used to this convention.

) ) 1 ) ) 1
Chapter 2 Trigonometry 44

2.10 Arc Sine

The inverse trigonometric formulas project a point from an axis back onto the circle. For the inverse sine formula (arcsin), a value is projected from the vertical axis.

We start with a point A on the vertical axis. The y-position of point P has to lie within the unit circle on the vertical axis, which means that the maximum is 1 and the minimum is –1. The y -position is 0.5 in this example.

PROEFVERSIE@VANIN

Point A is then projected to the right to find the intersection with the unit circle, resulting in the angle α1 with a value of 30° . Notice how this angle varies between 90° and –90°. There is still another way to project this point, do you know which?

If we can project to the right, we can also project to the left, resulting in the angle α 2 with a value of 150°

1 1 2
Chapter 2 Trigonometry 45

We can conclude that the formula arcsin( y) leads to two equally valid results, namely α1 and α 2. In this case: arcsin( y) = arcsin( y) = 30° or 150° .

2.11 Arc Cosine

The inverse trigonometric formulas project a point from an axis back onto the circle. For the inverse cosine formula (arccos), a value is projected from the horizontal axis.

We start with a point B on the horizontal axis. The x-position of point P has to lie on the horizontal axis within the unit circle, which means that the maximum is 1 and the minimum is –1.

Point B is then projected upwards to find the intersection with the unit circle, giving the angle α1 with a value of 60°

Notice how this angle varies between 0° and 180°.

1 2
1
Chapter 2 Trigonometry 46
PROEFVERSIE@VANIN

If we can project upwards, we can also project downwards, giving the angle α 2 with a value of – 60°

Notice how this angle is the negative value of α1.

PROEFVERSIE@VANIN

We can conclude that the formula arccos (x) leads to two equally valid results, namely α1 and α 2. In this case: arccos (x) = arccos (x) = 60° or – 60°

1 2 1 2
Chapter 2 Trigonometry 47

2.12 Arctangent

The arctangent is a frequently used function in game development, as it can be used to calculate an angle when you have a horizontal and a vertical distance. However, there is one important consideration: the formula is a ratio (division) of the two short sides of the triangle, with the adjacent side in the numerator: ) =

When the adjacent side is zero, the tan(α) is undefined and it is also not possible to calculate the arctangent

opposite

adjacent

You might wonder if a similar problem occurs for the sine and cosine functions. Indeed, there is, because the hypotenuse is in the numerator. This is only a problem if both the adjacent and opposite sides are equal to zero.

2.13 Inverse Formulas – Atan2

Most programming environments avoid the danger of the arctan function with a function called atan2 . This function is defined as follows:

α = atan2 (opposite, adjacent)

This function avoids the division and returns a correct value between –π and π or –180° and 180°.

Chapter 2 Trigonometry 48
PROEFVERSIE@VANIN

2.14 Non Right Triangles – Extra

The right triangle that we discussed so far is a special, because one of the angles in the triangle is 90°. You will encounter other triangles as well, so it is important to showcase how to solve acute or obtuse triangles.

PROEFVERSIE@VANIN

We start with an acute triangle defined by points A, B, and C, which are given. All of the angles in this triangle are smaller than 90° .

We divide the triangle into two right triangles by projecting point C on the horizontal axis, resulting in point D.

Chapter 2 Trigonometry 49

This results in two right triangles △ AC D and △ BC D, with a side h whose height is still unknown

You can work out the solution by trying to find a formula for x . As a first step we write down the Pythagorean formula for both triangles: △ ∶ 2 + ℎ2 = 2 △ ∶ ( )2 + ℎ2 = 2

Because h is unknown we try to get rid of this variable:

Combining both formulas gives the following equation:

c 2 – x2 = b 2 – a 2 + 2 a x – x2

Both sides have –x2 so we can simplify to:

c 2 = b 2 – a 2 + 2 a x

Now we can isolate x because a, b and c are known: = 2 2 + 2 2

△ △ ℎ
△ ∶
)2
∶ ℎ2 = 2 2
ℎ2 = 2 (
= 2 2 + 2 2
Chapter 2 Trigonometry 50
PROEFVERSIE@VANIN

Chapter 3 Introduction

3.1 Animation

The trigonometric functions and formulas allow you to calculate angles, position points via polar coordinates, and solve trigonometric problems.

PROEFVERSIE@VANIN

The sine and cosine functions can also be used to create simple animations which is the major topic for this chapter.

The chapter starts with an explanation of the concept of timeline and frame based animation. In games and 3D editors time is an important aspect of the development of animation and game play. Sometimes an absolute time is used, in other instances the time difference or delta time between two frames is sufficient to programme an animation.

The concept of using functions to control animations is the next topic, and the sine and cosine functions are used here to demonstrate how to control the timing with the help of mathematical functions.

3.2 Timeline

Games, animations and films are the digital world. As such it is common to hear concepts as frames per second (fps) or framerate. The framerate of a film or game is linked to the mathematical concepts of frequency and period which you will discover later on in this chapter.

For gamers the fps is an important metric when judging the quality of a game, i.e. a possible a potential for an fps drop can be detrimental to the fun of a game. For smooth motion and responsiveness the fps should strive to match the framerate of the monitor. Most game companies aim for at least 30 frames per second for games, while 60 frames per second is considered good. With the advent of modern monitors, the framerate for games can be even higher, for example 90 or even 144 frames per second. Although a high framerate is preferred in games it is also important to synchronise the frames to the framerate of the monitor. A typical problem is tearing where the lack of synchronisation results in a visible tear in the image.

For virtual reality applictions this is even more important as low framerates in these cases can induce dizzyness or even nausea. In cinematic settings a framerate of 24 frames per second is the gold standard. Most animation tools such as Houdini, Blender or Maya will use this setting as the default when you create character animations or film clips. The historical reasons for this framerate are varied. At the start of the film industry there was no generally accepted standard for film framerates, the only consensus was to keep the framerate low to reduce costs, which resulted in a framerate of about 16 frames per second. Cameras were handcranked, so this framerate was only by approximation.

There are different reasons for switching to 24 fps. The most important reason is that this framerate is an important threshold for visual perception. At 24 fps, a film appears to have continuous motion for most people. Another reason for the change is the introduction of

Chapter 3 Introduction 51

audio to films which necessitated a better framerate. Finally, for some the reason was mathematical as 24 has six dividers: 2,3,4,8,6,12. Whatever the reason, 24 fps is what people expect when they go see a film. Some films experiment with this setting, for example, “The Hobbit” was filmed at 48 fps. However, this was a change that was not received well by critics and audiences. Human perception remains subjective, so even though a framerate could be objectively better, people resist change. The following figure shows a time between 0 and 2 seconds with a framerate of 24 fps. Within this timeframe, 48 frames will be needed to create a cinematic animation.

PROEFVERSIE@VANIN

You can also calculate how much time passes between two subsequent frames. So if you have a timeframe of 2s and 48 frames the time between each frame can be calculated as:

The symbol Δt is commonly used to indicate a delta time, meaning a difference between two distinct moments in time.

3.3 Animation

If you want to create an animation, one of the important components will be the factor time. In a game or animation the time is the independent variable that dictates changes in an object’s position, rotation, and scale. If you want to animate a ball bouncing up and down, you need to calculate a new position for the ball for each frame.

0 2
=
48 =
Time Chapter 3 Introduction 52

In this chapter we will focus on using the sine and cosine functions to generate a new position. As the output of sine and cosine functions is limited to the range of [–1 1] it is necessary to add extra parameters if we want to achieve a specific movement.

Time Sine parameters

PROEFVERSIE@VANIN

A typical example is the motion of a platform in a game. The moving platform in the figure needs to move horizontally between the two points L and R

You can use the sine function for such a horizontal motion, and as you will see the sine function generates a simple but plausible animation for this moving platform. The first parameter of the sine function that will help achieve the desired result is the amplitude parameter, which allows you to modify the output range of the sine function.

The second parameter is the offset, that can move the centre of the sine function to the centre of the moving platform.

A third parameter is the frequency, which covers the speed of the moving platform animation. If you want the platform to move fast, a high frequency parameter will be required.

Finally, there is also a phase parameter, that allows you to change the starting position of the moving platform.

These four parameters and their influence on the shape of the sine function will be discussed in the following section.

Chapter 3 Introduction 53

3.4 The Sine Function

Sine function plot

We already covered the sine function in previous chapters. This week we discuss the sine function and plot out the relationship between the angle α and the sin(α) value.

Point P1 is traced along the circumference of the unit circle while the plot shows the value of angle α on the horizontal axis and the value of sin(α) on the vertical axis.

Notice some important characteristics of this shape. The maximum of the sine function is 1 and the minimum value is –1. The amplitude of the sine function is defined as the difference between the maximum and the minimum value, divided by 2. The amplitude is denoted with the letter a:

2 = 1

The sine function crosses the horizontal axis at α = π. Other important points are:

-2 -1 0 1 2 3 4 5 -1 1 1
=
⎧ ⎪ ⎪ ⎪ ⎨ ⎪ ⎪ ⎪ ⎩ ⇒ ( ) 0 ⇒ 0 3 ⇒ 1 ⇒ 0 3 2 ⇒−1 2 ⇒ 0 Chapter 3 Introduction 54 PROEFVERSIE@VANIN

3.5 Sine function shape

For clarity, we show the same sine function again, but now the horizontal axis shows a division that is based on multiples of π.

For an unmodified sine function, one full period takes 2π, and then the same shape is repeated again.

3.6 Parameters

The sine function is very interesting on its own, but you need extra parameters to make the sine function useful. The following parameters can be used:

• Amplitude – a: A sine function variates between –1 and 1, with the amplitude we can increase this minimum and maximum value.

• Frequency – f: One period has a duration of 2π, this can be changed with the pulsation parameter.

• Phase shift – Φ: This parameter can shift the sine function left and right (horizontal direction).

• Vertical shift – v: The vertical shift parameter shifts the centre of the sine function.

3.7 Sine function shape

The sine function without parameters has a minimum of –1 and a maximum of +1. One period of the sine function starts at 0 and ends at 2 π

-1/2 0 1/2 3/2 2 -1 1 1
-1/2 0 1/2 3/2 2
Chapter 3 Introduction 55
-1 1
PROEFVERSIE@VANIN

3.8 Amplitude parameter

The amplitude parameter determines the difference between the maximum and the minimum of the sine function. To implement this parameter you multiply the sine function with the parameter called a, which gives the following equation: a sin(t).

The amplitude a equals half the vertical distance from the maximum to the minimum of the sine function. This is visually represented by the distance 2a in the figure above. One way to determine the amplitude given the shape of the sine function is to divide this distance from top to top and divide by 2. An example of this calculation is as follows: = ( ) 2 = (1.5 −1.5) 2 = 1.5

As an exercise, take a look at the following figure:

Use the given formula to determine the amplitude of this sine function.

-1/2 0 1/2 3/2 2 -3 -2 -1 1 2 3 2
-1/2 0 1/2 3/2 2 -3 -2.5 -2 -1.5 -1 -0.5 0.5 1 1.5 2 2.5 3 2
Chapter 3 Introduction 56
PROEFVERSIE@VANIN

3.9 Frequency parameter

The frequency parameter determines how many periods there are within a range of [0s 1s] or one second. A period is defined as one full c ycle of the sine function, which you can measure as the horizontal distance from top to top of the sine function. The unit of frequency is called Hertz and is abbreviated as Hz . The following figure demonstrates what a frequency of 1Hz looks like:

PROEFVERSIE@VANIN

There are three possibilities for this parameter:

• Frequency > 1Hz: There will be more than one period within one second.

• Frequency == 1Hz: There is exactly one period in one second.

• Frequency < 1Hz: There will be only part of a period within one second.

The formula for the sine function with only the frequency parameter is:

sin ( 2π f t )

Frequency > 1Hz

The following figure shows the result of a frequency of 2 Hz. Notice that there are more periods per second, and that by doubling the frequency the period has been halved.

The relationship between period and frequency is inverse. If the frequency increases by a factor of two, the period will decrease by a factor of two.

-2 -1 0 1 2 34 5 6 -2 -1 1 2 3 period= (2 )
-2 -1 0 1 2 34 5 6 -2 -1 1 2 3 period= (2 )
Chapter 3 Introduction 57

Frequency < 1Hz

The following figure shows the result of a frequency of 0.5Hz. Notice that there are less periods per second, and that by halving the frequency the period has been doubled

3.10 Phase parameter Φ

The phase shift parameter determines a horizontal shift of the sine function. For a positive value of this parameter Φ, the sine function will be shifted to the left by an amount of Φ. In the figure below the value for Φ has been set to 1/3 π.

The original sine function with Φ set to zero sin(t) and the phase shift sine function with Φ set to 1/3 π which is + 3

The formula with only the Φ parameter is:

sin ( t + Φ )

The parameter Φ can be used to change the starting point of an animation. Without the phase, an animated object would by default always start at its centre position. The phase parameter allows you to pick a starting point anywhere within the range of motion of said object.

A positive Φ value will shift the sine function to the left

A negative Φ value will shift the sine function to the right.

-2 -1 0 1 2 34 5 6 -2 -1 1 2 3 period= (2 )
-1 0 1 2 =
Chapter 3 Introduction 58
PROEFVERSIE@VANIN

3.11 Vertical shift parameter

The shift parameter generates a shift of the sine function in a direction perpendicular to its baseline (in this figure the horizontal axis).

Two examples of adding a shift parameter to the sine function with v1 = 1.5, and v2 = –2. The central line of the sine function is defined as the line that runs exactly through the centre of the sine function.

The shift parameter is added to the sine function as: = ( )+ 1

As pictured here, the output of the sine function is a coordinate y. In a 2D or 3D world you can use the output of the function and connect it to whatever variable you want. For example the sine function could modify the x or z-coordinate of an object.

3.12 Sine function shape

Finally, you can combine all the parameters for the sine function in one formula:

With the actual values for these parameters, the formula is:

-1/2 0 1/2 3/2 2 -3 -2 -1 1 2 1 = 1.5 2 = −2 baseline baseline t y
a 1 sin ( 2 πf 1t + Φ 1 ) + v1
0.5 sin ( 2 π2 t + 1/3 π ) + 2 Chapter 3 Introduction 59 PROEFVERSIE@VANIN

PROEFVERSIE@VANIN

The period, amplitude and shift are relatively easy to read from this function plot. Period and frequency have an inverse relationship, which is given by:

The phase Φ1 involves more work as it involves the useage of the arc sine and knowledge about the locations of the peaks or zero crossings of the function. The methodology to determine this parameter correctly will be discussed in the following section.

Application

You can already put the knowledge of the sine function into action. In the following figure we take another look at the platform problem from the beginning of the chapter. Remember that you wanted to make the platform move from left to right with a repeating cycle and a certain speed.

The first problem is that the platform has a width that you need to take into account and also a point P that is defined as the model centre of the platform. The first step you need to take is to think about the valid locations of this point P in this situation. P cannot be at the location L or R because then half of the platform would intersect with the boundaries of the world. The answer is then to restrict P to make sure it keeps a distance of half the width of the platform itself or 2 away from the boundary points L and R

By labeling the baseline and the amplitude we can determine the parameters a and v if the position of L and R are known.

-1/2 0 1/2 3/2 -0.5 0.5 1 1.5 2 2.5 3 3.5 4 1 1 = 2 period= t y
1 = 1 1
Chapter 3 Introduction 60

PROEFVERSIE@VANIN

The x-coordinate of point L equals 1 and the x-coordinate of point R equals 6. Here you see the advantage of using the centre of the platform as model centre, because you can calculate the x-position of the baseline as the average between these two coordinates, which also corresponds to the parameter v:

For the amplitude parameter you can calculate the distance of the left boundary to the baseline, which is calculated as the horizontal distance between the baseline and the left boundary:

3.13 Phase Control

By determining a and v you can already setup a sine function that will animate the platform within the defined boundaries:

= asin ( t ) + v = 2sin ( t ) + 3,5

Notice how the time t is used as argument in the sine function. The result of the sine function is then used as the x-coordinate for the point P. The clear message here is that you are free to use the output of the sine function wherever you want. The result might be stored in the x, y or z-coordinate of a point, but it is also possible to use the sine function to animate colours.

0 1 2 3 4 5 6 7 = 1 = 0.5 + = 1.5 baseline ! ! = 12 = 62 x
= (1 + 6) 2 = 3.5
a = v – ( L x + w H ) = 3.5 – 1.5 = 2
x
Chapter 3 Introduction 61

PROEFVERSIE@VANIN

The next problem you need to tackle is the starting position of the platform. You can first determine what the starting position would be of the platform at t = 0s:

This corresponds to the x-position of the baseline and this indicates that at the start time of the game or simulation, the platform will be at the baseline position or the centre. It is possible to use the phase shift Φ to change this starting position. A common demand is for example to set the start position on the left boundary. This requires that at t = 0s, the point P must have the x-coordinate of : x = L x + wH = 1 + 0.5 = 1.5. You can now determine the phase by requiring that the sine function with an unknown phase must be equal to this coordinate x = 1.5 at time t = 0s:

The determination of the phase Φ will always involve setting a condition for the position of the animated object at a given time (usually at t = 0s). Determing the phase always involves an arc function. With the determination of Φ, the function is now:

When the condition is set at t = 0s, the frequency or period of the sine wave does not matter because the term in t will be zero. However, when the condition is set at a different time it will be necessary to take this frequency or period into account.

0 1 2 3 4 5 6 7 baseline ! ! = 62 x = 1.52
x
t
0 ) + v = 0 + 3.5
3.5
= asin (
) + v = asin (
=
= ( + ) + ⇒ (0 + ) + 3.5 = 1.5 ⇒ 2 ( ) = 1.5 3.5 ⇒ ( ) = 1.5 3.5 2 ⇒ ( ) = 1 ⇒ = ( 1) = 3 2 1 2
= ( + ) + ⇒ 2 + 3 2 + 3.5
Chapter 3 Introduction 62

3.14 Cosine

The cosine function has similar characteristics to the sine function, but has been shifted over the horizontal axis.

The following picture shows the plot of the regular cosine function:

= cos ( α )

PROEFVERSIE@VANIN

The cosine function starts with an initial value of 1. However if a bigger range of this function would be plotted, the function would look exactly the same as the sine function.

Sine and cosine are the result of the same operation, the only difference is that sine is projected on the vertical axis and cosine is projected on the horizontal axis. Therefore, the phase shift 2 , which is the result of the fact that the angle between these two axes is also 90° or 2 apart.

y
-1/2 0 1/2 3/2 2 y
-1/2 0 1/2 3/2 2 y 2
Chapter 3 Introduction 63

3.15 Determining the Frequency

Control the timing of the sine function

The period is the length of one full cycle of a sine wave and is typically expressed in the time unit seconds

The frequency is the number of full cycles per second

There is an inverse relationship between frequency and period: = 1 ⇒ = 1

PROEFVERSIE@VANIN

When you want to control the timing of the sine function you need to express the timing either by frequency or by period. Hence, using the inverse relationship you can express the sine function in two ways:

(2 ) ⇒ = 2

For example, if f = 2Hz, then = 1 = 1 2 = , and both forms of the sine function (either with frequency or with period) would lead to the same sine function shape: = (2 2 ) = (4 ) = 2 0,5 = (4 )

The use of the period T in the sine function can be more practical than using the expression with frequency. It is sometimes easier to express how long the animation should take in seconds than to try and come up with a plausible frequency.

As an example, suppose we want the moving platform to complete one full cycle in 16s, and we call this period T 2. The frequency in this case would be f 2 = 1 2 = 0.0625Hz. When the period is bigger than 1s it seems to be easier to express the timing with the period instead of the frequency, and the expression for the sine function is also easier to read and understand: = 2 2 = 2 16

However, when the period is less than one second, it may be more practical to think in terms of frequency, particularly in scenarios where rapid oscillations are involved, such as in audio signals. Another example might be animations in games, such as those in the Steampunk genre, which feature rapidly rotating gears, wheels, ... with frequencies that are higher than 1Hz.

=
2 =
Chapter 3 Introduction 64

3.16 Period of Ordinary Sine

Why is factor 2π necessary?

The formulas for the sine function with frequency or period parameter were introduced without an explanation for factor 2π. For a better understanding of this factor we take a step back and revisit the sine function without parameters:

PROEFVERSIE@VANIN

y = sin ( t )

You can make a table of important points of this sine function and calculate the values for t and y:

The sin function in this case works with radians, and the period of the sine function without parameters is T = 2π = 6.2832s. The standard period of 2 π is cumbersome in practice, which is one reason why the factor 2π is included in the sine function. The frequency 2 = 0.1592Hz of the standard sine function is also impractical to work with.

In the next section you can further explore what the exact reason behind the factor 2π is. To understand this properly you need to rethink the section about conversions from one unit to another. This problem is similar in that we want to have a full cycle of the sine function in a period from 0s to 1s.

⇒ ( ) ⇒ 0 ⇒ 0 ⇒ 1 2 ⇒ 1 ⇒ 2 ⇒ 0 ⇒ 3 3 2 ⇒−1 ⇒ 4 2 ⇒ 0 ⇒ 5
0s 1s 2s3s 4s 5s 6s 7s -1 s 0 s 1 s t y 1 2 3 4 5
Chapter 3 Introduction 65

3.17 Sine function shape

Given the sine function:

y = sin ( 2 πt )

You can now repeat the same process, but the range of t will be between 0s to 1s. Notice how this range between 0s and 1s in the first column is converted into a range of 0 to 2π radians in the second column. This effectively matches a period of 1s to a full cycle of the sine wave.

PROEFVERSIE@VANIN

The figure shows that the effective period T of the sine wave is now 1s and the frequency = 1 = 1 = .

This formula results in a frequency of one Hz. How can we now control the frequencies of the sine wave?

⇒ 2 ⇒ (2 ) ⇒ 0 ⇒ 0 ⇒ 0 ⇒ 1 0.25 ⇒ 2 ⇒ 1 ⇒ 2 0.5 ⇒ ⇒ 0 ⇒ 3 0.75 ⇒ 3 2 ⇒−1 ⇒ 4 1 ⇒ 2 ⇒ 0 ⇒ 5
0 1 2 3 4 -1 1 t y = 1 2 3 4 5
Chapter 3 Introduction 66

3.18 Sine function shape

The final step in controlling the frequency or period of the sine function is to add the factor f or frequency in the formula or the alternative version with the parameter T. = 2 = (2 )

If you set the frequency f = 2, then the period = 1 = 1 2 = .

The function with the value of the frequency is:

You can now repeat the same process, but the range of t will be between 0s to 0.5s. Notice how this range between 0s to 0.5s in the first column is converted into a range of 0 to 2πradians in the second column. This effectively matches a period of 0.5s to a full cycle of the sine wave.

y = sin ( 2π 2Hz t ) = sin4πt
⇒ 4 ⇒ (4 ) ⇒ 0 ⇒ 0 ⇒ 0 ⇒ 1 0.125 ⇒ 1 2 ⇒ 1 ⇒ 2 0.25 ⇒ ⇒ 0 ⇒ 3 0.375 ⇒ 3 2 ⇒−1 ⇒ 4 0,5 ⇒ 2 ⇒ 0 ⇒ 5 0s 1s 2s 3s -1 1 t y = 1 2 3 4 5 Chapter 3 Introduction 67
PROEFVERSIE@VANIN

3.19 Applications – Extra

Animation

The exponential function is given as:

PROEFVERSIE@VANIN

This is a power function with e as its base, which is also called Euler’s number and this is a constant with a value of 2.71828

The exponential function decreases over time and reaches zero at +infinity. This makes it a good fit for animations that have to fade out over time. The λ value controls how fast the value of this function reaches zero. A value smaller than 1 for λ results in a slowly decaying function.

When the value of λ is bigger than 1, the function reaches 0 faster. The function below the orginal function has λ = 3 and almost reaches zero after 2 seconds. The function with the actual value for λ is then:

= e –3 t

y
= e – λt
0
4 5 1 t y
1 2 3
0 1 2 3 4 5 1 t y
Chapter 3 Introduction 68
y

3.20 Applications – Extra

Animation

Previously, you used a constant (unchanging) amplitude for the sine function. However, you can use the previous section’s exponential function as slowly decaying amplitude and multiply it by the sine function to achieve a slowly decaying sine function. One example of where you can use this is a pendulum that slowly loses energy and stops swinging. The function is given by: e-λt sin ( 2 π f t )

PROEFVERSIE@VANIN

If you set the value for λ to 1 and the value for f to 1Hz you get the following graph. The sine function is still detectable for the first 4 seconds, where you can see that the period T = 1s:

3.21 Angular Velocity

You can now combine your knowledge about sine and cosine to create a variety of motion. The following figure illustrates what the possibilities are.

• Point P1 is defined as: ( cos ( t ) sin ( t ) ). This corresponds to a polar coordinate where the time t is used as angle for the cosine and sine functions. This coordinate moves along the unit circle over time.

• Point P2 is defined as: ( P2x sin ( t ) ). The x-coordinate of this point is constant, which results in a point that moves vertically.

• Point P 3 is defined as: ( cos ( t ) P 3y ). The y-coordinate of this point is constant, which results in a point that moves horizontally.

If we use time as input angle for the animation we can control the speed of this animation.

0
4 5 6 -1
1 2 3
1
2
1
3
Chapter 3 Introduction 69

3.22 Frequency

The formula for point P1 is:

1 = (2 ) (2 )

With the value for the frequency given as: 0.25Hz, the actual formula for point P1 is now:

PROEFVERSIE@VANIN

1 = (2 0.25 ) (2 0.25 )

The other two points are animated with the same frequency and are now:

• Point P1 is defined as: (P 2x sin ( 2 π f t ) ). The x-coordinate of this point is constant, which results in a point that moves vertically and with the frequency f = 0.25Hz.

• Point P 3 is defined as: ( cos ( 2 π f t ) P 3y ). The y-coordinate of this point is constant, which results in a point that moves horizontally and with the frequency f = 0.25Hz.

3

2
Chapter 3 Introduction 70
1

Chapter 4 Vectors

Vectors are an important concept for creating games and animations. Vectors offer a framework where typical game development problems can be formulated in a mathematically sound but compact manner. The topics of this chapter include the following:

PROEFVERSIE@VANIN

• Vectors versus points: In a game engine or 3D editor there is a difference between vectors and points. In this chapter this difference will be explained qualitatively, but as you will discover in the chapter about transformations, there is also a mathematically proper way to model vectors and points in the form of homogeneous coordinates. In general, points represent a location and time in space. Vectors on the other hand indicate a direction or movement of an object.

• Add and subtract points and vectors: Mathematical operations of adding points and vectors are important in the game world. For example, the remainder of two points results in a direction vector from the second point to the first point. The addition of two vectors can represent the combination of two forces acting upon an object.

• Length of a vector: When you use vectors to describe velocity, the length of this vector can be interpreted as the speed of the object. Another example is the calculation of the distance between two points, resulting in a vector with a length equal to the distance between the two points.

• Normalise a vector: It is sometimes necessary to modify the length of a vector. In such cases, reducing the vector to a length of 1 (defining it as a unit vector) is convenient. A normalised vector can then be thought of as representing only the direction of an object, which allows for precise control of the speed. Another use case for normalised vectors is the topic of lighting (or shading) where normalised vectors are required to correctly calculate the various elements of the lighting equation.

• Scale a vector: To implemenent movement you will model the velocity of an object with a vector. It is possible to decouple speed and direction with vectors to enable the control of these two elements.

• Coordinate systems: Vectors are used to describe coordinate systems, where for example a rotated coordinate system can be made by specifying rotated unit vectors.

A good understanding of the basic operations of vectors is necessary to further explore the concepts of the dot and cross product, which will be discussed in the following chapter. These two operations on vectors are crucial for implementing lighting, solving geometric problems and more advanced algorithms such as inverse kinematics. Vectors are also crucial in physics implementations within games or simulations, e.g. for object collisions or particle animations.

Chapter 4 Vectors 71

4.1 Vector

Definition

A vector of dimension n is an ordered collection of n elements, which are called components:

• a 1D vector is typically referred to as a scalar or number

• a 2D vector is a vector of dimension 2 with 2 components, typically called x and y. Other names are possible, such as u and v for texture coordinates.

PROEFVERSIE@VANIN

• a 3D vector is a vector of dimension 3 with 3 components, typically called x , y and z. Other names are for example r, g and b.

Notation

A vector is typically presented as a row of values in a specific order. A notation for a 2D vector where x equals 10 and y equals 5 is for example:

v 1 = (10 5)

For a 3D vector the same notation is used:

v 2 = (10  5  3)

Note: The names for vectors are typically lower case with a small arrow on top to indicate that this is indeed a vector.

It is useful to also have a way to name the components of a vector separately. The common way to do this is to add a subscript to the name of the vector, indicating the specific component. In a 2D example this can only be an x or a y-component:

v1x = 10

v1y = 5

The components of a vector are scalars (numbers), so it is not necessary to add an arrow on top of these components.

Vector in column format

Sometimes a vector is written as a column vector. This is the same concept, only with another notation.

The column notation for a 2D vector where x equals 10 and y equals 5 is for example:

⃗ 1 = 10 5

Chapter 4 Vectors 72

For a 3D vector the same notation is used, with the addition of a z-component that equals 3:

The column format is typically used for matrix multiplications where a vector can be transformed (rotated or scaled) by multiplying with another matrix.

Graphical notation

PROEFVERSIE@VANIN

A vector is draw as an arrow to indicate its role in determining the direction. The start of the vector is also called the tail and the end of the vector is called the head

The components of a 2D vector indicate the horizontal and vertical difference between the tail and the head of the vector.

4.2 Vectors versus Points

Points

Points are used to define locations in a two dimensional or three dimensional space. Examples of the usage of points:

• Quest location: In games, quests can have important locations attached to them. One example is the location where a quest starts, or where a player can interact with a non player character (NPC), to start a quest.

• Particle location: where a particle is currently visible.

• Vertex: a point inside a mesh is typically called a vertex

⃗ 2 = 10 5 3
= 10 =
head tail ⃗ 1
5
Chapter 4 Vectors 73

For points, the first coordinate describes the horizontal distance in a two dimensional cartesian axis system, while the second coordinate describes the vertical distance. Note also how the axis system is orthogonal, which means that the X and Y axis are 90° apart.

PROEFVERSIE@VANIN

Vectors

A vector is used to indicate a direction in two dimensional or three dimensional space. Examples for the usage of vectors:

• The direction a guard NPC is walking.

• The direction of a photon.

• The current direction of a particle. For example for a smoke particle this could be an upwards direction.

In the figure two vectors, both called v  are visualised. You should realise that a vector does not have a location, and drawing a vector at a certain location in a graph does not have a mathematical meaning. Drawing a vector at a certain location is purely for illustrative purposes; it is the direction of the vector and its length that carry the true meaning.

In this case, the vector v could describe the direction in which a guard at point G is moving.

x =
y = 6 X Y 1 = 5 6 2 2 3
5
x
y =
X Y ⃗ = 2 3 ⃗ 2 3 Chapter 4 Vectors 74
= 2
3

4.3 Example

The cars in the following figure show the concept of using points and vectors to model the behaviour of an object. The two cars on the right have the same direction vector:

1 = (–0.68 1.88)

PROEFVERSIE@VANIN

This is an important concept as it does not matter where a vector is displayed on a figure. It is just a matter of convenience to convey that v 1 is the direction vector of the first car, and v 2 is the direction vector of the second car.

The vector v 3 is different from the first two vectors as its components are different from the first two vectors:

The points P 1, P 2 and P 3 define the current locations of the three cars. In games and animations you give every object its own unique location.

v
v
2 = (– 0.68 1.88)
v 3 = (–1.73 1) ⃗ 1 1 ⃗ 2 2 3 ⃗ 3
Chapter 4 Vectors 75

4.4 Length of a Vector

The length of a vector is also called the magnitude, and is defined as the distance from tail to head of the vector. Calculating the magnitude of a vector is an operation that will be used to normalise vectors, to determine a distance between two points, or to calculate the speed at which an object is travelling.

The length of a vector is an application of the pythagorean formula in a right triangle: 2 + 2 = 2 ⇒ = 2 + 2

As always, you need to correctly identify the sides of the triangle to apply the formula.

= 4 3

⃗ = 4 3 y = 3 = opposite x = 4 = adjacent

The cartesian grid is orthonormal, which means that there is an angle ɣ equal to 90°. The length of a vector is written symbolically with two vertical lines around the vector: |v |.

It is no coincidence that the same symbol is used for the absolute value of a scalar, because you can interpret a scalar as a one-dimensional vector. Thus, the absolute value of such a vector is its length. y = 3 = opposite

= 4 3

= 4 = adjacent | ⃗|=

The length of the vector is given as: | ⃗ | = = 2 + 2 = 42 + 32 = √25 = 5

X
|
Y ⃗
Y
⃗|= X
Y
x
X
Chapter 4 Vectors 76
PROEFVERSIE@VANIN

The components of the three vectors are given by:

To calculate the lengths you apply the pythagorean formula:

A common error in vector calculations is incorrectly squaring the components when determining a vector’s magnitude. Remember that each component’s square contributes positively to the total magnitude, regardless of whether the original component is negative: ( 1)2 = 1

When you calculate the magnitude of a vector, you are taking the square of the components of a vector. These components can be negative but the square of them should be positive. Neglecting to square the components correctly will result in an inaccurate magnitude

⃗ 1 ⃗ 2 ⃗ 3
Examples
| ⃗
2
2
0.6752
2.9232
| ⃗
= 2 + 2 = (−2.462)2 + (−0.434)2
2.5 | ⃗
= 2 + 2 = (2.571)2 + (−3.064)2
1 | =
+
=
+
= 3
2 |
=
3 |
= 4
v 1 = (0.675 2.923) v 2 = (–2.462 –0.434) v 3 = (2.571 –3.064) Chapter 4 Vectors 77
PROEFVERSIE@VANIN

4.5 Unit Vectors

Vectors that have a length or magnitude of 1 are called unit vectors. Unit vectors play an important role in lighting and animation. In this chapter the hat notation is used to indicate that a vector has a magnitude of 1:

The construction of a unit vector is again an application of the concept of polar coordinates: = ( ) ( ) = (40∘ ) (40∘ )

To construct the unit vector correctly you need to set the radius value of this polar coordinate to 1

You can prove that the magnitude of the vector is 1 by applying the pythagorean formula in the right triangle formed by the cos (α) and sin (α):

| = ( )2 + ( )2

√1 = 1

Note: In 2D, polar coordinates define a vector with a radius and an angle, while in 3D, spherical coordinates use a radius and two angles for definition.

⇒ |
1 1 (
)
| = 1
) (
Chapter 4 Vectors 78
|
=
PROEFVERSIE@VANIN

4.6 Axis Unit Vector

A cartesian axis system is usually provided by 3D editors, grid paper or other means. There is however a mathematical underpinnig of the concept of such an axis system. For a 2D axis system, the cartesian grid typically consists of two orthogonal unit vectors, as demonstrated in the following figure:

A unit vector is a vector with length 1. In the following picture you can see that the unit vector u  x has a length of one unit and has the following definition: u x = (1 0)

PROEFVERSIE@VANIN

An axis unit vector is a vector that defines an axis in a coordinate system. In a 2D coordinate system, there are two basis vectors called u  x and u  y . In an orthogonal axis system the angle between vector u  x and u  y is 90°. Furthermore, when the two basis vectors both have length 1 we call the coordinate system orthonormal The second axis unit vector is defined as u  y = (0  1).

Chapter 4 Vectors 79

4.7 Multiply with Scalar

A vector can be scaled by multiplying the vector with a scalar. As the name suggest the new vector will be a scaled version of the original vector. The scale is said to be uniform because all the components of the original vector are multiply with the same scale factor.

This operation is written as follows, with s the scalar variable, v 1 the original vector and the result is v 2 which is the scaled vector.

PROEFVERSIE@VANIN

or with the value of s:

Definition

Multiplying with a scalar means multiplying all the components of the vector with that scalar:

Properties of the scale operation

The scale operation changes the magnitude of the vector but does not alter its direction. This means that you can use this operation to increase or decrease the speed of an object. In practice, you will typically use a unit vector to store the direction of a game object, and keep track of the speed in a separate variable. This makes it easier to alter the direction of a game object without changing its speed.

The speed itself is then the scalar that you can use to influence the speed of the game object.

Another interesting property is that if you scale a unit vector, the new length of the vector is the scale factor. You will apply this concept in the next section where you create polar coordinates.

v 2 = s * v 1
v 2 = 1.5 * v 1 ⃗ 2 ⃗ 1
⃗ 1 = 3 2 ⃗ 2 = ∗ ⃗ 1 = 1.5 3 2 = 1.5 ∗ 3 1.5 ∗ 2 = 4.5 3
Chapter 4 Vectors 80

4.8 Polar Coordinates

Polar coordinates are not only useful for defining unit vectors, they can also define vectors with a given magnitude and angle. You can use polar coordinates to give an object an initial speed and direction.

A vector can be defined with polar coordinates r and α. In this figure the following values have been set for these coordinates:

= 2 α = 34.38°

PROEFVERSIE@VANIN

The coordinate of the vector is then:

We can again apply the Pythagorean formula to prove that the length of vector v 1 is indeed equal to r = 2:

You can isolate r2 to get the following equation:

∗ ( ) ⃗
1
( )
1
| ⃗ 1 | = ( ∗ ( ))2 + ( ∗ ( ))2 = 2 ∗ ( ( ))2 + 2 ∗ ( ( ))2
| ⃗ 1 | = 2 ∗ ( )2 + ( )2 = √ 2 =
r
v
= (r * cos
α
*
α
=
=
Chapter 4 Vectors 81
1
(
) r
sin (
))
(2 * cos (34.38°2 * sin 34.38°) )
(1.65 1.13)

Example

The following example is a typical application of randomly generating interactive elements in a game. Animals, non playing characters and other moving elements of a game or animations will sometimes spawn in different random directions (vectors) and speed.

The goal is to create an ant game, with ants spawning in different locations, directions and speeds. Some ants can walk really fast, but they are no match for a walking human. The data for the three ants are:

• ant1: speed of 0.8 m/s and angle 120°.

• ant2: speed of 0.7m/s and angle 220°

• ant3: speed of 0.5m/s and angle 70°.

You can calculate the direction vectors for the three ants as an application of polar coordinates:

PROEFVERSIE@VANIN

For the radius of the polar coordinate you use the initial speed of the ant, and the angle is set to angle in which the ant should start moving.

The polar coordinate itself is also an example of multiplying a unit vector with a scalar, as seen in the previous section.

1 ⃗ 1 2 ⃗ 2 3 ⃗ 3
1 = 0.8 (120∘ ) (120∘ ) = −0.4 0.69
2 = 0.7 (220
) (220
) = −0.54 −0.45
3 = 0.5 (220∘ ) (220∘ ) = 0.17 0.47
Chapter 4 Vectors 82

4.9 Vector Operations – Add Vectors

Adding vectors is an operation that is used when dealing with physical forces or when calculating lighting equations for rendering in games or animations. The addition operation is performed on the separate components:

Adding up two vectors can be done in a graphical way by constructing a parallellogram. The tails of both vectors have to be at the same location.

PROEFVERSIE@VANIN

For the construction, add a helpline parallel to v 1 and starting at the the head of v 2 Create another helpline parallel to v 2 and starting at the head of v 1

The intersection of these two parallel helplines is the head of the resulting vector v 3 , and the tail is the same as the tail of the two vectors v1 and v 2.

⃗ 1 ⃗ 2 parallelto ⃗ 2 parallelto ⃗ 1 ⃗ 1 ⃗ 2 parallelto ⃗ 2 parallelto ⃗ 1 ⃗ 1 ⃗ 2 ⃗ 3
Chapter 4 Vectors 83

The graphical method to add two vectors is an educational tool to understand what the result of the addition would be. With game engines or 3D modelling software, this operation will be performed mathematically.

The addition operation is performed by components, meaning that you add all the x-components together to create the new x-component, and add all the y-components together to calculate the new y-component.

PROEFVERSIE@VANIN

4.10 Linear Combination

A linear combination of vectors means that you scale and add up vectors. In a cartesian grid this concept is used to create a system where every point is defined as the result of such a linear combination.

A further application is the concept of affine transformations where two new basis vectors create a new cartesian grid within the parent or world grid.

You can now use the scalar multiplication in combination with the vector addition to reach any point in 2D space, while only using the axis unit vectors. The scale factors for the linear combination are defined as s x and s y :

= 3 0

=

= ∗ = 0 2

With s x set to to 3 and s y set to 2.

The formula for the resulting vector is the addition of the scaled vectors:

= 3 0 + 0 2

= 3 2

In practice, it is far easier to use coordinates in the form (3 2). It would indeed be tedious to always write down coordinates in a cartesian grid in this manner. It is however important to understand the basics of defining a new cartesian grid, which will be important when you explore matrix transformations.

⃗ 1 == 3 1 ⃗ 2 == 0.5 3.5 ⃗ 3 = ⃗ 1 + ⃗ 2 = 3 + 0.5 1 + 3.5 = 3.5 4.5
⃗ ⃗ ⃗
⎧ ⎪ ⎨ ⎪ ⎩ ⃗
Chapter 4 Vectors 84
= ∗ + ∗ = ⃗ + ⃗

4.11 Angle of a Vector

With polar coordinates, you discovered how to create a new vector, starting with a radius and an angle. Sometimes, it is also useful to do the inverse operations, where you wonder what the angle is that a given vectors makes with the X-axis.

In games and animations however you must try to avoid these types of calculations, as they can be very expensive in terms of computing power.

The vector v 1 is defined as v 1 = (2.16 1.26) What is the angle that this vector makes with the horizontal axis? The angle is defined as the angle between the vector itself and the horizontal line going through the tail of the vector.

PROEFVERSIE@VANIN

The angle can be determined with the following formula:

The arctan function however has a limitation in that it only returns an angle in the interval (—π π). Furthermore, there is the potential for a division by zero (because we divide by x).

The better way is to use the atan2 function which is also available in Houdini: α = atan2 y , x = atan2 1.26 ,2.16 = 0.53

⃗ 1 x y ⃗ 1
( ) = = =
∘ Chapter 4 Vectors 85
30.37

4.12 Normalise a Vector

Normalising a vector means to scale a vector so that its length becomes one. The direction of the vector remains the same.

PROEFVERSIE@VANIN

The length of vector v  with components (2 1):

If you divide the vector v  by its length, the resulting vecor is a unit vector. This is also an application of multiplication with a scalar, since you can also consider this operation as the multiplication with the inverse of the length:

It is always a good idea to verify the result, which you can do by calculating the length of vector v  u , which should be 1 if your calculations are correct:

|⃗| ⃗
= | ⃗ | = 22 + 12 =
2.236
= ⃗ | ⃗ | = 2 1 2.236 = 0.894 0.447
| | =
= √1 = 1 Chapter 4 Vectors 86
0.8942 + 0.4472

4.13 Subtract Points

A vector can be defined as the subtraction of two points. To subtract two points you need to subtract the x-coordinates as well as the y-coordinates.

PROEFVERSIE@VANIN

This operation can be used to define velocity or displacement vectors. You can also use the resulting vector to calculate the distance between the two points.

4.14 Case Study

We conclude the chapter with a small case study of a simple top view 2D race car game that will enhance your knowledge about vectors.

How to model the data

The car model is a simple rectangle with a vector that indicates the direction of movement. Steering of the car can be done with four keys:

• A: turn left

• D: turn right

• W: speed up.

• S: slow down.

P
P
v
2 = (3 4)
1 = (2 7)
= P 2 –P 1 = (3 – 2 4 – 7 ) = (1 –3)
| 2 1 | = | ⃗ | = 12 + ( 3)2 = 3.2 1 2 ⃗
Chapter 4 Vectors 87

This is an application of vector math, so you will need to model the car with the following properties:

• C: The current position of the car. This is a point in the 2D world space.

• α : the angle relative to the X-axis of the world that indicates the direction of the car. This angle will be modified by keys A and D

• speed: The speed of the car in world units per second. This speed is modified with keys W and S. The maximum value for the speed is determined by the scale of the world. If the standard unit of the world is meter, a speed of 25m/s corresponds with 90 km/h .

The combination of the speed variable and the angle α form a polar coordinate: v  = (speed *cos (α) speed *sin (α))

PROEFVERSIE@VANIN

Animate the car

In the chapter about the sine function you learned about frames per second and how this relates to the concept of delta time: Δt = 0.067

If the game runs at a constant frame rate of 15fps (which is not always the case in games), you can use the value of Δt = 0.067s to calculate a new position for the car:

Chapter 4 Vectors 88

The following formula is the kinematic equation which relates position, velocity and time:

C’ = C + Δt *v

= C + Δt * (speed *cos (α) speed *sin (α)

PROEFVERSIE@VANIN

A prime character is used extensively in physics to indicate that the variable contains new information, calculated from previous (old) information.

4.15 Case Study 2

Control the angle

As mentioned at the start of the case study, two keys (‘A’ and ‘D’) will be used to control the steering angle of the car. Therefore, you will also want to define a speed for this angle change. If the angle changes too fast, it might be difficult to control the vehicle, on the other hand, if the angle changes too slowly, the game might be frustrating when trying to avoid obstacles.

As a good first attempt, it is worth considering how much angle difference you will allow in one second. For example, the allowed angle change might be 90° per second. You can again multiply with Δt to get the angle change in one frame. In this example, a framerate of 15fps is used, which results in a value Δt of 0.067s.

When the A key is pressed, the following positive update will be applied to the angle α , with the angle starting at 60°:

α’ = α Δt * 90°

= 60° + 0.067s * 90°

= 66°

When the D key is pressed, the following negative update will be applied to the angle α :

α’ = α + Δt * 90°

= 60° – 0.067s * 90°

= 54°

Turning to the left means turning counter clock wise, which is a positive angle change in the unit circle. Similarly, turning right is a clockwise turn, which results in a negative angle change in the unit circle.

Chapter 4 Vectors 89

Control the speed

The other two keys, ‘W’ and ‘S’, control the speed of the vehicle. To control the speed you need to set a maximum speed, for example 25m/s and a rate at which the car can accelerate. If you set the maximum acceleration to 5m/s, then it takes the car 5s to reach its top speed. The formulas to control the speed are quite similar to the formulas for the angle control, you need to use Δt again as the acceleration is defined per second. If the player presses the W key, the following positive update will be applied to the speed, that has a starting value of 6m/s :

PROEFVERSIE@VANIN

speed’ = speed + Δt * 5m/s

= 6m/s + 0.067s * 5m/s

= 6.333 m/s

If the player presses the S key, the following negative update will be applied to the speed, that has a starting value of 6m/s :

speed’ = speed — Δt * 5m/s

= 6m/s — 0.067s * 5 m/s = 5.667m/s

The formulas assume that Δt is a constant. In a simulation that might very well be the case, but in a game Δt might vary. Most game engines provide the Δt for each new frame, so you can accurately control the speed of objects.

Chapter 4 Vectors 90

Chapter 5

Vector Dot and Cross Product

PROEFVERSIE@VANIN

The concept of vectors allows you to model movement, and to calculate the distance between two points. In this chapter you extend your knowledge about vectors with two important operations: the dot and cross product. The dot product is also sometimes referred to as the scalar or inner product. While the dot product is defined for 2D and 3D space, the cross product is only defined in a 3D environment.

The dot and cross operation is supported by every game engine and 3D modelling software. The main reason behind the pervasive useage of these operations is the efficiency and performance of these two operations. As you will find out in this chapter, the dot and cross product can be calculated by a set of multiplications and additions, which is beneficial in terms of processor power.

The dot product can be used to calculate angles between vectors in a far more straightforward way then is possible with the triangle formulas. The dot product is also used as a mathematical tool to calculate lighting for games and rendering. There are so many problems that can be solved with the dot product that it can be described as the swiss army knife of game development.

The cross product is used to calculate a vector perpendicular to a plane or triangle. You can then use this perpendicular vector to calculate heights relative to the plane or to calculate lighting on a triangle.

Together with an understanding of the vector concept, the dot and cross product are an essential part of game development.

Chapter 5 Vector Dot and Cross Product 91

5.1 A First Example

A first use case for the dot product is shown in the figure below. Given a triangle defined by points A, B and C, you can calculate the relative height of point P to this triangle. This relative height is not the distance from the point to any of the points of the triangle, or the vertical distance from the point P to the triangle. The relative height is defined as the perpendicular distance from the triangle to the point P. This distance can be calculated by calculating the dot product of the normal n  and vector d . The normal is defined as a vector that is perpendicular to the triangle and you can calculate this vector with the cross product.

PROEFVERSIE@VANIN

In this chapter it is important that you start thinking in vectors. The dot and cross product are operations that work on vectors, and when tackling a problem you need to correctly identify the vectors that will be part of the solution.

5.2 A Second Example

The following example shows how the dot and cross product can be used to calculate lighting. In the scene, the familiar icosahedron is used and the question at hand is to calculate the intensity of the light at point P.

In this example (and specifically for all lighting calculations) it is important to work with unit vectors which allow you to efficiently calculate the required intensity at the requested point P. This point P is illuminated by the spotlight at position L

The examples of this chapter will always focus on a single point. This forms a good basis when you want to move on to shader programming, which calculates the lighting for all the pixels in a scene.

ℎ ⃗
Chapter 5 Vector Dot and Cross Product 92

PROEFVERSIE@VANIN

The point L represents a spotlight which emits light in all directions. The intensity of this light decreases with distance, but in this example we omit the distance factor.

The vector lN is the unit vector from the point P to the light source L. The normal n is defined as a unit vector that is perpendicular the triangle where P ….…..

The diffuse intensity is the result of the dot product of lN with n:

I D = lN n = 0.9085

This intensity will be a multiplication factor for the intensity of the light emitted by the spotlight L. In this instance, the point P will receive 91% of the intensity of the spotlight.

As you will find out in this chapter, the dot product is proportional to the cosine of α. This means that the light intensity will increase as this angle decreases. This is an important property of the dot product, and also one of the reasons why it is used so frequently. Chapter 5 Vector Dot and Cross Product

93
Hier mist tekst

5.3 2D Dot Product

The dot product is defined as the sum of the componentwise multiplication of two vectors

The symbol for the dot product multiplication is a dot, like the full stop at the end of a sentence. The dot product formula takes two vectors as operands and generates a scalar as result.

The dot product is an efficient way to calculate heights, lighting and even angles within a game or animation. It may seem daunting at first, but as you will find out in this chapter, the dot product offers a unified and fast way to solve the many trigonometric problems you will encounter while developing a game or animation.

PROEFVERSIE@VANIN

Let us start the discussion of the dot product with the statement of the algebraic form of the dot product formula. In the following sections you will delve into the principles underlying this algebraic form.

Given are two vectors v1 and v2 :

When the coordinates of the vectors are known, you can calculate the dot product with the following formula, which is the algebraic form of the dot product:

In other words, the dot product in 2D is the multiplication of x-components added to the multiplication of y-components. The result of the dot product for the vectors defined above is:

The result of the dot product is a single number, which has a trigonometric meaning. It may seem odd that a multiplication and addition of numbers might be proportional to an angle, but that is in fact a major reason behind the popularity of the dot product in game development.

⃗ 1 = 1.19 0.17 ⃗ 2 = 0.85 0.84
v1 v2 = v1xv2x + v1yv2y
⃗ 1 ⋅ ⃗ 2 = 1.19 0.17 ⋅ 0.85 0.84 = 1.19 ∗ 0.85 + 0.17 ∗ 0.84 = 1.16
⃗ 1 = ⃗ 2 = ⃗ 1 = 1.19 0.17 ⃗ 2 = 0.85 0.84 Chapter 5 Vector Dot and Cross Product 94

Back to the unit circle

To create an intuition for the dot product, you can take a look at the following situation within the unit circle, where a vector is defined on the horizontal axis, called v1 with coordinates (1  0). This vector is a unit vector.

A second vector v2 is defined as a polar coordinate with angle 34.38° and length 1, and is also a unit vector:

PROEFVERSIE@VANIN

According to the definition you need to multiply the x-coordinates of the two vectors, then the y-coordinates and add them up:

Because the y-coordinate of the first vector is 0 the term sin(α) is eliminated and the result is just cos(α).

If you apply the dot product in this situation, the result is the cos(α) with α the shortest angle between the two vectors. This is already an important implication of the dot product, but we cannot be sure yet that this is always true.

v1
(1  0) v2 = (cos(α) sin(α)) 1 2
=
1
1 0
1
⋅ 2 =
( ) ( )
⋅ 2 = ( ) ∗ 1 + ( ) ∗ 0 = ( )
95
Chapter 5 Vector Dot and Cross Product

Dot product with two unit vectors

Now you can take a look at the situation where a vector v1 is defined as a polar coordinate with an angle β, and with coordinates:

v1 = (cos( β ) sin( β ))

A second vector v2 is defined as a polar coordinate with an angle ɣ and length 1, and is also a unit vector: v2 = (cos(ɣ) sin (ɣ))

PROEFVERSIE@VANIN

We apply the definition of the dot product again: v1 ⋅ v2 = cos ( β ) cos (ɣ) + sin ( β ) sin (ɣ)

The formula above is one of the known identities in the sum and difference formulas and is equal to: v1 ⋅ v2 = cos ( β – ɣ) = cos(ɣ – β )

The angle between the two vectors is equal to ɣ – β, but it is equally valid to say that the angle is β – ɣ. Remember that the cosine of an angle is equal to the cosine of minus that angle: cos( β – ɣ) = cos( –( β – ɣ )) = cos(ɣ – β )

In other words, we cannot determine the sign of the angle with the dot product.

Again we find that the result of the dot product is the cos (ɣ – β ) with ɣ – β being the angle between the two vectors. The last step is to find out if this concept still holds if the two vectors are not unit vectors

1 2 1 2
Chapter 5 Vector Dot and Cross Product 96

Two non-unit vectors

The reasoning for the 2D dot product is now concluded by creating two vectors that are not defined on the unit circle, with v1 defined as a polar coordinate with length r1 and angle β and v2 defined as a polar coordinate with length r 2 and angle ɣ :

v1 = (r1cos( β ) r1sin( β )) v2 = (r 2cos(ɣ) r 2sin(ɣ))

PROEFVERSIE@VANIN

You apply the definition of the dot product again: v1 v2 = r1cos( β ) r 2cos(ɣ) + r1sin( β ) r 2sin(ɣ)

r1 and r 2 are common in both terms, so you can isolate them:

v1 v2 = r1r 2 (cos( β )cos(ɣ) + sin( β )sin(ɣ)) = r1r 2cos(ɣ – β )

As a conclusion for this case you can state: v1 ⋅ v2 = r1r 2cos( β – ɣ) = r1r 2cos(ɣ – β ) with r1 = |v1 | and also r 2 = |v2 | By convention we use the absolute value of the angle between the two vectors v 1 and v2

You can conclude that the equation for the dot product is an equality:

v1 v2 = v1xv2x + v1yv2y = |v1 | | v2 | cos (α)

With α the (shortest) angle between the two vectors. Note again that every element in this equation is a number (or scalar).

⃗ 1 ⃗
2 = | |
1
2
Chapter 5 Vector Dot
Cross Product 97
and

5.4 Angle between Vectors

A first use case for the dot product is the calculation of the angle between two vectors. This is possible when you know the coordinates of the two vectors, as you can calculate the left hand side of the equation and the length of both vectors, the only unknown is α :

Given are two vectors v1 and v2 . We can use the left hand side of the dot product:

PROEFVERSIE@VANIN

The right hand side of the dot product is

This is the multiplication of the lengths of the two vectors and the cosine of the smallest angle between these two vectors. The result must be equal to the value calculated for the left hand side of the dot product:

First you need to calculate the length of the two vectors:

You can then use this formula to calculate the angle between two vectors:

v1xv2x + v1yv2y = |v1 ||v2 |cos(α) ⃗ 1 ⃗ 2 ⃗ 1 ⃗ 2
| ⃗ 1 | = 2 + 2 = 2 | ⃗ 2 | = 2 + 2 = 1.5
| ⃗ 1 || ⃗ 2 | ( ) = + ( ) = + | ⃗ 1 || ⃗ 2 | = 1.09 (2 ∗ 1.5) = 0.36
v1 = (1 .910 .59) v2 = (0 111 5) v1 ⋅ v2 = v1xv2x + v1yv2y = 1.09
v1 ⋅ v2 = |v1 | |v2 | cos(α)
1.09 = v1xv2x + v1yv2y = |v1 | |v2 | cos(α) Chapter 5 Vector Dot and Cross Product 98

Chapter 5 Vector Dot and Cross Product

The angle α is then the arccos of this result:

) = 0.4 ⇒ = (0.36)

Cosine function

PROEFVERSIE@VANIN

As a reminder, the arccosine function means that you start with a value on the Y-axis and project horizontally and determine the intersection with the cosine function. Projecting down again on the horizontal axis results in the value of the angle α

(
=
= 68.75
-90∘ -45∘ 0∘ 45∘ 90∘ 135∘ 180∘ 225∘ = 68.75∘ ( ) = 0.36
99

5.5 Summary of the Dot Product

A problem that can be solved with a dot product always starts with two vectors that can be determined from the problem statement:

Formulas

PROEFVERSIE@VANIN

The two identities of the dot product can be confusing at first. The algebraic identity is defined purely in terms of the x and y coordinates of the two vectors. This identity is the one that is typically used when programming shaders and lighting and distance calculations. The main appeal here is that this scalar identity is very fast to calculate on the processor of a typical pc or laptop.

The algebraic identity is very useful if one or both vectors are unit vectors, as you will discover in the next sections.

The trigonometric identity uses lengths and angles as part of the formula. In game development you will typically want to avoid the use of arc functions, as they can be very slow compared to addition and multiplication.

With the arccosine function you can calculate the (shortest) angle between the two vectors v1 and v2 . Note however that this will also involve the calculation of the length of both vectors. For the length the square root function is necessary, which also takes a good amount of time on the processor to execute.

⃗ 1 ⃗ 2
v1 v2 = v1xv2x + v1y * v2y
v1 v2 = | v1 | | v2 | cos ( α )
Chapter 5 Vector Dot and Cross Product 100

5 Vector Dot and Cross Product

5.6 Dot Product and the Triangle

We start with a random triangle. This is not a right triangle! The coordinates of the points are known and are:

A = (2 1)

B = (7 3)

C = (1  7)

PROEFVERSIE@VANIN

Let us say we want to calculate the angle at point A called α

The dot product can be used to solve this, but you need vectors to be able to apply the dot product. These vectors will be constructed by calculating the difference between point A and B for the first vector, and the difference between the vector between point A and C

The first vector is the vector from A to B, which is calculated as follows:

You can visually verify that the vector v1 is indeed 5 units to the right and 2 units up.

X Y X Y X Y ⃗ 1
⃗ 1 = = 7 3 2 1
5
=
2
101
Chapter

The second vector is the vector from A to C, which is calculated as follows:

PROEFVERSIE@VANIN

Now that v1 and v2 have been determined, you can establish the angle α, by calculating the scalar identity and the lengths of the vectors first:

With these values, you can now calculate the value of cos(α):

Finally, with cos(α) known you can calculate α :

X Y ⃗ 1 ⃗ 2
| ⃗ 1 | = 52 + 22 ≈ 5.39 | ⃗ 2 | = (−1)2 + 62 ≈ 6.08 + = 5 ∗ −1 + 2 ∗ 6 = 7
( ) = + | ⃗ 1 || ⃗ 2 | ≈ 7 (5.39 ∗ 6.08) ≈ 0.21
( ) ≈ 0.21 ⇒ ≈ ⇒ ≈ 77.66∘
⃗ 2 = = 1 7 2 1 = −1 6 Chapter 5 Vector Dot and Cross Product 102

5.7 Height Calculation

Another use case for the dot product, and one that is used frequently in game development, is height calculation. When you want to calculate a height relative to a surface (such as a triangle), the calculation can be done very efficiently with the algebraic identity of the dot product.

In this first example you will see how you can determine when the female hero in the story lands on the platform. The height could be a factor in the animation of the hero character, or it could be part of a gameplay mechanic. The example is interesting because it involves many different trigonometric formulas and finally uses the dotproduct to calculate the height relative to the platform.

The coordinates of the points that you need to solve this problem are the following:

P = (- 0 5 2 6)

A = (0 1)

B = (3 2)

The variable that you need to calculate is h, which is the relative height of P to the platform defined by A and B

The first step in the calculation is to determine the normal of the platform. The normal should be a vector that is perpendicular to the platform, so let’s start with the vector from A to B: p = B – A = (3  1)

You can calculate the angle α that this vector makes with the horizontal axis by applying the arctan function:

18.43∘

Chapter 5 Vector Dot and Cross Product 103
= = 1 3 =
PROEFVERSIE@VANIN

The next step is to create the normal n . The vector p is parallel to the platform, so the normal vector n is 90° further in counter clockwise direction: β = α + 90° = 108.43°

The normal is then a polar coordinate with radius = 1 and angle equal to β: n = (cos( β ) sin( β )) ≈ (- 0 32 0 95)

PROEFVERSIE@VANIN

The final step is to calculate a vector from a point on the platform to the center of the player:

vP = P – C = (-2 1 .1)

The trigonometric identity of the dot product of v P and n ^ is:

vP ⋅ n = |vP | |n| cos(δ)

Because |n ^| == 1 by definition (it is a unit vector) the formula simplifies to:

vP n = |vP | cos(δ)

Surprisingly, the last step produces the requested height value h. Let us circle back and analyze the triangle that was formed in this last step. This triangle is a right triangle due to the manner in which it was constructed. The length of vector vP is the hypotenuse of this right triangle, and h is the adjacent side if you look at the situation from point C and angle δ.

ℎ ⃗
Chapter 5 Vector Dot and Cross Product 104

Chapter 5 Vector Dot and Cross Product

In this right triangle you can use the CAH formula:

PROEFVERSIE@VANIN

By isolating h you get the following formula:

To summarise, you get a formula from the dot product and a formula from looking at the problem as a right triangle:

Combining these two formulas, allows you to get rid of cos(δ) and you get:

The last step is now to calculate the height h and this is where you can get confused. The main goal of using the dot product in game development is to get rid of trigonometric functions as much as you can. If you have the coordinates of the two vectors in the dot product you have to prefer the algebraic form of the dot product. In this case, the coordinates of n and vP are known, so you can use the algebraic identity directly:

This method only works because you created a normal n ^ which is a unit vector. Another remark is that you used the arctan function to calculate an angle which can be costly. However, this calculation can be done before your game or animation starts and if the platform is fixed in the world, you only have to calculate this normal once.

ℎ ⃗
( ) = = ℎ | ⃗ |
h
vP
cos
δ
= |
|
(
)
vP ⋅ n = |vP | cos(δ
h = |vP | cos(δ
)
)
h = vP n
ℎ = ⃗ ⋅ = −2 1.1 ⋅ −0.32 0.95 = −2 ∗ −0.316 + 1.1 ∗ 0.949 = 1.68
105

5.8 3D Vectors

In most cases a game or animation takes place in a 3D world. Therefore, it is necessary to define what vector operations mean in a 3D world.

As a reminder, a 3D vector has an additional z-component, and can be written in row format or in column format:

PROEFVERSIE@VANIN

An example with values for the coordinates:

The operations that were defined for 2D vectors also work in exactly the same way for 3D vectors, but with taking the additional z-coordinate into account. For example, the addition of two 3D vectors means that you need to add the components of the two vectors. With v1 and v2 given as:

The addition is:

The important operations on 3D vectors for game development and animation involve the length, dot product and cross product of 3D vectors. These are essential operations that you have to understand to apply them correctly. The operations in more detail:

• Length of a 3D vector: The length of a 2D vector is given by 2 + 2 . As you will find out, the length of a 3D vector has the same concept of the square root of the sum of squares: 2 + 2 + 2 . The derivation of this formula is again an application of the Pythagorean theorem: a 2+b 2=c 2 .

⃗ 1 = ⃗ 1 =
⃗ 1 = 1 4 7 ⃗ 1 = 1 4 7
⃗ 1 = 1 4 7 ⃗ 2 = 3 −1 2
⃗ 1 + ⃗ 2 = 1 4 7 + 3 −1 2 = 4 3 9
Chapter 5 Vector Dot and Cross Product 106

Chapter 5 Vector Dot and Cross Product

• Dot product of a 3D vector: The formula of the dot product is defined by taking the additional z-component into account. This means that the algebraic identity of the dot product has the additional multiplication of the z-components, but the trigonometric identity remains the same as it is the multiplication of the lengths of both vectors with the cosine of the shortest angle between the two vectors.

• Cross product of a 3D vector: this is a new operation that creates vector that is perpendicular to two other vectors.

Length of a 3D vector

PROEFVERSIE@VANIN

We start with vector v  with coordinates (v x v y v z). u x, u y and u z are unit vectors that are perpendicular to one and another.

The most straightforward path is to calculate the length of vector vP which is the projection of vector v  on the X Y-plane. Vector vP is then defined as:

vP = (v x   v y 0)

Which is the same as vector v  but with the z-coordinate set to 0. You can consider a 3D vector with a z-coordinate set to 0 as a 2D vector and the length formula for such a vector is:

⃗ 2 + 2

⃗ ⃗ ⃗ 0
107

With the length of vP known you can now calculate the length of v  by considering the right triangle formed by vP and v  One of the short sides of this right triangle is vP , and the other short side is the z-coordinate of v , which is equal to v z .

The length of is: | ⃗ | = ⃗ 2 + 2 = 2 + 2 + 2

PROEFVERSIE@VANIN

Example

What is the length of the vector v = (2 . 2 2 .3 2.5)?

The length of the vector v  with components (2 . 2 2 .3  2.5) is: | ⃗ | = 2 + 2 + 2 = 2.22 + 2.32 + 2.52 ≈ 4.05

Dot product of 3D vectors

The dot product for 3D vectors is an extension of the concept in 2D. The trigonometric identity is exactly the same with the angle α defined as the shortest angle between the two vectors.

Given are two 3D vectors v1 and v2 which are defined as:

• v1 = (1 2  2)

1

• v2 = (3 1 1)

⃗ 0
⃗ 2
Chapter 5 Vector Dot and Cross Product 108

The trigonometric identity is defined as: v1 ⋅ v2 = |

| |v2 | cos(α)

And the algebraic identity now has the following form:

PROEFVERSIE@VANIN

The vectors in the previous figure are defined as:

v1 = (1 2 2)

v2 = (3  1 1)

The result of the algebraic identity is: v1 ⋅ v2 = 1 * 3 +2 *1 + 2 * 1 = 7

If you are interested in the angle between the two vectors, there is some more work to do. First task is to calculate the lengths of the two vectors:

With the trigonometric identity you now have:

You need to isolate cosα to calculate the angle which gives:

Then, finally, you can calculate angle α with the arccos function:

The principle of calculating an angle in 3D space is exactly the same as the calculation in 2D space. Remember that you need to add the additional z-components in the algebraic form, and that the calculation of the length also uses the length formula for 3D-vectors.

⃗ 1 ⃗ 2
| ⃗ 1 | = 12 + 22 + 22 = 3 | ⃗ 2 | = 32 + 12 + 12 = 3.317
|v 1
v2
cos
α
= v 1 v2
| |
|
(
)
= 7
( ) = ⃗ 1 ⋅ ⃗ 2 | ⃗ 1 || ⃗ 2 | = 7 3 ∗ 3.317 = 0.704
cos(α)
0.704 ⇒ α = arccos(0.704) = 45.29°
=
v1
v1 ⋅ v2 = v1xv2x + v1yv2y + v1zv2z Chapter
109
5 Vector Dot and Cross Product

Projection with the dot product

When one of the vectors is a unit vector (a vector with length 1) then an interesting property arises:

Given are two vectors.

• Vector u is a unit vector with length 1

• Vector v  is another vector with a different length.

You can calculate the value of the dot product, which returns a number:

u ⋅ v  = 3

This number (the result of the dot product) is the length of the projection of v  on the vector defined by u.

To prove this length we again use the trigonometric form of the dot product formula:

u v  = |u ^| |v | * cos(α)

u is a unit vector, so |u | == 1, and you can simplify to:

u ⋅ v  = |v | * cos(α)

PROEFVERSIE@VANIN

The next step is to once again consider the right triangle formula (CAH):

Adjacent = Hypothenuse * cos(α)

The length of the Adjacent side is given by the dot product:

Adjacent = u ⋅ v

u is a unit vector so you now also scale this unit vector with this length to get the projected vector u s :

u s = Adjacent * u

u s = (u ⋅ v ) * u

⃗ ⃗ ⃗ ⃗
Chapter 5 Vector Dot and Cross Product 110

5.9 Cross Product

The cross product is normally defined for dimensions higher than two. In three dimensions, the cross product is defined as an operation, creating a vector that is perpendicular to two other vectors. A perpendicular vector is typically called a normal vector.

v1 × v2 = n

The resulting normal vector is perpendicular to vectors v1 and v1 , which means that you can check the result of the cross product by applying the dot product as cos(90°) is 0:

PROEFVERSIE@VANIN

To calculate the cross product we need to define the basic operations of the cross product on the axis unit vectors. With those basic operations as a starting point, you can derive the cross product formula for two arbitrary vectors.

Cross product of axis unit vectors

In 3D, the axis unit vectors are the three following vectors:

To define the basic operations of the cross product, you need to find the results of the following nine cross products:

Notice that in this table there are operations that may seem the same, for example is u x × u y not the same as u y × u x ? You are probably used to the concept that a product (or multiplication) is commutative, which means that the order of the multiplication is irrelevant: 2 * 3 == 3 * 2. However, you will see that the cross product is not commutative and that the order of the operands does matter.

⃗ 1 ⋅ = | ⃗ 1 || | (90∘ ) = 0 ⃗ 2 = | ⃗ 2 || | (90∘ ) = 0
u x = (1  0 0) ⇒ |u  x| = 1 u  y = (0 1  0) ⇒ |u y| = 1 u  z = (0 0 1) ⇒ |u  z| = 1
u x × u x u y × u x u z × u x u x × u y u y × u y u z × u y u x × u z u y × u z u z × u z
Chapter 5 Vector Dot and Cross Product 111

Unit vector x itself

First, you take a look at the following cross product:

u x × u x

Here you try to get a result from applying the cross product of a vector to itself. There are however an infinite number of vectors that satisfy the condition that the result is perpendicular to u x :

PROEFVERSIE@VANIN

The vectors v1 and v2 are perpendicular to u x . In fact, every vector of the form: v  = (0y z) satisfies the condition that it must be perpendicular to u x :

The cross product of a vector with itself is undefined, in the sense that there are an infinite number of vectors that are perpendicular to this vector. We present this by setting the result of this operation to the null vector:

u x × u x = (0  0  0)

u x × u x = (0  0  0)

u x × u x = (0  0  0)

⃗ 1 ⃗ 2
v
v  u x
⊥ u x ⇒
== 0 (0   x   y) ⋅ (1  0 0) == 0 0 * 1 + x * 0 + y * 0 == 0
Chapter 5 Vector Dot and Cross Product 112

Unit vector x with y and z unit vector

What would the result be if you take the following cross product?

u x × u y

u x and u y are vectors on the ground plane or X Y-plane, so the only way is up or down.

PROEFVERSIE@VANIN

u x and u y are on the ground plane, so the only way is up or down. Indeed, vector u z meets our requirements and we can also check this with the dot product:

However, vector u zn is also a possible solution:

So the big question is: How do you decide which one of the two vectors to choose?

⋅ = 1 0 0 ⋅ 0 0 1 = 0
=
0 0 0 0 −1 = 0 Chapter 5 Vector Dot and Cross Product 113
1

Out of the two possible solutions, we choose the solution that follows the right hand rule

To use the right hand rule, place the little finger of your right hand on the first vector. Then, it must be possible to close your hand in the direction of the second vector

PROEFVERSIE@VANIN

1

When using this rule you get the following result:

u x × u y = u z = (0 0 1)

But if we reverse the order of u x and u y then we get a different result:

u y × u x = –u z = u zn = (0  0 –1)

The cross product is anticommutative. This means that if you change the order of the operation, the result will be different. For the cross product, reversing the order results in the same vector but with the direction flipped: v1 × v2 = n ⇒ v2 × v1 = –n

Completion of the table of cross product

Combining the knowledge from the previous two tables you can construct the following table where the last three rows and columns show the result of the cross product of a vector of the first row with a vector of the first column (in that order):

u x u y u z

u x 0 –u z u y

u y u z 0 u x

u z –u y u x 0

This table will be the basis for calculating cross products for two arbitrary vectors, meaning two vectors with x, y and z components.

2
Chapter 5 Vector Dot and Cross Product 114

Distributivity

We need an additional property for the cross product to get to the final cross product formula. You probably remember the distributive property for the regular product:

(a + b) * c = a * c + b * c

(2 + 5) * 3 = 2 * 3 + 5 * 3 = 21

This same distributivity also works for the cross product: (v1 + v2) × v3 = v1 × v3 + v2 × v3

PROEFVERSIE@VANIN

The distributive property of the cross product is given without proof. It is possible to see this as a necessary property for the cross product. The existing proofs depend on the actual formula for the cross product, so proving this property is a chicken-and-egg problem.

Cross product of two arbitrary vectors

We start with two vectors given by:

A 3D vector can be written as a linear combination of scaled unit vectors:

We take the cross product of vectors v1 and v2, but express them with the unit vectors:

With the distributive property, this leads to 9 cross products that we need to calculate, similar to the table of unit vector cross products, but now with scale factors and this results in a summation of cross products:

We can now apply the table of unit vector cross products to get the following result: (0 0 0) + –

v1
2x
= (v1x v1y v1z) v2 = (v
v2y  v2z)
v1 = v1x * u x + v1y * u y + v1z * u z v2 = v2x * u x + v2y * u y + v2z * u z
(v1x * u x + v1y * u y + v1z * u z ) × (v2x * u x + v2y * u y + v2z * u z )
v1xv2x (u x × u x ) + v1yv2x (u y × u x ) + v1zv1x (u z ×u x ) v1xv2y (u x × u y ) + v1yv2y (u y × u y ) + v1zv2y (u z ×u y ) v1xv2z (u x × uz ) + v1yv2z (u y × u z ) + v1zv2z (u z ×u z )
v1z
1x
y
Cross Product 115
v1yv2xu z +
v
u
v1xv2yu z + (0 0 0) + –v1zv2yu x -v1xv2zu y + v1yv2zu x + (0 0 0) Chapter 5 Vector Dot and

Gather the terms per unit vector

We can now apply the table of unit vector cross products to get the following result:

If you gather the factors by unit vectors you get the following formula as a result:

PROEFVERSIE@VANIN

And the shorter notation for a linear combination of unit vectors leads to the formula for the cross product of two vectors:

Length of the resulting vector

When you calculate a cross product, the resulting vector has a length which is determined by the lengths of the two operands, and the sine of the angle between these two vectors. The following example demonstrates the concept of calculating the cross product and determining its length:

Applying the formula for the cross product gives the following result:

From this result it should be clear that the resulting normal vector has a length bigger than 1. The length of this vector is given by the following formula:

With α the angle between the two vectors.

(0  0  0
+ –v1yv2xu z + v1zv1xu y v1xv2yu z + (0  0  0) + –v1zv2yu x –v1xv2zu y + v1yv2zu x + (0  0  0)
)
v1 × v2 = (v1yv2z – v1zv2y) u x + (v1zv1x – v1xv2z) u y + (v1xv2y – v1y *v2x) u z
⃗ 1 × ⃗ 2 =
⃗ 1 = 2 1 3 ⃗ 2 = 4 5 2
= ⃗ 1 × ⃗ 2 = 1 ∗ 2 5 ∗ 3 3 ∗ 4 2 ∗ 2 2 ∗ 5 4 ∗ 1 = −13 8 6
| n | = | v1 | | v2 | sin ( α )
Chapter 5 Vector Dot and Cross Product 116

In most cases the cross product will be used to create normal vectors for a 3D mesh. The important aspect that you should realise here, is that after using the cross product, the resulting vector must be normalised if you want to use this vector in lighting calculations.

5.10 Cross Product Example

To conclude this chapter, the following example demonstrates the process of generating a normal vector for a 3D triangle, that could be part of a mesh. The various steps offer the possibility to review operations with 3D vectors and also offer insight into the practical aspects of the programming that goes into a game egine or 3D modelling software.

PROEFVERSIE@VANIN

The cross product operation calculates a new vector that is perpendicular to two other vectors. If you start with points on a triangle, the first step is to calculate two vectors on this triangle. The points of the triangle are given by:

As a first step we calculate the vector that is defined as the vector from A to B and we call this vector v1

⃗ 1
A = (1 . 5  0 .2  0.3) B = (1 . 8 1 .2  0.5) C = (0 . 5  0 .8  0.1)
⃗ 1 = = 1.8 1.2 0.5 1.5 0.2 0.3 = 0.2 1.1 0.2 Chapter 5 Vector Dot and Cross Product 117

As a second step we calculate the vector that is defined as the vector from A to C and we call this vector v2

PROEFVERSIE@VANIN

Now we can calculate the normal with the cross product, which is represented by n in the picture. The formula for n  is:

Finally, for most calculations it is important to normalise this normal, visualised as nN

⃗ 1 ⃗ 2 ⃗ 1 ⃗ 2 ⃗ 1 ⃗ 2
⃗ 2 = = 0.5 0.8 0.1 1.5 0.2 0.3 = −1 0.6 −0.2
= ⃗ 1 × ⃗ 2 = = −0.29 −0.1 1.19
=
= −0.24 −0.08 0.97 Chapter 5 Vector Dot and Cross Product 118
| |

Chapter 6 Lighting

In this chapter we discuss the physical and mathematical principles that are the basics for lighting calculations in a 3D game. Most game engines use a rasteriser for 3D rendering, which means that an approximate model of real life lighting is used, or that realism is thrown out of the window altogether for the creation of a ‘cartoony’ rendering style.

PROEFVERSIE@VANIN

Rasterisation works by transforming triangles from world space into camera and applying textures and other effects to calculate the final pixel colour.

One of the weaknesses of the rasteriser is that shadows and reflections are somewhat harder to accomplish. The main reason is that a rasteriser works on individual objects in the scene, and the environment of the object can only be communicated via special means (e.g. environment textures, shadow maps, ...).

Raytracing works by shooting rays into the world from the location of the camera as a starting point. If the ray hits a 3D object, the colour of that particular pixel can be determined.

The principle of raytracing has gained popularity, as the most recent graphics hardware is now capable of supporting the many calculations that are needed to render the final result for games. In the visual effects industry the concept of raytracing has, of course, been possible since the late eighties, with the movie “Tin Toy” being the first example of the use of the RenderMan software.

6.1 Colour

Lighting mostly takes place in RGB (Red, Green, Blue) space or sRGB (standard RGB) space. sRGB was introduced by Microsoft, HP, and others to make it easier to use the same colour system for monitors, printers, and the internet. The use of red, green and blue stems from the fact that the human eye has separate vision cones for these three colours.

A value with 3 components can also be called a vector and it is indeed a standard approach in games and animation to represent a colour as a vector:

c1 =   (127 127 255)

This vector would have the value 127 for red, 127 for green and 255 for blue. The range (0 255) for colours is used extensively in editors, such as Photoshop, Gimp, Blender, and other ones. It is, however, also common to represent RGB colours by values between 0 and 1:

Chapter 6 Lighting 119

c 2 = (0 . 5 0 .5 1)

Colour c 2 above would represent the same colour as colour c1, but now with floating point values. It is a common mistake to use the wrong range when dealing with colours.

One important operation on colours is the multiplication by a scalar value. You typically want to change the intensity of a colour with this operation. For example, you might want to calculate a colour that is 2 times as bright as another colour (remember that multiplying a vector by a scalar means multiplying all the components with that scalar):

c 3 = 2 c1

= 2 (127 127 255)

= (254 254 510)

PROEFVERSIE@VANIN

The problem here is that we want to keep the colour values within the allowed range. The value for the blue channel is too high and you will want to keep this value within the range (0 255), so the actual result for c 3 will be:

c 3 = clamp (2 c1, 0, 255)

= (254 254 255)

The clamp function clamps a value between the provided range, in this case between the value of 0 and 255. Due to the way that colours are calculated in shaders, this function is also used to clamp light intensities in the scene within the accepted range of (0 1).

Another way of dealing with colour components that are too large is the maxToOne -function. With this approach you determine the largest component and then divide by that component. This results in a different colour from the one with the clamp method, but keeps the tint of the colour more in line with the colour you started with.

For lighting in games and animations you want to be able to set an intensity for part of the 3D mesh. This intensity can be the result of a light source that shines on this mesh. In the figure below you can see the different intensities in the two tiles.

Vectors are used to determine the direction from the tile to the light source, and this in turn determines the intensity. As you can intuitively understand, if a light source is directly above a tile, this tile will receive a lot of light and show an intense colour:

The base colour of the tiles is c g = (60 179 113). The calculated intensity will determine the final colour of the tile.

c g1 = I1 * c g = 0.9 * c g = (54 162 102)

c g2 = I 2 * c g = 0.69 * c g = (41  123 77)

As an additional detail, notice that the vectors in the figure above are unit vectors. By normalizing the light vectors (and all the other vectors in a lighting setup) you can efficiently use the dot product to calculate all the light contributions.

1 2
Chapter 6 Lighting 120

6.2 Reflection

In this part of the course you will model light rays as vectors. A first important concept is the reflection of a vector (light ray) from the surface of a material. Here is a reminder on how to create a unit vector from one point to another:

PROEFVERSIE@VANIN

The convention that you will use in this chapter is that light rays aim towards the source of the light from the point on the surface. The figure below demonstrates the concept of reflecting a vector according to this convention. You will learn the reflection formula for vectors in 2D and 3D from a surface in the section about specular reflection

The first step in the reasoning is that you need to create a unit vector that represents the light coming from light source L. By convention, the direction of this incoming light vector lN is reversed

In a 2D situation you have more freedom on how to approach the problem of calculating the reflection. However, in 3D, the only efficient method is to use normal n from the surface. You can see here that the angle between vector lR and normal n  must be equal to α

In many of the figures throughout this chapter the angles between the light vector and the normal will be displayed. It is a common pitfall for students to want to calculate these angles. However, you will use the dot product to calculate reflections and lighting intensities.

= | |
Chapter 6 Lighting 121

6.3 Refraction

When a light ray goes from one medium to another, the light is refracted:

PROEFVERSIE@VANIN

The refraction can be calculated with Snell’s law which states the following: ( ) 2 = ( ) 1 with n1 and n2 the refractive indices of the two media. For example, the refractive index of water is 1.33 and the refractive index of air is 1.00003.

Note: This is actually an important point of physically based rendering (PBR). By trying to work in a physically accurate way we can use actual physical values. So instead of tweaking all the values in a rendering we can just look up values from real life measurements.

The figure below shows an example of a light ray that is refracted in a medium. This medium does not have to be a fluid or transparent medium, the only requirement is that there is a transition from one medium (such as air, water, plastic, ...) to another.

In the picture, the values for the different angles and refractive indices are:

n1 = 0.2 n2 = 0.4 α = 49.89° β = 18.46° Chapter 6 Lighting 122

6.4 Types of Lighting

The following section describes a simplified model of light. It is a lighting model that has typically been used for games since the early beginning in the 1990s because it is easy to understand and efficient for calculating. However, there are more advanced models in use now, such as PBR (Physically Based Rendering), which offer higher realism, albeit at the cost of increased complexity and necessary computing power. Although we will not discuss the mathematical complexity of PBR, it is still useful to understand the simplified light model, while using the qualitative aspects of PBR .

PROEFVERSIE@VANIN

Diffuse light

Diffuse reflection means that the incoming light is equally scattered in all directions. You can get an idea of diffuse lighting when you observe your environment on a cloudy day. There are no bright reflections, only the soft gradients generated by the light coming from all directions.

The clouds in this scenario act as a layer that scatters the photons from the sun in all directions, thus creating a diffuse light. As the sun is far away from the earth, the light coming from the sun can be called parallel vectors. These light vectors (light rays) are then scattered by the clouds in all directions, creating a diffuse lighting effect.

Within a medium (a material such as plastic, wood, metal or other) the same scattering occurs, generating a diffuse lighting effect from this material:

clouds groundlevel ⃗ ⃗ ⃗ ⃗ ⃗ ⃗ ⃗ ⃗ ⃗
Chapter 6 Lighting 123

The light is scattered multiple times within this object. It is eventually refracted again, from the object, making its way back to the original medium at approximately the same point where it initially entered.

PROEFVERSIE@VANIN

Diffuse materials are absorbent. If the refracted light travels too long in such materials, it may be absorbed completely. If the light does exit this material, it has probably travelled only a very small distance from the point of entry. The figure below shows an example of an extremely absorbent material called vanta black, which creates an unusual effect:

Specular light

Specular reflection follows the law of reflection, which states that on a perfectly planar surface the angle of reflection is equal to the angle of incidence. In other words, the surface of a highly reflective surface acts as a mirror that reflects the light rays almost perfectly. In the real world a mirror is the closest resemblance to a perfect mathematical reflection.

Chapter 6 Lighting 124

Materials such as polished copper or brass also have mirrorlike properties, but there will be extra distortion involved. In the figure below, this is visualised as the reflection of a light ray on the surface which bounces off in different directions albeit with a minimal spread:

Smoother surfaces will keep specular reflections focused and they will appear brighter or more intense when viewed from the proper angle.

PROEFVERSIE@VANIN

Most surfaces are irregular (e.g. brushed metal, steel, ...), and the reflected directions will vary randomly based on the surface’s roughness. This changes the reflected light directions, while the light intensity remains constant.

Rougher surfaces will have highlights that are larger and that appear dimmer ⇒ diffuse. However, the same total amount of light is reflected in both cases.

Chapter 6 Lighting 125

Fresnel reflection

The Fresnel effect is a light refraction effect that occurs when light hits an object at very acute angles. This can create, for example, a reflective effect on roads on hot summer days and most game engines can even simulate the picture below if the material properties of the road are set correctly:

PROEFVERSIE@VANIN

Fresnel is also typicall used as an effect to create soft lighting on the edges (relative to the viewer) of smooth objects. A rough surface, such as a wooden handle that has not been sanded and/or oiled, will not demonstrate the Fresnel effect.

The Fresnel effect is related to refraction of light. We typically think that refraction of light only occurs in liquids, but on the edges of objects some refraction can take place too. Light ray lN coming from light source L would not normally reach the eye of the observer. However, the light ray glances the object and is refracted by the outer layer of the material.

Chapter 6 Lighting 126

6.5 Lighting Calculations

Now that you know the qualitative aspects of the different lighting types it is time to turn our attention to the calculation of diffuse, reflection and Fresnel.

Diffuse lighting

Diffuse lighting is the most straightforward to calculate. You can check the following figure for an indication of the formula that you can use:

PROEFVERSIE@VANIN

Notice that as angles α1 to α4 get bigger, the amount of light on the tiles diminishes. In other words, the amount of light on the tile is only determined by the angle between the light vector and the normal

As you may suspect, the light intensity can be calculated by using the dot product of the normal and the light vector. The following table shows the calculation for the intensities of the four tiles. Keep in mind that a lower intensity means a darker tile:

The dot formula has been used here to calculate the intensity of the entire tile. The correct term for this type of lighting is flat shading. In games and animation it is possible to calculate the diffuse lighting for every pixel of the screen, which typically results in a gradient colour effect.

2 1 4 3 2 3 4 1
I1 = lN1 n1 = 1 : α1 = 11.35° I 2 = lN2 ⋅ n2 = 0.9 : α 2 = 31.07° I 3 = lN3 ⋅ n3 = 0.7 : α 3 = 45.11° I4 = lN4 ⋅ n 4 = 0.6 : α4 = 54.57°
Chapter 6 Lighting 127

Distance

Sunlight is an important factor in games and with the dot product formula it is possible to calculate the diffuse lighting of sunlight. For sunlight the distance to the sun can be considered constant. The light calculation does not change, whether you are standing on a mountain or at sea level. For spotlights. however, this distance is important and follows what is called an inverse square law. Light source L (e.g. a spotlight) shines in all directions at source strength S (in games or simulations the unit for S can be whatever the game engine or renderer prefers).

PROEFVERSIE@VANIN

1 2 3 Point
intensity
to: 1 = 4 2 = 4
2 = 4 2 = 8
3 = 4 2 = 36 Chapter 6 Lighting 128
P1 is at distance 1 and will receive light at an
equal
The point P2 is at distance 2 and its intensity will be equal to:
Finally for point P 3 at distance 3, the intensity will be equal to:

Overview and 3D example

The necessary calculations for diffuse lighting can be summarised as follows in the case of a light source that models a sun:

• Determine the light vector (from point P to light source L ) and normalise this vector.

• Determine the normal vector of the triangle.

PROEFVERSIE@VANIN

• Calculate the dot product of the normal vector and the light vector and multiply by the source strength of the sun.

If the light source models a spotlight, you need to take the following steps:

• Determine the light vector (from point P to light source L ) and normalise this vector. Also, determine the distance between point P and light source L and call it distance r.

• Determine the normal vector of the triangle.

• Calculate the dot product of the normal vector and the light vector.

• Calculate the maximum intensity by using the formula: = 4 2

The following figure demonstrates the steps for a spotlight:

The distance between lightsource L and P is used to decrease the intensity of the light. We call this distance r and it is calculated using the following formula: r = |L – P |

The maximum intensity at point P is then calculated using the inverse square law: = 4 2

The light intensity on P is then the multiplication of this maximum intensity and the dot product of the light vector and the normal vector: I D = I M ( lN ⋅ nN)

Chapter 6 Lighting 129

Diffuse lighting examples without distance

In the following example, the distance is not taken into account. For each point on the sphere, the dot product at that point is taken with light vector lN . It is possible that this dot product is negative, so when calculating lighting (or when implementing them in shaders), it is necessary to check for (and clamp) negative values.

PROEFVERSIE@VANIN

This example does not use the inverse square law to reduce the lighting over distance. The intensity of the light does not fade, so the sphere that is further away from the light receives the same amount of light as the sphere in front.

Diffuse lighting example with distance

When using the distance formula (in other words the light is a spotlight), the light intensity diminishes with the square of the distance. For reference, the distance between L and S1 is equal to 1.9 units. You can see that, even with a source strength set to 50, the light output is reduced to practically nothing, even over short distances.

This example uses the inverse square law formula. Notice how the second sphere receives almost no light at all, while the sphere in front receives a lot of light. The source strength is set to 50, while the distance between the light and the first sphere is about two 2 units.

1
1
Chapter 6 Lighting 130

Specular lighting

Specular lighting is the reflection of a light source on an object. Some of the reflected light will be directed towards the viewer, or the virtual camera. An important part of specular lighting is to calculate such a reflected vector.

Another technique for specular reflection is the halfvector technique, which is a lot easier to understand and bring into practice.

Reflecting a vector over a normal

PROEFVERSIE@VANIN

Before you can use specular lighting, you need to understand how to reflect a vector from a surface. The example shows how you can do this in 2D, but the algorithm is set up in such a way that the resulting formula can also be used in a 3D situation.

• P: The point on a surface where a vector will be reflected.

• L: The position of the light.

• lN: The unit vector that indicates the light direction.

• nN: The normal of the surface, which is also a unit vector.

We calculate the projection of lN on vector nN using the dot product: h = lN ⋅ nN = cos(α)

Chapter 6 Lighting 131

We can now use length h and create a vector: v h = –h * nN v h

is a vector with length h, but it is antiparallel to the normal vector nN. In other words, vector nN is pointing away from the surface and vector v h is pointing towards the surface.

PROEFVERSIE@VANIN

Adding vector v h a second time, creates mirrored vector lM: lM = lN – 2 h nN

This mirrored vector is interesting, but it is not yet what we want. You can flip this vector to generate the desired reflected vector.

The final reflected vector lR can be calculated by flipping vector lM: lR = – lM

ℎ ⃗ ℎ ℎ ⃗ ℎ ⃗ ℎ ℎ
Chapter 6 Lighting 132

To summarise, you start with a light at a position L that shines on a point P of a surface. The normal of this surface is given as n N . The first step is to calculate the normalised light direction: = ( ) | |

The next step is to calculate the dot product of this light vector and the normal. Note that this also corresponds to the diffuse intensity:

h = lN ⋅ nN

PROEFVERSIE@VANIN

The mirrored vector is the light vector minus two times the scaled normal:

lM = lN – 2 h nN

And the reflected vector is the flipped version of the mirrored vector:

lR = – lM = –(lN – 2 h nN ) = 2 h nN – lN

Specular lighting in 3D

To calculate the specular light intensity you can use the mathematical method of reflecting a vector. For this technique to work you need to reflect the light vector over the normal. The dot product of this reflected vector and the view vector is then used to calculate the specular light intensity

In constrast to diffuse lighting, the reflection technique is dependent on the position of viewer E:

To calculate the specular effect with the reflection technique you reflect light vector lN on the triangle via the normal nN .

Chapter 6 Lighting 133

To get the reflected vector you use the formula that was derived in the previous section for 2D situations:

lR = 2 ( lN ⋅ nN ) nN – lN

PROEFVERSIE@VANIN

The specular effect is view dependant. It is necessary to take the camera position at E into account and vector e N from points P to E. The specular intensity is now the dot product of l R and vector e N: I s = e N ⋅ lR = 0.73

Example

The specular effect can be seen as the light reflecting towards the camera (or the viewer). Depending on the material there will be a strong specular effect (for example for metals) or a weak one (matte objects, such as wood, plaster, ...).

This example uses the reflection formula as shown in the previous section. Obviously something went wrong with this calculation, as both spheres are emitting too much light.

There is too much light shining on both spheres. In the next section you will see a simple operation that can reduce this light output from the specular effect.

Chapter 6 Lighting 134

Shininess

There is one problem with the specular lighting effect as demonstrated in the previous section. By using the dot product of the reflected vector and the view vector, the calculated intensity is too high.

The dot product is propertional to the cosine of the angle between the vectors, as shown in the following figure.

As an example you can derive what the between the vectors would be for a specular intensity of 75%:

PROEFVERSIE@VANIN

= ( )

This picture shows that for a large angle between the view vector and the reflected light vector, the specular effect is too bright, if we use the dot product as is. The solution is to raise the cosine function to a power. Remember that the cosine results in a value between –1 and 1. When you raise such a number to a power higher than 1, the result is that the number becomes smaller. This explains the fact that with higher powers you create functions that reach zero more quickly.

⋅ = ∗ ( )

Consider function A * cos(α) S where S is the glossiness. In the figure S is equal to 1, 10, 50 and 100 for the four functions.

A is equal to the specular level, which controls the strength of the specular highlight. This value has been set to 1 in this figure.

cosα
α
α
-30∘ -15∘ 0∘ 15∘ 30∘ 45∘ 60∘ 75∘ 90∘ 105∘ ⋅
= 0.8
= arccos (0.8)
= 41.41°
-30∘ -15∘ 0∘ 15∘ 30∘ 45∘ 60∘ 75∘ 90∘ 105∘
Chapter 6 Lighting 135

If you take a look at the intensity of those four functions at the same value for the angle you get:

cos (41.41°) = 0.8

cos (41.41°)10 = 0.1

cos (41.41°)50 ≈ 0

cos (41.41°)100 ≈ 0

So for a specular power or shininess of 10 the light output is already more reasonable. For larger powers this value even drops to close to zero.

PROEFVERSIE@VANIN

Remember that the specular lighting discussed here is part of a simplified model of lighting. The power function can even introduce artefacts when used for rendering games and graphics. The PBR model has better solutions for this problem.

Example

Various specular power values (or shininess values) have been used in the following rendering. The more sizable the area where the specular effect is visible, the smaller the specular power value.

This example uses the reflection formula as shown in the previous section with the shininess value being the parameter for the power function. For the specular effect the dot product is used in combination with unit vectors, so the result of the dot product can only be between –1 and 1

By clamping the value between 0 and 1 and increasing it to a power higher than or equal to one, the light output can only get lower.

In this example, the inverse square law for the distance has not been used. When using a spotlight, the light faloff must be taken into account.

Chapter 6 Lighting 136

Halfvector technique

An alternative for the specular lighting is the halfvector technique. Instead of calculating the reflected light vector, a vector halfway between the light vector and the view vector is calculated.

To calculate the specular effect using the halfvector technique we calculate the vector between vector l N  and vector e N.

To calculate the halfvector we first calculate the sum of e N and l N: h  = l N  + e N

Note: This vector is NOT a unit length vector, so you need to normalise.

PROEFVERSIE@VANIN

⃗ ℎ
Chapter 6 Lighting 137

The normalised version of h  is vector h N

PROEFVERSIE@VANIN

The specular effect is view dependant. Vector e N is defined as the normalised vector from points P to E. The specular intensity is then the result of the dot product of vector h N and the normal of triangle nN: I s = h N ⋅ nN = 0.94

The same specular power values (or shininess values) have been used in the following rendering of the halfvector technique. The technique results in highlights that are slightly different from those using the reflection technique, and the highlights are slightly larger and more elliptical.

ℎ ℎ Example
Chapter 6 Lighting 138

6.6 Fresnel

• When light hits a surface, some of the light gets reflected and some of the light gets refracted.

• The Fresnel equation gives us the percentage of light that gets reflected, based on the view angle. Based on the ratio of reflection and the conservation of energy, we can obtain the amount of refracted light.

PROEFVERSIE@VANIN

We start with the reflection of light on a plane.

Some of the light will refract (think about water), and this light will continue in the medium as shown by vector l Refr

The angle will be different from angle α and the ration of the sine of and ϴ is defined as Snell’s law: = ( ) ( )

Chapter 6 Lighting 139

Fresnel edge detection

To calculate the Fresnel effect for smooth objects you need a way to detect edges in the scene. Fortunately, there is again an efficient way by using the dot product

Given is a circle, which is an object that you want to render, and camera point of view E. Consider point P1, which seems to be an edge of the object as seen from viewpoint E.

• You see the back of an object if e N ⋅ nN < 0

PROEFVERSIE@VANIN

Vector e N is the view vector and vector nN is the normal vector in this point.

Intuitively you can see that the angle between these two vectors is approximately 90°.

The dot product is defined as :

• If e N ⋅ nN = = 0 then the camera vector is perpendicular to the normal. Around this spot there is a lot of Fresnel effect.

• You see the front of an object if e N ⋅ nN > 0

1 1 1
d
=
Chapter 6 Lighting 140
= e N ⋅ nN = |e N| |nN| cos(α)
0.02

The dot product of the view vector gives you an efficient way to calculate whether a point of an object is on an edge relative to the camera or not. You can change the formula to get a 1 as a result when a point is on an edge in the following way: edge = 1 – e N ⋅ nN

The advantage is that the further away a point is from the edge, the lower the result of this formula will be.

Fresnel effect

PROEFVERSIE@VANIN

The Fresnel reflectance function is an approximation of the actual physical model. The function presented here is called the Schlick approximation, which is commonly used in PBR (physically based rendering) techniques.

Point E represents the position of the camera.

Vector e N is the unit vector from point T to camera viewpoint E

The Fresnel intensity is the result of the following formula: I F = F0 + (1 – F0) (1 – e N ⋅ nN)5

With F0 = 0.04

For a non-metallic object, you can use this intensity to create a (grayscale) colour with:

C F = (I F I F I F )

You can add this colour to the final output of the rendering of a particular pixel.

Chapter 6 Lighting 141

Fresnel values and functions

Fresnel values are determined by experiments and this makes it possible to look up values when you need to define materials for games or animations. The value can be different for the red, green and blue channels. The following list are a couple of examples of values for some materials:

• water = (0 .02 0 .02  0 .02)

• glass = (0 .08 0 .08 0 .08)

• copper = (0 95 0 64 0 54)

• gold = (1 0 87  0 61)

• plastic = 0 . 21 to 0 . 25

The F0 -value is also the Fresnel reflectance at 0°. For metallic surfaces (as shown above) there can be different values for the RGB channels. For non-metallics the value is the same for all channels. To read the functions you need to realise that at 0° the camera vector is parallel with the normal, and at 90°, the camera vector is orthogonal to the normal. So, at 90° there is an intensity of 1

The figure shows different values for F0. A lower value for F0 means that the function starts at a lower value at 0°:

To calculate the output of the Fresnel effect, you first calculate the Fresnel intensity for each colour for metals:

One way to use these intensities is to add them to the the final output colour by combining the red, green and blue values: (I FR   I FG I FB). This is not necessarily the most correct way (when compared to the PBR workflow), but it already demonstrates the concept of what you can expect from Fresnel reflectance.

-5∘ 0∘ 5∘ 10∘ 15∘ 20∘ 25∘ 30∘ 35∘ 40∘ 45∘ 50∘ 55∘ 60∘ 65∘ 70∘ 75∘ 80∘ 85∘ 90∘ 95∘ 100∘ ( )
I FR = F 0R + (1 – F 0R) (1 – e N ⋅ nN)5 I FG = F 0G + (1 – F 0G) (1 – e N ⋅ nN)5 I FB = F 0B + (1 – F 0B) (1 – e N ⋅ nN)5
Chapter 6 Lighting 142
PROEFVERSIE@VANIN

Adding Fresnel reflectance

In the following figure the Fresnel effect has been added to two spheres. The sphere closest to the camera uses Fresnel values of (0 .1 0 .1  0 .1), which tries to approximate water, and the sphere behind it uses a Fresnel value of (0 .9  0 .6 0 .5), which is closer to copper. The Fresnel effect has been exaggerated somewhat to make clear that it adds an edge effect to the rendering of the spheres.

The final effect of the sphere will be determined by:

Diffuse

PROEFVERSIE@VANIN

The diffuse component of the rendering is determined by the colour of the sphere itself and the diffuse intensity:

I D = clamp (lN ⋅ nN, 0, 1)

C D = I D * (C R C G C B)

For the two spheres the colours are red and blue, but it is, of course, also possible to use textures when rendering. Notice again that you clamp the result of the dot product between 0 and 1 to avoid negative values, which would result in different colours.

Specular

For specular you can choose between the reflection technique or the halfvector technique.

Reflection technique

Halfvectortechnique

= 2 ⋅ = ⋅ ℎ = + + = ℎ ⋅ Chapter 6 Lighting 143

In both cases, shininess parameter S is used as a power for the dot product. This power function decreases the light output of the specular effect and also creates a smaller highlight area. The I S value can then be used to create a new colour. One way to do this is to use the colour of the light source, as it is the photons of the spotlight for example that are reflected from the source.

PROEFVERSIE@VANIN

Again, as with the diffuse calculation, the dot products in the final calculation of I S can be negative, so it is necessary to clamp them between 0 and 1 before using the power function.

Fresnel

As mentioned before, you need to calculate the Fresnel intensities for each channel (which is easier if the Fresnel base values F0 are the same):

Then you can use these intensities to create the Fresnel colour:

These values are often used as they are, without multiplying them by other colours.

Final colour

The final colour is obtained by adding the three calculated colours together:

The formulas presented here are not in accordance with the PBR workflow, but offer insight into the process of rendering a simple effect. PBR techniques, formulas and how to combine them are an interesting topic on its own, and if you are interested in shader programming it is definitely worth a look.

C S = I S * (L R   LG L B)
I FR = F 0R + (1 – F 0R) (1 – l N nN)5 I FG = F 0G + (1 – F 0G) (1 – l N nN)5 I FB = F 0B + (1 – F 0B) (1 – l N ⋅ nN)5
C F = (I FR   I FG I FB)
C = C D + C S + C F
Chapter 6 Lighting 144
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.