History: Intermediate Tutorial 2
Source of version: 154
Copy to clipboard
%tutorialhelp%
{maketoc}
!Introduction
In this tutorial we will be learning how to use the CEGUI mouse to select and place entities in our scene. We will cover:
# The use of the MouseListener and MouseMotionListener interfaces.
# How to use raycasts to keep the camera from passing through the terrain.
# How to use the mouse to select a specific location on the terrain.
((IntermediateTutorialBaseSource|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 ((IntermediateTutorial2SourceCurrent|here)).
__Note:__ There is also source available that uses the BaseApplication framework and Ogre 1.7 ((IntermediateTutorial2Source|here)).
__Note:__ There is also source available that uses the BaseApplication framework, Ogre 1.7, and the SdkTrays overlay system ((IntermediateTutorial2SdkTraysSource|here.))
{img fileId="2253" rel="box[g]"}
!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. If you want, you can simply copy the terrain code into your base files.
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 your resources.cfg file:
{CODE(wrap="1", colors="ini")}
[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
{CODE}
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.
!Setting up the Scene
We will now set up a basic scene. This should look familiar from previous tutorials. Add the following code to the beginning of {MONO()}createScene{MONO}:
{CODE(wrap="1", colors="c++")}
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));
{CODE}
Since we're dealing with a large terrain now, we should also set the near and far clip distance so we can see the distant terrain.
{CODE(wrap="1", colors="c++")}
mCamera->setNearClipDistance(0.1);
mCamera->setFarClipDistance(50000);
{CODE}
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.
{CODE(wrap="1", colors="c++")}
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);
{CODE}
If you did not create a {MONO()}setupTerrain{MONO} method, then you can look at the ((IntermediateTutorial2SourceCurrent|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, so that we can customize how the camera is controlled. In the {MONO()}mouseMoved{MONO} method change the comments to look like this:
{CODE(wrap="1", colors="c++")}
CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
context.injectMouseMove(me.state.X.rel, me.state.Y.rel);
// mCameraMan->injectMouseMove(me);
{CODE}
Do the same thing for {MONO()}mousePressed{MONO} and {MONO()}mouseReleased{MONO}. 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 {MONO()}keyPressed{MONO} 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:
# We will set up a "mouse look" mode that is activated when the right mouse button is held down.
# We will add basic terrain collision to prevent the camera from passing through the terrain.
# 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:
{CODE(wrap="1", colors="c++")}
float mRotSpd;
bool mLMouseDown, mRMouseDown;
Ogre::SceneNode* mCurObject;
{CODE}
The variable {MONO()}mRotSpd{MONO} will hold the rotation speed of our camera when the right mouse button is held down. {MONO()}mLMouseDown{MONO} and {MONO()}mRMouseDown{MONO} will track whether we have the mouse held down. {MONO()}mCurObject{MONO} holds a pointer to the most recently created SceneNode (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:
{CODE(wrap="1", colors="c++")}
mRotSpd(0.1),
mLMouseDown(false),
mRMouseDown(false),
mCurObject(0)
{CODE}
!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 this code to {MONO()}mousePressed{MONO}:
{CODE(wrap="1", colors="c++")}
if (id == OIS::MB_Left)
{
mLMouseDown = true;
}
else if (id == OIS::MB_Right)
{
mRMouseDown = true;
CEGUI::MouseCursor::getSingleton().hide();
}
{CODE}
Now we need to undo these settings when the the buttons are released. Add the following code to {MONO()}mouseReleased{MONO}:
{CODE(wrap="1", colors="c++")}
if (id == OIS::MB_Left)
{
mLMouseDown = false;
}
else if (id == OIS::MB_Right)
{
mRMouseDown = false;
CEGUI::MouseCursor::getSingleton().show();
}
{CODE}
Now we are going to change the camera's orientation when the mouse is moved while the right button is held. Add the following code to {MONO()}mouseMoved{MONO}:
{CODE(wrap="1", colors="c++")}
if (mLMouseDown)
{
}
else if (mRMouseDown)
{
mCamera->yaw(Ogre::Degree(-me.state.X.rel * mRotSpd));
mCamera->pitch(Ogre::Degree(-me.state.Y.rel * mRotSpd));
}
{CODE}
We are changing the camera's direction based on the change in the position of the cursor since the last frame. {MONO()}me.state.X.rel{MONO} 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 the 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 that our camera moves with the speed we chose.
Compile and run this code. 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 Basic 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.
{CODE(caption="ITutorial.h", wrap="1", colors="c++")}
void handleCameraCollision();
{CODE}
{CODE(caption="ITutorial.cpp", wrap="1", colors="c++")}
void BasicApp::handleCameraCollision()
{
}
{CODE}
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 RaySceneQuery, but now the TerrainGroup takes care of this for us. Add the following code to our new {MONO()}handleCameraCollision{MONO} method:
{CODE(wrap="1", colors="c++")}
Ogre::Vector3 camPos = mCamera->getPosition();
Ogre::Ray camRay(
Ogre::Vector3(camPos.x, 5000.0, camPos.z),
Ogre::Vector3::NEGATIVE_UNIT_Y);
{CODE}
The first line is simple. We are just retrieving the position vector from the 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 use the camera's y-value is so that our collision will still work if the camera is below the terrain. We are firing the ray in the negative y direction, so the ray would never hit the terrain if it was below the ground. 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 and bullet collision.
To finish up the {MONO()}handleCameraCollision{MONO} method we are going to use our Ray to check the height of the terrain at our camera's position.
{CODE(wrap="1", colors="c++")}
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);
}
{CODE}
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 (if any) was hit. The if statement checks to make sure a piece of the terrain was actually hit. If we have a hit, then we get the height of the terrain at that point from the position vector in our RayResult. 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 that is left to do is to add a call to our {MONO()}handleCameraCollision{MONO} method. Add this call right before the return statement in {MONO()}frameRenderingQueued{MONO}.
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, then we will be able to move the new entity around until we drop it by releasing the button. The first thing we will do is add some code to the {MONO()}mousePressed{MONO} method. This code will go inside the if statement that identifies the left mouse button being pressed.
{CODE(wrap="1", colors="c++")}
CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
CEGUI::Vector2f mousePos = context.getMouseCursor().getPosition();
{CODE}
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 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.
{CODE(wrap="1", colors="c++")}
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);
{CODE}
This should look quite familiar. We just did almost the same thing for the terrain collision. This time our raycast is a little more complicated. We use a convenience method called {MONO()}getCameraToViewportRay{MONO} which returns a ray that starts at our camera and fires off towards a point on our viewport. This is essentially a line-of-sight raycast focused on our cursor's position over the terrain. The last bit of complication is that this method requires the screen coordinates of the mouse cursor in "normalized coordinates". Just like with vectors, this means they should have a maximum size of one. So that screen values run from (0, 0) to (1, 1). To normalize our cursor position, we divide the cursors 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.
{CODE(wrap="1", colors="c++")}
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);
}
{CODE}
This is where we will actually add the new Entity to our scene. First we check to make sure we actually hit the terrain, and then we build a unique name for our Entity. If you don't understand the char and sprintf lines, then you probably need to seriously study some C/C++ before trying to dive into graphical programming with Ogre.
Next we take our unique name and use it to create a new robot Entity. Then we create a SceneNode for this entity automatically by calling the {MONO()}createChildSceneNode{MONO} method. Then we set the position of the new Entity to be the position we retrieved from our raycast hit on the terrain. Finally, we set the Entity's scale to something appropriate for our scene and attach it to the SceneNode so it will be displayed in our scene.
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!
!Exercises
!!Easy
# 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.
# 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
# It is wasteful to raycast against the terrain every frame even when the camera hasn't moved. Fix this problem by making sure the raycast is only done if the camera has moved sine the last frame. (Hint: Find the camera's translation vector and compare it against Vector3::ZERO.)
!!Difficult
# 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
# 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.
# Add a mode to your application where clicking on the terrain causes the robots to move to that location.
!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.
!Full Source
The full source for this tutorial is ((IntermediateTutorial2SourceCurrent|here)).
!Next
((Intermediate Tutorial 3))
---
Alias: (alias(Intermediate_Tutorial_2))