Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 1415)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 1418)
@@ -238,7 +238,8 @@
 		ApplyTransformations(mTransformations, &tempMesh);
 
-		FaceContainer::const_iterator fit, fit_end = tempMesh.mFaces.end();
-
-		for (fit = tempMesh.mFaces.begin(); fit != fit_end; ++ fit)
+		FaceContainer::const_iterator fit, fit_begin = tempMesh.mFaces.begin(), 
+			fit_end = tempMesh.mFaces.end();
+		
+		for (fit = fit_begin; fit != fit_end; ++ fit)
 		{
 			//cout << "f";
@@ -253,5 +254,4 @@
 			for (tit = triangles.begin(); tit != tit_end; ++ tit)
 			{
-				//cout << "triangle: " << *tit << endl;
 				TriangleIntersectable *ti = new TriangleIntersectable(*tit);
 				mCurrentNode->mGeometry.push_back(ti);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 1302)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 1418)
@@ -1281,7 +1281,4 @@
 		if (madeContrib)
 			++ contributingSamples;
-		
-		// note: vss rays are never deleted
-		if (0) leaf->mVssRays.push_back(new VssRay(*ray));
 	}
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 1418)
@@ -1274,4 +1274,5 @@
 					"view_cells_evaluation_stats_prefix=",
 					"viewCells");
+
 	RegisterOption("ViewCells.Evaluation.histogram",
 					optBool,
@@ -1490,7 +1491,7 @@
 
 	
-	/************************************************************************************/
-	/*                         Render simulation related options                        */
-	/************************************************************************************/
+	/****************************************************************************/
+	/*                     Render simulation related options                    */
+	/****************************************************************************/
 
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h	(revision 1418)
@@ -154,5 +154,6 @@
 	  const BvHierarchy &bvHierarchy, 
 	  const int maxPvs, 
-	  const AxisAlignedBox3 *box = NULL);
+	  const AxisAlignedBox3 *box = NULL,
+	  const bool exportBoundingBoxes = true);
 
   virtual void ExportMeshInstance(MeshInstance *mi);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp	(revision 1291)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp	(revision 1418)
@@ -130,4 +130,14 @@
 {
 	DEL_PTR(mPvs);
+
+	VssRayContainer::const_iterator vit, vit_end = mVssRays.end();
+	for (vit = mVssRays.begin(); vit != vit_end; ++ vit)
+	{
+		VssRay *ray = *vit;
+		ray->Unref();
+
+		if (!ray->IsActive())
+			delete ray;
+	}
 }
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1418)
@@ -788,17 +788,11 @@
 
 
-bool Preprocessor::InitRayCast(const string externKdTree)
-{
-	bool loadKdTree, exportKdTree;
-
+bool Preprocessor::InitRayCast(const string externKdTree, const string internkdtree)
+{
+	bool loadKdTree;
 	Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
-	Environment::GetSingleton()->GetBoolValue("Preprocessor.exportKdTree", exportKdTree);
-
-	char kdtreename[100];
-	Environment::GetSingleton()->GetStringValue("Preprocessor.kdTreeFilename", kdtreename);
-
 	
 	if (!loadKdTree)
-	{	//////
+	{	
 		//-- build new kd tree from scene geometry
 		BuildKdTree();
@@ -808,10 +802,12 @@
 	{
 		const long startTime = GetTime();
-		cout << "loading kd tree file " << kdtreename << " ... ";
-
-		if (!LoadKdTree(kdtreename))
+		cout << "loading kd tree file " << internkdtree << " ... ";
+
+		if (!LoadKdTree(internkdtree))
 		{
-			cout << "error loading kd tree with filename " << kdtreename << endl;
-			return false;
+			cout << "error loading kd tree with filename " << internkdtree << ", rebuilding it instead ..." << endl;
+
+			BuildKdTree();
+			KdTreeStatistics(cout);
 		}
 
@@ -827,18 +823,4 @@
 				delete exporter;
 			}
-		}
-	}
-
-	if (exportKdTree)
-	{
-		const long startTime = GetTime();
-		cout << "exporting kd tree ... ";
-		if (!ExportKdTree(kdtreename))
-		{
-			cout << " error exporting kd tree with filename " << kdtreename << endl;
-		}
-		else
-		{
-			cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
 		}
 	}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 1418)
@@ -206,6 +206,11 @@
 		Exporter *exporter, 
 		const ObjectContainer &objects,
-		const AxisAlignedBox3 *bbox) const;
-
+		const AxisAlignedBox3 *bbox,
+		const bool exportBounds = true) const;
+
+
+	Intersectable *GetIntersectable(
+		const VssRay &ray, 
+		const bool isTermination) const;
 
 protected:
@@ -254,17 +259,4 @@
 	void ExportOspTree(Exporter *exporter, const ObjectContainer &objects) const;
 
-	void ExportBvHierarchy(
-		Exporter *exporter, 
-		const ObjectContainer &objects, 
-		const AxisAlignedBox3 *box) const;
-
-	void PrepareBvHierarchy(
-		const VssRayContainer &sampleRays,
-		const ObjectContainer &objects);
-
-	void PrepareOspTree(
-		const VssRayContainer &sampleRays,
-		const ObjectContainer &objects);
-
 	void ParseEnvironment();
 
@@ -272,4 +264,12 @@
 	bool StartViewSpaceSubdivision() const;
 
+	void PrepareBvHierarchy(
+		const VssRayContainer &sampleRays,
+		const ObjectContainer &objects);
+
+	void PrepareOspTree(
+		const VssRayContainer &sampleRays,
+		const ObjectContainer &objects);
+
 	void PrepareViewSpaceSubdivision(
 		const VssRayContainer &sampleRays,
@@ -281,5 +281,5 @@
     void ResetQueue();
 
-	void FinishObjectSpaceSubdivision() const;
+	void FinishObjectSpaceSubdivision(const ObjectContainer &objects) const;
 
 	int GetObjectSpaceSubdivisionDepth() const;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VssPreprocessor.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VssPreprocessor.cpp	(revision 1414)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VssPreprocessor.cpp	(revision 1418)
@@ -331,5 +331,4 @@
 
 		bool exportViewCells = false;
-		
 		if (exportViewCells)
 		{
@@ -477,5 +476,5 @@
 	  mViewCellsManager->PrintStatistics(Debug);
   }
-#if 1 
+#if 0
   else 
   {	 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 1415)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 1418)
@@ -168,5 +168,5 @@
   GlRendererBuffer *GetRenderer() { return renderer;}
 
-  bool InitRayCast(const string externKdTree);
+  bool InitRayCast(const string externKdTree, const string internKdTree);
 
   int CastRay(
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp	(revision 1404)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp	(revision 1418)
@@ -66,4 +66,6 @@
 	mVertices.push_back(tri.mVertices[1]);
 	mVertices.push_back(tri.mVertices[2]);
+
+	//cout << "poly n: " << GetNormal() << " t normal: " << tri.GetNormal() << endl;
 }
 
@@ -539,5 +541,8 @@
 	while (i < k)
 	{
-		triangles.push_back(Triangle3(mVertices[i], mVertices[j], mVertices[k]));
+		if (0) // matt: I don't know why i made it like this because the normals are wrong!! 
+			triangles.push_back(Triangle3(mVertices[i], mVertices[j], mVertices[k]));
+		else
+			triangles.push_back(Triangle3(mVertices[k], mVertices[j], mVertices[i]));
 
 		if ((count ++) % 2)
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1418)
@@ -181,6 +181,5 @@
 
 
-
-	Debug << "************ View Cells options ***************" << endl;
+	Debug << "************ View Cells Manager options ***************" << endl;
 	Debug << "color code: " << mColorCode << endl;
 
@@ -211,5 +210,4 @@
 	Debug << "export bounding boxes: " << mExportBboxesForPvs << endl;
 	Debug << "export pvs for view cells: " << mExportPvs << endl;
-	
 	Debug << endl;
 }
