Intermediate Tutorial 3         Mouse Picking (3D Object Selection) and SceneQuery Masks (Part 2 of 2)
Print

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

 

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.

Info NOTE: If you want to try the tutorial without using CEGUI you can find the source code using the built in SdkTrays here.

Prerequisites

This tutorial will assume that you have gone through the previous tutorial using the Ogre Tutorial Framework. We will also be using STL iterators to go through multiple results of SceneQueries, so basic knowledge of them will be helpful.

Getting Started

 
Now if you want to follow this tutorial completely, or you just copy and paste, make sure your .h file looks something like this:

#ifndef __IntermediateTutorial3_h_
#define __IntermediateTutorial3_h_
 
#include "BaseApplication.h"
 
#include <CEGUISystem.h>
#include <CEGUISchemeManager.h>
#include <RendererModules/Ogre/CEGUIOgreRenderer.h>
 
class IntermediateTutorial3 : public BaseApplication
{
public:
    IntermediateTutorial3(void);
    virtual ~IntermediateTutorial3(void);
 
protected:
        virtual void createScene(void);
 
        virtual void chooseSceneManager(void);
	virtual void createFrameListener(void);
 
	virtual bool frameRenderingQueued(const Ogre::FrameEvent& arg);
 
	virtual bool mouseMoved(const OIS::MouseEvent& arg);
	virtual bool mousePressed(const OIS::MouseEvent& arg, OIS::MouseButtonID id);
	virtual bool mouseReleased(const OIS::MouseEvent& arg, OIS::MouseButtonID id);
 
	Ogre::SceneNode *mCurrentObject;	//pointer to our currently selected object
	Ogre::RaySceneQuery* mRayScnQuery;	//pointer to our ray scene query
	CEGUI::Renderer* mGUIRenderer;		//our CEGUI renderer
 
	bool bLMouseDown, bRMouseDown;	//true if mouse buttons are held down
	int mCount;						//number of objects created
	float mRotateSpeed;				//the rotation speed for the camera
 
};
 
#endif // #ifndef __IntermediateTutorial3_h_

 
You should also make sure IntermediateTutorial3.cpp looks like this. If you went through the previous tutorial and are continuing on from it, your code should already look something like this. If it doesn't, make sure that it does and that it compiles and runs successfully. The only thing different should be the comments and some of the variable initialization has been moved to the constructor.

#include "IntermediateTutorial3.h"
 
//-------------------------------------------------------------------------------------
IntermediateTutorial3::IntermediateTutorial3(void):
mCount(0),
mCurrentObject(0),
bLMouseDown(false),
bRMouseDown(false),
mRotateSpeed(0.1f)
{
}
//-------------------------------------------------------------------------------------
IntermediateTutorial3::~IntermediateTutorial3(void)
{
	mSceneMgr->destroyQuery(mRayScnQuery);
}
 
//-------------------------------------------------------------------------------------
void IntermediateTutorial3::createScene(void)
{
	//Scene setup
	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);
 
	//World geometry
	mSceneMgr->setWorldGeometry("terrain.cfg");
 
	//Camera setup
	mCamera->setPosition(40, 100, 580);
	mCamera->pitch(Ogre::Degree(-30));
	mCamera->yaw(Ogre::Degree(-45));
 
	//CEGUI setup
	mGUIRenderer = &CEGUI::OgreRenderer::bootstrapSystem();
 
	//show the CEGUI cursor
	CEGUI::SchemeManager::getSingleton().create((CEGUI::utf8*)"TaharezLook.scheme");
	CEGUI::MouseCursor::getSingleton().setImage("TaharezLook", "MouseArrow");
}
 
void IntermediateTutorial3::chooseSceneManager(void)
{
	//create a scene manager that is meant for handling outdoor scenes
	mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE);
}
 
void IntermediateTutorial3::createFrameListener(void)
{
	//we still want to create the frame listener from the base app
	BaseApplication::createFrameListener();
 
	//but we also want to set up our raySceneQuery after everything has been initialized
	mRayScnQuery = mSceneMgr->createRayQuery(Ogre::Ray());
}
 
bool IntermediateTutorial3::frameRenderingQueued(const Ogre::FrameEvent& arg)
{
	//we want to run everything in the previous frameRenderingQueued call
	//but we also want to do something afterwards, so lets  start off with this
	if(!BaseApplication::frameRenderingQueued(arg))
	{
		return false;
	}
 
	/*
	This next big chunk basically sends a raycast straight down from the camera's position
	It then checks to see if it is under world geometry and if it is we move the camera back up
	*/
	Ogre::Vector3 camPos = mCamera->getPosition();
	Ogre::Ray cameraRay(Ogre::Vector3(camPos.x, 5000.0f, camPos.z), Ogre::Vector3::NEGATIVE_UNIT_Y);
 
	mRayScnQuery->setRay(cameraRay);
 
	Ogre::RaySceneQueryResult& result = mRayScnQuery->execute();
	Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
	if(iter != result.end() && iter->worldFragment)
	{
		Ogre::Real terrainHeight = iter->worldFragment->singleIntersection.y;
 
		if((terrainHeight + 10.0f) > camPos.y)
		{
			mCamera->setPosition(camPos.x, terrainHeight + 10.0f, camPos.z);
		}
	}
	return true;
}
 
