Intermediate Tutorial 3: Mouse Picking (3D Object Selection) and SceneQuery Masks

Original version by Clay Culver

Initial C# Port by DigitalCyborg

Note: This was written for OgreDotNet 1.2 and is known to compile against it.
Any problems you encounter while working with this tutorial should be posted to the OgreDotNet Forum.

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.

Prerequisites

This tutorial will assume that you have gone through the previous tutorial. We will also be using C# Enumerators 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. For all of the mouse events, I have created wrapper functions to handle their functionality. 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. Here is the code we are starting from:

using System;
 using System.Drawing;
 using System.Text;
 //
 using Math3D;
 using OgreDotNet;
 using OgreDotNet.Cegui;
 using CeguiDotNet;
 //
 namespace OgreDotNetTutorials
 {
    class IntermediateTutorial3 : ExampleApplication
    {
        protected RaySceneQuery mRaySceneQuery = null;      // The ray scene query pointer
        protected bool mLMouseDown, mRMouseDown = false;    // True if the mouse buttons are down
        protected int mCount = 0;                           // The number of robots on the screen
        protected SceneNode mCurrentObject = null;          // The newly created object
 
        protected OgreCEGUIRenderer mGUIRenderer = null;    //CEGUI Renderer
        protected GuiSystem mGUISystem = null;              //GUISystem
        protected float mouseX, mouseY;
     
        protected override void MouseClick(MouseEvent e)
        {
            //base.MouseClick(e);
        }
 
        protected virtual void onLeftDragged(MouseMotionEvent e)
        {
            mouseX += e.DeltaX;
            mouseY += e.DeltaY;
            Ray mouseRay = mCamera.GetCameraToViewportRay(mouseX, mouseY);
            mRaySceneQuery.setRay(mouseRay);
 
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            if ((itr != null) && itr.MoveNext())
            {
                mCurrentObject.SetPosition(itr.Current.getWorldFragment().getSingleIntersection());
            }
            return;
        }
 
        protected virtual void onRightDragged(MouseMotionEvent e)
        {
            mCamera.Yaw(new Radian(-e.DeltaX * mRotateScale));
            mCamera.Pitch(new Radian(-e.DeltaY * mRotateScale));
            return;
        }
 
        protected override void MouseDragged(MouseMotionEvent e)
        {
            MouseMotion(e);
            // If we are dragging the left mouse button.
            if (mLMouseDown)
            {
                onLeftDragged(e);
            } // if mLMouseDown
 
            // If we are dragging the right mouse button.
            else if (mRMouseDown)
            {
                onRightDragged(e);
            } // else if mRMouseDown
        }
 
        protected override void MouseMotion(MouseMotionEvent e)
        {
            // Update CEGUI with the mouse motion
            GuiSystem.Instance.InjectMouseMove(e.DeltaX * mRenderWindow.Width,
                e.DeltaY * mRenderWindow.Height);
        }
 
        protected virtual void onLeftPressed(MouseEvent e)
        {
            // Save mouse position
            mouseX = e.X; mouseY = e.Y;
            
            // Setup the ray scene query
            Ray mouseRay = mCamera.GetCameraToViewportRay(mouseX, mouseY);
            mRaySceneQuery.setRay(mouseRay);
 
            // Execute query
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            // Get results, create a node/entity on the position
            if (itr != null && itr.MoveNext())
            {
                Entity ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                mCurrentObject = mSceneManager.GetRootSceneNode().CreateChildSceneNode("RobotNode" + mCount.ToString(),
                    itr.Current.getWorldFragment().getSingleIntersection());
                mCount++;
                mCurrentObject.AttachObject(ent);
                mCurrentObject.SetScale(0.1f, 0.1f, 0.1f);
            } // 
 
            mLMouseDown = true;
            return;
        }
 
        protected virtual void onRightPressed(MouseEvent e)
        {
            mRMouseDown = true;
            CeguiDotNet.MouseCursor.getSingleton().hide();
            return;
        }
 
        protected virtual void onLeftReleased(MouseEvent e)
        {
            mLMouseDown = false;
            return;
        }
 
        protected virtual void onRightReleased(MouseEvent e)
        {
            mRMouseDown = false;
            CeguiDotNet.MouseCursor.getSingleton().show();
            return;
        }
 
        protected override void MousePressed(MouseEvent e)
        {
            switch (e.ButtonID)
            {
                case 16:
                    onLeftPressed(e);
                    break;
                case 32:
                    onRightPressed(e);
                    break;
                default:
                    break;
            }
        }
 
        protected override void MouseReleased(MouseEvent e)
        {
            switch (e.ButtonID)
            {
                case 16:
                    onLeftReleased(e);
                    break;
                case 32:
                    onRightReleased(e);
                    break;
                default:
                    break;
            }
        }
 
        protected override bool FrameStarted(FrameEvent e)
        {
            if (!base.FrameStarted(e))
                return false;
 
            // Setup the scene query
            Math3D.Vector3 camPos = mCamera.GetPosition();
            Ray cameraRay = new Ray(new Math3D.Vector3(camPos.x, 5000.0f, camPos.z),
                Math3D.Vector3.NegativeUnitY);
            mRaySceneQuery.setRay(cameraRay);
 
            // Perform the scene query;
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            // Get the results, set the camera height
            if ((itr != null) && itr.MoveNext())
            {
                float terrainHeight = itr.Current.getWorldFragment().getSingleIntersection().y;
 
                if ((terrainHeight + 10.0f) > camPos.y)
                    mCamera.SetPosition(camPos.x, terrainHeight + 10.0f, camPos.z);
            }
            return true;
        }
 
        protected override bool FrameEnded(FrameEvent e)
        {
            return base.FrameEnded(e);
        }
 
        protected override void CreateSceneManager()
        {
            mSceneManager = mRoot.CreateSceneManager((ushort)SceneType.ExteriorClose);
        }
 
        protected override void CreateScene()
        {
            // Set ambient light
            mSceneManager.SetAmbientLight(Color.FromArgb(127, 127, 127));
            mSceneManager.SetSkyDome(true, "Examples/CloudySky", 5, 8);
 
            // World geometry
            mSceneManager.SetWorldGeometry("terrain.cfg");
 
            // Set camera look point           
            mCamera.SetPosition(new Math3D.Vector3(40, 100, 280));
            mCamera.Pitch(new Radian(new Degree(-30)));
            mCamera.Yaw(new Radian(new Degree(-45)));
 
            // CEGUI setup
            mGUIRenderer = new OgreCEGUIRenderer(base.mRenderWindow,
                (byte)RenderQueueGroupID.RENDER_QUEUE_OVERLAY, false, 3000, mSceneManager);
            mGUIRenderer.Initialise();
            mGUISystem = GuiSystem.CreateGuiSystemSpecial(mGUIRenderer);
 
            //Mouse cursor
            CeguiDotNet.SchemeManager.getSingleton().LoadScheme("TaharezLook.scheme");
            CeguiDotNet.MouseCursor.getSingleton().setImage("TaharezLook", "MouseArrow");
        }
 
        protected override void CreateEventHandler()
        {
            base.CreateEventHandler();
            mRaySceneQuery = mSceneManager.CreateRayQuery(new Ray());
        }
 
        public override void Dispose()
        {
            mRaySceneQuery.Dispose();
            mGUISystem.Dispose();
            mGUIRenderer.Dispose();
            base.Dispose();
        }
 
        [MTAThread]
        static void Main(string[] args)
        {
            using (IntermediateTutorial3 app = new IntermediateTutorial3())
                app.Start();
        }
    }
 }

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 he'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 != null)
            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 != null)
            mCurrentObject.ShowBoundingBox(false);