@@ -511,5 +509,5 @@
 
 
-AxisAlignedPlane * ViewCellsManager::GetClipPlane()
+AxisAlignedPlane *ViewCellsManager::GetClipPlane()
 {
 	return mUseClipPlaneForViz ? &mClipPlaneForViz : NULL;
@@ -1696,11 +1694,24 @@
 	int axis = 0;
 	float pos;
+	bool orientation;
+	Vector3 absPos;
 
 	Environment::GetSingleton()->GetFloatValue("ViewCells.Visualization.clipPlanePos", pos);
-	Vector3 absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
-	
 	Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.clipPlaneAxis", axis);
 
+	if (axis < 0) 
+	{
+		axis = -axis;
+		orientation = false;
+		absPos = mViewSpaceBox.Max() -  mViewSpaceBox.Size() * pos;
+	}
+	else
+	{
+		orientation = true;
+		absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
+	}
+
 	mClipPlaneForViz = AxisAlignedPlane(axis, absPos[axis]);
+	mClipPlaneForViz.mOrientation = orientation;
 }
 
@@ -2658,5 +2669,5 @@
 
 	
-	/////////////////////////////////////////
+	////////////////////////
 	//-- visualization and statistics
 
@@ -2729,6 +2740,6 @@
 	if (1) FinalizeViewCells(true);
 
-	// write view cells to disc
-	if (mExportViewCells)
+	// write view cells to disc (this moved to preprocessor)
+	if (0 && mExportViewCells)
 	{
 		char filename[100];
@@ -2843,6 +2854,5 @@
 
 	// sort view cells in order to find the largest view cells
-	if (0)
-		stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
+	if (0) stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
 
 	int limit = min(leafOut, (int)mViewCells.size());
@@ -3840,5 +3850,4 @@
 	}
 
-
 	// view cells already finished before post processing step 
 	// (i.e. because they were loaded)
@@ -3885,5 +3894,5 @@
 	if (0) FinalizeViewCells(false);
 		
-	//////////////////////////////////////
+	//////////////////
 	//-- merge the individual view cells
 	MergeViewCells(postProcessRays, objects);
@@ -3893,5 +3902,5 @@
 	if (0) RefineViewCells(postProcessRays, objects);
 
-	///////////////////////////////////////////
+	//////////////////
 	//-- render simulation after merge + refine
 
@@ -3904,5 +3913,5 @@
 	
 
-	///////////////////
+	////////////
 	//-- compression
 
@@ -3927,8 +3936,8 @@
 	// compute final meshes and volume / area
 	if (1) FinalizeViewCells(true);
-
+cout << "here09*******************" << endl;
 	// write view cells to disc
