Index: trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 161)
+++ trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 164)
@@ -120,5 +120,6 @@
 mCurrentObjectType(0),
 mApplication(app),
-mUseAnimation(false)
+mUseAnimation(false),
+mDeleteObjects(false)
 {
 	//mInputDevice = PlatformManager::getSingleton().createInputReader();
@@ -206,4 +207,5 @@
 		 
 		 Real val = Math::RangeRandom(0, 360); // random rotation
+
 		 // get results, create a node/entity on the position
 		 mCurrentObject = mTerrainContentGenerator->GenerateSceneObject(
@@ -301,4 +303,11 @@
 	}
 	
+	if (mDeleteObjects)
+	{
+		mApplication->deleteEntityStates();
+		mTerrainContentGenerator->RemoveGeneratedObjects();
+		mDeleteObjects = false;
+	}
+
 	if (mUseAnimation) // update animations
 	{
@@ -1034,8 +1043,8 @@
 		break;
 	case KC_F9:
-		toggleUseAnimation();
+		mUseAnimation = !mUseAnimation;
 		break;
 	case KC_F11:
-		takeScreenShot();
+		takeScreenshot();
 		break;
 	case KC_F12:
@@ -1053,6 +1062,5 @@
 		break;
 	case KC_DELETE:
-		mApplication->deleteEntityStates();
-		mTerrainContentGenerator->RemoveGeneratedObjects();
+		mDeleteObjects = true;
 		break;
 	//KEY_PRESSED(KC_F3, 0.3, writeFrames());
@@ -1223,5 +1231,5 @@
 }
 //-----------------------------------------------------------------------
-void TerrainFrameListener::takeScreenShot()
+void TerrainFrameListener::takeScreenshot()
 {
 	char tmp[20];
@@ -1415,7 +1423,2 @@
 	queryPanel->setHeight(top + border_height);
 }
-//-----------------------------------------------------------------------
-void TerrainFrameListener::toggleUseAnimation()
-{
-	mUseAnimation = !mUseAnimation;
-}
Index: trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp	(revision 161)
+++ trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.cpp	(revision 164)
@@ -24,7 +24,15 @@
 };
 
+const float walk_duration = 10.0f;
+const float wait_duration = 2.0f;
+const float rotate_factor = 0.7f;
+const float move_factor = 0.03;
+
 /***************************************/
 /*      EntityState implementation     */
 /***************************************/
+Vector3 EntityState::msMinPos = Vector3::ZERO;
+Vector3 EntityState::msMaxPos = Vector3::ZERO;
+
 EntityState::EntityState(Entity *ent, State entityState, Real speed):
 mEntity(ent), mState(entityState), mAnimationSpeed(speed)
@@ -53,4 +61,10 @@
 }
 //-----------------------------------------------------------------------
+EntityState::~EntityState()
+{
+	mAnimationState = NULL;
+	mEntity = NULL;
+}
+//-----------------------------------------------------------------------
 Entity *EntityState::GetEntity()
 {
@@ -66,8 +80,14 @@
 {
 	mTimeElapsed -= timeSinceLastFrame * mAnimationSpeed;
+
+	if (!mEntity || !mAnimationState)
+		return;
 	
 	if (mState == MOVING) // toggle between moving (longer) and waiting (short)
 	{
 		SceneNode *parent = mEntity->getParentSceneNode();
+		
+		if (!parent)
+			return;
 
 		if (mTimeElapsed <= 0) // toggle animation state
@@ -76,8 +96,9 @@
 			{
 				SetAnimationState("Walk", true);
-				mTimeElapsed = 10; // walk for mTimeElapsed units
-
-				// choose random direction between zero and two pi
-				Radian rnd = Radian(Math::UnitRandom() * Math::HALF_PI);
+				
+				mTimeElapsed = walk_duration; // walk for mTimeElapsed units
+
+				// choose random rotation
+				Radian rnd = Radian(Math::UnitRandom() * Math::PI * rotate_factor);
 
 				//mEntity->getParentSceneNode()->rotate();
@@ -87,33 +108,34 @@
 			{
 				SetAnimationState("Idle", true);
-				mTimeElapsed = 2; // wait for mTimeElapsed seconds
+				mTimeElapsed = wait_duration; // wait for mTimeElapsed seconds
 			}
 		}
 
-		if (mAnimationState->getAnimationName() == "Walk")
+		if (mAnimationState->getAnimationName() == "Walk") // move forward
 		{
+			// store old position, just in case we get out of bounds
 			Vector3 oldPos = parent->getPosition();
-
-			parent->translate(parent->getLocalAxes(), Vector3(0.03 * mAnimationSpeed, 0, 0));
-
-			// HACK: if out of bounds => go back to idle
+			parent->translate(parent->getLocalAxes(), Vector3(move_factor * mAnimationSpeed, 0, 0));
+
+			// HACK: if out of bounds => reset to old position and set animationstate to idle
 			if (OutOfBounds(parent)) 
 			{
 				parent->setPosition(oldPos);
-				SetAnimationState("Idle);
+				SetAnimationState("Idle", true);
 				
-				mTimeElapsed = 2;
+				mTimeElapsed = wait_duration;
 			}
 		}
 	}
 		
-	if (mAnimationState) // add time to drive animation
-	{
-		mAnimationState->addTime(timeSinceLastFrame * mAnimationSpeed);
-	}
+	// add time to drive animation
+	mAnimationState->addTime(timeSinceLastFrame * mAnimationSpeed);
 }
 //-----------------------------------------------------------------------
 void EntityState::SetAnimationState(String stateStr, bool loop)
 {
+	if (!mEntity)
+		return;
+
 	mAnimationState = mEntity->getAnimationState(stateStr);
 	mAnimationState->setLoop(loop);
@@ -126,8 +148,11 @@
 
 	if ((pos > msMinPos) && (pos < msMaxPos))
-		return true;
-
-	return false;
-}
+		return false;
+
+	return true;
+}
+
+
+
 /*********************************************************/
 /*      TestCullingTerrainApplication implementation     */
@@ -136,5 +161,5 @@
 
 TestCullingTerrainApplication::TestCullingTerrainApplication():
-mTerrainContentGenerator(NULL)
+mTerrainContentGenerator(NULL), mRayQueryExecutor(NULL)
 {
 }
@@ -144,4 +169,5 @@
 	OGRE_DELETE(mTerrainContentGenerator);
 	OGRE_DELETE(mRayQueryExecutor);
+
 	deleteEntityStates();
 }
