• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
GarrickW

Quaternion Object Rotation

14 posts in this topic

So I'm trying to code something similar to a 3D space sim, where I want six degrees of freedom. Apparently the best way to achieve 6DoF is with quaternions, so I've spent the last two days reading up about them and trying to get some code to work. I am using SFML 1.6 and OpenGL, nothing else.

I have a Quaternion class that I'm fairly certain is mathematically correct, and can create a quaternion from an axis and an angle; it normalizes itself, and the multiplication operator is overloaded to perform a proper multiplication.

However, don't understand how to transform the player's input into a quaternion representing a change in rotation. The player can input changes into the Pitch, Yaw and Roll, potentially all three at once. The object they are controlling is supposed to then rotate according to this input along its LOCAL axes.

Suppose the player wanted to change the Pitch by 30°, the Yaw by 45° and the Roll by 10° all at the same time (I'm using that example because it's the most complex possible situation my code will have to deal with). So I have these nice little values, 30-45-10 (which I could also convert to radians), but what do I do with them?

I've read dozens of tutorials, and what little I can make sense of them seems to indicate I need to make the change quaternion like this (pseudocode):

[code]Qaternion xChange = Quaternion.FromAxisAngle(30, 1, 0, 0);
Qaternion yChange = Quaternion.FromAxisAngle(45, 0, 1, 0);
Qaternion zChange = Quaternion.FromAxisAngle(10, 0, 0, 1);
Qaternion totalChange = zChange * yChange * xChange;[/code]

Where FromAxisAngle takes the parameters (float Angle, float X, float Y, float Z). Then I apparently need to perform this on the object's current Orientation, also a quaternion:

[code]Orientation = totalChange * Orientation;[/code]

And finally derive a matrix from Orientation and pass that to glMultMatrix().

Unfortunately, my current code doesn't really work. Trying to change the yaw or roll just makes the object shiver, and trying to change the pitch makes the object spin correctly for a moment and then start to roll and grow enormously large at the same time.

The thing is, deep down I know my code shouldn't work, because quaternion multiplications are non-commutative. I can't just willy-nilly multiply quaternions for three different orientations with one another - the order will end up influencing the result, right? What do I do when a particular axis isn't supposed to be rotating at the moment?

I've got this not-working system in place, but I've tried half a dozen other configurations that don't work either. Rotation is the user-input rotation around the X,Y,Z axes respectively. I'n not doing any translation at the moment.

[code]void Entity::Transform(sf::Vector3<float> Translation, sf::Vector3<float> Rotation)
{
if (Rotation.x != 0)
{
Quaternion Offset = Quaternion();
Offset.FromAxisAngle(Rotation.x, 1, 0, 0);
m_Orientation = Offset * m_Orientation;
}
if (Rotation.y != 0)
{
Quaternion Offset = Quaternion();
Offset.FromAxisAngle(Rotation.y, 0, 1, 0);
m_Orientation = Offset * m_Orientation;
}
if (Rotation.z != 0)
{
Quaternion Offset = Quaternion();
Offset.FromAxisAngle(Rotation.z, 0, 0, 1);
m_Orientation = Offset * m_Orientation;
}
//Derive a rotation matrix
m_Orientation.RotationMatrix(m_RotationMatrix);
}
[/code]

Can somebody tell me how I'm supposed to transform my player input into the appropriate quaternion transformations?

Note that I've also tried directly creating a quaternion from stored PYR variables, but this didn't work and I was told by someone reading my code that that was the wrong way to implement this sort of thing (unfortunately, his explanation of the right way to do it was extremely vague, at least to me).
0

Share this post