-	if (mExportViewCells)
-	{
+	if (0 && mExportViewCells)
+	{cout << "here77*******************" << endl;
 		char filename[100];
 		Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
@@ -4832,8 +4841,6 @@
 	}
 
-
-	// take this step only if 
-	// view cells already constructed before post processing step 
-	// (e.g., because they were loaded)
+	// if view cells were already constructed before post processing step 
+	// (e.g., because they were loaded), we are finished
 	if (mViewCellsFinished)
 	{
@@ -4881,5 +4888,6 @@
 	mViewCellsTree->SetRoot(root);
 
-	////////////////////////////////////
+
+	//////////////////////////
 	//-- update pvs in the whole hierarchy
 	ObjectPvs pvs;
@@ -4887,5 +4895,5 @@
 
 
-	///////////////////////////////////////////
+	//////////////////////
 	//-- render simulation after merge + refine
 
@@ -4896,5 +4904,5 @@
 	cout << ss << endl;
 	
-	///////////////////////
+	///////////////
 	//-- compression
 
@@ -4910,12 +4918,12 @@
 	}
 
-	/////////////////////////////////////
+	///////////////
 	//-- compute final meshes and volume / area
 	if (1) FinalizeViewCells(true);
 
-
-	// write out view cells
-	if (mExportViewCells)
-	{
+	// write out view cells (this moved to preprocessor)
+	if (0 && mExportViewCells)
+	{
+		cout << "here5" << endl;
 		char filename[100];
 		Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
@@ -5005,12 +5013,13 @@
 {
 	ViewCellContainer leaves;
-
 	mViewCellsTree->CollectLeaves(vc, leaves);
 	ViewCellContainer::const_iterator it, it_end = leaves.end();
 
 	Plane3 plane;
-
 	if (clipPlane)
+	{
+		// arbitrary plane definition
 		plane = clipPlane->GetPlane();
+	}
 
 	for (it = leaves.begin(); it != it_end; ++ it)
@@ -5022,5 +5031,5 @@
 			mHierarchyManager->GetVspTree()->GetBoundingBox(vspVc->mLeaf);
 		
-		if (!Overlap(*sceneBox, box))
+		if (sceneBox && !Overlap(*sceneBox, box))
 			continue;
 
@@ -5033,7 +5042,7 @@
 			else if (box.Side(plane) == 0)
 			{
+				// intersection
 				AxisAlignedBox3 fbox, bbox;
-				bbox.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
-
+				box.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
 				exporter->ExportBox(bbox);
 			}
@@ -5083,9 +5092,14 @@
 			cout << "exporting final view cells (after initial construction + post process) ... ";
 
-			// matt: hack
+			// matt: hack for clamping scene
 			AxisAlignedBox3 bbox = mHierarchyManager->GetViewSpaceBox();
 			bbox.Scale(Vector3(0.5, 1, 0.5));
-
-			if (mExportGeometry)
+			
+			exporter->SetWireframe(); 
+			exporter->ExportBox(bbox);
+			exporter->SetFilled(); 
+
+				
+			if (0 && mExportGeometry)
 			{
 				exporter->ExportGeometry(objects, true, &bbox);
@@ -5097,7 +5111,7 @@
 				exporter->ExportRays(visRays, RgbColor(0, 1, 0));
 			}
-
+		
+			mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects, &bbox, false);
 			ExportViewCellsForViz(exporter, &bbox, GetClipPlane());
-		
 			delete exporter;
 			cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
@@ -5145,9 +5159,8 @@
 	Debug << "\nOutput view cells: " << endl;
 
-	const bool sortViewCells = true;
-
-	if (sortViewCells)
-	{
-		//stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
+	const bool sortedViewCells = false;
+
+	if (sortedViewCells)
+	{
 		// sort view cells to visualize the view cells with highest render cost
 		stable_sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
@@ -5157,5 +5170,5 @@
 	int raysOut = 0;
 
-	///////////////////////////
+	///////////////
 	//-- some rays for output
 	
@@ -5163,12 +5176,9 @@
 	{
 		cout << "creating output for view cell " << i << " ... ";
-
-		ViewCell *vc;
-	
-		if (sortViewCells) // largest view cell pvs first
-			vc = mViewCells[i];
-		else // random view cell
-			vc = mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
-
+		
+		// largest view cell pvs first of random view cell
+		ViewCell *vc = sortedViewCells ? 
+			mViewCells[i] : mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
+		
 		ObjectPvs pvs;
 		mViewCellsTree->GetPvs(vc, pvs);
@@ -5179,5 +5189,7 @@
 		Debug << i << ": pvs size=" << (int)mViewCellsTree->GetPvsSize(vc) << endl;
 
+		////////////
 		//-- export the sample rays
+
 		if (1 || mExportRays)
 		{
@@ -5199,5 +5211,4 @@
 				{
 					VspLeaf *vcLeaf = dynamic_cast<VspViewCell *>(*vit)->mLeaf;
-				
 					VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
 
@@ -5212,38 +5223,30 @@
 				for (rit = collectRays.begin(); rit != rit_end; ++ rit)
 				{
-					float p = RandomValue(0.0f, (float)collectRays.size());
+					const float p = RandomValue(0.0f, (float)collectRays.size());
 			
 					if (p < raysOut)
 						vcRays.push_back(*rit);
 				}
-
+				
 				//-- export rays piercing this view cell
 				exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
+
+				//-- export objects seen from the rays
+				Intersectable::NewMail();
+                VssRayContainer::const_iterator vcit, vcit_end = vcRays.end();
+				for (vcit = vcRays.begin(); vcit != vcit_end; ++ vcit)
+				{
+					VssRay *ray = *vcit;
+					//Intersectable *obj = ray->mTerminationObject;
+					Intersectable *obj = mHierarchyManager->GetIntersectable(*ray, true);
+					
+					if (obj && !obj->Mailed())
+					{
+						obj->Mail();
+					//	exporter->ExportIntersectable(obj);
+					}
+				}
 			}
-		
-			// associate new rays with output view cell
-			if (0)
-			{
-				VssRayContainer vcRays;
-				raysOut = min((int)rays.size(), mVisualizationSamples);
-
-				// check whether we can add the current ray to the output rays
-				for (int k = 0; k < raysOut; ++ k)
-				{
-					VssRay *ray = rays[k];
-					for	(int j = 0; j < (int)ray->mViewCells.size(); ++ j)
-					{
-						ViewCell *rayvc = ray->mViewCells[j];
-	
-						if (rayvc == vc)
-							vcRays.push_back(ray);
-					}
-				}	
-				
-				// export rays piercing this view cell
-				exporter->ExportRays(vcRays, RgbColor(1, 1, 0));
-			}
-		}
-
+		}
 
 		/////////////////
@@ -5259,45 +5262,4 @@
 		exporter->SetFilled();
 
-#if 0	
-		//////////
-		//-- export pvs
-
-		Intersectable::NewMail();
-		KdLeaf::NewMail();
-
-		vector<KdLeaf *> kdLeaves;
-
-		ObjectPvsMap::const_iterator oit, oit_end = pvs.mEntries.end();
-
-		for (oit = pvs.mEntries.begin(); oit != oit_end; ++ oit)
-		{	
-			Intersectable *obj = (*oit).first;
-
-			if (obj->Type() == Intersectable::KD_INTERSECTABLE)
-			{
-				m.mDiffuseColor = RgbColor(1, 1, 1);
-				exporter->SetForcedMaterial(m);
-
-				// export bounding box of node
-				KdIntersectable *kdObj  = dynamic_cast<KdIntersectable *>(obj);
-				AxisAlignedBox3 box = mOspTree->GetBoundingBox(kdObj->GetItem());
-
-				exporter->SetWireframe();
-				exporter->ExportBox(box);
-				exporter->SetFilled();
-			}
-
-			m.mDiffuseColor = RgbColor(1, 0, 0);
-			exporter->SetForcedMaterial(m);
-
-			// export pvs entry
-			if (!obj->Mailed())
-			{
-				exporter->ExportIntersectable(obj);
-				obj->Mail();
-			}
-		}		
-#endif
-	
 		DEL_PTR(exporter);
 		cout << "finished" << endl;
@@ -5398,8 +5360,6 @@
 	if (!ViewCellsConstructed())
 		return NULL;
-
 	if (!mViewSpaceBox.IsInside(point))
-	  return NULL;
-
+		return NULL;
 	return mHierarchyManager->GetVspTree()->GetViewCell(point, active);
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 1418)
@@ -106,5 +106,6 @@
 bool Exporter::ExportBvHierarchy(const BvHierarchy &bvHierarchy, 
 								 const int maxPvs,
-								 const AxisAlignedBox3 *box)
+								 const AxisAlignedBox3 *box,
+								 const bool exportBoundingBoxes)
 {
 	vector<BvhLeaf *> leaves;
@@ -122,16 +123,17 @@
 	{
 		BvhLeaf *leaf = *it;
-		if (leaf->mObjects.empty())
+
+		if (leaf->mObjects.empty() || 
+			(box && !Overlap(*box, leaf->GetBoundingBox())))
 			continue;
 
-		if (box && !Overlap(*box, leaf->GetBoundingBox()))
-			continue;
-
-		SetWireframe();
-		SetForcedMaterial(white);
-		ExportBox(leaf->GetBoundingBox());
-		SetFilled();
-
-		if (maxPvs) // color code pvs
+		if (exportBoundingBoxes)
+		{
+			SetWireframe();
+			SetForcedMaterial(white);
+			ExportBox(leaf->GetBoundingBox());
+		}
+
+        if (maxPvs) // color code pvs
 		{
 			mForcedMaterial.mDiffuseColor.b = 1.0f;
@@ -146,10 +148,9 @@
 		}
 
-		if (1) 
-		{
-			SetFilled();
-			ExportGeometry(leaf->mObjects, true);
-		}
-	}
+		SetFilled();
+		ExportGeometry(leaf->mObjects, true);
+	}
+
+	SetFilled();
 
 	return true;
@@ -176,14 +177,15 @@
 		{
 			const Triangle3 triangle = dynamic_cast<TriangleIntersectable *>(object)->GetItem();
-
-			VertexContainer vertices;
-			vertices.push_back(triangle.mVertices[0]);
-			vertices.push_back(triangle.mVertices[1]);
-			vertices.push_back(triangle.mVertices[2]);
-
-			Polygon3 poly(vertices);
+			Polygon3 poly(triangle);
 			ExportPolygon(&poly);
 			break;
 		}
+	case Intersectable::BVH_INTERSECTABLE:
+		{
+			BvhNode *node = dynamic_cast<BvhIntersectable *>(object)->GetItem();
+			if (node->IsLeaf())
+				ExportGeometry(dynamic_cast<BvhLeaf *>(node)->mObjects, true);
+			break;
+		}
 	default:
 		cerr << "Sorry the export for object type " << Intersectable::GetTypeName(object) << " is not available yet" << endl;
@@ -191,4 +193,5 @@
 	}
 }
+
 
 void Exporter::ExportMeshInstance(MeshInstance *object)
@@ -234,5 +237,5 @@
 		for (oit = objects.begin(); oit != oit_end; ++ oit)
 		{
-			if (bbox && Overlap(*bbox, (*oit)->GetBox()))
+			if (!bbox || Overlap(*bbox, (*oit)->GetBox()))
 			{
 				if (0) SetForcedMaterial(RandomMaterial());
@@ -240,12 +243,11 @@
 			}
 		}
-
 		return;
 	}