@@ -151,7 +177,7 @@
 	for (int i = 0; i < (int)mEntityStates.size(); ++i)
 	{
-		delete mEntityStates[i];
-		mEntityStates[i] = NULL;
-	}
+		OGRE_DELETE(mEntityStates[i]);
+	}
+
 	mEntityStates.clear();
 }
@@ -248,6 +274,4 @@
 	mSceneMgr->setWorldGeometry(terrain_cfg);
 	
-	// ray query executor
-	mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
 
 	//-- CEGUI setup
@@ -274,4 +298,10 @@
 	mSceneMgr->_renderScene(mCamera, mWindow->getViewport(0), true);
 
+	// ray query executor: needed to clamp to terrain
+	mRayQueryExecutor = new RayQueryExecutor(mSceneMgr);
+
+	mTerrainMinPos = EntityState::msMinPos = Vector3(0, 0, 0);
+	mTerrainMaxPos = EntityState::msMaxPos = Vector3(3000, 5000, 3000);
+
 	mTerrainContentGenerator = new TerrainContentGenerator(mSceneMgr);
 	
@@ -280,6 +310,7 @@
 	{
 		// to provide much occlusion,
-		// height is restricted to 50 => no objects appear on peaks
-		mTerrainContentGenerator->SetMaxPos(Vector3(3000.0f, 50.0f, 3000.0f));
+		// height is restricted to 50 => no objects are created on peaks
+		mTerrainContentGenerator->SetMinPos(Vector3(mTerrainMinPos));
+		mTerrainContentGenerator->SetMaxPos(Vector3(mTerrainMaxPos.x, 50.0f, mTerrainMaxPos.z));
 		mTerrainContentGenerator->SetOffset(0);
 
@@ -288,7 +319,7 @@
 	}
 
-	// no limitations needed anymore: the user can set 
-	// objects also on peaks of terrain
-	mTerrainContentGenerator->SetMaxPos(Vector3(3000.0f, 5000.0f, 3000.0f));
+	// no limitations anymore => it is possible for the user to put single 
+	// objects on peaks of the terrain (only few, not relevant for occlusion)
+	mTerrainContentGenerator->SetMaxPos(mTerrainMaxPos);
 }
 //-----------------------------------------------------------------------
@@ -314,5 +345,5 @@
 	for (int i = 0; i < (int)mEntityStates.size(); ++i)
 	{
-		SceneNode *sm = mEntityStates[i]->GetEntity()->getParentSceneNode();
+		SceneNode *sn = mEntityStates[i]->GetEntity()->getParentSceneNode();
 
 		mEntityStates[i]->update(timeSinceLastFrame);
@@ -320,6 +351,5 @@
 		if (mEntityStates[i]->GetState() == EntityState::MOVING)
 		{
-			Clamp2Terrain(sn, 0);
-			//sm->setNodeVisible(false);
+			Clamp2Terrain(sn, 0); //sn->setNodeVisible(false);
 		}
 	}
