History: Intermediate Tutorial 3
Source of version: 105
Copy to clipboard
%tutorialhelp%
{maketoc}
!Introduction
This tutorial will continue from the previous tutorial. Do not start with the usual base code. Instead, start up exactly where ((Intermediate Tutorial 2)) left off. This tutorial will be covering the basics of selecting entities in the scene. It will also cover ways of restricting what is selectable.
The full source for this tutorial is ((IntermediateTutorial3SourceCurrent|here)).
The full source for Intermediate Tutorial 2 is ((IntermediateTutorial2SourceCurrent|here)). This should be your starting point for this tutorial.
__Note:__ There is also source available that uses the BaseApplication framework and Ogre 1.7 ((IntermediateTutorial3Source|here)).
__Note:__ There is also source available that uses the BaseApplication framework, Ogre 1.7, and the builtin SdkTrays overlay system ((IntermediateTutorial3SdkTraysSource|here)).
{img fileId="2254" 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 is a continuation of ((Intermediate Tutorial 2)). You should start this tutorial after completing that one.
!Highlighting a Selected Entity
The first thing we want to do is make it possible to highlight a selected object. In your own serious applications, you will most likely want to use something ((Intermediate Tutorial 6|projective decals)) or make changes to the color of the entity's actual mesh, but we will use the basic bounding box visualization provided by Ogre.
Setting up this bounding box is easy. When the left mouse button is pressed, we will check to see if there was already a previous entity selected. Add the following to the if statement that checks for the left mouse button in {MONO()}mousePressed{MONO}:
{CODE(wrap="1", colors="c++")}
if (mCurObject)
mCurObject->showBoundingBox(false);
{CODE}
That will turn off the bounding box for any previously selected entity. Now add the following code right before the return statement:
{CODE(wrap="1", colors="c++")}
if (mCurObject)
mCurObject->showBoundingBox(true);
{CODE}
This will turn on the bounding box for any entity that was just selected. That's it. Compile and run the application. You should now see the current entity highlighted with a wireframe box.
{img fileId="2266" rel="box[g]"}
!Ninjas!
Now we want to modify the code so that we can also create ninjas. We will have a "Robot Mode" and a "Ninja Mode". We will use the spacebar to switch between them.
First, let's add a boolean variable that will keep track of what mode we are in.
{CODE(caption="BasicApp.h", wrap="1", colors="c++")}
bool bRobotMode;
{CODE}
Now initialize the variable to true so that we start in Robot Mode.
{CODE(caption="BasicApp.cpp", wrap="1", colors="c++")}
bRobotMode(true)
{CODE}
We need to make sure that the right kind of wntity is created based on our current mode. Find the following code in {MONO()}mousePressed{MONO}:
{CODE(wrap="1", colors="c++")}
Entity* ent = mSceneMgr->createEntity("robot.mesh");
{CODE}
We will replace this with code that takes our current mode into account.
{CODE(wrap="1", colors="c++")}
Ogre::Entity* ent;
if (bRobotMode)
{
ent = mSceneMgr->createEntity("robot.mesh");
}
else
{
ent = mSceneMgr->createEntity("ninja.mesh");
}
{CODE}
Now we need to do is toggle our mode when the SPACE key is pressed. Add the following code to {MONO()}keyPressed{MONO}:
{CODE(wrap="1", colors="c++")}
if(ke.key == OIS::KC_SPACE)
bRobotMode = !bRobotMode;
{CODE}
The last thing we'll do is simply for convenience. We already have a CEGUI label that tells us the terrain is building, but we don't use it for anything after that. Let's have it display what mode we are in so the user can know what they will place next.
Find this line in {MONO()}frameRenderingQueued{MONO}:
{CODE(wrap="1", colors="c++")}
terrainLabel->setText("");
{CODE}
And change it to this:
{CODE(wrap="1", colors="c++")}
if (mRobotMode)
terrainLabel->setText("Robot Mode");
else
terrainLabel->setText("Ninja Mode");
{CODE}
That's all there is to it. Compile and run the application. You should be able to switch between placing robots and ninjas and the current mode should be displayed in the label.
!Selecting Entities
We are now going to use RaySceneQueries to select entities in our scene. The result of a RaySceneQuery is a RaySceneQueryResult, which is an iterable collection of [http://www.ogre3d.org/docs/api/1.9/struct_ogre_1_1_ray_scene_query_result_entry.html|RaySceneQueryResultEntry] structs.
A RaySceneQueryResultEntry struct contains three variables. The distance variable tells you how far along the ray the object is. The movable and worldFragment variables tell you what kind of object was hit by the ray. With the old terrain system, testing for worldFragments was how you would do raycasts against the terrain. The new terrain system makes this method obsolete. But the movable variable is still used to determine when a ray has hit any entity attached to a SceneNode (notice that this includes things like the camera, which is clearly a movable entity). If an Entity was hit, then the movable variable will contain a [http://www.ogre3d.org/docs/api/1.9/class_ogre_1_1_movable_object.html|MovableObject]. Usually, we will get the SceneNode for our MovableObject by calling {MONO()}getParentSceneNode{MONO}.
Let's look at an example to help clarify these concepts. For the example, we will simply print out everything that was discovered by a RaySceneQuery.
{CODE(wrap="1", colors="c++")}
// Do not add this to your project
RaySceneQueryResult& result = mRayScnQuery->execute();
RaySceneQueryResult::iterator it;
for (it = result.begin(); it != result.end(); it++)
{
if (it->worldFragment)
{
Vector3 location = it->worldFragment->singleIntersection;
std::cout << "WorldFragment: (" <<
location.x << ", " << location.y << ", " << location.z << ")" << std::endl;
}
else if (it->movable)
{
std::cout << "MovableObject: " << it->movable->getName() << std::endl;
}
}
{CODE}
Using the new terrain system, we would not get any worldFragment results, even when clicking on the terrain. I've left it in simply for completeness. But we would still get MovableObject results if our ray hit one of the Entities we've placed in our scene.
Now let's actually add these concepts into our application. To get started, let's add a few more variables to our class. Add the following to the header:
{CODE(caption="BasicApp.h", wrap="1", colors="c++")}
bool mMovableFound;
Ogre::RaySceneQuery* mRayScnQuery;
{CODE}
Then add these initializations:
{CODE(caption="BasicApp.cpp", wrap="1", colors="c++")}
mMovableFound(false),
mRayScnQuery(0)
{CODE}
We now have to reorganize our {MONO()}mousePressed{MONO} function. First, find the code that starts with this line:
{CODE(wrap="1", colors="c++")}
Ogre::TerrainGroup::RayResult terrainResult =
{CODE}
And ends with this:
{CODE(wrap="1", colors="c++")}
mCurObject->attachObject(ent);
{CODE}
We're going to wrap this in an if statement that checks to see if our mMovableFound variable is false.
{CODE(wrap="1", colors="c++")}
if (!mMovableFound)
{
Ogre::TerrainGroup::RayResult terrainResult =
...
mCurObject->attachObject(ent);
}
{CODE}
Now we need to get into setting up and using our RaySceneQuery. Add the following code right before our new if statement (after we create the Ogre::Ray):
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setRay(mouseRay);
mRayScnQuery->setSortByDistance(true);
Ogre::RaySceneQueryResult& result = mRaySceneQuery->execute();
Ogre::RaySceneQueryResult::iterator it = result.begin();
mMovableFound = false;
{CODE}
The first thing we do is give our mouseRay to the RaySceneQuery object. It requires this to do the raycast. Next, we tell it to return the results sorted by distance. Otherwise, they would come back in a seemingly random order for performance reasons.
Then we actually execute the query, and save a reference to the result. We also get an iterator pointing to the first position in the collection. The last thing we do is "reset" our flag that keeps track of whether or not we've found a MovableObject.
Now we have to look through the results of our query. Add the following code:
{CODE(wrap="1", colors="c++")}
for ( ; it != result.end(); it++)
{
mMovableFound =
it->movable &&
it->movable->getName() != "" &&
it->movable->getName() != "PlayerCam";
if (mMovableFound)
{
mCurObject = it->movable->getParentSceneNode();
break;
}
}
{CODE}
For each RaySceneQueryResult, we first check to make sure it is one of our robot/ninja entities. As mentioned before, the Camera is also an entity, and if you run tests on your current scene with the RaySceneQuery, you will notice there seems to be other entities that have no name floating around your scene. We must also discard these entities as invalid (they are not terrain elements either, try clicking on the sky and you'll still get some no-name results).
Then we update our currently selected object if what we found was indeed a robot or ninja entity. After that we break from the for loop, because we've found what we're looking for.
Finally, we should make sure to clean up the RaySceneQuery. Add the following to {MONO()}~BasicApp{MONO}:
{CODE(wrap="1", colors="c++")}
mSceneMgr->destroyQuery(mRayScnQuery);
{CODE}
That is actually all we have to do. That's pretty impressive! Imagine trying to accomplish all of this by calculating all of these rays and manipulating all of the matrices involved. Compile and run the application. You should be able to reselect entities that you've already placed into the world, while still being able to create new entities when clicking on empty terrain.
!Selecting Specific Types of Entities
That last major part of this tutorial is going to deal with masking our selection. This means only selecting certain entities. We want to be able to select robots only when we're in Robot Mode and select ninjas only when we're in Ninja Mode. This is actually very easy to do.
The first thing we are going to do is add an enum to our class. Add the following to the public section of our header:
{CODE(caption="BasicApp.h", wrap="1", colors="c++")}
enum QueryFlags
{
ROBOT_MASK = 1 << 0,
NINJA_MASK = 1 << 1
};
{CODE}
The technique we are going to use is called bitmasking. It is a __very__ widely used concept in programming. It makes use of the bitwise operators that most languages provide for changing individual bits in a byte (or at least they simulate it). Wikipedia has a pretty good introduction to the topic [http://en.wikipedia.org/wiki/Mask_%28computing%29|here]. It something worth understanding well. The technique allows us to pack a lot of information into a small amount of data. What we're doing with the enum is declaring two values using the bitwise "shift" operator. This takes a binary number and shifts the bits by a certain number of places. So our ROBOT_MASK value is going to be the number one shifted ''zero'' places to the left, and our NINJA_MASK is going to be the number one shifted ''one'' place to the left.
{CODE(wrap="1")}
ROBOT_MASK = 0000 0001
NINJA_MASK = 0000 0010
{CODE}
These will be used to uniquely identify each type of entity. The next step is to set our entities QueryFlags when we create them. Update the entity creation code in {MONO()}mousePressed{MONO} so that it looks like this:
{CODE(wrap="1", colors="c++")}
if (mRobotMode)
{
ent = mSceneMgr->createEntity("robot.mesh");
ent->setQueryFlags(ROBOT_MASK);
}
else
{
ent = mSceneMgr->createEntity("ninja.mesh");
ent->setQueryFlags(NINJA_MASK);
}
{CODE}
The only thing we've changed is the addition of the {MONO()}setQueryFlags{MONO} methods. This method takes the enum values we set up. The last thing we need to do is to tell our RaySceneQuery when to use each mask. Add the following to {MONO()}mousePressed{MONO} right after we call {MONO()}setSortByDistance{MONO}:
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(mRobotMode ? ROBOT_MODE : NINJA_MASK);
{CODE}
That is all there is to it. Compile and run your application. You should only be able to select an entity when you are in the corresponding mode. This is the end of the main tutorial. The rest is supplemental information about further making use of bitmasks with Ogre. It is some very useful information, but it will not add anything new to the code.
!More on Masks
We will now give a brief description of some other useful applications of using these masks. The code from this point forth will ''not'' be added to this tutorial, because most of it requires adding more to the scene. But these techniques should give you a number of ideas on how to customize the application we've already built. Especially once you've learned more about building your scene from later tutorials.
!!Query Type Masks
There are many other kinds of MovableObject that can used in your raycasts. For instance, if you were using a [http://www.ogre3d.org/docs/api/1.9/class_ogre_1_1_billboard_set.html|BillboardSet] or a [http://www.ogre3d.org/docs/api/1.9/class_ogre_1_1_particle_system.html|ParticleSystem], then the raycasts we've been using in this tutorial would ignore those elements in your scene. You may or may not want things to work that way. This is where QueryTypeMasks come in.
A QueryTypeMask allows you to decide what type of objects are to be included. By default, the RaySceneQuery has its QueryTypeMask set to ENTITY_TYPE_MASK. This only returns entities you've placed in your scene. To change the current QueryTypeMask we would use the following:
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryTypeMask(Ogre::SceneManager::FX_TYPE_MASK);
{CODE}
The SceneManager defines six QueryTypeMask values:
{CODE(wrap="1", colors="c++")}
WORLD_GEOMETRY_TYPE_MASK // returns world geometry
ENTITY_TYPE_MASK // returns entities (default)
FX_TYPE_MASK // returns BillboardSets/ParticleSystems.
STATICGEOMETRY_TYPE_MASK // returns static geometry
LIGHT_TYPE_MASK // returns lights
USER_TYPE_MASK_LIMIT // user type mask limit
{CODE}
!!Combining Masks
It is often useful to be able to combine masks so that you can select objects from more than one group with the same query. This is easily accomplished by using another bitwise operator. The bitwise OR operator allows us to combine masks in such a way. Let's say we had a set of QueryFlags like this:
{CODE(wrap="1", colors="c++")}
enum QueryFlags
{
NPC = 1 << 0,
ENEMY = 1 << 1,
ITEM = 1 << 2,
};
{CODE}
If we wanted to be able to select both NPCs and ITEMS we could set the mask like this:
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(NPC | ITEM);
{CODE}
Now this RaySceneQuery would return MovableObjects with either NPC or ITEM masks set. You can start to see why these bitmasks are so often useful. If you have a particular combination that you use a lot, then you can assign it a new name for convenience in your enum:
{CODE(wrap="1", colors="c++")}
enum QueryFlags
{
NPC = 1 << 0,
ENEMY = 1 << 1,
ITEM = 1 << 2,
NONHOSTILE = NPC | ITEM,
}
{CODE}
!! Negation of a Mask
There is another bitwise operator that flips every bit in the number. This is bitwise negation. It is equivalent to combining together all of the masks except the one you negated. An example will probably help.
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(~ENEMY);
{CODE}
This is exactly equivalent to our previous example with bitwise OR. This "not ENEMY" QueryMask would return everything except objects with the ENEMY mask. In our case, that is exactly the same as return NPC | ITEM, but you can see it is more concise.
Finally, you can begin to combine these bitwise operations. What if we wanted to return everything except NPCs ''and'' ITEMs? We could do this by combining bitwise negation and bitwise OR.
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(~(NPC | ITEM));
{CODE}
One last trick you can do with negation is create a query that returns ''every'' kind of movable object. The trick is to negate the number zero. By doing this you get the mask of all ones. This is the same mask you'd get by using bitwise OR on every mask in your enum.
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(~0);
{CODE}
In our example, this is equivalent to:
{CODE(wrap="1", colors="c++")}
mRayScnQuery->setQueryMask(NPC | ENEMY | ITEM);
{CODE}
__Note:__ To avoid confusion, it should be pointed out that the binary numbers ~0 and {MONO()}NPC | ENEMY | ITEM{MONO} would ''not'' be equivalent. It is just that they will have the equivalent effect in our example because we have not defined any masks beyond those three. The actual values would be:
{CODE(wrap="1", colors="c++")}
NPC | ENEMY | ITEM = 0000 0000 0000 0111
~0 = 1111 1111 1111 1111
{CODE}
The important part is that they match for the first three places, because that is all our example was using.
Again, if a lot of these bitmasking examples have been confusing, then you should seriously consider doing some supplemental reading along with these tutorials. If you have a solid handle on the mathematics, it will help you immensely as a programmer, and if you try and skate by without it, then you will constantly be struggling and trying to understand two subjects at once.
!Exercises
!!Easy
# Choose some of the techniques introduced in the More About Masks section and update your scene to use them in any way you choose.
!!Intermediate
# Our application only allows two types of entities. In a real scene editor, you would want to be able to choose from a customizable list of entities. Use CEGUI to create GUI elements that allow you to chose from a number of different entities to place onto the terrain.
# After you've completed the previous exercise, then allow the user to use the GUI to select what types of entities are active. You will be using techniqes that are covered in the More About Masks section after the main tutorial.
# Since we are creating multiples types of objects now, we should be using the concept of a [http://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29|Factory] to properly create our Entities and SceneNodes. Implement this design pattern.
!!Difficult
# One bug in our current design is that no matter where you select an entity, our application will consider it like you are holding the model from the very bottom. To make this more clear, just try it in your application. Grab a model by the top and then move the mouse slightly. If your cursor is still over some terrain, then the model will fly far across the terrain. This is because it is trying to place the __bottom__ of the model where your cursor is. Fix this issue.
!!Advanced
# Add the ability to select multiple objects by holding the Ctrl key and clicking on a number of different entities. Also make it so that moving one of these selected entities moves the entire group.
# Many RTS games allow you to create persistent groups of entities that can be selected automatically and moved together. Implement this feature in your program.
!Conclusion
This tutorial was a continuation of the previous tutorial about using raycasts in your scene. We were introduced to the full RaySceneQuery process for building a raycast and searching through the results.
We used these queries to reselect entities we had already placed into our scene. This lead us to the notion of how we could control what entities would be selected. The problem was solved by the use of bitmasks. Bitmasking is widely-used technique that allows us to make use of the concept of individual bits to keep track of data instead of always using full bytes. We learned about a series of bitwise operations which allows us to quickly create complicated bit patterns representing collections of entities to be used in our raycasts.
!Full Source
The full source for this tutorial is ((IntermediateTutorial3SourceCurrent|here)).
!Next
((Intermediate Tutorial 4))
---
Alias: (alias(Intermediate_Tutorial_3))