Index: /trunk/VUT/GtpVisibility/include/VisibilityInfo.h
===================================================================
--- /trunk/VUT/GtpVisibility/include/VisibilityInfo.h	(revision 135)
+++ /trunk/VUT/GtpVisibility/include/VisibilityInfo.h	(revision 141)
@@ -17,6 +17,11 @@
 
 	float GetVisibility() const {return mVisibility;}
+	void SetVisibility(float vis) { mVisibility = vis;}
+	bool operator<(const NodeInfo& rhs) const {return mNode < rhs.mNode;}
+	//bool operator>(const NodeInfo& rhs) const {return mNode > rhs.mNode;}
+	//bool operator==(const NodeInfo& rhs) const {return mNode == rhs.mNode;}
 
 protected:
+
     /** pointer to the scene node */
     HierarchyNode *mNode;
@@ -35,6 +40,12 @@
 
 	float GetVisibility() const {return mVisibility;}
+	void SetVisibility(float vis) { mVisibility = vis;}
 
+	bool operator<(const MeshInfo& rhs) const {return mMesh < rhs.mMesh;}
+	//bool operator>(const MeshInfo& rhs) const {return mMesh > rhs.mMesh;}
+	//bool operator==(const MeshInfo& rhs) const {return mMesh == rhs.mMesh;}
+	
 protected:
+
     /** Pointer to the mesh.
 	*/
@@ -48,5 +59,6 @@
   
 //TODO: this define shall be replaced by template typedef
-#define InfoContainer std::vector
+//#define InfoContainer std::vector
+#define InfoContainer std::set
 };
 
Index: /trunk/VUT/GtpVisibility/src/DummyQueryManager.cpp
===================================================================
--- /trunk/VUT/GtpVisibility/src/DummyQueryManager.cpp	(revision 65)
+++ /trunk/VUT/GtpVisibility/src/DummyQueryManager.cpp	(revision 141)
@@ -14,5 +14,5 @@
 					     )
   {
-    visibleNodes->push_back(NodeInfo(mHierarchyInterface->GetSceneRoot(), 1.0f));
+	  visibleNodes->insert(NodeInfo(mHierarchyInterface->GetSceneRoot(), 1.0f));
     
 //      HierarchyInterface::MeshIterator *mi =
@@ -33,5 +33,5 @@
 						)
   {
-    visibleNodes->push_back(NodeInfo(mHierarchyInterface->GetSceneRoot(), 1.0f));
+	  visibleNodes->insert(NodeInfo(mHierarchyInterface->GetSceneRoot(), 1.0f));
     
 //      HierarchyInterface::MeshIterator *mi =
Index: /trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp
===================================================================
--- /trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 140)
+++ /trunk/VUT/work/TestCullingTerrain/TerrainFrameListener.cpp	(revision 141)
@@ -373,21 +373,28 @@
 	float averageGeometryVis = 0;
 
-	for (int i=0; i < visibleGeometry.size(); ++i)
-	{
-		averageGeometryVis += visibleGeometry[i].GetVisibility();
-
-		std::stringstream d; d << "Geometry visibility: " << visibleGeometry[i].GetVisibility();
+	InfoContainer<GtpVisibility::MeshInfo>::iterator geomIt, geomIt_end = visibleGeometry.end();
+
+	for (geomIt = visibleGeometry.begin(); geomIt != geomIt_end; ++geomIt)
+	{
+		averageGeometryVis += (*geomIt).GetVisibility();
+
+		std::stringstream d; d << "Geometry visibility: " << (*geomIt).GetVisibility();
 		LogManager::getSingleton().logMessage(d.str());
 	}
-	for (int i=0; i < visibleNodes.size(); ++i)
-	{
-		averageNodeVis += visibleNodes[i].GetVisibility();
-
-		std::stringstream d; d << "Node visibility: " << visibleNodes[i].GetVisibility();
+
+	InfoContainer<GtpVisibility::NodeInfo>::iterator nodesIt, nodesIt_end = visibleNodes.end();
+
+	for (nodesIt = visibleNodes.begin(); nodesIt != nodesIt_end; ++nodesIt)
+	{
+		averageNodeVis += (*nodesIt).GetVisibility();
+
+		std::stringstream d; d << "Node visibility: " << (*nodesIt).GetVisibility();
 		LogManager::getSingleton().logMessage(d.str());
 	}
 
-	averageNodeVis /= (float)visibleNodes.size();
-	averageGeometryVis /= (float)visibleGeometry.size();
+	if ((int)visibleNodes.size())
+		averageNodeVis /= (float)visibleNodes.size();
+	if ((int)visibleGeometry.size())
+		averageGeometryVis /= (float)visibleGeometry.size();
 
 	char str[100];
@@ -437,6 +444,6 @@
 			Vector3(camPos.x, 5000.0f, camPos.z), Vector3::NEGATIVE_UNIT_Y))
 	{
-		const int overTerrain = 200;
-		mCamNode->setPosition(camPos.x, queryResult.y + overTerrain, camPos.z);
+		const int terrainOffs = 10;
+		mCamNode->setPosition(camPos.x, queryResult.y + terrainOffs, camPos.z);
 	}
 }
