Reader small image

You're reading from  Mathematics for Game Programming and Computer Graphics

Product typeBook
Published inNov 2022
PublisherPackt
ISBN-139781801077330
Edition1st Edition
Tools
Right arrow
Author (1)
Penny de Byl
Penny de Byl
author image
Penny de Byl

Penny de Byl is a full stack developer with an honors in graphics and Ph.D. in artificial intelligence for games. She has a passion for teaching, teaching games development and computer graphics for over 25 years in universities in Australia and Europe. Her best-selling textbooks, including Holistic Game Development with Unity, are used in over 100 institutions. She has won numerous awards for teaching, including an Australian Government Excellence in Teaching Award and the Unity Mobile Game Curriculum Competition. Her approach to teaching computer science and related fields is project-based giving you hands-on workshops you can immediately get your teeth into. The full range of her teaching interests can be found at H3D Learn.
Read more about Penny de Byl

Right arrow

Rotating with Quaternions

If you can’t remember me saying it before, you’ll be sure to hear me say it numerous times throughout this chapter: quaternions are an advanced mathematical construct. They are so advanced I don’t expect you to fully comprehend them by the end of this chapter. However, what I want you to take away is a healthy appreciation for what they do with respect to solving the gimbal lock issue we discussed in Chapter 15, Navigating the View Space.

Besides their usefulness in calculating 3D rotations, quaternions are useful in numerous fields, including computer vision, crystallographic texture analysis, and quantum mechanics. Conceptually, quaternions live in a 4D space through the addition of another dimension to those of the x, y, and z axes used by Euler angles.

In this chapter, we will start with an overview of quaternions and delve into the benefits of their 4D structure. This will reveal how they can be used to replace operations...

Technical requirements

In this chapter, we will be using Python, PyCharm, and Pygame, as used in previous chapters.

Before you begin coding, create a new folder in the PyCharm project for the contents of this chapter called Chapter_16.

The solution files containing the code can be found on GitHub at https://github.com/PacktPublishing/Mathematics-for-Game-Programming-and-Computer-Graphics/tree/main/Chapter16.

Introducing quaternions

The minimum number of values needed to represent rotations in 3D space is three. The most intuitive and long-applied method for defining rotations, as we’ve seen, is to use these values as the three angles of rotation around the x axis, the y axis, and the z axis. The values of these angles can range from 0 to 360 degrees or 0 to 2 PI radians.

Any object in 3D space can be rotated around these axes that represent either the world axes or the object’s own local access system. Formally, the angles around the world axes are called fixed angles, while the angles around an object’s local axis system are called Euler angles. However, often both sets of angles are referred to as Euler angles. We covered the mathematics to apply rotations around these three axes in Chapter 15, Navigating the View Space, in addition to investigating when these calculations break down and cause gimbal lock.

Quaternions were devised in 1843 by Irish mathematician...

Rotating around an arbitrary axis

