Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.h	(revision 2756)
@@ -10,8 +10,4 @@
 {
 
-class Material;
-
-
-
 /** Represents drawable geometry consisting of triangles
 */
@@ -19,65 +15,39 @@
 {
 public:
-	/** Constructor taking a triangle container.
+	/** Constructor taking an array of triangles.
 	*/
-	Geometry(const TriangleContainer &triangles);
+	Geometry(Vector3 *vertices, Vector3 *normals, float *texcoords, int numVertices);
+	/** Render the geometry
+	*/
+	void Render();
 
-	int CountTriangles() const { return (int)mTriangles.size(); }
+	int CountTriangles() const { return mNumVertices / 3; }
 
+	inline bool HasTexture() const { return mTexCoords != NULL; }
+	const AxisAlignedBox3& GetBoundingBox() const;
 
 protected:
 
+	void CalcBoundingBox();
+	/** Prepare vbos for rendering
+	*/
+	void Prepare();
+
+
+	//////////
+
+	unsigned int mVboId;
+
+	Vector3 *mVertices;
+
+	Vector3 *mNormals;
+
+	float *mTexCoords;
+
+	int mNumVertices;
+
 	AxisAlignedBox3 mBoundingBox;
-	TriangleContainer mTriangles;
 };
 
-
-/** Class representing a scene entity.
-    A scene entity basicly consists of geometry, transformation, and a material
-*/
-class SceneEntity
-{
-public:
-
-	/** Create scene entity.
-	*/
-	SceneEntity(Geometry *geometry, Matrix4x4 *trafo, Material *mat);
-	/** Renders this geometry.
-	*/
-	void Render();	
-	/** Set pointer to the geometry
-	*/
-	void SetGeometry(Geometry *geom);
-	/** See set
-	*/
-	Geometry *GetGeometry() const { return mGeometry; }
-	/** Set pointer to the geometry
-	*/
-	void SetTransformation(Matrix4x4 *trafo);
-	/** Set pointer to the material
-	*/
-	void SetMaterial(Material *mat);
-	/** Returns the transformed bounding box.
-	*/
-	const AxisAlignedBox3& GetBoundingVolume();
-	/** set frame where we last visitied this node
-	*/
-	void SetLastVisited(int lastVisited);
-	/** returns frame where we last visited this node
-	*/
-	int GetLastVisited() const;
-
-
-protected:
-
-	/// transform matrix 
-	Matrix4x4 *mTransform;
-	Geometry *mGeometry;
-	Material *mMaterial;
-
-	AxisAlignedBox3 mBoundingBox;
-	
-	int mLastVisited;
-};
 
 }
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Material.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Material.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Material.h	(revision 2756)
@@ -6,4 +6,5 @@
 {
 
+class Texture;
 
 class RgbColor 
@@ -54,5 +55,5 @@
   Material();
   
-  Material(const int id);
+  Material(int id);
 
   Material(const RgbColor &color);
@@ -63,8 +64,21 @@
   friend Material RandomMaterial();
 
+  Texture *GetTexture() const { return mTexture; }
+
+  void SetTexture(Texture *texture) { mTexture = texture; }
+  /** Renders this material.
+  */
+  void Render();
+
 protected:
 
-	// unique material id
+	/** Initialize the material with default values
+	*/
+	void InitMaterial();
+
+	/// unique material id
 	int mId;
+	/// the assciated texture
+	Texture *mTexture;
 };
 
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Matrix4x4.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Matrix4x4.h	(revision 2751)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Matrix4x4.h	(revision 2756)
@@ -8,7 +8,5 @@
 {
 
-
 class Vector3;
-
 
 
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.cpp	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.cpp	(revision 2756)
@@ -10,5 +10,6 @@
 #include "glInterface.h"
 #include "Triangle3.h"
-
+#include "SceneEntity.h"
+#include "Geometry.h"
 
 namespace CHCDemo
@@ -557,16 +558,13 @@
 
 
-/*
 void Bvh::ComputeIds()
 {
-	// collect all nodes, also the nodes from local bvh
-	// warning: root nodes local bvh are not in there, as they 
-	// are equivalent geometry bvh leaves
+	// collect all nodes
 	BvhNodeContainer nodes;
-	CollectAllNodes(mRoot, nodes);
+	CollectNodes(mRoot, nodes);
 
 	// assign ids to all nodes of the "regular" hierarchy
 	int i = 0;
-	HierarchyNodeContainer::const_iterator lit, lit_end = nodes.end();
+	BvhNodeContainer::const_iterator lit, lit_end = nodes.end();
 
 	for (lit = nodes.begin(); lit != lit_end; ++ lit, ++ i)
@@ -575,5 +573,5 @@
 	}
 }
-*/
+
 
 void Bvh::PrepareVertices()
@@ -819,13 +817,11 @@
 
 	for (int i = node->mFirst; i <= node->mLast; ++ i)
-	{
 		numTriangles += mGeometry[i]->GetGeometry()->CountTriangles();
-	}
-
+	
 	return numTriangles;
 }
 
 
