Tutorial Introduction
Ogre Tutorial Head

This first tutorial will cover how to animate an entity walking between predefined points. We will use quaternion rotation to keep the entity facing in the direction it is moving. As you read through the tutorial, you should be slowly adding code to your own project.

The full source for this tutorial is here.

Note: There is also source available that uses the BaseApplication framework and Ogre 1.7 here.

Any problems you encounter during working with this tutorial should be posted in the Help Forum(external link).

robot_walk_visual.png

Prerequisites

This tutorial assumes that you already know how to set up an Ogre project and compile it successfully. It will also make use of the STL deque data structure. No prior knowledge of deque is required, but you should at least understand what templates are. If you are unfamiliar with the STL, then the STL Pocket Reference [ISBN 0-596-00556-3] is recommended. You can read the first part of it for free here.

The base code for this tutorial is here.

Setting up the Scene

First, let's add some new variables to BasicApp.h. Add these to the Tutorial Section of the header:

//////////////////////
// Tutorial Section //
//////////////////////
std::deque<Ogre::Vector3> mWalkList;

Ogre::Real mDistance;
Ogre::Real mWalkSpd;
Ogre::Vector3 mDirection;
Ogre::Vector3 mDestination;
Ogre::AnimationState* mAnimationState;
Ogre::Entity* mEntity;
Ogre::SceneNode* mNode;

Then add these initializations to the constructor:

mDistance(0),
mWalkSpd(70.0),
mDirection(Ogre::Vector3::ZERO),
mDestination(Ogre::Vector3::ZERO),
mAnimationState(0),
mEntity(0),
mNode(0)

Let's start by setting the ambient light to full so that we can clearly see the objects we put in our scene. Add the following to the beginning of createScene:

mSceneMgr->setAmbientLight(Ogre::ColourValue(1.0, 1.0, 1.0));

We will now create a robot entity. The first call creates the entity, and the second creates a scene node which will attach the entity to our scene. The last line actually attaches the entity to the scene node.

mEntity = mSceneMgr->createEntity("robot.mesh");
 
mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(
  Ogre::Vector3(0, 0, 25.0));
mNode->attachObject(mEntity);

We will now give the robot a path to walk. This is what we'll use the deque ("deck") for. It is the STL implementation of a double-ended queue. It's like a queue, but you can efficiently add objects to either the front or back of the collection. We will be using the push_front and push_back methods to add objects to either the front or back of the deque. The front and back methods are used to return those values without removing them, and the pop_front and pop_back methods are used to remove those values from the deque (they do not return these values). Finally, the empty method returns true when the deque is...well, empty.

This code will add three vectors to our deque. These will later be used as waypoints on the robot's walking path.

mWalkList.push_back(Ogre::Vector3(550.0, 0, 50.0));
mWalkList.push_back(Ogre::Vector3(-100.0, 0, -200.0));
mWalkList.push_back(Ogre::Vector3(0, 0, 25.0));

Next, we want to place some objects in the scene so we can see the robot's path. We make the y components of these objects negative so the robot will stand on top of them rather than walking into them.

Ogre::Entity* ent;
Ogre::SceneNode* node;
 
ent = mSceneMgr->createEntity("knot.mesh");
node = mSceneMgr->getRootSceneNode()->createChildSceneNode(
  Ogre::Vector3(0, -10.0, 25.0));
node->attachObject(ent);
node->setScale(0.1, 0.1, 0.1);
 
ent = mSceneMgr->createEntity("knot.mesh");
node = mSceneMgr->getRootSceneNode()->createChildSceneNode(
  Ogre::Vector3(550.0, -10.0, 50.0));
node->attachObject(ent);
node->setScale(0.1, 0.1, 0.1);
 
ent = mSceneMgr->createEntity("knot.mesh");
node = mSceneMgr->getRootSceneNode()->createChildSceneNode(
  Ogre::Vector3(-100.0, -10.0,-200.0));
node->attachObject(ent);
node->setScale(0.1, 0.1, 0.1);

Finally, we will position the camera to get a good view of the scene.

mCamera->setPosition(90.0, 280.0, 535.0);
mCamera->pitch(Ogre::Degree(-30.0));
mCamera->yaw(Ogre::Degree(-15.0));

Make sure this compiles before continuing.

Animation

We are now going to set up animation for the robot. We will get an animation state from the robot entity, set its options, and then enable it. We will then need to update the animation state based on how much time has passed since the last frame.

Add the following code right after the camera positioning in createScene:

mAnimationState = mEntity->getAnimationState("Idle");
mAnimationState->setLoop(true);
mAnimationState->setEnabled(true);

The first line gets the animation state from the entity. The second line makes the animation repeat. For certain animations, like the robot's death animation, we would set this to false. A robot should only die once, but until that day, he can walk on. The last line makes the animation state active.

