Intermediate Tutorial 3
From Ogre Wiki
Intermediate Tutorial 3: Mouse Picking (3D Object Selection) and SceneQuery Masks
Any problems you encounter while working with this tutorial should be posted to the Help Forum.
Contents |
Introduction
In this tutorial we will continue the work on the previous tutorial. We will be covering how to select any object on the screen using the mouse, and how to restrict what is selectable.
You can find the code for this tutorial here. As you go through the demo you should be slowly adding code to your own project and watching the results as we build it.
Prerequisites
This tutorial will assume that you have gone through the previous tutorial. We will also be using STL iterators to go through multiple results of SceneQueries, so basic knowledge of them will be helpful.
Getting Started
Even though we will be editing the code from last time, some changes have been made to make the rest of the tutorial more readable. For all of the mouse events, I have created wrapper functions to handle them. Now when the user presses the left mouse button, the "onLeftPressed" function is called, when the right button is released, the "onRightReleased" function is called, and so on. You should take the time to review these changes before starting the tutorial.
Create a new.cpp file and add it your to your solution, add the code below:
#include <CEGUI/CEGUISystem.h>
#include <CEGUI/CEGUISchemeManager.h>
#include <OgreCEGUIRenderer.h>
#include "ExampleApplication.h"
class MouseQueryListener : public ExampleFrameListener, public OIS::MouseListener
{
public:
MouseQueryListener(RenderWindow* win, Camera* cam, SceneManager *sceneManager, CEGUI::Renderer *renderer)
: ExampleFrameListener(win, cam, false, true), mGUIRenderer(renderer)
{
// Setup default variables
mCount = 0;
mCurrentObject = NULL;
mLMouseDown = false;
mRMouseDown = false;
mSceneMgr = sceneManager;
// Reduce move speed
mMoveSpeed = 50;
mRotateSpeed /= 500;
// Register this so that we get mouse events.
mMouse->setEventCallback(this);
// Create RaySceneQuery
mRaySceneQuery = mSceneMgr->createRayQuery(Ray());
} // MouseQueryListener
~MouseQueryListener()
{
mSceneMgr->destroyQuery(mRaySceneQuery);
}
bool frameStarted(const FrameEvent &evt)
{
// Process the base frame listener code. Since we are going to be
// manipulating the translate vector, we need this to happen first.
if (!ExampleFrameListener::frameStarted(evt))
return false;
// Setup the scene query
Vector3 camPos = mCamera->getPosition();
Ray cameraRay(Vector3(camPos.x, 5000.0f, camPos.z), Vector3::NEGATIVE_UNIT_Y);
mRaySceneQuery->setRay(cameraRay);
// Perform the scene query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();
// Get the results, set the camera height
if (itr != result.end() && itr->worldFragment)
{
Real terrainHeight = itr->worldFragment->singleIntersection.y;
if ((terrainHeight + 10.0f) > camPos.y)
mCamera->setPosition( camPos.x, terrainHeight + 10.0f, camPos.z );
}
return true;
}
/* MouseListener callbacks. */
bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
// Left mouse button up
if (id == OIS::MB_Left)
{
onLeftReleased(arg);
mLMouseDown = false;
} // if
// Right mouse button up
else if (id == OIS::MB_Right)
{
onRightReleased(arg);
mRMouseDown = false;
} // else if
return true;
}
bool mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
// Left mouse button down
if (id == OIS::MB_Left)
{
onLeftPressed(arg);
mLMouseDown = true;
} // if
// Right mouse button down
else if (id == OIS::MB_Right)
{
onRightPressed(arg);
mRMouseDown = true;
} // else if
return true;
}
bool mouseMoved(const OIS::MouseEvent &arg)
{
// Update CEGUI with the mouse motion
CEGUI::System::getSingleton().injectMouseMove(arg.state.X.rel, arg.state.Y.rel);
// If we are dragging the left mouse button.
if (mLMouseDown)
{
CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width),mousePos.d_y/float(arg.state.height));
mRaySceneQuery->setRay(mouseRay);
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();
if (itr != result.end() && itr->worldFragment)
mCurrentObject->setPosition(itr->worldFragment->singleIntersection);
} // if
// If we are dragging the right mouse button.
else if (mRMouseDown)
{
mCamera->yaw(Degree(-arg.state.X.rel * mRotateSpeed));
mCamera->pitch(Degree(-arg.state.Y.rel * mRotateSpeed));
} // else if
return true;
}
// Specific handlers
void onLeftPressed(const OIS::MouseEvent &arg)
{
// Setup the ray scene query, use CEGUI's mouse position
CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
mRaySceneQuery->setRay(mouseRay);
// Execute query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin( );
// Get results, create a node/entity on the position
if (itr != result.end() && itr->worldFragment)
{
char name[16];
sprintf(name, "Robot%d", mCount++);
Entity *ent = mSceneMgr->createEntity(name, "robot.mesh");
mCurrentObject = mSceneMgr->getRootSceneNode()->createChildSceneNode(String(name) + "Node", itr->worldFragment->singleIntersection);
mCurrentObject->attachObject(ent);
mCurrentObject->setScale(0.1f, 0.1f, 0.1f);
} // if
}
void onLeftReleased(const OIS::MouseEvent &arg)
{
}
void onRightPressed(const OIS::MouseEvent &arg)
{
CEGUI::MouseCursor::getSingleton().hide();
}
virtual void onRightReleased(const OIS::MouseEvent &arg)
{
CEGUI::MouseCursor::getSingleton().show();
}
protected:
RaySceneQuery *mRaySceneQuery; // The ray scene query pointer
bool mLMouseDown, mRMouseDown; // True if the mouse buttons are down
int mCount; // The number of robots on the screen
SceneManager *mSceneMgr; // A pointer to the scene manager
SceneNode *mCurrentObject; // The newly created object
CEGUI::Renderer *mGUIRenderer; // CEGUI renderer
};
class MouseQueryApplication : public ExampleApplication
{
protected:
CEGUI::OgreCEGUIRenderer *mGUIRenderer;
CEGUI::System *mGUISystem; // CEGUI system
public:
MouseQueryApplication()
{
}
~MouseQueryApplication()
{
}
protected:
void chooseSceneManager(void)
{
// Use the terrain scene manager.
mSceneMgr = mRoot->createSceneManager(ST_EXTERIOR_CLOSE);
}
void createScene(void)
{
// Set ambient light
mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5));
mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);
// World geometry
mSceneMgr->setWorldGeometry("terrain.cfg");
// Set camera look point
mCamera->setPosition(40, 100, 580);
mCamera->pitch(Degree(-30));
mCamera->yaw(Degree(-45));
// CEGUI setup
mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 3000, mSceneMgr);
mGUISystem = new CEGUI::System(mGUIRenderer);
// Mouse
CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLookSkin.scheme");
CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
}
void createFrameListener(void)
{
mFrameListener = new MouseQueryListener(mWindow, mCamera, mSceneMgr, mGUIRenderer);
mFrameListener->showDebugOverlay(true);
mRoot->addFrameListener(mFrameListener);
}
};
#if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char **argv)
#endif
{
// Create application object
MouseQueryApplication app;
try {
app.go();
} catch(Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
fprintf(stderr, "An exception has occurred: %s\n",
e.getFullDescription().c_str());
#endif
}
return 0;
}
Be sure you can compile and run this code before continuing. Despite some code changes, it should work the exact same as the last tutorial.
Showing Which Object is Selected
In this tutorial we will be making it so that you can "pick up" and move objects after you have placed them. We would like to have a way for the user to know which object she's currently manipulating. In a game, we would probably like to create a special way of highlighting the object, but for our tutorial (and for your applications before they are release-ready), you can use the showBoundingBox method to create a box around objects.
Our basic idea is to disable the bounding box on the old current object when the mouse is first clicked, then enable the bounding box as soon as we have the new object. To do this, we will add the following code to the beginning of the onLeftPressed function:
// Turn off bounding box.
if (mCurrentObject)
mCurrentObject->showBoundingBox(false);
Then add the following code to the very end of the onLeftPressed function:
// Show the bounding box to highlight the selected object
if (mCurrentObject)
mCurrentObject->showBoundingBox(true);
Now the mCurrentObject is always highlighted on the screen.
Adding Ninjas
We now want to modify the code to not just support robots, but also placing and moving ninjas. We will have a "Robot Mode" and a "Ninja Mode" that will determine which object we are placing on the screen. We will make the space key be our mode switching button, and we will display a message to the user which mode they are in.
First, we will setup the MouseQueryListener to be in Robot Mode from the beginning. We need to add a variable to hold the state of the object (that is, if we are placing robots or ninjas). Go to the protected section of MouseQueryListener and add this variable:
bool mRobotMode; // The current state
Now add this code to the end of the MouseQueryListener constructor:
// Set result text, and default state
mRobotMode = true;
mDebugText = "Robot Mode Enabled - Press Space to Toggle";
This puts us in Robot Mode! If only it were that simple. Now we need to create either a Robot or a Ninja mesh based on the mRobotMode variable. Locate this code in onLeftPressed:
char name[16];
sprintf(name, "Robot%d", mCount++);
Entity *ent = mSceneMgr->createEntity(name, "robot.mesh");
The replacement should be straight forward. Depending on the mRobotMode state we either put out a Robot or a Ninja, and name it accordingly:
Entity *ent;
char name[16];
if (mRobotMode)
{
sprintf(name, "Robot%d", mCount++);
ent = mSceneMgr->createEntity(name, "robot.mesh");
} // if
else
{
sprintf(name, "Ninja%d", mCount++);
ent = mSceneMgr->createEntity(name, "ninja.mesh");
} // else
Now we are almost done. The only thing left to do is to bind the spacebar to change states. Find the following code in frameStarted:
if (!ExampleFrameListener::frameStarted(evt))
return false;
And add this code after it:
// Swap modes
if(mKeyboard->isKeyDown(OIS::KC_SPACE) && mTimeUntilNextToggle <= 0)
{
mRobotMode = !mRobotMode;
mTimeUntilNextToggle = 1;
mDebugText = (mRobotMode ? String("Robot") : String("Ninja")) + " Mode Enabled - Press Space to Toggle";
}
Now we are done! Compile and run the demo. You can now choose which object you place by using the space bar.
Selecting Objects
Now we are going to dive into the meat of this tutorial: using RaySceneQueries to select objects on the screen. Before we start making changes to the code I will first explain a RaySceneQueryResultEntry in more detail. (Please follow the link and look at the struct briefly.)
The RaySceneQueryResult returns an iterator of RaySceneQueryResultEntry structs. This struct contains three variables. The distance variable tells you how far away the object is along the ray. One of the other two variables will be non-null. The movable variable will contain a MovableObject if the Ray intersected one. The worldFragment will contain a WorldFragment object if it hit a world fragment (like the terrain).
MovableObjects are basically any object you would attach to a SceneNode (such as Entities, Lights, etc). See the inheritance tree on this page to find out what type of objects would be returned. Most normal applications of RaySceneQueries will involve selecting and manipulating either the MovableObject you have clicked on, or the SceneNodes they are attached to. To get the name of the MovableObject, call the getName method. To get the SceneNode (or Node) the object is attached to, call getParentSceneNode (or getParentNode). The movable variable in a RaySceneQueryResultEntry will be equal to NULL if the result is not a MovableObject.
The WorldFragment is a different beast all together. When the worldFragment member of a RaySceneQueryResult is set, it means that the result is part of the world geometry created by the SceneManager. The type of world fragment that is returned is based on the SceneManager. The way this is implemented is WorldFragment struct contains the fragmentType variable which specifies the type of world fragment it contains. Based on the fragmentType variable, one of the other variables will be set (singleIntersection, planes, geometry, or renderOp). Generally speaking, RaySceneQueries only return WFT_SINGLE_INTERSECTION WorldFragments. The singleIntersection variable is simply a Vector3 reporting the location of the intersection. Other types of world fragments are beyond the scope of this tutorial.
Now lets look at an example. Lets say we wanted to print out a list of results after a RaySceneQuery. The following code would do this. (Assume that the fout object is of type ofstream, and that it has already been created using the open method.)
// Do not add this code to the program, just read along:
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;
// loop through the results
for ( itr = result.begin( ); itr != result.end(); itr++ )
{
// Is this result a WorldFragment?
if ( itr->worldFragment )
{
Vector3 location = itr->worldFragment->singleIntersection;
fout << "WorldFragment: (" << location.x << ", " << location.y << ", " << location.z << ")" << endl;
} // if
// Is this result a MovableObject?
else if ( itr->movable )
{
fout << "MovableObject: " << itr->movable->getName() << endl;
} // else if
} // for
This would print out the names of all MovableObjects that the ray intersects, and it would print the location of where it intersected the world geometry (if it did hit it). Note that this can sometimes act in strange ways. For example, if you are using the TerrainSceneManager, the origin of the Ray you fire must be over the Terrain or the intersection query will not register it as a hit. Different scene managers implement RaySceneQueries in different ways. Be sure to experiment with it when you use it with a new SceneManager.
Now, if we look back at our RaySceneQuery code, something should jump out at you: we are not looping through all the results! In fact we are only looking at the first result, which (in the case of the TerrainSceneManager) is the world geometry. This is bad, since we cannot be sure that the TerrainSceneManager will always return the world geometry first. We need to loop through the results to make sure we are finding what we are looking for. Another thing that we want to do is to "pick up" and drag objects that have already been placed. Currently if you click on an object that has already been placed, the program ignores it and places a robot behind it. Let's fix that now.
Go to the onLeftPressed function in the code. We first want to make sure that when we click, we get the first thing along the Ray. To do that, we need to set the RaySceneQuery to sort by depth. Find this code in the onLeftPressed function:
// Setup the ray scene query, use CEGUI's mouse position
CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
mRaySceneQuery->setRay(mouseRay);
// Execute query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();
And change it to this:
// Setup the ray scene query
CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
mRaySceneQuery->setRay(mouseRay);
mRaySceneQuery->setSortByDistance(true);
// Execute query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;
Now that we are returning the results in order, need to update the query results code. We are going to rewrite that section, so remove this code:
// Get results, create a node/entity on the position
if (itr != result.end() && itr->worldFragment)
{
Entity *ent;
char name[16];
if (mRobotMode)
{
sprintf(name, "Robot%d", mCount++);
ent = mSceneMgr->createEntity(name, "robot.mesh");
} // if
else
{
sprintf(name, "Ninja%d", mCount++);
ent = mSceneMgr->createEntity(name, "ninja.mesh");
} // else
mCurrentObject = mSceneMgr->getRootSceneNode()->createChildSceneNode(String(name) + "Node", itr->worldFragment->singleIntersection);
mCurrentObject->attachObject(ent);
mCurrentObject->setScale(0.1f, 0.1f, 0.1f);
} // if
We want to make it so that we can select objects that are already placed on the screen. Our strategy is going to have two parts. First, if the user clicks on an object, then make mCurrentObject equal to its parent SceneNode. If the user does not click on an object (if he clicks on the terrain instead), place a new Robot there like we did before. The first change is that we will be using a for loop instead of an if statement:
// Get results, create a node/entity on the position
for ( itr = result.begin(); itr != result.end(); itr++ )
{
First we will check if the first intersection is a MovableObject, if so we'll assign mCurrentObject to be its parent SceneNode. There is a catch though. The TerrainSceneManager creates MovableObjects for the terrain itself, so we might actually be intersecting one of the tiles. In order to fix that, I check the name of the object to make sure that it does not resemble a terrain tile name; a sample tile name would be "tile[0][0,2]". Finally, notice the break statement. We only need to act on the first object, so as soon as we find a valid one we need to get out of the for loop altogether.
if (itr->movable && itr->movable->getName().substr(0, 5) != "tile[")
{
mCurrentObject = itr->movable->getParentSceneNode();
break;
} // if
Next, we will check to see if the intersection returned a WorldFragment.
else if (itr->worldFragment)
{
Entity *ent;
char name[16];
Now we are either going to create a Robot entity or a Ninja entity based on mRobotState. After creating the entity we will create the SceneNode and break out of the for loop.
if (mRobotMode)
{
sprintf(name, "Robot%d", mCount++);
ent = mSceneMgr->createEntity(name, "robot.mesh");
} // if
else
{
sprintf(name, "Ninja%d", mCount++);
ent = mSceneMgr->createEntity(name, "ninja.mesh");
} // else
mCurrentObject = mSceneMgr->getRootSceneNode()->createChildSceneNode(String(name) + "Node", itr->worldFragment->singleIntersection);
mCurrentObject->attachObject(ent);
mCurrentObject->setScale(0.1f, 0.1f, 0.1f);
break;
} // else if
} // for
Believe it or not, that's all that has to be done! Compile and play with the code. Now we create the correct type of object when we click on terrain, and when we click on an object we will see the bounding box (no dragging it around right now, this comes in the next Step). One valid question is, since we only want the first intersection, and since we sorted by depth, why not just use an if statement? The main reason is we could actually have a fall through if there the first returned object is one of those pesky tiles. We have to loop until we find something other than a tile or we hit the end of the list.
Now that we are on the subject, we need to also update the RaySceneQuery code in other locations. In both the frameStarted and the onLeftDragged functions we only need to find the Terrain. There is no reason to sort the results because the terrain will be at the end of the sorted list (so we are going to turn sorting off). We still want to loop through the results though, just in case the TerrainSceneManager is changed at a future date to not return the terrain first. First, find this section of code in frameStarted:
// Perform the scene query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();
// Get the results, set the camera height
if (itr != result.end() && itr->worldFragment)
{
Real terrainHeight = itr->worldFragment->singleIntersection.y;
if ((terrainHeight + 10.0f) > camPos.y)
mCamera->setPosition(camPos.x, terrainHeight + 10.0f, camPos.z);
}
Then replace it with this:
// Perform the scene query
mRaySceneQuery->setSortByDistance(false);
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;
// Get the results, set the camera height
for (itr = result.begin(); itr != result.end(); itr++)
{
if (itr->worldFragment)
{
Real terrainHeight = itr->worldFragment->singleIntersection.y;
if ((terrainHeight + 10.0f) > camPos.y)
mCamera->setPosition(camPos.x, terrainHeight + 10.0f, camPos.z);
break;
} // if
} // for
This should be self explanatory. We add a line to turn off sorting, then we convert the if statement into a for loop, and break as soon as we have found the position we are looking for. We will do the exact same thing with the mouseMoved function. Find this section of code in the mouseMoved:
mRaySceneQuery->setRay(mouseRay);
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();
if (itr != result.end() && itr->worldFragment)
mCurrentObject->setPosition(itr->worldFragment->singleIntersection);
And replace it with this code:
mRaySceneQuery->setRay(mouseRay);
mRaySceneQuery->setSortByDistance(false);
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;
for (itr = result.begin(); itr != result.end(); itr++)
if (itr->worldFragment)
{
mCurrentObject->setPosition(itr->worldFragment->singleIntersection);
break;
} // if
Compile and test the code. There shouldn't be any noticeable difference since the last time we ran the code, but now we are doing it the correct way, and future updates to the TerrainSceneManager will not break our code.
Query Masks
Notice that no matter what mode we are in we can select either object. Our RaySceneQuery will return either Robots or Ninjas, whichever is in front. It doesn't have to be this way though. All MovableObjects allow you to set a mask value for them, and SceneQueries allow you to filter your results based on this mask. All masks are done using the binary AND operation, so if you are unfamiliar with this, you should brush up on it before continuing.
The first thing we are going to do is create the mask values. Go to the very beginning of the MouseQueryListener class and add this after the public statement:
enum QueryFlags
{
NINJA_MASK = 1<<0,
ROBOT_MASK = 1<<1
};
This creates an enum with two values, which in binary are 0001 and 0010. Now, every time we create a Robot entity, we call its "setMask" function to set the query flags to be ROBOT_MASK. Every time we create a Ninja entity we call its "setMask" function and use NINJA_MASK instead. Now, when we are in Ninja mode, we will make the RaySceneQuery only consider objects with the NINJA_MASK flag, and when we are in Robot mode we will make it only consider ROBOT_MASK.
Find this section of onLeftPressed:
if (mRobotMode)
{
sprintf(name, "Robot%d", mCount++);
ent = mSceneMgr->createEntity(name, "robot.mesh");
} // if
else
{
sprintf(name, "Ninja%d", mCount++);
ent = mSceneMgr->createEntity(name, "ninja.mesh");
} // else
We will add two lines to set the mask on both of them:
if (mRobotMode)
{
sprintf(name, "Robot%d", mCount++);
ent = mSceneMgr->createEntity(name, "robot.mesh");
ent->setQueryFlags(ROBOT_MASK);
} // if
else
{
sprintf(name, "Ninja%d", mCount++);
ent = mSceneMgr->createEntity(name, "ninja.mesh");
ent->setQueryFlags(NINJA_MASK);
} // else
We still need to make it so that when we are in a mode, we can only click and drag objects of that type. We need to set the query flags so that only the correct object type can be selected. We accomplish this by setting the query mask in the RaySceneQuery to be the ROBOT_MASK in Robot mode, and set it to NINJA_MASK in Ninja mode. In the onLeftPressed function, find this code:
mRaySceneQuery->setSortByDistance(true);
Add this line of code after it:
mRaySceneQuery->setQueryMask(mRobotMode ? ROBOT_MASK : NINJA_MASK);
Compile and run the tutorial. We now select only the objects we are looking for. All rays that pass through other objects go through them and hit the correct object. We are now finished working on this code. The next section will not be modifying it.
Query Type Masks
There's one more thing to consider when using scene queries. Suppose you added a billboardset or a particle system to your scene above, and you want to move it around. You will find that the query never returns the billboardset that you click on. This is because the SceneQuery has another mask, the QueryTypeMask, that limits you to selecting only the type specified as the flag. By default when you do a query, it returns only objects of entity type.
In your code, if you want your query to return BillboardSets or ParticleSystems, you'll have to do this first before executing your query:
mRaySceneQuery->setQueryTypeMask(SceneManager::FX_TYPE_MASK);
Now the query will only return BillboardSets or ParticleSystems as results.
There are 6 types of QueryTypeMask defined in the SceneManager class as static members:
WORLD_GEOMETRY_TYPE_MASK //Returns world geometry. ENTITY_TYPE_MASK //Returns entities. FX_TYPE_MASK //Returns billboardsets / particle systems. STATICGEOMETRY_TYPE_MASK //Returns static geometry. LIGHT_TYPE_MASK //Returns lights. USER_TYPE_MASK_LIMIT //User type mask limit.
The default QueryTypeMask when the property is not set manually is ENTITY_TYPE_MASK.
More on Masks
Our mask example is very simple, so I would like to go through a few more complex examples.
Setting a MovableObject's Mask
Every time we want to create a new mask, the binary representation must contain only one 1 in it. That is, these are valid masks:
00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000
And so on. We can very easily create these values by taking 1 and bitshifting them by a position value. That is:
00000001 = 1<<0 00000010 = 1<<1 00000100 = 1<<2 00001000 = 1<<3 00010000 = 1<<4 00100000 = 1<<5 01000000 = 1<<6 10000000 = 1<<7
All the way up to 1<<31. This gives us 32 distinct masks we can use for MovableObjects.
Querying for Multiple Masks
We can query for multiple masks by using the bitwise OR operator. Let say we have three different groups of objects in a game:
enum QueryFlags
{
FRIENDLY_CHARACTERS = 1<<0,
ENEMY_CHARACTERS = 1<<1,
STATIONARY_OBJECTS = 1<<2
};
Now, if we wanted to query for only friendly characters we could do:
mRaySceneQuery->setQueryMask(FRIENDLY_CHARACTERS);
If we want the query to return both enemy characters and stationary objects, we would use:
mRaySceneQuery->setQueryMask(ENEMY_CHARACTERS | STATIONARY_OBJECTS);
If you use a lot of these types of queries, you might want to define this in the enum:
OBJECTS_ENEMIES = ENEMY_CHARACTERS | STATIONARY_OBJECTS
And then simply use OBJECTS_ENEMIES to query.
Querying for Everything but a Mask
You can also query for anything other than a mask using the bit inversion operator, like so:
mRaySceneQuery->setQueryMask(~FRIENDLY_CHARACTERS);
Which will return everything other than friendly characters. You can also do this for multiple masks:
mRaySceneQuery->setQueryMask(~(FRIENDLY_CHARACTERS | STATIONARY_OBJECTS));
Which would return everything other than friendly characters and stationary objects.
Selecting all Objects or No Objects
You can do some very interesting stuff with masks. The thing to remember is, if you set the query mask QM for a SceneQuery, it will match all MovableObjects that have the mask OM if QM & OM contains at least one 1. Thus, setting the query mask for a SceneQuery to 0 will make it return no MovableObjects. Setting the query mask to ~0 (0xFFFFF...) will make it return all MovableObjects that do not have a 0 query mask.
Using a query mask of 0 can be highly useful in some situations. For example, the TerrainSceneManager does not use QueryMasks when it returns a worldFragment. By doing this:
mRaySceneQuery->setQueryMask(0);
You will get ONLY the worldFragment in your RaySceneQueries for that SceneManager. This can be very useful if you have a lot of objects on screen and you do not want to waste time looping through all of them if you only need to look for the Terrain intersection.
Exercises
Easy Exercises
- The TerrainSceneManager creates tiles with a default mask of ~0 (all queries select it). We fixed this problem by testing to see if the name of the movable object equaled "tile[0][0,2]". Even though it's not implemented yet, the TerrainSceneManager supports multiple pages, and if there were more things than just "tile[0][0,2]" this would cause our code to break down. Instead of making the test in the loop, fix the problem properly by setting all of the tile objects created by the TerrainSceneManager to have a unique mask. (Hint: The TerrainSceneManager creates a SceneNode called "Terrain" which contains all of these tiles. Loop through them and set the attached object's masks to something of your choosing.)
Intermediate Exercises
- Our program delt with two things, Robots and Ninjas. If we were going to implement a scene editor, we would want to place any number of different object types. Generalize this code to allow the placement of any type of object from a predefined list. Create an overlay with the list of objects you want the editor to have (such as Ninjas, Robots, Knots, Ships, etc), and have the SceneQueries only select that type of object.
- Since we are using multiple types of objects now, use the Factory Pattern to properly create the SceneNodes and Entities.
Advanced Exercises
- Generalize the previous exercises to read in all of the meshes that Ogre knows about (IE everything that was parsed in from the Media directory), and give the ability to place them. Note that there should not be a limit as to how many types of objects ogre can place. Since you only have 32 unique query masks to use, you may need to come up with a way to quickly change all of the query flags for objects on the screen.
- You might have noticed that when you click on an object, the object is "lifted" from the bottom of the bounding box. To see this, click on the top of any character and move him. He will be transported instantly elsewhere. Modify the program to fix this problem.
Exercises for Further Study
- Add a way to select multiple objects to the program such that when you hold the Ctrl key and click multiple objects are highlighted. When you move these objects, move all of them as a group.
- Many scene editing programs allow you to group objects so that they are always moved together. Implement this in the program.
- Proceed to Intermediate Tutorial 4 Volume Selection and Basic Manual Objects
| Ogre Tutorials |
|---|
|
Ogre Beginner Tutorials: 1. Basic Introduction - 2. Cameras, Lights and Shadows - 3. Terrain, Sky and Fog - 4. Frame Listeners and Unbuffered Input - 5. Buffered Input - 6. The Ogre Startup Sequence - 7. CEGUI and OGRE - 8. Multiple and Dual SceneManagers Intermediate Tutorials: 1. Animation, Interpolation and Quaternions - 2. RaySceneQueries and Basic Mouse Usage (1/2) - 3. Mouse Picking and SceneQuery Masks (2/2) - 4. Volume Selection and Manual Objects - 5. Static Geometry - 6. Projective Decals - 7. Render to Texture Advanced Tutorials: 1. Resources and ResourceManagers See also: Artist Tutorials - Ogre Articles - Cookbook |