-float Bvh::GetGeometryArea(BvhNode *node) const
+float Bvh::GetArea(BvhNode *node) const
 {
 	return node->mArea;
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.h	(revision 2756)
@@ -26,5 +26,5 @@
 protected:
 	
-	SceneEntity *LoadShape(std::ifstream &str);
+	SceneEntity *LoadSceneEntity(std::ifstream &str);
 	Material *LoadMaterial(std::ifstream &str);
 	Geometry *LoadGeometry(std::ifstream &str);
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/common.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/common.cpp	(revision 2753)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/common.cpp	(revision 2756)
@@ -35,4 +35,5 @@
 
 
+
 Real Random(Real max)
 {
@@ -57,8 +58,8 @@
 }
 
-void
-Randomize(const unsigned int seed)
-{
-  srand(seed);
+
+void Randomize(const unsigned int seed)
+{
+	srand(seed);
 }
 
@@ -299,52 +300,3 @@
 }
 
-
-#if TOIMPLEMENT
-
-bool
-CreateDir(char *dir)
-{
-#ifdef _MSC_VER
-	HANDLE fFile; // File Handle
-	WIN32_FIND_DATA fileinfo; // File Information Structure
-	int n = strlen(dir) - 1;
-
-	if (dir[n] == '\\' || dir[n] == '/')
-		dir[n]=0;
-
-	fFile = FindFirstFile(dir, &fileinfo);
-
-	// if the file exists and it is a directory
-	if (fileinfo.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) {
-		// Directory Exists close file and return
-		FindClose(fFile);
-		return true;
-	}
-
-	FindClose(fFile);
-
-	// Now lets cycle through the String Array and create each directory in turn
-	if (CreateDirectory(dir, 0)) {
-		SetFileAttributes(dir, FILE_ATTRIBUTE_NORMAL);
-		return true;
-	} else {
-		char *temp = GetPath(dir);
-
-		if (strcmp(temp, dir)!=0) {
-			CreateDir(temp);
-			if (CreateDirectory(dir, 0)) {
-				SetFileAttributes(dir, FILE_ATTRIBUTE_NORMAL);
-				return true;
-			}
-		}
-		delete temp;
-	}
-	Debug << "cannot create directory " << dir << endl;
-#endif
-	return false;
-}
-
-
-#endif
-
-}
+}
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Vector3.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Vector3.h	(revision 2753)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Vector3.h	(revision 2756)
@@ -7,10 +7,10 @@
 
 
+namespace CHCDemo
+{
+
 // Forward-declare some other classes.
 class Matrix4x4;
 
-
-namespace CHCDemo
-{
 
 /** Vector class.
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.cpp	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Geometry.cpp	(revision 2756)
@@ -1,4 +1,5 @@
 #include "Geometry.h"
 #include "Triangle3.h"
+#include "glInterface.h"
 
 
@@ -6,40 +7,91 @@
 {
 
-Geometry::Geometry(const TriangleContainer &triangles)
-{}
-
-
-SceneEntity::SceneEntity(Geometry *geometry, 
-						 Matrix4x4 *trafo, 
-						 Material *mat):
-mGeometry(geometry), mTransform(trafo), mMaterial(mat)
+Geometry::Geometry(Vector3 *vertices, 
+				   Vector3 *normals,
+				   float *texcoords,
+				   int numVertices):
+mVertices(vertices), 
+mNormals(normals), 
+mTexCoords(texcoords),
+mNumVertices(numVertices), 
+mVboId(-1)
 {
+	Prepare();
 }
 
 
-void SceneEntity::Render()
+void Geometry::Prepare()
 {
+	CalcBoundingBox();
+
+	int dataSize = mNumVertices * 6;
+
+	if (mTexCoords)
+		dataSize += mNumVertices * 2;
+	
+	float *data = new float[dataSize];
+
+	for (int i = 0; i < mNumVertices; ++ i)
+	{
+		((Vector3 *)data)[i] = mVertices[i];
+		((Vector3 *)data)[i + mNumVertices] = mNormals[i];
+	}
+
+	if (mTexCoords)
+	{
+		for (int i = 0; i < mNumVertices * 2; ++ i)
+			data[mNumVertices * 6 + i] = mTexCoords[i];
+	}
+
+	glGenBuffersARB(1, &mVboId);
+	
+	glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
+
+	glVertexPointer(3, GL_FLOAT, 0, (char *)NULL);
+	glNormalPointer(GL_FLOAT, 0, (char *)NULL + mNumVertices * sizeof(Vector3));
+
+	if (mTexCoords)
+	{
+		glTexCoordPointer(2, GL_FLOAT, 0, (char *)NULL + 2 * mNumVertices * sizeof(Vector3));
+	}
+	glBufferDataARB(GL_ARRAY_BUFFER_ARB, 
+		            dataSize * sizeof(float), 
+		            (float *)data, 
+					GL_STATIC_DRAW_ARB);
+
+	glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+
+	// data handled by graphics driver from now on
+	delete [] data;
 }
 
 
-void SceneEntity::SetGeometry(Geometry *geom)
+void Geometry::Render()
 {
-	mGeometry = geom;
+	glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
+
+	glVertexPointer(3, GL_FLOAT, 0, (char *)NULL);	
+	glNormalPointer(GL_FLOAT, 0, (char *)NULL + mNumVertices * sizeof(Vector3));
+
+	if (mTexCoords)
+		glTexCoordPointer(2, GL_FLOAT, 0, (char *)NULL + 2 * mNumVertices * sizeof(Vector3));
+
+	// don't render first degenerate index
+	glDrawArrays(GL_TRIANGLES, 0, mNumVertices);
 }
 
 
-void SceneEntity::SetTransformation(Matrix4x4 *trafo)
+void Geometry::CalcBoundingBox()
 {
-	mTransform = trafo;
+	mBoundingBox.Initialize();
+
+	for (int i = 0; i < mNumVertices; ++ i)
+	{
+		mBoundingBox.Include(mVertices[i]);
+	}
 }
 
 
-void SceneEntity::SetMaterial(Material *mat)
-{
-	mMaterial = mat;
-}
-
-
-const AxisAlignedBox3& SceneEntity::GetBoundingVolume()
+const AxisAlignedBox3& Geometry::GetBoundingBox() const
 {
 	return mBoundingBox;
@@ -47,15 +99,3 @@
 
 
-void SceneEntity::SetLastVisited(int lastVisited)
-{
-	mLastVisited = lastVisited;
 }
-
-
-int SceneEntity::GetLastVisited() const
-{
-	return mLastVisited;
-}
-
-
-}
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/chc_revisited.vcproj
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/chc_revisited.vcproj	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/chc_revisited.vcproj	(revision 2756)
@@ -41,5 +41,5 @@
 				Name="VCCLCompilerTool"
 				Optimization="0"
-				AdditionalIncludeDirectories="GL"
+				AdditionalIncludeDirectories="Devil/include;GL"
 				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
 				MinimalRebuild="true"
@@ -63,7 +63,7 @@
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="glut32.lib glew32s.lib glew32.lib"
+				AdditionalDependencies="glut32.lib glew32s.lib glew32.lib DevIL.lib ILUT.lib"
 				LinkIncremental="2"
-				AdditionalLibraryDirectories="GL"
+				AdditionalLibraryDirectories="GL;Devil/lib"
 				GenerateDebugInformation="true"
 				SubSystem="1"
@@ -126,5 +126,5 @@
 				OmitFramePointers="true"
 				EnableFiberSafeOptimizations="true"
-				AdditionalIncludeDirectories="GL"
+				AdditionalIncludeDirectories="GL;Devil/include"
 				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
 				RuntimeLibrary="2"
@@ -147,8 +147,8 @@
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="glut32.lib glew32s.lib glew32.lib"
+				AdditionalDependencies="glut32.lib glew32s.lib glew32.lib DevIL.lib ILUT.lib"
 				LinkIncremental="1"
-				AdditionalLibraryDirectories="GL"
-				GenerateDebugInformation="true"
+				AdditionalLibraryDirectories="GL;Devil/lib"
+				GenerateDebugInformation="false"
 				SubSystem="1"
 				OptimizeReferences="2"
@@ -186,60 +186,4 @@
 	<Files>
 		<Filter
-			Name="Source Files"
-			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
-			>
-			<File
-				RelativePath=".\Bvh.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\Camera.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\chcdemo.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\Geometry.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\Material.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\OcclusionQuery.cpp"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="Header Files"
-			Filter="h;hpp;hxx;hm;inl;inc;xsd"
-			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
-			>
-			<File
-				RelativePath=".\Bvh.h"
-				>
-			</File>
-			<File
-				RelativePath=".\Camera.h"
-				>
-			</File>
-			<File
-				RelativePath=".\Geometry.h"
-				>
-			</File>
-			<File
-				RelativePath=".\Material.h"
-				>
-			</File>
-			<File
-				RelativePath=".\OcclusionQuery.h"
-				>
-			</File>
-		</Filter>
-		<Filter
 			Name="utils"
 			>
@@ -324,44 +268,128 @@
 			Name="traversal"
 			>
-			<File
-				RelativePath=".\CHCPlusPlusTraverser.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\CHCPlusPlusTraverser.h"
-				>
-			</File>
-			<File
-				RelativePath=".\CHCTraverser.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\CHCTraverser.h"
-				>
-			</File>
-			<File
-				RelativePath=".\FrustumCullingTraverser.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\FrustumCullingTraverser.h"
-				>
-			</File>
-			<File
-				RelativePath=".\RenderTraverser.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\RenderTraverser.h"
-				>
-			</File>
-			<File
-				RelativePath=".\StopAndWaitTraverser.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\StopAndWaitTraverser.h"
-				>
-			</File>
+			<Filter
+				Name="Header Files"
+				>
+				<File
+					RelativePath=".\CHCPlusPlusTraverser.h"
+					>
+				</File>
+				<File
+					RelativePath=".\CHCTraverser.h"
+					>
+				</File>
+				<File
+					RelativePath=".\FrustumCullingTraverser.h"
+					>
+				</File>
+				<File
+					RelativePath=".\RenderTraverser.h"
+					>
+				</File>
+				<File
+					RelativePath=".\StopAndWaitTraverser.h"
+					>
+				</File>
+			</Filter>
+			<Filter
+				Name="Source Files"
+				>
+				<File
+					RelativePath=".\CHCPlusPlusTraverser.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\CHCTraverser.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\FrustumCullingTraverser.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\RenderTraverser.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\StopAndWaitTraverser.cpp"
+					>
+				</File>
+			</Filter>
+		</Filter>
+		<Filter
+			Name="render"
+			>
+			<Filter
+				Name="Header Files"
+				Filter="h;hpp;hxx;hm;inl;inc;xsd"
+				UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+				>
+				<File
+					RelativePath=".\Bvh.h"
+					>
+				</File>
+				<File
+					RelativePath=".\Camera.h"
+					>
+				</File>
+				<File
+					RelativePath=".\Geometry.h"
+					>
+				</File>
+				<File
+					RelativePath=".\Material.h"
+					>
+				</File>
+				<File
+					RelativePath=".\OcclusionQuery.h"
+					>
+				</File>
+				<File
+					RelativePath=".\SceneEntity.h"
+					>
+				</File>
+				<File
+					RelativePath=".\Texture.h"
+					>
+				</File>
+			</Filter>
+			<Filter
+				Name="Source Files"
+				Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+				UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+				>
+				<File
+					RelativePath=".\Bvh.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\Camera.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\chcdemo.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\Geometry.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\Material.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\OcclusionQuery.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\SceneEntity.cpp"
+					>
+				</File>
+				<File
+					RelativePath=".\Texture.cpp"
+					>
+				</File>
+			</Filter>
 		</Filter>
 		<File
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.h	(revision 2756)
@@ -49,4 +49,5 @@
 	inline float GetAspect() const { return (float) mWidth / mHeight; }
 
+	void SetupCameraView();
 	void GetProjectionMatrix(Matrix4x4 &mat);
 	void GetModelViewMatrix(Matrix4x4 &mat);
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Material.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Material.cpp	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Material.cpp	(revision 2756)
@@ -1,9 +1,12 @@
 #include "common.h"
 #include "Material.h"
+#include "Texture.h"
+#include "glInterface.h"
+
 
 namespace CHCDemo
 {
 
-RgbColor RandomColor(const float a, const float b)
+RgbColor RandomColor(float a, float b)
 {
 	return RgbColor(a + Random(b), a + Random(b), a + Random(b));
@@ -11,17 +14,33 @@
 
 
- 
-Material::Material(): mId(0)
-{}
-  
+void Material::InitMaterial()
+{
+	mTexture = NULL;
 
-Material::Material(const int id): mId(id)
-{
+	mAmbientColor = RgbColor(0, 0, 0);
+	mDiffuseColor = RgbColor(1, 1, 1);
+	mSpecularColor = RgbColor(0, 0, 0);
 }
 
 
-Material::Material(const RgbColor &color):mDiffuseColor(color),
+Material::Material(): mId(0)
+{
+	InitMaterial();
+}
+
+
+Material::Material(int id): 
+mId(id)
+{
+	InitMaterial();
+}
+
+
+Material::Material(const RgbColor &color):
+mDiffuseColor(color),
 mAmbientColor(color),
-mSpecularColor(0,0,0), mId(0)
+mSpecularColor(0, 0, 0), 
+mId(0),
+mTexture(NULL)
 {
 }
@@ -45,3 +64,17 @@
 }
 
+
+void Material::Render()
+{
+	if (mTexture)
+		mTexture->Bind();
+	else
+		glBindTexture(GL_TEXTURE_2D, 0);
+
+	glMaterialfv(GL_FRONT, GL_AMBIENT, (float *)&mAmbientColor.r);
+	glMaterialfv(GL_FRONT, GL_DIFFUSE, (float *)&mDiffuseColor.r);
+	glMaterialfv(GL_FRONT, GL_SPECULAR, (float *)&mSpecularColor.r);
 }
+
+
+}
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/chcdemo.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/chcdemo.cpp	(revision 2753)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/chcdemo.cpp	(revision 2756)
@@ -1,20 +1,37 @@
 // occquery.cpp : Defines the entry point for the console application.
 //
-#if TOIMPLEMENT
-
 #include <math.h>
 #include <time.h>
+#include "common.h"
 #include "glInterface.h"
 #include "RenderTraverser.h"
-
-
-
-bool arbQuerySupport = false;
-bool nvQuerySupport = false;
-
-double nearDist = 0.1; // eye near plane distance
+#include "SceneEntity.h"
+#include "Vector3.h"
+#include "Matrix4x4.h"
+#include "BinaryLoader.h"
+#include "Bvh.h"
+#include "Camera.h"
+#include "Geometry.h"
+
+
+using namespace std;
+using namespace CHCDemo;
+
+
+
+/// the renderable scene geometry
+SceneEntityContainer sceneEntities;
+// traverses and renders the hierarchy
+RenderTraverser *traverser;
+/// the hierarchy
+Bvh *bvh;
+/// the scene camera
+Camera *camera;
+/// the scene bounding box
+AxisAlignedBox3 sceneBox;
+
+// eye near plane distance
+float nearDist = 0.1f; 
 int winWidth, winHeight;
-int objectType = Geometry::TEAPOT;
-int nextObjectType = objectType;
 
 float visZoomFactor = 1.5f;
@@ -26,10 +43,8 @@
 bool showCreateParams = false;
 
-// traverses and renders the hierarchy
-RenderTraverser traverser;
-
-Vector3 eyePos = {0.0, 0.0, 3.0};  // eye position 
-Vector3 viewDir = {0.0, 0.0, -1.0};  // eye view dir 
-Vector3 lightDir = {0.0, 0.0, 1.0};  // light dir 
+
+Vector3 eyePos = Vector3(0.0f, 0.0f, 3.0f);    // eye position 
+Vector3 viewDir = Vector3(0.0f, 0.0f, -1.0f);  // eye view dir 
+Vector3 lightDir = Vector3(0.0f, 0.0f, 1.0f);  // light dir 
 
 Matrix4x4 eyeView; // eye view matrix
@@ -41,5 +56,5 @@
 //mouse navigation state
 int xEyeBegin, yEyeBegin, yMotionBegin, verticalMotionBegin, horizontalMotionBegin = 0;
-int renderMode = RenderTraverser::RENDER_COHERENT;
+//int renderMode = RenderTraverser::RENDER_COHERENT;
 
 // relative size of an object
@@ -51,6 +66,6 @@
 
 // this defines the volume where objects can be drawn
-Vector3 minTranslation = {-2.5f, -2.5f, -3.0f};
-Vector3 maxTranslation = {2.5f, 2.5f, -3.0 - zLength};
+Vector3 minTranslation(-2.5f, -2.5f, -3.0f);
+Vector3 maxTranslation(2.5f, 2.5f, -3.0 - zLength);
 
 const float minAngle = 0;
@@ -62,9 +77,6 @@
 int renderTimesValid = 0;
 
-typedef vector<Geometry *> GeometryList;
-GeometryList geometry;
-
 bool useOptimization = true;
-bool useArbQueries = false;
+
 
 Vector3 amb[2];
@@ -72,44 +84,49 @@
 Vector3 spec[2];
 
+void InitExtensions(void);
+void DisplayVisualization();
+void InitGLstate(void);
+void CleanUp(void);
+void SetupEyeView(void);
+void UpdateEyeMtx(void);
+
+
 void begin2D(void);
 void end2D(void);
-void output(const int x, const int y, const char *string);
-void initGLstate(void);
-void keyboard(const unsigned char c, const int x, const int y);
+void output(int x, int y, const char *string);
+void keyboard(const unsigned char c, int x, int y);
 void drawHelpMessage(void);
 void drawStatistics(void);
 void display(void);
-void special(const int c, const int x, const int y);
-void reshape(const int w, const int h);
+void special(int c, int x, int y);
+void reshape(int w, int h);
 void mouse(int button, int state, int x, int y);
-void initExtensions(void);
 void leftMotion(int x, int y);
-//void rightMotion(int x, int y);
 void middleMotion(int x, int y);
 void drawEyeView(void);
-void setupEyeView(void);
 void setupVisView(void);
-void updateEyeMtx(void);
 long calcRenderTime(void);
 void resetTimer(void);
-void cleanUp(void);
-void calcDecimalPoint(string &str, int d);
-
-HierarchyNode* generateHierarchy(int numObjects);
-Geometry *generateGeometry(Vector3 translateRatio, float xRotRatio, 
-						   float yRotRatio, float zRotRatio, int materialIdx);
-void displayVisualization();
-
-void deleteGeometry();
-
-#endif
+void calcDecimalPoint(std::string &str, int d);
+
+
+
+void SetupProjection(int w, int h, float angle, const AxisAlignedBox3 &sceneBox)
+{
+	glViewport(0, 0, w, h);
+	glMatrixMode(GL_PROJECTION);
+	glLoadIdentity();
+
+	gluPerspective(angle, 1.0, 1.0f, 2.0 * Magnitude(sceneBox.Diagonal()));
+	glMatrixMode(GL_MODELVIEW);
+}
+
 
 int main(int argc, char* argv[])
 {
-#if 0
-	glutInitWindowSize(800,600);
-	glutInit(&argc,argv);
+	glutInitWindowSize(800, 600);
+	glutInit(&argc, argv);
 	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
-	
+
 	glutCreateWindow("Coherent Hierarchical Culling");
 
@@ -120,12 +137,37 @@
 	glutMouseFunc(mouse);
 	glutIdleFunc(display);
-	initExtensions();
-	initGLstate();
-
-	leftMotion(0,0);
-	middleMotion(0,0);
-	
-	HierarchyNode *hierarchy = generateHierarchy(numObjects);
-	traverser.SetHierarchy(hierarchy);
+	
+	InitExtensions();
+	InitGLstate();
+
+	leftMotion(0, 0);
+	middleMotion(0, 0);
+
+	BinaryLoader loader;
+
+	const string filename("house_test.dem");
+	//const string filename("city.dem");
+
+	camera = new Camera(800, 600);
+
+	if (loader.Load(filename, sceneEntities))
+		cout << "scene " << filename << " loaded" << endl;
+	else
+		cerr << "loading scene " << filename << " failed" << endl;
+
+	sceneBox.Initialize();
+
+	SceneEntityContainer::const_iterator it, it_end = sceneEntities.end();
+
+	for (it = sceneEntities.begin(); it != it_end; ++ it)
+		sceneBox.Include((*it)->GetBoundingBox());
+
+	Debug << "scene box: " << sceneBox << endl;
+
+	SetupProjection(800, 600, 60, sceneBox);
+	camera->LookAtBox(sceneBox);
+	//camera->LookInBox(sceneBox);
+	//camera->SetPosition(Vector3(0, 0, -3));
+	//camera->SetDirection(Vector3(0, 0, 1));
 
 	/// initialise rendertime array
@@ -136,33 +178,33 @@
 
 	// clean up
-	cleanUp();
-#endif
+	CleanUp();
+
 	return 0;
 }
 
-#if 0
-void initGLstate(void) 
-{
-	glClearColor(0.6, 0.6, 0.8, 1.0);
+
+void InitGLstate(void) 
+{
+	glClearColor(0.0f, 1.0f, 0.0f, 0.0);
 	
 	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 	glPixelStorei(GL_PACK_ALIGNMENT,1); 
 	
-	glDepthRange(0.0, 1.0);
-	glClearDepth(1.0);
 	glDepthFunc(GL_LESS);
 
 	glEnable(GL_LIGHTING);
 	glEnable(GL_LIGHT0);
-
+	//glDisable(GL_LIGHTING);
+
+	glColor3f(1.0f, 0.0f, 0.0f);
 	glShadeModel(GL_SMOOTH);
 	
-	GLfloat ambient[] = { 0.0, 0.0, 0.0, 1.0 };
-	GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
-	GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 };
-	GLfloat position[] = { 0.0, 3.0, 3.0, 0.0 };
+	GLfloat ambient[] = {0.5, 0.5, 0.5, 1.0};
+	GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
+	GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
+	GLfloat position[] = {0.0, 3.0, 3.0, 0.0};
     
-	GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
-	GLfloat local_view[] = { 0.0 };
+	GLfloat lmodel_ambient[] = {0.2, 0.2, 0.2, 1.0};
+	GLfloat local_view[] = {0.0};
 
 	glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
@@ -179,8 +221,16 @@
 	glCullFace(GL_BACK);
 	glEnable(GL_CULL_FACE);
-	
-	glClearColor(0.2, 0.2, 0.8, 0.0);
-
-	setupVisView();
+	//glDisable(GL_CULL_FACE);
+	
+	GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
+	GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
+	GLfloat specularColor[] = {1.0, 1.0, 1.0, 1.0};
+
+	glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
+	glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
+	glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
+
+	glColor3f(1.0f, 0.0f, 0.0f);
+	//setupVisView();
 }
 
@@ -226,9 +276,10 @@
 	};
 	
-	int i;
+	
 	int x = 40, y = 42;
+
 	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 	glEnable(GL_BLEND);
-	glColor4f(0.0,1.0,0.0,0.2);  // 20% green. 
+	glColor4f(0.0f, 1.0f , 0.0f, 0.2f);  // 20% green. 
 
 	// Drawn clockwise because the flipped Y axis flips CCW and CW. 
@@ -237,11 +288,15 @@
 	glDisable(GL_BLEND);
 	
-
-	glColor3f(1.0,1.0,1.0);
-	for(i = 0; message[i] != 0; i++) {
-		if(message[i][0] == '\0') {
+	glColor3f(1.0f, 1.0f, 1.0f);
+	
+	for(int i = 0; message[i] != 0; i++) 
+	{
+		if(message[i][0] == '\0') 
+		{
 			y += 7;
-		} else {
-			output(x,y,message[i]);
+		} 
+		else 
+		{
+			output(x, y, message[i]);
 			y += 14;
 		}
@@ -250,91 +305,28 @@
 }
 
-// generates a teapot, all parameters between zero and one
-Geometry *generateGeometry(Vector3 translationRatio, float xRotRatio, 
-						   float yRotRatio, float zRotRatio, int materialIdx)
-{
-	float xRot = minAngle + xRotRatio * (maxAngle - minAngle);
-	float yRot = minAngle + yRotRatio * (maxAngle - minAngle);
-	float zRot = minAngle + zRotRatio * (maxAngle - minAngle);
-
-	Vector3 translation;
-	translation[0] = minTranslation[0] + translationRatio[0] * (maxTranslation[0] - minTranslation[0]);
-	translation[1] = minTranslation[1] + translationRatio[1] * (maxTranslation[1] - minTranslation[1]);
-	translation[2] = minTranslation[2] + translationRatio[2] * (maxTranslation[2] - minTranslation[2]);
-
-	Geometry *result = new Geometry(translation, xRot, yRot, zRot, objectSize, objectType);
-
-	result->SetAmbientColor(amb[materialIdx][0], amb[materialIdx][1], amb[materialIdx][2]);
-	result->SetDiffuseColor(dif[materialIdx][0], dif[materialIdx][1], dif[materialIdx][2]);
-	result->SetSpecularColor(spec[materialIdx][0], spec[materialIdx][1], spec[materialIdx][2]);
-
-	return result;
-}
-
-// generates a the scene hierarchy with random values
-HierarchyNode* generateHierarchy(int numObjects)
-{
-    HierarchyNode *hierarchy = new HierarchyNode();
-
-	// initialise materials
-	copyVector3Values(amb[0], 0.0215, 0.1745, 0.0215);
-	copyVector3Values(dif[0], 0.727811, 0.633, 0.6);
-	copyVector3Values(spec[0], 0.633, 0.727811, 0.633);
-
-	copyVector3Values(amb[1], 0.1745, 0.01175, 0.01175);
-	copyVector3Values(dif[1], 0.61424, 0.04136, 0.04136);
-	copyVector3Values(spec[1], 0.727811, 0.626959, 0.626959);
-
-	srand (time (0));
-	
-	printf("generating geometry with random position and orientation ... ");
-
-	for(int i=0; i < numObjects; i++)
-	{
-		float xRotRatio = rand() / (float) RAND_MAX;
-		float yRotRatio = rand() / (float) RAND_MAX;
-		float zRotRatio = rand() / (float) RAND_MAX;
-
-		Vector3 translationRatio = {rand() / (float) RAND_MAX, 
-									rand() / (float) RAND_MAX, 
-									rand() / (float) RAND_MAX};
-
-		int materialIdx = int(2 * rand() / (float) RAND_MAX);
-			
-		Geometry *geo = generateGeometry(translationRatio, xRotRatio, 
-									     yRotRatio, zRotRatio, materialIdx);
-		hierarchy->AddGeometry(geo);
-
-		// put into global geometry list for later deletion
-		geometry.push_back(geo);
-	}
-
-	printf("finished\n");
-	printf("generating new kd-tree hierarchy ... ");
-	HierarchyNode::InitKdTree(hierarchy);
-	hierarchy->GenerateKdTree();
-	printf("finished\n");
-
-	return hierarchy;
-}
-
-
-void updateEyeMtx(void) 
-{
-	const Vector3 up = {0.0, 1.0, 0.0};
+
+void UpdateEyeMtx(void) 
+{
+	/*const Vector3 up(0.0, 1.0, 0.0);
 
 	look(eyeView, eyePos, viewDir, up);
 	mult(eyeProjView, eyeProjection, eyeView); //eyeProjView = eyeProjection*eyeView
 	invert(invEyeProjView, eyeProjView); //invert matrix
-}
-
-
-void setupEyeView(void)
-{
-	glMatrixMode(GL_PROJECTION);
-	glLoadMatrixd(eyeProjection);
-
+	*/
+}
+
+
+void SetupEyeView(void)
+{
+	SetupProjection(800,600,60,sceneBox);
 	glMatrixMode(GL_MODELVIEW);
-	glLoadMatrixd(eyeView);
+	camera->SetupCameraView();
+
+/*	glMatrixMode(GL_PROJECTION);
+	glLoadMatrixf((float *)eyeProjection.x);
+
+	glMatrixMode(GL_MODELVIEW);
+	glLoadMatrixf((float *)eyeView.x);
+	*/
 }
 
@@ -353,9 +345,10 @@
 	char msg8[100];
 
+/*
 	sprintf_s(msg2, "Traversed: %4d, frustum culled: %4d, query culled: %4d (of %d nodes)",
 			traverser.GetNumTraversedNodes(), traverser.GetNumFrustumCulledNodes(),
 			traverser.GetNumQueryCulledNodes(), 
 			traverser.GetHierarchy()->GetNumHierarchyNodes());
-	
+
 	char *optstr[2] = {"", ", using optimization"};
 	char *querystr[2] = {"NV", "ARB"};
@@ -384,14 +377,49 @@
 	sprintf_s(msg7, "Next object type: %s", objectTypeStr[nextObjectType]);
 	sprintf_s(msg8, "Next object size: %3.3f", objectSize);
+*/
 
 	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
-	updateEyeMtx(); // bring eye modelview matrix up-to-date
-	setupEyeView();
-
+	// bring eye modelview matrix up-to-date
+	UpdateEyeMtx(); 
+	SetupEyeView();
+
+	glEnableClientState(GL_VERTEX_ARRAY);
+	glEnableClientState(GL_NORMAL_ARRAY);
+
+	bool usesTextures = false;
+
+	SceneEntityContainer::const_iterator sit, sit_end = sceneEntities.end();
+
+	for (sit = sceneEntities.begin(); sit != sit_end; ++ sit)
+	{
+		SceneEntity *entity = *sit;
+
+		if (!usesTextures && entity->GetGeometry()->HasTexture())
+		{
+			glEnable(GL_TEXTURE_2D);
+			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+			usesTextures = true;
+		}
+		else if (usesTextures && !entity->GetGeometry()->HasTexture())
+		{
+			glDisable(GL_TEXTURE_2D);
+			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+			usesTextures = false;
+		}
+
+		entity->Render();
+	}
+
+	glDisableClientState(GL_VERTEX_ARRAY);
+	glDisableClientState(GL_NORMAL_ARRAY);
+
+	glDisable(GL_TEXTURE_2D);
+	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+
+	/*
 	traverser.SetViewpoint(eyePos);
 	traverser.SetProjViewMatrix(eyeProjView);
 	traverser.Render(renderMode);
-
 	// cycle through rendertime array
 	renderTimes[renderTimesIdx] = traverser.GetRenderTime();
@@ -402,15 +430,18 @@
 
 	if(visMode)
-	{
 		displayVisualization();
-	}
+	*/
+
 	
 	begin2D();
+	
 	if(showHelp)
+	{	
 		drawHelpMessage();
+	}
 	else
 	{
 		glColor3f(1.0,1.0,1.0);
-		output(10,winHeight-10, msg[renderMode]);
+		//output(10, winHeight-10, msg[renderMode]);
 
 		if(showStatistics)
@@ -428,4 +459,5 @@
 		}
 	}