Link to post
Share on other sites
How do you render the objects - are you converting them back into Euler angles and then using glRotatef with them? AFAIK your general idea is correct, if you want to represent a bunch of rotations, you make them, and then combine then (and you're right, order matters).

I think that the order you multiply them by should be the same order as the one you render them in, for example if you're multipling x * y * z, then when you convert to Euler angles you should rotate around the X axis, then Y then z.

I'm still trying to get my head around Quaternions, but I _think_ this is correct. It's how they're being represented in my game at the moment anyway, and I'm doing a space themed game too ;p
0

Share this post


Link to post
Share on other sites
Actually, I'm deriving a rotation matrix from the quaternion each time the quaternion is modified, and then multiplying the object's view matrix by that rotation matrix upon rendering. I've heard that reduces the issues you can sometimes get where some rotations continue to be around the global rather than local axes. Originlally I had reconverted them to Euler angles, and that was the problem I got. For example, for a given order, if I rotated along the X axis and then tried to rotate alone the Y axis, the Y rotation would still take place along the global axis. Which axes were a problem changed depending on the order, but there was no order that removed the problem entirely.

This is how I render the VBO's transformations:

[code]glPushMatrix();
//Apply transformations
glTranslatef(m_Position.x, m_Position.y, m_Position.z);
glMultMatrixf(m_RotationMatrix);

//(...) VBO rendering code
glPopMatrix();[/code]
0

Share this post


Link to post
Share on other sites
Nobody?

I've tried all sorts of things, and nothing has worked. I've tried adding input directly to stored Euler angles and simply creating a new quaternion each time, but that results in rotations around global axes with no regard to local axes.

[code]m_Rotation.x += Rotation.x;
m_Rotation.y += Rotation.y;
m_Rotation.z += Rotation.z;
m_Orientation.FromPYR(m_Rotation.x, m_Rotation.y, m_Rotation.z);
m_Orientation.RotationMatrix(m_RotationMatrix);[/code]

I've tried passing input as axis-angle and creating offset quaternions with those, multiplying them into the main orientation, but this results in extremely fast rotation around the X axis and explosive scaling or near-invisible shivering along the y and z axes.

[code]xOffset.FromAxisAngle(Rotation.x, 1.0, 0.0, 0.0);
yOffset.FromAxisAngle(Rotation.y, 0.0, 1.0, 0.0);
zOffset.FromAxisAngle(Rotation.z, 0.0, 0.0, 1.0);
m_Orientation = xOffset * yOffset * zOffset * m_Orientation;
m_Orientation.RotationMatrix(m_RotationMatrix);[/code]

I've tried directly making an offest quaternion from the entire PYR input, but the roll command makes the plane pitch and everything else just makes it wobble ever so slightly.

[code]Quaternion Change = Quaternion();
Change.FromPYR(Rotation.x, Rotation.y, Rotation.z);
m_Orientation = Change * m_Orientation;
m_Orientation.RotationMatrix(m_RotationMatrix);[/code]

What other ways are there to transform input into quaternions? I have to use Pitch-Yaw-Roll because that's ultimately what players will be using their input as - mouse left-right for yaw, mouse up-down for pitch, and Q and E for roll (I'm copying the flight controls from [i]Star Wars: Battlefront II[/i]). I can't get away from Euler angles, or at least not from a Pitch-Yaw-Roll scheme. How do I do this? Also, please note that the objects have to rotate [i]independently [/i]of the camera.

I've tried all sorts of tutorials:

[url="http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/index.htm"]http://www.euclidean...forms/index.htm[/url]
[url="http://www.idevgames.com/articles/quaternions"]http://www.idevgames...les/quaternions[/url]
[url="http://www.cprogramming.com/tutorial/3d/quaternions.html"]http://www.cprogramm...uaternions.html[/url]
[url="http://www.arcsynthesis.org/gltut/Positioning/Tut08%20Quaternions.html"]http://www.arcsynthe...uaternions.html[/url]

But none of them cover implementation in a way I can grok. They mostly cover the mathematical operations for using quaternions, which I think I've already got. I would have thought just converting the PYR rotation to a quaternion and multiplying that with the orientation would work, but it doesn't, and I don't know where to go from here.

EDIT:

Just in case my quaternion math [i]is [/i]wrong, here are some parts of my Quaternion class:

From [url="http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm"]http://www.euclidean...rnion/index.htm[/url]:

[code]void Quaternion::FromPYR(float Pitch, float Yaw, float Roll)
{
//Set Pi
float Pi = 4 * atan(1);
//Set the values, which came in degrees, to radians
float rYaw = Yaw * Pi / 180;
float rPitch = Pitch * Pi / 180;
float rRoll = Roll * Pi / 180;
//Components
float C1 = cos(rYaw / 2);
float C2 = cos(rPitch / 2);
float C3 = cos(rRoll / 2);
float S1 = sin(rYaw / 2);
float S2 = sin(rPitch / 2);
float S3 = sin(rRoll / 2);
//Remember to convert A to degrees again
a = ((C1 * C2 * C3) - (S1 * S2 * S3));
x = (S1 * S2 * C3) + (C1 * C2 * S3);
y = (S1 * C2 * C3) + (C1 * S2 * S3);
z = (C1 * S2 * C3) - (S1 * C2 * S3);
//Normalize
Normalize();
}[/code]

