Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHeightmapTerrainPageSource.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHeightmapTerrainPageSource.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHeightmapTerrainPageSource.h	(revision 2349)
@@ -0,0 +1,78 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __BiHeightmapTerrainPageSource_H__
+#define __BiHeightmapTerrainPageSource_H__
+
+#include "OgreBiTerrainPrerequisites.h"
+#include "OgreBiTerrainPageSource.h"
+#include "OgreImage.h"
+
+namespace Ogre {
+
+    /** Specialisation of the TerrainPageSource class to provide tiles loaded
+        from a 2D greyscale image.
+    @remarks
+        This is a simple tile provider that does not support paging; it is
+        assumed that the entire heightmap is loaded as one page.
+    */
+    class _OgreBiTerrainExport BiHeightmapTerrainPageSource : public BiTerrainPageSource
+    {
+    protected:
+        /// Is this input RAW?
+        bool mIsRaw;
+        /// Should we flip terrain vertically?
+        bool mFlipTerrain;
+        /// Image containing the source heightmap if loaded from non-RAW
+        Image mImage;
+        /// Arbitrary data loaded from RAW
+        MemoryDataStreamPtr mRawData;
+        /// The (single) terrain page this source will provide
+        BiTerrainPage* mPage;
+        /// Source file name
+        String mSource;
+        /// Manual size if source is RAW
+        uint mRawSize;
+        /// Manual bpp if source is RAW
+        uchar mRawBpp;
+        
+        /// Load a heightmap
+        void loadHeightmap(void);
+    public:
+        BiHeightmapTerrainPageSource();
+        ~BiHeightmapTerrainPageSource();
+        /// @see TerrainPageSource
+        void shutdown(void);
+        /// @see TerrainPageSource
+        void requestPage(ushort x, ushort y);
+        /// @see TerrainPageSource
+        void expirePage(ushort x, ushort y);
+        /// @see TerrainPageSource
+        void initialise(BiTerrainSceneManager* tsm, 
+            uint tileSize, uint pageSize, bool asyncLoading, 
+            BiTerrainPageSourceOptionList& optionList);
+    };
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBihRenderable.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBihRenderable.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBihRenderable.h	(revision 2349)
@@ -0,0 +1,128 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBihRenderable_H__
+#define _OgreBihRenderable_H__
+
+#include "OgreBiHierarchy.h"
+
+namespace Ogre
+{
+
+	// interface which must be implemented by all objects which desire to be
+	// placed in the kd-tree
+	class BihRenderable
+	{
+	public:
+		BihRenderable():mSide(BihPlaneEvent::PES_BOTH), mClassified(false), mLastQueued(0), mBiHierarchy(0) {};
+		virtual ~BihRenderable()
+		{
+			if (mBiHierarchy)
+				mBiHierarchy->remove(this);
+		}
+
+		// gather the information required for the creation of the kd-tree
+		virtual void computeScene(BihPlaneEventList& events, AxisAlignedBox& aabb, int& nObjects, bool includeChildren = true) = 0;
+
+		// put all objects this element holds in the renedering queue
+		virtual void queueObjects(Camera* cam, RenderQueue* queue, bool onlyShadowCasters) = 0;
+
+		// place all entities in geometry queue (for CHC)
+		virtual void getGeometryList(GeometryVector *geometryList) = 0;
+
+		// return a bounding box enclosing all objects
+		virtual AxisAlignedBox getBoundingBox() const = 0;
+
+		// TODO: reconsider getters/setters !!!
+		inline bool isClassified()
+		{
+			return mClassified;
+		};
+		inline void setClassified(bool q)
+		{
+			mClassified = q;
+		};
+
+		inline BihPlaneEvent::Side getSide()
+		{
+			return mSide;
+		};
+		inline void setSide(BihPlaneEvent::Side s)
+		{
+			mSide = s;
+		};
+
+		// funcions for attachment/detachment of renderables to/from the kd-tree
+		inline bool isAttached()
+		{
+			return mLeaves.size() != 0;
+		};
+		// the following functions should work in O(log N)
+		inline bool isAttached(BiHierarchy::LeafPtr leaf)
+		{
+			return mLeaves.find(leaf) != mLeaves.end();
+		};
+		inline bool attachTo(BiHierarchy::LeafPtr leaf, BiHierarchy * BiHierarchy)
+		{
+			if (mBiHierarchy == 0 || mBiHierarchy == BiHierarchy)
+				mBiHierarchy = BiHierarchy;
+			else
+				return false;
+
+			BiHierarchy::LeafSet::_Pairib p = mLeaves.insert(leaf);
+			return p.second;
+		};
+		inline bool detachFrom(BiHierarchy::LeafPtr leaf)
+		{
+			bool success = (mLeaves.erase(leaf) == 1);
+			if (mLeaves.size() == 0)
+				mBiHierarchy = 0;
+
+			return success;
+		};
+
+		inline bool isQueued(unsigned long currentFrame, Camera * currentCam)
+		{
+			if (mLastQueued == currentFrame && mLastCam == currentCam)
+			{
+				return true;
+			}
+			else
+			{
+				mLastQueued = currentFrame;
+				mLastCam = currentCam;
+				return false;
+			}
+		};
+
+		BiHierarchy::LeafSet& getLeaves()
+		{
+			return mLeaves;
+		};
+
+	protected:
+		// number of the frame in which this renderable was last queued for rendering
+		unsigned long mLastQueued;
+		// the camera for which this renderable was last queued for rendering
+		Camera * mLastCam;
+		
+		// BiHierarchy to which this renderable is attached
+		BiHierarchy * mBiHierarchy;
+		// BiHierarchy leaves which overlap this renderable
+		BiHierarchy::LeafSet mLeaves;
+
+		// Flag for the SAH determining the "cheaper" side of the split plane
+		BihPlaneEvent::Side mSide;
+		// Flag for the SAH which marks if this renderable was already placed in the list after a split
+		bool mClassified;
+	}; // class BihRenderable
+
+} // namespace Ogre
+
+#endif // _OgreBihRenderable_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneManager.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneManager.h	(revision 2349)
@@ -0,0 +1,351 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _BiHierarchySceneManager_H__
+#define _BiHierarchySceneManager_H__
+
+#include <OgreSceneManager.h>
+#include <VisibilityManager.h>
+#include <ViewCellsManager.h>
+
+#include "OgreBiHierarchy.h"
+#include "OgreBiHierarchyCamera.h"
+#include "OgreBiHierarchyInterface.h"
+
+#define BiHierarchy_MAX_DEPTH 12
+
+namespace Ogre
+{
+
+class BiHierarchySceneNode;
+
+class BiHierarchySceneManager : public SceneManager
+{
+public:
+	BiHierarchySceneManager(const String& name, GtpVisibility::VisibilityManager *vm);
+	~BiHierarchySceneManager(void);
+
+	virtual const String& getTypeName(void) const;
+
+	//typedef std::list<BiHierarchySceneNode *> NodeList;
+	//typedef std::list<WireBoundingBox *> BoxList;
+
+	/************************************************************************/
+	/* Functions overridden form SceneManager for BiHierarchy                    */
+	/************************************************************************/
+
+	/** Override from Scenemanager to create Camera as instance of BiHierarchyCamera
+	*/
+	virtual Camera* createCamera(const String& name);
+
+	/** Override from SceneManager to create SceneNodes as instance of BiHierarchySceneNode
+	*/
+	virtual SceneNode* createSceneNode(void);
+	/** Override from SceneManager to create SceneNodes as instance of BiHierarchySceneNode
+	*/
+	virtual SceneNode* createSceneNode(const String& name);
+
+	/** Override from Scenemanager, employ kd-tree based culling or CHC
+	*/
+	virtual void _findVisibleObjects(Camera *cam, bool onlyShadowCasters);
+
+	virtual bool setOption(const String& strKey, const void* pValue);
+	virtual bool getOption(const String& strKey, void* pDestValue);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Overide from scene manager to destroy BiHierarchy properly (before the scene graph is destroyed)
+	*/
+	virtual void clearScene();
+
+	/************************************************************************/
+	/* Functions overridden from SceneManager for CHC                       */
+	/************************************************************************/
+
+	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
+	*/
+	Entity* createEntity(const String& entityName, const String& meshName);
+
+	/** Override from scene manager to set up culling manager
+	*/
+	virtual void _updateSceneGraph(Camera* cam);
+
+	/** Override from SceneManager, employ normal rendering or CHC
+	*/
+	virtual void _renderVisibleObjects();
+
+	/** Override pass so we can do the z-fail pass.
+	*/
+	virtual const Pass* _setPass(const Pass* pass, bool evenIfSuppressed = false);
+
+	/** Render a queue group. 
+	Override so we can handle delayed rendering of transparent objects
+	*/
+	void renderBasicQueueGroupObjects(RenderQueueGroup* pGroup, 
+		QueuedRenderableCollection::OrganisationMode om);
+
+	/** Override from scene manager
+	*/
+	void _renderQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+
+	/** Override from SceneManager so we can skip all but first pass for depth pass. 
+	*/
+	bool validatePassForRendering(Pass* pass);
+
+	/** Override from SceneManager because idontknow
+	*/
+	void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+	void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup,
+		QueuedRenderableCollection::OrganisationMode om);
+
+
+	/************************************************************************/
+	/* Functions which are specific to the BiHierarchy                           */
+	/************************************************************************/
+	
+	/** Update the BiHierarchy with the node (more or less disabled now)
+	*/
+	virtual void _updateNode(BiHierarchySceneNode *node); // TODO: 
+
+	/** Show or hide the bounding boxes of BiHierarchy nodes - obsolete, use options
+	*/
+	virtual void setShowBoxes(bool showboxes);
+	/** Tell if show boxes is enabled - obsolete, use options
+	*/
+	virtual bool getShowBoxes(void) const;
+
+	/** Recurses the BiHierarchy, adding any nodes intersecting with the 
+	box/sphere/volume/ray into the given list.
+	It ignores the exclude scene node.
+	*/
+	void findNodesIn( const AxisAlignedBox &box, std::list < SceneNode * > &list, SceneNode *exclude = 0 )
+	{
+		if (mBiHierarchy)
+			mBiHierarchy->findNodesIn(box, list, exclude);
+	}
+	void findNodesIn( const Sphere &sphere, std::list < SceneNode * > &list, SceneNode *exclude = 0 )
+	{
+		if (mBiHierarchy)
+			mBiHierarchy->findNodesIn(sphere, list, exclude);
+	}
+	void findNodesIn( const PlaneBoundedVolume &volume, std::list < SceneNode * > &list, SceneNode *exclude=0 )
+	{
+		if (mBiHierarchy)
+			mBiHierarchy->findNodesIn(volume, list, exclude);
+	}
+	void findNodesIn( const Ray &ray, std::list < SceneNode * > &list, SceneNode *exclude=0 )
+	{
+		if (mBiHierarchy)
+			mBiHierarchy->findNodesIn(ray, list, exclude);
+	}
+
+	/************************************************************************/
+	/* Functions for PVS                                                    */
+	/************************************************************************/
+	/** Loads view cells for this particular scene.
+	*/
+	bool LoadViewCells(const String &filename);
+
+	/************************************************************************/
+	/* Functions for CHC                                                    */
+	/************************************************************************/
+
+	/** Render a list of scenenodes
+	*/
+	//virtual void _renderNodes(const BihRenderableList& nodelist, Camera * cam,
+	//	bool onlyShadowCasters, int leavePassesInQueue);
+	virtual void _renderNode(BiHierarchy::NodePtr node, Camera * cam,
+		bool onlyShadowCasters, int leavePassesInQueue);
+
+	/** Sets the visibility manager.
+	@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+
+	/** Returns pointer to visibility manager.
+	*/
+	GtpVisibility::VisibilityManager *GetVisibilityManager();
+
+	/** Returns hierarchy interface.
+	*/
+	BiHierarchyInterface *GetHierarchyInterface();
+
+protected:
+	/** Creates material for depth pass, e.g., a pass that only fills the depth buffer. 
+	*/
+	void InitDepthPass();
+	/** Creates material for item buffer. 
+	*/
+	void InitItemBufferPass();
+	/** Fills render queue so that a visualization can be rendered. 
+	*/
+	void PrepareVisualization(Camera *cam);
+	/** Initialises necessary parameters for hierarchical visibility culling.
+	*/
+	void InitVisibilityCulling(Camera *cam);
+
+	/** Writes out stats into the Ogre log file.
+	*/
+	void WriteLog();
+
+	/************************************************************************/
+	/* Functions for PVS                                                    */
+	/************************************************************************/
+	/** Loads / unloads pvs of the view cell to set the visibility in the scene.
+	*/
+	void applyViewCellPvs(GtpVisibilityPreprocessor::ViewCell *vc, const bool load);
+
+	/** updates pvs in current frame.
+	*/
+	void updatePvs(Camera *cam);
+
+	/** Sets all objects invisible.
+	*/
+	void SetObjectsVisible(const bool visible);
+
+	/************************************************************************/
+	/* CHC-specific options & members                                       */
+	/************************************************************************/
+	// pointer to the visibility manager
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+
+	// the hierarchy interface for CHC
+	BiHierarchyInterface *mHierarchyInterface;
+
+	// if hierarchical culling is currently in use
+	bool mIsHierarchicalCulling;
+
+	// if a visualization of the hierarchical culling is shown
+	bool mShowVisualization;
+	
+	// if the culled nodes are indicated in the visualization
+	bool mVisualizeCulledNodes;
+
+	// consecutive number for sub-entities
+	int mCurrentEntityId;
+
+	// flag for passes which should not be deleted from queue during first traversal
+	int mLeavePassesInQueue;
+
+	// if symbols for the nodes are shown in the visualization
+	bool mRenderNodesForViz;
+	// if content of the nodes is shown in the visualization
+	bool mRenderNodesContentForViz;
+	/// render transparents after the hierarchical traversal
+	bool mDelayRenderTransparents;
+	
+	// if transparent object are considered for item buffer visibility
+	bool mRenderTransparentsForItemBuffer;
+	// Always execute the vertex program of a pass, e.g., for the depth pass or item buffer
+	bool mExecuteVertexProgramForAllPasses;
+
+	// the depth pass (no lighting, just filling the depth buffer)
+	Pass *mDepthPass;
+	// use a depth pass (i.e., fill only the depth buffer in the first pass)
+	bool mUseDepthPass;
+	// flag indicating if we currently render the depth pass
+	bool mIsDepthPassPhase;
+	// if depth write should be enabled
+	bool mEnableDepthWrite;
+	// if transparents are skipped during rendering
+	bool mSkipTransparents;
+	// the item buffer pass (render items color-coded)
+	Pass *mItemBufferPass;
+	// if we use an item buffer for rendering (i.e., object ids as color codes
+	bool mUseItemBuffer;
+	// if we currently render the item buffer 
+	bool mIsItemBufferPhase;
+	// delete or clear the renderqueue after each rame?
+	bool mDeleteQueueAfterRendering;
+
+	// remember visited scene nodes for viz
+	BiHierarchy::NodeList mVisibleNodes;
+
+
+	/************************************************************************/
+	/* Bih specific options & members                                   */
+	/************************************************************************/
+
+
+	// maximum depth of the BiHierarchy
+	int mMaxDepth;
+
+	// the BiHierarchy which holds the scene
+	BiHierarchy *mBiHierarchy;
+
+	// if bounding boxes of BiHierarchy nodes are shown
+	bool mShowBoxes;
+	// bounding boxes of kd nodes will be highlighted on this level of the kd tree
+	int mHiLiteLevel;
+	// if all bounding boxes shall be displayed, not only the highlighted level
+	bool mShowAllBoxes;
+	// visualize BiHierarchy nodes or bounding boxes of objects in nodes
+	bool mShowNodes;
+
+	// vis mode
+	bool mEnhancedVisiblity;
+
+	// the method/algorithm used when rendering the scene
+	BiHierarchy::RenderMethod mRenderMethod;
+
+	// the method of building the tree
+	BiHierarchy::BuildMethod mBuildMethod;
+
+	/************************************************************************/
+	/* PVS specific options and members                                     */
+	/************************************************************************/
+
+	// The view cell manager
+	GtpVisibilityPreprocessor::ViewCellsManager *mViewCellsManager;
+
+	/// Used to assign Ogre meshes to view cell entries.
+	GtpVisibilityPreprocessor::ObjectContainer mObjects;
+
+	GtpVisibilityPreprocessor::ViewCell *mElementaryViewCell;
+	GtpVisibilityPreprocessor::ViewCell *mCurrentViewCell;
+
+	/// If view cells are loaded.
+	bool mViewCellsLoaded;
+
+	/// If view cells are used.
+	bool mUseViewCells;
+
+	/// if the view cells are filtered
+	bool mUseVisibilityFilter;
+};
+
+
+
+/// Factory for BiHierarchySceneManager
+class BiHierarchySceneManagerFactory: public SceneManagerFactory
+{
+protected:
+	void initMetaData(void) const;
+	GtpVisibility::VisibilityManager *visManager;
+public:
+	BiHierarchySceneManagerFactory(GtpVisibility::VisibilityManager * vm)
+	{
+		visManager = vm;
+	}
+	~BiHierarchySceneManagerFactory(void) {};
+	/// Factory type name
+	static const String FACTORY_TYPE_NAME;
+	SceneManager* createInstance(const String& instanceName);
+	void destroyInstance(SceneManager* instance);
+};
+
+} // namespace Ogre
+
+#endif // _BiHierarchySceneManager_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPrerequisites.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPrerequisites.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPrerequisites.h	(revision 2349)
@@ -0,0 +1,57 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __BiTerrainPrerequisites_H__
+#define __BiTerrainPrerequisites_H__
+
+#include "OgrePrerequisites.h"
+
+//-----------------------------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------------------------
+
+namespace Ogre
+{
+    class BiTerrainSceneManager;
+    class BiTerrainPageSource;
+    class BiTerrainRenderable;
+    class BiTerrainPage;
+}
+//-----------------------------------------------------------------------
+// Windows Settings
+//-----------------------------------------------------------------------
+
+#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 
+#   ifdef PLUGIN_KD_TERRAIN_EXPORTS 
+#       define _OgreBiTerrainExport __declspec(dllexport) 
+#   else 
+#       define _OgreBiTerrainExport __declspec(dllimport) 
+#   endif 
+#else 
+#   define _OgreBiTerrainExport 
+#endif 
+
+#endif
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainVertexProgram.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainVertexProgram.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainVertexProgram.h	(revision 2349)
@@ -0,0 +1,222 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __BiTerrainVertexProgram_H__
+#define __BiTerrainVertexProgram_H__
+
+#include "OgrePrerequisites.h"
+#include "OgreCommon.h"
+#include "OgreString.h"
+
+namespace Ogre {
+
+    /*
+    Static class containing the source to vertex programs used to 
+    morph the terrain LOD levels. The programs are generated from 
+    the following Cg:
+    @code 	
+    // No fog morphing terrain
+    void terrain_vp(
+	    float4 position : POSITION,
+	    float2 uv1   	: TEXCOORD0,
+	    float2 uv2	 	: TEXCOORD1,
+	    float delta     : BLENDWEIGHT,
+
+	    out float4 oPosition : POSITION,
+	    out float2 oUv1		 : TEXCOORD0,
+	    out float2 oUv2		 : TEXCOORD1,
+	    out float4 colour    : COLOR,
+	    uniform float4x4 worldViewProj,
+	    uniform float morphFactor
+	    )
+    {
+	    // Apply morph
+	    position.y = position.y + (delta.x * morphFactor);
+	    // world / view / projection
+	    oPosition = mul(worldViewProj, position);
+	    // Main texture coords
+	    oUv1 = uv1;
+	    // Detail texture coords
+	    oUv2 = uv2;
+	    // Full bright (no lighting)
+	    colour = float4(1,1,1,1);
+    }
+
+
+    // Linear fogged morphing terrain
+    void terrain_vp_linear(
+	    float4 position : POSITION,
+	    float2 uv1   	: TEXCOORD0,
+	    float2 uv2	 	: TEXCOORD1,
+	    float delta     : BLENDWEIGHT,
+
+	    out float4 oPosition : POSITION,
+	    out float2 oUv1		 : TEXCOORD0,
+	    out float2 oUv2		 : TEXCOORD1,
+	    out float4 colour    : COLOR,
+	    out float fog		 : FOG,
+	    uniform float4x4 worldViewProj,
+	    uniform float morphFactor
+	    )
+    {
+	    // Apply morph
+	    position.y = position.y + (delta.x * morphFactor);
+	    // world / view / projection
+	    oPosition = mul(worldViewProj, position);
+	    // Main texture coords
+	    oUv1 = uv1;
+	    // Detail texture coords
+	    oUv2 = uv2;
+	    // Full bright (no lighting)
+	    colour = float4(1,1,1,1);
+	    // Fog 
+	    // f = end - camz / end - start
+	    // when start / end has been set, fog value is distance
+	    fog = oPosition.z;
+    }
+
+
+    // Exp fogged morphing terrain
+    void terrain_vp_exp(
+	    float4 position : POSITION,
+	    float2 uv1   	: TEXCOORD0,
+	    float2 uv2	 	: TEXCOORD1,
+	    float delta     : BLENDWEIGHT,
+
+	    out float4 oPosition : POSITION,
+	    out float2 oUv1		 : TEXCOORD0,
+	    out float2 oUv2		 : TEXCOORD1,
+	    out float4 colour    : COLOR,
+	    out float fog		 : FOG,
+	    uniform float4x4 worldViewProj,
+	    uniform float morphFactor,
+	    uniform float fogDensity)
+    {
+	    // Apply morph
+	    position.y = position.y + (delta.x * morphFactor);
+	    // world / view / projection
+	    oPosition = mul(worldViewProj, position);
+	    // Main texture coords
+	    oUv1 = uv1;
+	    // Detail texture coords
+	    oUv2 = uv2;
+	    // Full bright (no lighting)
+	    colour = float4(1,1,1,1);
+	    // Fog 
+	    // f = 1 / e ^ (camz x density)
+	    // note pow = exp(src1 * log(src0)).
+	    fog = 1 / (exp((oPosition.z * fogDensity) * log(2.718281828)));
+    }
+
+
+    // Exp2 fogged morphing terrain
+    void terrain_vp_exp2(
+	    float4 position : POSITION,
+	    float2 uv1   	: TEXCOORD0,
+	    float2 uv2	 	: TEXCOORD1,
+	    float delta     : BLENDWEIGHT,
+
+	    out float4 oPosition : POSITION,
+	    out float2 oUv1		 : TEXCOORD0,
+	    out float2 oUv2		 : TEXCOORD1,
+	    out float4 colour    : COLOR,
+	    out float fog		 : FOG,
+	    uniform float4x4 worldViewProj,
+	    uniform float morphFactor,
+	    uniform float fogDensity)
+    {
+	    // Apply morph
+	    position.y = position.y + (delta.x * morphFactor);
+	    // world / view / projection
+	    oPosition = mul(worldViewProj, position);
+	    // Main texture coords
+	    oUv1 = uv1;
+	    // Detail texture coords
+	    oUv2 = uv2;
+	    // Full bright (no lighting)
+	    colour = float4(1,1,1,1);
+	    // Fog 
+	    // f = 1 / e ^ (camz x density)^2
+	    // note pow = exp(src1 * log(src0)).
+	    float src1 = oPosition.z * 0.002;
+	    fog = 1 / (exp((src1*src1) * log(2.718281828f)));
+    }
+
+	// Shadow receiver vertex program
+    void terrain_shadow_receiver_vp(
+	    float4 position : POSITION,
+	    float2 uv1   	: TEXCOORD0,
+	    float2 uv2	 	: TEXCOORD1,
+	    float delta     : BLENDWEIGHT,
+
+	    out float4 oPosition : POSITION,
+	    out float2 oUv1		 : TEXCOORD0,
+	    out float4 colour    : COLOR,
+	    uniform float4x4 worldViewProj,
+		uniform float4x4 world,
+	    uniform float4x4 textureViewProj,
+	    uniform float morphFactor
+	    )
+    {
+	    // Apply morph
+	    position.y = position.y + (delta.x * morphFactor);
+	    // world / view / projection
+	    oPosition = mul(worldViewProj, position);
+		
+	    // Main texture coords
+		float4 worldpos = mul(world, position);
+	    float4 projuv = mul(textureViewProj, worldpos);
+		oUv1.xy = projuv.xy / projuv.w;
+	    // Full bright (no lighting)
+	    colour = float4(1,1,1,1);
+    }
+
+    @endcode
+    */
+    class BiTerrainVertexProgram
+    {
+    private:
+        static String mNoFogArbvp1;
+        static String mLinearFogArbvp1;
+        static String mExpFogArbvp1;
+        static String mExp2FogArbvp1;
+		static String mShadowReceiverArbvp1;
+
+        static String mNoFogVs_1_1;
+        static String mLinearFogVs_1_1;
+        static String mExpFogVs_1_1;
+        static String mExp2FogVs_1_1;
+		static String mShadowReceiverVs_1_1;
+
+    public:
+        /// General purpose method to get any of the program sources
+        static const String& getProgramSource(FogMode fogMode, 
+			const String syntax, bool shadowReceiver = false);
+
+
+    };
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyInterface.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyInterface.h	(revision 2349)
@@ -0,0 +1,112 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBiHierarchyInterface_H_
+#define _OgreBiHierarchyInterface_H_
+
+#include "OgrePlatformHierarchyInterface.h"
+
+namespace Ogre
+{
+
+class BiHierarchySceneManager;
+
+class BiHierarchyInterface : public PlatformHierarchyInterface
+{
+public:
+	BiHierarchyInterface(BiHierarchySceneManager *sm, RenderSystem *rsys);
+
+	virtual ~BiHierarchyInterface() {};
+
+	/** Returns true if current node is leaf of the hierarchy. 
+	@param node hierarchy node
+	@returns true if node is leaf
+	*/
+	virtual bool IsLeaf(GtpVisibility::HierarchyNode *node) const;
+	/** Traverses and renders the hierarchy from the given node. 
+	@param node the hierarchy node
+	*/
+	virtual void TraverseNode(GtpVisibility::HierarchyNode *node);
+	/** Renders the given hierarchy node.
+	@param node current hierarchy node to be rendered
+	*/
+	virtual void RenderNode(GtpVisibility::HierarchyNode *node);
+	/** Pulls up the visibility from the current node recursively to the parent nodes. 
+	@param node the current node 
+	*/
+	virtual void PullUpVisibility(GtpVisibility::HierarchyNode *node) const;
+
+	/** Returns distance of the node to the view plane.
+	@param node the hierarchy node
+	*/			
+	virtual float GetSquaredDistance(GtpVisibility::HierarchyNode *node) const;
+	/** Returns pointer to bounding box of node.
+	@param node current hierarchy node
+	@returns bounding box of current node
+	*/
+	virtual AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node);
+	/** Returns true if there is renderable geometry attached to this node
+	@param node the current node
+	@returns if the node has renderable geometry
+	*/
+	virtual bool HasGeometry(GtpVisibility::HierarchyNode *node) const;
+	/** Sets the visible flag for this node.
+	@param node the current node
+	@param visible the visible flag
+	*/
+	virtual void SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const;
+	/** Returns true if node has the visible flag set. See set
+	*/
+	virtual bool IsNodeVisible(GtpVisibility::HierarchyNode *node) const;
+	/** Sets the last visited frame id for this node.
+	@param node the current node
+	@param frameId the current frame id
+	*/
+	virtual void SetLastVisited(GtpVisibility::HierarchyNode *node, const unsigned int frameId) const;
+	/** Returns frame id when this node was last visited by the traverser. See set
+	*/
+	virtual unsigned int LastVisited(GtpVisibility::HierarchyNode *node) const;
+
+
+	/** Visualization of a culled node, dependent on the culling type. 
+	@param node the hierarchy node to be visualized
+	@param type can be one of FRUSTUM_CULLED, QUERY_CULLED
+	*/
+	virtual void VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+		GtpVisibility::CullingType type) const;
+
+
+	/** Returns the geometry of a given hierarchy node. 
+	@param node the hierarchy node containing the geometry
+	@param geometryList geometry is returned in this list
+	@param includeChildren if the geometry of the children should be taken into account
+	*/
+	virtual void GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
+		GeometryVector *geometryList, 
+		bool includeChildren);
+	void DetermineFullVisibility(GtpVisibility::HierarchyNode *node) const {}
+	
+	bool IsNodeFullyVisible(GtpVisibility::HierarchyNode *node) const { return false;}
+
+	void CollectLeaves(GtpVisibility::HierarchyNode *root, 
+					   GtpVisibility::HierarchyNodeContainer &nodes) {};
+
+	void RenderNodeRecursive(GtpVisibility::HierarchyNode *node) {};
+
+	GtpVisibility::HierarchyNode *GetRandomLeaf(GtpVisibility::HierarchyNode *root) { return NULL;}
+
+
+};
+
+
+
+
+} // namespace Ogre
+
+#endif // _OgreBiHierarchyInterface_H_
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPage.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPage.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPage.h	(revision 2349)
@@ -0,0 +1,90 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __TerrainPage_H__
+#define __TerrainPage_H__
+
+#include "OgreBiTerrainPrerequisites.h"
+#include "OgreRenderQueue.h"
+
+namespace Ogre {
+
+    /** Groups a number of TerrainRenderables (tiles) into a page, which is
+        the unit of loading / unloading.
+    @remarks
+        Note that this class, whilst holding onto TerrainRenderable instances, 
+        does not actually process or initialise them itself - this is 
+        intentional so the TerrainPageSource which is providing the tiles
+        is able to load and prepare each renderable incrementally if required, 
+        thus avoiding any 'single hit' load methods for the page.
+    @par
+        All this class does do is pre-create a 2D vector of 'slots' in which 
+        to place the TerrainRenderable pointers, which it does on 
+        construction. Note that this structure is public to allow completely
+        free access to users of this class.
+    */
+    class _OgreBiTerrainExport BiTerrainPage
+    {
+    public:
+        typedef std::vector < BiTerrainRenderable * > BiTerrainRow;
+        typedef std::vector < BiTerrainRow > BiTerrain2D;
+        
+        /// 2-dimensional vector of tiles, pre-allocated to the correct size
+        BiTerrain2D tiles;
+        /// The number of tiles across a page
+        unsigned short tilesPerPage;
+        /// The scene node to which all the tiles for this page are attached
+        SceneNode* pageSceneNode;
+
+        /** The main constructor. 
+        @param numTiles The number of terrain tiles (TerrainRenderable)
+            across (and down) a page
+        */
+        BiTerrainPage(unsigned short numTiles);
+
+        /** Destructor, will organise the deletion of pages
+        */
+        virtual ~BiTerrainPage();
+        /** After TerrainRenderables have been populated, this method
+            adds the neighbour links. 
+        @remarks
+            Should be called before adding the page to the scene manager.
+        */
+        void linkNeighbours(void);
+
+        /** Returns the TerrainRenderable that contains the given pt.
+        If no tile exists at the point, it returns 0;
+        */
+        BiTerrainRenderable * getTerrainTile( const Vector3 & pt );
+
+		/** Sets the render queue group which the tiles should be rendered in. */
+		void setRenderQueue(uint8 qid);
+
+
+    };
+
+
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneNode.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneNode.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchySceneNode.h	(revision 2349)
@@ -0,0 +1,54 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBiHierarchySceneNode_H__
+#define _OgreBiHierarchySceneNode_H__
+
+#include <OgreSceneNode.h>
+#include "OgreBihRenderable.h"
+
+namespace Ogre
+{
+
+	class BiHierarchySceneNode : public SceneNode, public BihRenderable
+	{
+	public:
+		BiHierarchySceneNode(SceneManager *creator):
+		  SceneNode(creator) {};
+
+		BiHierarchySceneNode(SceneManager *creator, const String& name):
+		  SceneNode(creator, name) {};
+
+		~BiHierarchySceneNode() {};
+
+		// gather info for kd-tree creation
+		virtual void computeScene(BihPlaneEventList& events, AxisAlignedBox& aabb, int& nObjects, bool includeChildren = true);
+
+		// add all contained objects to render queue
+		virtual void queueObjects(Camera* cam, RenderQueue* queue, bool onlyShadowCasters);
+
+		// place all entities in geometry queue (for CHC)
+		virtual void getGeometryList(GeometryVector *geometryList);
+
+		// return a bounding box enclosing all objects
+		virtual AxisAlignedBox getBoundingBox(void) const;
+
+		// DEBUG
+		String dumpToString(void);
+	protected:
+		virtual void _updateBounds(void);
+
+		typedef std::set<String> StringSet;
+
+		static StringSet& getExcludedMovables(void);
+	};
+
+} // namespace Ogre
+
+#endif // _OgreBiHierarchySceneNode_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBvHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBvHierarchyInterface.h	(revision 2292)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBvHierarchyInterface.h	(revision 2349)
@@ -106,4 +106,6 @@
 };
 