+
 	end2D();
 
@@ -437,6 +469,6 @@
 void keyboard(const unsigned char c, const int x, const int y) 
 {
-	int threshold;
-	HierarchyNode *hierarchy;
+	//int threshold;
+	//HierarchyNode *hierarchy;
 
 	switch(c) 
@@ -446,8 +478,9 @@
 		break;
 	case 32: //space
-		renderMode = (renderMode + 1) % RenderTraverser::NUM_RENDERMODES;
+	
+		//	renderMode = (renderMode + 1) % RenderTraverser::NUM_RENDERMODES;
 		
 		resetTimer();
-		traverser.Render(renderMode);		// render once so stats are updated
+		//traverser.Render(renderMode);		// render once so stats are updated
 		break;
 	case 'h':
@@ -458,5 +491,5 @@
 	case 'V':
 		showBoundingVolumes = !showBoundingVolumes;
-		HierarchyNode::SetRenderBoundingVolume(showBoundingVolumes);
+		//HierarchyNode::SetRenderBoundingVolume(showBoundingVolumes);
 		break;
 	case 's':
@@ -465,12 +498,12 @@
 		break;
 	case '+':
-		threshold = traverser.GetVisibilityThreshold() + 10;
-		traverser.SetVisibilityThreshold(threshold);
+		//threshold = traverser.GetVisibilityThreshold() + 10;
+		//traverser.SetVisibilityThreshold(threshold);
 		break;
 	case '-':
-		threshold = traverser.GetVisibilityThreshold() - 10;
-		if(threshold < 0) threshold = 0;
-
-		traverser.SetVisibilityThreshold(threshold);		
+		//threshold = traverser.GetVisibilityThreshold() - 10;
+		//if(threshold < 0) threshold = 0;
+
+		//traverser.SetVisibilityThreshold(threshold);		
 		break;
 	case '1':
@@ -495,17 +528,12 @@
 	case 'G':
 		useOptimization = !useOptimization;
-		traverser.SetUseOptimization(useOptimization);
-		break;
-	case 'n':
-	case 'N':
-		useArbQueries = !useArbQueries;
-		traverser.SetUseArbQueries(useArbQueries);
-		break;
+		//traverser.SetUseOptimization(useOptimization);
+		break;
+		/*
 	case 'c':
 	case 'C':	
-		
 		hierarchy = traverser.GetHierarchy();
 		// delete old hierarchy
-		if(hierarchy) delete hierarchy; 
+		if (hierarchy) delete hierarchy; 
 		deleteGeometry();
 
@@ -522,5 +550,5 @@
 		resetTimer();
 		break;
-
+		*/
 	default:
 		return;
@@ -534,5 +562,5 @@
 {
 	// used to avoid vertical motion with the keys
-	Vector3 hvec = {viewDir[0], 0, viewDir[2]};
+	Vector3 hvec = Vector3(viewDir[0], 0, viewDir[2]);
 	
 	switch(c) 
@@ -542,9 +570,9 @@
 		break;
 	case GLUT_KEY_F2:
-		numNextObjects -= 100;
-		if(numNextObjects < 100) numNextObjects = 100;
+		//numNextObjects -= 100;
+		//if(numNextObjects < 100) numNextObjects = 100;
 		break;
 	case GLUT_KEY_F3:
-        numNextObjects += 100;
+       // numNextObjects += 100;
 		break;
 	case GLUT_KEY_F4:
@@ -563,17 +591,17 @@
 		break;
 	case GLUT_KEY_F8:
-		nextObjectType = (nextObjectType + 1) % Geometry::NUM_OBJECTS;
+		//nextObjectType = (nextObjectType + 1) % Geometry::NUM_OBJECTS;
 		break;
 	case GLUT_KEY_LEFT:
-		rotateVectorY(viewDir, 0.2);
+	//	rotateVectorY(viewDir, 0.2);
 		break;
 	case GLUT_KEY_RIGHT:
-		rotateVectorY(viewDir, -0.2);
+		//rotateVectorY(viewDir, -0.2);
 		break;
 	case GLUT_KEY_UP:
-		linCombVector3(eyePos, eyePos, hvec, 0.6);
+	//	linCombVector3(eyePos, eyePos, hvec, 0.6);
 		break;
 	case GLUT_KEY_DOWN:
-		linCombVector3(eyePos, eyePos, hvec, -0.6);
+		//linCombVector3(eyePos, eyePos, hvec, -0.6);
 		break;
 	default:
@@ -598,5 +626,5 @@
 	if(w) winAspectRatio = (double) h / (double) w;
 
-	perspectiveDeg(eyeProjection, 60.0, 1.0/winAspectRatio, nearDist, 150.0);
+	//perspectiveDeg(eyeProjection, 60.0, 1.0/winAspectRatio, nearDist, 150.0);
 
 	glutPostRedisplay();
@@ -631,7 +659,9 @@
 	static double eyeXAngle = 0.0;
 	// not move in the vertical direction
-	Vector3 horView = {viewDir[0], 0, viewDir[2]};
-	
-	eyeXAngle = 0.6 *  PI * (xEyeBegin - x) / 180.0;
+	Vector3 horView = Vector3(viewDir[0], 0, viewDir[2]);
+	
+	eyeXAngle = 0.6 *  M_PI * (xEyeBegin - x) / 180.0;
+
+	/*
 	linCombVector3(eyePos, eyePos, horView, (yMotionBegin - y) * 0.1);
 	
@@ -640,5 +670,5 @@
 	xEyeBegin = x;
 	yMotionBegin = y;
-
+	*/
 	glutPostRedisplay();
 }
@@ -649,7 +679,7 @@
 	// the 90 degree rotated view vector 
 	// y zero so we don't move in the vertical
-	Vector3 rVec = {viewDir[0], 0, viewDir[2]};
-	
-	rotateVectorY(rVec, PI / 2.0);
+	Vector3 rVec = Vector3(viewDir[0], 0, viewDir[2]);
+	
+	/*rotateVectorY(rVec, PI / 2.0);
 	linCombVector3(eyePos, eyePos, rVec, (horizontalMotionBegin - x) * 0.1);
 	
@@ -658,12 +688,13 @@
 	horizontalMotionBegin = x;
 	verticalMotionBegin = y;
-
+*/
 	glutPostRedisplay();
 }
 
 