Now the mCurrentObject is always highlighted on the screen. cool!

Adding Ninjas

Whoa. 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 variables section of the class and add this variable:

bool mRobotMode = true;            // The current state

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:

Entity ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "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;
                if (mRobotMode)
                {
                    ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                }
                else
                {
                    ent = mSceneManager.CreateEntity("Ninja" + mCount.ToString(), "ninja.mesh");
                }

Now, we'll need to add a couple more variable to our variables section:

bool mToggleObjects = false;
        float mTimeUntilNextToggle = 1.0f;

Next, we'll check the mTimeUntilNextToggle variable and set the mToggleObjects variable if we've waited long enough between toggling between Robots & Ninjas. update KeyClicked to bind the spacebar to change states:

base.KeyClicked(e);
            switch (e.KeyCode)
            {
                case KeyCode.Space:
                    if(mTimeUntilNextToggle <= 0)
                        mToggleObjects = true;
                    break;
            }

The only thing left to do is update the mTimeUntilNextToggle variable and change states . Find the following code in FrameStarted:

if (!base.FrameStarted(e))
                return false;

and add this code after it:

mTimeUntilNextToggle -= mDeltaTime;
 
            // Swap modes
            if (mToggleObjects)
            {
                mToggleObjects = false;
                mRobotMode = !mRobotMode;
                mTimeUntilNextToggle = 1.0f;
                mRenderWindow.SetDebugText((mRobotMode ? "Robot" : "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 Enumerator 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.)
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:
And change it to this:
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:
You'll notice that I snuck in a little extra code to scale the Ninja Object since it was about twice the size of the Robot.
Now, 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 while loop instead of an if statement:
First we will check if the first intersection is a MovableObject, but there is a catch. 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 while loop.

//ok.. what we need to do, is iterate through the list and see if there
            //are any objects that aren't tile.
            //if there are.. this is the one to MOVE!!
            // Get results, create a node/entity on the position
            bool placeObject = true;
            while(itr.MoveNext())
            {
                if ((itr.Current.movable != null) &&
                    (itr.Current.movable.GetName().Substring(0,4) != "tile"))
                {
                    //System.Console.WriteLine("movable Object {0}", itr.Current.movable.GetName());
                    mCurrentObject = itr.Current.movable.GetParentSceneNode();
                    placeObject = false;
                    break;
                }
            }
            
            if(placeObject)
            {
                itr.Reset();
                itr.MoveNext();
                Entity ent;
                if (mRobotMode)
                {
                    ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                }
                else
                {
                    ent = mSceneManager.CreateEntity("Ninja" + mCount.ToString(), "ninja.mesh");
                }
                mCurrentObject = mSceneManager.GetRootSceneNode().CreateChildSceneNode("ObjectNode" + mCount.ToString(),
                    itr.Current.getWorldFragment().getSingleIntersection());
                mCount++;
                mCurrentObject.AttachObject(ent);
                if (mRobotMode)
                    mCurrentObject.SetScale(0.1f, 0.1f, 0.1f);
                else
                    mCurrentObject.SetScale(0.05f, 0.05f, 0.05f);
            }

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 can drag it around. 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 fallthrough 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 onLeftDragged function. Find this section of code in the onLeftDraggedFunction:

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

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 
        } // 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 class and add this:

enum QueryFlags
    {
        NINJA_MASK = 0x1,
        ROBOT_MASK = 0x2
    };

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)
                {
                    ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                }
                else
                {
                    ent = mSceneManager.CreateEntity("Ninja" + mCount.ToString(), "ninja.mesh");
                }

We will add two lines to set the mask on both of them:

if (mRobotMode)
                {
                    ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                    ent.SetQueryFlags((uint)QueryFlags.ROBOT_MASK);
                }
                else
                {
                    ent = mSceneManager.CreateEntity("Ninja" + mCount.ToString(), "ninja.mesh");
                    ent.SetQueryFlags((uint)QueryFlags.NINJA_MASK);
                }

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 ? (uint)QueryFlags.ROBOT_MASK : (uint)QueryFlags.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.

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.

Note that these are all powers of 2. 0x1 (1), 0x2 (2), 0x4 (4), 0x8 (8), 0x10 (16), 0x20 (32) ...

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( (uint)QueryFlags.FRIENDLY_CHARACTERS );

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

mRaySceneQuery.SetQueryMask( (uint)QueryFlags.ENEMY_CHARACTERS | (uint)QueryFlags.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 (uint)QueryFlags.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( (uint) ~QueryFlags.FRIENDLY_CHARACTERS );

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

mRaySceneQuery->SetQueryMask( (uint) ~( QueryFlags.FRIENDLY_CHARACTERS | QueryFlags.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

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

COMPLETE TUTORIAL CODE BEFORE EXERCISES

using System;
 using System.Drawing;
 using System.Text;
 using Math3D;
 using OgreDotNet;
 using OgreDotNet.Cegui;
 using CeguiDotNet;
 
 namespace DigitalCyborg
 {
    class IntermediateTutorial3 : ExampleApplication
    {
        protected RaySceneQuery mRaySceneQuery = null;      // The ray scene query pointer
        protected bool mLMouseDown, mRMouseDown = false;    // True if the mouse buttons are down
        protected int mCount = 0;                           // The number of robots on the screen
        protected SceneNode mCurrentObject = null;          // The newly created object
 
        protected OgreCEGUIRenderer mGUIRenderer = null;    //CEGUI Renderer
        protected GuiSystem mGUISystem = null;              //GUISystem
 
        bool mRobotMode = true;
        bool mToggleObjects = false;
        float mTimeUntilNextToggle = 1.0f;
 
        float mouseX, mouseY;
 
        enum QueryFlags
        {
            NINJA_MASK = 0x1,
            ROBOT_MASK = 0x2
        };
 
        protected override void KeyClicked(KeyEvent e)
        {
            base.KeyClicked(e);
            switch (e.KeyCode)
            {
                case KeyCode.Space:
                    if(mTimeUntilNextToggle <= 0)
                        mToggleObjects = true;
                    break;
            }
        }
 
        protected override void MouseClick(MouseEvent e)
        {
            //base.MouseClick(e);
        }
 
        protected virtual void onLeftDragged(MouseMotionEvent e)
        {
            mouseX += e.DeltaX;
            mouseY += e.DeltaY;
 
            Ray mouseRay = mCamera.GetCameraToViewportRay(mouseX,mouseY);
            mRaySceneQuery.setRay(mouseRay);
 
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            if ((itr != null) && itr.MoveNext())
            {
                mCurrentObject.SetPosition(itr.Current.getWorldFragment().getSingleIntersection());
            }
            return;
        }
 
        protected virtual void onRightDragged(MouseMotionEvent e)
        {
            mCamera.Yaw(new Radian(-e.DeltaX * mRotateScale));
            mCamera.Pitch(new Radian(-e.DeltaY * mRotateScale));
            return;
        }
 
        protected override void MouseDragged(MouseMotionEvent e)
        {
            MouseMotion(e);
            // If we are dragging the left mouse button.
            if (mLMouseDown)
            {
                onLeftDragged(e);
            } // if mLMouseDown
 
            // If we are dragging the right mouse button.
            else if (mRMouseDown)
            {
                onRightDragged(e);
            } // else if mRMouseDown
        }
 
        protected override void MouseMotion(MouseMotionEvent e)
        {
            // Update CEGUI with the mouse motion
            GuiSystem.Instance.InjectMouseMove(e.DeltaX * mRenderWindow.Width,
                e.DeltaY * mRenderWindow.Height);
        }
 
        protected virtual void onLeftPressed(MouseEvent e)
        {
            mouseX = e.X;
            mouseY = e.Y;
            // Turn off bounding box.
            if ( mCurrentObject != null)
                mCurrentObject.ShowBoundingBox(false);
 
            // Setup the ray scene query
            Ray mouseRay = mCamera.GetCameraToViewportRay(mouseX,mouseY);
            mRaySceneQuery.setRay(mouseRay);
            //mRaySceneQuery.setSortByDistance(true);
            mRaySceneQuery.setQueryMask(mRobotMode ? 
                (uint)QueryFlags.ROBOT_MASK :
                (uint)QueryFlags.NINJA_MASK);
            
            // Execute query
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            //ok.. what we need to do, is iterate through the list and see if there
            //are any objects that aren't tile.
            //if there are.. this is the one to MOVE!!
            // Get results, create a node/entity on the position
            bool placeObject = true;
            while(itr.MoveNext())
            {
                if ((itr.Current.movable != null) &&
                    (itr.Current.movable.GetName().Substring(0,4) != "tile"))
                //itr->movable && itr->movable->getName( ) != "tile[0][0,2]"
                {
                    System.Console.WriteLine("movable Object {0}", itr.Current.movable.GetName());
                    mCurrentObject = itr.Current.movable.GetParentSceneNode();
                    placeObject = false;
                    break;
                }
            }
            
            if(placeObject)
            {
                itr.Reset();
                itr.MoveNext();
                Entity ent;
                if (mRobotMode)
                {
                    ent = mSceneManager.CreateEntity("Robot" + mCount.ToString(), "robot.mesh");
                    ent.SetQueryFlags((uint)QueryFlags.ROBOT_MASK);
                }
                else
                {
                    ent = mSceneManager.CreateEntity("Ninja" + mCount.ToString(), "ninja.mesh");
                    ent.SetQueryFlags((uint)QueryFlags.NINJA_MASK);
                }
                mCurrentObject = mSceneManager.GetRootSceneNode().CreateChildSceneNode("ObjectNode" + mCount.ToString(),
                    itr.Current.getWorldFragment().getSingleIntersection());
                mCount++;
                mCurrentObject.AttachObject(ent);
                if (mRobotMode)
                    mCurrentObject.SetScale(0.1f, 0.1f, 0.1f);
                else
                    mCurrentObject.SetScale(0.05f, 0.05f, 0.05f);
            }
            
            // Show the bounding box to highlight the selected object
            if (mCurrentObject != null)
                mCurrentObject.ShowBoundingBox(true);
 
            mLMouseDown = true;
            return;
        }
 
        protected virtual void onRightPressed(MouseEvent e)
        {
            mRMouseDown = true;
            CeguiDotNet.MouseCursor.getSingleton().hide();
            return;
        }
 
        protected virtual void onLeftReleased(MouseEvent e)
        {
            mLMouseDown = false;
            return;
        }
 
        protected virtual void onRightReleased(MouseEvent e)
        {
            mRMouseDown = false;
            CeguiDotNet.MouseCursor.getSingleton().show();
            return;
        }
 
        protected override void MousePressed(MouseEvent e)
        {
            switch (e.ButtonID)
            {
                case 16:
                    onLeftPressed(e);
                    break;
                case 32:
                    onRightPressed(e);
                    break;
                default:
                    break;
            }
        }
 
        protected override void MouseReleased(MouseEvent e)
        {
            switch (e.ButtonID)
            {
                case 16:
                    onLeftReleased(e);
                    break;
                case 32:
                    onRightReleased(e);
                    break;
                default:
                    break;
            }
        }
 
        protected override bool FrameStarted(FrameEvent e)
        {
            if (!base.FrameStarted(e))
                return false;
 
            mTimeUntilNextToggle -= mDeltaTime;
 
            // Swap modes
            if (mToggleObjects)
            {
                mToggleObjects = false;
                mRobotMode = !mRobotMode;
                mTimeUntilNextToggle = 1.0f;
                mRenderWindow.SetDebugText((mRobotMode ? "Robot" : "Ninja") + " Mode Enabled - Press Space to Toggle");
            }
 
            // Setup the scene query
            Math3D.Vector3 camPos = mCamera.GetPosition();
            Ray cameraRay = new Ray(new Math3D.Vector3(camPos.x, 5000.0f, camPos.z),
                Math3D.Vector3.NegativeUnitY);
            mRaySceneQuery.setRay(cameraRay);
 
            // Perform the scene query;
            RaySceneQueryResult result = mRaySceneQuery.execute();
            RaySceneQueryResult.RaySceneQueryResultEnumerator itr = result.GetEnumerator();
 
            // Get the results, set the camera height
            if ((itr != null) && itr.MoveNext())
            {
                float terrainHeight = itr.Current.getWorldFragment().getSingleIntersection().y;
 
                if ((terrainHeight + 10.0f) > camPos.y)
                    mCamera.SetPosition(camPos.x, terrainHeight + 10.0f, camPos.z);
            }
            return true;
        }
 
        protected override bool FrameEnded(FrameEvent e)
        {
            return base.FrameEnded(e);
        }
 
        protected override void CreateSceneManager()
        {
            mSceneManager = mRoot.CreateSceneManager((ushort)SceneType.ExteriorClose);
            mRenderWindow.SetDebugText("Robot Mode Enabled - Press Space to Toggle");
        }
 
        protected override void CreateScene()
        {
            // Set ambient light
            mSceneManager.SetAmbientLight(Color.FromArgb(127, 127, 127));
            mSceneManager.SetSkyDome(true, "Examples/CloudySky", 5, 8);
 
            // World geometry
            mSceneManager.SetWorldGeometry("terrain.cfg");
 
            // Set camera look point           
            mCamera.SetPosition(new Math3D.Vector3(40, 100, 280));
            mCamera.Pitch(new Radian(new Degree(-30)));
            mCamera.Yaw(new Radian(new Degree(-45)));
 
            // CEGUI setup
            mGUIRenderer = new OgreCEGUIRenderer(base.mRenderWindow,
                (byte)RenderQueueGroupID.RENDER_QUEUE_OVERLAY, false, 3000, mSceneManager);
            mGUIRenderer.Initialise();
            mGUISystem = GuiSystem.CreateGuiSystemSpecial(mGUIRenderer);
 
            //Mouse cursor
            CeguiDotNet.SchemeManager.getSingleton().LoadScheme("TaharezLook.scheme");
            CeguiDotNet.MouseCursor.getSingleton().setImage("TaharezLook", "MouseArrow");
        }
 
        protected override void CreateEventHandler()
        {
            base.CreateEventHandler();
            mRaySceneQuery = mSceneManager.CreateRayQuery(new Ray());
        }
 
        public override void Dispose()
        {
            mRaySceneQuery.Dispose();
            mGUISystem.Dispose();
            mGUIRenderer.Dispose();
            base.Dispose();
        }
 
        [MTAThread]
        static void Main(string[] args)
        {
            using (IntermediateTutorial3 app = new IntermediateTutorial3())
                app.Start();
        }
    }
 }