Index: /trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp
===================================================================
--- /trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp	(revision 141)
+++ /trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp	(revision 141)
@@ -0,0 +1,223 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2005 The OGRE Team
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+/***************************************************************************
+octreenode.cpp  -  description
+-------------------
+begin                : Fri Sep 27 2002
+copyright            : (C) 2002 by Jon Anderson
+email                : janders@users.sf.net
+
+Enhancements 2003 - 2004 (C) The OGRE Team
+
+***************************************************************************/
+
+#include <OgreRoot.h>
+
+#include <OgreOctreeNode.h>
+#include <OgreOctreeSceneManager.h>
+#include <OgreLogManager.h>
+#include <OgreMeshManager.h>
+#include <OgreSubMesh.h>
+
+namespace Ogre
+{
+unsigned long green = 0xFFFFFFFF;
+
+unsigned short OctreeNode::mIndexes[ 24 ] = {0, 1, 1, 2, 2, 3, 3, 0,       //back
+        0, 6, 6, 5, 5, 1,             //left
+        3, 7, 7, 4, 4, 2,             //right
+        6, 7, 5, 4 };          //front
+unsigned long OctreeNode::mColors[ 8 ] = {green, green, green, green, green, green, green, green };
+
+OctreeNode::OctreeNode( SceneManager* creator ) : SceneNode( creator )
+{
+    mOctant = 0;
+}
+
+OctreeNode::OctreeNode( SceneManager* creator, const String& name ) : SceneNode( creator, name )
+{
+    mOctant = 0;
+}
+
+OctreeNode::~OctreeNode()
+{}
+void OctreeNode::_removeNodeAndChildren( )
+{
+    static_cast< OctreeSceneManager * > ( mCreator ) -> _removeOctreeNode( this ); 
+    //remove all the children nodes as well from the octree.
+    ChildNodeMap::iterator it = mChildren.begin();
+    while( it != mChildren.end() )
+    {
+        static_cast<OctreeNode *>( it->second ) -> _removeNodeAndChildren();
+        ++it;
+    }
+}
+Node * OctreeNode::removeChild( unsigned short index )
+{
+    OctreeNode *on = static_cast<OctreeNode* >( SceneNode::removeChild( index ) );
+    on -> _removeNodeAndChildren(); 
+    return on; 
+}
+Node * OctreeNode::removeChild( Node* child )
+{
+    OctreeNode *on = static_cast<OctreeNode* >( SceneNode::removeChild( child ) );
+    on -> _removeNodeAndChildren(); 
+    return on; 
+}
+    
+Node * OctreeNode::removeChild( const String & name )
+{
+    OctreeNode *on = static_cast< OctreeNode * >( SceneNode::removeChild(  name ) );
+    on -> _removeNodeAndChildren( ); 
+    return on; 
+}
+
+//same as SceneNode, only it doesn't care about children...
+void OctreeNode::_updateBounds( void )
+{
+    mWorldAABB.setNull();
+    mLocalAABB.setNull();
+
+    // Update bounds from own attached objects
+    ObjectMap::iterator i = mObjectsByName.begin();
+    AxisAlignedBox bx;
+
+    while ( i != mObjectsByName.end() )
+    {
+
+        // Get local bounds of object
+        bx = i->second ->getBoundingBox();
+
+        mLocalAABB.merge( bx );
+
+        mWorldAABB.merge( i->second ->getWorldBoundingBox(true) );
+        ++i;
+    }
+
+
+    //update the OctreeSceneManager that things might have moved.
+    // if it hasn't been added to the octree, add it, and if has moved
+    // enough to leave it's current node, we'll update it.
+    if ( ! mWorldAABB.isNull() )
+    {
+        static_cast < OctreeSceneManager * > ( mCreator ) -> _updateOctreeNode( this );
+    }
+
+}
+
+/** Since we are loose, only check the center.
+*/
+bool OctreeNode::_isIn( AxisAlignedBox &box )
+{
+	// Always fail if not in the scene graph
+	if (!mIsInSceneGraph) return false;
+
+    Vector3 center = mWorldAABB.getMaximum().midPoint( mWorldAABB.getMinimum() );
+
+    Vector3 bmin = box.getMinimum();
+    Vector3 bmax = box.getMaximum();
+
+    return ( bmax > center && bmin < center );
+
+}
+
+/** Addes the attached objects of this OctreeScene node into the queue. */
+void OctreeNode::_addToRenderQueue( Camera* cam, RenderQueue *queue, bool onlyShadowCasters )
+{
+    ObjectMap::iterator mit = mObjectsByName.begin();
+
+    while ( mit != mObjectsByName.end() )
+    {
+        MovableObject * mo = mit->second;
+
+		//LogManager::getSingleton().logMessage("notify");
+        mo->_notifyCurrentCamera(cam);
+        if ( mo->isVisible() &&
+            (!onlyShadowCasters || mo->getCastShadows()))
+        {
+			//LogManager::getSingleton().logMessage("update queue");
+            mo -> _updateRenderQueue( queue );
+        }
+
+        ++mit;
+    }
+
+}
+
+
+void OctreeNode::getRenderOperation( RenderOperation& rend )
+{
+	//Node::getRenderOperation(rend);
+	/*static SubMesh* pSubMesh = 0;
+
+	if (!pSubMesh)
+	{
+		MeshPtr pMesh = MeshManager::getSingleton().load("axis.mesh", 
+			ResourceGroupManager::BOOTSTRAP_RESOURCE_GROUP_NAME);
+		pSubMesh = pMesh->getSubMesh(0);
+	}
+	pSubMesh->_getRenderOperation(rend);*/
+	if (mWireBoundingBox == NULL) 
+	{
+		mWireBoundingBox = new WireBoundingBox();
+	}
+
+	AxisAlignedBox box = mLocalAABB;
+	// HACK: scale should not be done here
+	box.scale(Vector3(10,10,10));
+	mWireBoundingBox->setupBoundingBox(box);
+	mWireBoundingBox->getRenderOperation(rend);
+
+
+    /* TODO
+    rend.useIndexes = true;
+    rend.numTextureCoordSets = 0; // no textures
+    rend.vertexOptions = LegacyRenderOperation::VO_DIFFUSE_COLOURS;
+    rend.operationType = LegacyRenderOperation::OT_LINE_LIST;
+    rend.numVertices = 8;
+    rend.numIndexes = 24;
+
+    rend.pVertices = mCorners;
+    rend.pIndexes = mIndexes;
+    rend.pDiffuseColour = mColors;
+
+    const Vector3 * corners = _getLocalAABB().getAllCorners();
+
+    int index = 0;
+
+    for ( int i = 0; i < 8; i++ )
+    {
+        rend.pVertices[ index ] = corners[ i ].x;
+        index++;
+        rend.pVertices[ index ] = corners[ i ].y;
+        index++;
+        rend.pVertices[ index ] = corners[ i ].z;
+        index++;
+    }
+    */
+
+
+}
+}
Index: /trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- /trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 139)
+++ /trunk/VUT/Ogre/src/OgreVisibilityTerrainSceneManager.cpp	(revision 141)
@@ -609,5 +609,5 @@
 	mLeavePassesInQueue = 0;
 	