-void initExtensions(void) 
+void InitExtensions(void) 
 {
 	GLenum err = glewInit();
+
 	if (GLEW_OK != err) 
 	{
@@ -672,15 +703,7 @@
 		exit(1);
 	}
-
-	if (GLEW_ARB_occlusion_query) 
-		arbQuerySupport = true;
-	
-	if (GLEW_NV_occlusion_query) 
-		nvQuerySupport = true;
-	
-
-	if  (!arbQuerySupport && !nvQuerySupport)
-	{
-		printf("I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n");
+	if  (!GLEW_ARB_occlusion_query)
+	{
+		printf("I require the GL_ARB_occlusion_query to work.\n");
 		exit(1);
 	}
@@ -729,14 +752,4 @@
 }
 
-// explicitly deletes geometry generated for hierarchy 
-// (deleting the hierarchy does not delete the geometry)
-void deleteGeometry()
-{
-	for (GeometryList::iterator it = geometry.begin(); it != geometry.end(); it++)
-		if(*it)	delete (*it);
-	
-	geometry.clear();
-}
-
 // displays the visualisation of the kd tree node culling
 void displayVisualization()
@@ -753,26 +766,25 @@
 	glViewport(winWidth / 2, winHeight / 2, winWidth, winHeight);
 	glPushMatrix();
-	glLoadMatrixd(visView);
+	glLoadMatrixf((float *)visView.x);
 	
 	glClear(GL_DEPTH_BUFFER_BIT);
 
 	// --- visualization of the occlusion culling
-	HierarchyNode::SetRenderBoundingVolume(true);
+	/*HierarchyNode::SetRenderBoundingVolume(true);
 	traverser.RenderVisualization();
 	HierarchyNode::SetRenderBoundingVolume(showBoundingVolumes);
-
+*/
 	glPopMatrix();
 	glViewport(0, 0, winWidth, winHeight);
 }
 