Index: trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.h
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.h	(revision 161)
+++ trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.h	(revision 164)
@@ -112,5 +112,5 @@
 	void toggleShowShadows();
 	void toggleDisplayCameraDetails();
-	void takeScreenShot();
+	void takeScreenshot();
 	void nextSceneDetailLevel();
 	void nextFilter();
@@ -125,5 +125,4 @@
 	void toggleShowViz();
 	void toggleRecord();
-	void toggleUseAnimation();
 
 	/** Applies visibility query. Collects the visible objects 
@@ -241,4 +240,5 @@
 	float mMoveScale;
     Degree mRotScale;
+
     // just to stop toggles flipping too fast
     Real mTimeDelay;
@@ -272,4 +272,6 @@
 	int mCurrentObjectType;
 
+	bool mDeleteObjects;
+
 	TestCullingTerrainApplication *mApplication;
 };
Index: trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h
===================================================================
--- trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h	(revision 161)
+++ trunk/VUT/work/TestCullingTerrain/TestCullingTerrainApplication.h	(revision 164)
@@ -34,5 +34,5 @@
 
 	EntityState(Entity *ent, State entityState, Real speed);
-
+	~EntityState();
 	/** Update the entity state.
 	*/
@@ -46,4 +46,9 @@
 	*/
 	EntityState::State GetState();
+
+	static bool OutOfBounds(SceneNode *node);
+
+	static Vector3 msMinPos;
+	static Vector3 msMaxPos;
 
 protected:
@@ -136,4 +141,6 @@
 	RayQueryExecutor *mRayQueryExecutor;
 
+	Vector3 mTerrainMinPos;
+	Vector3 mTerrainMaxPos;
 private:
 	void chooseSceneManager(void);
Index: trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h
===================================================================
--- trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 159)
+++ trunk/VUT/Ogre/include/OgreVisibilityTerrainSceneManager.h	(revision 164)
@@ -33,13 +33,13 @@
 	*/
 	
-	virtual bool setOption( const String &, const void * );
+	virtual bool setOption(const String &, const void *);
 	/** Gets the given option for the Scene VisibilityManager.
 	    @remarks
 		See setOption
 	*/
-	virtual bool getOption( const String &, void * );
+	virtual bool getOption(const String &, void *);
 
-	bool getOptionValues( const String & key, StringVector &refValueList );
-	bool getOptionKeys( StringVector &refKeys );
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
 
 	/** Sets the visibility manager.
@@ -75,5 +75,5 @@
 	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
 	*/
-	//Entity* createEntity(const String& entityName, const String& meshName);
+	Entity* createEntity(const String& entityName, const String& meshName);
 
 	/** Returns pointer to visibility manager.
@@ -85,4 +85,6 @@
 	OctreeHierarchyInterface *GetHierarchyInterface();
 
+	/** Inherited from scene manager. Neccesary to draw terrain properly.
+	*/
 	void endFrame();
 
Index: trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 160)
+++ trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 164)
@@ -37,7 +37,5 @@
 	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
 	
-	//mDisplayNodes = true;
-	//mShowBoundingBoxes = true;
-	//mShowBoxes = true;
+	//mDisplayNodes = true;//mShowBoundingBoxes = true;//mShowBoxes = true;
 
 	// TODO: set maxdepth to reasonable value
@@ -120,5 +118,5 @@
 	if (mRenderNodesForViz || mRenderNodesContentForViz)
 	{
-		// change node material so it is better suited for visualization
+		// HACK: change node material so it is better suited for visualization
 		MaterialPtr nodeMat = MaterialManager::getSingleton().getByName("Core/NodeMaterial");
 		nodeMat->setAmbient(1, 1, 0);
@@ -130,7 +128,10 @@
 			if (mRenderNodesForViz)
 			{
-				if (((*it)->numAttachedObjects() > 0) && ((*it)->numChildren() == 0)
-					&& (*it)->getAttachedObject(0)->getMovableType() == "Entity")
-				getRenderQueue()->addRenderable((*it));
+				// render the leaf nodes
+				if (((*it)->numAttachedObjects() > 0) && ((*it)->numChildren() == 0) && 
+					 (*it)->getAttachedObject(0)->getMovableType() == "Entity")
+				{
+					getRenderQueue()->addRenderable((*it));
+				}
 
 				// addbounding boxes instead of node itself
@@ -508,5 +509,5 @@
 	}
 
-	// --- item buffer
+	//-- item buffer
 
     // Iterate through priorities
@@ -743,5 +744,4 @@
 */
 //-----------------------------------------------------------------------
-/*
 Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
 													const String& meshName)
@@ -752,4 +752,6 @@
 	{
 		ent->getSubEntity(i)->setId(mCurrentEntityId);
+		ent->getSubEntity(i)->setId((41 << 16) + (4 << 8) + 60);
+		//ent->getSubEntity(i)->setId((2 << 16) + (4 << 8) + 60);
 	}
 
@@ -759,4 +761,3 @@
 	return ent;
 }
-*/
 } // namespace Ogre