-/*	if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
+	if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
 	{
 		mShadowTechnique = SHADOWTYPE_NONE;
@@ -615,5 +615,5 @@
 		if (!mUseDepthPass)
 		{
-			// TODO: remove this
+			// TODO: remove this because should be processed in first pass
 			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
 
@@ -633,11 +633,10 @@
 		}
 	}
-	*/
+	
 	if (mDelayRenderTransparents && (!mUseDepthPass))
 	{
 		mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
 	}
-	std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;
-	LogManager::getSingleton().logMessage(d.str());
+	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
 
 	// possible two cameras (one for culling, one for rendering)
Index: /trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp
===================================================================
--- /trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 140)
+++ /trunk/VUT/Ogre/src/OgrePlatformQueryManager.cpp	(revision 141)
@@ -105,4 +105,6 @@
 	//---- collect results
 	unsigned int visiblePixels = 0;
+	std::pair<InfoContainer<GtpVisibility::NodeInfo>::iterator, bool> insertNode;
+	std::pair<InfoContainer<GtpVisibility::MeshInfo>::iterator, bool> insertGeom;
 
 	GtpVisibility::QueryList::iterator visQueryIt, projQueryIt;
@@ -116,6 +118,6 @@
 		(*visQueryIt)->GetQueryResult(visiblePixels, true);
 	
-		
 		float vis = (float)visiblePixels;