-/**
-	sets up view matrix in order to get a good position 
+/** Sets up view matrix in order to get a good position 
 	for viewing the kd tree node culling
 */
 void setupVisView()
 {
-	const Vector3 up = {0.0, 1.0, 0.0};
-	
-	Vector3 visPos = {24, 23, -6};
+	const Vector3 up(0.0, 1.0, 0.0);
+	
+	Vector3 visPos(24, 23, -6);
 	
 	visPos[0] *= visZoomFactor; 
@@ -780,8 +792,8 @@
 	visPos[2] *= visZoomFactor;
 
-	Vector3 visDir = {-1.3,-1,-1};
-	
-	normalize(visDir);
-	look(visView, visPos, visDir, up);
+	Vector3 visDir = Vector3(-1.3, -1, -1);
+	
+	//normalize(visDir);
+	//look(visView, visPos, visDir, up);
 }
 
@@ -810,12 +822,10 @@
 
 // cleanup routine after the main loop
-void cleanUp()
-{
-	if(traverser.GetHierarchy()) 
-		delete traverser.GetHierarchy();
-
-	deleteGeometry();
-
-	Geometry::CleanUp();
+void CleanUp()
+{
+	CLEAR_CONTAINER(sceneEntities);
+	DEL_PTR(traverser);
+
+	DEL_PTR(bvh);
 }
 
@@ -846,4 +856,2 @@
 	}
 }