A vector lying on the x axis that is represented by (1, 0) and rotated by results in the vector that will be the cosine of the angle and the sine of the angle ( as illustrated in Figure 16.1. Likewise, a vector sitting on the y axis represented by (0, 1), when rotated by the same angle, will result in a vector that, too, contains a combination of cosine and sine as (-.

Figure 16.1: Two-dimensional rotations

Do these values look familiar? They should because they are the values we’ve used in the rotation matrix for a rotation around the z axis in Chapter 15, Navigating the View Space. Rotating in 2D is essentially the same operation as rotating around the z axis; as you can imagine, the z axis added to Figure 16.1 coming out of the screen toward you, and thus rotations in this 2D space are, in fact, rotating around an unseen z axis.

All the rotations we’ve looked at thus far have been to rotate a vector or...

Exploring quaternion spaces

As we saw in Chapter 13, Understanding the Importance of Matrices, 4 x 4 matrices are important in graphics as they allow for easy multiplication of compound transformations. Although I didn’t make a big deal of it at the time, these matrices are, in fact, four-dimensional as they have four columns and four rows. Just as we need 4 x 4 matrices to multiply transformation operations, Hamilton found he could use them to find quotients of 3D values. However, the process is a little more complex than how we just created a w dimension for coordinates with a 1 or a 0 on the end for (x, y, z, w).

So, where did Hamilton find his fourth dimension? He had to add another number system and he turned to complex numbers. If you aren’t familiar with complex numbers, then take a look at the explanation here: https://en.wikipedia.org/wiki/Complex_number.

In short, complex numbers were devised for solving quadratic equations and to come up with a solution...

Working with unit quaternions

As discussed, quaternions remove the limitations involved in compounding Euler-angle rotations. In this section, we will concentrate on reprogramming the camera in our project to pitch and roll with quaternions.

Before quaternions are multiplied, we must ensure they are unit quaternions. That means they will have a length of 1. If we go back to thinking of quaternion spacing being a sphere encompassing Euclidean space, then a quaternion represents a vector from the origin of both spaces to the surface of the sphere. In Figure 16.9, the vectors q1 and q2 represent these. The vector representing a quaternion is four-dimensional, with the coordinates storing the angle and axis as .

Of course, you must remember we can’t see these four dimensions in our 2D/3D sphere diagram, but they are there. In Figure 16.8, q3 represents an invalid quaternion in that it extends beyond the surface of the sphere. However, the rotation that it is meant to represent...

Understanding the purpose of normalization

If you are wondering why we need to normalize a quaternion in the first place, it’s because the values used to create it may produce a quaternion with a length longer than 1, especially if it’s code that you are adding yourself.

Take, for example, the 3D process of moving an object along a vector at a constant speed. In Chapter 10, Getting Acquainted with Lines, Rays, and Normals, we moved an object along a line segment at a constant speed. To achieve a constant speed, we needed to take into consideration the time between frames so we could factor in any changes. The code we created moved an object in equal steps from one end of a line segment to the other. Taking this same idea, we can write code to move an object in 3D along a vector at a constant speed. The essential parts of this script would look something like this:

dt = 0
direction = (0, 0, 0.1)
while not done:
  new_position = old_position + (direction...

Summary

In case you missed it the first time, let me say it again: quaternions are an advanced mathematical construct. Though I am sure, by now, you appreciate this statement. They are also extremely powerful, and this chapter has but scratched the surface of all the applications for which they can be applied. Hamilton wasn’t even thinking of 3D graphics rotations when he defined them, but thankfully for us, they exist and remove the inherent issue of compounding Euler angle rotations.

If you’ve reached the end of this chapter and still don’t feel comfortable employing quaternion mathematics, you won’t be alone. In fact, I hesitated to include this chapter as a full comprehension of quaternions requires background knowledge in complex numbers, pure mathematics, and division algebra that we don’t have the scope in this book to include. And if you don’t feel comfortable yet working them, then the simple solution is, don’t. Euler angles...

Answers

Exercise A:

normalize(Quaternion q)
  length = sqrt( pow(w,2) + pow(x,2) + pow(y,2) + pow(z,2))
  q.w /= length
  q.x /= length
  q.y /= length
  q.z /= length

Exercise B:

def rotate_with_mouse(self, yaw, pitch):
    right = pygame.Vector3(1, 0, 0)
    up = pygame.Vector3(1, 0, 0)
    y_rot = Quaternion(axis=up, angle=self.mouse_invert * yaw * 
                       self.mouse_sensitivityY)
    x_rot = Quaternion(axis=right, 
                       angle=self.mouse_invert * pitch * 
                       self.mouse_sensitivityX)
    m_rot = x_rot * y_rot
    self.transform...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mathematics for Game Programming and Computer Graphics
Published in: Nov 2022Publisher: PacktISBN-13: 9781801077330
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Penny de Byl

Penny de Byl is a full stack developer with an honors in graphics and Ph.D. in artificial intelligence for games. She has a passion for teaching, teaching games development and computer graphics for over 25 years in universities in Australia and Europe. Her best-selling textbooks, including Holistic Game Development with Unity, are used in over 100 institutions. She has won numerous awards for teaching, including an Australian Government Excellence in Teaching Award and the Unity Mobile Game Curriculum Competition. Her approach to teaching computer science and related fields is project-based giving you hands-on workshops you can immediately get your teeth into. The full range of her teaching interests can be found at H3D Learn.
Read more about Penny de Byl