From [url="http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm"]http://www.euclidean...rnion/index.htm[/url]:

[code]//Rebuilds this quaternion using an angle and a rotation axis
void Quaternion::FromAxisAngle(float Angle, float xAxis, float yAxis, float zAxis)
{
//Angle should be in radians
a = cos(Angle/2);
//Axes
x = xAxis * sin(Angle/2);
y = yAxis * sin(Angle/2);
z = zAxis * sin(Angle/2);
//Normalize
Normalize();
}[/code]

From [url="http://www.idevgames.com/articles/quaternions"]http://www.idevgames...les/quaternions[/url]

[code]void Quaternion::RotationMatrix(GLfloat* Matrix)
{
//Column 1
Matrix[0] = 1.0 - (2.0*((y*y) + (z*z)));
Matrix[1] = 2.0*((x*y) + (a*z));
Matrix[2] = 2.0*((x*z) - (a*y));
Matrix[3] = 0.0;
//Column 2
Matrix[4] = 2.0*((x*y) - (a*z));
Matrix[5] = 1.0 - (2.0*((x*x) + (z*z)));
Matrix[6] = 2.0*((y*z) + (a*x));
Matrix[7] = 0.0;
//Column 3
Matrix[8] = 2.0*((x*z) + (a*y));
Matrix[9] = 2.0*((y*z) - (a*x));
Matrix[10] = 1.0 - (2.0*((x*x) + (y*y)));
Matrix[11] = 0.0;
//Column 4
Matrix[12] = 0.0;
Matrix[13] = 0.0;
Matrix[14] = 0.0;
Matrix[15] = 1.0;
}[/code]
0

Share this post


Link to post
Share on other sites
If you want to do 6DOF movement using quaternions, do *not* use roll, pitch and yaw. You want to take the user's input and apply small incremental rotations along the three axes to the existing quaternion.

Does that make sense?
1

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1332421825' post='4924289']
If you want to do 6DOF movement using quaternions, do *not* use roll, pitch and yaw. You want to take the user's input and apply small incremental rotations along the three axes to the existing quaternion.

Does that make sense?
[/quote]