bool IntermediateTutorial3::mouseMoved(const OIS::MouseEvent& arg)
{
	//updates CEGUI with mouse movement
	CEGUI::System::getSingleton().injectMouseMove(arg.state.X.rel, arg.state.Y.rel);
 
	//if the left mouse button is held down
	if(bLMouseDown)
	{
		//find the current mouse position
		CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
 
		//create a raycast straight out from the camera at the mouse's location
		Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
		mRayScnQuery->setRay(mouseRay);
 
		Ogre::RaySceneQueryResult& result = mRayScnQuery->execute();
		Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
		//check to see if the mouse is pointing at the world and put our current object at that location
		if(iter != result.end() && iter->worldFragment)
		{
			mCurrentObject->setPosition(iter->worldFragment->singleIntersection);
		}	
	}
	else if(bRMouseDown)	//if the right mouse button is held down, be rotate the camera with the mouse
	{
		mCamera->yaw(Ogre::Degree(-arg.state.X.rel * mRotateSpeed));
		mCamera->pitch(Ogre::Degree(-arg.state.Y.rel * mRotateSpeed));
	}
 
	return true;
}
 
bool IntermediateTutorial3::mousePressed(const OIS::MouseEvent& arg, OIS::MouseButtonID id)
{
	if(id == OIS::MB_Left)
	{
		//find the current mouse position
		CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
 
		//then send a raycast straight out from the camera at the mouse's position
		Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
		mRayScnQuery->setRay(mouseRay);
 
		/*
		This next chunk finds the results of the raycast
		If the mouse is pointing at world geometry we spawn a robot at that position
		*/
		Ogre::RaySceneQueryResult& result = mRayScnQuery->execute();
		Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
		if(iter != result.end() && iter->worldFragment)
		{
			char name[16];
			sprintf(name, "Robot%d", mCount++);
 
			Ogre::Entity* ent = mSceneMgr->createEntity(name, "robot.mesh");
			mCurrentObject = mSceneMgr->getRootSceneNode()->createChildSceneNode(std::string(name) + "Node", iter->worldFragment->singleIntersection);
			mCurrentObject->attachObject(ent);
 
			mCurrentObject->setScale(0.1f, 0.1f, 0.1f);
		}
		bLMouseDown = true;
	}
	else if(id == OIS::MB_Right)	// if the right mouse button is held we hide the mouse cursor for view mode
	{
		CEGUI::MouseCursor::getSingleton().hide();
		bRMouseDown = true;
	}
 
	return true;
}
 
bool IntermediateTutorial3::mouseReleased(const OIS::MouseEvent& arg, OIS::MouseButtonID id)
{
	if(id  == OIS::MB_Left)
	{
		bLMouseDown = false;
	}
	else if(id == OIS::MB_Right)	//when the right mouse is released we then unhide the cursor
	{
		CEGUI::MouseCursor::getSingleton().show();
		bRMouseDown = false;
	}
	return true;
}
 
 
 
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
 
#ifdef __cplusplus
extern "C" {
#endif
 
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
	INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
	int main(int argc, char *argv[])
#endif
	{
		// Create application object
		IntermediateTutorial3 app;
 
		try {
			app.go();
		} catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
			MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
			std::cerr << "An exception has occured: " <<
				e.getFullDescription().c_str() << std::endl;
#endif
		}
 
		return 0;
	}
 
#ifdef __cplusplus
}
#endif

Be sure you can compile and run this code before continuing. It should work the exact same as in 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 allow the user to know which object is currently being manipulated. 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 mousePressed() function, inside the first if statement:

//show that the current object has been deselected by removing the bounding box visual
if(mCurrentObject)
{
	mCurrentObject->showBoundingBox(false);
}

Then add the following code near the end of the mousePressed() function, just before the return statement:

//now we show the bounding box so the user can see that this object is selected
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. Let's make the space key be our mode switching button.

First, we will set up the IntermediateTutorial 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 IntermediateTutorial and add this variable:

bool bRobotMode;        // The current state

Now add this code to the into the IntermediateTutorial3 constructor:

// Set the default state
bRobotMode = true;

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 bRobotMode variable. Locate this code in mousePressed:

char name[16];
sprintf(name, "Robot%d", mCount++);
 
Entity *ent = mSceneMgr->createEntity(name, "robot.mesh");

The replacement should be straight forward. Depending on the bRobotMode state we either put out a Robot or a Ninja, and name it accordingly:

Entity *ent;
char name[16];
 
