Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/include/DistanceQueue.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/include/DistanceQueue.h	(revision 722)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/include/DistanceQueue.h	(revision 726)
@@ -23,7 +23,8 @@
 	{}
 	
-	bool operator() (T v1, T v2) const
+	bool operator() (const T v1, const T v2) const
 	{
-		return false;//mHierarchyInterface->GetSquaredDistance(v1) > mHierarchyInterface->GetSquaredDistance(v2);
+		//return false;
+		return mHierarchyInterface->GetSquaredDistance(v1) > mHierarchyInterface->GetSquaredDistance(v2);
 	}
 		
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/include/HierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/include/HierarchyInterface.h	(revision 606)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/include/HierarchyInterface.h	(revision 726)
@@ -72,6 +72,7 @@
 	*/
 	DistanceQueue *GetQueue();
+	
 	/** Returns distance of the node to the view plane.
-		@param node1 the hierarchy node
+		@param node the hierarchy node
 	*/			
 	virtual float GetSquaredDistance(HierarchyNode *node) const = 0;
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/src/FrustumCullingManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/src/FrustumCullingManager.cpp	(revision 720)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/src/FrustumCullingManager.cpp	(revision 726)
@@ -8,9 +8,10 @@
 {
 	if (0) Ogre::LogManager::getSingleton().logMessage("Frustum Culling");
+
 	while (!mHierarchyInterface->GetQueue()->empty())
 	{
 		HierarchyNode *node = mHierarchyInterface->GetQueue()->top();
 		mHierarchyInterface->GetQueue()->pop();
-		
+
 		// interesting for visualization purpose
 		mHierarchyInterface->SetNodeVisible(node, false);
@@ -33,4 +34,3 @@
 	}
 }
