%tutorialhelp%

Introduction

In this tutorial, we will be learning how to display the CEGUI mouse, and how to use it to select and place entities in our scene. We will cover:

  1. The use of the MouseListener and MouseMotionListener interfaces.
  2. How to use raycasts to keep the camera from passing through the terrain.
  3. Using the mouse to select a specific location on the terrain.

Here is the code you should begin this tutorial with. It should compile and produce a black screen with a single CEGUI label saying, "Intermediate Tutorials". As you read through the tutorial, you should be slowly adding the 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.

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

terrain_visual.png

Prerequisites

This tutorial assumes that you already know how to set up an Ogre project and compile it successfully. Knowledge of the topics from previous tutorials is also assumed.

This tutorial requires that you add some terrain into your scene before beginning. Basic Tutorial 3 gives an overview of using the new terrain system. If you have difficulties, the full source for this tutorial has all of the terrain setup done for you. You can simply copy the terrain code into your base files. Although learning how to use the new terrain system is also suggested.

This tutorial also uses CEGUI (Crazy Eddie's GUI). Basic Tutorial 7 covers setup and use of this library with Ogre.

If you have trouble with CEGUI not finding resources, then remember that the Ogre resource manager needs to know where they are. The following code should be in 'resources.cfg':

[Imagesets]
FileSystem=/usr/local/share/cegui-0/imagesets
[Fonts]
FileSystem=/usr/local/share/cegui-0/fonts
[Schemes]
FileSystem=/usr/local/share/cegui-0/schemes
[LookNFeel]
FileSystem=/usr/local/share/cegui-0/looknfeel
[Layouts]
FileSystem=/usr/local/share/cegui-0/layouts

This is the directory structure you will have if you built CEGUI 0.8x from source on linux. If you installed CEGUI through your package manager, or are using an older version, then the directory structure will be different. A package manager will use '/usr/share' instead of '/usr/local/share'. If you're using a prebuilt SDK, then everything should be in there.

The base code for this tutorial is here.

Setting up the Scene

We will now set up a basic scene. This should look familiar from previous tutorials. Add the following to the beginning of createScene:

mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);
 
mCamera->setPosition(40, 100, 580);
mCamera->pitch(Ogre::Degree(-30));
mCamera->yaw(Ogre::Degree(-45));

Since we're dealing with a large terrain, we should also set the near and far clip distances so we can see the distant terrain.

mCamera->setNearClipDistance(0.1);
mCamera->setFarClipDistance(50000);

After these two calls, we should set up the lighting that we will cast on our terrain. We'll create a directional light to act like a sun.

Ogre::Vector3 lightDir(0.55, 0.3, 0.75);
lightDir.normalise();

Ogre::Light* light = mSceneMgr->createLight("SceneLight");
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(lightDir);
light->setDiffuseColour(Ogre::ColourValue(0.4, 0.4, 0.4));
light->setSpecularColour(Ogre::ColourValue(0.2, 0.2, 0.2));

setupTerrain(light);

If you did not create a setupTerrain method, then you can look at the full source for this tutorial to see how it was written. It has all of the stuff from Basic Tutorial 3, except it has been put into a separate method.

Finally, we need to comment out the SdkCameraMan mouse injection and uncomment the CEGUI mouse injection. This is so that we can customize how the camera is controlled. In the mouseMoved method, change the commenting to look like this:

CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
context.injectMouseMove(me.state.X.rel, me.state.Y.rel);

// mCameraMan->injectMouseMove(me);

Do the same thing for mousePressed and mouseReleased. If you're still having trouble with CEGUI, then remember to refer to Basic Tutorial 7.

Compile and run the application. You should see terrain with lighting and a skybox above. You should also be able to move the mouse cursor.

The Event Listeners

We will now introduce the event listeners. In the base source code, you will see that BasicApp inherits from WindowEventListener, FrameListener, MouseListener, and KeyListener. Each of these listeners bring methods that will be called when their related events occur. For instance, the KeyListener provides the keyPressed method that is called whenever a key is pressed. Also, if you look at these methods, you'll notice that we inject the event information into CEGUI as well. This is so that CEGUI can react to events created by Ogre.

This is what we are going to accomplish with the event listeners:

  1. We will set up a "mouse look" mode that is activated when the right mouse button is held down.
  2. We will add basic terrain collision to prevent the camera from passing through the terrain.
  3. We will make it so that clicking on the terrain with the left mouse button creates an entity, and holding down the button allows the user to move the new entity.

First, let's add some variables to our header:

BasicApp.h
float mRotSpd;
bool mLMouseDown, mRMouseDown;
     
Ogre::SceneNode* mCurObject;

The variable mRotSpd will hold the rotation speed of our camera when the right mouse button is held down. mLMouseDown and mRMouseDown will keep track of when a button is held down. mCurObject holds a pointer to the most recently created scene node (we will be using this to drag the entity around).

As always, we should make sure to initialize our variables in the constructor. If you want the camera to rotate faster, then you can adjust the mRotSpd here. Add these to the end of the initializer list:

BasicApp.cpp
mRotSpd(0.1),
mLMouseDown(false),
mRMouseDown(false),
mCurObject(0)

Controlling the Camera

We are going to allow the camera to be controlled by the mouse whenever the right button is held down. We will also hide the cursor when the camera is being controlled.

First, we will hide the cursor when the right mouse button is pressed. Add the following to mousePressed:

if (id == OIS::MB_Left)
{
  mLMouseDown = true;
}
else if (id == OIS::MB_Right)
{
  mRMouseDown = true;
  CEGUI::MouseCursor::getSingleton().hide();
}

Now we need to undo this when the the buttons are released. Add the following to mouseReleased:

if (id == OIS::MB_Left)
{
  mLMouseDown = false;
}
else if (id == OIS::MB_Right)
{
  mRMouseDown = false;
  CEGUI::MouseCursor::getSingleton().show();
}

Now we are going to change the camera's orientation when the mouse is moved while the right button is held. Add the following to mouseMoved:

if (mLMouseDown)
{
}
else if (mRMouseDown)
{
  mCamera->yaw(Ogre::Degree(-me.state.X.rel * mRotSpd));
  mCamera->pitch(Ogre::Degree(-me.state.Y.rel * mRotSpd));
}

We are changing the camera's direction based on the change in the position of the cursor since the last frame. me.state.X.rel is the relative distance along the x-axis the mouse moved since the last frame, and the yaw method rotates the camera left and right. The negative sign is because moving to the left on the x-axis is the negative direction, but rotating to the left is a positive change in angle. So to match them up we need to flip the sign.

You might be surprised to learn the same is true for the y-axis. This is because Ogre, like many other graphics engines, uses a system where y values increase as you move down the screen, but the pitch increases as the camera rotates upwards. The point (0, 0) is actually the top-left point on the screen. Finally, multiplying by mRotSpd ensures our camera moves with the speed we chose.

Compile and run the application. You should be able to control the camera while holding down the right mouse button. Since we are still injecting the keyboard events into our SdkCameraMan, you can also move around the world with WASD. This is one of the benefits of leaving behind the Tutorial Framework. We don't have to dig around in another class to change how our application handles input.

Collision with the Terrain

We are now going to make sure the camera can't pass through the terrain. Let's add a new method to our class to keep things more organized.

ITutorial.h
void handleCameraCollision();
ITutorial.cpp
void BasicApp::handleCameraCollision()
{
}

The new terrain system handles ray intersection directly. In previous versions of Ogre, we would have needed to set up and tear down an entire ray scene query, but now the terrain group takes care of this for us. Add the following to handleCameraCollision:

Ogre::Vector3 camPos = mCamera->getPosition();
Ogre::Ray camRay(
  Ogre::Vector3(camPos.x, 5000.0, camPos.z),
  Ogre::Vector3::NEGATIVE_UNIT_Y);

The first line is simple. We are just retrieving the position vector from mCamera. After that we create a ray that has its origin at a height of 5000.0 units and is directly above our camera. The reason we don't just use the camera's y-value is because our collision detection would fail if the camera was below the terrain. We are firing the ray in the negative y direction, so the ray would never hit the terrain if the camera was below the terrain. A ray is like a vector that never ends. It has a starting point, but then it goes off to infinity. They are used to track all kinds of things like line-of-sight, bullet collisions, and lighting.

To finish up the handleCameraCollision method we are going to use our ray to check the height of the terrain at our camera's position.

Ogre::TerrainGroup::RayResult result = mTerrainGroup->rayIntersects(camRay);

if (result.terrain)
{
  Ogre::Real terrainHeight = result.position.y;

  if (camPos.y < (terrainHeight + 10.0))
    mCamera->setPosition(camPos.x, terrainHeight + 10.0, camPos.z);
}

The first thing we do is to actually cast the ray against the our terrain and retrieve the result. A RayResult is a struct with a terrain component and a position component that we can use to determine what piece of terrain was hit. The if statement checks to make sure a piece of the terrain was actually hit, then we get the height of the terrain at that point from the position vector in our result. Finally, we check to see if our current camera height is less than 10.0 units above the terrain. If the camera has moved below this point, then we simply reset the camera's position to move it 10.0 units above the terrain without changing it's x or z value.