+		bool isVisible = visiblePixels > 0;
 
 		if (relativeVisibility)
@@ -132,7 +134,21 @@
 		++visQueryIt;
 		
-		// leave nodes with visibilty 0 in queue: 
+		// nodes with visibilty 0 in queue: 
 		// happens if node is intersected by near plane
-		visibleNodes->push_back(GtpVisibility::NodeInfo(*nodeIt, vis));
+		if (isVisible)
+		{
+			insertNode = visibleNodes->insert(GtpVisibility::NodeInfo(*nodeIt, vis));
+
+			if (!insertNode.second) // element already in list
+			{
+				//LogManager::getSingleton().logMessage("element already in list");
+                (*insertNode.first).SetVisibility((*insertNode.first).GetVisibility() + vis);
+
+				if (relativeVisibility) // relative visibility between zero and one
+				{
+					(*insertNode.first).SetVisibility((*insertNode.first).GetVisibility() * 0.5);
+				}
+			}
+		}
 	}
 
@@ -164,6 +180,16 @@
 		// geometry maybe occluded
 		if (isVisible)
-		{
-			visibleGeometry->push_back(GtpVisibility::MeshInfo(*geometryIt, vis));
+		{			 
+			insertGeom = visibleGeometry->insert(GtpVisibility::MeshInfo(*geometryIt, vis));
+			if (!insertGeom.second) // element already in list
+			{
+				//LogManager::getSingleton().logMessage("element already in list");
+                (*insertGeom.first).SetVisibility((*insertGeom.first).GetVisibility() + vis);
+
+				if (relativeVisibility) // relative visibility between zero and one
+				{
+					(*insertGeom.first).SetVisibility((*insertGeom.first).GetVisibility() * 0.5);
+				}
+			}
 		}
 	}
@@ -179,16 +205,21 @@
 	Camera *cam = sm->createCamera("PointQueryCam");	
 
-	Camera *oldCam = mViewport->getCamera();
+	//save old camera
+	Camera *savedCam = mViewport->getCamera();
+	
+	// --- initialise new camera
 	mViewport->setCamera(cam);
-
 	cam->setPosition(point);
 
+	cam->setNearClipDistance(savedCam->getNearClipDistance());
+	cam->setFarClipDistance(savedCam->getFarClipDistance());
+
 	// set frustum to 45 degrees so all the scene can be captured with 6 shots
-	//cam->setAspectRatio(1.0);
-	//cam->setFOVy(Radian(Math::HALF_PI));
-	
+	cam->setAspectRatio(1.0);
+	cam->setFOVy(Radian(Math::HALF_PI));
+
 	std::stringstream d;
-	d << "old camera: " + StringConverter::toString(oldCam->getDerivedPosition()) + 
-		" " + "O: " + StringConverter::toString(oldCam->getDerivedOrientation());
+	d << "old camera: " + StringConverter::toString(savedCam->getDerivedPosition()) + 
+		" " + "O: " + StringConverter::toString(savedCam->getDerivedOrientation());
 	LogManager::getSingleton().logMessage(d.str());
 
@@ -201,8 +232,5 @@
 		
 		// Print camera details
-        //mViewport->getTarget()->setDebugText("P: " + StringConverter::toString(cam->getDerivedPosition()) + 
-		//	" " + "O: " + StringConverter::toString(cam->getDerivedOrientation()));
-		
-		std::stringstream d;
+      	std::stringstream d;
 		d << "Point query camera: " + StringConverter::toString(cam->getDerivedPosition()) + 
 			" " + "O: " + StringConverter::toString(cam->getDerivedOrientation());
@@ -211,22 +239,16 @@
 		ComputeCameraVisibility(*cam, visibleNodes, visibleGeometry, relativeVisibility);
 			   
-		mViewport->getTarget()->update();
-		
+		//mViewport->getTarget()->update(); for(int j=0; j<10000000; j++)	printf("HAAHHAHAHAHAH");
+
+		// permute directions
 		Vector3 dir(0,0,0);
 		dir[i/2] = sign;
 
 		cam->setDirection(dir);
-
-		for(int j=0; j<10000000; j++)	printf("HAAHHAHAHAHAH");
-				
-		// four shots around y axis, two around x axis
-		//Vector3 axis = i < 4 ? Vector3::UNIT_Y : Vector3::UNIT_X;		
-		//Radian angle = i < 5 ? 
-		//cam->rotate(axis, Radian(Math::HALF_PI));		
 	}
 	
 
 	// reset camera
-	mViewport->setCamera(oldCam);
+	mViewport->setCamera(savedCam);
 }
 //-----------------------------------------------------------------------