-
 	
-	///////////////////////////////////////////
+
+	///////////////////////
 	//-- all objects exported as one mesh
-	//-- hack: currently works only for triangles
+	//-- warning: currently works only for triangles
 
 	PolygonContainer polys;
@@ -255,6 +257,9 @@
 		Intersectable *obj = *oit;
 
-		if (bbox && !Overlap(*bbox, (*oit)->GetBox()))
+		if (bbox && !Overlap(*bbox, obj->GetBox()))
+		{
+			//cout << *bbox << " " << obj->GetBox() << endl;
 			continue;
+		}
 
 		switch (obj->Type())
@@ -266,4 +271,11 @@
                 break;
 			}
+		case Intersectable::MESH_INSTANCE:
+			{
+				MeshInstance *mi = dynamic_cast<MeshInstance *>(obj);
+				ExportMesh(mi->GetMesh());
+				//polys.push_back(new Polygon3(ti->GetItem()));
+                break;
+			}
 		default:
 			cout << "merging of object type " << obj->Type() << " not implemented yet" << endl;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 1344)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 1418)
@@ -187,5 +187,5 @@
 					  );
   
-  Plane3 GetFacePlane(const int faceIndex);
+  Plane3 GetFacePlane(const int faceIndex) const;
 
   AxisAlignedBox3 GetFaceBox(const int faceIndex);