-
-#endif
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.cpp	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/BinaryLoader.cpp	(revision 2756)
@@ -2,5 +2,7 @@
 #include "Matrix4x4.h"
 #include "Geometry.h"
+#include "SceneEntity.h"
 #include "Material.h"
+#include "Texture.h"
 //#include "gzstream.h"
 
@@ -66,12 +68,12 @@
 
 
-//SceneEntity *BinaryLoader::LoadShape(igzstream &str)
-SceneEntity *BinaryLoader::LoadShape(ifstream &str)
+//SceneEntity *BinaryLoader::LoadSceneEntity(igzstream &str)
+SceneEntity *BinaryLoader::LoadSceneEntity(ifstream &str)
 {	
 	Geometry *geom = LoadGeometry(str);
 	Material *mat = LoadMaterial(str);
-
-	Matrix4x4 *m;
-	SceneEntity *sceneGeom = new SceneEntity(geom, m, mat);
+	Matrix4x4 *trafo = NULL;//IdentityMatrix();
+
+	SceneEntity *sceneGeom = new SceneEntity(geom, mat, trafo);
 
 	return sceneGeom;
@@ -82,6 +84,7 @@
 Material *BinaryLoader::LoadMaterial(ifstream &str)
 {
+	// default material
 	Material *mat = new Material();
-/*	
+	
 	// texture
 	int texnameSize;
@@ -91,15 +94,18 @@
 	if (texnameSize)
 	{
-		TextureAttributes *texAttr;
 		char *texname = new char[texnameSize];
-		str.read(texname, sizeof(char) * texnameSize);
-
-		Texture *tex = get_texture(texname, texAttr);
-		app->setTexture(tex);
-		app->setTextureAttributes(texAttr);
-	}
+		str.read(texname, sizeof(char) *texnameSize);
+
+
+		cout << "loading texture " << texname << " with len " << texnameSize << endl;
+		Texture *tex = new Texture(texname);
+		
+		mat->SetTexture(tex);
+	}
+	else
+		cout << "no texture " << texnameSize << endl;
 
 	// material
-	char hasMaterial;
+	/*char hasMaterial;
 	str.read(&hasMaterial, sizeof(char));
 	
@@ -137,129 +143,50 @@
 Geometry *BinaryLoader::LoadGeometry(ifstream &str)
 {
-/*
+	Vector3 *vertices;
+	Vector3 *normals;
+	float *texcoords;
+
+
+	//////////////
+	//-- read in vertices
+
 	int vertexCount;
-	int stripCount;
-
-	Point3f *vertices;
-	Vector3f *normals = NULL;
-	Point2f *texCoords = NULL;
-
-	int *stripIndexCounts;
-	int *indices;
-	int *normalIndices;
-
-	// todo
-	int colorCount = 0;
-	int normalCount = 0;
-	int texCount = 0;
-
-	int format;
-
-	// read in format
-	str.read(reinterpret_cast<char *>(&format), sizeof(int));
-	
-	format = IndexedTriangleStripArray::COORDINATES 
-		| IndexedTriangleStripArray::NORMALS
-		;
-
-	//OUT1("new format: " << format);
-
+	str.read(reinterpret_cast<char *>(&vertexCount), sizeof(int));
+	
 	// end of file reached
 	if (str.eof())
 		return NULL;
 
-
-	//////////////
-	// read in vertices
-	
-	str.read(reinterpret_cast<char *>(&vertexCount), sizeof(int));
-	
-	vertices = new Point3f[vertexCount];
-    str.read(reinterpret_cast<char *>(vertices), sizeof(Point3f) * vertexCount);
-
-
-	/////////////////
-	// read in strip counters
-	
-	str.read(reinterpret_cast<char *>(&stripCount), sizeof(int));
-
-	stripIndexCounts = new int[stripCount];
-    str.read(reinterpret_cast<char *>(stripIndexCounts), sizeof(int) * stripCount);
-
-
-	//////////
-	// read in indices
-
-	int indexCount;
-	str.read(reinterpret_cast<char *>(&indexCount), sizeof(int));
-	indices = new int[indexCount];
-    str.read(reinterpret_cast<char *>(indices), sizeof(int) * indexCount);
-
-
-	///////////////
-	// read in normals
-	
-	str.read(reinterpret_cast<char *>(&normalCount), sizeof(int));
-
-	if (normalCount)
-	{
-		normals = new Vector3f[normalCount];
-		str.read(reinterpret_cast<char *>(normals), sizeof(Vector3f) * normalCount);
-		normalIndices = new int[indexCount];
-		str.read(reinterpret_cast<char *>(normalIndices), sizeof(int) * indexCount);
-	}
-
-
-	//////////////
-	// read in texCoords
-	
-	str.read(reinterpret_cast<char *>(&texCount), sizeof(int));
-	if (texCount)
-	{
-		texCoords = new Point2f[texCount];
-		str.read(reinterpret_cast<char *>(texCoords), sizeof(Point2f) * texCount);
-	}
-	
-	IndexedTriangleStripArray *geom = 
-		new IndexedTriangleStripArray(vertexCount, 
-									  normalCount, 
-									  texCount, 
-									  colorCount, 
-									  format, 
-									  indexCount, 
-									  stripIndexCounts, 
-									  stripCount);
-
-	geom->setCoordinates(0, vertices, vertexCount);
-	geom->setCoordinateIndices(0, indices, indexCount);
-
-
-	if (texCount)
-	{
-		geom->setTextureCoordinateIndices(0, indices, indexCount);
-		geom->setTextureCoordinates(0, texCoords, texCount);
-	}
-
-	if (normalCount)
-	{
-		geom->setNormals(0, normals, normalCount);
-		geom->setNormalIndices(0, normalIndices, indexCount);
-	}
-	
-
-	///////
-	//-- cleanup
-
-	DELAPTR(stripIndexCounts);
-	DELAPTR(vertices);
-	DELAPTR(normals); 
-	DELAPTR(texCoords);
-	DELAPTR(indices);
-	DELAPTR(normalIndices);
-
-	
-	return geom; 
-	*/
-return 0;
+	cout << "vertexcount: " << vertexCount << endl;
+
+	vertices = new Vector3[vertexCount];
+    str.read(reinterpret_cast<char *>(vertices), sizeof(Vector3) * vertexCount);
+	
+	normals = new Vector3[vertexCount];
+	str.read(reinterpret_cast<char *>(normals), sizeof(Vector3) * vertexCount);
+
+	int texCoordCount;
+	str.read(reinterpret_cast<char *>(&texCoordCount), sizeof(int));
+
+	if (texCoordCount)
+	{
+		cout << "loading texcoords of size " << texCoordCount << endl;
+		texcoords = new float[texCoordCount * 2];
+		str.read(reinterpret_cast<char *>(texcoords), sizeof(float) * vertexCount * 2);
+	}
+	else
+		texcoords = NULL;
+
+	for (int i = 0; i < vertexCount; i += 3)
+	{
+		Triangle3 tri(vertices[i], vertices[i + 1], vertices[i + 2]);
+		Vector3 n = tri.GetNormal();
+
+		normals[i + 0] = n;
+		normals[i + 1] = n;
+		normals[i + 2] = n;
+	}
+
+	return new Geometry(vertices, normals, texcoords, vertexCount);
 }
 
@@ -267,68 +194,36 @@
 bool BinaryLoader::Load(const std::string &filename, SceneEntityContainer &geometry)
 {
-#if 0
-	clear_textures(); // clear the texture table
-
-	BranchGroup *root = new BranchGroup();
-	//root->setName("start");
-	igzstream str(filename.c_str());//, ios::binary);
-	
-	if (!str.is_open())
+	//clear_textures(); // clear the texture table
+
+	//igzstream str(filename.c_str());//, ios::binary);
+	ifstream istr(filename.c_str(), ios::binary);
+	
+	if (!istr.is_open())
 		return false;
 
 	// #shapes
 	int shapeCount;
-	str.read(reinterpret_cast<char *>(&shapeCount), sizeof(int));
+	istr.read(reinterpret_cast<char *>(&shapeCount), sizeof(int));
 
 	int progress = 0;
 
-	GeometryProcessor geomConv(500000, NULL);
-
 	for (int i = 0; i < shapeCount; ++ i)
 	{
-		Shape3D *shape = LoadShape(str);
-
-		vector<Shape3D *> newShapes;
-		ShapePair shapePair = ShapePair(shape, -1);
-
-		// check, if this node actually contains any geometry
-		CalcNumTrianglesVisitor	triangleVisitor;
-		triangleVisitor.Apply(shape);
-		const int numTriangles = triangleVisitor.GetNumTriangles();
-
-		// the shape should be subdivided => replace old shape
-		if (geomConv.SubdivideShape(newShapes, shapePair, numTriangles))
-		{
-			OUT1("triangleCount: " << numTriangles  << " => subdividing to " << newShapes.size() << " shapes");			
-			delete shape;//shape->unref();
-		}
-		else
-		{
-			newShapes.push_back(shape);
-		}
-
-		VisibilityGroup * visGrp = new VisibilityGroup();
-		root->addChild(visGrp);
-
-		for (size_t j = 0; j < newShapes.size(); ++ j)
-		{
-			Shape3D *sh = newShapes[j];
-			visGrp->addChild(sh);
-		}
-
-		int p = i * 100 / shapeCount;
+		SceneEntity *ent = LoadSceneEntity(istr);
+		geometry.push_back(ent);
+		
+		int p = (i + 1) * 100 / shapeCount;
 		
 		if (p >= progress)
 		{
-			OUT1("% loaded: " << p);
+			cout << "% loaded: " << p << endl;
 			progress += 10;
 		}
 	}
 
-	OUT1("bin loading finished");
-
-	return root;
-#endif
-}
-
-}
+	cout << "bin loading finished" << endl;
+
+	return true;
+}
+
+}
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.h	(revision 2756)
@@ -4,5 +4,8 @@
 #define __BVH_H
 