You might be wondering where 'Idle' came from. Each mesh can have its own set of animations defined for it. Ogre+Meshy can be used to view Ogre meshes and their animations. Or you can create them from models from scratch by using a program like Blender and then installing the Ogre exporter.

Finally, we need to update the animation state based on the elapsed frame time. Find the frameRenderingQueued method, and add this line right after the keyboard and mouse are captured:

mAnimationState->addTime(fe.timeSinceLastFrame);

This will get the elapsed time from the frame event reference and use it to update the animation state. Compile and run the application again. You should see a robot using its Idle animation.

Moving the Robot

We will now make the robot walk. Let's look at some of the variables we will be using. First, we store the direction the robot is moving in a called called mDirection. We store the robot's current destination in a vector called mDestination. We store the distance the robot has left to reach its current destination in mDistance. Finally, we store the robot's walking speed in a real called mWalkSpd. In the constructor, we set mWalkSpd to be 70.0 units per second.

Now we need to start the robot's walking animation, but we only want it to start walking when it has a location left in its mWalkList. The nextLocation method will be used to determine this. Add the following to frameRenderingQueued just before the addTime call:

if (mDirection == Ogre::Vector3::ZERO) 
{
  if (nextLocation())
  {
    mAnimationState = mEntity->getAnimationState("Walk");
    mAnimationState->setLoop(true);
    mAnimationState->setEnabled(true);
  }
}

If you compile and run the application now, the robot will walk in place. The robot starts out with a direction vector of zero, and our nextLocation method always returns true. We will fix that soon.

We are now going to add code to move the robot to its next destination. We will move the robot a small amount each frame based on how much time has passed since the last frame. This will ensure the robot moves at the same speed across the screen regardless of how fast a computer renders the frames. Basically, if the computer renders frames really fast, then we would want the robot to move relatively small distances each frame, because there will be a lot of frames. But if the computer renders frames slow, then we would want to move the robot farther each frame so it could keep up.

For now, we're safe simply multiplying the elapsed time by our speed to smooth things out (try temporarily removing the multiplication to see how things change). We will also update the distance the robot has left to travel. We do this by subtracting how far it moved since the last frame from the total distance it had to walk for that part of the path. Add the following to frameRenderingQueued right after the if statement and before the addTime call:

else
{
  Ogre::Real move = mWalkSpd * fe.timeSinceLastFrame;
  mDistance -= move;

Next we need to see if we've arrived at our destination (or moved slightly past it). If the distance left is less than or equal to 0, then we set the position of the entity's scene node to our destination vector. This means as soon as the robot gets really close to its destination, then it will be placed exactly on its destination. We then set its current direction to be the zero vector so the next part of the path can be started. If there are no further points, then the robot will come to rest since we've set the direction vector to zero and nextLocation will return false.

^ if (mDistance <= 0)
  {
    mNode->setPosition(mDestination);
    mDirection = Ogre::Vector3::ZERO;

If the robot has completed one leg of its journey, we need to look for another destination. If we find one, then we should rotate the robot to face its next destination. If there are no more locations in the robot's path, then we will return it to the Idle animation.

^   if (nextLocation())
    {   
      // rotation code will go here                  
    } 
    else
    {
      mAnimationState = mEntity->getAnimationState("Idle");
      mAnimationState->setLoop(true);
      mAnimationState->setEnabled(true);
    }
  }

We do not need to set the walking animation again, because the robot will already be in this state. However, the robot will most likely not be facing in the right direction, so we will have to rotate it. We will come back to the rotation code soon.

That takes care of when the robot is very close to its destination. In the else statement, we will take care of the case where the robot is still walking along the path. All we have to do is translate the robot along its current direction vector by an amount proportional to the move value we calculated.

^ else
  {
    mNode->translate(move * mDirection);
  }
}

The next thing we need to do is fill in the nextLocation method. This will set up the variables the robot needs to correctly follow its path. The nextLocation method will return false when there are no points left to walk to. Add the following to nextLocation:

if (mWalkList.empty())
  return false;

Next we are going to get another destination vector from the deque. We will set the robot's direction vector by subtracting its scene node's current position from the destination vector we pull out of the deque (to get a vector from X to Y, you subtract X from Y).

mDestination = mWalkList.front();
mWalkList.pop_front();
mDirection = mDestination - mNode->getPosition();

We have another problem. We multiply the direction vector by the move value in frameRenderingQueued. For everything to work out, we need the destination vector to have a length of one (a "unit vector"). The vector operation that does this is called normalise. This method also returns the vector's length before normalisation. This is very useful, because this length is exactly the distance we need for our robot's mDistance variable.

mDistance = mDirection.normalise();