Index: trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp	(revision 159)
+++ trunk/VUT/Ogre/src/OgreVisibilityOctreeSceneManager.cpp	(revision 164)
@@ -739,6 +739,5 @@
 }
 */
-//-----------------------------------------------------------------------
-/*
+/*//-----------------------------------------------------------------------
 Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
 													const String& meshName)
Index: trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 159)
+++ trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 164)
@@ -49,5 +49,5 @@
 	
 	// ---- capture visibility from all 6 directions
-	for (int i=0; i < 6; i++)	
+	for (int dir=0; dir < 6; dir++)	
 	{
 		sign *= -1;
@@ -60,5 +60,5 @@
 
 		// prevent from initialising geometry / node array again
-		if (i > 0)
+		if (dir > 0)
 		{
 			mWasInitialised = true;
@@ -70,8 +70,8 @@
 
 		// permute directions
-		Vector3 dir(0,0,0);
-		dir[i/2] = sign;
+		Vector3 direction(0,0,0);
+		direction[dir/2] = sign;
 
-		cam->setDirection(dir);
+		cam->setDirection(direction);
 	}
 	
Index: trunk/VUT/Ogre/src/OgreTerrainContentGenerator.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreTerrainContentGenerator.cpp	(revision 161)
+++ trunk/VUT/Ogre/src/OgreTerrainContentGenerator.cpp	(revision 164)
@@ -16,5 +16,5 @@
 RayQueryExecutor::~RayQueryExecutor()
 {
-	delete mRaySceneQuery;
+	OGRE_DELETE(mRaySceneQuery);
 }
 //-----------------------------------------------------------------------
Index: trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp
===================================================================
--- trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 159)
+++ trunk/VUT/Ogre/src/OgreItemBufferQueryManager.cpp	(revision 164)
@@ -6,6 +6,8 @@
 
 namespace Ogre {
+
 //----------------------------------------------------------------------- 
-ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp,
+ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, 
+											   Viewport *vp,
 											   const bool renderPatches):
 PlatformQueryManager(hierarchyInterface, vp), mRenderPatchesForItemBuffer(renderPatches)
@@ -13,5 +15,7 @@
 }
 //-----------------------------------------------------------------------
-bool ItemBufferQueryManager::ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine)
+bool ItemBufferQueryManager::ShootRay(const Ray &ray, 
+									  std::vector<Mesh *> *visibleMeshes, 
+									  bool isGlobalLine)
 {
     // run OGRE ray shooting query
@@ -50,8 +54,11 @@
 	ColourValue bg = mViewport->getBackgroundColour();
 	mViewport->setBackgroundColour(ColourValue(0, 0, 0, 0));
+	pfHierarchyInterface->GetRenderSystem()->clearFrameBuffer(FBT_COLOUR | FBT_DEPTH);
 
+	//-- render item buffer
+	sm->_renderScene(pCam, mViewport, false);
+    //mViewport->getTarget()->update();
 
-	// --- render item buffer
-	pfHierarchyInterface->GetSceneManager()->_renderScene(pCam, mViewport, false);
+//for(int j=0; j<10000000; j++)	printf("wait");
 
 
@@ -64,14 +71,20 @@
 
 	int n = mRenderPatchesForItemBuffer ? (int)visiblePatches->size() : (int)visibleGeometry->size();
-	
+
+	std::stringstream d; d << "dimx: " << dimx << ", dimy: " << dimy;
+	LogManager::getSingleton().logMessage(d.str());
+
 	// loop through frame buffer & collect visible pixels
 	for (int idx = 0; idx < dimy * dimx * 3; idx += 3)
 	{
-		// -- decode color code to receive id
+		//-- decode color code to receive id
 		int id = buf[idx] << 16;
 		id += buf[idx + 1] << 8;
 		id += buf[idx + 2];
 
-		// if valid id <= add visibility (id values start at 1
+		std::stringstream d; d << "myid: " << (int)buf[idx] << " " << (int)buf[idx + 1] << " " << (int)buf[idx + 2];
+		LogManager::getSingleton().logMessage(d.str());
+
+		// if valid id <= add visibility (id values start at 1)
 		if ((id > 0) && (id < n))
 		{
@@ -144,4 +157,6 @@
 				
 			subEnt->setId(id);
+			subEnt->setId((41 << 16) + (4 << 8) + 60);
+			//subEnt->setId((2 << 16) + (4 << 8) + 60);
 		}
 			