@@ -207,4 +207,7 @@
   }
 
+
+  Vector3 GetNormal(const int idx) const;
+
   virtual ostream &Describe(ostream &s) {
 	return s<<"Mesh #vertices="<<(int)mVertices.size()<<" #faces="<<(int)mFaces.size();
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.h	(revision 1076)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.h	(revision 1418)
@@ -77,10 +77,10 @@
 	AxisAlignedPlane(){}
 	AxisAlignedPlane(const int axis, const float position):
-	  mAxis(axis), mPosition(position)
+	  mAxis(axis), mPosition(position), mOrientation(false)
 	  {
 	  }
 	Plane3 GetPlane() const
 	{
-		Vector3 normal(0,0,0); normal[mAxis] = 1;
+		Vector3 normal(0,0,0); normal[mAxis] = mOrientation ? 1.0f : -1.0f;
 		Vector3 point(0,0,0); point[mAxis] = mPosition;
 
@@ -92,8 +92,13 @@
 	/// the absolute position of the split axis
 	float mPosition;
+	/// the plane orientation
+	bool mOrientation;
+
+	friend ostream &operator<<(ostream &s, const AxisAlignedPlane &p) 
+	{
+		s << "a: " << p.mAxis << " p: " << p.mPosition;
+		return s;
+	}
 };
-
-
 }