-#include "Geometry.h"
+#include "common.h"
+#include "Vector3.h"
+#include "AxisAlignedBox3.h"
+//#include "SceneEntity.h"
 
 
@@ -436,10 +439,13 @@
 public:
 
+	/** Destructor.
+	*/
+	~Bvh();
 	/** Returns number of bvh nodes.
 	*/
-	inline int GetNumNodes() const {return mNumNodes;}
+	inline int GetNumNodes() const { return mNumNodes; }
 	/** Returns number of bvh leaves.
 	*/
-	inline int GetNumLeaves() const {return mNumNodes / 2 + 1;}
+	inline int GetNumLeaves() const { return mNumNodes / 2 + 1;}
 	/** Returns root node of the bvh.
 	*/
@@ -505,7 +511,10 @@
 	*/
 	int CountTriangles(BvhNode *node) const;
-	/** Returns area of the geometry contained in the node.
-	*/
-	float GetGeometryArea(BvhNode *node) const;
+	/** Returns area of the the node.
+	*/
+	float GetArea(BvhNode *node) const;
+	/** Compute unique ids for the nodes.
+	*/
+	void ComputeIds();
 
 
@@ -534,8 +543,5 @@
 	*/
 	Bvh();
-	/** Destructor.
-	*/
-	~Bvh();
-
+	
 
 	/////////////
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.cpp
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.cpp	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/Camera.cpp	(revision 2756)
@@ -29,7 +29,7 @@
 	mDirection.Normalize();
 