Hm... So say the user wants the ship to pitch down a little (relative to the ship's previous orientation, not global orientation). What confuses me is "apply rotations." I take that to mean:

1. Create a quaternion [b]qPitch [/b]from an axis-angle value where the Axis = [b]{1.0, 0.0, 0.0}[/b] and the Angle is, for example, [b]0.1[/b]
2. Multiply qPitch by m_Orientation, the current orientation of the ship, so [b]m_Orientation = qPitch * m_Orientation[/b]

Does that sound right? That has been my intuition up until now, so I assume it's wrong, but I'm not quite sure in what way.

Also, because quaternion multiplications are noncommutative, I've been worried about extending this approach to all three possible axes at once, since the order in which I multiply them will determine the kind of result I get - although I want all rotations to be relative to local axes. It seems that any order I put them in will shortchange one of the axes or another.
0

Share this post


Link to post
Share on other sites
I think you got it. The non-conmutativeness of the quaternion product is not apparent under small angles, so I would start by just ignoring it.
0

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1332425519' post='4924313']
I think you got it. The non-conmutativeness of the quaternion product is not apparent under small angles, so I would start by just ignoring it.
[/quote]

Okay, so that part works; thanks for the confirm! I've interpreted that as this in my current code:

[code] Quaternion xOffset = Quaternion();
Quaternion yOffset = Quaternion();
Quaternion zOffset = Quaternion();
xOffset.FromAxisAngle(Rotation.x, 1.0, 0.0, 0.0);
yOffset.FromAxisAngle(Rotation.y, 0.0, 1.0, 0.0);
zOffset.FromAxisAngle(Rotation.z, 0.0, 0.0, 1.0);
m_Orientation = xOffset * yOffset * zOffset * m_Orientation;
m_Orientation.RotationMatrix(m_RotationMatrix);[/code]

To clarify: Rotation is basically a vector {x, y, z} where each value represents either a positive, negative or null change, as implied by player input. Currently that change is 0.01.

Quaternions are initialized as identity quaternions (so {a, x, y, z} = {1, 0, 0, 0}), but that data is overwritten in FromAxisAngle(...), so that shouldn't be an issue.

So if that part of my code is correct, what could be causing the problem? m_RotationMatrix is a GLfloat[16], stored in column-major format (I think that's what it's called - the first 4 floats represent the first column, etc.), so that should be okay. Should I be using something other than glMultMatrix()?
0

Share this post


Link to post
Share on other sites
I am not sure what "the problem" is at this stage. If you still haven't solved the issues with the volume of the object changing, you need to renormalize the quaternion periodically (for instance, after each step) by dividing it by its length. Does anything else seem broken?

Also, can you explain what you put in Rotation?
0

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1332426277' post='4924320']
I am not sure what "the problem" is at this stage. If you still haven't solved the issues with the volume of the object changing, you need to renormalize the quaternion periodically (for instance, after each step) by dividing it by its length. Does anything else seem broken?

Also, can you explain what you put in Rotation?
[/quote]

I checked to make sure it was normalizing, and I wasn't normalizing every frame, so I added that in. The result is that the size stays the same (thank you!), but the model only wobbles a bit along the Y and Z axes. To clarify: Holding down Left, which should make it rotate along the Y axis, instead makes it rotate a tiny bit to the left, then a tiny bit to the right, repeatedly, as though the ship were shaking its head.

Rotation around the X axis works fine, though.

Here is how I fill Rotation:

[code] ///Rotation
float TurnSpeed = 0.01;
sf::Vector3<float> Rotation;
Rotation.x = 0.0;
Rotation.y = 0.0;
Rotation.z = 0.0;
//Pitch
if (m_App->GetInput().IsKeyDown(sf::Key::Up) == true)
{
Rotation.x -= TurnSpeed;
}
if (m_App->GetInput().IsKeyDown(sf::Key::Down) == true)
{
Rotation.x += TurnSpeed;
}
//Yaw
if (m_App->GetInput().IsKeyDown(sf::Key::Left) == true)
{
Rotation.y -= TurnSpeed;
}
if (m_App->GetInput().IsKeyDown(sf::Key::Right) == true)
{
Rotation.y += TurnSpeed;
}
//Roll
if (m_App->GetInput().IsKeyDown(sf::Key::Q) == true)
{
Rotation.z -= TurnSpeed;
}
if (m_App->GetInput().IsKeyDown(sf::Key::E) == true)
{
Rotation.z += TurnSpeed;
}[/code]
0

Share this post


Link to post
Share on other sites
What part of that code is initialization that you do once and what part is something you do in each iteration of the loop? Or do you do all of that every time?
0

Share this post


Link to post
Share on other sites
[quote name='alvaro' timestamp='1332426906' post='4924326']
What part of that code is initialization that you do once and what part is something you do in each iteration of the loop? Or do you do all of that every time?
[/quote]

The input code above is performed every time, assuming a certain flag is true. Rotation is then passed to the entity that is supposed to be rotating. Is that bad?

EDIT: Just to be sure, I changed the code such that it is executed regardless of the flag, and the same problem occurs.
0

Share this post


Link to post
Share on other sites
I would remove the input and pretend the user is pressing "Down" constantly. Then either debug the program step by step and see if variables have the values you expect, or add logging to your code so you can see what it's doing. The advantage of doing it with logging is that you can then post the log here if you need help.
0

Share this post


Link to post
Share on other sites
Found it!

It turns out my implementation of quaternions [i]wasn't[/i] correct after all. The code for quaternion multiplication I had was either wrong, or I copied it wrong. Either way, fixing it by referring to this site helped: [url="http://www.arcsynthesis.org/gltut/Positioning/Tut08%20Quaternions.html"]http://www.arcsynthesis.org/gltut/Positioning/Tut08%20Quaternions.html[/url]

For the record, the correct quaternion multiplication code I now use is:

[code]Quaternion Quaternion::operator* (Quaternion OtherQuat)
{
float A = (OtherQuat.a * a) - (OtherQuat.x * x) - (OtherQuat.y * y) - (OtherQuat.z * z);
float X = (OtherQuat.a * x) + (OtherQuat.x * a) + (OtherQuat.y * z) - (OtherQuat.z * y);
float Y = (OtherQuat.a * y) + (OtherQuat.y * a) + (OtherQuat.z * x) - (OtherQuat.x * z);
float Z = (OtherQuat.a * z) + (OtherQuat.z * a) + (OtherQuat.x * y) - (OtherQuat.y * x);
Quaternion NewQuat = Quaternion();
NewQuat.a = A;
NewQuat.x = X;
NewQuat.y = Y;
NewQuat.z = Z;
return NewQuat;
}[/code]

Many thanks to you, [b]alvaro[/b]! I otherwise would have just assumed this was beyond my capabilities.

The object now rotates easily along all its local axes, no matter what previous rotations took place. Awesome!
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0