-
 #endif
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 1415)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 1418)
@@ -305,5 +305,15 @@
 {
 	DEL_PTR(mPvs);
-	CLEAR_CONTAINER(mVssRays);
+
+	VssRayContainer::const_iterator vit, vit_end = mVssRays.end();
+	for (vit = mVssRays.begin(); vit != vit_end; ++ vit)
+	{
+		VssRay *ray = *vit;
+		ray->Unref();
+
+		if (!ray->IsActive())
+			delete ray;
+	}
+	//CLEAR_CONTAINER(mVssRays);
 }
 
@@ -357,5 +367,5 @@
 mRoot(NULL),
 mOutOfBoundsCell(NULL),
-mStoreRays(false),
+mStoreRays(true),
 mTimeStamp(1),
 mHierarchyManager(NULL)
@@ -588,8 +598,8 @@
 	}
 
-
-	//-- store additional info
 	if (mStoreRays)
 	{
+		///////////
+		//-- store sampling rays
 		RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
 
@@ -684,4 +694,5 @@
 
 #if 0
+		/////////////
 		//-- store pvs optained from rays
 		AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp);
@@ -694,7 +705,8 @@
 		mVspStats.sampleContributions += (int)sampCon;
 #endif
-		//-- store additional info
 		if (mStoreRays)
 		{
+			//////////
+			//-- store rays piercing this view cell
 			RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
 			for (it = tData.mRays->begin(); it != it_end; ++ it)
@@ -702,4 +714,5 @@
 				(*it).mRay->Ref();			
 				leaf->mVssRays.push_back((*it).mRay);
+				//leaf->mVssRays.push_back(new VssRay(*(*it).mRay));
 			}
 		}
@@ -767,6 +780,6 @@
 	VspLeaf *leaf = dynamic_cast<VspLeaf *>(tData.mNode);
 	
-	////////////////////////////////////////////////////////
-	//-- the front and back traversal data are filled with the new values
+	///////////////
+	//-- new traversal values
 
 	frontData.mDepth = tData.mDepth + 1;
@@ -782,4 +795,5 @@
 			  *backData.mRays);
 
+	/////////////
 	//-- compute pvs
 	frontData.mPvs = EvalPvsSize(*frontData.mRays);
@@ -2741,5 +2755,6 @@
 			{
 				leaf->Mail();
-				if (leaf->GetSubdivisionCandidate()) // a candidate still attached to this node
+				 // a candidate still attached to this node
+				if (leaf->GetSubdivisionCandidate())
 				{
 					dirtyList.push_back(leaf->GetSubdivisionCandidate());
Index: GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1415)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1418)
@@ -163,8 +163,11 @@
 	}
 
-	string rayCastFile = ReplaceSuffix(filename, ".obj", ".kdf");
+
+	string externKdTree = ReplaceSuffix(filename, ".obj", ".kdf");
+	char internKdTree[100];
+	Environment::GetSingleton()->GetStringValue("Preprocessor.kdTreeFilename", internKdTree);
 
 	//-- initialize external ray casters
-	if (preprocessor->InitRayCast(rayCastFile))
+	if (preprocessor->InitRayCast(externKdTree, internKdTree))
 	{
 		cout << "ray casting initialized!" << endl;
@@ -175,4 +178,22 @@
 		Cleanup();
 		exit(1);
+	}
+
+	// export kd tree?
+	bool exportKdTree;
+	Environment::GetSingleton()->GetBoolValue("Preprocessor.exportKdTree", exportKdTree);
+	if (exportKdTree)
+	{
+		const long startTime = GetTime();
+		cout << "exporting kd tree ... ";
+
+		if (!preprocessor->ExportKdTree(internKdTree))
+		{
+			cout << " error exporting kd tree with filename " << internKdTree << endl;
+		}
+		else
+		{
+			cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
+		}
 	}
 
@@ -198,5 +219,4 @@
 #endif
 
-	
 	bool guiSupported = false;
 	if (preprocessor->mUseGlRenderer || preprocessor->mUseGlDebugger)
