Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOcclusionQueriesQueryManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOcclusionQueriesQueryManager.h	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOcclusionQueriesQueryManager.h	(revision 370)
@@ -0,0 +1,82 @@
+#ifndef _OcclusionQueriesQueryManager_H__
+#define _OcclusionQueriesQueryManager_H__
+
+#include "OgrePlatformQueryManager.h"
+
+namespace Ogre {
+  
+/**
+	Class which implements a query manager for Ogre scene queries using occlusion queries.
+*/
+class __declspec(dllexport) OcclusionQueriesQueryManager: public PlatformQueryManager
+{
+public:
+    /** Constructor taking a hierarchy interface as an argument. This allows to operate
+		on different hierarchy types, while reusing the implementation of the query methods.
+    */
+	OcclusionQueriesQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp,
+								 int queryModes, int itemBufferMode);
+    
+    void ComputeCameraVisibility(const Camera &camera,
+			    GtpVisibility::NodeInfoContainer *visibleNodes,
+			    GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches,
+			    bool relativeVisibility = false);
+    
+    /** 
+	Uses the specified point to execute the visibility query in all directions. 
+	@sa ComputeCameraVisibility()
+    */
+    void ComputeFromPointVisibility(const Vector3 &point,
+			       GtpVisibility::NodeInfoContainer *visibleNodes,
+			       GtpVisibility::MeshInfoContainer *visibleGeometry,
+				   GtpVisibility::PatchInfoContainer *visiblePatches,
+			       bool relativeVisibility = false);
+    
+
+protected:
+
+	void CollectGeometryVisibility(GtpVisibility::QueryList::iterator &visQueryIt, 
+								   GtpVisibility::QueryList::iterator &projQueryIt,
+								   GtpVisibility::GeometryVector *geometryList, 
+								   GtpVisibility::MeshInfoContainer *visibleGeometry,
+								   bool relativeVisibility);
+
+	void CollectNodeVisibility(GtpVisibility::QueryList::iterator &visQueryIt, 
+							   GtpVisibility::QueryList::iterator &projQueryIt,
+							   GtpVisibility::NodeVector *nodeList, 
+							   GtpVisibility::NodeInfoContainer *visibleNodes,
+							   bool relativeVisibility);
+
+	void CollectRelativeGeometryVisibilityForItemBuffer(GtpVisibility::QueryList::iterator &projQueryIt,
+												GtpVisibility::GeometryVector *geometryList, 
+												GtpVisibility::MeshInfoContainer *visibleGeometry);
+
+	void CollectRelativePatchVisibilityForItemBuffer(
+									GtpVisibility::QueryList::iterator &projQueryIt,
+									GtpVisibility::PatchVector *patchList, 
+									GtpVisibility::PatchInfoContainer *visiblePatches);
+
+	void CollectPatchVisibility(GtpVisibility::QueryList::iterator &visQueryIt, 
+								GtpVisibility::QueryList::iterator &projQueryIt,
+								GtpVisibility::PatchVector *patchList, 
+								GtpVisibility::PatchInfoContainer *visiblePatches,
+								bool relativeVisibility);
+
+	void RemoveDuplicateNodes(GtpVisibility::NodeInfoContainer *visibleNodes);
+	void RemoveDuplicateGeometry(GtpVisibility::MeshInfoContainer *visibleMesh);
+	void RemoveDuplicatePatches(GtpVisibility::PatchInfoContainer *visiblePatches);
+
+	/** Returns the patches of the geometry of a given node. 
+		@param node the node containing the patches
+		@param patchList the patches are returned in this list
+	*/
+	virtual void GetNodePatchList(GtpVisibility::HierarchyNode *node,	
+					 			  GtpVisibility::PatchVector *patchList);
+
+	int mItemBufferMode;
+};
+
+} // namespace Ogre
+
+#endif // OcclusionQueriesQueryManager
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneNodeHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneNodeHierarchyInterface.h	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneNodeHierarchyInterface.h	(revision 370)
@@ -0,0 +1,51 @@
+#ifndef _SceneNodeHierarchyInterface_H__
+#define _SceneNodeHierarchyInterface_H__
+
+#include "OgrePlatformHierarchyInterface.h"
+#include "VisibilityInfo.h"
+#include "QueryManager.h"
+
+
+namespace Ogre {
+
+/**
+	This class implements the hierarchy interface for the Ogre scene node hierarchy.
+*/
+class SceneNodeHierarchyInterface: public PlatformHierarchyInterface
+{
+public:
+	/** Construction taking the current scene manager and the current 
+		rendersystem as argument
+		@param sm current scene manager
+		@param rsys current render system 
+	*/
+	SceneNodeHierarchyInterface(SceneManager *sm, RenderSystem *rsys);
+	
+	bool IsLeaf(GtpVisibility::HierarchyNode *node) const;
+	
+	void TraverseNode(GtpVisibility::HierarchyNode *node);
+	void RenderNode(GtpVisibility::HierarchyNode *node);
+	void PullUpVisibility(GtpVisibility::HierarchyNode *node) const;
+	bool HasGeometry(GtpVisibility::HierarchyNode *node) const;
+	float GetSquaredDistance(GtpVisibility::HierarchyNode *node) const;
+
+	void SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const;
+	void SetLastVisited(GtpVisibility::HierarchyNode *node, 
+						const unsigned int frameId) const;
+
+	bool IsNodeVisible(GtpVisibility::HierarchyNode *node) const;
+	unsigned int LastVisited(GtpVisibility::HierarchyNode *node) const;
+
+	AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node);
+
+	void VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+							GtpVisibility::CullingType type) const;
+	
+	void GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
+					 GtpVisibility::GeometryVector *geometryList, 
+					 bool includeChildren);
+
+};
+
+} // namespace Ogre
+#endif // SceneNodeHierarchyInterface_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h	(revision 347)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityTerrainSceneManager.h	(revision 347)
@@ -0,0 +1,167 @@
+#ifndef _VisibilityTerrainSceneManager_H__
+#define _VisibilityTerrainSceneManager_H__
+
+#include <OgreSceneNode.h>
+#include <OgreTerrainSceneManager.h>
+#include <OgreOctreeNode.h>
+#include <OgreOctreeCamera.h>
+#include <OgrePrerequisites.h>
+
+#include "OgreOctreeHierarchyInterface.h"
+#include "OgrePlatformQueryManager.h"
+#include "VisibilityManager.h"
+
+
+namespace Ogre {
+
+/**
+	This class extends the terrain scene manager,
+	using occlusion queries for visibility culling.
+*/
+class __declspec(dllexport) VisibilityTerrainSceneManager: public TerrainSceneManager
+{
+public:
+	VisibilityTerrainSceneManager(GtpVisibility::VisibilityManager *visManager);
+	~VisibilityTerrainSceneManager();
+
+	void _renderVisibleObjects();
+	void _findVisibleObjects(Camera* cam, bool onlyShadowCasters);
+	void _updateSceneGraph(Camera* cam);
+
+	/** Sets the given option for the SceneManager
+		@remarks Options are: "Algorithm", int *;			
+	*/
+	
+	virtual bool setOption(const String &, const void *);
+	/** Gets the given option for the Scene VisibilityManager.
+	    @remarks
+		See setOption
+	*/
+	virtual bool getOption(const String &, void *);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Sets the visibility manager.
+		@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+
+	/** Render a set of objects, see renderSingleObject for param definitions 
+		Override so we can handle delayed rendering of transparent objects
+	*/
+	virtual void renderObjects(const RenderPriorityGroup::TransparentRenderablePassList& objs, 
+            bool doLightIteration, const LightList* manualLightList = 0);
+
+	/** Writes out stats into the Ogre log file.
+	*/
+	void WriteLog();
+
+	/** Override pass so we can do the z-fail pass. 
+	*/
+	Pass* setPass(Pass* pass);
+
+	/** Override from SceneManager so we can skip all but first pass for depth pass. 
+	*/
+	bool validatePassForRendering(Pass* pass);
+
+	void RenderItemBuffer(RenderPriorityGroup* pGroup);
+	void RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass);
+	void renderQueueGroupObjects(RenderQueueGroup* pGroup);
+
+	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
+	*/
+	Entity* createEntity(const String& entityName, const String& meshName);
+
+	/** Returns pointer to visibility manager.
+	*/
+	GtpVisibility::VisibilityManager *GetVisibilityManager();
+
+	/** Returns hierarchy interface.
+	*/
+	OctreeHierarchyInterface *GetHierarchyInterface();
+
+	/** Inherited from scene manager. Neccesary to draw terrain properly.
+	*/
+	void endFrame();
+
+	void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
+	void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
+
+	/** Override standard function so octree boxes are always of equal side length.
+		This has advantages for CHC, because terrain tiles are in different octree nodes
+		and can be culled.
+	*/
+	void setWorldGeometry( const String& filename );
+
+protected:
+	
+	/** 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);
+
+	/// the interface to the scene hierarchy.
+	OctreeHierarchyInterface *mHierarchyInterface;
+	/// manages all visibility options
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+
+	/// if a visualization of the hierarchical culling is shown
+	bool mShowVisualization;
+
+	/// if the culled nodes are indicated in the visualization
+	bool mVisualizeCulledNodes;
+
+	/// if symbols for the nodes are shown in the visualization
+	bool mRenderNodesForViz;
+	/// if content of the nodes is shown in the visualization
+	bool mRenderNodesContentForViz;
+
+	/// if we render transparents after the hierarchical traversal
+	bool mDelayRenderTransparents;
+
+	/// if we use a depth pass (i.e., fill only the depth buffer in the first pass)
+	bool mUseDepthPass;
+	/// if we currently rendering the depth pass
+	bool mIsDepthPassPhase;
+	
+	/// 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;
+
+	/// if depth write should be enabled
+	bool mEnableDepthWrite;
+	/// if transparents are skipped during rendering
+	bool mSkipTransparents;
+
+	/// the depth pass (no lighting, just filling the depth buffer)
+	Pass *mDepthPass;
+	Pass *mItemBufferPass;
+
+	int mCurrentEntityId;
+	/// flag for passes which should not be deleted from queue during first traversal
+	int mLeavePassesInQueue;
+
+	/// 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;
+
+	bool mIsHierarchicalCulling;
+};
+
+} // namespace Ogre
+
+#endif // CullingTerrainSceneManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformOcclusionQuery.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformOcclusionQuery.h	(revision 160)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformOcclusionQuery.h	(revision 160)
@@ -0,0 +1,32 @@
+#ifndef _PlatformOcclusionQuery_H__
+#define _PlatformOcclusionQuery_H__
+
+#include <OgreHardwareOcclusionQuery.h>
+#include <OgreRenderSystem.h>
+
+#include "OcclusionQuery.h"
+
+namespace Ogre {
+
+/** This class is an implementation for occlusion queries using Ogre.
+	@remark the class encapsulates Ogre occlusion query calls.
+*/
+class PlatformOcclusionQuery: public GtpVisibility::OcclusionQuery
+{
+public:
+	
+	PlatformOcclusionQuery(RenderSystem *rsys);
+
+	virtual ~PlatformOcclusionQuery();
+
+	virtual bool GetQueryResult(unsigned int &queryResult,
+	const bool waitForResult) const;
+	virtual void BeginQuery();
+	virtual void EndQuery();
+
+protected:
+	HardwareOcclusionQuery *mHardwareOcclusionQuery;
+};
+
+} // namespace Ogre
+#endif // PlatformOcclusionQuery_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOptionsManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOptionsManager.h	(revision 187)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOptionsManager.h	(revision 187)
@@ -0,0 +1,48 @@
+#ifndef _VisibilityOptionsManager_H__
+#define _VisibilityOptionsManager_H__
+
+
+#include <OgreString.h>
+#include <OgreStringVector.h>
+#include "VisibilityManager.h"
+#include "OgrePlatformHierarchyInterface.h"
+
+
+namespace Ogre {
+	
+/**
+	Helper class for setting and getting different options directly
+	related to visibility culling.
+*/
+class VisibilityOptionsManager
+{
+public:
+	/** Contructor.
+		@param visManager current visibility manager handling
+		the culling options
+		@param hierarchInterface current hierarchy interface for 
+		handling the traversal options
+	*/
+	VisibilityOptionsManager(GtpVisibility::VisibilityManager *visManager, 
+							 PlatformHierarchyInterface *hierarchyInterface);
+	
+	/** Sets the given option for the scene traverser.
+	    @remarks
+		Options are:
+		"Algorithm", "Threshold";			
+	*/
+	bool setOption(const String &, const void *);
+	/** Gets the given option for the scene traverser.
+	    @remarks
+	    See setOption
+	*/
+	bool getOption(const String &, void *);
+	bool getOptionKeys( StringVector &refKeys );
+	
+protected:
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+	PlatformHierarchyInterface *mHierarchyInterface;
+};
+
+}
+#endif // VisibilityOptionsManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneContentGenerator.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneContentGenerator.h	(revision 160)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSceneContentGenerator.h	(revision 160)
@@ -0,0 +1,104 @@
+#ifndef _SCENECONTENTGENERATOR_H__
+#define _SCENECONTENTGENERATOR_H__
+
+#include <OgrePrerequisites.h>
+#include <OgreMath.h>
+#include <Ogre.h>
+
+namespace Ogre {
+
+typedef std::vector<SceneNode *> SceneNodeList;
+typedef std::vector<Entity *> EntityList;
+
+/** Class which fills a scene with content in a random fashion.
+*/
+class __declspec(dllexport) SceneContentGenerator
+{
+public:
+	SceneContentGenerator(SceneManager *sm);
+	virtual ~SceneContentGenerator() {};
+	/** Generates scene object in a random fashion.
+		@param number of objects to generate
+		@param objName the name of the mesh to be generated
+	*/
+	void GenerateScene(int numObjects, const String &objName);
+
+	/** Generates a new object in the scene using ray scene queries 
+		and inserts it into thr scene hierarchy.
+		@param position position where the object is created
+		@param rotation rotation angle applied locally to object
+		@objName the name of the object entity
+		@returns scene object if it was successfully created, NULL otherwise
+		@remark internally stores pointer to object
+	*/
+	virtual SceneNode *GenerateSceneObject(const Vector3 &position, 
+		const Vector3 &rotation, const String &objName);
+
+	/** Minimum angle for the random orientation.
+	*/
+	void SetMinAngle(Vector3 minAngle);
+	
+	/** Maximum angle for the random orientation.
+	*/
+	void SetMaxAngle(Vector3 maxAngle);
+	
+	/** Minimum possible random position.
+	*/
+	void SetMinPos(Vector3 minPos);
+	/** Maximum possible random position.
+	*/
+	void SetMaxPos(Vector3 maxPos);
+	/** Scale factor applied to each generated object.
+	*/
+	void SetScale(Vector3 scale);
+	
+	/** The number of created objects.
+	*/
+	int GetObjectCount();
+
+	/** Writes scene nodes to file.
+	*/
+	bool WriteObjects(const std::string &filename);
+
+	/** Loads scene nodes from file.
+	*/
+	bool LoadObjects(const std::string &filename);
+
+	/** Generates a scene object with the specified parameters
+		@param position the position of the scene object
+		@param orientation the orientation of the scene object
+		@param objName the mesh name of the scene object
+		@returns the created scene object
+	*/
+	SceneNode *GenerateSceneObject(const Vector3 &position, 
+		const Quaternion &orientation, const String &objName);
+
+	/** Gets pointer to list of generated scene nodes.
+	*/
+	SceneNodeList *GetGeneratedSceneNodes();
+	
+	/** Gets pointer to list of entities.
+	*/
+	EntityList *GetGeneratedEntities();
+
+	/** Removes generated object from scene graph.
+	*/
+	void RemoveGeneratedObjects();
+
+protected:
+
+	Vector3 mMinAngle;
+	Vector3 mMaxAngle;
+	Vector3 mMaxPos;
+	Vector3 mMinPos;
+	Vector3 mScale;
+
+	SceneManager *mSceneMgr;
+	
+	SceneNodeList mSceneNodes;
+	EntityList mEntities;
+};
+
+} // namespace Ogre
+
+#endif // SCENECONTENTGENERATOR_H_
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilitySceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilitySceneManager.h	(revision 115)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilitySceneManager.h	(revision 115)
@@ -0,0 +1,65 @@
+#ifndef _VisibilitySceneManager_H__
+#define _VisibilitySceneManager_H__
+
+#include "OgreSceneNodeHierarchyInterface.h"
+#include "VisibilityManager.h"
+
+#include <OgreSceneNode.h>
+#include <OgreSceneManager.h>
+#include <OgrePrerequisites.h>
+
+namespace Ogre {
+
+/**
+	This class implements the default scene manager, using occlusion queries for 
+	visibility culling.
+*/
+class VisibilitySceneManager: public SceneManager
+{
+public:
+	VisibilitySceneManager(GtpVisibility::VisibilityManager *visManager);
+	~VisibilitySceneManager();
+
+	/** Overriden from SceneManager. Renders the scene using occlusion culling.
+	@remark the type of algorithm is specified by the occlusion culling manager type
+	using by the visibility manager.
+	*/
+	void _renderVisibleObjects();
+	void _findVisibleObjects(Camera* cam, bool onlyShadowCasters);
+	void _updateSceneGraph(Camera* cam);
+
+	/** Sets the given option for the SceneManager
+			    @remarks
+		Options are:
+		"Algorithm", int *;			
+	*/
+	virtual bool setOption(const String &, const void *);
+	/** Gets the given option for the Scene VisibilityManager.
+	    @remarks
+		See setOption
+	*/
+	virtual bool getOption(const String &, void *);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys( StringVector &refKeys );
+
+	/** Sets the visibility manager.
+		@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+
+protected:
+	
+	SceneNodeHierarchyInterface *mHierarchyInterface;
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+
+	bool mUseDepthPass;
+	bool mShowVisualization;
+
+	bool mVisualizeCulledNodes;
+};
+} // namespace Ogre
+#endif // VisibilitySceneManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOctreeHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOctreeHierarchyInterface.h	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreOctreeHierarchyInterface.h	(revision 370)
@@ -0,0 +1,67 @@
+#ifndef _OctreeHierarchyInterface_H__
+#define _OctreeHierarchyInterface_H__
+
+#include <OgreOctree.h>
+#include <OgreOctreeSceneManager.h>
+#include "OgreSceneNodeHierarchyInterface.h"
+
+namespace Ogre {
+/**
+	This class implements the hierarchy interface for the Ogre octree hierarchy.
+*/
+class OctreeHierarchyInterface : public SceneNodeHierarchyInterface
+{
+public:
+	OctreeHierarchyInterface(OctreeSceneManager *sm, RenderSystem *rsys);
+	
+	/** Sets the number of nodes in this octree 
+		@remark do not confuse this with the OctreeNode class which is derived from SceneNode
+		@param num number of nodes in the octree
+	*/
+	void SetNumOctreeNodes(unsigned int num);
+
+	/** Gets the given option for the scene traverser.
+	    @remarks
+		See setOption
+	*/
+	void PullUpVisibility(GtpVisibility::HierarchyNode *node) const;
+	
+	/** Traverses and renders the given node.
+		@param node current node
+		@remark pushes children on a distance queue.
+	*/
+	void TraverseNode(GtpVisibility::HierarchyNode *node);
+	/** @copydoc HierarchyInterface::RenderNode */
+	void RenderNode(GtpVisibility::HierarchyNode *node);
+	bool IsLeaf(GtpVisibility::HierarchyNode *node) const;
+	bool HasGeometry(GtpVisibility::HierarchyNode *node) const;
+	float GetSquaredDistance(GtpVisibility::HierarchyNode *node) const;
+	
+	void SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const;
+	void SetLastVisited(GtpVisibility::HierarchyNode *node, const unsigned int frameId) const;
+
+	bool IsNodeVisible(GtpVisibility::HierarchyNode *node) const;
+	unsigned int LastVisited(GtpVisibility::HierarchyNode *node) const;
+
+	void VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+							 GtpVisibility::CullingType type) const;
+
+	void GetNodeGeometryList(GtpVisibility::HierarchyNode *node,
+							 GtpVisibility::GeometryVector *geometryList, 
+							 bool includeChildren);
+	
+protected:
+	/** Returns pointer to the bounding box of the node.
+		@param node current hierarchy node
+		@returns bounding box of current node
+	*/
+	AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node);
+	/** Returns squared distance of center of box with respect to the camera .
+		@param cam current camera
+		@param box axis aligned box
+	*/
+	Real GetSquaredViewDepth(const Camera* cam, const AxisAlignedBox* box) const;
+};
+} // namespace Ogre
+
+#endif // OctreeHierarchyInterface_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOctreeSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOctreeSceneManager.h	(revision 254)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityOctreeSceneManager.h	(revision 254)
@@ -0,0 +1,158 @@
+#ifndef _VisibilityOctreeSceneManager_H__
+#define _VisibilityOctreeSceneManager_H__
+
+#include <OgreSceneNode.h>
+#include <OgreOctreeSceneManager.h>
+#include <OgreOctreeNode.h>
+#include <OgreOctreeCamera.h>
+#include <OgrePrerequisites.h>
+
+#include "OgreOctreeHierarchyInterface.h"
+#include "VisibilityManager.h"
+
+namespace Ogre {
+
+/**
+	This class extends the octree scene manager, using 
+	occlusion queries for visibility culling.
+*/
+class __declspec(dllexport) VisibilityOctreeSceneManager: public OctreeSceneManager
+{
+public:
+	VisibilityOctreeSceneManager(GtpVisibility::VisibilityManager *visManager);
+	~VisibilityOctreeSceneManager();
+
+	void _renderVisibleObjects();
+	void _findVisibleObjects(Camera* cam, bool onlyShadowCasters);
+	void _updateSceneGraph(Camera* cam );
+
+	/** Sets the given option for the SceneManager
+		@remarks Options are: "Algorithm", int *;			
+	*/
+	
+	virtual bool setOption(const String &, const void *);
+	/** Gets the given option for the Scene VisibilityManager.
+	    @remarks
+		See setOption
+	*/
+	virtual bool getOption(const String &, void *);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Sets the visibility manager.
+		@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+	
+	/** Render a set of objects, see renderSingleObject for param definitions 
+		Override so we can handle delayed rendering of transparent objects
+	*/
+	virtual void renderObjects(const RenderPriorityGroup::TransparentRenderablePassList& objs, 
+            bool doLightIteration, const LightList* manualLightList = 0);
+
+	/** Writes out stats into the Ogre log file.
+	*/
+	void WriteLog();
+
+	/** Override pass so we can do the z-fail pass. 
+	*/
+	Pass* setPass(Pass* pass);
+
+	/** Override from SceneManager so we can skip all but first pass for depth pass. 
+	*/
+	bool validatePassForRendering(Pass* pass);
+
+	void RenderItemBuffer(RenderPriorityGroup* pGroup);
+	void RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass);
+	void renderQueueGroupObjects(RenderQueueGroup* pGroup);
+
+	/** Override from SceneManager so that sub entities can be assigned an id for item buffer.
+	*/
+	//Entity* createEntity(const String& entityName, const String& meshName);
+
+	/** Returns pointer to visibility manager.
+	*/
+	GtpVisibility::VisibilityManager *GetVisibilityManager();
+
+	/** Returns hierarchy interface.
+	*/
+	OctreeHierarchyInterface *GetHierarchyInterface();
+
+	void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
+	void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup);
+
+	void loadVisibilityConfig(const String& filename);
+
+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);
+	
+	/// the interface to the scene hierarchy.
+	OctreeHierarchyInterface *mHierarchyInterface;
+	/// manages all visibility options
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+	
+	/// if a visualization of the hierarchical culling is shown
+	bool mShowVisualization;
+
+	/// if the culled nodes are indicated in the visualization
+	bool mVisualizeCulledNodes;
+
+	/// 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;
+
+	/// 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 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;
+
+	/// if depth write should be enabled
+	bool mEnableDepthWrite;
+	/// if transparents are skipped during rendering
+	bool mSkipTransparents;
+
+	/// the depth pass (no lighting, just filling the depth buffer)
+	Pass *mDepthPass;
+	Pass *mItemBufferPass;
+
+	int mCurrentEntityId;
+	/// flag for passes which should not be deleted from queue during first traversal
+	int mLeavePassesInQueue;
+	
+
+	/// 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;
+
+	bool mIsHierarchicalCulling;
+};
+
+} // namespace Ogre
+
+#endif // VisibilityOctreeSceneManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBspHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBspHierarchyInterface.h	(revision 345)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreBspHierarchyInterface.h	(revision 345)
@@ -0,0 +1,48 @@
+#ifndef _BspHierarchyInterface_H__
+#define _BspHierarchyInterface_H__
+
+#include "OgrePlatformHierarchyInterface.h"
+
+namespace Ogre {
+/**
+	This class implements the hierarchy interface for the Ogre bsp hierarchy.
+*/
+class BspHierarchyInterface : public PlatformHierarchyInterface
+{
+public:
+	BspHierarchyInterface(SceneManager *sm, RenderSystem *rsys);
+
+	/** Gets the given option for the scene traverser.
+	    @remarks
+		See setOption
+	*/
+	//bool getOption( const String &, void * );
+	//bool getOptionKeys( StringVector &refKeys );
+	void PullUpVisibility(GtpVisibility::HierarchyNode *node) const;
+	/** Traverses given node.
+		@param node current node
+		@remark pushes children on the distance queue
+	*/
+	void TraverseNode(GtpVisibility::HierarchyNode *node);
+	void RenderNode(GtpVisibility::HierarchyNode *node);
+	bool IsLeaf(GtpVisibility::HierarchyNode *node) const;
+	bool HasGeometry(GtpVisibility::HierarchyNode *node) const;
+	float GetSquaredDistance(GtpVisibility::HierarchyNode *node) const;
+	
+	void SetNodeVisible(GtpVisibility::HierarchyNode *node, const bool visible) const;
+	void SetLastVisited(GtpVisibility::HierarchyNode *node, 
+						const unsigned int frameId) const;
+
+	bool IsNodeVisible(GtpVisibility::HierarchyNode *node) const;
+	unsigned int LastVisited(GtpVisibility::HierarchyNode *node) const;
+
+protected:
+	/** Returns pointer to the bounding box of the node.
+		@param node current hierarchy node
+		@returns bounding box of current node
+	*/
+	AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node);
+};
+} // namespace Ogre
+
+#endif // BspHierarchyInterface_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h	(revision 187)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformHierarchyInterface.h	(revision 187)
@@ -0,0 +1,162 @@
+#ifndef _PlatformHierarchyInterface_H__
+#define _PlatformHierarchyInterface_H__
+
+#include <OgreSceneManager.h>
+#include <OgrePrerequisites.h>
+#include <OgreCamera.h>
+#include <OgreRenderSystem.h>
+
+//#include "OgreSolidHalfBoundingBox.h"
+#include "OgreSolidBoundingBox.h"
+#include "HierarchyInterface.h"
+#include "VisibilityInfo.h"
+#include "OgrePlatformOcclusionQuery.h"
+
+/** This namespace contains the Ogre dependent classes.
+*/
+namespace Ogre {
+
+/**	Class which implements a hierarchy interface for a specific type of hierarchy.
+	@remark also provides methods for using occlusion queries on the hierarchy nodes
+*/
+class PlatformHierarchyInterface: public GtpVisibility::HierarchyInterface
+{
+public:
+	/** Construction taking the current scene manager and the current rendersystem as argument
+		@param sm current scene manager
+		@param rsys current render system 
+	*/
+	PlatformHierarchyInterface(SceneManager *sm, RenderSystem *rsys);
+	~PlatformHierarchyInterface();
+		
+	/** Returns next available occlusion query or creates new one.
+		@return the next occlusion query
+	*/
+	GtpVisibility::OcclusionQuery *GetNextOcclusionQuery();
+		
+	/** Sets the current camera used for the rendering.
+		@param cam the current camera
+	*/
+	void SetCamera(Camera *cam);
+	/** Sets the current camera used for culling.
+		@param cam the current camera
+		@remark the default is the camera used for rendering
+	*/
+	void SetCullCamera(Camera *cullCam);
+	/** Initialises this scene traverser for the current frame.
+		@remark This is a convenience method which resets the stats, 
+				sets the current camera, and initialises the distance queue.
+		@param cam the actual camera definding the view frustum
+		@param cullCam the camera used for culling. 
+		@remark If cullCam is null, the actual camera is used for both viewing and culling		
+	*/
+	void InitTraversal(Camera *cam, Camera *cullCam = NULL, int leavePassesInQueue = 0);
+	/** Checks if the node is visible from the current view frustum.
+		@param node the current node
+		@param intersects returns true if the current node intersects the near plane
+	*/
+	bool CheckFrustumVisible(GtpVisibility::HierarchyNode *node, bool &intersects);
+	/** Sets pointer to the current scene manager.
+		@param sm the scene manager 
+	*/
+	void SetSceneManager(SceneManager *sm);
+	/** Sets pointer to the current render system .
+		@param rsys the rendersystem 
+	*/
+	void SetRenderSystem(RenderSystem *rsys);
+	/** Returns pointer to bounding box of node.
+		@param node current hierarchy node
+		@returns bounding box of current node
+	*/
+	virtual AxisAlignedBox *GetBoundingBox(GtpVisibility::HierarchyNode *node) = 0;
+	/** Issue a occlusion query for this node. 
+		@param node the current hierarchy node
+		@param wasVisible if the node was visible in the last frame
+		@returns occlusion query for this node
+	*/
+	GtpVisibility::OcclusionQuery *IssueNodeOcclusionQuery(
+		GtpVisibility::HierarchyNode *node, const bool wasVisible);
+
+	/** Issue a occlusion query for this mesh.
+		@param mesh the mesh for which an occlusion query is issued.
+		@returns occlusion query for this mesh.
+	*/
+	GtpVisibility::OcclusionQuery *IssueMeshOcclusionQuery(GtpVisibility::Mesh *mesh);
+
+	/** If true, the interface finds and renders only objects which are marked as shadow casters.
+		@remark This is important for the shadow texture pass
+	*/
+	void SetOnlyShadowCasters(bool onlyShadowCasters);
+	/** see set 
+	*/
+	bool GetOnlyShadowCasters();
+	/** see set 
+	*/
+	bool GetTestGeometryForVisibleLeaves();
+	/** see set
+	*/
+	SceneManager *GetSceneManager();
+
+	/** see set 
+	*/
+	RenderSystem *GetRenderSystem();
+	
+	/** true if bounding box query is currently active. 
+	*/
+    bool IsBoundingBoxQuery();
+
+	GtpVisibility::OcclusionQuery *IssuePatchOcclusionQuery(GtpVisibility::Patch *patch);
+
+	/** Deletes all occlusion queries.
+	*/
+	void DeleteQueries();
+
+protected:
+	/** Renders the given geometry 
+	*/
+	void RenderGeometry(GtpVisibility::Mesh *geom);
+	
+	/** Renders the given patch 
+	*/
+	void RenderPatch(GtpVisibility::Patch *patch);
+
+	/** Materials for visualizing frustum and query culled nodes.
+	*/
+	void CreateNodeVizMaterials();
+
+	/** Returns pointer to current renderable bounding box geometry.
+	*/
+	SolidBoundingBox *GetSolidBoundingBox();
+
+	/** A pass that prepares an occlusion query.
+		@remark disables depth write, colour write, lighting,
+		vertex and fragment program.*/
+	//void SetOcclusionPass();
+
+	/** Renders given bounding box.
+		@param box the bounding box of the scene node to be rendered 
+	*/
+	void RenderBoundingBox(AxisAlignedBox *box);
+
+	/** Renderable of an aabb.
+	*/
+	SolidBoundingBox *mSolidBoundingBox;
+
+	SceneManager *mSceneManager;
+	RenderSystem *mRenderSystem;
+
+	Camera *mCamera;
+	Camera *mCullCamera;
+
+	AxisAlignedBox mBox;
+	
+	std::vector<PlatformOcclusionQuery *> mOcclusionQueries;
+
+	bool mOnlyShadowCasters;
+	int mLeavePassesInQueue;
+	bool mIsBoundingBoxQuery;
+};
+
+} // namespace Ogre
+
+#endif // PlatformHierarchyInterface_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidHalfBoundingBox.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidHalfBoundingBox.h	(revision 117)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidHalfBoundingBox.h	(revision 117)
@@ -0,0 +1,47 @@
+#ifndef _SolidHalfBoundingBox_H__
+#define _SolidHalfBoundingBox_H__
+
+#include "OgreWireBoundingBox.h"
+
+namespace Ogre {
+
+/** The renderable of one half of a solid bounding box.
+    @remarks
+        This class builds a solid renderable from a given aabb. A pointer to this class can be
+		added to a render queue to display the bounding box of an object.
+*/
+class SolidHalfBoundingBox : public WireBoundingBox
+{
+public:
+
+	SolidHalfBoundingBox();
+	/** Sets up the first or second half of a the solid box.
+		@param aab the axis aligned bounding box
+		@param isFirstHalf if it is the first or the second half
+	*/
+	void SetupBoundingBox(const AxisAlignedBox& aabb, const bool isFirstHalf);
+	
+	/** Builds the wireframe line list.
+		@param aab the axis aligned bounding box for setting up the vertices
+		@param first or second half of the box
+    */
+	void SetupBoundingBoxVertices(const AxisAlignedBox& aab, const bool isFirstHalf);
+
+protected:
+   
+	/** 
+		Sets the material used for occlusion queries. 
+		@remark the material is called "Visibility/QueryMaterial" and
+		uses no lighting, no depth write, and no colours
+	*/
+	void SetOcclusionQueryMaterial();
+	/** Whether this half box is the first or the second half of the bounding box. 
+	*/
+	bool mIsFirstHalf;	
+};
+
+}// namespace Ogre
+
+#endif // SolidHalfBoundingBox
+
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformQueryManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformQueryManager.h	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgrePlatformQueryManager.h	(revision 316)
@@ -0,0 +1,60 @@
+#ifndef _PlatformQueryManager_H__
+#define _PlatformQueryManager_H__
+
+#include "VisibilityInfo.h"
+#include "QueryManager.h"
+#include "OgrePlatformHierarchyInterface.h"
+
+namespace Ogre {
+  
+/**
+	Class which implements the QueryManager for Ogre scene queries.
+*/
+class __declspec(dllexport) PlatformQueryManager: public GtpVisibility::QueryManager
+{
+public:
+    /** Constructor taking a hierarchy interface as an argument. This allows to operate
+	    on different hierarchy types, while reusing the implementation of the query methods.
+    */
+	PlatformQueryManager(PlatformHierarchyInterface *hierarchyInterface, 
+		                 Viewport *vp, int queryModes);
+    
+    /** 
+	Uses the specified point to execute the visibility query in all directions. 
+	@sa ComputeCameraVisibility()
+    */
+    void ComputeFromPointVisibility(const Vector3 &point,
+			       GtpVisibility::NodeInfoContainer *visibleNodes,
+			       GtpVisibility::MeshInfoContainer *visibleGeometry,
+				   GtpVisibility::PatchInfoContainer *visiblePatches,
+			       bool relativeVisibility = false);
+  
+	void ComputeCameraVisibility(const Camera &camera,
+			       GtpVisibility::NodeInfoContainer *visibleNodes,
+			       GtpVisibility::MeshInfoContainer *visibleGeometry,
+				   GtpVisibility::PatchInfoContainer *visiblePatches,
+			       bool relativeVisibility = false);
+  
+	bool ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine = false);  
+
+	/** Sets a viewport for rendering.
+	*/
+	void SetViewport(Viewport *vp);
+
+protected:
+
+	void CollectItemBufferResults(
+				GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches);
+
+	void InitItemBuffer(GtpVisibility::MeshInfoContainer *visibleGeometry,
+						GtpVisibility::PatchInfoContainer *visiblePatches);
+
+	Viewport *mViewport;
+	
+	bool mWasInitialised;
+};
+
+} // namespace Ogre
+
+#endif // PlatformQueryManager
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityBspSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityBspSceneManager.h	(revision 59)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityBspSceneManager.h	(revision 59)
@@ -0,0 +1,61 @@
+#ifndef _VisibilityBspSceneManager_H__
+#define _VisibilityBspSceneManager_H__
+
+#include <OgreSceneNode.h>
+#include <OgreBspSceneManager.h>
+#include <OgreOctreeNode.h>
+#include <OgreOctreeCamera.h>
+#include <OgrePrerequisites.h>
+
+#include "OgreBspHierarchyInterface.h"
+#include "GtpVisibility/Manager.h"
+
+namespace Ogre {
+
+/**
+	This class extends the octree scene manager, using 
+	occlusion queries for visibility culling.
+*/
+class VisibilityBspSceneManager: public BspSceneManager
+{
+public:
+	VisibilityBspSceneManager(GtpVisibility::Manager *visManager);
+	~VisibilityBspSceneManager();
+
+	void _renderVisibleObjects();
+	void _findVisibleObjects(Camera* cam, bool onlyShadowCasters);
+	void _updateSceneGraph(Camera* cam );
+
+	/** Sets the given option for the SceneManager
+			    @remarks
+		Options are:
+		"Algorithm", int *;			
+	*/
+	
+	virtual bool setOption(const String &, const void *);
+	/** Gets the given option for the Scene Manager.
+	    @remarks
+		See setOption
+	*/
+	virtual bool getOption(const String &, void *);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Sets the visibility manager.
+		@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::Manager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::Manager *getVisibilityManager( void );
+
+protected:
+	
+	BspHierarchyInterface *mHierarchyInterface;
+	GtpVisibility::Manager *mVisibilityManager;
+};
+
+} // namespace Ogre
+
+#endif // VisibilityBspSceneManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreTerrainContentGenerator.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreTerrainContentGenerator.h	(revision 183)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreTerrainContentGenerator.h	(revision 183)
@@ -0,0 +1,56 @@
+#ifndef _TERRAINCONTENTGENERATOR_H__
+#define _TERRAINCONTENTGENERATOR_H__
+
+#include "OgreSceneContentGenerator.h"
+
+#define MAX_HEIGHT 5000 // maximal possible height for object position
+
+namespace Ogre {
+
+/** Class which executes a simple ray query.
+*/
+class __declspec(dllexport) RayQueryExecutor
+{
+public:
+	RayQueryExecutor(SceneManager *sm);
+	~RayQueryExecutor();
+	
+	bool executeRayQuery(Vector3 *result, const Vector3 &pos, const Vector3 &dir);
+	bool RayQueryExecutor::executeRayQuery( Vector3 *result, const Ray &ray);
+
+protected:
+	
+	RaySceneQuery *mRaySceneQuery;
+};
+
+/** 
+	This class used to fill a terrain with content, e.g., 
+	it randomly fills a terrain with objects of a specific type.
+*/
+class __declspec(dllexport) TerrainContentGenerator: public SceneContentGenerator
+{
+public:
+	TerrainContentGenerator(SceneManager *sm);
+	~TerrainContentGenerator();
+
+	/** Generates objects and places it on the terrain.
+	*/
+	SceneNode *GenerateSceneObject(const Vector3 &position, 
+		const Vector3 &rotation, const String &objName);
+	/** Generates objects and optionally places it on the terrain.
+		@param clampToTerrain if true, scene object is clamped to the terrain
+	*/
+	SceneNode *GenerateSceneObject(const Vector3 &position, 
+		const Vector3 &rotation, const String &objName, const bool clampToTerrain);
+	
+	/** The offset is added to objects when they are put into the terrain.
+	*/
+	void SetOffset(Real offset);
+
+protected:
+	RayQueryExecutor *mRayQueryExecutor;
+	Real mOffset;
+};
+
+} // namespace Ogre
+#endif // _TERRAINCONTENTGENERATOR_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityDotSceneManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityDotSceneManager.h	(revision 59)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreVisibilityDotSceneManager.h	(revision 59)
@@ -0,0 +1,58 @@
+#ifndef _VisibilityDotSceneManager_H__
+#define _VisibilityDotSceneManager_H__
+
+#include <OgreSceneNode.h>
+#include <DotSceneManager.h>
+#include <OgrePrerequisites.h>
+#include "VisibilityManager.h"
+#include "OgreSceneNodeHierarchyInterface.h"
+
+namespace Ogre {
+
+/**
+	This class extends the dot scene manager, using occlusion queries for 
+	visibility culling. 
+	@remark the scene manager can operate on Ogre scene descriptions in 
+	XML defined by the ".scene" format
+*/
+class VisibilityDotSceneManager: public DotSceneManager
+{
+public:
+	VisibilityDotSceneManager(GtpVisibility::VisibilityManager *visManager);
+	~VisibilityDotSceneManager();
+
+	void _renderVisibleObjects();
+	void _findVisibleObjects(Camera* cam, bool onlyShadowCasters);
+	void _updateSceneGraph(Camera* cam);
+
+	/** Sets the given option for the SceneManager
+		@remarks
+		Options are:
+		"Algorithm", int *;			
+	*/
+	virtual bool setOption(const String &, const void *);
+	/** Gets the given option for the Scene VisibilityManager.
+	    @remarks
+		See setOption
+	*/
+	virtual bool getOption(const String &, void *);
+
+	bool getOptionValues(const String & key, StringVector &refValueList);
+	bool getOptionKeys(StringVector &refKeys);
+
+	/** Sets the visibility manager.
+		@param visManager the visibility manager
+	*/
+	void setVisibilityManager(GtpVisibility::VisibilityManager *visManager);
+	/** See set.
+	*/
+	GtpVisibility::VisibilityManager *getVisibilityManager();
+
+protected:
+
+	Ogre::SceneNodeHierarchyInterface *mHierarchyInterface;
+	GtpVisibility::VisibilityManager *mVisibilityManager;
+};
+} // namespace Ogre
+
+#endif // VisibilityDotSceneManager_H
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidBoundingBox.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidBoundingBox.h	(revision 156)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreSolidBoundingBox.h	(revision 156)
@@ -0,0 +1,58 @@
+#ifndef _SolidBoundingBox_H__
+#define _SolidBoundingBox_H__
+
+#include "OgreSimpleRenderable.h"
+
+namespace Ogre {
+
+/** A renderable of a solid bounding box using a material with no depth write,
+	no colors, and no lighting.
+*/
+class __declspec(dllexport) SolidBoundingBox : public SimpleRenderable
+{
+public:
+
+	SolidBoundingBox();
+	~SolidBoundingBox();
+	/** Sets up the solid box.
+		@param aab the axis aligned bounding box
+	*/
+	void SetupBoundingBox(const AxisAlignedBox& aabb);
+	
+	/** Builds the wireframe line list.
+		@param aab the axis aligned bounding box for setting up the vertices
+    */
+	void SetupBoundingBoxVertices(const AxisAlignedBox& aab);
+
+	Real getSquaredViewDepth(const Camera* cam) const;
+
+	Real getBoundingRadius(void) const { return mRadius; }
+
+protected:
+	/** 
+		Sets the material used for occlusion queries. 
+		@remark the material is called "Visibility/QueryMaterial" and
+		uses no lighting, no depth write, and no colours
+	*/
+	void SetOcclusionQueryMaterial();
+
+	/** Override this method to prevent parent transforms (rotation,translation,scale)
+    */
+	void getWorldTransforms( Matrix4* xform ) const;
+    /** @copydoc Renderable::getWorldOrientation */
+    const Quaternion& getWorldOrientation(void) const;
+    /** @copydoc Renderable::getWorldPosition */
+    const Vector3& getWorldPosition(void) const;
+		
+    /** Builds the wireframe line list.
+    */
+	void setupBoundingBoxVertices(const AxisAlignedBox& aab);
+
+    Real mRadius;
+};
+
+}// namespace Ogre
+
+#endif // SolidBoundingBox
+
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreItemBufferQueryManager.h
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreItemBufferQueryManager.h	(revision 159)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/include/OgreItemBufferQueryManager.h	(revision 159)
@@ -0,0 +1,45 @@
+#ifndef _ItemBufferQueryManager_H__
+#define _ItemBufferQueryManager_H__
+
+#include "OgrePlatformQueryManager.h"
+
+namespace Ogre {
+  
+/**
+	Class which implements the QueryManager for Ogre scene queries using an item buffer,
+	i.e., the objects are rendered with their id used as unique color code. After reading
+	back the frame buffer, the visibility information can be established for each object.
+*/
+class __declspec(dllexport) ItemBufferQueryManager: public PlatformQueryManager
+{
+public:
+    /** Constructor taking a hierarchy interface as an argument. This allows to operate
+		on different hierarchy types, while reusing the implementation of the query methods.
+		@param renderPatches determines if the visibility of either patches or meshes is computed.
+    */
+	ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, Viewport *vp,
+						   const bool renderPatches);
+    
+    void ComputeCameraVisibility(const Camera &camera,
+			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
+			    bool relativeVisibility = false);
+    
+	bool ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine = false);  
+	
+protected:
+	/** Helper function used to initialise item buffer.
+	*/
+	void InitItemBuffer( 
+				InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches);
+	
+	/// if patches are used instead of meshes (only one at a time)
+	bool mRenderPatchesForItemBuffer;
+};
+
+} // namespace Ogre
+
+#endif // ItemBufferQueryManager
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.vcproj	(revision 316)
@@ -0,0 +1,265 @@
+<?xml version="1.0" encoding="windows-1250"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="7.10"
+	Name="Plugin_VisibilitySceneManager"
+	ProjectGUID="{80DECC17-BDDD-4412-8CF8-F7C1C17A7436}"
+	Keyword="Win32Proj">
+	<Platforms>
+		<Platform
+			Name="Win32"/>
+	</Platforms>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="..\lib\$(ConfigurationName)"
+			IntermediateDirectory="..\obj\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\GtpVisibility\include"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS;GTP_VISIBILITY_MODIFIED_OGRE"
+				MinimalRebuild="TRUE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="2"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="4"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain_d.lib CEGUIBase_d.lib OgreGUIRenderer_d.lib Plugin_OctreeSceneManager.lib Plugin_DotSceneManager.lib GtpVisibility.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="2"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\..\GtpVisibility\lib\$(ConfigurationName)&quot;"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				ProgramDatabaseFile="$(OutDir)/Plugin_VisibilitySceneManager.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="..\lib\$(ConfigurationName)"
+			IntermediateDirectory="..\obj\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			WholeProgramOptimization="TRUE">
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="TRUE"
+				ImproveFloatingPointConsistency="TRUE"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="TRUE"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="2"
+				AdditionalIncludeDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\include&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\include&quot;;&quot;$(OGRE_PATH)\Samples\Common\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include\CEGUI&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\include&quot;;&quot;$(OGRE_PATH)\OgreMain\include&quot;;&quot;$(OGRE_PATH)\Dependencies\include&quot;;..\include;..\..\GtpVisibility\include"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;GTP_VISIBILITY_MODIFIED_OGRE"
+				StringPooling="TRUE"
+				RuntimeLibrary="2"
+				BufferSecurityCheck="FALSE"
+				EnableFunctionLevelLinking="TRUE"
+				RuntimeTypeInfo="TRUE"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="TRUE"
+				DebugInformationFormat="3"/>
+			<Tool
+				Name="VCCustomBuildTool"/>
+			<Tool
+				Name="VCLinkerTool"
+				IgnoreImportLibrary="TRUE"
+				AdditionalDependencies="OgreMain.lib CEGUIBase.lib OgreGUIRenderer.lib Plugin_OctreeSceneManager.lib GtpVisibility.lib"
+				OutputFile="$(OutDir)/Plugin_VisibilitySceneManager.dll"
+				Version="0.99"
+				LinkIncremental="1"
+				SuppressStartupBanner="TRUE"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\OgreMain\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_ADDONS_PATH)\dotsceneoctree\PlugIns\DotSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\..\GtpVisibility\lib\$(ConfigurationName)&quot;;&quot;..\..\lib\$(ConfigurationName)&quot;;&quot;..\lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\lib\$(ConfigurationName)&quot;"
+				ModuleDefinitionFile="..\misc\OgreVisibilitySceneManager.def"
+				GenerateDebugInformation="TRUE"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/Plugin_VisibilitySceneManager.lib"
+				TargetMachine="1"/>
+			<Tool
+				Name="VCMIDLTool"/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(OutDir)\$(TargetFileName) $(OGRE_PATH)\Samples\Common\bin\$(ConfigurationName)"/>
+			<Tool
+				Name="VCPreBuildEventTool"/>
+			<Tool
+				Name="VCPreLinkEventTool"/>
+			<Tool
+				Name="VCResourceCompilerTool"/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"/>
+			<Tool
+				Name="VCWebDeploymentTool"/>
+			<Tool
+				Name="VCManagedWrapperGeneratorTool"/>
+			<Tool
+				Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="SceneManager_Plugins"
+			Filter="">
+			<Filter
+				Name="Header Files"
+				Filter="">
+				<File
+					RelativePath="..\include\OgreOctreeHierarchyInterface.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreTerrainContentGenerator.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreVisibilityOctreeSceneManager.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreVisibilityTerrainSceneManager.h">
+				</File>
+			</Filter>
+			<Filter
+				Name="Source Files"
+				Filter="">
+				<File
+					RelativePath="..\src\OgreBspHierarchyInterface.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreOctreeHierarchyInterface.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreTerrainContentGenerator.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreVisibilityOctreeSceneManager.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreVisibilityTerrainSceneManager.cpp">
+				</File>
+			</Filter>
+		</Filter>
+		<Filter
+			Name="VisibilitySceneManager"
+			Filter="">
+			<Filter
+				Name="Header Files"
+				Filter="h;hpp;hxx;hm;inl;inc">
+				<File
+					RelativePath="..\include\OgreBspHierarchyInterface.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreOcclusionQueriesQueryManager.h">
+				</File>
+				<File
+					RelativePath="..\include\OgrePlatformHierarchyInterface.h">
+				</File>
+				<File
+					RelativePath="..\include\OgrePlatformOcclusionQuery.h">
+				</File>
+				<File
+					RelativePath="..\include\OgrePlatformQueryManager.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreSceneContentGenerator.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreSceneNodeHierarchyInterface.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreSolidBoundingBox.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreSolidHalfBoundingBox.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreVisibilityOptionsManager.h">
+				</File>
+				<File
+					RelativePath="..\include\OgreVisibilitySceneManager.h">
+				</File>
+			</Filter>
+			<Filter
+				Name="Source Files"
+				Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm">
+				<File
+					RelativePath="..\src\OgreOcclusionQueriesQueryManager.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgrePlatformHierarchyInterface.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgrePlatformOcclusionQuery.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgrePlatformQueryManager.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreSceneContentGenerator.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreSceneNodeHierarchyInterface.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreSolidBoundingBox.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreSolidHalfBoundingBox.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreVisibilityOptionsManager.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreVisibilitySceneManager.cpp">
+				</File>
+				<File
+					RelativePath="..\src\OgreVisibilitySceneManagerDll.cpp">
+				</File>
+			</Filter>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.dsp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.dsp	(revision 59)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/scripts/Plugin_VisibilitySceneManager.dsp	(revision 59)
@@ -0,0 +1,137 @@
+# Microsoft Developer Studio Project File - Name="Plugin_OcclusionCullingSceneManager" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=Plugin_OcclusionCullingSceneManager - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE 
+!MESSAGE NMAKE /f "Plugin_OcclusionCullingSceneManager.mak".
+!MESSAGE 
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE 
+!MESSAGE NMAKE /f "Plugin_OcclusionCullingSceneManager.mak" CFG="Plugin_OcclusionCullingSceneManager - Win32 Debug"
+!MESSAGE 
+!MESSAGE Possible choices for configuration are:
+!MESSAGE 
+!MESSAGE "Plugin_OcclusionCullingSceneManager - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "Plugin_OcclusionCullingSceneManager - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE 
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF  "$(CFG)" == "Plugin_OcclusionCullingSceneManager - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "..\bin\Release"
+# PROP Intermediate_Dir "..\obj\Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /c
+# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\include" /I "$(OGRE_PATH)\OgreMain\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x418 /d "NDEBUG"
+# ADD RSC /l 0x418 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib OgreMain.lib /nologo /dll /machine:I386 /libpath:"$(OGRE_PATH)\OgreMain\lib\Release"
+# SUBTRACT LINK32 /pdb:none
+# Begin Special Build Tool
+SOURCE="$(InputPath)"
+PostBuild_Cmds=copy ..\bin\Release\*.dll $(OGRE_PATH)\Samples\Common\bin\Release
+# End Special Build Tool
+
+!ELSEIF  "$(CFG)" == "Plugin_OcclusionCullingSceneManager - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "..\bin\Debug"
+# PROP Intermediate_Dir "..\obj\Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /GZ /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\include" /I "$(OGRE_PATH)\OgreMain\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PLUGIN_OCCLUSIONCULLINGSCENEMANAGER_EXPORTS" /YX /FD /GZ /Zm200 /c
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x418 /d "_DEBUG"
+# ADD RSC /l 0x418 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib OgreMain_d.lib /nologo /dll /debug /machine:I386 /pdbtype:sept /libpath:"$(OGRE_PATH)\OgreMain\lib\Debug"
+# SUBTRACT LINK32 /pdb:none
+# Begin Special Build Tool
+SOURCE="$(InputPath)"
+PostBuild_Cmds=copy ..\bin\Debug\*.dll $(OGRE_PATH)\Samples\Common\bin\Debug
+# End Special Build Tool
+
+!ENDIF 
+
+# Begin Target
+
+# Name "Plugin_OcclusionCullingSceneManager - Win32 Release"
+# Name "Plugin_OcclusionCullingSceneManager - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingResourceManager.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingSceneManager.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\misc\OgreOcclusionCullingSceneManager.def
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\OgreOcclusionCullingSceneManagerDll.cpp
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=..\include\OgreOcclusionCullingResourceManager.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\include\OgreOcclusionCullingSceneManager.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneNodeHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneNodeHierarchyInterface.cpp	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneNodeHierarchyInterface.cpp	(revision 370)
@@ -0,0 +1,160 @@
+#include <OgreIteratorWrappers.h>
+#include <OgreCamera.h>
+#include <OgreSceneNode.h>
+#include <OgreEntity.h>
+#include <OgreSubEntity.h>
+#include <OgreLogManager.h>
+#include "OgreSceneNodeHierarchyInterface.h"
+#include "OgrePlatformOcclusionQuery.h"
+
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+SceneNodeHierarchyInterface::SceneNodeHierarchyInterface(SceneManager *sm, RenderSystem *rsys): 
+PlatformHierarchyInterface(sm, rsys)
+{		
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::TraverseNode(GtpVisibility::HierarchyNode *node)
+{
+	++ mNumTraversedNodes;
+	
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+
+	if (HasGeometry(node))
+	{
+		RenderNode(node);
+	}
+
+	// internal node: add children to priority queue for further processing
+	Node::ChildNodeIterator it = sceneNode->getChildIterator();
+				
+	while (it.hasMoreElements())			
+	{ 
+		mDistanceQueue->push(it.getNext());
+	}
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::RenderNode(GtpVisibility::HierarchyNode *node)
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+
+	if (sceneNode->lastRendered() != sceneNode->lastVisited())
+	{
+		sceneNode->setLastRendered(sceneNode->lastVisited());
+		mVisibleNodes.push_back(node);
+
+		mSceneManager->_renderSceneNode(mCamera, sceneNode, mLeavePassesInQueue);
+	}
+#endif
+}
+//-----------------------------------------------------------------------
+bool SceneNodeHierarchyInterface::IsLeaf(GtpVisibility::HierarchyNode *node) const
+{
+	return (static_cast<SceneNode *>(node)->numChildren() == 0);
+}
+//-----------------------------------------------------------------------
+bool SceneNodeHierarchyInterface::HasGeometry(GtpVisibility::HierarchyNode *node) const
+{
+	return static_cast<SceneNode *>(node)->numAttachedObjects() > 0;
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::PullUpVisibility(GtpVisibility::HierarchyNode *node) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+
+	while (sceneNode && !sceneNode->isNodeVisible())
+	{
+		sceneNode->setNodeVisible(true);
+		sceneNode = sceneNode->getParentSceneNode();
+	}
+#endif
+}
+//-----------------------------------------------------------------------
+float SceneNodeHierarchyInterface::GetSquaredDistance(GtpVisibility::HierarchyNode *node) const
+{
+	return static_cast<SceneNode *>(node)->getSquaredViewDepth(mCamera);
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::SetNodeVisible(GtpVisibility::HierarchyNode *node, 
+												 const bool visible) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+	sceneNode->setNodeVisible(visible);
+#endif
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::SetLastVisited(GtpVisibility::HierarchyNode *node, 
+												 const unsigned int frameId) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+	sceneNode->setLastVisited(frameId);
+#endif
+}
+//-----------------------------------------------------------------------
+bool SceneNodeHierarchyInterface::IsNodeVisible(GtpVisibility::HierarchyNode *node) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+	return sceneNode->isNodeVisible();
+#else
+	return true;
+#endif
+}
+//-----------------------------------------------------------------------
+unsigned int SceneNodeHierarchyInterface::LastVisited(GtpVisibility::HierarchyNode *node) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	SceneNode *sceneNode = static_cast<SceneNode *>(node);
+	return sceneNode->lastVisited();
+#else
+	return 0;
+#endif
+}
+//-----------------------------------------------------------------------
+AxisAlignedBox *SceneNodeHierarchyInterface::GetBoundingBox(GtpVisibility::HierarchyNode *node)
+{
+	// only create renderable bounding box for new node
+	if (node != mSavedNode)
+	{
+		mSavedNode = node;
+		mBox = static_cast<SceneNode *>(node)->_getWorldAABB();
+	}
+
+	return &mBox;
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+													  GtpVisibility::CullingType type) const
+{
+	// TODO
+}
+//-----------------------------------------------------------------------
+void SceneNodeHierarchyInterface::GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
+											  GtpVisibility::GeometryVector *geometryList, 
+											  bool includeChildren)
+{
+	SceneNode::ObjectIterator objIt = 
+		static_cast<SceneNode *>(node)->getAttachedObjectIterator();
+
+	while (objIt.hasMoreElements())
+    {
+		MovableObject *movable = objIt.getNext();
+		
+		// we are interested only in the entities, i.e., instances of geometry
+		if (movable->getMovableType() == "Entity")
+		{
+			Entity *ent = static_cast<Entity *>(movable);
+			//std::stringstream d; d << "ent " << ent->getName(); 
+			//LogManager::getSingleton().logMessage(d.str());
+			geometryList->push_back(ent);
+		}
+    }
+}
+
+} // namespace Ogre	
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp	(revision 347)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityTerrainSceneManager.cpp	(revision 347)
@@ -0,0 +1,831 @@
+#include "OgreVisibilityTerrainSceneManager.h"
+#include "OgreVisibilityOptionsManager.h"
+#include <OgreMath.h>
+#include <OgreIteratorWrappers.h>
+#include <OgreRenderSystem.h>
+#include <OgreCamera.h>
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <OgreEntity.h>
+#include <OgreSubEntity.h>
+
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+VisibilityTerrainSceneManager::VisibilityTerrainSceneManager(
+							GtpVisibility::VisibilityManager *visManager): 
+mVisibilityManager(visManager), 
+mShowVisualization(false),
+mRenderNodesForViz(false),
+mRenderNodesContentForViz(false),
+mVisualizeCulledNodes(false),
+mLeavePassesInQueue(0),
+mDelayRenderTransparents(true),
+mUseDepthPass(false),
+mIsDepthPassPhase(false),
+mUseItemBuffer(false),
+//mUseItemBuffer(true),
+mIsItemBufferPhase(false),
+mCurrentEntityId(1),
+mEnableDepthWrite(true),
+mSkipTransparents(false),
+mRenderTransparentsForItemBuffer(true),
+mExecuteVertexProgramForAllPasses(true),
+mIsHierarchicalCulling(false)
+{
+	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
+	
+	//mDisplayNodes = true;
+	//mShowBoundingBoxes = true;
+	//mShowBoxes = true;
+
+	// TODO: set maxdepth to reasonable value
+	mMaxDepth = 50;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::InitDepthPass()
+{
+	MaterialPtr depthMat = MaterialManager::getSingleton().getByName("Visibility/DepthPass");
+
+	if (depthMat.isNull())
+    {
+		depthMat = MaterialManager::getSingleton().create(
+                "Visibility/DepthPass",
+                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+        mDepthPass = depthMat->getTechnique(0)->getPass(0);
+		mDepthPass->setColourWriteEnabled(false);
+		mDepthPass->setDepthWriteEnabled(true);
+		mDepthPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+	}
+}
+//-----------------------------------------------------------------------
+VisibilityTerrainSceneManager::~VisibilityTerrainSceneManager()
+{
+	OGRE_DELETE(mHierarchyInterface);
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::InitItemBufferPass()
+{
+	MaterialPtr itemBufferMat = MaterialManager::getSingleton().
+		getByName("Visibility/ItemBufferPass");
+
+	if (itemBufferMat.isNull())
+    {
+		// Init
+		itemBufferMat = MaterialManager::getSingleton().create("Visibility/ItemBufferPass",
+                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+		mItemBufferPass->setColourWriteEnabled(true);
+		mItemBufferPass->setDepthWriteEnabled(true);
+		mItemBufferPass->setLightingEnabled(true);
+		//mItemBufferPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+	}
+	//mItemBufferPass->setAmbient(1, 1, 0);
+}
+//-------------------------------------------------------------------------
+void VisibilityTerrainSceneManager::setWorldGeometry( const String& filename )
+{
+    // Clear out any existing world resources (if not default)
+    if (ResourceGroupManager::getSingleton().getWorldResourceGroupName() != 
+        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
+    {
+        ResourceGroupManager::getSingleton().clearResourceGroup(
+            ResourceGroupManager::getSingleton().getWorldResourceGroupName());
+    }
+    mTerrainPages.clear();
+    // Load the configuration
+    loadConfig(filename);
+
+    // Resize the octree, allow for 1 page for now
+    float max_x = mOptions.scale.x * mOptions.pageSize;
+    float max_y = mOptions.scale.y;
+    float max_z = mOptions.scale.z * mOptions.pageSize;
+
+	float maxAxis = std::max(max_x, max_y);
+	maxAxis = std::max(maxAxis, max_z);
+	resize( AxisAlignedBox( 0, 0, 0, maxAxis, maxAxis, maxAxis ) );
+    
+    setupTerrainMaterial();
+
+    setupTerrainPages();
+
+ }
+
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::PrepareVisualization(Camera *cam)
+{
+	// add player camera for visualization purpose
+	try 
+	{
+		Camera *c;
+		if ((c = getCamera("PlayerCam")) != NULL)
+		{
+			getRenderQueue()->addRenderable(c);
+		}   
+    }
+    catch (...)
+    {
+        // ignore
+    }
+	for (BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it)
+	{
+		getRenderQueue()->addRenderable(*it);
+	}
+	if (mRenderNodesForViz || mRenderNodesContentForViz)
+	{
+		// HACK: change node material so it is better suited for visualization
+		MaterialPtr nodeMat = MaterialManager::getSingleton().getByName("Core/NodeMaterial");
+		nodeMat->setAmbient(1, 1, 0);
+		nodeMat->setLightingEnabled(true);
+		nodeMat->getTechnique(0)->getPass(0)->removeAllTextureUnitStates();
+
+		for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
+		{
+			if (mRenderNodesForViz)
+			{
+				// render the leaf nodes
+				if (((*it)->numAttachedObjects() > 0) && ((*it)->numChildren() == 0) && 
+					 (*it)->getAttachedObject(0)->getMovableType() == "Entity")
+				{
+					getRenderQueue()->addRenderable((*it));
+				}
+
+				// addbounding boxes instead of node itself
+				//(*it)->_addBoundingBoxToQueue(getRenderQueue());
+			}
+			if (mRenderNodesContentForViz) 
+			{
+				(*it)->_addToRenderQueue(cam, getRenderQueue(), false);
+			}
+		}
+	}	
+}
+//-----------------------------------------------------------------------
+Pass *VisibilityTerrainSceneManager::setPass(Pass* pass)
+{
+	// TODO: setting vertex program is not efficient
+	//Pass *usedPass = ((mIsDepthPassPhase && !pass->hasVertexProgram()) ? mDepthPass : pass); 
+	
+	// set depth fill pass if we currently do not make an aabb occlusion query
+	Pass *usedPass = (mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery() ? 
+					  mDepthPass : pass);
+		
+	IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+	// set illumination stage to NONE so no shadow material is used 
+	// for depth pass or for occlusion query
+	if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
+	{
+		mIlluminationStage = IRS_NONE;
+	}
+	
+	// --- set vertex program of current pass in order to set correct depth
+	if (mExecuteVertexProgramForAllPasses && mIsDepthPassPhase && pass->hasVertexProgram())
+	{
+		// add vertex program of current pass to depth pass
+		mDepthPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mDepthPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mDepthPass->hasVertexProgram())
+	{
+		mDepthPass->setVertexProgram("");
+	}
+	
+
+	bool IsDepthWrite = usedPass->getDepthWriteEnabled();
+
+	// global option which enables / disables depth writes
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(false);
+	}
+	//else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
+	
+	Pass *result = SceneManager::setPass(usedPass);
+
+	// reset depth write
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(IsDepthWrite);
+	}
+
+	// reset illumination stage
+	mIlluminationStage = savedStage;
+
+	return result;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::_findVisibleObjects(Camera* cam,
+														bool onlyShadowCasters)
+{
+	//-- show visible scene nodes and octree bounding boxes from last frame
+	if (mShowVisualization)
+    {
+		PrepareVisualization(cam);
+	}
+	else 
+	{	
+		// for hierarchical culling, we interleave identification 
+		// and rendering of objects in _renderVisibibleObjects
+
+		// for the shadow pass we use only standard rendering
+		// because of low occlusion
+		if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+			mIlluminationStage == IRS_RENDER_TO_TEXTURE)
+		{
+			TerrainSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+		}
+		// only shadow casters will be rendered in shadow texture pass
+		// mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+	}
+	
+	
+	// -- delete lists stored for visualization
+	mVisible.clear();
+	mBoxes.clear();
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::_renderVisibleObjects()
+{
+
+	InitDepthPass(); 	  // create material for depth pass
+	InitItemBufferPass(); // create material for item buffer pass
+
+	// save ambient light to reset later
+	ColourValue savedAmbient = mAmbientLight;
+
+	//-- apply standard rendering for some modes (e.g., visualization, shadow pass)
+
+	if (mShowVisualization ||
+	   (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+	    mIlluminationStage == IRS_RENDER_TO_TEXTURE))
+	{	
+		IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+		if (mShowVisualization) 
+			// disable illumination stage to prevent rendering shadows
+			mIlluminationStage = IRS_NONE;
+
+		// standard rendering for shadow maps because of performance
+		TerrainSceneManager::_renderVisibleObjects();
+
+		mIlluminationStage = savedStage;
+	}
+	else //-- the hierarchical culling algorithm
+	{
+		// don't render backgrounds for item buffer
+		if (mUseItemBuffer)
+		{
+			clearSpecialCaseRenderQueues();
+			getRenderQueue()->clear();
+		}
+
+		//-- hierarchical culling
+		// the objects of different layers (e.g., background, scene, 
+		// overlay) must be identified and rendered one after another
+
+		//-- render all early skies
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+
+		TerrainSceneManager::_renderVisibleObjects();
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		// delete previously rendered content
+		_deleteRenderedQueueGroups();
+#endif
+
+		//-- prepare queue for visible objects (i.e., all but overlay and skies late)
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+	
+		// exclude this queues from hierarchical rendering
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+
+		// set all necessary parameters for 
+		// hierarchical visibility culling and rendering
+		InitVisibilityCulling(mCameraInProgress);
+
+		/** 
+		* the hierarchical culling algorithm
+		* for depth pass: we just find objects and update depth buffer
+		* for "delayed" rendering: we render some passes afterwards
+		* e.g., transparents, because they need front-to-back sorting
+		**/
+		
+		mVisibilityManager->ApplyVisibilityCulling();
+
+		// delete remaining renderables from queue (all not in mLeavePassesInQueue)
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		_deleteRenderedQueueGroups(mLeavePassesInQueue);
+#endif
+
+		//-- reset parameters
+		mIsDepthPassPhase = false;
+		mIsItemBufferPhase = false;
+		mSkipTransparents = false;
+		mLeavePassesInQueue = 0;
+		
+
+		// add visible nodes found by the visibility culling algorithm
+		if (mUseDepthPass)
+		{
+			for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
+			{
+				(*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
+			}
+		}
+		
+		//-- now we can render all remaining queue objects
+		// used for depth pass, transparents, overlay 
+		clearSpecialCaseRenderQueues();
+
+		TerrainSceneManager::_renderVisibleObjects();
+	}
+		
+	// HACK: set the new render level index, important to avoid cracks
+	// in terrain caused by LOD
+	TerrainRenderable::NextRenderLevelIndex();
+	
+	// reset ambient light
+	setAmbientLight(savedAmbient);
+
+	getRenderQueue()->clear(); // finally clear render queue
+	OGRE_DELETE(mRenderQueue); // HACK: should be cleared before...
+	//WriteLog(); // write out stats
+
+}
+
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::_updateSceneGraph(Camera* cam)
+{
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+
+	TerrainSceneManager::_updateSceneGraph(cam);
+}
+//-----------------------------------------------------------------------
+bool VisibilityTerrainSceneManager::setOption(const String & key, const void * val)
+{
+	if (key == "UseDepthPass")
+	{
+		mUseDepthPass = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "PrepareVisualization")
+	{
+		mShowVisualization = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderNodesForViz")
+	{
+		mRenderNodesForViz = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderNodesContentForViz")
+	{
+		mRenderNodesContentForViz = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyBoxEnabled")
+	{
+		mSkyBoxEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyPlaneEnabled")
+	{
+		mSkyPlaneEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyDomeEnabled")
+	{
+		mSkyDomeEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "VisualizeCulledNodes")
+	{
+		mVisualizeCulledNodes = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "DelayRenderTransparents")
+	{
+		mDelayRenderTransparents = (*static_cast<const bool *>(val));
+		return true;
+	}
+
+	if (key == "DepthWrite")
+	{
+		mEnableDepthWrite = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "UseItemBuffer")
+	{
+		mUseItemBuffer = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "ExecuteVertexProgramForAllPasses")
+	{ 
+		mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderTransparentsForItemBuffer")
+	{ 
+		mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "NodeVizScale")
+	{ 
+		OctreeNode::setVizScale(*static_cast<const float *>(val));
+		return true;
+	}
+
+	if (key == "UseArbQueries")
+	{
+		bool useArbQueries = (*static_cast<const bool *>(val));
+
+		if (useArbQueries)
+		{
+			mHierarchyInterface->DeleteQueries();
+			mDestRenderSystem->setConfigOption("ArbQueries", "Yes");
+		}
+		else
+		{
+			mHierarchyInterface->DeleteQueries();
+			mDestRenderSystem->setConfigOption("ArbQueries", "No");
+		}
+	}
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		setOption(key, val) || TerrainSceneManager::setOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityTerrainSceneManager::getOption(const String & key, void *val)
+{
+	if (key == "NumHierarchyNodes")
+	{
+		* static_cast<unsigned int *>(val) = (unsigned int)mNumOctants;
+		return true;
+	}
+	
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOption(key, val) && TerrainSceneManager::getOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityTerrainSceneManager::getOptionValues(const String & key, 
+													StringVector &refValueList)
+{
+	return TerrainSceneManager::getOptionValues( key, refValueList);
+}
+//-----------------------------------------------------------------------
+bool VisibilityTerrainSceneManager::getOptionKeys(StringVector & refKeys)
+{
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOptionKeys(refKeys) || TerrainSceneManager::getOptionKeys(refKeys);
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::setVisibilityManager(GtpVisibility::
+														 VisibilityManager *visManager)
+{
+	mVisibilityManager = visManager;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityTerrainSceneManager::getVisibilityManager( void )
+{
+	return mVisibilityManager;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::WriteLog()
+{
+	std::stringstream d;
+
+	d << "Depth pass: " << StringConverter::toString(mUseDepthPass) << ", "
+	  << "Delay transparents: " << StringConverter::toString(mDelayRenderTransparents) << ", "
+	  << "Use optimization: " << StringConverter::toString(mHierarchyInterface->GetTestGeometryForVisibleLeaves()) << ", "
+	  << "Algorithm type: " << mVisibilityManager->GetCullingManagerType() << ", "
+	  << "Hierarchy nodes: " << mNumOctants << ", " 
+	  << "Traversed nodes: " << mHierarchyInterface->GetNumTraversedNodes() << ", "
+	  << "Rendered nodes: " << mHierarchyInterface->GetNumRenderedNodes() << ", "
+	  << "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
+	  << "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
+      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << "\n";
+
+	LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::renderObjects(
+	const RenderPriorityGroup::TransparentRenderablePassList& objs, 
+    bool doLightIteration, const LightList* manualLightList)
+{
+	// for correct rendering, transparents must be rendered after hierarchical culling
+	if (!mSkipTransparents)
+	{
+		OctreeSceneManager::renderObjects(objs, doLightIteration, manualLightList);
+	}
+}
+//-----------------------------------------------------------------------
+bool VisibilityTerrainSceneManager::validatePassForRendering(Pass* pass)
+{
+	// skip all but first pass if we are doing the depth pass
+	if ((mIsDepthPassPhase || mIsItemBufferPhase) && pass->getIndex() > 0)
+	{
+		return false;
+	}
+	return SceneManager::validatePassForRendering(pass);
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::renderQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+	if (!mIsItemBufferPhase)
+	{
+		TerrainSceneManager::renderQueueGroupObjects(pGroup);
+		return;
+	}
+
+	//-- item buffer
+
+    // Iterate through priorities
+    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	while (groupIt.hasMoreElements())
+    {
+		RenderItemBuffer(groupIt.getNext());
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::RenderItemBuffer(RenderPriorityGroup* pGroup)
+{
+	// Do solids
+	RenderPriorityGroup::SolidRenderablePassMap solidObjs = pGroup->_getSolidPasses();
+
+	// ----- SOLIDS LOOP -----
+	RenderPriorityGroup::SolidRenderablePassMap::const_iterator ipass, ipassend;
+	ipassend = solidObjs.end();
+
+	for (ipass = solidObjs.begin(); ipass != ipassend; ++ipass)
+	{
+		// Fast bypass if this group is now empty
+		if (ipass->second->empty()) 
+			continue;
+
+		// Render only first pass
+		if (ipass->first->getIndex() > 0)
+			continue;
+
+		RenderPriorityGroup::RenderableList* rendList = ipass->second;
+		
+		RenderPriorityGroup::RenderableList::const_iterator irend, irendend;
+		irendend = rendList->end();
+			
+		for (irend = rendList->begin(); irend != irendend; ++irend)
+		{
+			std::stringstream d; d << "itembuffer, pass name: " << 
+				ipass->first->getParent()->getParent()->getName();
+				
+			LogManager::getSingleton().logMessage(d.str());
+			
+			RenderSingleObjectForItemBuffer(*irend, ipass->first);
+		}
+	}
+
+	// -- TRANSPARENT LOOP: must be handled differently 
+
+	// transparents are treated either as solids or completely discarded
+	if (mRenderTransparentsForItemBuffer)
+	{
+		RenderPriorityGroup::TransparentRenderablePassList transpObjs = 
+			pGroup->_getTransparentPasses();
+		RenderPriorityGroup::TransparentRenderablePassList::const_iterator 
+			itrans, itransend;
+
+		itransend = transpObjs.end();
+		for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
+		{
+			// like for solids, render only first pass
+			if (itrans->pass->getIndex() == 0)
+			{	
+				RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
+			}
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass)
+{
+	static LightList nullLightList;
+	
+	int col[4];
+	
+	// -- create color code out of object id
+	col[0] = (rend->getId() >> 16) & 255;
+	col[1] = (rend->getId() >> 8) & 255;
+	col[2] = rend->getId() & 255;
+//	col[3] = 255;
+
+	//mDestRenderSystem->setColour(col[0], col[1], col[2], col[3]);
+    
+	mItemBufferPass->setAmbient(ColourValue(col[0] / 255.0f,
+										    col[1] / 255.0f, 
+											col[2] / 255.0f, 1));
+
+	// set vertex program of current pass
+	if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mItemBufferPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mItemBufferPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mItemBufferPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mItemBufferPass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram("");
+	}
+
+	Pass *usedPass = setPass(mItemBufferPass); 
+
+
+	// Render a single object, this will set up auto params if required
+	renderSingleObject(rend, usedPass, false, &nullLightList);
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityTerrainSceneManager::GetVisibilityManager()
+{
+	return mVisibilityManager;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::InitVisibilityCulling(Camera *cam)
+{
+	// reset culling manager stats
+	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
+
+	// set depth pass flag before rendering
+	mIsDepthPassPhase = mUseDepthPass;
+
+	// item buffer needs full ambient lighting to use item colors as unique id
+	if (mUseItemBuffer) 
+	{
+		mIsItemBufferPhase = true;
+		setAmbientLight(ColourValue(1,1,1,1));
+	}
+
+
+	// set passes which are stored in render queue 
+	// for rendering AFTER hierarchical culling, i.e., passes which need 
+	// a special rendering order
+	mLeavePassesInQueue = 0;
+
+	if (!mUseDepthPass && !mUseItemBuffer)
+	{
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
+		{
+			// TODO: remove this pass because it should be processed during hierarchical culling
+			//mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
+
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DECAL;
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+
+			// just render ambient stuff
+			mIlluminationStage = IRS_AMBIENT;
+		}
+	
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	
+		// transparents should be rendered after hierarchical culling to 
+		// provide front-to-back ordering
+		if (mDelayRenderTransparents)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	}
+
+	// skip rendering transparents in the hierarchical culling
+	// (because they will be rendered afterwards)
+	mSkipTransparents = mUseDepthPass || 
+		(mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES);
+
+	// -- initialise interface for rendering traversal of the hierarchy
+	mHierarchyInterface->SetHierarchyRoot(mOctree);
+	
+	// possible two cameras (one for culling, one for rendering)
+	mHierarchyInterface->InitTraversal(mCameraInProgress, 
+							mCullCamera ? getCamera("CullCamera") : NULL,
+							mLeavePassesInQueue);
+		
+	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+OctreeHierarchyInterface *VisibilityTerrainSceneManager::GetHierarchyInterface()
+{
+	return mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::endFrame()
+{
+	TerrainRenderable::ResetRenderLevelIndex();
+}
+//-----------------------------------------------------------------------
+Entity* VisibilityTerrainSceneManager::createEntity(const String& entityName, 
+													const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+
+	return ent;
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+	// only render solid passes during hierarchical culling
+	if (mIsHierarchicalCulling)
+	{
+		RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+	    LightList lightList;
+
+		while (groupIt.hasMoreElements())
+		{
+			RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+			// Sort the queue first
+			pPriorityGrp->sort(mCameraInProgress);
+
+			// Clear light list
+			lightList.clear();
+
+			// Render all the ambient passes first, no light iteration, no lights
+			mIlluminationStage = IRS_AMBIENT;
+
+			OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPasses(), false, &lightList);
+			// Also render any objects which have receive shadows disabled
+			OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPassesNoShadow(), true);
+		}
+	}
+	else
+	{
+		OctreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(pGroup);
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityTerrainSceneManager::renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+   if (mIsHierarchicalCulling)
+   {
+	   // Iterate through priorities
+	   RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	   while (groupIt.hasMoreElements())
+	   {
+		   RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+		   // Sort the queue first
+		   pPriorityGrp->sort(mCameraInProgress);
+
+		   // Do (shadowable) solids
+		   OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPasses(), true);
+	   }
+   }
+   else
+   {
+	   SceneManager::renderModulativeStencilShadowedQueueGroupObjects(pGroup);
+   }
+}
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformOcclusionQuery.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformOcclusionQuery.cpp	(revision 115)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformOcclusionQuery.cpp	(revision 115)
@@ -0,0 +1,33 @@
+#include "OgrePlatformOcclusionQuery.h"
+#include <OgreLogManager.h>
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+PlatformOcclusionQuery::PlatformOcclusionQuery(RenderSystem *rsys)
+{
+	mHardwareOcclusionQuery = rsys->createHardwareOcclusionQuery();
+}
+//-----------------------------------------------------------------------
+PlatformOcclusionQuery::~PlatformOcclusionQuery()
+{
+	delete mHardwareOcclusionQuery;
+}
+//-----------------------------------------------------------------------
+void PlatformOcclusionQuery::BeginQuery()
+{
+	mHardwareOcclusionQuery->beginOcclusionQuery();
+}
+//-----------------------------------------------------------------------
+void PlatformOcclusionQuery::EndQuery()
+{
+	mHardwareOcclusionQuery->endOcclusionQuery();
+}
+//-----------------------------------------------------------------------
+bool PlatformOcclusionQuery::GetQueryResult(unsigned int &visiblePixels, 
+											const bool waitForResult) const
+{
+	return mHardwareOcclusionQuery->pullOcclusionQuery(&visiblePixels, waitForResult);
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManagerDll.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManagerDll.cpp	(revision 133)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManagerDll.cpp	(revision 133)
@@ -0,0 +1,87 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright © 2000-2002 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.
+-----------------------------------------------------------------------------
+*/
+
+#include <OgreVisibilityTerrainSceneManager.h>
+#include <OgreVisibilityOctreeSceneManager.h>
+//#include <OgreVisibilityDotSceneManager.h>
+
+#include <OgreHeightmapTerrainPageSource.h>
+#include <OgreRoot.h>
+#include <OgreLogManager.h>
+#include "VisibilityManager.h"
+#include "VisibilityEnvironment.h"
+
+GtpVisibility::VisibilityEnvironment *visEnv;
+GtpVisibility::VisibilityManager *visManager;
+
+namespace Ogre {
+
+VisibilityOctreeSceneManager *visibilityOctreePlugin;
+VisibilityTerrainSceneManager *visibilityTerrainPlugin;
+//VisibilityDotSceneManager *visibilityDotPlugin;
+
+HeightmapTerrainPageSource *heightmapTerrainPageSource;
+
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllStartPlugin(void)
+{
+	visEnv = new GtpVisibility::VisibilityEnvironment();
+	visManager = new GtpVisibility::VisibilityManager(visEnv);
+
+	// Create new scene manager
+	visibilityOctreePlugin = new VisibilityOctreeSceneManager(visManager);
+	visibilityTerrainPlugin = new VisibilityTerrainSceneManager(visManager);
+	//occlusionDotPlugin = new VisibilityDotSceneManager();
+
+	heightmapTerrainPageSource = new HeightmapTerrainPageSource();
+	
+	// Register
+	Root::getSingleton().setSceneManager(ST_GENERIC, visibilityOctreePlugin);
+	Root::getSingleton().setSceneManager(ST_EXTERIOR_CLOSE, visibilityTerrainPlugin);
+	//Root::getSingleton().setSceneManager(ST_GENERIC, occlusionDotPlugin);
+
+	visibilityTerrainPlugin->registerPageSource("Heightmap", heightmapTerrainPageSource);
+}
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllShutdownPlugin()
+{
+	visibilityTerrainPlugin->shutdown();
+	heightmapTerrainPageSource->shutdown();
+}
+//-----------------------------------------------------------------------
+extern "C" void __declspec(dllexport) dllStopPlugin()
+{
+	delete heightmapTerrainPageSource;
+
+	delete visibilityOctreePlugin;
+	delete visibilityTerrainPlugin;
+	//delete occlusionDotPlugin;
+	
+	delete visManager;
+	delete visEnv;
+}
+
+
+} //namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOptionsManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOptionsManager.cpp	(revision 254)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOptionsManager.cpp	(revision 254)
@@ -0,0 +1,87 @@
+#include "OgreVisibilityOptionsManager.h"
+
+namespace Ogre {
+//-----------------------------------------------------------------------
+VisibilityOptionsManager::VisibilityOptionsManager(
+							GtpVisibility::VisibilityManager *visManager, 
+							PlatformHierarchyInterface *hierarchyInterface):
+mVisibilityManager(visManager), 
+mHierarchyInterface(hierarchyInterface)
+{
+}
+//-----------------------------------------------------------------------
+bool VisibilityOptionsManager::setOption(const String & key, const void * val)
+{
+	if (key == "Algorithm")
+	{
+		// delete old queries (not needed for e.g., view frustum culling)
+		mHierarchyInterface->DeleteQueries();
+		mVisibilityManager->SetCullingManager(*static_cast<const 
+			GtpVisibility::VisibilityEnvironment::CullingManagerType *>(val));
+		return true;
+	}
+	if (key == "Threshold")
+	{
+		mVisibilityManager->SetVisibilityCullingThreshold(*static_cast<const int *>(val));
+		return true;
+	}
+	if (key == "AssumedVisibility")
+	{
+		mVisibilityManager->SetAssumedVisibilityForChc(*static_cast<const int *>(val));
+		return true;
+	}
+	if (key == "TestGeometryForVisibleLeaves")
+	{
+		mHierarchyInterface->TestGeometryForVisibleLeaves(*static_cast<const bool *>(val));
+		return true;
+	}
+	
+	return false;
+}
+//-----------------------------------------------------------------------
+bool VisibilityOptionsManager::getOption( const String & key, void *val )
+{
+	if (key == "NumTraversedNodes")
+	{
+		* static_cast <unsigned int *>(val) = 
+			mHierarchyInterface->GetNumTraversedNodes();
+		return true;
+	}
+	if (key == "NumRenderedNodes")
+	{
+		* static_cast <unsigned int *>(val) = 
+			mHierarchyInterface->GetNumRenderedNodes();
+		return true;
+	}
+	if (key == "NumQueryCulledNodes")
+	{
+		* static_cast <unsigned int *>(val) = 
+			mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes();
+		return true;
+	}
+	if (key == "NumFrustumCulledNodes")
+	{
+		* static_cast<unsigned int *>(val) = 
+			mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes();
+		return true;
+	}
+	if (key == "NumQueriesIssued")
+	{
+		* static_cast<unsigned int *>(val) = 
+			mVisibilityManager->GetCullingManager()->GetNumQueriesIssued();
+		return true;
+	}
+	
+	return false;
+}
+//-----------------------------------------------------------------------
+bool VisibilityOptionsManager::getOptionKeys(StringVector & refKeys)
+{
+	refKeys.push_back("NumRenderedNodes");
+	refKeys.push_back("NumTraversedNodes");
+	refKeys.push_back("NumQueryCulledNodes");
+	refKeys.push_back("NumFrustumCulledNodes");
+	
+	return true;
+}
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneContentGenerator.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneContentGenerator.cpp	(revision 415)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSceneContentGenerator.cpp	(revision 415)
@@ -0,0 +1,212 @@
+/**
+    \file 
+        SceneContentGenerator.cpp
+    \brief
+        Creates content for a scene.
+*/
+#include "OgreSceneContentGenerator.h"
+
+// limit for failed attempts to create objects (to avoids infinite loop)
+#define MAX_FAILED_ATTEMPTS 500000
+
+namespace Ogre {
+
+/*************************************************************/
+/*           SceneContentGenerator implementation            */
+/*************************************************************/
+
+//-----------------------------------------------------------------------
+SceneContentGenerator::SceneContentGenerator(SceneManager *sm):
+mSceneMgr(sm),
+mMinPos(Vector3(-70.0f, -70.0f, 0.0f)),
+mMaxPos(Vector3(70.0f, 70.0f, 600.0f)), 
+mMinAngle(Vector3(0.0f, 0.0f, 0.0f)),
+mMaxAngle(Vector3(360, 360, 360)),
+mScale(0.1, 0.1, 0.1)//, mObjectCount(0)
+{
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::GenerateScene(int numObjects, const String &objName)
+{
+	int new_size = GetObjectCount() + numObjects;
+	int failed_attempts = 0; // counter used to avoid invinite loop
+
+	//-- create random values between zero and one
+	while ((GetObjectCount() <  new_size) && 
+		   (failed_attempts < MAX_FAILED_ATTEMPTS))
+	{
+		// Setup the ray scene query
+		Vector3 rotation = Vector3(Math::RangeRandom(mMinAngle.x, mMaxAngle.x),
+								   Math::RangeRandom(mMinAngle.y, mMaxAngle.y),
+								   Math::RangeRandom(mMinAngle.z, mMaxAngle.z));
+
+		Vector3 position = Vector3(Math::RangeRandom(mMinPos.x, mMaxPos.x),
+								   Math::RangeRandom(mMinPos.y, mMaxPos.y),
+								   Math::RangeRandom(mMinPos.z, mMaxPos.z));
+
+		// failed to generate new object
+		if (!GenerateSceneObject(position, rotation, objName))
+			++ failed_attempts; 
+	}
+}
+//-----------------------------------------------------------------------
+SceneNode *SceneContentGenerator::GenerateSceneObject(const Vector3 &position, 
+					 const Quaternion &orientation, const String& objName)
+{
+	char name[25];
+
+	sprintf(name, "%s Entity%d", objName.c_str(), GetObjectCount());
+		
+	Entity *ent = mSceneMgr->createEntity(name, objName + ".mesh");
+	
+	ent->setCastShadows(true);
+
+	SceneNode *node = mSceneMgr->getRootSceneNode()->
+		createChildSceneNode(String(name) + "Node", position);
+
+	//std::stringstream d; d << "new node: " << name << "Node";
+	//Ogre::LogManager::getSingleton().logMessage(d.str());
+
+	//ent->setCastShadows(false);
+	node->attachObject(ent);
+	node->setScale(mScale);
+	node->setOrientation(orientation);
+
+	// store pointer to node and object
+	mSceneNodes.push_back(node);
+	mEntities.push_back(ent);
+	
+	return node;
+}
+//-----------------------------------------------------------------------
+SceneNode *SceneContentGenerator::GenerateSceneObject(const Vector3 &position, 
+					 const Vector3 &rotation, const String& objName)
+{
+	Matrix3 mat;
+	mat.FromEulerAnglesYXZ(Degree(rotation.x), Degree(rotation.y),
+						   Degree(rotation.z));
+
+	return GenerateSceneObject(position, Quaternion(mat), objName);
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::SetMinAngle(Vector3 minAngle)
+{
+	mMinAngle = minAngle;
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::SetMaxAngle(Vector3 maxAngle)
+{
+	mMaxAngle = maxAngle;
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::SetMinPos(Vector3 minPos)
+{
+	mMinPos = minPos;
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::SetMaxPos(Vector3 maxPos)
+{
+	mMaxPos = maxPos;
+}
+//-----------------------------------------------------------------------
+int SceneContentGenerator::GetObjectCount()
+{
+	return (int)mSceneNodes.size();
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::SetScale(Vector3 scale)
+{
+	mScale = scale;
+}
+//-----------------------------------------------------------------------
+bool SceneContentGenerator::WriteObjects(const std::string &filename)
+{
+	std::ofstream ofstr(filename.c_str());
+	std::vector<SceneNode *>::const_iterator it, it_end;
+
+	it_end = mSceneNodes.end();
+
+	if(!ofstr.is_open())
+		return false;
+
+	char str[100];
+
+	for(it = mSceneNodes.begin(); it < it_end; ++it)
+	{
+		SceneNode *node = (*it);
+		sscanf(node->getName().c_str(), "%s ", str); // write name of mesh
+
+		ofstr << str << " "
+			  << StringConverter::toString(node->getPosition()) << " " 
+			  << StringConverter::toString(node->getOrientation()) << " "
+			  << StringConverter::toString(node->getScale()) << "\n";
+	}
+	ofstr.close();
+
+	return true;
+}
+//-----------------------------------------------------------------------
+bool SceneContentGenerator::LoadObjects(const std::string &filename)
+{
+	std::ifstream ifstr(filename.c_str());
+	
+	char line[256];
+
+	Vector3 position;
+	Quaternion orientation;
+	char objName[100];
+
+	if (!ifstr.is_open())
+		return false;
+
+	//mSceneNodes.clear(); // reset list of objects
+
+	while (!ifstr.eof()) 
+	{
+		ifstr.getline(line, 256);
+		sscanf(line, "%s %f %f %f %f %f %f %f %f %f %f", objName, 
+			&position.x, &position.y, &position.z,
+			&orientation.w, &orientation.x, &orientation.y, &orientation.z,
+			&mScale.x, &mScale.y, &mScale.z);
+
+		GenerateSceneObject(position, orientation, objName);
+		
+		//std::stringstream d; d << StringConverter::toString(position) << " " << StringConverter::toString(orientation);
+		//LogManager::getSingleton().logMessage(d.str());
+	}
+	ifstr.close();
+
+	return true;
+}
+//-----------------------------------------------------------------------
+SceneNodeList *SceneContentGenerator::GetGeneratedSceneNodes()
+{
+	return &mSceneNodes;
+}
+//-----------------------------------------------------------------------
+EntityList *SceneContentGenerator::GetGeneratedEntities()
+{
+	return &mEntities;
+}
+//-----------------------------------------------------------------------
+void SceneContentGenerator::RemoveGeneratedObjects()
+{
+	//-- destroy scene nodes and detach entities
+	while (!mSceneNodes.empty())
+	{
+		SceneNode *node = mSceneNodes.back();
+		mSceneNodes.pop_back();
+		
+		//node->detachAllObjects();
+		mSceneMgr->destroySceneNode(node->getName());
+	}
+	//-- remove and destroy entities
+	while (!mEntities.empty())
+	{
+		Entity *ent = mEntities.back();
+		mEntities.pop_back();
+		
+		mSceneMgr->removeEntity(ent);
+	}
+}
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManager.cpp	(revision 155)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilitySceneManager.cpp	(revision 155)
@@ -0,0 +1,143 @@
+#include <OgreMath.h>
+#include <OgreIteratorWrappers.h>
+#include <OgreRenderSystem.h>
+#include <OgreCamera.h>
+#include "OgreVisibilitySceneManager.h"
+#include "OgreSceneNodeHierarchyInterface.h"
+#include "OgreVisibilityOptionsManager.h"
+
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+VisibilitySceneManager::VisibilitySceneManager(GtpVisibility::VisibilityManager *visManager)
+:mVisibilityManager(visManager), mUseDepthPass(false), mShowVisualization(false)
+{
+	mHierarchyInterface = 
+		new SceneNodeHierarchyInterface(this, mDestRenderSystem);
+}
+//-----------------------------------------------------------------------
+VisibilitySceneManager::~VisibilitySceneManager()
+{
+	delete mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+void VisibilitySceneManager::_findVisibleObjects(Camera* cam, bool onlyShadowCasters)
+{
+	mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+	// does nothing if hierarchical culling is used =>
+	// we interleave identification and rendering of objects 
+	// in _renderVisibibleObjects
+	if (!mUseDepthPass)
+	{
+		SceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+		return;	
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilitySceneManager::_renderVisibleObjects()
+{
+	if (!mShowVisualization)
+	{
+		mHierarchyInterface->SetHierarchyRoot(mSceneRoot);
+		mHierarchyInterface->InitTraversal(mCameraInProgress);
+
+		// reset culling manager stats
+		mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
+	}
+
+	// standard terrain scenemanager rendering without hierarchical culling
+	if (!mUseDepthPass || mShowVisualization)
+	{	
+		SceneManager::_renderVisibleObjects();
+	
+		return;
+	} 
+
+	//-- hierarchical culling
+	// the objects of different layers (e.g., background, scene, 
+	// overlay) must be identified and rendered one after another
+
+	//-- render background
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+	addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+	SceneManager::_renderVisibleObjects();
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+
+	//-- render visible objects (i.e., all but overlay)
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+
+
+	/** 
+	* the hierarchical culling algorithm
+	**/
+	mVisibilityManager->ApplyVisibilityCulling();
+
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+
+	//-- render overlay
+	clearSpecialCaseRenderQueues();
+	SceneManager::_renderVisibleObjects();
+
+	//WriteLog(); // write out stats
+}
+//-----------------------------------------------------------------------
+void VisibilitySceneManager::_updateSceneGraph(Camera* cam)
+{
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+	
+	SceneManager::_updateSceneGraph(cam);
+}
+//-----------------------------------------------------------------------
+bool VisibilitySceneManager::setOption(const String & key, const void * val)
+{
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		setOption(key, val) || SceneManager::setOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilitySceneManager::getOption(const String & key, void *val)
+{
+	if (key == "NumHierarchyNodes")
+	{
+		* static_cast<unsigned int *>(val) = (unsigned int)mSceneNodes.size();
+		return true;
+	}
+	
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOption(key, val) && SceneManager::getOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilitySceneManager::getOptionValues(const String & key, StringVector  &refValueList)
+{
+	return SceneManager::getOptionValues(key, refValueList);
+}
+//-----------------------------------------------------------------------
+bool VisibilitySceneManager::getOptionKeys(StringVector & refKeys)
+{
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOptionKeys(refKeys) || SceneManager::getOptionKeys(refKeys);
+}
+//-----------------------------------------------------------------------
+void VisibilitySceneManager::setVisibilityManager(GtpVisibility::VisibilityManager *visManager)
+{
+	mVisibilityManager = visManager;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilitySceneManager::getVisibilityManager()
+{
+	return mVisibilityManager;
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOctreeHierarchyInterface.cpp	(revision 370)
@@ -0,0 +1,171 @@
+#include "OgreOctreeHierarchyInterface.h"
+#include "OgreVisibilityOctreeSceneManager.h"
+#include <OgreOctree.h>
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+OctreeHierarchyInterface::OctreeHierarchyInterface(OctreeSceneManager *sm, RenderSystem *rsys): 
+SceneNodeHierarchyInterface(sm, rsys)
+{
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::TraverseNode(GtpVisibility::HierarchyNode *node)
+{
+	++ mNumTraversedNodes;
+
+	Octree *octree = static_cast<Octree *>(node);
+
+	// if we come across some renderable geometry => render it
+	if (octree->mNodes.size() > 0)
+	{
+		RenderNode(node);
+	}
+	
+	//if (octree->numNodes() > (int)octree->mNodes.size()) // if not all subtrees are empty
+	if (!IsLeaf(node))
+	{
+		for(int i=0; i<8; ++i)
+		{
+			Octree *nextChild = 
+				octree->mChildren[(i & 4) >> 2][(i & 2) >> 1][i & 1];
+			
+			if (nextChild)
+			{
+				mDistanceQueue->push(nextChild);
+			}
+		}
+	}
+}
+//-----------------------------------------------------------------------
+bool OctreeHierarchyInterface::IsLeaf(GtpVisibility::HierarchyNode *node) const
+{
+	Octree *octree = static_cast<Octree *>(node);
+	// HACK: if there are subtrees, they are empty => we are not interested in them
+	return octree->numNodes() == (int)octree->mNodes.size();
+}
+//-----------------------------------------------------------------------
+bool OctreeHierarchyInterface::HasGeometry(GtpVisibility::HierarchyNode *node) const
+{
+	return static_cast<Octree *>(node)->mNodes.size() > 0;
+}
+//-----------------------------------------------------------------------
+float OctreeHierarchyInterface::GetSquaredDistance(GtpVisibility::HierarchyNode *node) const
+{
+	AxisAlignedBox *box = &static_cast<Octree *>(node)->mBox;
+	Vector3 pos = ((box->getMaximum() - box->getMinimum()) * 0.5) + box->getMinimum();
+	
+	return (mCullCamera->getDerivedPosition() - pos).squaredLength();
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::SetNodeVisible(GtpVisibility::HierarchyNode *node, 
+											  const bool visible) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	static_cast<Octree *>(node)->setOctreeVisible(visible);
+#endif
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::SetLastVisited(GtpVisibility::HierarchyNode *node, 
+											  const unsigned int frameId) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	static_cast<Octree *>(node)->setLastVisited(frameId);
+#endif
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::PullUpVisibility(GtpVisibility::HierarchyNode *node) const
+{		
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	Octree *octant = static_cast<Octree *>(node);
+
+	while (octant && !octant->isOctreeVisible())
+	{
+		octant->setOctreeVisible(true);
+		octant = octant->getParent();
+	}
+#endif
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::RenderNode(GtpVisibility::HierarchyNode *node)
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	Octree *octant = static_cast<Octree *>(node);
+
+	if (octant->lastRendered() != mFrameId)
+	{
+		octant->setLastRendered(mFrameId);
+
+		dynamic_cast<OctreeSceneManager *>(mSceneManager)->_renderOctant(mCamera, 
+			octant, mOnlyShadowCasters, mLeavePassesInQueue);
+
+		mVisibleNodes.push_back(node);
+	}
+#endif
+	
+}
+//-----------------------------------------------------------------------
+bool OctreeHierarchyInterface::IsNodeVisible(GtpVisibility::HierarchyNode *node) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	return static_cast<Octree *>(node)->isOctreeVisible();
+#else
+	return true;
+#endif
+}
+//-----------------------------------------------------------------------
+unsigned int OctreeHierarchyInterface::LastVisited(GtpVisibility::HierarchyNode *node) const
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	return static_cast<Octree *>(node)->lastVisited();
+#else
+	return 0;
+#endif
+}
+//-----------------------------------------------------------------------
+AxisAlignedBox *OctreeHierarchyInterface::GetBoundingBox(GtpVisibility::HierarchyNode *node)
+{
+	if (node != mSavedNode)
+	{
+		mSavedNode = node;
+	    //static_cast<Octree *>(node)->_getCullBounds(&mBox);
+		mBox = static_cast<Octree *>(node)->_getWorldAABB();
+	}
+
+	return &mBox;
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::VisualizeCulledNode(GtpVisibility::HierarchyNode *node, 
+												   GtpVisibility::CullingType type) const
+{
+	WireBoundingBox *box = static_cast<Octree *>(node)->getWireBoundingBox();
+
+	if (type == GtpVisibility::FRUSTUM_CULLED)
+	{
+		box->setMaterial("FrustumCulledNodesMaterial");
+	}
+	else // type == GtpVisibility::QUERY_CULLED
+	{
+		box->setMaterial("QueryCulledNodesMaterial");
+	}
+
+	dynamic_cast<OctreeSceneManager *>(mSceneManager)->getBoxes()->push_back(box);
+}
+//-----------------------------------------------------------------------
+void OctreeHierarchyInterface::GetNodeGeometryList(GtpVisibility::HierarchyNode *node,	
+										   GtpVisibility::GeometryVector *geometryList, 
+										   bool includeChildren)
+{
+	NodeList::const_iterator nodeIt, nodeIt_end;
+	nodeIt_end = static_cast<Octree *>(node)->mNodes.end();
+
+	for (nodeIt = static_cast<Octree *>(node)->mNodes.begin(); nodeIt != nodeIt_end; ++nodeIt)
+	{
+		SceneNodeHierarchyInterface::GetNodeGeometryList(*nodeIt, geometryList, includeChildren);
+	}
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp	(revision 343)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityOctreeSceneManager.cpp	(revision 343)
@@ -0,0 +1,819 @@
+#include "OgreVisibilityOctreeSceneManager.h"
+#include "OgreVisibilityOptionsManager.h"
+#include <OgreMath.h>
+#include <OgreIteratorWrappers.h>
+#include <OgreRenderSystem.h>
+#include <OgreCamera.h>
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <OgreEntity.h>
+#include <OgreSubEntity.h>
+#include <OgreConfigFile.h>
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+VisibilityOctreeSceneManager::VisibilityOctreeSceneManager(
+	GtpVisibility::VisibilityManager *visManager)
+: 
+mVisibilityManager(visManager), 
+mShowVisualization(false),
+mRenderNodesForViz(false),
+mRenderNodesContentForViz(false),
+mVisualizeCulledNodes(false),
+mLeavePassesInQueue(0),
+mDelayRenderTransparents(true),
+//mDelayRenderTransparents(false),
+//mUseDepthPass(true),
+mUseDepthPass(false),
+mIsDepthPassPhase(false),
+mUseItemBuffer(false),
+//mUseItemBuffer(true),
+mIsItemBufferPhase(false),
+mCurrentEntityId(1),
+mEnableDepthWrite(true),
+mSkipTransparents(false),
+mRenderTransparentsForItemBuffer(true),
+mExecuteVertexProgramForAllPasses(true),
+mIsHierarchicalCulling(false)
+{
+	mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
+		
+	//mDisplayNodes = true;
+	//mShowBoundingBoxes = true;
+	//mShowBoxes = true;
+
+	// TODO: set maxdepth to reasonable value
+	mMaxDepth = 50;
+
+	//loadVisibilityConfig("GtpVisibility.cfg");
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::InitDepthPass()
+{
+	MaterialPtr depthMat = MaterialManager::getSingleton().getByName("Visibility/DepthPass");
+
+	if (depthMat.isNull())
+    {
+		depthMat = MaterialManager::getSingleton().create(
+                "Visibility/DepthPass",
+                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+		mDepthPass->setColourWriteEnabled(false);
+		mDepthPass->setDepthWriteEnabled(true);
+		mDepthPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mDepthPass = depthMat->getTechnique(0)->getPass(0);
+	}
+}
+//-----------------------------------------------------------------------
+VisibilityOctreeSceneManager::~VisibilityOctreeSceneManager()
+{
+	OGRE_DELETE(mHierarchyInterface);
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::InitItemBufferPass()
+{
+	MaterialPtr itemBufferMat = MaterialManager::getSingleton().
+		getByName("Visibility/ItemBufferPass");
+
+	if (itemBufferMat.isNull())
+    {
+		// Init
+		itemBufferMat = MaterialManager::getSingleton().create("Visibility/ItemBufferPass",
+                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+		mItemBufferPass->setColourWriteEnabled(true);
+		mItemBufferPass->setDepthWriteEnabled(true);
+		mItemBufferPass->setLightingEnabled(true);
+		//mItemBufferPass->setLightingEnabled(false);
+	}
+	else
+	{
+		mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
+	}
+	//mItemBufferPass->setAmbient(1, 1, 0);
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::PrepareVisualization(Camera *cam)
+{
+	// add player camera for visualization purpose
+	try 
+	{
+		Camera *c;
+		if ((c = getCamera("PlayerCam")) != NULL)
+		{
+			getRenderQueue()->addRenderable(c);
+		}   
+    }
+    catch(...)
+    {
+        // ignore
+    }
+	for (BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it)
+{
+		getRenderQueue()->addRenderable(*it);
+	}
+	if (mRenderNodesForViz || mRenderNodesContentForViz)
+	{
+		// change node material so it is better suited for visualization
+		MaterialPtr nodeMat = MaterialManager::getSingleton().getByName("Core/NodeMaterial");
+		nodeMat->setAmbient(1, 1, 0);
+		nodeMat->setLightingEnabled(true);
+		nodeMat->getTechnique(0)->getPass(0)->removeAllTextureUnitStates();
+
+		for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
+		{
+			if (mRenderNodesForViz)
+			{
+				if (((*it)->numAttachedObjects() > 0) && ((*it)->numChildren() == 0)
+					&& (*it)->getAttachedObject(0)->getMovableType() == "Entity")
+				getRenderQueue()->addRenderable((*it));
+
+				// addbounding boxes instead of node itself
+				//(*it)->_addBoundingBoxToQueue(getRenderQueue());
+			}
+			if (mRenderNodesContentForViz) 
+			{
+				(*it)->_addToRenderQueue(cam, getRenderQueue(), false);
+			}
+		}
+	}
+}
+//-----------------------------------------------------------------------
+Pass *VisibilityOctreeSceneManager::setPass(Pass* pass)
+{
+	// set depth fill pass if we currently do not make an aabb occlusion query
+	Pass *usedPass = (mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery() ? 
+					  mDepthPass : pass);
+
+	IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+	// set illumination stage to NONE so no shadow material is used 
+	// for depth pass or for occlusion query
+	if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
+	{
+		mIlluminationStage = IRS_NONE;
+	}
+
+	//-- set vertex program of current pass in order to set correct depth
+	if (mIsDepthPassPhase && mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
+    {
+		// add vertex program of current pass to depth pass
+		mDepthPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mDepthPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mDepthPass->hasVertexProgram())
+	{
+		mDepthPass->setVertexProgram("");
+	}
+
+	// store depth write flag to reset later
+	bool IsDepthWrite = usedPass->getDepthWriteEnabled();
+
+	// global option which enables / disables depth writes
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(false);
+	}
+	//else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
+
+	Pass *result = SceneManager::setPass(usedPass);
+
+	// reset depth write
+	if (!mEnableDepthWrite)
+	{
+		usedPass->setDepthWriteEnabled(IsDepthWrite);
+	}
+
+	// reset illumination stage
+	mIlluminationStage = savedStage;
+
+	return result;
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::_findVisibleObjects(Camera* cam, bool onlyShadowCasters)
+{
+	//-- show visible scene nodes and octree bounding boxes from last frame
+	if (mShowVisualization)
+    {
+		PrepareVisualization(cam);
+	}
+	else 
+	{	
+		// for hierarchical culling, we interleave identification 
+		// and rendering of objects in _renderVisibibleObjects
+
+		// for the shadow pass we use only standard rendering
+		// because of low occlusion
+		if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+			mIlluminationStage == IRS_RENDER_TO_TEXTURE)
+		{
+			OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
+		}
+		// only shadow casters will be rendered in shadow texture pass
+		// mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
+	}
+	
+	
+	// -- delete lists stored for visualization
+	mVisible.clear();
+	mBoxes.clear();
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::_renderVisibleObjects()
+{
+	
+		//InitVisibilityCulling(mCameraInProgress);
+		//mVisibilityManager->ApplyVisibilityCulling();
+
+		if(1){
+	InitDepthPass(); 	  // create material for depth pass
+	InitItemBufferPass(); // create material for item buffer pass
+
+	// save ambient light to reset later
+	ColourValue savedAmbient = mAmbientLight;
+
+	//-- apply standard rendering for some modes (e.g., visualization, shadow pass)
+
+	if (mShowVisualization ||
+	   (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && 
+	    mIlluminationStage == IRS_RENDER_TO_TEXTURE))
+	{
+		IlluminationRenderStage savedStage = mIlluminationStage; 
+	
+		if (mShowVisualization)
+		{
+			// disable illumination stage to prevent rendering shadows
+			mIlluminationStage = IRS_NONE;
+		}
+
+		// standard rendering for shadow maps because of performance
+		OctreeSceneManager::_renderVisibleObjects();
+
+		mIlluminationStage = savedStage;
+	}
+	else //-- the hierarchical culling algorithm
+	{	
+		// don't render backgrounds for item buffer
+		if (mUseItemBuffer)
+		{
+			clearSpecialCaseRenderQueues();
+			getRenderQueue()->clear();
+		} 	
+
+		//-- hierarchical culling
+		// the objects of different layers (e.g., background, scene, 
+		// overlay) must be identified and rendered one after another
+
+		//-- render all early skies
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+
+		OctreeSceneManager::_renderVisibleObjects();
+
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		// delete previously rendered content
+		_deleteRenderedQueueGroups();
+#endif
+
+		//-- prepare queue for visible objects (i.e., all but overlay and skies late)
+		clearSpecialCaseRenderQueues();
+		addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
+		addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+		setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+	
+
+		// set all necessary parameters for 
+		// hierarchical visibility culling and rendering
+		InitVisibilityCulling(mCameraInProgress);
+	
+		/** 
+		* the hierarchical culling algorithm
+		* for depth pass: we just find objects and update depth buffer
+		* for "delayed" rendering: we render some passes afterwards
+		* e.g., transparents, because they need front-to-back sorting
+		**/
+	
+		mVisibilityManager->ApplyVisibilityCulling();
+	
+		// delete remaining renderables from queue (all not in mLeavePassesInQueue)
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		_deleteRenderedQueueGroups(mLeavePassesInQueue);
+#endif
+
+		//-- reset parameters
+		mIsDepthPassPhase = false;
+		mIsItemBufferPhase = false;
+		mSkipTransparents = false;
+		mIsHierarchicalCulling = false;
+
+		mLeavePassesInQueue = 0;
+
+		// add visible nodes found by the visibility culling algorithm
+		if (mUseDepthPass)
+		{
+			for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
+			{
+				(*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
+			}
+		}
+	
+		//-- we render all remaining queue objects
+		// used for depth pass, transparents, overlay 
+		clearSpecialCaseRenderQueues();
+		OctreeSceneManager::_renderVisibleObjects();
+	
+	}   // hierarchical culling
+
+	// reset ambient light
+	setAmbientLight(savedAmbient);
+}	
+	getRenderQueue()->clear(); // finally clear render queue
+	OGRE_DELETE(mRenderQueue); // HACK: should be cleared before...
+	//WriteLog(); // write out stats
+
+}
+
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::_updateSceneGraph(Camera* cam)
+{
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+
+	OctreeSceneManager::_updateSceneGraph(cam);
+}
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::setOption(const String & key, const void * val)
+{
+	if (key == "UseDepthPass")
+	{
+		mUseDepthPass = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "PrepareVisualization")
+	{
+		mShowVisualization = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderNodesForViz")
+	{
+		mRenderNodesForViz = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderNodesContentForViz")
+	{
+		mRenderNodesContentForViz = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyBoxEnabled")
+	{
+		mSkyBoxEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyPlaneEnabled")
+	{
+		mSkyPlaneEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "SkyDomeEnabled")
+	{
+		mSkyDomeEnabled = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "VisualizeCulledNodes")
+	{
+		mVisualizeCulledNodes = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "DelayRenderTransparents")
+	{
+		mDelayRenderTransparents = (*static_cast<const bool *>(val));
+		return true;
+	}
+
+	if (key == "DepthWrite")
+	{
+		mEnableDepthWrite = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "UseItemBuffer")
+	{
+		mUseItemBuffer = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "ExecuteVertexProgramForAllPasses")
+	{ 
+		mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "RenderTransparentsForItemBuffer")
+	{ 
+		mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
+		return true;
+	}
+	if (key == "NodeVizScale")
+	{ 
+		OctreeNode::setVizScale(*static_cast<const float *>(val));
+		return true;
+	}
+	if (key == "UseArbQueries")
+	{
+		bool useArbQueries = (*static_cast<const bool *>(val));
+
+		if (useArbQueries)
+		{
+			mHierarchyInterface->DeleteQueries();
+			mDestRenderSystem->setConfigOption("ArbQueries", "Yes");
+		}
+		else
+		{
+			mHierarchyInterface->DeleteQueries();
+			mDestRenderSystem->setConfigOption("ArbQueries", "No");
+		}
+	}
+
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		setOption(key, val) || OctreeSceneManager::setOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::getOption(const String & key, void *val)
+{
+	if (key == "NumHierarchyNodes")
+	{
+		* static_cast<unsigned int *>(val) = (unsigned int)mNumOctants;
+		return true;
+	}
+
+	return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOption(key, val) && OctreeSceneManager::getOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::getOptionValues(const String & key, StringVector  &refValueList)
+{
+	return OctreeSceneManager::getOptionValues( key, refValueList );
+}
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::getOptionKeys(StringVector & refKeys)
+{
+	return  VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
+		getOptionKeys (refKeys) || OctreeSceneManager::getOptionKeys(refKeys);
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::setVisibilityManager(GtpVisibility::VisibilityManager *visManager)
+{
+    mVisibilityManager = visManager;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityOctreeSceneManager::getVisibilityManager()
+{
+	return mVisibilityManager;
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::WriteLog()
+{
+	std::stringstream d;
+
+	d << "Depth pass: " << StringConverter::toString(mUseDepthPass) << ", "
+	  << "Delay transparents: " << StringConverter::toString(mDelayRenderTransparents) << ", "
+	  << "Use optimization: " << StringConverter::toString(mHierarchyInterface->GetTestGeometryForVisibleLeaves()) << ", "
+	  << "Algorithm type: " << mVisibilityManager->GetCullingManagerType() << "\n"
+	  << "Hierarchy nodes: " << mNumOctants << ", " 
+	  << "Traversed nodes: " << mHierarchyInterface->GetNumTraversedNodes() << ", "
+	  << "Rendered nodes: " << mHierarchyInterface->GetNumRenderedNodes() << ", "
+	  << "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
+	  << "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
+      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << "\n";
+	  /*<< "avg. FPS: " << mCurrentViewport->getTarget()->getAverageFPS() << ", "
+	  << "best FPS: " << mCurrentViewport->getTarget()->getBestFPS() << ", "
+	  << "worst FPS: " << mCurrentViewport->getTarget()->getWorstFPS() << ", "
+	  << "best frame time: " <<	mCurrentViewport->getTarget()->getBestFrameTime() << ", "
+	  << "worst frame time: " << mCurrentViewport->getTarget()->getWorstFrameTime() << "\n";*/
+
+	LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::renderObjects(
+	const RenderPriorityGroup::TransparentRenderablePassList& objs, 
+            bool doLightIteration, const LightList* manualLightList)
+{
+	// for correct rendering, transparents must be rendered after hierarchical culling
+	if (!mSkipTransparents)
+	{
+		OctreeSceneManager::renderObjects(objs, doLightIteration, manualLightList);
+	}
+}
+//-----------------------------------------------------------------------
+bool VisibilityOctreeSceneManager::validatePassForRendering(Pass* pass)
+{
+	// skip all but first pass if we are doing the depth pass
+	if ((mIsDepthPassPhase || mIsItemBufferPhase) && pass->getIndex() > 0)
+	{
+		return false;
+	}
+	return SceneManager::validatePassForRendering(pass);
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::renderQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+	if (!mIsItemBufferPhase)
+	{
+		OctreeSceneManager::renderQueueGroupObjects(pGroup);
+		return;
+	}
+
+	//-- renders item buffer
+
+    // Iterate through priorities
+    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	while (groupIt.hasMoreElements())
+    {
+		RenderItemBuffer(groupIt.getNext());
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::RenderItemBuffer(RenderPriorityGroup* pGroup)
+{
+	// Do solids
+	RenderPriorityGroup::SolidRenderablePassMap solidObjs = pGroup->_getSolidPasses();
+
+	// ----- SOLIDS LOOP -----
+	RenderPriorityGroup::SolidRenderablePassMap::const_iterator ipass, ipassend;
+	ipassend = solidObjs.end();
+
+	for (ipass = solidObjs.begin(); ipass != ipassend; ++ipass)
+	{
+		// Fast bypass if this group is now empty
+		if (ipass->second->empty()) 
+			continue;
+
+		// Render only first pass
+		if (ipass->first->getIndex() > 0)
+			continue;
+
+		RenderPriorityGroup::RenderableList* rendList = ipass->second;
+		
+		RenderPriorityGroup::RenderableList::const_iterator irend, irendend;
+		irendend = rendList->end();
+			
+		for (irend = rendList->begin(); irend != irendend; ++irend)
+		{
+			std::stringstream d; d << "itembuffer, pass name: " << 
+				ipass->first->getParent()->getParent()->getName();
+				
+			LogManager::getSingleton().logMessage(d.str());
+			
+			RenderSingleObjectForItemBuffer(*irend, ipass->first);
+		}
+	}
+
+	//-- TRANSPARENT LOOP: must be handled differently 
+
+	// transparents are treated either as solids or completely discarded
+	if (mRenderTransparentsForItemBuffer)
+	{
+		RenderPriorityGroup::TransparentRenderablePassList transpObjs = 
+			pGroup->_getTransparentPasses();
+		RenderPriorityGroup::TransparentRenderablePassList::const_iterator 
+			itrans, itransend;
+
+		itransend = transpObjs.end();
+		for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
+		{
+			// like for solids, render only first pass
+			if (itrans->pass->getIndex() == 0)
+			{	
+				RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
+			}
+		} 
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass)
+{
+	static LightList nullLightList;
+	
+	int col[4];
+	
+	// -- create color code out of object id
+	col[0] = (rend->getId() >> 16) & 255;
+	col[1] = (rend->getId() >> 8) & 255;
+	col[2] = rend->getId() & 255;
+//	col[3] = 255;
+
+	//mDestRenderSystem->setColour(col[0], col[1], col[2], col[3]);
+    
+	mItemBufferPass->setAmbient(ColourValue(col[0] / 255.0f,
+										    col[1] / 255.0f, 
+											col[2] / 255.0f, 1));
+
+	// set vertex program of current pass
+	if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
+
+		if (mItemBufferPass->hasVertexProgram())
+		{
+			const GpuProgramPtr& prg = mItemBufferPass->getVertexProgram();
+			// Load this program if not done already
+			if (!prg->isLoaded())
+				prg->load();
+			// Copy params
+			mItemBufferPass->setVertexProgramParameters(pass->getVertexProgramParameters());
+		}
+	}
+	else if (mItemBufferPass->hasVertexProgram())
+	{
+		mItemBufferPass->setVertexProgram("");
+	}
+
+	Pass *usedPass = setPass(mItemBufferPass); 
+
+
+	// Render a single object, this will set up auto params if required
+	renderSingleObject(rend, usedPass, false, &nullLightList);
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityOctreeSceneManager::GetVisibilityManager()
+{
+	return mVisibilityManager;
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::InitVisibilityCulling(Camera *cam)
+{
+	// reset culling manager stats
+	mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
+
+	// set depth pass flag before rendering
+	mIsDepthPassPhase = mUseDepthPass;
+
+	mIsHierarchicalCulling = true; // during hierarchical culling
+
+	// item buffer needs full ambient lighting to use item colors as unique id
+	if (mUseItemBuffer) 
+	{
+		mIsItemBufferPhase = true;
+		setAmbientLight(ColourValue(1,1,1,1));
+	}
+
+
+	// set passes which are stored in render queue 
+	// for rendering AFTER hierarchical culling, i.e., passes which need 
+	// a special rendering order
+	
+	mLeavePassesInQueue = 0;
+
+	if (!mUseDepthPass && !mUseItemBuffer)
+	{
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
+		{
+			// TODO: remove this pass because it should be processed during hierarchical culling
+			//mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
+
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DECAL;
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+
+			// just render ambient passes
+			mIlluminationStage = IRS_AMBIENT;
+			getRenderQueue()->setSplitPassesByLightingType(true);
+		}
+	
+		if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	
+		// transparents should be rendered after hierarchical culling to 
+		// provide front-to-back ordering
+		if (mDelayRenderTransparents)
+		{
+			mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
+		}
+	}
+
+	// skip rendering transparents in the hierarchical culling
+	// (because they will be rendered afterwards)
+	mSkipTransparents = mUseDepthPass || 
+		(mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES);
+
+	// -- initialise interface for rendering traversal of the hierarchy
+	mHierarchyInterface->SetHierarchyRoot(mOctree);
+	
+	// possible two cameras (one for culling, one for rendering)
+	mHierarchyInterface->InitTraversal(mCameraInProgress, 
+							mCullCamera ? getCamera("CullCamera") : NULL,
+							mLeavePassesInQueue);
+		
+	//std::stringstream d; d << "leave passes in queue: " << mLeavePassesInQueue;LogManager::getSingleton().logMessage(d.str());
+}
+//-----------------------------------------------------------------------
+OctreeHierarchyInterface *VisibilityOctreeSceneManager::GetHierarchyInterface()
+{
+	return mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+	// only render solid passes during hierarchical culling
+	if (mIsHierarchicalCulling)
+	{
+		RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+	    LightList lightList;
+
+		while (groupIt.hasMoreElements())
+		{
+			RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+			// Sort the queue first
+			pPriorityGrp->sort(mCameraInProgress);
+
+			// Clear light list
+			lightList.clear();
+
+			// Render all the ambient passes first, no light iteration, no lights
+			mIlluminationStage = IRS_AMBIENT;
+
+			OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPasses(), false, &lightList);
+			// Also render any objects which have receive shadows disabled
+			OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPassesNoShadow(), true);
+		
+			/*std::stringstream d; 
+			d << " solid size: " << (int)pPriorityGrp->_getSolidPasses().size()
+				<< " solid no shadow size: " << (int)pPriorityGrp->_getSolidPassesNoShadow().size()
+				<< "difspec size: " << (int)pPriorityGrp->_getSolidPassesDiffuseSpecular().size()
+				<< " decal size: " << (int)pPriorityGrp->_getSolidPassesDecal().size();
+			LogManager::getSingleton().logMessage(d.str());*/
+		}
+	}
+	else // render the rest of the passes
+	{
+		OctreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(pGroup);
+	}
+}
+//-----------------------------------------------------------------------
+void VisibilityOctreeSceneManager::renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* pGroup)
+{
+   if (mIsHierarchicalCulling)
+   {
+	   // Iterate through priorities
+	   RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
+
+	   while (groupIt.hasMoreElements())
+	   {
+		   RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
+
+		   // Sort the queue first
+		   pPriorityGrp->sort(mCameraInProgress);
+
+		   // Do (shadowable) solids
+		   OctreeSceneManager::renderObjects(pPriorityGrp->_getSolidPasses(), true);
+	   }
+   }
+   else
+   {
+	   SceneManager::renderModulativeStencilShadowedQueueGroupObjects(pGroup);
+   }
+}
+//-------------------------------------------------------------------------
+void VisibilityOctreeSceneManager::loadVisibilityConfig(const String& filename)
+{
+	/// Set up the options
+	ConfigFile config;
+	String val;
+
+	config.load(filename);
+
+	val = config.getSetting("Algorithm");
+
+    if (!val.empty())
+	{
+		 VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).setOption("Algorithm", val.c_str());
+	}
+
+	val = config.getSetting("UseDepthPass");
+
+	if (!val.empty())
+	{
+		 setOption("UseDepthPass", val.c_str());
+	}
+}
+}  // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreBspHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreBspHierarchyInterface.cpp	(revision 345)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreBspHierarchyInterface.cpp	(revision 345)
@@ -0,0 +1,66 @@
+#include "OgreBspHierarchyInterface.h"
+#include "OgreVisibilityOctreeSceneManager.h"
+
+//#include <windows.h>
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+BspHierarchyInterface::BspHierarchyInterface(SceneManager *sm, RenderSystem *rsys): 
+PlatformHierarchyInterface(sm, rsys)
+{
+}
+//-----------------------------------------------------------------------
+void BspHierarchyInterface::TraverseNode(GtpVisibility::HierarchyNode *node)
+{
+}
+//-----------------------------------------------------------------------
+bool BspHierarchyInterface::IsLeaf(GtpVisibility::HierarchyNode *node) const
+{
+	return true;
+}
+//-----------------------------------------------------------------------
+bool BspHierarchyInterface::HasGeometry(GtpVisibility::HierarchyNode *node) const
+{
+	return true;
+}
+//-----------------------------------------------------------------------
+float BspHierarchyInterface::GetSquaredDistance(GtpVisibility::HierarchyNode *node) const
+{
+	return 0.0f;
+}
+//-----------------------------------------------------------------------
+void BspHierarchyInterface::SetNodeVisible(GtpVisibility::HierarchyNode *node, 
+										   const bool visible) const
+{
+}
+//-----------------------------------------------------------------------
+void BspHierarchyInterface::SetLastVisited(GtpVisibility::HierarchyNode *node, 
+										   const unsigned int frameId) const
+{
+}
+//-----------------------------------------------------------------------
+void BspHierarchyInterface::PullUpVisibility(GtpVisibility::HierarchyNode *node) const
+{		
+}
+//-----------------------------------------------------------------------
+void BspHierarchyInterface::RenderNode(GtpVisibility::HierarchyNode *node)
+{
+}
+//-----------------------------------------------------------------------
+bool BspHierarchyInterface::IsNodeVisible(GtpVisibility::HierarchyNode *node) const
+{
+	return true;
+}
+//-----------------------------------------------------------------------
+unsigned int BspHierarchyInterface::LastVisited(GtpVisibility::HierarchyNode *node) const
+{
+	return 0;
+}
+//-----------------------------------------------------------------------
+AxisAlignedBox *BspHierarchyInterface::GetBoundingBox(GtpVisibility::HierarchyNode *node)
+{
+	return NULL;
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformHierarchyInterface.cpp	(revision 316)
@@ -0,0 +1,292 @@
+#include <OgreCamera.h>
+#include <OgreLogManager.h>
+#include <OgreSubEntity.h>
+#include <OgreEntity.h>
+#include <OgreMovableObject.h>
+#include "OgreSolidBoundingBox.h"
+#include "OgrePlatformHierarchyInterface.h"
+#include "OgrePlatformOcclusionQuery.h"
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+PlatformHierarchyInterface::PlatformHierarchyInterface(SceneManager *sm, RenderSystem *rsys):
+mSceneManager(sm), mRenderSystem(rsys), mSolidBoundingBox(NULL), mCamera(NULL), 
+mCullCamera(NULL), mOnlyShadowCasters(false), mLeavePassesInQueue(0),
+mIsBoundingBoxQuery(false)
+{
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::CreateNodeVizMaterials()
+{
+	// material for frustum culled nodes
+	MaterialPtr mat = MaterialManager::getSingleton().getByName("FrustumCulledNodesMaterial");
+	
+	if (mat.isNull())
+	{
+		mat = MaterialManager::getSingleton().create("FrustumCulledNodesMaterial", 
+			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+		mat->createTechnique()->createPass();
+		
+		mat->getTechnique(0)->getPass(0)->setAmbient(1, 0, 0);
+		mat->getTechnique(0)->getPass(0)->setLightingEnabled(true);
+		//mat->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
+		mat->load();
+	}
+
+	// material for query culled nodes
+	mat = MaterialManager::getSingleton().getByName("QueryCulledNodesMaterial");
+
+	if (mat.isNull())
+	{
+		mat = MaterialManager::getSingleton().create("QueryCulledNodesMaterial", 
+			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+		mat->createTechnique()->createPass();
+		
+		mat->getTechnique(0)->getPass(0)->setAmbient(0, 0, 1);
+		mat->getTechnique(0)->getPass(0)->setLightingEnabled(true);
+		mat->load();
+	}
+
+	// material for scene nodes
+	/*mat = MaterialManager::getSingleton().getByName("SceneNodesMaterial");
+
+	if (mat.isNull())
+	{
+		mat = MaterialManager::getSingleton().create("SceneNodesMaterial", 
+			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+		mat->createTechnique()->createPass();
+		
+		mat->getTechnique(0)->getPass(0)->setAmbient(1, 1, 0);
+		mat->getTechnique(0)->getPass(0)->setLightingEnabled(true);
+		mat->load();
+	}*/
+}
+//-----------------------------------------------------------------------
+PlatformHierarchyInterface::~PlatformHierarchyInterface()
+{
+	DeleteQueries();
+
+	OGRE_DELETE(mSolidBoundingBox);
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::DeleteQueries()
+{
+	for (int i = 0; i < (int)mOcclusionQueries.size(); ++ i)
+		OGRE_DELETE(mOcclusionQueries[i]);
+
+	mCurrentTestIdx = 0;
+    mOcclusionQueries.clear();
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::RenderBoundingBox(AxisAlignedBox *box)
+{
+	static RenderOperation ro;
+
+	SolidBoundingBox *solidBox = GetSolidBoundingBox();
+	
+	mRenderSystem->_setWorldMatrix(Ogre::Matrix4::IDENTITY);
+	mSceneManager->useRenderableViewProjModeWrapper(solidBox);
+	
+	// set no depth write, no color, no lighting material
+	mSceneManager->setPassWrapper(solidBox->getTechnique()->getPass(0)); // HACK! (mySetPass should be setPass)
+	//SetOcclusionPass();
+
+	solidBox->SetupBoundingBoxVertices(*box);
+				
+	solidBox->getRenderOperation(ro);
+	ro.srcRenderable = solidBox;
+	mRenderSystem->_render(ro);
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::SetCamera(Ogre::Camera *cam)
+{
+	mCamera = cam;
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::SetCullCamera(Ogre::Camera *cullCam)
+{
+	mCullCamera = cullCam;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::GetNextOcclusionQuery()
+{
+	if (mCurrentTestIdx == mOcclusionQueries.size())
+	{
+		mOcclusionQueries.push_back(new PlatformOcclusionQuery(mRenderSystem));
+	}
+	
+	return mOcclusionQueries[mCurrentTestIdx ++];
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::InitTraversal(Camera *cam, Camera *cullCam, 
+											   int leavePassesInQueue)
+{
+	GtpVisibility::HierarchyInterface::InitTraversal();
+	
+	mSavedNode = NULL;
+	mLeavePassesInQueue = leavePassesInQueue;
+
+	mCamera = cam;
+	mCullCamera = cullCam ? cullCam : cam;
+
+	// create materials for node visualization
+	CreateNodeVizMaterials();
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::SetSceneManager(SceneManager *sm)
+{
+	mSceneManager = sm;
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::SetRenderSystem(RenderSystem *rsys)
+{
+	mRenderSystem = rsys;
+}
+//-----------------------------------------------------------------------
+bool PlatformHierarchyInterface::CheckFrustumVisible(GtpVisibility::HierarchyNode *node, 
+													 bool &intersects)
+{
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	return mCullCamera->isVisible(*GetBoundingBox(node), intersects);
+#else
+	return true;
+#endif
+}
+//-----------------------------------------------------------------------
+GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::IssueNodeOcclusionQuery(
+	GtpVisibility::HierarchyNode *node, const bool wasVisible) 
+{
+	// get next available test id
+	GtpVisibility::OcclusionQuery *query = GetNextOcclusionQuery();
+
+	//-- the actual query test
+	query->BeginQuery();
+	
+	// if node is leaf and was visible => will be rendered anyway.
+	// In this case we can also test with the real geometry.
+	// If camera for culling is different from camera for rendering or only solids 
+	// will be rendereded => cannot optimize
+	if (mTestGeometryForVisibleLeaves && (mCamera == mCullCamera) && wasVisible && IsLeaf(node)) 
+	{
+		//LogManager::getSingleton().logMessage("render node\n");
+		RenderNode(node);
+	}
+	else
+	{
+		// this information is used e.g., by the scene graph, because the bounding box
+		// must be treated differently to the scene geometry during rendering
+		mIsBoundingBoxQuery = true;
+
+		//LogManager::getSingleton().logMessage("render box\n");
+		RenderBoundingBox(GetBoundingBox(node));
+
+		mIsBoundingBoxQuery = false;
+	}
+
+	query->EndQuery();
+	
+	return query;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::IssuePatchOcclusionQuery(
+	GtpVisibility::Patch *patch)
+{
+	// get next available test id
+	GtpVisibility::OcclusionQuery *query = GetNextOcclusionQuery();
+
+	//-- the actual query test
+	query->BeginQuery();
+	
+	RenderPatch(patch);
+
+	query->EndQuery();
+
+	return query;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::OcclusionQuery *PlatformHierarchyInterface::IssueMeshOcclusionQuery(
+	GtpVisibility::Mesh *mesh)
+{
+	// get next available test id
+	GtpVisibility::OcclusionQuery *query = GetNextOcclusionQuery();
+
+	//-- the actual query test
+	query->BeginQuery();
+	
+	RenderGeometry(mesh);
+
+	query->EndQuery();
+
+	return query;
+}
+//-----------------------------------------------------------------------
+/*void PlatformHierarchyInterface::SetOcclusionPass()
+{
+    // disable vertex and fragment program
+	mRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
+	mRenderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
+	
+	// disable lighting
+	mRenderSystem->setLightingEnabled(false);
+
+    // Disable remaining texture units
+    mRenderSystem->_disableTextureUnitsFrom(0);
+
+    //--Set up non-texture related material settings
+   
+	// Depth buffer settings
+	mRenderSystem->_setDepthBufferParams(true, false, CMPF_LESS_EQUAL);
+	// Set colour write mode off
+	mRenderSystem->_setColourBufferWriteEnabled(false, false, false, false);
+}*/
+//-----------------------------------------------------------------------
+SolidBoundingBox *PlatformHierarchyInterface::GetSolidBoundingBox()
+{
+	if (!mSolidBoundingBox)
+		mSolidBoundingBox = new SolidBoundingBox;
+
+	return mSolidBoundingBox;
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::SetOnlyShadowCasters(bool onlyShadowCasters)
+{
+	mOnlyShadowCasters = onlyShadowCasters;
+}
+//-----------------------------------------------------------------------
+bool PlatformHierarchyInterface::GetOnlyShadowCasters()
+{
+	return mOnlyShadowCasters;
+}
+//-----------------------------------------------------------------------
+bool PlatformHierarchyInterface::GetTestGeometryForVisibleLeaves()
+{
+	return mTestGeometryForVisibleLeaves;
+}
+//-----------------------------------------------------------------------
+bool PlatformHierarchyInterface::IsBoundingBoxQuery()
+{
+	return mIsBoundingBoxQuery;
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::RenderGeometry(GtpVisibility::Mesh *geom)
+{
+	mSceneManager->_renderMovableObject(geom, mLeavePassesInQueue);
+}
+//-----------------------------------------------------------------------
+void PlatformHierarchyInterface::RenderPatch(GtpVisibility::Patch *patch)
+{
+	mSceneManager->_renderSingleRenderable(patch);
+}
+//-----------------------------------------------------------------------
+SceneManager *PlatformHierarchyInterface::GetSceneManager()
+{
+	return mSceneManager;
+}
+//-----------------------------------------------------------------------
+RenderSystem *PlatformHierarchyInterface::GetRenderSystem()
+{
+	return mRenderSystem;
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidHalfBoundingBox.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidHalfBoundingBox.cpp	(revision 117)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidHalfBoundingBox.cpp	(revision 117)
@@ -0,0 +1,105 @@
+#include "OgreStableHeaders.h"
+#include "OgreSolidHalfBoundingBox.h"
+
+#include "OgreSimpleRenderable.h"
+#include "OgreHardwareBufferManager.h"
+#include "OgreCamera.h"
+#include "OgreMaterialManager.h"
+
+
+namespace Ogre {
+
+#define POSITION_BINDING 0
+//-----------------------------------------------------------------------
+SolidHalfBoundingBox::SolidHalfBoundingBox()
+{
+	SetOcclusionQueryMaterial();
+	
+	mRenderOp.vertexData->vertexCount = 8;
+    mRenderOp.operationType = RenderOperation::OT_TRIANGLE_FAN; 
+}
+//-----------------------------------------------------------------------
+void SolidHalfBoundingBox::SetupBoundingBoxVertices(const AxisAlignedBox& aab, 
+													const bool isFirstHalf) 
+{
+	const Vector3& min = aab.getMinimum();
+    const Vector3& max = aab.getMaximum();
+
+	// fill the vertex buffer: 12 lines with 2 endpoints each make up a box
+    HardwareVertexBufferSharedPtr vbuf =
+        mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING);     
+
+    float* pPos = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
+
+	//     5+------+7
+	//     /|     /|
+	//    / |    / |
+	//   / 1+---/--+3
+	// 2+------+6 /    y   z
+	//  | /    | /     |  /
+	//  |/     |/      |/
+	// 0+------+4      *---x
+
+	// fan 1
+	if (isFirstHalf)
+	{
+		*pPos++ = min.x; *pPos++ = max.y; *pPos++ = max.z; //011
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = max.z; //001
+		*pPos++ = max.x; *pPos++ = min.y; *pPos++ = max.z; //101
+		*pPos++ = max.x; *pPos++ = max.y; *pPos++ = max.z; //111
+		
+		*pPos++ = max.x; *pPos++ = max.y; *pPos++ = min.z; //110
+		*pPos++ = min.x; *pPos++ = max.y; *pPos++ = min.z; //010
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = min.z; //000
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = max.z; //001
+	}
+	else
+	// fan 2
+	{
+		*pPos++ = max.x; *pPos++ = min.y; *pPos++ = min.z; //100
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = min.z; //000 					
+		*pPos++ = min.x; *pPos++ = max.y; *pPos++ = min.z; //010
+		*pPos++ = max.x; *pPos++ = max.y; *pPos++ = min.z; //110
+
+		*pPos++ = max.x; *pPos++ = max.y; *pPos++ = max.z; //111
+		*pPos++ = max.x; *pPos++ = min.y; *pPos++ = max.z; //101
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = max.z; //001
+		*pPos++ = min.x; *pPos++ = min.y; *pPos++ = min.z; //000
+	}
+
+    vbuf->unlock();
+}
+//-----------------------------------------------------------------------
+void SolidHalfBoundingBox::SetupBoundingBox(const AxisAlignedBox& aab, 
+											const bool isFirstHalf) 
+{
+	// init the vertices to the aabb
+	SetupBoundingBoxVertices(aab, isFirstHalf);
+
+	Real sqLen = std::max(aab.getMaximum().squaredLength(), 
+						  aab.getMinimum().squaredLength());
+    mRadius = Math::Sqrt(sqLen);
+
+    // setup the bounding box of this SimpleRenderable
+	setBoundingBox(aab);
+}
+//-----------------------------------------------------------------------
+void SolidHalfBoundingBox::SetOcclusionQueryMaterial( void )
+{
+	m_pMaterial = MaterialManager::getSingleton().getByName("Visibility/QueryMaterial");
+
+	if (m_pMaterial.isNull())
+	{
+		m_pMaterial = MaterialManager::getSingleton().
+			create("Visibility/QueryMaterial", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+	}
+
+	m_pMaterial->setColourWriteEnabled(false);
+	m_pMaterial->setDepthWriteEnabled(false);
+	m_pMaterial->setLightingEnabled(false);
+
+	setMaterial("Visibility/QueryMaterial");
+}
+
+} // namespace Ogre
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp	(revision 316)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgrePlatformQueryManager.cpp	(revision 316)
@@ -0,0 +1,236 @@
+#include "OgrePlatformQueryManager.h"
+#include "OcclusionQuery.h"
+#include <OgreSceneManager.h>
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <vector>
+#include <OgreSubEntity.h>
+
+
+namespace Ogre {
+
+//----------------------------------------------------------------------- 
+PlatformQueryManager::PlatformQueryManager(PlatformHierarchyInterface *hierarchyInterface, 
+										   Viewport *vp, int queryModes):
+QueryManager(hierarchyInterface, queryModes), 
+mViewport(vp), 
+mWasInitialised(false)
+{
+}
+//-----------------------------------------------------------------------
+bool PlatformQueryManager::ShootRay(const Ray &ray, std::vector<Mesh *> *visibleMeshes, bool isGlobalLine)
+{
+    // run OGRE ray shooting query
+    return false;
+}
+//-----------------------------------------------------------------------
+void PlatformQueryManager::ComputeFromPointVisibility(const Vector3 &point,
+			       GtpVisibility::NodeInfoContainer *visibleNodes,
+			       GtpVisibility::MeshInfoContainer *visibleGeometry,
+				   GtpVisibility::PatchInfoContainer *visiblePatches,
+			       bool relativeVisibility)
+{
+	SceneManager *sm = dynamic_cast<PlatformHierarchyInterface *>
+		(mHierarchyInterface)->GetSceneManager();
+
+	// create a camera for the point query
+	Camera *cam = sm->createCamera("PointQueryCam");	
+
+	//save old camera
+	Camera *savedCam = mViewport->getCamera();
+	
+	// --- initialise new camera
+	mViewport->setCamera(cam);
+	cam->setPosition(point);
+
+	cam->setNearClipDistance(savedCam->getNearClipDistance());
+	cam->setFarClipDistance(savedCam->getFarClipDistance());
+
+	// set frustum to 45 degrees so all the scene can be captured with 6 shots
+	cam->setAspectRatio(1.0);
+	cam->setFOVy(Radian(Math::HALF_PI));
+
+	int sign = -1;
+	
+	// ---- capture visibility from all 6 directions
+	for (int dir=0; dir < 6; dir++)	
+	{
+		sign *= -1;
+		
+		// Print camera details
+      	std::stringstream d;
+		d << "Point query camera: " + StringConverter::toString(cam->getDerivedPosition()) + 
+			" " + "O: " + StringConverter::toString(cam->getDerivedOrientation());
+		LogManager::getSingleton().logMessage(d.str());
+
+		// prevent from initialising geometry / node array again
+		if (dir > 0)
+		{
+			mWasInitialised = true;
+		}
+
+		ComputeCameraVisibility(*cam, visibleNodes, visibleGeometry, visiblePatches, 
+			                    relativeVisibility);
+		//mViewport->getTarget()->update(); for(int j=0; j<10000000; j++)	printf("wait");
+
+		// permute directions
+		Vector3 direction(0,0,0);
+		direction[dir/2] = sign;
+
+		cam->setDirection(direction);
+	}
+	
+	// reset camera
+	mViewport->setCamera(savedCam);
+}
+//-----------------------------------------------------------------------
+void PlatformQueryManager::ComputeCameraVisibility(const Camera &camera,
+			    GtpVisibility::NodeInfoContainer *visibleNodes,
+			    GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches,
+			    bool relativeVisibility)
+{
+	// we need access to the scene manager and the rendersystem
+	PlatformHierarchyInterface *pfHierarchyInterface = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+
+	SceneManager *sm = pfHierarchyInterface->GetSceneManager();
+
+
+	// const_cast allowed because camera is not changed in renderScene
+	Camera *pCam = const_cast<Camera *>(&camera); 
+
+	// disable overlays, reset them later
+	bool overlayEnabled = mViewport->getOverlaysEnabled();
+	mViewport->setOverlaysEnabled(false);
+	
+	// clear background with black (i.e., not a valid item id)
+	ColourValue bg = mViewport->getBackgroundColour();
+	mViewport->setBackgroundColour(ColourValue(0, 0, 0, 0));
+	//pfHierarchyInterface->GetRenderSystem()->clearFrameBuffer(FBT_COLOUR | FBT_DEPTH);
+
+	// initialise item buffer (if not already initialised)
+	InitItemBuffer(visibleGeometry, visiblePatches);
+
+	//-- render scene with item buffer (i.e., objects with their id as color codes)
+
+	// enable item buffer (must be provided by scene manager)
+	bool useItemBuffer = true;
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+
+
+	sm->_renderScene(pCam, mViewport, false); // render item buffer
+   
+
+	//-- collect results
+	CollectItemBufferResults(visibleGeometry, visiblePatches);
+
+	//-- reset options
+
+	useItemBuffer = false; // don't need item buffer anymore
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+
+	mWasInitialised = false; // reset initialised - flag
+	mViewport->setOverlaysEnabled(overlayEnabled); // reset old overlay status
+	mViewport->setBackgroundColour(bg); // reset background color
+}
+//-----------------------------------------------------------------------
+void PlatformQueryManager::CollectItemBufferResults(
+				GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches)
+{
+	int dimx = 0;
+	int dimy = 0;
+
+	// copy frame buffer 
+	uchar *buf = mViewport->getTarget()->getBufferContents(dimx, dimy);
+
+	//std::stringstream d; d << "dimx: " << dimx << ", dimy: " << dimy; LogManager::getSingleton().logMessage(d.str());
+
+	// loop through frame buffer and collect visible pixels
+	for (int idx = 0; idx < dimy * dimx * 3; idx += 3)
+	{
+		//-- decode color code to receive id
+		int id = buf[idx] << 16;
+		id += buf[idx + 1] << 8;
+		id += buf[idx + 2];
+
+		//std::stringstream d; d << "myid: " << (int)buf[idx] << " " << (int)buf[idx + 1] << " " << (int)buf[idx + 2]; LogManager::getSingleton().logMessage(d.str());
+
+		// if valid id <= add visibility (id values start at 1)
+		if (mQueryModes == PATCH_VISIBILITY)
+		{	
+			if ((id > 0) && (id < (int)visiblePatches->size()))
+			{
+				((*visiblePatches)[id]).AddVisibility(1, 0);
+			}
+		}
+		else if (mQueryModes == GEOMETRY_VISIBILITY)
+		{
+			if ((id > 0) && (id < (int)visibleGeometry->size()))
+			{
+				((*visibleGeometry)[id]).AddVisibility(1, 0);
+			}
+		}
+	}
+
+	delete [] buf;
+}
+
+//-----------------------------------------------------------------------
+void PlatformQueryManager::InitItemBuffer(
+				GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches)
+{
+	if (mWasInitialised)
+		return;
+
+	mWasInitialised = true;
+
+	SceneManager *sm = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
+
+	SceneManager::EntityIterator it = sm->getEntityIterator();
+
+	// TODO: make the function more efficient
+
+	visibleGeometry->clear();
+	visiblePatches->clear();
+
+	int id = 0;
+
+	/* We can either use patches or meshes. If patches are used, an unique id must
+	   be given each patch. Otherwise the same id must be given to all patches belonging
+	   to the same mesh.
+    */
+	while (it.hasMoreElements())
+	{
+		Entity *ent = it.getNext();
+
+		for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+		{
+			SubEntity *subEnt = ent->getSubEntity(i);
+
+			if (mQueryModes == PATCH_VISIBILITY)
+			{
+				++ id;
+				visiblePatches->push_back(GtpVisibility::PatchInfo(subEnt, 0, 0));
+			}
+				
+			subEnt->setId(id);
+			//subEnt->setId((41 << 16) + (4 << 8) + 60);
+		}
+			
+		if (mQueryModes == GEOMETRY_VISIBILITY)
+		{
+			visibleGeometry->push_back(GtpVisibility::MeshInfo(ent, 0, 0));
+			++ id;
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void PlatformQueryManager::SetViewport(Viewport *vp)
+{
+	mViewport = vp;
+}
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityBspSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityBspSceneManager.cpp	(revision 59)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityBspSceneManager.cpp	(revision 59)
@@ -0,0 +1,108 @@
+#include "OgreVisibilityBspSceneManager.h"
+#include <OgreMath.h>
+#include <OgreIteratorWrappers.h>
+#include <OgreRenderSystem.h>
+#include <OgreCamera.h>
+
+#include <windows.h>
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+VisibilityBspSceneManager::VisibilityBspSceneManager(
+	GtpVisibility::Manager *visManager): mVisibilityManager(visManager)
+{
+	mHierarchyInterface = 
+		new BspHierarchyInterface(this, mDestRenderSystem);
+
+	//mDisplayNodes = true;
+	//mShowBoundingBoxes = true;
+	//mShowBoxes = true;
+	//mMaxDepth = 20;
+}
+//-----------------------------------------------------------------------
+VisibilityBspSceneManager::~VisibilityBspSceneManager()
+{
+	delete mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+void VisibilityBspSceneManager::_renderVisibleObjects()
+{
+	//-- render background
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+	addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+	SceneManager::_renderVisibleObjects( );
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+
+	//-- render visible objects (i.e., all but overlay)
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+
+	mHierarchyInterface->InitFrame(mSceneRoot, mCameraInProgress);
+	mVisibilityManager->ApplyVisibilityCulling();
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+
+	//-- render rest, e.g., overlay
+	clearSpecialCaseRenderQueues();
+	SceneManager::_renderVisibleObjects();
+	//_deleteRenderedQueueGroups();
+}
+//-----------------------------------------------------------------------
+void VisibilityBspSceneManager::_findVisibleObjects(Camera* cam, bool onlyShadowCasters)
+{
+	// must be empty because objects are found and rendered in an interleaved fashion
+	// in _renderVisibibleObjects 
+}
+//-----------------------------------------------------------------------
+void VisibilityBspSceneManager::_updateSceneGraph(Camera* cam)
+{
+	//mOcclusionBspHierarchyInterface->setNumSceneNodes((int)mSceneNodes.size());
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+    mHierarchyInterface->SetNumOctreeNodes(mNumOctreeNodes);
+#endif
+	BspSceneManager::_updateSceneGraph(cam);
+}
+//-----------------------------------------------------------------------
+bool VisibilityBspSceneManager::setOption(const String & key, const void * val)
+{
+	return /*mVisibilitySceneTraverser->setOption( key, val) || */BspSceneManager::setOption( key, val );
+}
+//-----------------------------------------------------------------------
+bool VisibilityBspSceneManager::getOption(const String & key, void *val)
+{
+	return /*mVisibilitySceneTraverser->getOption( key, val) || */BspSceneManager::getOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityBspSceneManager::getOptionValues(const String & key, StringVector  &refValueList)
+{
+	return BspSceneManager::getOptionValues( key, refValueList );
+}
+//-----------------------------------------------------------------------
+bool VisibilityBspSceneManager::getOptionKeys(StringVector & refKeys)
+{
+	return /*mVisibilitySceneTraverser->getOptionKeys ( refKeys ) || */BspSceneManager::getOptionKeys(refKeys);
+}
+//-----------------------------------------------------------------------
+void VisibilityBspSceneManager::setVisibilityManager(GtpVisibility::Manager *visManager)
+{
+    mVisibilityManager = visManager;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::Manager *VisibilityBspSceneManager::getVisibilityManager()
+{
+	return mVisibilityManager;
+}
+
+}   // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreTerrainContentGenerator.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreTerrainContentGenerator.cpp	(revision 164)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreTerrainContentGenerator.cpp	(revision 164)
@@ -0,0 +1,104 @@
+#include "OgreTerrainContentGenerator.h"
+
+
+namespace Ogre {
+
+/*************************************************/
+/*         RayQueryExecutor implementation       */
+/*************************************************/
+
+//-----------------------------------------------------------------------
+RayQueryExecutor::RayQueryExecutor(SceneManager *sm)
+{
+	mRaySceneQuery = sm->createRayQuery(Ray());
+}
+//-----------------------------------------------------------------------
+RayQueryExecutor::~RayQueryExecutor()
+{
+	OGRE_DELETE(mRaySceneQuery);
+}
+//-----------------------------------------------------------------------
+bool RayQueryExecutor::executeRayQuery(Vector3 *result, const Vector3 &pos, 
+									   const Vector3 &dir)
+{
+	return executeRayQuery(result, Ray(pos, dir));
+}
+//-----------------------------------------------------------------------
+bool RayQueryExecutor::executeRayQuery(Vector3 *result, const Ray &ray)
+{
+    mRaySceneQuery->setRay(ray);
+
+    // Perform the scene query
+    RaySceneQueryResult &queryResult = mRaySceneQuery->execute();
+    RaySceneQueryResult::iterator it = queryResult.begin();
+
+	if (it != queryResult.end() && it->worldFragment)
+	{
+		SceneQuery::WorldFragment* wf = it->worldFragment;
+
+		*result = wf->singleIntersection; 
+		return true;
+	}
+
+	return false;
+}
+
+/*******************************************************/
+/*     TerrainContentGenerator implementation          */
+/*******************************************************/
+
+//-----------------------------------------------------------------------
+TerrainContentGenerator::TerrainContentGenerator(SceneManager *sm):
+SceneContentGenerator(sm), mOffset(0)
+{
+	mMinPos = Vector3(0.0f, MAX_HEIGHT, 0.0f);
+	mMaxPos = Vector3(3000.0f, MAX_HEIGHT, 3000.0f);
+
+	mMinAngle = Vector3(0.0f, 0.0f, 0.0f);
+	mMaxAngle = Vector3(360.0f, 0.0f, 0.0f);
+
+	mRayQueryExecutor = new RayQueryExecutor(sm);
+}
+//-----------------------------------------------------------------------
+TerrainContentGenerator::~TerrainContentGenerator()
+{
+	delete mRayQueryExecutor;
+}
+//-----------------------------------------------------------------------
+SceneNode *TerrainContentGenerator::GenerateSceneObject(const Vector3 &position, 
+					 const Vector3 &rotation, const String& objName, const bool clampToTerrain)
+{	
+	if (clampToTerrain)
+		return GenerateSceneObject(position, rotation, objName);
+	
+	return SceneContentGenerator::GenerateSceneObject(position, rotation, objName);
+}
+//-----------------------------------------------------------------------
+SceneNode *TerrainContentGenerator::GenerateSceneObject(const Vector3 &position, 
+					 const Vector3 &rotation, const String& objName)
+{
+	Vector3 queryResult;
+	// set y to max height so we are sure to be over terrain
+	Vector3 pos(position.x, MAX_HEIGHT, position.z);
+
+	if (mRayQueryExecutor->executeRayQuery(&queryResult, position, Vector3::NEGATIVE_UNIT_Y))
+	{
+		// reject if height is too high
+		if (queryResult.y < mMaxPos.y)
+		{
+			// add offset so object is over terrain
+			queryResult.y += mOffset;
+
+			return SceneContentGenerator::GenerateSceneObject(queryResult, rotation, objName);
+		}
+	}
+	
+	return NULL;
+}
+//-----------------------------------------------------------------------
+void TerrainContentGenerator::SetOffset(Real offset)
+{
+	mOffset = offset;
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityDotSceneManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityDotSceneManager.cpp	(revision 59)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreVisibilityDotSceneManager.cpp	(revision 59)
@@ -0,0 +1,107 @@
+#include <OgreVisibilityDotSceneManager.h>
+#include <OgreMath.h>
+#include <OgreIteratorWrappers.h>
+#include <OgreRenderSystem.h>
+#include <OgreCamera.h>
+
+//#include <windows.h>
+
+namespace Ogre {
+
+//-----------------------------------------------------------------------
+VisibilityDotSceneManager::VisibilityDotSceneManager(GtpVisibility::VisibilityManager *visManager)
+:mVisibilityManager(visManager)
+{
+	mHierarchyInterface = 
+		new SceneNodeHierarchyInterface(this, mDestRenderSystem);
+	
+	mShowBoundingBoxes = true;
+	
+	//mDisplayNodes = true;
+	//mShowBoxes = true;
+}
+//-----------------------------------------------------------------------
+VisibilityDotSceneManager::~VisibilityDotSceneManager()
+{
+	delete mHierarchyInterface;
+}
+//-----------------------------------------------------------------------
+void VisibilityDotSceneManager::_renderVisibleObjects(void)
+{
+	//-- render background
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
+	addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
+
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
+	DotSceneManager::_renderVisibleObjects();
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+	//-- render visible objects (i.e., all but overlay)
+	clearSpecialCaseRenderQueues();
+	addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
+	setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
+
+	mHierarchyInterface->InitFrame(mSceneRoot, mCameraInProgress);
+
+	mVisibilityManager->ApplyVisibilityCulling();
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	_deleteRenderedQueueGroups();
+#endif
+
+	//-- render overlay
+	clearSpecialCaseRenderQueues();
+	DotSceneManager::_renderVisibleObjects( );
+
+	clearSpecialCaseRenderQueues();
+}
+//-----------------------------------------------------------------------
+void VisibilityDotSceneManager::_findVisibleObjects(Camera* cam, bool onlyShadowCasters)
+{
+	// must be empty because objects are found and rendered in an interleaved fashion
+	// in _renderVisibibleObjects 
+}
+//-----------------------------------------------------------------------
+void VisibilityDotSceneManager::_updateSceneGraph(Camera* cam)
+{
+	//mVisibilitySceneTraverser->setNumSceneNodes((int)mSceneNodes.size());
+	mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
+	mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
+		        	
+	DotSceneManager::_updateSceneGraph(cam);
+}
+//-----------------------------------------------------------------------
+bool VisibilityDotSceneManager::setOption(const String & key, const void * val)
+{
+	return /*mVisibilitySceneTraverser->setOption( key, val) || */DotSceneManager::setOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityDotSceneManager::getOption(const String & key, void *val)
+{
+	return /*mVisibilitySceneTraverser->getOption( key, val) || */DotSceneManager::getOption(key, val);
+}
+//-----------------------------------------------------------------------
+bool VisibilityDotSceneManager::getOptionValues(const String & key, StringVector  &refValueList)
+{
+	return DotSceneManager::getOptionValues(key, refValueList);
+}
+//-----------------------------------------------------------------------
+bool VisibilityDotSceneManager::getOptionKeys(StringVector & refKeys)
+{
+	return /*mVisibilitySceneTraverser->getOptionKeys ( refKeys ) || */DotSceneManager::getOptionKeys( refKeys );
+}
+//-----------------------------------------------------------------------
+void VisibilityDotSceneManager::setVisibilityManager(GtpVisibility::VisibilityManager *visManager)
+{
+	mVisibilityManager = visManager;
+}
+//-----------------------------------------------------------------------
+GtpVisibility::VisibilityManager *VisibilityDotSceneManager::getVisibilityManager()
+{
+	return mVisibilityManager;
+}
+
+//} // namespace GtpVisibility
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidBoundingBox.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidBoundingBox.cpp	(revision 118)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreSolidBoundingBox.cpp	(revision 118)
@@ -0,0 +1,170 @@
+#include "OgreStableHeaders.h"
+#include "OgreSolidBoundingBox.h"
+
+#include <OgreSimpleRenderable.h>
+#include <OgreHardwareBufferManager.h>
+#include <OgreCamera.h>
+#include <OgreMaterialManager.h>
+#include <OgreMaterial.h>
+#include <OgrePass.h>
+#include <OgreTechnique.h>
+
+namespace Ogre {
+
+#define POSITION_BINDING 0
+//-----------------------------------------------------------------------
+SolidBoundingBox::SolidBoundingBox()
+{
+	 mRenderOp.vertexData = new VertexData();
+	 mRenderOp.indexData = new IndexData();
+
+	 mRenderOp.indexData->indexStart = 0;
+	 mRenderOp.vertexData->vertexStart = 0;
+
+	 mRenderOp.vertexData->vertexCount = 8;
+	 mRenderOp.indexData->indexCount  = 36;
+
+	 mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; 
+	 mRenderOp.useIndexes = true; 
+
+     VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration;
+     VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding;
+
+     decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION);
+	 //decl->addElement(INDEX_BINDING, 0, VET_, VES_POSITION);
+
+	 // create the vertex buffer
+     HardwareVertexBufferSharedPtr vbuf = 
+            HardwareBufferManager::getSingleton().createVertexBuffer(
+                decl->getVertexSize(POSITION_BINDING),
+                mRenderOp.vertexData->vertexCount,
+                HardwareBuffer::HBU_STATIC_WRITE_ONLY);
+
+     // Bind buffer
+     bind->setBinding(POSITION_BINDING, vbuf);
+
+	 //-- index buffer
+	 unsigned short faces[36] = 
+	 {
+        0,2,3,
+        0,1,2,
+        1,6,2,
+        1,5,6,
+        4,6,5,
+        4,7,6,
+        0,7,4,
+        0,3,7,
+        0,5,1,
+        0,4,5,
+        2,7,3,
+        2,6,7
+	 };
+
+	 /// Allocate index buffer of the requested number of vertices 
+     HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton().
+         createIndexBuffer(
+             HardwareIndexBuffer::IT_16BIT, 
+             mRenderOp.indexData->indexCount, 
+             HardwareBuffer::HBU_STATIC_WRITE_ONLY);
+
+	 /// Upload the index data to the card
+	 ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);
+	 //mRenderOp.useSharedVertices = true;
+	 mRenderOp.indexData->indexBuffer = ibuf;
+	 // set material with no lighting, no color, no depth write
+	 SetOcclusionQueryMaterial();
+	 //setMaterial("BaseWhiteNoLighting");
+}
+//-----------------------------------------------------------------------
+SolidBoundingBox::~SolidBoundingBox() 
+{
+	delete mRenderOp.vertexData;
+	delete mRenderOp.indexData;
+}
+//-----------------------------------------------------------------------
+void SolidBoundingBox::SetupBoundingBoxVertices(const AxisAlignedBox& aab) 
+{
+	const Vector3& min = aab.getMinimum();
+    const Vector3& max = aab.getMaximum();
+
+	// fill the vertex buffer: 12 lines with 2 endpoints each make up a box
+    HardwareVertexBufferSharedPtr vbuf =
+        mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING);     
+
+    float* pPos = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
+
+	*pPos++ = min.x; *pPos++ = max.y; *pPos++ = min.z; 
+	*pPos++ = max.x; *pPos++ = max.y; *pPos++ = min.z; 
+	*pPos++ = max.x; *pPos++ = min.y; *pPos++ = min.z; 
+	*pPos++ = min.x; *pPos++ = min.y; *pPos++ = min.z; 
+		
+	*pPos++ = min.x; *pPos++ = max.y; *pPos++ = max.z; 
+	*pPos++ = max.x; *pPos++ = max.y; *pPos++ = max.z; 
+	*pPos++ = max.x; *pPos++ = min.y; *pPos++ = max.z; 
+	*pPos++ = min.x; *pPos++ = min.y; *pPos++ = max.z;
+
+    vbuf->unlock();
+}
+//-----------------------------------------------------------------------
+void SolidBoundingBox::SetupBoundingBox(const AxisAlignedBox& aab)
+{
+	// init the vertices to the aabb
+	SetupBoundingBoxVertices(aab);
+
+	Real sqLen = std::max(aab.getMaximum().squaredLength(), 
+						  aab.getMinimum().squaredLength());
+    mRadius = Math::Sqrt(sqLen);
+
+    // setup the bounding box of this SimpleRenderable
+	setBoundingBox(aab);
+}
+//-----------------------------------------------------------------------
+void SolidBoundingBox::SetOcclusionQueryMaterial()
+{
+	m_pMaterial = MaterialManager::getSingleton().getByName("Visibility/QueryMaterial");
+
+	if (m_pMaterial.isNull())
+	{
+		m_pMaterial = MaterialManager::getSingleton().
+			create("Visibility/QueryMaterial", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+
+		Pass *queryPass = m_pMaterial->getTechnique(0)->getPass(0);
+		queryPass->setColourWriteEnabled(false);
+		queryPass->setDepthWriteEnabled(false);
+		queryPass->setLightingEnabled(false);
+	}
+
+	setMaterial("Visibility/QueryMaterial");
+}
+
+// Override this method to prevent parent transforms (rotation,translation,scale)
+void SolidBoundingBox::getWorldTransforms(Matrix4* xform) const
+{
+	// return identity matrix to prevent parent transforms
+    *xform = Matrix4::IDENTITY;
+}
+//-----------------------------------------------------------------------
+const Quaternion& SolidBoundingBox::getWorldOrientation() const
+{
+	return Quaternion::IDENTITY;
+}
+//-----------------------------------------------------------------------
+const Vector3& SolidBoundingBox::getWorldPosition() const
+{
+	return Vector3::ZERO;
+}
+
+Real SolidBoundingBox::getSquaredViewDepth(const Camera* cam) const
+{
+	Vector3 min, max, mid, dist;
+
+	min = mBox.getMinimum();
+	max = mBox.getMaximum();
+	mid = ((min - max) * 0.5) + min;
+	dist = cam->getDerivedPosition() - mid;
+
+	return dist.squaredLength();
+}
+
+} // namespace Ogre
+
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreItemBufferQueryManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreItemBufferQueryManager.cpp	(revision 171)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreItemBufferQueryManager.cpp	(revision 171)
@@ -0,0 +1,175 @@
+#include "OgreItemBufferQueryManager.h"
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <vector>
+#include <OgreSubEntity.h>
+
+namespace Ogre {
+
+//----------------------------------------------------------------------- 
+ItemBufferQueryManager::ItemBufferQueryManager(PlatformHierarchyInterface *hierarchyInterface, 
+											   Viewport *vp,
+											   const bool renderPatches):
+PlatformQueryManager(hierarchyInterface, vp), mRenderPatchesForItemBuffer(renderPatches)
+{
+}
+//-----------------------------------------------------------------------
+void ItemBufferQueryManager::ComputeCameraVisibility(const Camera &camera,
+			    InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches,
+			    bool relativeVisibility)
+{
+	// we need access to the scene manager and the rendersystem
+	PlatformHierarchyInterface *pfHierarchyInterface = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+
+	SceneManager *sm = pfHierarchyInterface->GetSceneManager();
+
+
+	// const_cast allowed because camera is not changed in renderScene
+	Camera *pCam = const_cast<Camera *>(&camera); 
+
+	// disable overlays, reset them later
+	bool overlayEnabled = mViewport->getOverlaysEnabled();
+	mViewport->setOverlaysEnabled(false);
+	
+	// clear background with black (i.e., not a valid item id)
+	ColourValue bg = mViewport->getBackgroundColour();
+	mViewport->setBackgroundColour(ColourValue(0, 0, 0, 0));
+	//pfHierarchyInterface->GetRenderSystem()->clearFrameBuffer(FBT_COLOUR | FBT_DEPTH);
+
+
+	//-- render scene with item buffer (i.e., objects with their id as color codes)
+
+	// enable item buffer (must be provided by scene manager)
+	bool useItemBuffer = true;
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+	sm->_renderScene(pCam, mViewport, false); // render item buffer
+   
+
+	//-- collect results
+	
+	// initialise item buffer (if not already initialised)
+	InitItemBuffer(visibleNodes, visibleGeometry, visiblePatches);
+
+	int dimx = 0;
+	int dimy = 0;
+
+	// copy frame buffer 
+	uchar *buf = mViewport->getTarget()->getBufferContents(dimx, dimy);
+
+	int n = mRenderPatchesForItemBuffer ? 
+		(int)visiblePatches->size() : (int)visibleGeometry->size();
+
+	//std::stringstream d; d << "dimx: " << dimx << ", dimy: " << dimy; LogManager::getSingleton().logMessage(d.str());
+
+	// loop through frame buffer and collect visible pixels
+	for (int idx = 0; idx < dimy * dimx * 3; idx += 3)
+	{
+		//-- decode color code to receive id
+		int id = buf[idx] << 16;
+		id += buf[idx + 1] << 8;
+		id += buf[idx + 2];
+
+		//std::stringstream d; d << "myid: " << (int)buf[idx] << " " << (int)buf[idx + 1] << " " << (int)buf[idx + 2]; LogManager::getSingleton().logMessage(d.str());
+
+		// if valid id <= add visibility (id values start at 1)
+		if ((id > 0) && (id < n))
+		{
+			if (mRenderPatchesForItemBuffer)
+			{
+				((*visiblePatches)[id]).AddVisibility(1, 1);
+			}
+			else
+			{
+				((*visibleGeometry)[id]).AddVisibility(1, 1);
+			}
+		}
+	}
+
+
+	//-- reset options
+
+	useItemBuffer = false; // don't need item buffer anymore
+	sm->setOption("UseItemBuffer", &useItemBuffer);
+
+	mWasInitialised = false; // reset initialised - flag
+	mViewport->setOverlaysEnabled(overlayEnabled); // reset old overlay status
+	mViewport->setBackgroundColour(bg); // reset background color
+
+	delete [] buf; 	// delete copy of the frame buffer
+}
+//-----------------------------------------------------------------------
+void ItemBufferQueryManager::InitItemBuffer(
+				InfoContainer<GtpVisibility::NodeInfo> *visibleNodes,
+			    InfoContainer<GtpVisibility::MeshInfo> *visibleGeometry,
+				InfoContainer<GtpVisibility::PatchInfo> *visiblePatches)
+{
+	if (mWasInitialised)
+		return;
+
+	mWasInitialised = true;
+
+	SceneManager *sm = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface)->GetSceneManager();
+
+	SceneManager::EntityIterator it = sm->getEntityIterator();
+
+	// TODO: make this more efficient
+	visibleGeometry->clear();
+	visibleNodes->clear();
+	visiblePatches->clear();
+
+	int id = 0;
+
+	/* We can either use patches or meshes. If patches are used, an unique id must
+	   be given each patch. Otherwise the same id must be given to all patches belonging
+	   to the same mesh.
+    */
+	while (it.hasMoreElements())
+	{
+		Entity *ent = it.getNext();
+
+		for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+		{
+			SubEntity *subEnt = ent->getSubEntity(i);
+
+			if (mRenderPatchesForItemBuffer)
+			{
+				++ id;
+				visiblePatches->push_back(GtpVisibility::PatchInfo(subEnt, 0, 0));
+			}
+				
+			subEnt->setId(id);
+			//subEnt->setId((41 << 16) + (4 << 8) + 60);
+			//subEnt->setId((2 << 16) + (4 << 8) + 60);
+		}
+			
+		if (!mRenderPatchesForItemBuffer)
+		{
+			visibleGeometry->push_back(GtpVisibility::MeshInfo(ent, 0, 0));
+			++ id;
+		}
+	}
+}
+
+/*
+//-----------------------------------------------------------------------
+Entity* VisibilityOctreeSceneManager::createEntity(const String& entityName, 
+													const String& meshName)
+{
+	Entity *ent = SceneManager::createEntity(entityName, meshName);
+
+	for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
+	{
+		ent->getSubEntity(i)->setId(mCurrentEntityId);
+	}
+
+	// increase counter of entity id values
+	++ mCurrentEntityId;
+
+	return ent;
+}
+*/
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp	(revision 370)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionQueriesQueryManager.cpp	(revision 370)
@@ -0,0 +1,483 @@
+#include "OgreOcclusionQueriesQueryManager.h"
+#include <OgreLogManager.h>
+#include <OgreStringConverter.h>
+#include <vector>
+#include <OgreSubEntity.h>
+
+
+namespace Ogre {
+
+//----------------------------------------------------------------------- 
+OcclusionQueriesQueryManager::OcclusionQueriesQueryManager(
+							PlatformHierarchyInterface *hierarchyInterface, 
+							Viewport *vp,
+							int queryModes,
+							int itemBufferMode):
+PlatformQueryManager(hierarchyInterface, vp, queryModes), 
+mItemBufferMode(itemBufferMode)
+{
+}
+//-----------------------------------------------------------------------
+void OcclusionQueriesQueryManager::ComputeCameraVisibility(const Camera &camera,
+			    GtpVisibility::NodeInfoContainer *visibleNodes,
+			    GtpVisibility::MeshInfoContainer *visibleGeometry,
+				GtpVisibility::PatchInfoContainer *visiblePatches,
+			    bool relativeVisibility)
+{
+	// we need access to the scene manager and the rendersystem
+	PlatformHierarchyInterface *pfHierarchyInterface = 
+		dynamic_cast<PlatformHierarchyInterface *>(mHierarchyInterface);
+
+	// disable overlays, reset them later
+	bool overlayEnabled = mViewport->getOverlaysEnabled();
+
+	//-- render scene with item buffer (i.e., objects with their id as color codes)
+//mItemBufferMode = 0;
+	if ((mItemBufferMode && mQueryModes) != 0)
+	{
+		int savedQueryModes = mQueryModes;
+		mQueryModes = mItemBufferMode;
+		
+		PlatformQueryManager::ComputeCameraVisibility(camera, visibleNodes,
+			    visibleGeometry, visiblePatches, relativeVisibility);
+		
+		// overlays cause false visibility
+		mViewport->setOverlaysEnabled(false);
+		mQueryModes = savedQueryModes;
+	}
+	else
+	{
+   		// const_cast allowed because camera is not changed in renderScene
+		Camera *pCam = const_cast<Camera *>(&camera); 
+		mViewport->setOverlaysEnabled(false);
+
+		//-- Render scene to get conservative visibility and fill depth buffer
+		pfHierarchyInterface->GetSceneManager()->_renderScene(pCam, mViewport, false);
+	}
+
+	
+	/* 	Two query lists for projected pixels and for visibile pixels:
+		We test queries after a rendering pass 
+		to get exact visibility with regard to the current camera.
+		We issue all queries at once to avoid starvation & stalls.
+	*/
+	GtpVisibility::QueryList queryList[2];
+	
+	// rendered visibile hierarchy nodes from previous rendering
+	GtpVisibility::NodeVector *visNodes = mHierarchyInterface->GetVisibleNodes();
+	GtpVisibility::NodeVector::iterator visNodesIt, visNodesIt_end = visNodes->end();
+
+    GtpVisibility::NodeVector nodeList;
+
+	if (mQueryModes & NODE_VISIBILITY)
+	{
+		for (visNodesIt = visNodes->begin(); visNodesIt != visNodesIt_end; ++visNodesIt)
+		{
+			nodeList.push_back((*visNodesIt));
+		}
+	}
+
+	GtpVisibility::NodeVector::iterator nodeIt, nodeIt_end = nodeList.end();
+
+	// vector for storing entities of meshes
+	GtpVisibility::GeometryVector geometryList;
+	
+	// store geometry of the hierarchy nodes in a geometry list
+	if (mQueryModes & GEOMETRY_VISIBILITY)
+	{	
+		for (visNodesIt = visNodes->begin(); visNodesIt != visNodesIt_end; ++visNodesIt)	
+		{
+			mHierarchyInterface->GetNodeGeometryList(*visNodesIt, &geometryList, false);
+		}
+	}
+	
+	// geometry list iterator
+	GtpVisibility::GeometryVector::iterator geometryIt, geometryIt_end = geometryList.end();
+
+	// vector for storing subentities of meshes
+	GtpVisibility::PatchVector patchList;
+
+	// store patchges of the geometries in a patch list
+	if (mQueryModes & PATCH_VISIBILITY)
+	{
+		for (visNodesIt = visNodes->begin(); visNodesIt != visNodesIt_end; ++visNodesIt)	
+		{
+			GetNodePatchList(*visNodesIt, &patchList);
+		}
+	}
+
+	GtpVisibility::PatchVector::iterator patchIt, patchIt_end = patchList.end();
+
+	// to obtain the correct number of projected pixels, depth write must be disabled
+	bool enableDepthWrite = false;
+	// this option must be provided by the scene manager
+	pfHierarchyInterface->GetSceneManager()->setOption("DepthWrite", &enableDepthWrite);
+
+
+	/* relative visiblity:
+	   1) get visible pixels count of objects
+	   2) clear frame buffer
+	   3) get projected visible pixels count:
+	      test all objects again without depth write (set as option in scene manager)
+	   4) calculate ratio between visible vs. projected pixels
+	*/
+		
+	// for relative visibility we need 2 rendering passes
+	int n = relativeVisibility ? 2 : 1;
+	if (mItemBufferMode > 0)
+		LogManager::getSingleton().logMessage("item buffer");
+
+	for (int i = 0; i < n; ++i)
+	{
+		//-- queries for hierarchy nodes
+		for (nodeIt = nodeList.begin(); nodeIt != nodeIt_end; ++nodeIt)		
+		{
+			// TODO: DELETE QUERIES FROM PREVIOUS RENDER
+			queryList[i].push_back(mHierarchyInterface->IssueNodeOcclusionQuery(*nodeIt, false));
+		}
+
+		//-- queries for geometry: if item buffer, capture only projected visibility
+		if ((mItemBufferMode != GEOMETRY_VISIBILITY) || (i == 1))
+		{			
+			for (geometryIt = geometryList.begin(); geometryIt != geometryIt_end; ++geometryIt)
+			{
+				queryList[i].push_back(pfHierarchyInterface->IssueMeshOcclusionQuery(*geometryIt));
+			}
+		}
+		
+		//-- queries for patches: if item buffer, capture only projected visibility
+		if ((mItemBufferMode != PATCH_VISIBILITY) || (i == 1))
+		{
+			for (patchIt = patchList.begin(); patchIt != patchIt_end; ++patchIt)
+			{
+				queryList[i].push_back(pfHierarchyInterface->IssuePatchOcclusionQuery(*patchIt));
+			}
+		}
+
+		pfHierarchyInterface->GetRenderSystem()->clearFrameBuffer(FBT_DEPTH);
+	}
+
+	
+	//-- collect results
+	GtpVisibility::QueryList::iterator visQueryIt = queryList[0].begin();
+	GtpVisibility::QueryList::iterator projQueryIt = queryList[1].begin();
+	
+	// collect occlusion queries for hierarchy nodes
+	CollectNodeVisibility(visQueryIt, projQueryIt, &nodeList, visibleNodes, relativeVisibility);
+
+
+	// collect occlusion queries for geometry
+	if ((mItemBufferMode == GEOMETRY_VISIBILITY) && relativeVisibility)
+	{
+		// if visibility was established using the item buffer,
+		// the array is organized different (e.g., ordered by id, all possible objects)
+		CollectRelativeGeometryVisibilityForItemBuffer(projQueryIt, &geometryList, visibleGeometry);
+	}
+	else if (mItemBufferMode != GEOMETRY_VISIBILITY)
+	{
+		CollectGeometryVisibility(visQueryIt, projQueryIt, &geometryList, visibleGeometry, 
+								  relativeVisibility);
+	}
+
+
+	// collect occlusion queries for patches
+	if ((mItemBufferMode == PATCH_VISIBILITY) && relativeVisibility)
+	{
+		CollectRelativePatchVisibilityForItemBuffer(projQueryIt, &patchList, visiblePatches);
+	}
+	else if (mItemBufferMode != PATCH_VISIBILITY)
+	{
+		CollectPatchVisibility(visQueryIt, projQueryIt, &patchList, visiblePatches, relativeVisibility);
+	}	
+
+		
+	//-- reset options
+	enableDepthWrite = true;
+	// this option must be provided by the scene manager
+	pfHierarchyInterface->GetSceneManager()->setOption("DepthWrite", &enableDepthWrite);
+	// reset old overlay status
+	mViewport->setOverlaysEnabled(overlayEnabled);
+
+	mWasInitialised = false;
+}
+//-----------------------------------------------------------------------
+void OcclusionQueriesQueryManager::ComputeFromPointVisibility(const Vector3 &point,
+			       GtpVisibility::NodeInfoContainer *visibleNodes,
+			       GtpVisibility::MeshInfoContainer *visibleGeometry,
+				   GtpVisibility::PatchInfoContainer *visiblePatches,
+			       bool relativeVisibility)
+{
+	PlatformQueryManager::ComputeFromPointVisibility(point, visibleNodes, 
+		visibleGeometry, visiblePatches, relativeVisibility);
+
+	// adds up their visibility and removes duplicates 
+	// (duplicates occur if an object is on the edge of the viewport)
+	RemoveDuplicateNodes(visibleNodes);
+	
+	if (mItemBufferMode != GEOMETRY_VISIBILITY)
+	{
+		RemoveDuplicateGeometry(visibleGeometry);
+	}
+	
+	if (mItemBufferMode != PATCH_VISIBILITY)
+	{
+		RemoveDuplicatePatches(visiblePatches);
+	}
+}
+//------j-----------------------------------------------------------------
+void  OcclusionQueriesQueryManager::CollectNodeVisibility(
+						GtpVisibility::QueryList::iterator &visQueryIt, 
+						GtpVisibility::QueryList::iterator &projQueryIt,
+						GtpVisibility::NodeVector *nodeList,  
+						GtpVisibility::NodeInfoContainer *visibleNodes,
+						bool relativeVisibility)
+{
+	GtpVisibility::NodeVector::iterator nodeIt;
+
+	//-- queries for nodes
+	for (nodeIt = nodeList->begin(); nodeIt != nodeList->end(); ++nodeIt)
+	{
+		unsigned int visiblePixels = 0;
+		(*visQueryIt)->GetQueryResult(visiblePixels, true);
+	
+		unsigned int projectedPixels = 0;
+
+		if (relativeVisibility)
+		{
+			(*projQueryIt)->GetQueryResult(projectedPixels, true);
+		
+			++projQueryIt;
+		}
+
+		++visQueryIt;
+		
+		// node with visibilty 0 in queue (e.g., if node is intersected by near plane)
+		if (visiblePixels > 0)
+		{
+			visibleNodes->push_back(GtpVisibility::NodeInfo(*nodeIt, visiblePixels, 
+				projectedPixels));
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void OcclusionQueriesQueryManager::CollectRelativeGeometryVisibilityForItemBuffer(
+									GtpVisibility::QueryList::iterator &projQueryIt,
+									GtpVisibility::GeometryVector *geometryList, 
+									GtpVisibility::MeshInfoContainer *visibleGeometry)
+{
+	GtpVisibility::GeometryVector::iterator geometryIt;
+
+	//-- queries for geometry
+	for (geometryIt = geometryList->begin(); geometryIt != geometryList->end(); ++ geometryIt)
+	{
+		unsigned int projectedPixels = 0;
+
+		(*projQueryIt)->GetQueryResult(projectedPixels, true);
+
+		++projQueryIt;
+		int id = (*geometryIt)->getSubEntity(0)->getId();
+
+		if ((id > 0) && (id < (int)visibleGeometry->size()))
+		{
+			(*visibleGeometry)[id].AddVisibility(0, projectedPixels);
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void OcclusionQueriesQueryManager::CollectRelativePatchVisibilityForItemBuffer(
+									GtpVisibility::QueryList::iterator &projQueryIt,
+									GtpVisibility::PatchVector *patchList, 
+									GtpVisibility::PatchInfoContainer *visiblePatches)
+{
+	GtpVisibility::PatchVector::iterator patchIt;
+
+	//-- queries for geometry
+	for (patchIt = patchList->begin(); patchIt != patchList->end(); ++ patchIt)
+	{
+		unsigned int projectedPixels = 0;
+
+		(*projQueryIt)->GetQueryResult(projectedPixels, true);
+
+		++projQueryIt;
+		int id = (*patchIt)->getId();
+
+		if ((id > 0) && (id < (int)visiblePatches->size()))
+		{
+			(*visiblePatches)[id].AddVisibility(0, projectedPixels);
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void  OcclusionQueriesQueryManager::CollectGeometryVisibility(
+							GtpVisibility::QueryList::iterator &visQueryIt, 
+							GtpVisibility::QueryList::iterator &projQueryIt,
+							GtpVisibility::GeometryVector *geometryList, 
+							GtpVisibility::MeshInfoContainer *visibleGeometry,
+							bool relativeVisibility)
+{
+	GtpVisibility::GeometryVector::iterator geometryIt;
+
+	//-- queries for geometry
+	for (geometryIt = geometryList->begin(); geometryIt != geometryList->end(); ++ geometryIt)
+	{
+		unsigned int visiblePixels = 0;
+		(*visQueryIt)->GetQueryResult(visiblePixels, true);
+		
+		unsigned int projectedPixels = 0;
+
+		if (relativeVisibility)
+		{
+			(*projQueryIt)->GetQueryResult(projectedPixels, true);
+			++ projQueryIt;
+		}
+
+		++ visQueryIt;
+
+		// WARNING: approximate depth ordering during rendering => 
+		// geometry maybe occluded
+		if (visiblePixels > 0)
+		{			 
+			visibleGeometry->push_back(GtpVisibility::MeshInfo(*geometryIt, visiblePixels, 
+				projectedPixels));
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void  OcclusionQueriesQueryManager::CollectPatchVisibility(
+							GtpVisibility::QueryList::iterator &visQueryIt, 
+							GtpVisibility::QueryList::iterator &projQueryIt,
+							GtpVisibility::PatchVector *patchList, 
+							GtpVisibility::PatchInfoContainer *visiblePatches,
+							bool relativeVisibility)
+{
+	GtpVisibility::PatchVector::iterator patchIt;
+
+	//-- queries for patch
+	for (patchIt = patchList->begin(); patchIt != patchList->end(); ++ patchIt)
+	{
+		unsigned int visiblePixels = 0;
+		(*visQueryIt)->GetQueryResult(visiblePixels, true);
+		
+		unsigned int projectedPixels = 0;
+
+		if (relativeVisibility)
+		{
+			(*projQueryIt)->GetQueryResult(projectedPixels, true);
+			++ projQueryIt;
+		}
+
+		++ visQueryIt;
+
+		// WARNING: approximate depth ordering during rendering => 
+		// patch maybe occluded
+		if (visiblePixels > 0)
+		{			 
+			visiblePatches->push_back(GtpVisibility::PatchInfo(*patchIt, visiblePixels, 
+				projectedPixels));
+		}
+	}
+}
+//-----------------------------------------------------------------------
+void  OcclusionQueriesQueryManager::RemoveDuplicateNodes(
+					GtpVisibility::NodeInfoContainer *visibleNodes)
+{
+	stable_sort(visibleNodes->begin(), visibleNodes->end()/*, nodeinfo_lt*/);
+
+	GtpVisibility::NodeInfoContainer::iterator visibleNodesIt,
+		visibleNodesIt_end = visibleNodes->end();
+	
+	GtpVisibility::NodeInfo *nodeInfo = NULL;
+
+	for (visibleNodesIt = visibleNodes->begin(); visibleNodesIt != visibleNodesIt_end; 
+		++visibleNodesIt)
+	{
+		if (!nodeInfo || (nodeInfo->GetSource() != (*visibleNodesIt).GetSource()))
+		{
+			nodeInfo = &(*visibleNodesIt);
+		}
+		else // add visibility
+		{			
+			nodeInfo->AddVisibility(*visibleNodesIt);
+		}
+	}
+	
+	// physically delete duplicates
+	visibleNodes->erase(std::unique(visibleNodes->begin(), visibleNodes->end()),
+						visibleNodes->end());
+}
+//-----------------------------------------------------------------------
+void  OcclusionQueriesQueryManager::RemoveDuplicateGeometry(
+				GtpVisibility::MeshInfoContainer *visibleGeometry)
+{
+	stable_sort(visibleGeometry->begin(), visibleGeometry->end());
+	
+	GtpVisibility::MeshInfoContainer::iterator visibleGeomIt,
+			visibleGeomIt_end = visibleGeometry->end();
+
+	GtpVisibility::MeshInfo *geomInfo = NULL;
+
+	for (visibleGeomIt = visibleGeometry->begin(); visibleGeomIt != visibleGeomIt_end; 
+		++visibleGeomIt)
+	{
+		if (!geomInfo || (geomInfo->GetSource() != (*visibleGeomIt).GetSource()))
+		{
+			geomInfo = &(*visibleGeomIt);
+		}
+		else // info points to same mesh, just add visibility
+		{
+			geomInfo->AddVisibility(*visibleGeomIt);
+		}
+	}
+
+	// physically delete duplicates
+	visibleGeometry->erase(std::unique(visibleGeometry->begin(), visibleGeometry->end()), 
+						   visibleGeometry->end());
+}
+//-----------------------------------------------------------------------
+void  OcclusionQueriesQueryManager::RemoveDuplicatePatches(
+				GtpVisibility::PatchInfoContainer *visiblePatches)
+{
+	stable_sort(visiblePatches->begin(), visiblePatches->end());
+	
+	GtpVisibility::PatchInfoContainer::iterator visiblePatchIt,
+			visiblePatchIt_end = visiblePatches->end();
+
+	GtpVisibility::PatchInfo *patchInfo = NULL;
+
+	for (visiblePatchIt = visiblePatches->begin(); visiblePatchIt != visiblePatchIt_end; 
+		++visiblePatchIt)
+	{
+		if (!patchInfo || (patchInfo->GetSource() != (*visiblePatchIt).GetSource()))
+		{
+			patchInfo = &(*visiblePatchIt);
+		}
+		else // info points to same mesh, just add visibility
+		{
+			patchInfo->AddVisibility(*visiblePatchIt);
+		}
+	}
+
+	// physically delete duplicates
+	visiblePatches->erase(std::unique(visiblePatches->begin(), visiblePatches->end()), 
+						  visiblePatches->end());
+}
+//-----------------------------------------------------------------------
+void OcclusionQueriesQueryManager::GetNodePatchList(GtpVisibility::HierarchyNode *node,	
+					 			 					GtpVisibility::PatchVector *patchList)
+{
+	GtpVisibility::GeometryVector geomList;
+	mHierarchyInterface->GetNodeGeometryList(node, &geomList, false);
+
+	// geometry list iterator
+	GtpVisibility::GeometryVector::iterator geomIt, geomIt_end = geomList.end();
+
+	for (geomIt = geomList.begin(); geomIt != geomIt_end; ++geomIt)
+	{
+		for	(int i = 0; i < (int)(*geomIt)->getNumSubEntities(); ++i)
+		{
+			patchList->push_back((*geomIt)->getSubEntity(i));
+		}
+	}
+}
+
+} // namespace Ogre
Index: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreVisibilitySceneManager.def
===================================================================
--- GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreVisibilitySceneManager.def	(revision 74)
+++ GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/misc/OgreVisibilitySceneManager.def	(revision 74)
@@ -0,0 +1,4 @@
+LIBRARY Plugin_VisibilitySceneManager
+EXPORTS	
+	dllStartPlugin
+	dllStopPlugin