if (bRobotMode)
{
        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. Go back to IntermediateTutorial3.h and add an override to the keyPressed function like this:

virtual bool keyPressed(const OIS::KeyEvent& arg);

 
Now in IntermediateTutorial3.cpp let's fill in the function. We need to add functionality for the space bar, but we also want to keep the functionality of the BaseApplication. So how do we do this? Easy, it's actually only a few lines:

bool IntermediateTutorial3::keyPressed(const OIS::KeyEvent& arg)
{
	//check and see if the spacebar was hit, and this will switch which mesh is spawned
	if(arg.key == OIS::KC_SPACE)
	{
		bRobotMode = !bRobotMode;
	}
 
	//then we return the base app keyPressed function so that we get all of the functionality
	//and the return value in one line
	return BaseApplication::keyPressed(arg);
}

You see, we check for the space bar and switch the mode we are in. We also call the BaseApplication's keyPressed() function within the return statement, that way we check everything programmed before, plus we get its return value.

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 briefly look at the struct.)

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 that the 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 let's look at an example. Let's say we wanted to print out the results of 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 = mRayScnQuery->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 mousePressed 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 mousePressed() function:

// Set up 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));
mRayScnQuery->setRay(mouseRay);
 
// Execute query
RaySceneQueryResult &result = mRayScnQuery->execute();
RaySceneQueryResult::iterator itr = result.begin();

And change it to this:

// Set up 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));
mRayScnQuery->setRay(mouseRay);
mRayScnQuery->setSortByDistance(true);
 
// Execute query
RaySceneQueryResult &result = mRayScnQuery->execute();
RaySceneQueryResult::iterator iter = result.begin();

Now that we are returning the results in order, we 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 (iter != result.end() && iter->worldFragment)
{
        Entity *ent;
        char name[16];
 
        if (bRobotMode)
        {
                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", iter->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 refer 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 ( iter; iter != result.end(); iter++ )
{

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 (iter->movable && iter->movable->getName().substr(0, 5) != "tile[")
{
        mCurrentObject = iter->movable->getParentSceneNode();
        break;
} // if

Next, we will check to see if the intersection returned a WorldFragment.

else if (iter->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 (bRobotMode)
        {
                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", iter->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 to have a fall-through if 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 frameRenderingQueued and the mouseMoved 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 frameRenderingQueued:

// Perform the scene query
Ogre::RaySceneQueryResult &result = mRayScnQuery->execute();
Ogre::RaySceneQueryResult::iterator itr = result.begin();
 
// Get the results, set the camera height
if (iter != result.end() && iter->worldFragment)
{
        Ogre::Real terrainHeight = iter->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
mRayScnQuery->setSortByDistance(false);
Ogre::RaySceneQueryResult &result = mRayScnQuery->execute();
Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
// Get the results, set the camera height
for (iter; iter != result.end(); iter++)
{
        if (iter->worldFragment)
        {
                Ogre::Real terrainHeight = iter->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 mouseMoved():

mRayScnQuery->setRay(mouseRay);
 
            Ogre::RaySceneQueryResult &result = mRayScnQuery->execute();
            Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
            if (iter != result.end() && iter->worldFragment)
            {
                mCurrentObject->setPosition(iter->worldFragment->singleIntersection);
            }

And replace it with this code:

mRayScnQuery->setRay(mouseRay);
mRayScnQuery->setSortByDistance(false);
 
Ogre::RaySceneQueryResult &result = mRayScnQuery->execute();
Ogre::RaySceneQueryResult::iterator iter = result.begin();
 
for (iter; iter != result.end(); iter++)
{
        if (iter->worldFragment)
        {
                mCurrentObject->setPosition(iter->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(external link) before continuing.

The first thing we are going to do is create the mask values. Go to the very beginning of the IntermediateTutorial3 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 mousePressed:

if (bRobotMode)
{
        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 (bRobotMode)
{
        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 one mode, we can only click and drag objects of the corresponding 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. Find this code in the mousePressed() function:

mRayScnQuery->setSortByDistance(true);

Add this line of code after it:

mRayScnQuery->setQueryMask(bRobotMode ? 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:

mRayScnQuery->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's 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:

mRayScnQuery->setQueryMask(FRIENDLY_CHARACTERS);

If we want the query to return both enemy characters and stationary objects, we would use:

mRayScnQuery->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:

mRayScnQuery->setQueryMask(~FRIENDLY_CHARACTERS);

Which will return everything other than friendly characters. You can also do this for multiple masks:

mRayScnQuery->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:

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

  1. 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 "tile00,2". Even though it's not implemented yet, the TerrainSceneManager supports multiple pages, and if there were more things than just "tile00,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

  1. 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.
  2. Since we are using multiple types of objects now, use the Factory Pattern(external link) to properly create the SceneNodes and Entities.

 

Advanced Exercises

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

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


Alias: Intermediate_Tutorial_3


Contributors to this page: Flateno13 points  , Spacegaier3733 points  , purdyjo389 points  , pidigi43 points  , lingfors11 points  , Latin11 points  and jacmoe111451 points  .
Page last modified on Saturday 24 of September, 2011 14:12:59 GMT by Flateno13 points .


The content on this page is licensed under the terms of the Creative Commons Attribution-ShareAlike License.
As an exception, any source code contributed within the content is released into the Public Domain.