-	Vector3 side = CrossProd(Vector3(0,1,0), mDirection);
-	mUp = Normalize(CrossProd(side, mDirection));
-	mRight = Normalize(CrossProd(mDirection, mUp));
+	Vector3 side = CrossProd(Vector3(0, 1, 0), mDirection);
+	mUp = -Normalize(CrossProd(side, mDirection));
+	mRight = -Normalize(CrossProd(mDirection, mUp));
 
 	float k = tan(mFovy/2);
@@ -55,6 +55,7 @@
 void Camera::LookInBox(const AxisAlignedBox3 &box)
 {
-	mDirection = Vector3(0,0,1);
+	mDirection = Vector3(0, 0, 1);
 	mPosition = box.Center();
+	mPosition.y += 50;
 
 	Precompute();
@@ -64,6 +65,6 @@
 void Camera::LookAtBox(const AxisAlignedBox3 &box)
 {
-	mDirection = box.Max() - box.Min();
-	mPosition = box.Min() - mDirection;
+	mDirection = box.Min() - box.Max();
+	mPosition = box.Max() - mDirection;
 
 	Precompute();
@@ -152,4 +153,15 @@
 
 
+void Camera::SetupCameraView()
+{
+	glLoadIdentity();
+	gluLookAt(mPosition.x, mPosition.y, mPosition.z,
+         	  mPosition.x + mDirection.x, mPosition.y + mDirection.y, mPosition.z + mDirection.z, 
+			  mUp.x, mUp.y, mUp.z);
+
+	//std::cout << "dir: " << mDirection << " pos: " << mPosition << " up: " << mUp << std::endl;
 }
 
+
+}
+
Index: GTP/trunk/App/Demos/Vis/CHC_revisited/common.h
===================================================================
--- GTP/trunk/App/Demos/Vis/CHC_revisited/common.h	(revision 2755)
+++ GTP/trunk/App/Demos/Vis/CHC_revisited/common.h	(revision 2756)
@@ -285,8 +285,7 @@
 
 Real Random(Real max);
-int  Random(int max);
+int Random(int max);
 void Randomize();
-void
-Randomize(const unsigned int seed);
+void Randomize(unsigned int seed);
 
 
@@ -473,13 +472,15 @@
 typedef std::queue<OcclusionQuery *> QueryQueue;
 
-}
-
-#endif
-
-
-
-
-
-
-
-
+static std::ofstream Debug("debug.log");
+
+}
+
+#endif
+
+
+
+
+
+
+
+