That completes the nextLocation method. You may want to read this method a few times. It is short, but a lot is going on.

You can compile and run the code. The robot is walking! But he is not turning.

Turning the Robot

We will now add in the rotation code. We need to get the direction the robot is facing and then rotate it. Add the following code to where our placeholder comment was in the previous step:

Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;
Ogre::Quaternion quat = src.getRotationTo(mDirection);
mNode->rotate(quat);

Quaternions were briefly mentioned in Basic Tutorial 4, but this is the first real use of them. They can be thought of as representations of rotations in three dimensional space. In modern 3D rendering, they are used to keep track of transformations like rotation.

In the first line we call getOrientation. This method returns a quaternion representing the robot's current orientation in space. The problem is that it does not take into account that our model's default direction is facing down the x-axis. To fix this, we multiply the quaternion by the unit vector along the x-axis. You can see that quaternions are like matrices in that you can transform a vector by multiplying it by a quaternion. The second line gets a quaternion that represents a rotation from the robot's current direction towards its next destination.

It's completely alright if this is confusing. Quaternions are a rather tricky subject, but you can learn how to use them without needing to understand too much about why they work. Just keep in mind that they represent transformations like rotations.

There is one problem with our code. There is a special case where the rotation will fail. If we are trying to rotate the robot exactly 180 degrees, then the rotation code will throw a divide by zero error. In order to fix that, we will deal with the special case separately. Two vectors are 180 degrees apart exactly when their dot product is -1. We can use this to determine when we are attempting a 180 degree rotation, and then simply use the yaw method to manually turn the scene node by 180 degrees. Replace the code we just wrote with this:

Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;

if ((1.0 + src.dotProduct(mDirection)) < 0.0001) 
{
  mNode->yaw(Ogre::Degree(180));
}
else
{
  Ogre::Quaternion quat = src.getRotationTo(mDirection);
  mNode->rotate(quat);
}

Notice that we are not directly comparing the dot product of the two vectors to zero. This is because there are inherent limitations to floating point numbers. These limitations can mean that a dot product that "should" equal zero is actually a number very close to zero, but not zero. To account for this, we check to see if adding one to the dot product is close enough to zero for our purposes (since -1 + 1 = 0).

It should be clear by now that a minimum understanding of linear algebra will be helpful for any 3D simulation programmer. If you would like to read more on the subject, then take a look at the Quaternion and Rotation Primer.

Compile and run the application. We should now have a robot that walks its path and faces the right direction.

Conclusion

In this tutorial, we set up the animation state for our robot entity. By getting a reference to this state, we were able to set animation options like looping, and we were able to choose between animations that were defined in our mesh.

We introduced the STL deque to represent a list of points for the robot's path. The C++ Standard Template Library is something you will most likely see a lot of as a c++ programmer. It is worth understanding well. The deque is a double-ended queue. It has an efficient implementation of adding objects to the front and back of its collection.

We also covered our first significant use of quaternions for modeling rotations. Quaternions are a rich and interesting subject, but the main point to remember is that they are used in 3D rendering to represent rotations. They are similar to matrices, as we saw when we multiplied them together with vectors to get transformed vectors. We used quaternions to rotate our robot as it walked along its path. They can be used to simplify much more complicated motions.

Exercises

Easy

  1. Add new points to the robot's path. Also add a new knot for each new location, so you can track the robot's progress.
  2. When a robot has come to the end of its journey, then it must die to make room for another generation of path-walkers. Have the robot perform its death animation when it is done walking. The animation name is 'Die'.

Intermediate

  1. The variable mWalkSpd is set once and never changed. In the name of good practice, change mWalkSpeed to a constant static class variable.
  2. It is ugly to check whether the robot is walking by comparing the mDirection vector to the zero vector. It would be better if we created a boolean flag called mWalking to keep track of this.

Difficult

  1. One of the limits to our class is that points can't be added to the robot's path after we've created the object. Fix this problem by implementing a new method which takes a Vector3 and adds it to the mWalkList deque. (Hint: If the robot is still walking, then you only have to add the point to the end of the deque. If the robot has finished walking, you will need to call nextLocation to get the robot walking again.)

Advanced

  1. Another limitation to our class is that it only animates one robot. Implement the class so that it can control any number of robots around the path. (Hint: You should create another class that completely controls the animation of a single robot. Then store some of these robot animations in a STL map, so that you can retrieve them for animation.) See if you can do this without adding any more frame listeners.
  2. If you were successful in the previous question and you created robots moving at different speeds, then you now know that robots can now walk right through each other. Fix this by implementing some type of pathfinding function or by adding some collision detection to prevent this.

Full Source

The full source for this tutorial is here.

Next

Intermediate Tutorial 2


Alias: Intermediate_Tutorial_1

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.