Index: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1416)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1418)
@@ -281,9 +281,11 @@
 	RunConstruction(sampleRays, objects, forcedViewSpace);
 	
-	cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
-
+	cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
+
+	cout << "here5 " << GetViewSpaceBox() << endl;
+	cout << "here6 " << GetObjectSpaceBox() << endl;
 	mHierarchyStats.Stop();
 	mVspTree->mVspStats.Stop();
-	FinishObjectSpaceSubdivision();
+	FinishObjectSpaceSubdivision(objects);
 
 	mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
@@ -762,5 +764,6 @@
 void HierarchyManager::ExportObjectSpaceHierarchy(Exporter *exporter,
 												  const ObjectContainer &objects,
-												  const AxisAlignedBox3 *bbox) const
+												  const AxisAlignedBox3 *bbox,
+												  const bool exportBounds) const
 {
 	switch (mObjectSpaceSubdivisionType)
@@ -773,5 +776,5 @@
 	case BV_BASED_OBJ_SUBDIV:
 		{
-			ExportBvHierarchy(exporter, objects, bbox);
+			exporter->ExportBvHierarchy(*mBvHierarchy, 0, bbox, exportBounds);
 			break;
 		}
@@ -779,13 +782,4 @@
 		break;
 	}
-}
-
-
-void HierarchyManager::ExportBvHierarchy(Exporter *exporter, 
-										 const ObjectContainer &objects,
-										 const AxisAlignedBox3 *bbox) const
-{
-	exporter->SetWireframe();
-	exporter->ExportBvHierarchy(*mBvHierarchy, 0, bbox);
 }
 
@@ -801,4 +795,34 @@
 
 
+Intersectable *HierarchyManager::GetIntersectable(const VssRay &ray, 
+												  const bool isTermination) const
+{
+
+	Intersectable *obj;
+	Vector3 pt;
+	KdNode *node;
+
+	ray.GetSampleData(isTermination, pt, &obj, &node);
+	
+	if (!obj) return NULL;
+
+	switch (mObjectSpaceSubdivisionType)
+	{
+	case HierarchyManager::KD_BASED_OBJ_SUBDIV:
+		{
+			KdLeaf *leaf = mOspTree->GetLeaf(pt, node);
+			return mOspTree->GetOrCreateKdIntersectable(leaf);
+		}
+	case HierarchyManager::BV_BASED_OBJ_SUBDIV:
+		{
+			BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
+			return mBvHierarchy->GetOrCreateBvhIntersectable(leaf);
+		}
+	default:
+		return obj;
+	}
+}
+
+
 void HierarchyStatistics::Print(ostream &app) const
 {
@@ -823,5 +847,15 @@
 
 
-void HierarchyManager::FinishObjectSpaceSubdivision() const
+static void RemoveRayRefs(const ObjectContainer &objects)
+{
+	ObjectContainer::const_iterator oit, oit_end = objects.end();
+	for (oit = objects.begin(); oit != oit_end; ++ oit)
+	{
+		(*oit)->mVssRays.clear();
+	}
+}
+
+
+void HierarchyManager::FinishObjectSpaceSubdivision(const ObjectContainer &objects) const
 {
 	switch (mObjectSpaceSubdivisionType)
@@ -835,4 +869,5 @@
 		{
 			mBvHierarchy->mBvhStats.Stop();
+			RemoveRayRefs(objects);
 			break;
 		}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp	(revision 1344)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp	(revision 1418)
@@ -476,5 +476,5 @@
 
 Plane3
-Mesh::GetFacePlane(const int faceIndex)
+Mesh::GetFacePlane(const int faceIndex) const
 {
   Face *face = mFaces[faceIndex];
@@ -521,4 +521,10 @@
 
 
+Vector3 Mesh::GetNormal(const int idx) const
+{
+	return GetFacePlane(idx).mNormal;
+}
+
+
 void
 Mesh::AddTriangle(const Triangle3 &triangle)
@@ -728,5 +734,5 @@
 Vector3 MeshInstance::GetNormal(const int idx) const
 {
-	return mMesh->GetFacePlane(idx).mNormal;
+	return mMesh->GetNormal(idx);
 }
 