-
 } // namespace GtpVisibility
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/src/CoherentHierarchicalCullingManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/src/CoherentHierarchicalCullingManager.cpp	(revision 350)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/src/CoherentHierarchicalCullingManager.cpp	(revision 726)
@@ -30,4 +30,5 @@
 	while (!mHierarchyInterface->GetQueue()->empty() || !queryQueue.empty())
 	{
+		// only wait for result if queue is empty
 		while (!queryQueue.empty() && 
 			   queryQueue.front().second->GetQueryResult(visiblePixels, 
@@ -40,7 +41,10 @@
 			if (visiblePixels > mVisibilityThreshold)
 			{
-				// ensure that we only traverse once if geometry in node
+				// in case geometry is in omterior node: ensure that we only traverse once
 				if (!mHierarchyInterface->IsNodeVisible(node))
+				{
 					mHierarchyInterface->TraverseNode(node);
+				}
+
 				mHierarchyInterface->PullUpVisibility(node);
 			}
@@ -96,5 +100,4 @@
 				{
 					SkipQuery(node);
-
 					continue;
 				}
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/src/HierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/src/HierarchyInterface.cpp	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/src/HierarchyInterface.cpp	(revision 726)
@@ -7,6 +7,10 @@
 //-----------------------------------------------------------------------
 HierarchyInterface::HierarchyInterface(): 
-mFrameId(0), mNumTraversedNodes(0), mHierarchyRoot(NULL), 
-mSavedNode(NULL), mCurrentTestIdx(0), mTestGeometryForVisibleLeaves(false)
+mFrameId(0), 
+mNumTraversedNodes(0), 
+mHierarchyRoot(NULL), 
+mSavedNode(NULL), 
+mCurrentTestIdx(0), 
+mTestGeometryForVisibleLeaves(false)
 {	
 	mDistanceQueue = new DistanceQueue(GtDistance<HierarchyNode *>(this));
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/src/BatchedQueriesCullingManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/src/BatchedQueriesCullingManager.cpp	(revision 373)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/src/BatchedQueriesCullingManager.cpp	(revision 726)
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/src/VisibilityManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/src/VisibilityManager.cpp	(revision 722)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/src/VisibilityManager.cpp	(revision 726)
@@ -18,5 +18,4 @@
 mAssumedVisibilityForChc(0)
 {
-
 #if 1
 	SetCullingManager(VisibilityEnvironment::COHERENT_HIERARCHICAL_CULLING);
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h	(revision 347)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h	(revision 726)
@@ -11,5 +11,4 @@
 #include "OgrePlatformQueryManager.h"
 #include "VisibilityManager.h"
-
 
 namespace Ogre {
@@ -56,19 +55,23 @@
 	virtual void renderObjects(const RenderPriorityGroup::TransparentRenderablePassList& objs, 
             bool doLightIteration, const LightList* manualLightList = 0);
-
 	/** Writes out stats into the Ogre log file.
 	*/
 	void WriteLog();
 
-	/** Override pass so we can do the z-fail pass. 
+	/** We override this because we want to include the z-fail pass. 
 	*/
 	Pass* setPass(Pass* pass);
-
 	/** Override from SceneManager so we can skip all but first pass for depth pass. 
 	*/
 	bool validatePassForRendering(Pass* pass);
-
+	/** This function renders renderables using false color ids.
+	*/
 	void RenderItemBuffer(RenderPriorityGroup* pGroup);
+	/** Renders a single object using false color id.
+	*/
 	void RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass);
+	/** Overritten from scene manager to include the false color id rendering of the
+		scene objects.
+	*/
 	void renderQueueGroupObjects(RenderQueueGroup* pGroup);
 
@@ -89,12 +92,10 @@
 	void endFrame();
 
+	/** Override this because we must handle shadows differently.
+	*/
 	void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
+	/** Override this because we must handle shadows differently.
+	*/
 	void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
-
-	/** Override standard function so octree boxes are always of equal side length.
-		This has advantages for CHC, because terrain tiles are in different octree nodes
-		and can be culled.
-	*/
-	void setWorldGeometry( const String& filename );
 
 protected:
@@ -161,4 +162,6 @@
 
 	bool mIsHierarchicalCulling;
+
+	std::ofstream mDummyLog;
 };
 
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h	(revision 187)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h	(revision 726)
@@ -153,4 +153,5 @@
 	std::vector<PlatformOcclusionQuery *> mOcclusionQueries;
 
+	Vector3 mCameraPosition;
 	bool mOnlyShadowCasters;
 	int mLeavePassesInQueue;
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj	(revision 722)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj	(revision 726)
@@ -94,5 +94,5 @@
 				BufferSecurityCheck="FALSE"
 				EnableFunctionLevelLinking="TRUE"
-				RuntimeTypeInfo="TRUE"
+				RuntimeTypeInfo="FALSE"
 				UsePrecompiledHeader="0"
 				WarningLevel="3"
@@ -227,4 +227,7 @@
 					RelativePath="..\include\OgreVisibilitySceneManager.h">
 				</File>
+				<File
+					RelativePath="..\include\VspBspTree.h">
+				</File>
 			</Filter>
 			<Filter
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp	(revision 720)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp	(revision 726)
@@ -10,6 +10,7 @@
 #include <OgreSubEntity.h>
 
-// HACK
-const static DEBUG_CHC = false;
+
+// normal terrain rendering
+const static NORMAL_RENDER_HACK = false;
 
 namespace Ogre {
@@ -17,5 +18,6 @@
 //-----------------------------------------------------------------------
 VisibilityTerrainSceneManager::VisibilityTerrainSceneManager(
-							GtpVisibility::VisibilityManager *visManager): 
+	GtpVisibility::VisibilityManager *visManager):
+TerrainSceneManager(),
 mVisibilityManager(visManager), 
 mShowVisualization(false),
@@ -28,5 +30,4 @@
 mIsDepthPassPhase(false),
 mUseItemBuffer(false),
-//mUseItemBuffer(true),
 mIsItemBufferPhase(false),
 mCurrentEntityId(1),
@@ -101,33 +102,4 @@
 	//mItemBufferPass->setAmbient(1, 1, 0);
 }
-//-------------------------------------------------------------------------
-void VisibilityTerrainSceneManager::setWorldGeometry( const String& filename )
-{
-    // Clear out any existing world resources (if not default)
-    if (ResourceGroupManager::getSingleton().getWorldResourceGroupName() != 
-        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
-    {
-        ResourceGroupManager::getSingleton().clearResourceGroup(
-            ResourceGroupManager::getSingleton().getWorldResourceGroupName());
-    }
-
-    mTerrainPages.clear();
-	
-	// Load the configuration
-    loadConfig(filename);
-
-    // Resize the octree, allow for 1 page for now
-    float max_x = mOptions.scale.x * mOptions.pageSize;
-    float max_y = mOptions.scale.y;
-    float max_z = mOptions.scale.z * mOptions.pageSize;
-
-	float maxAxis = std::max(max_x, max_y);
-	maxAxis = std::max(maxAxis, max_z);
-	resize(AxisAlignedBox(0, 0, 0, maxAxis, maxAxis, maxAxis));
-    
-    setupTerrainMaterial();
-    setupTerrainPages();
-}
-
 //-----------------------------------------------------------------------
 void VisibilityTerrainSceneManager::PrepareVisualization(Camera *cam)
@@ -146,8 +118,10 @@
         // ignore
     }
+	// add bounding boxes of rendered objects
 	for (BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it)
 	{
 		getRenderQueue()->addRenderable(*it);
 	}
+	
 	if (mRenderNodesForViz || mRenderNodesContentForViz)
 	{
@@ -182,9 +156,14 @@
 Pass *VisibilityTerrainSceneManager::setPass(Pass* pass)
 {
+	if (NORMAL_RENDER_HACK)
+	{
+		return SceneManager::setPass(pass);
+	}
+
 	// TODO: setting vertex program is not efficient
 	//Pass *usedPass = ((mIsDepthPassPhase && !pass->hasVertexProgram()) ? mDepthPass : pass); 
 	
 	// set depth fill pass if we currently do not make an aabb occlusion query
-	const bool useDepthPass = 1 &&
+	const bool useDepthPass = 
 		(mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery());
 
@@ -196,6 +175,5 @@
 	// set illumination stage to NONE so no shadow material is used 
 	// for depth pass or for occlusion query
-	if (1 && 
-		(mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery()))
+	if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
 	{
 		mIlluminationStage = IRS_NONE;
@@ -203,7 +181,7 @@
 	
 	// --- set vertex program of current pass in order to set correct depth
-	if (mExecuteVertexProgramForAllPasses 
-		&& mIsDepthPassPhase 
-		&& pass->hasVertexProgram())
+	if (mExecuteVertexProgramForAllPasses && 
+		mIsDepthPassPhase && 
+		pass->hasVertexProgram())
 	{
 		// add vertex program of current pass to depth pass
@@ -254,4 +232,10 @@
 														bool onlyShadowCasters)
 {
+	if (NORMAL_RENDER_HACK)
+	{
+		TerrainSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+		return;
+	}
+
 	//-- show visible scene nodes and octree bounding boxes from last frame
 	if (mShowVisualization)
@@ -273,6 +257,5 @@
 
 		// only shadow casters will be rendered in shadow texture pass
-		if (0)
-			mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+		if (0) mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
 	}
 	
@@ -285,4 +268,11 @@
 void VisibilityTerrainSceneManager::_renderVisibleObjects()
 {
+	if (NORMAL_RENDER_HACK)
+	{
+		TerrainSceneManager::_renderVisibleObjects();
+
+		return;
+	}
+
 	InitDepthPass(); 	  // create material for depth pass
 	InitItemBufferPass(); // create material for item buffer pass
@@ -309,5 +299,8 @@
 	}
 	else //-- the hierarchical culling algorithm
-	{
+	{ 
+		// from TerrainSceneManager
+		mDestRenderSystem -> setLightingEnabled(false);
+
 		// don't render backgrounds for item buffer
 		if (mUseItemBuffer)
@@ -327,5 +320,5 @@
 		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
 
-		TerrainSceneManager::_renderVisibleObjects();
+		OctreeSceneManager::_renderVisibleObjects();
 		/////////////////////////////////////////////////
 
@@ -356,5 +349,6 @@
 		mVisibilityManager->ApplyVisibilityCulling();
 
-		// delete remaining renderables from queue (all not in mLeavePassesInQueue)
+		// delete remaining renderables from queue:
+		// all which are not in mLeavePassesInQueue)
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		_deleteRenderedQueueGroups(mLeavePassesInQueue);
@@ -367,10 +361,12 @@
 		mLeavePassesInQueue = 0;
 		
-
+#if 1	
 		// add visible nodes found by the visibility culling algorithm
-#if 1
 		if (mUseDepthPass)
 		{
-			for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++ it)
+			NodeList::const_iterator it, it_end = mVisible.end();
+
+			//getRenderQueue()->clear();
+			for (it = mVisible.begin(); it != it_end; ++ it)
 			{
 				(*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
@@ -382,6 +378,5 @@
 		clearSpecialCaseRenderQueues();
 	
-		if (!DEBUG_CHC)
-			TerrainSceneManager::_renderVisibleObjects();
+		OctreeSceneManager::_renderVisibleObjects();
 	}
 		
@@ -394,7 +389,7 @@
 
 	getRenderQueue()->clear(); // finally clear render queue
-	OGRE_DELETE(mRenderQueue); // HACK: should rather only be cleared...
-
-	//WriteLog(); // write out stats
+	if (0) OGRE_DELETE(mRenderQueue); // HACK: should rather only be cleared ...
+
+	if (0) WriteLog(); // write out stats
 }
 
@@ -402,4 +397,10 @@
 void VisibilityTerrainSceneManager::_updateSceneGraph(Camera* cam)
 {
+	if (NORMAL_RENDER_HACK)
+	{
+		TerrainSceneManager::_updateSceneGraph(cam);
+		return;
+	}
+
 	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
 	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
@@ -531,5 +532,5 @@
 }
 //-----------------------------------------------------------------------
-GtpVisibility::VisibilityManager *VisibilityTerrainSceneManager::getVisibilityManager( void )
+GtpVisibility::VisibilityManager *VisibilityTerrainSceneManager::getVisibilityManager()
 {
 	return mVisibilityManager;
@@ -549,5 +550,6 @@
 	  << "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
 	  << "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
-      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << "\n";
+      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << ", "
+	  << "Found objects: " << (int)mVisible.size() << "\n";
 
 	LogManager::getSingleton().logMessage(d.str());
@@ -560,12 +562,18 @@
 {
 	// for correct rendering, transparents must be rendered after hierarchical culling
-	if (1 && !mSkipTransparents)
-	{
-		OctreeSceneManager::renderObjects(objs, doLightIteration, manualLightList);
+	// => do nothing
+	if (NORMAL_RENDER_HACK || !mSkipTransparents)
+	{
+		SceneManager::renderObjects(objs, doLightIteration, manualLightList);
 	}
 }
 //-----------------------------------------------------------------------
 bool VisibilityTerrainSceneManager::validatePassForRendering(Pass* pass)
-{
+{	
+	if (NORMAL_RENDER_HACK)
+	{
+		return SceneManager::validatePassForRendering(pass);
+	}
+
 	// skip all but first pass if we are doing the depth pass
 	if ((mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() > 0))
@@ -584,7 +592,7 @@
 void VisibilityTerrainSceneManager::renderQueueGroupObjects(RenderQueueGroup* pGroup)
 {
-	if (!mIsItemBufferPhase)
-	{
-		TerrainSceneManager::renderQueueGroupObjects(pGroup);
+	if (NORMAL_RENDER_HACK || !mIsItemBufferPhase)
+	{
+		SceneManager::renderQueueGroupObjects(pGroup);
 		return;
 	}
@@ -616,5 +624,5 @@
 			continue;
 
-		// Render only first pass
+		// Render only first pass of renderable as false color
 		if (ipass->first->getIndex() > 0)
 			continue;
@@ -627,8 +635,10 @@
 		for (irend = rendList->begin(); irend != irendend; ++irend)
 		{
-			std::stringstream d; d << "itembuffer, pass name: " << 
+			if (0)
+			{
+				std::stringstream d; d << "itembuffer, pass name: " << 
 				ipass->first->getParent()->getParent()->getName();
-				
-			//LogManager::getSingleton().logMessage(d.str());
+				LogManager::getSingleton().logMessage(d.str());
+			}
 			
 			RenderSingleObjectForItemBuffer(*irend, ipass->first);
@@ -636,5 +646,5 @@
 	}
 
-	// -- TRANSPARENT LOOP: must be handled differently 
+	//-- TRANSPARENT LOOP: must be handled differently from solids
 
 	// transparents are treated either as solids or completely discarded
@@ -729,5 +739,5 @@
 	mLeavePassesInQueue = 0;
 
-	if (!DEBUG_CHC && !mUseDepthPass && !mUseItemBuffer)
+	if (!mUseDepthPass && !mUseItemBuffer)
 	{
 		if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
@@ -760,5 +770,5 @@
 	// skip rendering transparents during the hierarchical culling
 	// (because they will be rendered afterwards)
-	mSkipTransparents = !DEBUG_CHC && 
+	mSkipTransparents = 
 		(mIsDepthPassPhase || (mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES));
 
@@ -800,5 +810,6 @@
 }
 //-----------------------------------------------------------------------
-void VisibilityTerrainSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+void VisibilityTerrainSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(
+	RenderQueueGroup* pGroup)
 {
 	// only render solid passes during hierarchical culling
@@ -832,5 +843,6 @@
 }
 //-----------------------------------------------------------------------
-void VisibilityTerrainSceneManager::renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+void VisibilityTerrainSceneManager::renderModulativeStencilShadowedQueueGroupObjects(
+	RenderQueueGroup* pGroup)
 {
    if (mIsHierarchicalCulling)
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionCullingSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionCullingSceneManager.cpp	(revision 720)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionCullingSceneManager.cpp	(revision 726)
@@ -380,5 +380,5 @@
 
 	getRenderQueue()->clear(); // finally clear render queue
-	OGRE_DELETE(mRenderQueue); // HACK: should be cleared before...
+	OGRE_DELETE(mRenderQueue); // HACK: should be cleared before ...
 	WriteLog(); // write out stats
 
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp	(revision 722)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp	(revision 726)
@@ -21,22 +21,30 @@
 
 	// if we come across some renderable geometry => render it
-	if (octree->mNodes.size() > 0)
+	if (!octree->mNodes.empty())
 	{
 		RenderNode(node);
 	}
 	
-	//if (octree->numNodes() > (int)octree->mNodes.size()) // if not all subtrees are empty
+	// if not all subtrees are empty
 	if (!IsLeaf(node))
 	{
-		for(int i=0; i<8; ++i)
-		{
-			Octree *nextChild = 
-				octree->mChildren[(i & 4) >> 2][(i & 2) >> 1][i & 1];
-			
-			if (nextChild)
-			{
-				mDistanceQueue->push(nextChild);
-			}
-		}
+		Octree *nextChild;
+
+		if ((nextChild = octree->mChildren[0][0][0]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[0][0][1]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[0][1][0]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[0][1][1]) != NULL)
+           	mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[1][0][0]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[1][0][1]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[1][1][0]) != NULL)
+			mDistanceQueue->push(nextChild);
+		if ((nextChild = octree->mChildren[1][1][1]) != NULL)
+			mDistanceQueue->push(nextChild);
 	}
 }
@@ -56,10 +64,10 @@
 float OctreeHierarchyInterface::GetSquaredDistance(GtpVisibility::HierarchyNode *node) const
 {
-	LogManager::getSingleton().logMessage("here4");
+	const Vector3 bmin = static_cast<Octree *>(node)->mBox.getMinimum();
+	const Vector3 bmax = static_cast<Octree *>(node)->mBox.getMaximum();
 
-	const AxisAlignedBox &box = static_cast<Octree *>(node)->mBox;
-	const Vector3 pos = ((box.getMaximum() - box.getMinimum()) * 0.5) + box.getMinimum();
+	const Vector3 pos = (bmax - bmin) * 0.5 + bmin;
 	
-	return (mCullCamera->getDerivedPosition() - pos).squaredLength();
+	return (mCameraPosition - pos).squaredLength();
 }
 //-----------------------------------------------------------------------
@@ -101,7 +109,8 @@
 	{
 		octant->setLastRendered(mFrameId);
-
-		dynamic_cast<OctreeSceneManager *>(mSceneManager)->_renderOctant(mCamera, 
-			octant, mOnlyShadowCasters, mLeavePassesInQueue);
+		OctreeSceneManager *ocm = 
+			//dynamic_cast<OctreeSceneManager *>(mSceneManager);
+			static_cast<OctreeSceneManager *>(mSceneManager);
+		ocm->_renderOctant(mCamera, octant, mOnlyShadowCasters, mLeavePassesInQueue);
 
 		mVisibleNodes.push_back(node);
@@ -155,10 +164,11 @@
 	}
 
-	dynamic_cast<OctreeSceneManager *>(mSceneManager)->getBoxes()->push_back(box);
+	//dynamic_cast<OctreeSceneManager *>(mSceneManager)->getBoxes()->push_back(box);
+	static_cast<OctreeSceneManager *>(mSceneManager)->getBoxes()->push_back(box);
 }
 //-----------------------------------------------------------------------
-void OctreeHierarchyInterface::GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
-										   GtpVisibility::GeometryVector *geometryList, 
-										   bool includeChildren)
+void OctreeHierarchyInterface::GetNodeGeometryList(GtpVisibility::HierarchyNode *node,
+												   GtpVisibility::GeometryVector *geometryList, 
+												   bool includeChildren)
 {
 	NodeList::const_iterator nodeIt, nodeIt_end;
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp	(revision 720)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp	(revision 726)
@@ -24,10 +24,7 @@
 mLeavePassesInQueue(0),
 mDelayRenderTransparents(true),
-//mDelayRenderTransparents(false),
-//mUseDepthPass(true),
 mUseDepthPass(false),
 mIsDepthPassPhase(false),
 mUseItemBuffer(false),
-//mUseItemBuffer(true),
 mIsItemBufferPhase(false),
 mCurrentEntityId(1),
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp	(revision 726)
@@ -11,8 +11,15 @@
 
 //-----------------------------------------------------------------------
-PlatformHierarchyInterface::PlatformHierarchyInterface(SceneManager *sm, RenderSystem *rsys):
-mSceneManager(sm), mRenderSystem(rsys), mSolidBoundingBox(NULL), mCamera(NULL), 
-mCullCamera(NULL), mOnlyShadowCasters(false), mLeavePassesInQueue(0),
-mIsBoundingBoxQuery(false)
+PlatformHierarchyInterface::PlatformHierarchyInterface(SceneManager *sm, 
+													   RenderSystem *rsys):
+mSceneManager(sm), 
+mRenderSystem(rsys), 
+mSolidBoundingBox(NULL), 
+mCamera(NULL), 
+mCullCamera(NULL), 
+mOnlyShadowCasters(false), 
+mLeavePassesInQueue(0),
+mIsBoundingBoxQuery(false),
+mCameraPosition(Vector3(0, 0, 0))
 {
 }
@@ -131,4 +138,5 @@
 	mCullCamera = cullCam ? cullCam : cam;
 
+	mCameraPosition = mCullCamera->getDerivedPosition();
 	// create materials for node visualization
 	CreateNodeVizMaterials();
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp	(revision 726)
@@ -31,5 +31,6 @@
 			       bool relativeVisibility)
 {
-	SceneManager *sm = dynamic_cast<PlatformHierarchyInterface *>
+	SceneManager *sm = //dynamic_cast<PlatformHierarchyInterface *>
+		static_cast<PlatformHierarchyInterface *>
 		(mHierarchyInterface)->GetSceneManager();
 
@@ -93,5 +94,6 @@
 	// we need access to the scene manager and the rendersystem
 	PlatformHierarchyInterface *pfHierarchyInterface = 
-		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+		//dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+		static_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
 
 	SceneManager *sm = pfHierarchyInterface->GetSceneManager();
@@ -189,5 +191,6 @@
 
 	SceneManager *sm = 
-		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
+		//dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
+		static_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
 
 	SceneManager::EntityIterator it = sm->getEntityIterator();
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp	(revision 645)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp	(revision 726)
@@ -27,5 +27,6 @@
 	// we need access to the scene manager and the rendersystem
 	PlatformHierarchyInterface *pfHierarchyInterface = 
-		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+		//dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+		static_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
 
 	// disable overlays, reset them later
Index: GTP/trunk/Lib/Vis/Preprocessing/scripts/Preprocessor.vcproj
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/scripts/Preprocessor.vcproj	(revision 722)
+++ GTP/trunk/Lib/Vis/Preprocessing/scripts/Preprocessor.vcproj	(revision 726)
@@ -65,4 +65,7 @@
 			<Tool
 				Name="VCCLCompilerTool"
+				InlineFunctionExpansion="2"
+				FavorSizeOrSpeed="1"
+				OptimizeForWindowsApplication="TRUE"
 				AdditionalIncludeDirectories="..\support;..\support\devil\include;..\support\zlib\include;..\include;&quot;$(QTDIR)\include\QtCore&quot;;&quot;$(QTDIR)\include\QtGui&quot;;&quot;$(QTDIR)\include&quot;;&quot;$(QTDIR)\include\QtOpenGl&quot;;..\src;&quot;$(CG_INC_PATH)&quot;;..\..\..\..\..\..\NonGTP\Devil\include;..\..\..\..\..\..\NonGTP\Zlib\include;..\..\..\..\..\..\NonGTP\Xerces"
 				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;"
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 712)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 726)
@@ -57,4 +57,16 @@
 
 
+static void RotateMesh(Mesh *mesh)
+{
+	VertexContainer::iterator it, it_end = mesh->mVertices.end();
+
+	const float angle = 30.0f * PI / 180.0f;
+	const Matrix4x4 rot = RotationYMatrix(angle);
+
+	for (it = mesh->mVertices.begin(); it != it_end; ++ it)
+	{
+		(*it) = rot * (*it);        
+	}
+}
 
 // ---------------------------------------------------------------------------
@@ -96,16 +108,4 @@
 
 
-static void RotateMesh(Mesh *mesh)
-{
-	VertexContainer::iterator it, it_end = mesh->mVertices.end();
-
-	const float angle = 30.0f * PI / 180.0f;
-	const Matrix4x4 rot = RotationYMatrix(angle);
-
-	for (it = mesh->mVertices.begin(); it != it_end; ++ it)
-	{
-		(*it) = rot * (*it);        
-	}
-}
 
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp	(revision 704)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp	(revision 726)
@@ -156,6 +156,5 @@
       
       currentMesh->AddFace(face);
-      if (meshGrouping != 0 &&
-					currentMesh->mFaces.size() >=  meshGrouping) {
+      if (meshGrouping != 0 && currentMesh->mFaces.size() >=  meshGrouping) {
 		if (ROTATE_SCENE)
 			RotateMesh(currentMesh);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 719)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 726)
@@ -458,8 +458,5 @@
 
 	EvalPriority(tData);
-	
-
-	if (mSimulateOctree)
-        tData.mAxis = 0;
+
 
 	// first node is kd node, i.e. an axis aligned box
@@ -569,5 +566,4 @@
 							  geom);
 
-	
 
 	// compute first split candidate
@@ -695,10 +691,4 @@
 		VspBspTraversalData tBackData;
 
-		if (mSimulateOctree)
-		{	// choose axes in circular motion
-			tFrontData.mAxis = (tData.mAxis + 1) % 3;
-			tBackData.mAxis = (tData.mAxis + 1) % 3;
-		}
-
 		// create new interior node and two leaf nodes
 		// or return leaf as it is (if maxCostRatio missed)
@@ -709,5 +699,6 @@
 		Plane3 splitPlane;
 		BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
-
+		
+		// choose next split plane
 		if (!SelectPlane(splitPlane, leaf, tData, tFrontData, tBackData, splitAxis))
 		{
@@ -722,4 +713,5 @@
 		}
 	
+		// if this a valid split => subdivide this node further
 		if (splitFurther) //-- continue subdivision
 		{
@@ -732,4 +724,5 @@
 
 			tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
+			tFrontData.mAxis = tBackData.mAxis = splitAxis;
 
 			// how often was max cost ratio missed in this branch?
@@ -740,7 +733,7 @@
 			EvalPriority(tBackData);
 
+			// evaluate subdivision stats
 			if (1)
 			{
-
 				float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
 				float cBack = (float)tBackData.mPvs * tBackData.mProbability;
@@ -823,5 +816,5 @@
 }
 
-
+// subdivide using a split plane queue
 BspNode *VspBspTree::Subdivide(VspBspSplitQueue &tQueue,
 							   VspBspSplitCandidate &splitCandidate)
@@ -839,4 +832,5 @@
 
 		//-- continue subdivision
+		
 		// create new interior node and two leaf node
 		const Plane3 splitPlane = splitCandidate.mSplitPlane;
@@ -853,5 +847,6 @@
 
 		tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
-		
+		tFrontData.mAxis = tBackData.mAxis = splitAxis;
+
 		// how often was max cost ratio missed in this branch?
 		tFrontData.mMaxCostMisses = maxCostMisses;
@@ -960,5 +955,5 @@
 
 	// compute locally best split plane
-	bool success = SelectPlane(splitData.mSplitPlane, leaf, tData, 
+    bool success = SelectPlane(splitData.mSplitPlane, leaf, tData, 
 							   frontData, backData, splitData.mSplitAxis);
 
@@ -1403,5 +1398,5 @@
 		sAxis = Random(3);
 	else if (mSimulateOctree)
-		sAxis = tData.mAxis;
+		sAxis = (tData.mAxis + 1) % 3;
 		
 	//Debug << "use special axis: " << useSpecialAxis << endl;
@@ -2012,5 +2007,5 @@
 
 	const int pvsSize = data.mPvs;
-//cout << "here433" << endl;
+
 	RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp	(revision 719)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp	(revision 726)
@@ -2441,5 +2441,4 @@
 		{
 			geom.Add(candidatePolys[i], candidatePlanes[i]);
-			//	geom.mPolys.push_back(candidates[i]);
 		}
 	}
@@ -2456,6 +2455,6 @@
 
 
-int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> 
-						   &neighbors,
+int BspTree::FindNeighbors(BspNode *n, 
+						   vector<BspLeaf *> &neighbors,
 						   const bool onlyUnmailed) const
 {
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp	(revision 712)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp	(revision 726)
@@ -1145,9 +1145,7 @@
 		for (oit = objects.begin(); oit != oit_end; ++ oit)
 		{
-			if (1)
-			{
+			if (0)
 				SetForcedMaterial(RandomMaterial());
-			}
-
+			
 			ExportIntersectable(*oit);
 		}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 722)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 726)
@@ -2104,52 +2104,71 @@
 	{
 		exporter->ExportMesh(vc->GetMesh());
+	
 		return;
 	}
 
+	
+	if (clipPlane)
+	{
+		ViewCellContainer leaves;
+		mViewCellsTree->CollectLeaves(vc, leaves);
+		ViewCellContainer::const_iterator it, it_end = leaves.end();
+
+		for (it = leaves.begin(); it != it_end; ++ it)
+		{
+			BspNodeGeometry geom;
+
+			BspNodeGeometry front;
+			BspNodeGeometry back;
+
+			BspLeaf *leaf = dynamic_cast<BspViewCell *>(*it)->mLeaf;
+			mBspTree->ConstructGeometry(leaf, geom);
+
+			const float eps = 0.00000001f;
+			const int cf = geom.Side(*clipPlane, eps);
+
+			if (cf == -1)
+			{
+				exporter->ExportPolygons(geom.GetPolys());
+			}
+			else if (cf == 0)
+			{
+				geom.SplitGeometry(front,
+								   back,
+								   *clipPlane,
+								   mViewSpaceBox, 
+								   eps);
+	
+				//Debug << "geo size: " << geom.Size() << endl;
+				//Debug << "size b: " << back.Size() << " f: " << front.Size() << endl;
+				if (back.Valid())
+				{
+					exporter->ExportPolygons(back.GetPolys());
+				}			
+			}
+		}
+	}
+	else
+	{
+		BspNodeGeometry geom;
+		mBspTree->ConstructGeometry(vc, geom);
+			
+		exporter->ExportPolygons(geom.GetPolys());
+	}
+}
+
+
+void BspViewCellsManager::CreateMesh(ViewCell *vc)
+{
+	// delete previous mesh
+	///DEL_PTR(vc->GetMesh());
 	BspNodeGeometry geom;
 	mBspTree->ConstructGeometry(vc, geom);
 
-	if (clipPlane)
-	{
-		const int cf = Polygon3::ClassifyPlane(geom.GetPolys(), *clipPlane, 0.0001f);
-
-		if (cf == Polygon3::BACK_SIDE)
-		{
-			exporter->ExportPolygons(geom.GetPolys());
-		}
-		else if (cf == Polygon3::SPLIT)
-		{
-			BspNodeGeometry front;
-			BspNodeGeometry back;
-
-			geom.SplitGeometry(front,
-							   back,
-							   *clipPlane,
-							   mViewSpaceBox, 
-							   0.0001f);
-
-			if (back.Valid())
-				exporter->ExportPolygons(back.GetPolys());
-		}
-	}
-	else
-	{
-		exporter->ExportPolygons(geom.GetPolys());
-	}
-}
-
-
-void BspViewCellsManager::CreateMesh(ViewCell *vc)
-{
-	if (vc->GetMesh())
-		delete vc->GetMesh();
-
-	BspNodeGeometry geom;
-	
-	mBspTree->ConstructGeometry(vc, geom);
-
 	Mesh *mesh = new Mesh();
+
 	geom.AddToMesh(*mesh);
 	vc->SetMesh(mesh);
+	// put mesh into mesh container so we can savely delete it
 	mMeshContainer.push_back(mesh);
 }
@@ -2785,4 +2804,5 @@
 }
 
+
 void VspKdViewCellsManager::Visualize(const ObjectContainer &objects,
 									  const VssRayContainer &sampleRays)
@@ -2882,6 +2902,4 @@
 	Exporter *exporter = Exporter::GetExporter("vspkdtree_merged.x3d");
 
-	//if (exportGeometry) exporter->SetWireframe();
-	//else exporter->SetFilled();
 
 	ExportViewCellsForViz(exporter);
@@ -4000,8 +4018,5 @@
 void VspBspViewCellsManager::CreateMesh(ViewCell *vc)
 {
-	if (vc->GetMesh())
-		delete vc->GetMesh();
-
-	
+	//if (vc->GetMesh()) delete vc->GetMesh();
 	BspNodeGeometry geom;
 
@@ -4011,4 +4026,5 @@
 	geom.AddToMesh(*mesh);
 	vc->SetMesh(mesh);
+	// put mesh into mesh container so we can savely delete it
 	mMeshContainer.push_back(mesh);
 }