+
+
 } // namespace Ogre
 
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainSceneManager.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainSceneManager.h	(revision 2349)
@@ -0,0 +1,310 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _BiTreeTerrainSceneManager_H__
+#define _BiTreeTerrainSceneManager_H__
+
+#include <OgreIteratorWrappers.h>
+
+#include "OgreBiTerrainPrerequisites.h"
+#include "OgreBiTerrainPageSource.h"
+#include "OgreBiTerrainRenderable.h"
+
+#include "OgreBiHierarchySceneManager.h"
+
+
+namespace Ogre
+{
+
+typedef std::vector < BiTerrainPage * > BiTerrainPageRow;
+typedef std::vector < BiTerrainPageRow > BiTerrainPage2D;
+
+/** Default implementation of RaySceneQuery. */
+// TODO: all scene queries in Bi-tree
+class _OgreBiTerrainExport BiTerrainRaySceneQuery : public DefaultRaySceneQuery
+{
+protected:
+	WorldFragment mWorldFrag;
+public:
+	BiTerrainRaySceneQuery(SceneManager* creator);
+	~BiTerrainRaySceneQuery();
+
+	/** See RayScenQuery. */
+	void execute(RaySceneQueryListener* listener);
+};
+
+class BiTerrainSceneManager : public BiHierarchySceneManager
+{
+public:
+	BiTerrainSceneManager(const String& name, GtpVisibility::VisibilityManager *vm);
+	~BiTerrainSceneManager(void);
+
+	virtual const String& getTypeName(void) const;
+
+	/************************************************************************/
+	/* Functions overriden from (BiTree)SceneManager                        */
+	/************************************************************************/
+
+	/** Loads the terrain using parameters int he given config file. */
+	void setWorldGeometry( const String& filename );
+	/** Loads the terrain using parameters in the given config file (contained 
+	in a stream). */
+	virtual void setWorldGeometry(DataStreamPtr& stream, 
+		const String& typeName = StringUtil::BLANK);
+
+	/** Sets the given option for the SceneManager.
+	@remarks
+	Options are (in addition to those supported by superclasses):
+	"PageSize", int*;
+	"TileSize", int*; 
+	"PrimaryCamera, Camera*;
+	"MaxMipMapLevel", int*;
+	"Scale", Vector3 *;
+	"MaxPixelError", int*;
+	"UseTriStrips", bool*;
+	"VertexProgramMorph", bool*;
+	"DetailTile", int*;
+	"LodMorphStart", Real*;
+	"VertexNormals", bool*;
+	"VertexColours", bool*;
+	"MorphLODFactorParamName", String*;
+	"MorphLODFactorParamIndex", size_t*;
+	"CustomMaterialName", String*;
+	"WorldTexture", String*;
+	"DetailTexture", String*;
+	*/
+	virtual bool setOption(const String& strKey, const void* pValue);
+
+
+	// Overridden from Bitree scene mananger
+	//void _findVisibleObjects(Camera *cam, bool onlyShadowCasters);
+	// Overridden from Bitree scene manager
+	void _renderScene(Camera *cam, Viewport *vp, bool includeOverlays);
+	/** Overridden to user _renderVisibleObjects from BiTreeSceneManager */
+	//virtual void _renderVisibleObjects( void );
+	/** Overridden from SceneManager */
+	void setWorldGeometryRenderQueue(uint8 qid);
+
+	/** Overridden in order to store the first camera created as the primary
+	one, for determining error metrics and the 'home' terrain page.
+	*/
+	Camera* createCamera( const String &name );
+
+
+	/** Creates a RaySceneQuery for this scene manager. */
+	RaySceneQuery* 
+		createRayQuery(const Ray& ray, unsigned long mask = 0xFFFFFFFF);
+
+	/** Overide from scene manager to destroy Bitree properly (before the scene graph is destroyed)
+	*/
+	virtual void clearScene();
+
+	/************************************************************************/
+	/* Functions for terrain rendering                                      */
+	/************************************************************************/
+	/** Returns the height at the given terrain coordinates. */
+	float getHeightAt( float x, float y );
+
+	bool intersectSegment( const Vector3 & start, const Vector3 & end, Vector3 * result );
+
+	/** Sets the texture to use for the main world texture. */
+	void setWorldTexture(const String& textureName);
+	/** Sets the texture to use for the detail texture. */
+	void setDetailTexture(const String& textureName);
+	/** Sets the number of times per tile the detail texture should be repeated. */
+	void setDetailTextureRepeat(int repeat);
+	/** Sets the dimensions of each tile (must be power of 2 + 1) */
+	void setTileSize(int size); 
+	/** Sets the dimensions of each page (must be power of 2 + 1) */
+	void setPageSize(int size); 
+	/** Sets the maximum screen space pixel error.  */
+	void setMaxPixelError(int pixelError); 
+	/** Sets how to scale the terrain data. */
+	void setScale(const Vector3& scale);
+	/** Sets the maximum geomipmap level to allow. */
+	void setMaxGeoMipMapLevel(int maxMip);
+
+	/** Gets the texture to use for the main world texture. */
+	const String& getWorldTexture(void) { return mWorldTextureName; }
+	/** Gets the texture to use for the detail texture. */
+	const String& getDetailTexture(void) { return mDetailTextureName; }
+	/** Gets the number of times per tile the detail texture should be repeated. */
+	int getDetailTextureRepeat(void);
+	/** Gets the dimensions of each tile (must be power of 2 + 1) */
+	int getTileSize(void); 
+	/** Gets the dimensions of each page (must be power of 2 + 1) */
+	int getPageSize(void); 
+	/** Gets the maximum screen space pixel error.  */
+	int getMaxPixelError(void); 
+	/** Gets how to scale the terrain data. */
+	const Vector3& getScale(void);
+	/** Gets the maximum geomipmap level to allow. */
+	int getMaxGeoMipMapLevel(void);
+
+
+	/** Sets whether the terrain should use triangle strips or not.	*/
+	void setUseTriStrips(bool useStrips);
+	/** Sets whether or not terrain tiles should be morphed between LODs
+	(NB requires vertex program support). */
+	void setUseLODMorph(bool useMorph);
+	/** Sets whether vertex normals will be generated for the terrain. */
+	void setUseVertexNormals(bool useNormals);
+	/** Sets whether vertex colours will be used. */
+	void setUseVertexColours(bool useColours);
+
+	/** Sets the name of a custom material to use to shade the landcape. */
+	void setCustomMaterial(const String& materialName);
+	/** Sets the name of the vertex program parameter to which to pass the
+	LOD morph factor. */
+	void setCustomMaterialMorphFactorParam(const String& paramName);
+	/** Sets the index of the vertex program parameter to which to pass the
+	LOD morph factor. */
+	void setCustomMaterialMorphFactorParam(uint paramIndex);
+	/** Sets the distance at which the LOD will start to morph downwards, as
+	a proportion of the distance between the LODs. */
+	void setLODMorphStart(Real morphStart);
+
+	/** Returns the TerrainRenderable that contains the given pt.
+	If no tile exists at the point, it returns 0;
+	*/
+	virtual BiTerrainRenderable * getTerrainTile( const Vector3 & pt );
+
+	/** Returns the TerrainPage that contains the given pt.
+	If no page exists at the point, it returns 0;
+	*/
+	virtual BiTerrainPage* getTerrainPage( const Vector3 & pt );
+
+	/// Gets the terrain options 
+	const BiTerrainOptions& getOptions(void) { return mOptions; }
+
+	/** Sets the 'primary' camera, i.e. the one which will be used to determine
+	the 'home' terrain page, and to calculate the error metrics. 
+	*/
+	virtual void setPrimaryCamera(const Camera* cam);
+	/// Internal map of page source name to page source
+	typedef std::map<String, BiTerrainPageSource*> BiPageSourceMap;
+
+	/// Iterator over all page sources
+	typedef ConstMapIterator<BiPageSourceMap> BiPageSourceIterator;
+	/// Get an iterator over all page sources
+	BiPageSourceIterator getPageSourceIterator(void);
+	/** Registers a TerrainPageSource class and associates it with a named type 
+	of source. */
+	virtual void registerPageSource(const String& typeName, BiTerrainPageSource* source);
+	/** Selects a given page source based on its type name. */
+	virtual void selectPageSource(const String& typeName, 
+		BiTerrainPageSourceOptionList& optionList);
+
+	/** Attaches a previously built page to the list of available pages. */
+	virtual void attachPage(ushort pageX, ushort pageZ, BiTerrainPage* page);
+	/// Get a pointer to the material being used for the terrain
+	MaterialPtr& getTerrainMaterial(void);
+
+	/// Get the SceneNode under which all terrain nodes are attached.
+	SceneNode* getTerrainRootNode(void) const { return mTerrainRoot; }
+
+	/// Get the shared list of indexes cached (internal use only)
+	BiTerrainBufferCache& _getIndexCache(void) {return mIndexCache;}
+
+	/// Get the shared level index list (internal use only)
+	LevelArray& _getLevelIndex(void) { return mLevelIndex; }
+
+	/// Get the current page count (internal use only)
+	uint _getPageCount(void) { return (uint)mTerrainPages.size(); }
+
+	/// Shutdown cleanly before we get destroyed
+	void shutdown(void);
+
+protected:
+	/// Validates that the size picked for the terrain is acceptable
+	bool _checkSize( int s )
+	{
+		for ( int i = 0; i < 16; i++ )
+		{
+			printf( "Checking...%d\n", ( 1 << i ) + 1 );
+
+			if ( s == ( 1 << i ) + 1 )
+				return true;
+		}
+
+		return false;
+
+	}
+
+	/// The node to which all terrain tiles are attached
+	SceneNode * mTerrainRoot;
+	/// Terrain size, detail etc
+	BiTerrainOptions mOptions;
+	/// Should we use an externally-defined custom material?
+	bool mUseCustomMaterial;
+	/// The name of the custom material to use
+	String mCustomMaterialName;
+	/// The name of the world texture
+	String mWorldTextureName;
+	/// The name of the detail texture
+	String mDetailTextureName;
+	/// Are we using a named parameter to hook up LOD morph?
+	bool mUseNamedParameterLodMorph;
+	/// The name of the parameter to send the LOD morph to
+	String mLodMorphParamName;
+	/// The index of the parameter to send the LOD morph to
+	uint mLodMorphParamIndex;
+	/// Whether paging is enabled, or whether a single page will be used
+	bool mPagingEnabled;
+	/// The number of pages to render outside the 'home' page
+	unsigned short mLivePageMargin;
+	/// The number of pages to keep loaded outside the 'home' page
+	unsigned short mBufferedPageMargin;
+	/// Grid of buffered pages
+	BiTerrainPage2D mTerrainPages;
+	//-- attributes to share across tiles
+	/// Shared list of index buffers
+	BiTerrainBufferCache mIndexCache;
+	/// Shared array of IndexData (reuse indexes across tiles)
+	LevelArray mLevelIndex;
+
+	/// Internal method for loading configurations settings
+	void loadConfig(DataStreamPtr& stream);
+
+	/// Sets up the terrain material
+	void setupTerrainMaterial(void);
+	/// Sets up the terrain page slots
+	void setupTerrainPages(void);
+	/// Initialise level indexes
+	void initLevelIndexes(void);
+	/// Destroy level indexes
+	void destroyLevelIndexes(void);
+
+
+	/// Map of source type -> TerrainPageSource
+	BiPageSourceMap mPageSources;
+	/// The currently active page source
+	BiTerrainPageSource* mActivePageSource;
+};
+
+/// Factory for BiTreeSceneManager
+class BiTerrainSceneManagerFactory : public SceneManagerFactory
+{
+protected:
+	typedef std::vector<BiTerrainPageSource*> BiTerrainPageSources;
+	BiTerrainPageSources mTerrainPageSources;
+	GtpVisibility::VisibilityManager *visManager;
+	void initMetaData(void) const;
+public:
+	BiTerrainSceneManagerFactory(GtpVisibility::VisibilityManager * vm);
+	~BiTerrainSceneManagerFactory(void);
+	/// Factory type name
+	static const String FACTORY_TYPE_NAME;
+	SceneManager* createInstance(const String& instanceName);
+	void destroyInstance(SceneManager* instance);
+};
+
+} // namespace Ogre
+
+#endif // _BiTreeTerrainSceneManager_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchy.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchy.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchy.h	(revision 2349)
@@ -0,0 +1,741 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBiHierarchy_H__
+#define _OgreBiHierarchy_H__
+
+#define BIHNODE_CAST(a) (static_cast<BiHierarchy::Node>(a))
+#define BIHBRANCH_CAST(a) (static_cast<BiHierarchy::Branch>(a))
+#define BIHLEAF_CAST(a) (static_cast<BiHierarchy::Leaf>(a))
+#define BIHNODEPTR_CAST(a) (static_cast<BiHierarchy::Node *>(a))
+#define BIHBRANCHPTR_CAST(a) (static_cast<BiHierarchy::Branch *>(a))
+#define BIHLEAFPTR_CAST(a) (static_cast<BiHierarchy::Leaf *>(a))
+
+#define BiHierarchy_LOGNAME "BiHierarchyBuild.log"
+
+#include <OgreAxisAlignedBox.h>
+#include <OgreWireBoundingBox.h>
+#include <OgrePlane.h>
+#include <OgreVector3.h>
+
+#include <OgreRoot.h>
+
+#include <stack>
+
+#include "OgreBiHierarchyCamera.h"
+#include "HierarchyInterface.h"
+#include "OgreKdTree.h"
+
+namespace Ogre
+{
+	class BiHierarchyCamera;
+	class BihRenderable;
+	struct BihSplitInfo;
+	
+	class BihPlaneEvent
+	{
+	public:
+		enum Type
+		{
+			PET_END,
+			PET_ON,
+			PET_START
+		};
+
+		enum Dimension
+		{
+			PED_X,
+			PED_Y,
+			PED_Z
+		};
+
+		enum Side
+		{
+			PES_LEFT = 0x01,
+			PES_RIGHT = 0x02,
+			PES_BOTH = PES_LEFT | PES_RIGHT
+		};
+
+		BihPlaneEvent(): mRenderable(0), mPosition(Vector3()), mDimension(PED_X), mType(PET_ON)
+		{ };
+
+		BihPlaneEvent(BihRenderable *rend, const Vector3& pos, BihPlaneEvent::Dimension dim, BihPlaneEvent::Type type):
+			mRenderable(rend), mPosition(pos), mDimension(dim), mType(type) 
+		{ };
+
+		~BihPlaneEvent() {};
+
+		// the less operator for plane events
+		// first sort by position, then by dimension and finally by type
+		bool operator < (const BihPlaneEvent& e) const
+		{
+			if(mPosition[mDimension] < e.mPosition[e.mDimension])
+			{
+				return true;
+			}
+
+			if(mPosition[mDimension] == e.mPosition[e.mDimension])
+			{
+				if (mDimension < e.mDimension)
+				{
+					return true;
+				}
+				if (mDimension == e.mDimension)
+				{
+					if (mType < e.mType)
+					{
+						return true;
+					}
+				}
+			}
+
+			return false;
+		};
+
+		// the equals operator for tree events
+		bool operator == (const BihPlaneEvent& e) const
+		{
+			return	(mPosition[mDimension] == e.mPosition[e.mDimension]) &&
+				(mDimension == e.mDimension) &&
+				(mType == e.mType);
+		};
+
+		bool equalsType(const BihPlaneEvent& e, BihPlaneEvent::Type t)
+		{
+			return	(mPosition[mDimension] == e.mPosition[e.mDimension]) &&
+				(mDimension == e.mDimension) &&
+				(mType == t);
+		};
+
+		void classify(const BihPlaneEvent& e, BihPlaneEvent::Side side, bool absolute);
+
+		BihPlaneEvent clip(AxisAlignedBox& box, BihPlaneEvent::Dimension dim);
+
+		Plane * getSplitPlane() const
+		{
+			Vector3 normal(0,0,0);
+			normal[mDimension] = 1;
+			return new Plane(normal, mPosition);
+		}
+
+		BihRenderable * getRenderable() const //??
+		{
+			return mRenderable;
+		};
+
+		BihPlaneEvent::Dimension getDimension() const //??
+		{
+			return mDimension;
+		};
+
+		// DEBUG
+		String print();
+	protected:
+		// event info
+		BihRenderable *			mRenderable;
+		Vector3					mPosition;
+		BihPlaneEvent::Dimension	mDimension;
+		BihPlaneEvent::Type		mType;
+
+		// ------------------------------------------------------------------------------//
+		// functions to determine the cost of splitting the node parent with the plane
+		// represented by this event
+		// TODO discuss if these functions really belong here, OO & SE - wise
+		// pros: convenient, don't have to pass internal data to the outside
+		// cons: BihSplitInfo ... 
+	public:
+		// compute "global" surface area heuristic (SAH) for the plane represented by this event
+		// use only with priority queue build method
+		void pqSAH(Real globalSA, Real parentSA, int nLeft, int nPlane, int nRight, AxisAlignedBox& parentBox, BihSplitInfo& split);
+		static Real pqSplitCost(Real p, Real pl, Real pr, int nLeft, int nRight, Real mu);
+
+		// compute the surface area heuristic (SAH) for the plane represented by this event
+		void SAH(const AxisAlignedBox& parent, int nLeft, int nPlane, int nRight, BihSplitInfo& split);
+		void SAH(const AxisAlignedBox& parent, int nLeft, int nPlane, int nRight, BihSplitInfo& split,AxisAlignedBox left,AxisAlignedBox right);
+
+		// the variables determining the cost of a branch traversal (KT) and a leaf intersection (KI)
+		static Real KT;
+		static Real KI;
+		// helper functions
+		static Real splitCost(Real pl, Real pr, int nLeft, int nRight);
+		static Real splitCost(Real pl, Real pr, int nLeft, int nRight, Real mu);
+		static Real surfaceArea(const AxisAlignedBox& box);
+		static Real lookupPenalty(Real p);
+	protected:
+		Real splitBox(const AxisAlignedBox& parent, AxisAlignedBox& left, AxisAlignedBox& right);
+	};
+
+	// Holds all the important information on a split
+	struct BihSplitInfo
+	{
+		AxisAlignedBox bleft;
+		AxisAlignedBox bright;
+		int nleft;
+		int nright;
+		Real cost;
+		BihPlaneEvent::Side side;
+		BihPlaneEvent event;
+
+		// DEBUG
+		String print();
+	};
+
+	typedef std::list<BihRenderable *> BihRenderableList;
+	typedef std::list<BihPlaneEvent> BihPlaneEventList;
+	
+	class BiHierarchy
+	{
+	protected:
+		class Branch;
+		class Leaf;
+
+		class Node
+		{
+		public:
+			Node(BiHierarchy * owner, int level, AxisAlignedBox& aabb, Branch * parent):
+			mOwner(owner),
+			mLevel(level),
+			mAABB(aabb),
+			mParent(parent),
+			mWBB(0),
+			m_iSide(0)
+			{ };
+
+			virtual ~Node()
+			{
+				delete mWBB;
+			};
+
+			virtual bool isLeaf() const = 0;
+			virtual bool isEmpty() const = 0;
+			virtual bool hasGeometry() const = 0;
+			
+			virtual void mergeLeaves(std::set<Leaf *>& leaves) = 0;
+
+			// Gets this node's parent (NULL if this is the root).
+			BiHierarchy::Node *getParent(void) const { return mParent; };
+
+			// Gets the nodes left & right child nodes, or NULL if not present or node is leaf
+			virtual BiHierarchy::Node *getLeftChild(void) const = 0;
+			virtual BiHierarchy::Node *getRightChild(void) const = 0;
+
+			// add contained objects to render queue
+			virtual void queueVisibleObjects(unsigned long currentFrame, 
+				Camera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, bool fullVis = false) = 0;
+
+			// add contained geometry (Entities) to list
+			virtual void getGeometryList(GeometryVector *geometryList) = 0;
+			
+			// create (when necessary), setup and return wire bounding box representing the node
+			WireBoundingBox * getWireBoundingBox()
+			{
+				if (mWBB == 0)
+					mWBB = new WireBoundingBox();
+
+				if (mOwner->getShowNodes())
+					mWBB->setupBoundingBox(mAABB);
+				else
+					mWBB->setupBoundingBox(mWorldAABB);
+
+				// cse
+				if (mOwner->getHiLiteLevel() == mLevel)
+					switch (m_iSide)
+					{
+					case 0:
+						{ 
+							mWBB->setMaterial("BiHierarchy/BoxViz"); break;
+						}
+					case 1: {
+						     mWBB->setMaterial("BiHierarchy/BoxLeft"); break;
+							}
+					default: 
+						{ 
+							mWBB->setMaterial("BiHierarchy/BoxRight");
+						}
+					}
+				 else if (mOwner->getHiLiteLevel() == (mLevel+1))
+				 {
+					
+							mWBB->setMaterial("BiHierarchy/BoxViz");
+					
+					
+				 } else
+				 {
+					switch (m_iSide)
+					{
+					case 0:
+						{ 
+							mWBB->setMaterial("BiHierarchy/BoxViz"); break;
+						}
+					case 1: {
+						     mWBB->setMaterial("BiHierarchy/BoxLeftDark"); break;
+							}
+					default: 
+						{ 
+							mWBB->setMaterial("BiHierarchy/BoxRightDark");
+						}
+					}
+				
+					
+				 }
+				
+				return mWBB;
+			}
+
+			// returns the level the node is on
+			int getLevel(void) const { return mLevel; };
+
+			void SetToLeft() {
+				m_iSide=1; 
+			};
+			void SetToRight() { 
+				m_iSide=2; 
+			};
+			int GetSide() { return m_iSide; };
+
+
+			// functions for the CHC hierarchy interface
+
+			/** Returns last visited frame id. */
+			unsigned int lastVisited(void) { return mLastVisited; };
+			/** Set to current frame id.
+			@param current frame id.
+			*/
+			void setLastVisited(unsigned int frameid) { mLastVisited = frameid; };
+			/** Makes this octree become visible / invisble.
+			@param visible Whether this node is to be made visible or invisible
+			*/
+			void setNodeVisible(bool visible) { mVisible = visible; };
+			/** Returns true if this node is marked visible, false otherwise. 
+			*/
+			bool isNodeVisible(void) { return mVisible; };
+			/** Frame id when this octree was last rendered. 
+			@return last rendered frame id
+			*/	
+			unsigned int lastRendered(void) { return mLastRendered; };
+			/** Sets frame id when this octree was last rendered. 
+			@param last rendered frame id
+			*/
+			void setLastRendered(unsigned int frameid) { mLastRendered = frameid; };
+			/** Returns real extent of the BiHierarchy, i.e., the merged extent of the bounding boxes. 
+			*/
+			AxisAlignedBox _getWorldAABB(void) const { return mAABB; };
+			/** Updates bound of the real aabb of BiHierarchy
+			*/
+			virtual void _updateBounds(bool recurse = true) = 0;
+			
+			/** bounding box of the node
+			*/
+			AxisAlignedBox mAABB;
+
+			/** bounding box of all objects inside the node 
+			*/
+			AxisAlignedBox mWorldAABB;
+
+
+		protected:
+			BiHierarchy * mOwner;
+			Branch * mParent;
+			int mLevel;
+			int m_iSide; // defines the side ( left / right ) for better debugging. 
+
+			WireBoundingBox * mWBB;
+			
+			// for the CHC hierarchy interface
+			unsigned int mLastRendered;
+			unsigned int mLastVisited;
+			bool mVisible;
+		};
+
+		class Branch : public Node
+		{
+		public:
+			Branch(BiHierarchy * owner, int level, AxisAlignedBox& aabb, Branch * parent, 
+				Plane * splitplane, BihPlaneEvent::Side side):
+			Node(owner, level, aabb, parent), 
+			mSplitPlane(splitplane), 
+			mLeft(0), 
+			mRight(0),
+			mPlaneSide(side)
+			{ };
+
+			virtual ~Branch()
+			{
+				delete mLeft;
+				delete mRight;
+				delete mSplitPlane;
+			};
+
+			// a branch is not a leaf 
+			virtual bool isLeaf() const { return false; };
+
+			// s branch is empty when it does not have children
+			virtual bool isEmpty() const { return (mLeft == 0 && mRight == 0); }
+
+			// a branch never has geometry
+			virtual bool hasGeometry() const { return false; };
+
+			virtual void mergeLeaves(std::set<Leaf *>& leaves)
+			{
+				for (std::set<Leaf *>::iterator it = mLeaves.begin(); it != mLeaves.end(); it++)
+					leaves.insert(*it);
+			}
+
+			// a branch should have at least one child
+			virtual BiHierarchy::Node * getLeftChild() const { return mLeft; };
+			virtual BiHierarchy::Node * getRightChild() const { return mRight; };
+
+			virtual void queueVisibleObjects(unsigned long currentFrame, 
+				Camera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, bool fullVis = false)
+			{
+				// cse 
+				//showBoxes=true;
+				if (showBoxes)
+				{
+					if (mLevel == mOwner->getHiLiteLevel()|| (mLevel-1) == mOwner->getHiLiteLevel() || mOwner->getShowAllBoxes())
+					queue->addRenderable(getWireBoundingBox());
+					/*
+					if (mLevel == mOwner->getHiLiteLevel() || mOwner->getShowAllBoxes())
+						queue->addRenderable(getWireBoundingBox());
+					*/
+				}
+
+				if (fullVis)
+					for (std::set<Leaf *>::iterator it = mLeaves.begin(); it != mLeaves.end(); it ++)
+						(*it)->queueVisibleObjects(currentFrame, cam, queue, onlyShadowCasters, showBoxes, fullVis);
+			}
+
+			// a branch has no geometry, do nothing
+			virtual void getGeometryList(GeometryVector *geometryList) { }
+
+			// branches do not posses geometry => just merge child aabbs
+			virtual void _updateBounds(bool recurse = true)
+			{
+				// reset box
+				mWorldAABB.setNull();
+
+				// merge box & leaves
+				if (mLeft)
+				{
+					mWorldAABB.merge(mLeft->mWorldAABB);
+					mLeft->mergeLeaves(mLeaves);
+				}
+				if (mRight)
+				{
+					mWorldAABB.merge(mRight->mWorldAABB);
+					mRight->mergeLeaves(mLeaves);
+				}
+
+				// update parent recursively
+				if (recurse && mParent)
+					mParent->_updateBounds(recurse);
+			}
+			
+			Node * mLeft;
+			Node * mRight;
+			Plane  * mSplitPlane;
+			BihPlaneEvent::Side mPlaneSide;
+		protected:
+			std::set<Leaf *> mLeaves;
+		};
+
+		class Leaf : public Node
+		{
+		public:
+			Leaf(BiHierarchy * owner, int level, AxisAlignedBox& aabb, Branch *parent):
+			Node(owner, level, aabb, parent) 
+			{};
+
+			virtual ~Leaf();
+
+			// a leaf is a leaf, dammit
+			virtual bool isLeaf() const { return true; }
+
+			// a leaf is empty when it does not posses renderables
+			virtual bool isEmpty() const { return mBihRenderables.empty(); }
+
+			// a leaf has geometry when it has renderables
+			virtual bool hasGeometry() const { return !mBihRenderables.empty(); }
+
+			// a leaf adds itself to the leaf set
+			virtual void mergeLeaves(std::set<Leaf *>& leaves)	{ leaves.insert(this); }
+
+			// a leaf never has children 
+			virtual BiHierarchy::Node * getLeftChild() const { return 0; };
+			virtual BiHierarchy::Node * getRightChild() const { return 0; };
+
+			virtual void queueVisibleObjects(unsigned long currentFrame, 
+				Camera* cam, RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, bool fullVis = false);
+
+			virtual void getGeometryList(GeometryVector *geometryList);
+
+			// update the world aabb based on the contained geometry
+			virtual void _updateBounds(bool recurse = true);
+
+			virtual void remove(BihRenderable * rend)
+			{
+				mBihRenderables.remove(rend);
+				//mBihRenderables.erase(find(mBihRenderables.begin(), mBihRenderables.end(), rend));
+			};
+
+			virtual void insert(BihRenderable * rend)
+			{
+				mBihRenderables.push_back(rend);
+			};
+
+			BihRenderableList mBihRenderables;
+		};
+
+		struct BihSubdivisionCandidate
+		{
+			BihSubdivisionCandidate(BihPlaneEventList * e, int n, AxisAlignedBox& a,
+				BiHierarchy::Branch * p, Real c, Real d, BihSplitInfo * b, BihPlaneEvent::Side s):
+			events(e), nObjects(n), aabb(a), parent(p), cost(c), decrease(d), best(b), side(s)
+			{ };
+
+			bool operator < (const BihSubdivisionCandidate& rhs) const
+			{
+				return decrease < rhs.decrease;
+			};
+
+			void operator = (const BihSubdivisionCandidate& rhs)
+			{
+				decrease = rhs.decrease;
+				cost = rhs.cost;
+				nObjects = rhs.nObjects;
+				side = rhs.side;
+				aabb = rhs.aabb;
+				events = rhs.events;
+				parent = rhs.parent;
+				best = rhs.best;
+			};
+
+			// DEBUG
+			String print();
+
+			Real decrease;
+			Real cost;
+			int nObjects;
+			BihPlaneEvent::Side side;
+			AxisAlignedBox aabb;
+			BihPlaneEventList *events;
+			BiHierarchy::Branch * parent;
+			BihSplitInfo * best;
+		};
+
+		// typedef std::stack<BihSubdivisionCandidate> SplitCandidatePQ;
+		typedef std::priority_queue<BihSubdivisionCandidate> SplitCandidatePQ;
+
+		// nodestack for the stack-based rendering function
+		typedef std::stack<BiHierarchy::Node *> NodeStack;
+	public:
+		friend class BiHierarchyInterface;
+
+		typedef BiHierarchy::Node * NodePtr;
+		typedef BiHierarchy::Branch * BranchPtr;
+		typedef BiHierarchy::Leaf * LeafPtr;
+
+		typedef std::list<NodePtr> NodeList;
+		typedef std::set<LeafPtr> LeafSet;
+
+		struct TreeStats
+		{
+			unsigned int mNumNodes;
+			unsigned int mNumLeaves;
+			unsigned int mNumSceneNodes;
+
+			void clear(void)
+			{
+				mNumNodes = 0;
+				mNumLeaves = 0;
+				mNumSceneNodes = 0;
+			}
+		};
+
+		struct FrameStats 
+		{
+			unsigned int mTraversedNodes;
+			unsigned int mRenderedNodes;
+			unsigned int mFrustumCulledNodes;
+
+			void clear(void)
+			{
+				mTraversedNodes = 0;
+				mRenderedNodes = 0;
+				mFrustumCulledNodes = 0;
+			}
+		};
+
+		enum RenderMethod
+		{
+			BIHRM_INTERNAL,
+			BIHRM_GTP_VFC,
+			BIHRM_GTP_SWC,
+			BIHRM_GTP_CHC,
+			// invalid modes, just for convenience
+			BIHRM_SIZE,
+			BIHRM_NOTSET
+		};
+
+		enum BuildMethod
+		{
+			BIHBM_RECURSIVE,
+			BIHBM_PRIORITYQUEUE,
+			// invalid modes, just for convenience
+			BIHBM_SIZE,
+			BIHBM_NOTSET
+		};
+
+		enum PlaneAlorithm
+		{
+			BIHAL_SAH,
+			BIHAL_MID
+		};
+
+
+		const static int HILITE_OFF  = -1;
+		
+		BiHierarchy(int maxdepth, BuildMethod bm);
+		BiHierarchy(int maxdepth, BuildMethod bm, int hilite, bool allboxes, bool shownodes);
+		virtual ~BiHierarchy();
+
+		// DEBUG
+		void dump(void);
+		Real calcCost(void);
+
+		// sets the level to highlight or turns it off (when hilite < 0)
+		inline void setHiLiteLevel(int hilite) { mHiLiteLevel = hilite; };
+		inline int  getHiLiteLevel(void) { return mHiLiteLevel; };
+
+		// toggles displaying the BiHierarchy boxes
+		inline void setShowAllBoxes(bool show) { mShowAllBoxes = show; };
+		inline bool getShowAllBoxes(void) { return mShowAllBoxes; };
+
+		// toggles between displaying the bounding box of the node and
+		// the box of the contained scene nodes
+		inline void setShowNodes(bool show = true) { mShowNodes = show; };
+		inline bool getShowNodes(void) { return mShowNodes; };
+
+		// changes vis mode (simple/enhanced with NONE/PART/FULL vis)
+		void setEnhancedVis(bool enh);
+		bool getEnhancedVis(void);
+
+		NodePtr getRoot(void) const { return mBihRoot; };
+
+		// insert a new scene node into an existing Bihierarchy
+		void insert(BihRenderable * rend);
+		// remove a scene node from the tree
+		void remove(BihRenderable * rend);
+		// function to initialize a kd-tree based on the contents of the scene
+		void build(BihRenderable * sceneRoot);
+
+		// test visibility of objects and add to render	queue
+		void queueVisibleObjects(BiHierarchyCamera* cam, RenderQueue* queue, bool onlyShadowCasters, 
+			bool showBoxes, BiHierarchy::NodeList& visibleNodes);
+
+		// find visible nodes & place in list
+		//void findVisibleNodes(NodeList& visibleNodes, Camera * cam);
+
+		/** Recurses the BiHierarchy, adding any nodes intersecting with the 
+		box/sphere/volume/ray into the given list.
+		It ignores the exclude scene node.
+		*/
+		void findNodesIn(const AxisAlignedBox &box, std::list<SceneNode *> &list, SceneNode *exclude = 0);
+		void findNodesIn(const Sphere &sphere, std::list<SceneNode *> &list, SceneNode *exclude = 0);
+		void findNodesIn(const PlaneBoundedVolume &volume, std::list<SceneNode *> &list, SceneNode *exclude = 0);
+		void findNodesIn(const Ray &ray, std::list<SceneNode *> &list, SceneNode *exclude = 0);
+
+		// self-explanatory ...
+		int getMaxDepth(void) { return mMaxDepth; }
+		const TreeStats& getTreeStats(void) const { return mTreeStats; }
+		const FrameStats& getFramesStats(void) const { return mFrameStats; }
+		AxisAlignedBox getBox(void) { if (mBihRoot) return mBihRoot->mAABB; else return AxisAlignedBox(); }
+		void setBuildMethod(BuildMethod bm) { mBuildMethod = bm; }
+	protected:
+		// init materials, logs and stuff
+		void init();
+		// recursive insert funciton
+		void recInsert(BiHierarchy::Node * node, BihRenderable * rend);
+		// helper functions for insert
+		void recInsertNew(BiHierarchy::Branch * parent, BihPlaneEvent::Side side, BihRenderable * rend);
+		void splitBox(const BiHierarchy::Branch& parent, AxisAlignedBox& left, AxisAlignedBox& right);
+		void rebuildSubtree(BiHierarchy::Node * node, BihRenderable * rend);
+		// build scene from a list of nodes rather than a hierarchy
+		BiHierarchy::Node * buildFromList(BihRenderableList& nodelist, BiHierarchy::Branch * parent, AxisAlignedBox& aabb);
+		void addRendToList(BiHierarchy::Node * node, BihRenderableList& nodelist);
+
+		// recursively delete empty nodes
+		void recDelete(BiHierarchy::Node * node);
+
+		// find the best plane for node division
+		BihSplitInfo * pqFindPlane(BihPlaneEventList * events, int nObjects, AxisAlignedBox& aabb, Real globalSA);
+
+		// priority queue based build function
+		BiHierarchy::Node * pqBuild(BihPlaneEventList& events, int nObjects, AxisAlignedBox& aabb, BiHierarchy::Branch * parent);
+		// recursive build function
+		BiHierarchy::Node * recBuild(BihPlaneEventList& events, int nObjects, AxisAlignedBox& aabb, BiHierarchy::Branch * parent);
+
+		// recursive rendering function
+		void recQueueVisibleObjects(BiHierarchy::Node * node, unsigned long currentFrame, BiHierarchyCamera* cam,
+			RenderQueue* queue, bool onlyShadowCasters, bool showBoxes, 
+			BiHierarchy::NodeList& visibleNodes, bool fullVis = false);
+
+		// recursively find visible nodes
+		//void recFindVisibleNodes(BiHierarchy::Node * node, NodeList& visibleNodes, Camera * cam);
+
+		/** Recurses the BiHierarchy, adding any nodes intersecting with the 
+		box/sphere/volume/ray into the given list.
+		It ignores the exclude scene node.
+		*/
+		void recFindNodesIn(const AxisAlignedBox &box, std::list<SceneNode *> &list, SceneNode *exclude, Node * node, bool full = false);
+		void recFindNodesIn(const Sphere &sphere, std::list<SceneNode *> &list, SceneNode *exclude, Node * node, bool full = false);
+		void recFindNodesIn(const PlaneBoundedVolume &volume, std::list<SceneNode *> &list, SceneNode *exclude, Node * node, bool full = false);
+		void recFindNodesIn(const Ray &ray, std::list<SceneNode *> &list, SceneNode *exclude, Node * node, bool full = false);
+
+		// the root node of the BiHierarchy
+		BiHierarchy::Node * mBihRoot;
+		// Maximum depth of the tree
+		int mMaxDepth;
+
+		// how to build the tree
+		BuildMethod mBuildMethod;
+
+		// what algorithm will be used to find the split plane
+		PlaneAlorithm mAlgorithm;
+
+		// logfile for tree creation
+		Log * mBuildLog;
+
+		// statistical information on the tree
+		TreeStats mTreeStats;
+
+		// statistical info on a single rendered frame
+		FrameStats mFrameStats;
+
+		/** Visualization flags **/
+		// show/highlight selected level in BiHierarchy
+		int mHiLiteLevel;
+		// show whole kd-tree
+		bool mShowAllBoxes;
+		// show node or object boxes
+		bool mShowNodes;
+
+		// function pointer to the getVisibility function
+		// allows choosing between regular vis (NONE/PART, same es isVisible)
+		// and enhaced vis (NONE/PART/FULL) for early traversal abort
+		BiHierarchyCamera::NodeVisibility (BiHierarchyCamera::*getVisibility)(const AxisAlignedBox& box) const;
+
+		// DEBUG
+		void BiHierarchy::dump(BiHierarchy::Node * node);
+		Real BiHierarchy::calcCost(BiHierarchy::Node * node, Real vs);
+	}; // class BiHierarchy
+
+} // namespace Ogre
+
+#endif // _OgreBiHierarchy_H__
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPageSource.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPageSource.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainPageSource.h	(revision 2349)
@@ -0,0 +1,262 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __BiTerrainPageSource_H__
+#define __BiTerrainPageSource_H__
+
+#include <OgreSingleton.h>
+#include "OgreBiTerrainPrerequisites.h"
+
+namespace Ogre {
+
+    typedef std::pair<String, String> BiTerrainPageSourceOption;
+    typedef std::vector<BiTerrainPageSourceOption> BiTerrainPageSourceOptionList;
+
+    /** Abstract class which classes can override to receive notifications
+        when a page is ready to be added to the terrain manager.
+    */
+    class _OgreBiTerrainExport BiTerrainPageSourceListener
+    {
+    public:
+        /** Listener method called when a new page is about to be constructed. 
+		@param manager The manager in question
+        @param pagex, pagez The index of the page being constructed
+        @param heightData Array of normalised height data (0..1). The size of
+            this buffer will conform to the scene manager page size. The listener
+            may modify the data if it wishes.
+        */
+        virtual void pageConstructed(BiTerrainSceneManager* manager, uint pagex, uint pagez, Real* heightData) = 0;
+    };
+
+	/** Simple manager class to hold onto a list of page source listeners 
+	    across all sources.
+	*/
+	class _OgreBiTerrainExport BiTerrainPageSourceListenerManager :
+		public Singleton<BiTerrainPageSourceListenerManager>
+	{
+	protected:
+        typedef std::vector<BiTerrainPageSourceListener*> BiPageSourceListenerList;
+        BiPageSourceListenerList mPageSourceListeners;
+	public:
+        BiTerrainPageSourceListenerManager() {}
+        ~BiTerrainPageSourceListenerManager() {}
+
+        /** Register a class which will be called back whenever a new page is
+            available.
+        @remarks
+            Since this method is static, it applies to any page source which 
+            is in active use; there is no need to register one per source.
+        */
+        void addListener(BiTerrainPageSourceListener* pl);
+        /** Unregister a class which will be called back whenever a new page is
+        available.
+        */
+        void removeListener(BiTerrainPageSourceListener* pl);
+		
+        /// Fire pageContructed events
+        void firePageConstructed(BiTerrainSceneManager* manager, uint pagex, uint pagez, Real* heightData);
+
+       /** Override standard Singleton retrieval.
+        */
+        static BiTerrainPageSourceListenerManager& getSingleton(void);
+        /** Override standard Singleton retrieval.
+        */
+        static BiTerrainPageSourceListenerManager* getSingletonPtr(void);	
+	
+	};
+
+
+    /** Abstract class which describes the interface which a source of terrain 
+        pages must implement.
+    @remarks
+        The TerrainSceneManager can accept external classes as providers of
+        terrain data, to allow terrain height data to come from anywhere the
+        user application may choose, and additionally to support on-demand
+        loading an unloading of terrain data. Providers must suclass this class, 
+        and implement the abstract methods (details are described within each method)
+    @par
+        The overall sequence of events is this:
+        <ol>
+        <li>TerrainSceneManager is created as usual, and options such as tile
+        size etc are set.</li>
+        <li>CustomTerrainPageSource is registered with TerrainSceneManager by 
+        calling registerPageSource(), registering a particular named type of source 
+        data with this tile source. <li>
+        <li>TerrainSceneManager::setWorldGeometry is called. Depending on the
+        configuration, this will call one of the page source classes 
+        initialise methods, when the scene manager will communicate it's 
+        preferred options. It does not have to load anything immediately on this 
+        call (especially if the terrain options include paging). It will 
+        also set this tile source as the primary.<li>
+        <li>As and when TerrainSceneManager requires more tiles (and this will
+        either be done all up-front, or progressively depending on paging settings)
+        it will call the primary tile source's requestPage() method, with the 
+        page it requires. </li>
+        <li>It is then the responsibility of the tile source to prepare
+        TerrainRenderable instances for the page(s) requested, and to attach them 
+        to the TerrainSceneManager. Note that preparing the tiles does not
+        involve modifying any shared data so may be done in an alternate thread,
+        if required. Attaching them must be done synchronously though.
+        <li>When paging, the TerrainSceneManager will request tiles in advance,
+        within it's 'buffer zone' so some delay in loading is acceptable. It
+        will also indicate when tiles are no longer required (and will detach
+        them); it is up to the tile source whether that memory is actually freed
+        or held for a while longer.
+        </ol>
+    @note The comments on paging above are in principle, the implementation of
+    paging in this manager is not present yet but the system is designed to 
+    extend to it. For now, all tiles are requested up-front.
+    */
+    class _OgreBiTerrainExport BiTerrainPageSource
+    {
+    protected:
+        /// Link back to parent manager
+        BiTerrainSceneManager* mSceneManager;
+        /// Has asynchronous loading been requested?
+        bool mAsyncLoading;
+        /// The expected size of the page in number of vertices
+        uint mPageSize;
+        /// The expected size of a tile in number of vertices
+        uint mTileSize;
+
+        /// Internal method for firing pageContructed events
+        void firePageConstructed(uint pagex, uint pagez, Real* heightData);
+
+        /** Utility method for building a page of tiles based on some source
+        data, wherever that may have come from.
+        @remarks
+            It is expected that this height data is represented in the range
+            [0..1], which will be duly scaled by the TerrainRenderables it
+            creates.
+        */
+        virtual BiTerrainPage* buildPage(Real* heightData, const MaterialPtr& pMaterial);
+
+
+    public:
+        BiTerrainPageSource(); 
+        virtual ~BiTerrainPageSource() { shutdown(); }
+
+        /** Initialise this tile source based on a series of options as
+            dictated by the scene manager. 
+        @param tsm The TerrainSceneManager doing the initialising. This should be 
+            allowed NULL, for use by external tools if they want to read data 
+            generically without necessarily having a real scene manager involved
+        @param tileSize The number of horizontal (and hence also vertical) 
+            vertices in a single tile (which is a TerrainRenderable). This will
+            always be (2^n)+1.
+        @param pageSize The number of horizontal (and hence also vertical) 
+            vertices in a single page. This will always be (2^n)+1.
+        @param asyncLoading
+            True if the scene manager would like the tile source to load tiles
+            asynchronously. It does not have to do this, although if it does not
+            when requested, it will likely result in stalls in the terrain rendering.
+        @param optionList 
+            A list of name/value pairs describing custom options for this particular
+            page source. The expected convention for option names is
+            "TypeName.OptionName", where TypeName is the type under which this
+            page source has been registered.
+        */
+        virtual void initialise(BiTerrainSceneManager* tsm, 
+            uint tileSize, uint pageSize, bool asyncLoading, 
+            BiTerrainPageSourceOptionList& optionList)
+        {
+            mSceneManager = tsm;
+            mTileSize = tileSize;
+            mPageSize = pageSize;
+            mAsyncLoading = asyncLoading;
+        }
+        /** Shut down this tile source, freeing all it's memory ready for 
+            decommissioning.
+        @remarks
+            This method will normally just be called on destruction; however
+            it may also be called by the TerrainSceneManager if another source
+            is provided for the same type of tile source.
+        */
+        virtual void shutdown(void) {}
+
+        /** Requests a new page of tiles from the source.
+        @remarks
+            The TerrainSceneManager will call this method when it needs new tiles.
+            In response, this class must prepare TerrainRenderable instances for
+            the page requested and attach the entire page when ready using 
+            TerrainSceneManager::attachTerrainPage.
+        @par
+            Now, the tile source does not necessarily need to do all that before the
+            return of this method. If it likes, and particularly if asynchronous 
+            loading is enabled, it can merely queue this request, and process it
+            either in another thread, or over a series of frames. The key thing
+            is that attaching the new page has to be done synchronously with 
+            the main rendering loop in order to avoid concurrency issues; 
+            other than that, you are free to load and prepare new tiles in 
+            a concurrent fashion if you like.
+        @par
+            Typically the scene manager will request at least one page up-front,
+            with the possibility of requesting more if paging is enabled.
+        @param x The x index of the page requested
+        @param z The z index of the page requested
+        */
+        virtual void requestPage(ushort x, ushort z) = 0;
+        /** This notifies the tile source that the specified page of tiles 
+            has been automatically detached.
+        @remarks
+            When paging is enabled, tiles go out of scope and the TerrainSceneManager
+            detaches them automatically, notifying the TerrainPageSource that 
+            this has happened. The tile source can choose to either keep these
+            tiles in memory (incase they are requested again) or can delete them
+            if it wishes to free memory. This freeing does not need to be done
+            before the return of this method - like requesting tiles, the
+            freeing of them can be done in another thread or across many frames
+            if required, since the shared data in TerrainSceneManager has already
+            been updated synchronously when the page was detached.
+        @param x The x index of the page expired
+        @param z The z index of the page expired
+        */
+        virtual void expirePage(ushort x, ushort z) = 0;
+        
+        /** Register a class which will be called back whenever a new page is
+            available.
+        @remarks
+            Since this method is static, it applies to any page source which 
+            is in active use; there is no need to register one per source.
+        */
+        static void addListener(BiTerrainPageSourceListener* pl);
+        /** Unregister a class which will be called back whenever a new page is
+        available.
+        */
+        static void removeListener(BiTerrainPageSourceListener* pl);
+
+    };
+
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyCamera.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyCamera.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiHierarchyCamera.h	(revision 2349)
@@ -0,0 +1,46 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of the GameTools Project
+http://www.gametools.org
+
+Author: Martin Szydlowski
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _OgreBiHierarchyCamera_H_
+#define _OgreBiHierarchyCamera_H_
+
+#include <OgreCamera.h>
+
+#define BIHCAMPTR_CAST(cam) (static_cast<BiHierarchyCamera *>(cam))
+
+namespace Ogre
+{
+
+class BiHierarchyCamera : public Camera
+{
+public:
+	enum NodeVisibility
+	{
+		BIHNV_NONE,
+		BIHNV_PART,
+		BIHNV_FULL
+	};
+
+	// default constructor
+	BiHierarchyCamera(const String& name, SceneManager *sm);
+	// default destructor
+	~BiHierarchyCamera();
+
+	// regular visibility, like isVisible
+	NodeVisibility getVisibilitySimple(const AxisAlignedBox& box ) const;
+	// enhanced visibility
+	NodeVisibility getVisibilityEnhanced(const AxisAlignedBox& box) const;
+
+	// statistical info
+	mutable unsigned int mNumVisQueries;
+};
+
+} // namespace Ogre
+
+#endif // _OgreBiHierarchyCamera_H_
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainRenderable.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainRenderable.h	(revision 2349)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBiTerrainRenderable.h	(revision 2349)
@@ -0,0 +1,441 @@
+/*
+-----------------------------------------------------------------------------
+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.
+-----------------------------------------------------------------------------
+*/
+/***************************************************************************
+BiTerrainRenderable.h  -  description
+-------------------
+begin                : Sat Oct 5 2002
+copyright            : (C) 2002 by Jon Anderson
+email                : janders@users.sf.net
+
+Enhancements 2003 - 2004 (C) The OGRE Team
+
+***************************************************************************/
+
+#ifndef _BiTerrainRenderable_H__
+#define _BiTerrainRenderable_H__
+
+#include "OgreBiTerrainPrerequisites.h"
+#include <OgreRenderable.h>
+#include <OgreMovableObject.h>
+#include <OgreAxisAlignedBox.h>
+#include <OgreString.h>
+#include <OgreHardwareBufferManager.h>
+
+#include <vector>
+
+#define MORPH_CUSTOM_PARAM_ID 77
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+#define MAX_RENDERLEVEL_INDEX 15 // maximal different number of render levels, e.g., used for chc
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+
+namespace Ogre
+{
+    typedef std::map <unsigned int, IndexData* > IndexMap;
+    typedef std::vector < IndexData* > IndexArray;
+    typedef std::vector < IndexMap* > LevelArray;
+
+    /**
+    * A cache of TerrainIndexBuffers.  Used to keep track of the buffers, and
+    * delete them when the program finishes.
+    */
+    class BiTerrainBufferCache
+    {
+    public:
+        void shutdown(void)
+        {
+            for( size_t i=0; i<mCache.size(); i++ )
+            {
+                delete mCache[i];
+            }
+            mCache.clear();
+        }
+        ~BiTerrainBufferCache()
+        {
+            shutdown();
+        }
+
+        IndexArray mCache;
+    };
+
+    //inline Real _max( Real x, Real y )
+    //{
+    //    return ( x > y ) ? x : y;
+    //}
+
+    /** A simple class for encapsulating parameters which are commonly needed by 
+    both TerrainSceneManager and BiTerrainRenderable.
+    */
+    class BiTerrainOptions
+    {
+    public:
+        BiTerrainOptions()
+        {
+            pageSize = 0;
+            tileSize = 0;
+            tilesPerPage = 0;
+            maxGeoMipMapLevel = 0;
+            scale = Vector3::UNIT_SCALE;
+            maxPixelError = 4;
+            detailTile = 1;
+            lit = false;
+            coloured = false;
+            lodMorph = false;
+            lodMorphStart = 0.5;
+            useTriStrips = false;
+            primaryCamera = 0;
+            terrainMaterial.setNull();
+        };
+        /// The size of one edge of a terrain page, in vertices
+        uint pageSize;
+        /// The size of one edge of a terrain tile, in vertices
+        uint tileSize; 
+        /// Precalculated number of tiles per page
+        uint tilesPerPage;
+        /// The primary camera, used for error metric calculation and page choice
+        const Camera* primaryCamera;
+        /// The maximum terrain geo-mipmap level
+        uint maxGeoMipMapLevel;
+        /// The scale factor to apply to the terrain (each vertex is 1 unscaled unit
+        /// away from the next, and height is from 0 to 1)
+        Vector3 scale;
+        /// The maximum pixel error allowed
+        uint maxPixelError;
+        /// Whether we should use triangle strips
+        bool useTriStrips;
+        /// The number of times to repeat a detail texture over a tile
+        uint detailTile;
+        /// Whether LOD morphing is enabled
+        bool lodMorph;
+        /// At what point (parametric) should LOD morphing start
+        Real lodMorphStart;
+        /// Whether dynamic lighting is enabled
+        bool lit;
+        /// Whether vertex colours are enabled
+        bool coloured;
+        /// Pointer to the material to use to render the terrain
+        MaterialPtr terrainMaterial;
+
+    };
+
+#define STITCH_NORTH_SHIFT 0
+#define STITCH_SOUTH_SHIFT 8
+#define STITCH_WEST_SHIFT  16
+#define STITCH_EAST_SHIFT  24
+
+#define STITCH_NORTH  128 << STITCH_NORTH_SHIFT
+#define STITCH_SOUTH  128 << STITCH_SOUTH_SHIFT
+#define STITCH_WEST   128 << STITCH_WEST_SHIFT
+#define STITCH_EAST   128 << STITCH_EAST_SHIFT
+
+    /**
+    Represents a terrain tile.
+    @remarks
+    A BiTerrainRenderable represents a tile used to render a block of terrain using the geomipmap approach
+    for LOD.
+    *@author Jon Anderson
+    */
+
+    class _OgreBiTerrainExport BiTerrainRenderable : public Renderable, public MovableObject
+    {
+    public:
+
+        BiTerrainRenderable(const String& name, BiTerrainSceneManager* tsm);
+        ~BiTerrainRenderable();
+
+        void deleteGeometry();
+
+        enum Neighbor
+        {
+            NORTH = 0,
+            SOUTH = 1,
+            EAST = 2,
+            WEST = 3,
+            HERE = 4
+        };
+
+        /** Initializes the BiTerrainRenderable.
+        @param startx, startz 
+        The starting points of the top-left of this tile, in terms of the
+        number of vertices.
+        @param pageHeightData The source height data for the entire parent page
+        */
+        void initialise(int startx, int startz, Real* pageHeightData);
+
+        //movable object methods
+
+        /** Returns the type of the movable. */
+        virtual const String& getMovableType( void ) const
+        {
+            return mType;
+        };
+
+        /** Returns the bounding box of this BiTerrainRenderable */
+        const AxisAlignedBox& getBoundingBox( void ) const
+        {
+            return mBounds;
+        };
+
+        /** Updates the level of detail to be used for rendering this BiTerrainRenderable based on the passed in Camera */
+        virtual void _notifyCurrentCamera( Camera* cam );
+
+        virtual void _updateRenderQueue( RenderQueue* queue );
+
+        /**
+        Constructs a RenderOperation to render the BiTerrainRenderable.
+        @remarks
+        Each BiTerrainRenderable has a block of vertices that represent the terrain.  Index arrays are dynamically
+        created for mipmap level, and then cached.
+        */
+        virtual void getRenderOperation( RenderOperation& rend );
+
+        virtual const MaterialPtr& getMaterial( void ) const
+        {
+            return mMaterial;
+        };
+
+        virtual void getWorldTransforms( Matrix4* xform ) const;
+
+        virtual const Quaternion& getWorldOrientation(void) const;
+        virtual const Vector3& getWorldPosition(void) const;
+
+        /** Returns the mipmap level that will be rendered for this frame. */
+        inline int getRenderLevel() const
+        {
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+            return mRenderLevel[msCurrentRenderLevelIndex];
+#else
+            return mRenderLevel;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+        };
+
+        /** Forces the LOD to the given level from this point on. */
+        inline void setForcedRenderLevel( int i )
+        {
+            mForcedRenderLevel = i;
+        }
+
+        /** Calculates the normal at the given location */
+        void _getNormalAt( float x, float y, Vector3 * result );
+
+        /** Returns the terrain height at the given coordinates */
+        float getHeightAt( float x, float y );
+
+        /** Intersects the segment witht he terrain tile
+        */
+        bool intersectSegment( const Vector3 & start, const Vector3 & end, Vector3 * result );
+
+        /** Sets the appropriate neighbor for this BiTerrainRenderable.  Neighbors are necessary
+        to know when to bridge between LODs.
+        */
+        void _setNeighbor( Neighbor n, BiTerrainRenderable *t )
+        {
+            mNeighbors[ n ] = t;
+        };
+
+        /** Returns the neighbor BiTerrainRenderable.
+        */
+        BiTerrainRenderable * _getNeighbor( Neighbor n )
+        {
+            return mNeighbors[ n ];
+        }
+
+
+        void setMaterial(const MaterialPtr& m )
+        {
+            mMaterial = m;
+        };
+
+        /** Calculates static normals for lighting the terrain. */
+        void _calculateNormals();
+
+
+
+
+        /** Generates terrain shadows and lighting using vertex colors
+        */
+        void _generateVertexLighting( const Vector3 &sun, ColourValue ambient );
+
+
+        /** Overridden, see Renderable */
+        Real getSquaredViewDepth(const Camera* cam) const;
+
+        /** Overridden from MovableObject */
+        Real getBoundingRadius(void) const { return mBoundingRadius; }
+
+        /** @copydoc Renderable::getLights */
+        const LightList& getLights(void) const;
+
+        /// Overridden from Renderable to allow the morph LOD entry to be set
+        void _updateCustomGpuParameter(
+            const GpuProgramParameters::AutoConstantEntry& constantEntry,
+            GpuProgramParameters* params) const;
+		/// @see MovableObject
+		uint32 getTypeFlags(void) const;
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		// resets index of renderlevel used for current pass
+		static void ResetRenderLevelIndex();
+		// next index of renderlevel
+		static void NextRenderLevelIndex();
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+
+    protected:
+		/// Parent SceneManager
+		BiTerrainSceneManager* mSceneManager;
+        /// Link to shared options
+        const BiTerrainOptions* mOptions;
+
+        /** Returns the index into the height array for the given coords. */
+        inline size_t _index( int x, int z ) const
+        {
+            return ( x + z * mOptions->tileSize );
+        };
+
+        /** Returns the  vertex coord for the given coordinates */
+        inline float _vertex( int x, int z, int n )
+        {
+            return mPositionBuffer[x * 3 + z * mOptions->tileSize * 3 + n];
+        };
+
+
+        inline int _numNeighbors() const
+        {
+            int n = 0;
+
+            for ( int i = 0; i < 4; i++ )
+            {
+                if ( mNeighbors[ i ] != 0 )
+                    n++;
+            }
+
+            return n;
+        }
+
+        inline bool _hasNeighborRenderLevel( int i ) const
+        {
+            for ( int j = 0; j < 4; j++ )
+            {
+/*** msz: added for v1-2-0 compatibility ***/
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+				if ( mNeighbors[ j ] != 0 && mNeighbors[ j ] ->getRenderLevel() == i )
+                    return true;
+#else
+                if ( mNeighbors[ j ] != 0 && mNeighbors[ j ] ->mRenderLevel == i )
+                    return true;
+#endif //GTP_VISIBILITY_MODIFIED_OGRE
+            }
+
+            return false;
+
+        }
+
+        void _adjustRenderLevel( int i );
+
+        bool _checkSize( int n );
+
+        void _calculateMinLevelDist2( Real C );
+
+        Real _calculateCFactor();
+
+        VertexData* mTerrain;
+
+        /// The current LOD level
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+        int mRenderLevel[MAX_RENDERLEVEL_INDEX];
+
+		/*** msz: added for v1-2-0 compatibility ***/
+		// index of renderlevel of current pass
+		static int msCurrentRenderLevelIndex;
+#else
+		int mRenderLevel;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+
+        /// The previous 'next' LOD level down, for frame coherency
+        int mLastNextLevel; 
+        /// The morph factor between this and the next LOD level down
+        Real mLODMorphFactor;
+        /// List of squared distances at which LODs change
+        Real *mMinLevelDistSqr;
+        /// Connection to tiles four neighbours
+        BiTerrainRenderable *mNeighbors [ 4 ];
+        /// Whether light list need to re-calculate
+        mutable bool mLightListDirty;
+        /// Cached light list
+        mutable LightList mLightList;
+        /// The bounding radius of this tile
+        Real mBoundingRadius;
+        /// Bounding box of this tile
+        AxisAlignedBox mBounds;
+        /// The center point of this tile
+        Vector3 mCenter;
+        /// The MovableObject type
+        static String mType;
+        /// Current material used by this tile
+        MaterialPtr mMaterial;    
+        /// Whether this tile has been initialised    
+        bool mInit;
+        /// The buffer with all the renderable geometry in it
+        HardwareVertexBufferSharedPtr mMainBuffer;
+        /// Optional set of delta buffers, used to morph from one LOD to the next
+        HardwareVertexBufferSharedPtr* mDeltaBuffers;
+        /// System-memory buffer with just positions in it, for CPU operations
+        float* mPositionBuffer;
+        /// Forced rendering LOD level, optional
+        int mForcedRenderLevel;
+        /// Array of LOD indexes specifying which LOD is the next one down
+        /// (deals with clustered error metrics which cause LODs to be skipped)
+        int mNextLevelDown[10];
+        /// Gets the index data for this tile based on current settings
+        IndexData* getIndexData(void);
+        /// Internal method for generating stripified terrain indexes
+        IndexData* generateTriStripIndexes(unsigned int stitchFlags);
+        /// Internal method for generating triangle list terrain indexes
+        IndexData* generateTriListIndexes(unsigned int stitchFlags);
+        /** Utility method to generate stitching indexes on the edge of a tile
+        @param neighbor The neighbor direction to stitch
+        @param hiLOD The LOD of this tile
+        @param loLOD The LOD of the neighbor
+        @param omitFirstTri Whether the first tri of the stitch (always clockwise
+        relative to the centre of this tile) is to be omitted because an 
+        adjoining edge is also being stitched
+        @param omitLastTri Whether the last tri of the stitch (always clockwise
+        relative to the centre of this tile) is to be omitted because an 
+        adjoining edge is also being stitched
+        @param pIdx Pointer to a pointer to the index buffer to push the results 
+        into (this pointer will be updated)
+        @returns The number of indexes added
+        */
+        int stitchEdge(Neighbor neighbor, int hiLOD, int loLOD, 
+            bool omitFirstTri, bool omitLastTri, unsigned short** ppIdx);
+
+        /// Create a blank delta buffer for usein morphing
+        HardwareVertexBufferSharedPtr createDeltaBuffer(void);
+
+    };
+
+}
+
+#endif
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBoundingBoxConverter.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBoundingBoxConverter.h	(revision 2123)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBoundingBoxConverter.h	(revision 2349)
@@ -18,4 +18,5 @@
 class KdTreeSceneManager;
 class BvHierarchySceneManager;
+class BiHierarchySceneManager;
 
 typedef vector<Entity *> EntityContainer;
@@ -322,5 +323,5 @@
 	}
 
-	return true;
+	return true; 
 }
 #endif
@@ -328,4 +329,5 @@
 typedef PlatFormBoundingBoxConverter<OctreeSceneManager> OctreeBoundingBoxConverter;
 typedef PlatFormBoundingBoxConverter<BvHierarchySceneManager> BvhBoundingBoxConverter;
+typedef PlatFormBoundingBoxConverter<BiHierarchySceneManager> BihBoundingBoxConverter;
 typedef PlatFormBoundingBoxConverter<KdTreeSceneManager> KdTreeBoundingBoxConverter;
 