The only thing left to do is to call our handleCameraCollision method. Add this right before the return statement in frameRenderingQueued:

handleCameraCollision();

That's it! If you compile and run the application now, you should no longer be able to move the camera through the terrain.

Selecting Points on the Terrain

Now we are going to add the ability to create new entities when the terrain is clicked. If the left mouse button is held down after clicking, then we will be able to move the new entity around until we drop it by releasing the button. The first thing we do is add some code to the mousePressed method. This code will go inside the if statement that identifies the left mouse button being pressed.

CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
CEGUI::Vector2f mousePos = context.getMouseCursor().getPosition();

The first thing we do is get a reference to the default GUI context of CEGUI. This allows us access to large amount of information taken from the GUI. Using this context, we get the position of the mouse cursor. This is a very common pattern when working with CEGUI. Notice we hold on to the reference, because it will be useful again within this very method.

Ogre::Ray mouseRay =
  mCamera->getCameraToViewportRay(
    mousePos.d_x / float(me.state.width),
    mousePos.d_y / float(me.state.height));

Ogre::TerrainGroup::RayResult result = mTerrainGroup->rayIntersects(mouseRay);

This should look familiar. We just did something similar for terrain collision, but this time our raycast is a little more complicated. We use a convenience method called getCameraToViewportRay which returns a ray that starts at our camera frustum and goes off in a direction normal to it.

The last bit of complication is that this method requires the screen coordinates of the mouse cursor in "normalized coordinates". This means they should have a maximum size of one. Similar to how a normalized vector has a length of one. The coordinates we want run from (0, 0) to (1, 1). To normalize our cursor position, we divide the cursor's current position in pixels by the width of our viewport. Finally, we check for a raycast hit the same way we did with the collision.

if (result.terrain)
{
  Ogre::Entity* ent = mSceneMgr->createEntity("robot.mesh");

  mCurObject = mSceneMgr->getRootSceneNode()->createChildSceneNode();
  mCurObject->setPosition(result.position);
  mCurObject->setScale(0.2, 0.2, 0.2);
  mCurObject->attachObject(ent);
}

This is where we actually add the new entity to our scene. We check to make sure we actually hit the terrain, and then we build a scene node to attach our entity to. Newer versions no longer require you to provide a unique name for each entity or scene node. If you don't provide a name, then Ogre will generate a unique name for you. You can still provide your own name for the sake of convenience.

Compile and run the application. You should be able to place robots on the terrain and move them around before releasing the left mouse button. We've completed everything we set out to complete in this tutorial!

Conclusion

This tutorial is a solid introduction to using raycasts with terrain in Ogre. There is much more to learn, but you now have some of the basics under control.

The first thing we did was add a "mouse look" mode that is activated by holding down the right mouse button. This replaced the SdkCameraMan who was controlling the direction of the camera. It accomplished the same thing, but allowed us more direct control over the details.

Then we used a raycast to determine whether or not the camera had collided with the terrain. After that we used a raycast to determine the point on the terrain the user had clicked. Finally, we used this information to allow the creation and manipulation of entities in our scene.

Using raycasts to select entities instead of terrain will be covered in the next tutorial.

Exercises

Easy

  1. The camera's minimum height above the terrain should be kept in a static class member instead of hardcorded as 10.0 units. Make this change, and adjust the value to your personal tastes.
  2. Sometimes you will want to be able to pass through the terrain with the camera. Add a boolean flag to your application which toggles collision detection. Bind this effect to a key of your choice.

Intermediate

  1. It is wasteful to raycast against the terrain if the camera hasn't moved. Fix this problem by making sure the raycast is only done if the camera has moved since the last frame. (Hint: Find the camera's translation vector and compare it against Vector3::ZERO.)

Difficult

  1. We have very similar code involved in casting rays each time. Try to wrap up the raycast into a method. (Hint: You might find it useful to pass this method some parameters to make the method flexible enough to handle different types of raycasts.)

Advanced

  1. Raycasts are very useful throughout game programming. Take the code from Intermediate Tutorial 1 and complete the Difficult and Advanced exercises. then merge that code with this tutorial so that the robot walks on the terrain.
  2. Add a mode to your application where clicking on the terrain causes the robots to move to that location.

Full Source

The full source for this tutorial is here.

Next

Intermediate Tutorial 3


Alias: Intermediate_Tutorial_2

<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.