Index: /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.h	(revision 2575)
@@ -28,33 +28,33 @@
 {
 public:
-	/** Default constructor initialising e.g., KD tree
-	*/
-	InternalRayCaster(const Preprocessor &preprocessor);
-	virtual ~InternalRayCaster();
-
-	int Type() const { return INTERNAL_RAYCASTER; }
-
-	virtual int CastRay(
-						const SimpleRay &simpleRay,
-						VssRayContainer &vssRays,
-						const AxisAlignedBox3 &box,
-						const bool castDoubleRay,
-						const bool pruneInvalidRays = true
-						);
-
-	 virtual void CastRays16(SimpleRayContainer &rays, 
-							 VssRayContainer &vssRays,
-							 const AxisAlignedBox3 &sbox,
-							 const bool castDoubleRay,
-							 const bool pruneInvalidRays = true
-							 );
-
-	virtual int
-	CastGlobalRay(
-				  const SimpleRay &simpleRay,
-				  VssRayContainer &vssRays,
-				  const AxisAlignedBox3 &box,
-				  const bool pruneInvalidRays
-				  );
+  /** Default constructor initialising e.g., KD tree
+   */
+  InternalRayCaster(const Preprocessor &preprocessor);
+  virtual ~InternalRayCaster();
+  
+  int Type() const { return INTERNAL_RAYCASTER; }
+  
+  virtual int CastRay(
+		      const SimpleRay &simpleRay,
+		      VssRayContainer &vssRays,
+		      const AxisAlignedBox3 &box,
+		      const bool castDoubleRay,
+		      const bool pruneInvalidRays = true
+		      );
+  
+  virtual void CastRays16(SimpleRayContainer &rays, 
+			  VssRayContainer &vssRays,
+			  const AxisAlignedBox3 &sbox,
+			  const bool castDoubleRay,
+			  const bool pruneInvalidRays = true
+			  );
+  
+  virtual int
+  CastGlobalRay(
+		const SimpleRay &simpleRay,
+		VssRayContainer &vssRays,
+		const AxisAlignedBox3 &box,
+		const bool pruneInvalidRays
+		);
 
 protected:
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RenderTexture.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RenderTexture.cpp	(revision 1940)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RenderTexture.cpp	(revision 2575)
@@ -240,5 +240,5 @@
   {
     // [Redge]
-#if defined(_DEBUG) | defined(DEBUG)
+#if defined(_DEBUG) || defined(DEBUG)
     fprintf(stderr, "Warning: OpenGL extension GL_ARB_depth_texture not available.\n"
                     "         Using glReadPixels() to emulate behavior.\n");
@@ -250,5 +250,5 @@
   }
   SetLastError(0);
-#else
+#else // _WIN32
   if (!GLXEW_SGIX_pbuffer)
   {
@@ -270,5 +270,5 @@
     PrintExtensionError("Some GLX render texture extension");
   }
-#endif
+#endif // _WIN32
 
   if (_bInitialized)
@@ -292,5 +292,5 @@
 	  PrintExtensionError("NV_float_buffer or ATI_texture_float");
   }
-#else
+#else // _WIN32
   if (_bFloat && _bIsTexture && !GLXEW_NV_float_buffer)
   {
@@ -298,5 +298,5 @@
     return false;
   }
-#endif  
+#endif // _WIN32
   if (!_bFloat && !GLEW_NV_texture_rectangle)
   {
@@ -461,7 +461,9 @@
           }
         }
-#else if defined(DEBUG) || defined(_DEBUG)
+#else // _WIN32 
+#if defined(DEBUG) || defined(_DEBUG)
         printf("RenderTexture Error: Render-to-Texture not supported in Linux\n");
-#endif    
+#endif
+#endif // _WIN32 
       }
     }
@@ -850,5 +852,5 @@
   _iBits[5] = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; 
  
-#if defined(_DEBUG) | defined(DEBUG)
+#if defined(_DEBUG) || defined(DEBUG)
   fprintf(stderr, "Created a %dx%d RenderTexture with BPP(%d, %d, %d, %d)",
           _iWidth, _iHeight, _iBits[0], _iBits[1], _iBits[2], _iBits[3]);
@@ -857,5 +859,5 @@
   fprintf(stderr, "\n");
 #endif
-#else
+#else // _WIN32 
   _pDpy = glXGetCurrentDisplay();
   GLXContext context = glXGetCurrentContext();
@@ -936,5 +938,5 @@
   // XXX Query the color format
 
-#endif
+#endif // _WIN32 
   
   return true;
@@ -982,5 +984,5 @@
     return true;
   }
-#else
+#else // _WIN32 
   if ( _hPBuffer )
   {
@@ -992,5 +994,5 @@
     return true;
   }
-#endif
+#endif // _WIN32 
   return false;
 }
@@ -1080,5 +1082,5 @@
     return false;
   }
-#else
+#else // _WIN32 
   _hPreviousContext = glXGetCurrentContext();
   _hPreviousDrawable = glXGetCurrentDrawable();
@@ -1087,5 +1089,5 @@
     return false;
   }
-#endif
+#endif // _WIN32 
   
   return true;
@@ -1196,5 +1198,5 @@
     }
   }
-#else
+#else // _WIN32 
   assert(_bIsTexture);
   glBindTexture(_iTextureTarget, _iTextureID);
@@ -1208,5 +1210,5 @@
     }
   }
-#endif
+#endif // _WIN32 
   return true;
 }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.h	(revision 2575)
@@ -4,4 +4,5 @@
 #include "common.h"
 #include "PvsDefinitions.h"
+#include "Intersectable.h"
 
 //
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/run_test2
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/run_test2	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/run_test2	(revision 2575)
@@ -3,5 +3,5 @@
 
 #COMMAND="./release/preprocessor.exe -preprocessor_quit_on_finish+"
-COMMAND="../scripts/preprocessor.sh -preprocessor_quit_on_finish+ -preprocessor_use_gl_renderer- -preprocessor_evaluate_filter- -samples_per_evaluation=5000000 -samples_per_pass=500000 -total_samples=6000000"
+COMMAND="../scripts/preprocessor.sh -preprocessor_quit_on_finish+ -preprocessor_use_gl_renderer+ -preprocessor_evaluate_filter- -samples_per_evaluation=5000000 -samples_per_pass=500000 -total_samples=6000000"
 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.h	(revision 2575)
@@ -303,7 +303,7 @@
 	/** Sets parent node.
 	*/
-	inline void BspNode::SetParent(BspInterior *parent)
-	{
-		mParent = parent;
+	inline void SetParent(BspInterior *parent)
+	{
+	  mParent = parent;
 	}
 
@@ -375,5 +375,5 @@
 	/** Returns split plane.
 	*/
-	Plane3 BspInterior::GetPlane() const
+	Plane3 GetPlane() const
 	{
 		return mPlane;
@@ -441,5 +441,5 @@
 	/** @return true since it is an interior node 
 	*/
-	bool BspLeaf::IsLeaf() const 
+        bool IsLeaf() const 
 	{ 
 		return true; 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/OcclusionQuery.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/OcclusionQuery.cpp	(revision 2023)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/OcclusionQuery.cpp	(revision 2575)
@@ -1,6 +1,14 @@
 #include "OcclusionQuery.h"
 #include <iostream>
+
+
+#ifdef _WIN32
 #include <glInterface.h>
-
+#else
+#include <GL/gl.h>
+#include <GL/glu.h>
+//#include <GL/glxext.h>
+#include <SDL/SDL_opengl.h>
+#endif
 
 using namespace std;
@@ -17,9 +25,15 @@
 	if (sUseArbQueries)
 	{
-		glGenQueriesARB(1, &id);
+#ifdef _ARBGL
+	  // VH
+	  glGenQueriesARB(1, &id);
+#endif
 	}
 	else
 	{		
+#ifdef _ARBGL
+	  // VH
 		glGenOcclusionQueriesNV(1, &id);
+#endif
 	}
 }
@@ -34,9 +48,15 @@
 	if (sUseArbQueries)
 	{
+#ifdef _ARBGL
+	  // VH
 		glDeleteQueriesARB(1, &mId);
+#endif
 	}
 	else
 	{
+#ifdef _ARBGL
+	  // VH
 		glDeleteOcclusionQueriesNV(1, &mId);
+#endif
 	}
 	
@@ -47,9 +67,15 @@
 	if (sUseArbQueries)
 	{
+#ifdef _ARBGL
+	  // VH
 		glBeginQueryARB(GL_SAMPLES_PASSED_ARB, mId);
+#endif
 	}
 	else
 	{
+#ifdef _ARBGL
+	  // VH
 		glBeginOcclusionQueryNV(mId);
+#endif
 	}
 }
@@ -59,9 +85,15 @@
 	if (sUseArbQueries)
 	{
+#ifdef _ARBGL
+	  // VH
 		glEndQueryARB(GL_SAMPLES_PASSED_ARB);
+#endif
 	}
 	else
 	{
+#ifdef _ARBGL
+	  // VH
 		glEndOcclusionQueryNV();	
+#endif
 	}
 }
@@ -79,15 +111,19 @@
 	if (sUseArbQueries)
 	{
+#ifdef _ARBGL
+	  // VH
 		//GLint available;
 		glGetQueryObjectuivARB(mId,
 							   GL_QUERY_RESULT_AVAILABLE_ARB,
-                               &available);
+				       &available);
+#endif		
 		return available == GL_TRUE;
 	}
 	else
 	{
-		
-		glGetOcclusionQueryuivNV(mId, GL_PIXEL_COUNT_AVAILABLE_NV, &available);
-
+#ifdef _ARBGL
+	  // VH
+	  glGetOcclusionQueryuivNV(mId, GL_PIXEL_COUNT_AVAILABLE_NV, &available);
+#endif
 		return available == GL_TRUE;
 	}
@@ -102,11 +138,16 @@
 	if (sUseArbQueries)
 	{
+#ifdef _ARBGL
+	  // VH
 		glGetQueryObjectuivARB(mId, GL_QUERY_RESULT_ARB, &sampleCount);
+#endif
 		return sampleCount;
 	}
 	else
 	{	
-
+#ifdef _ARBGL
+	  // VH
 		glGetOcclusionQueryuivNV(mId, GL_PIXEL_COUNT_NV, &sampleCount);
+#endif		
 		return sampleCount;
 	}	
@@ -124,9 +165,15 @@
 		if (sUseArbQueries)
 		{
+#ifdef _ARBGL
+	  // VH
 			glGenQueriesARB(n, (unsigned int *)newQueries);
+#endif
 		}
 		else
 		{
-			glGenOcclusionQueriesNV(n, (unsigned int *)newQueries);
+#ifdef _ARBGL
+	  // VH		  
+		  glGenOcclusionQueriesNV(n, (unsigned int *)newQueries);
+#endif		  
 		}
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.h	(revision 2575)
@@ -250,4 +250,9 @@
 };
 
+// forward declaration
+extern Vector3 UniformRandomVector(const Vector3 &normal);
+extern Vector3 UniformRandomVector();
+extern Vector3 UniformRandomVector(const float r1, const float r2);
+  
 inline Vector3
 ArbitraryNormal(const Vector3 &N)
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.h	(revision 2575)
@@ -6,4 +6,50 @@
 namespace GtpVisibilityPreprocessor {
 
+
+/**
+ * Assert whether the argument is a prime number.
+ * @param number the number to be checked
+ */
+inline bool IsPrime(const int number) {
+  bool isIt = true;
+  for(int i = 2; i < number; i++) {
+	if(number % i == 0) {
+	  isIt = false;
+	  break;
+	}
+  }
+	if(number == 2) {
+	  isIt = false;
+	}
+	return isIt;
+}
+
+  
+  /**
+ * Find the nth prime number.
+ * @param index the ordinal position in the sequence
+ */
+inline int FindPrime(const int index) {
+  //  if (index < 1) {
+  //	cerr<<"FindPrime: The argument must be non-negative."<<endl;
+  //	return -1;
+  //  }
+
+  const int primes[] = {-1, 1, 3, 5, 7, 11, 13};
+  if (index <= 6)
+	return primes[index];
+
+  int prime = 1;
+  int found = 1;
+  while(found != index) {
+	prime += 2;
+	  if(IsPrime(prime) == true) {
+		found++;
+	  }
+  }
+  return prime;
+}
+
+  
 inline float halton(float baseRec, float prev) {
   //  float r = 1 - prev - 1e-10f;
@@ -82,48 +128,5 @@
 
 
-/**
- * Assert whether the argument is a prime number.
- * @param number the number to be checked
- */
-inline bool IsPrime(const int number) {
-  bool isIt = true;
-  for(int i = 2; i < number; i++) {
-	if(number % i == 0) {
-	  isIt = false;
-	  break;
-	}
-  }
-	if(number == 2) {
-	  isIt = false;
-	}
-	return isIt;
-}
-
-  
-  /**
- * Find the nth prime number.
- * @param index the ordinal position in the sequence
- */
-inline int FindPrime(const int index) {
-  //  if (index < 1) {
-  //	cerr<<"FindPrime: The argument must be non-negative."<<endl;
-  //	return -1;
-  //  }
-
-  const int primes[] = {-1, 1, 3, 5, 7, 11, 13};
-  if (index <= 6)
-	return primes[index];
-
-  int prime = 1;
-  int found = 1;
-  while(found != index) {
-	prime += 2;
-	  if(IsPrime(prime) == true) {
-		found++;
-	  }
-  }
-  return prime;
-}
-
+  
 struct HaltonSequence {
 public:
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 2347)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp	(revision 2575)
@@ -3478,8 +3478,8 @@
 			BspInterior *in = static_cast<BspInterior *>(node);
 
-			Plane3 &splitPlane = in->GetPlane();
+			Plane3 *splitPlane = &(in->GetPlane());
 			
-			const int entSide = splitPlane.Side(entp, thresh);
-			const int extSide = splitPlane.Side(extp, thresh);
+			const int entSide = splitPlane->Side(entp, thresh);
+			const int extSide = splitPlane->Side(extp, thresh);
 
 			if (entSide < 0) 
@@ -3518,5 +3518,5 @@
 
 			// find intersection of ray segment with plane
-			extp = splitPlane.FindIntersection(origin, extp, &t);
+			extp = splitPlane->FindIntersection(origin, extp, &t);
 		} 
 		else
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 2575)
@@ -364,10 +364,10 @@
 	/** Creates mesh for this view cell.
 	*/
-	virtual void CreateMesh(ViewCell *vc) = NULL;
+	virtual void CreateMesh(ViewCell *vc) = 0;
 	/** Writes view cells to disc.
 	*/
 	virtual bool ExportViewCells(const string filename, 
-								 const bool exportPvs, 
-								 const ObjectContainer &objects);
+				     const bool exportPvs, 
+				     const ObjectContainer &objects);
 	/** Casts beam to collect view cells.
 	*/
@@ -626,5 +626,5 @@
 									   const int maxRays,
 									   const string &prefix,
-									   VssRayContainer *visRays = NULL) = NULL;
+									   VssRayContainer *visRays = NULL) = 0;
 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.cpp	(revision 2332)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ObjectPvs.cpp	(revision 2575)
@@ -1,4 +1,6 @@
 #include <iostream>
 #include <stack>
+
+#include "Mesh.h"
 #include "ObjectPvs.h"
 #include "Intersectable.h"
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Ray.h	(revision 2575)
@@ -128,7 +128,7 @@
   // Inititalize the ray again when already constructed
   void Init(const Vector3 &wherefrom,
-			const Vector3 &whichdir,
-			const int _type, 
-			bool dirNormalized = false) {
+	    const Vector3 &whichdir,
+	    const int _type, 
+	    bool dirNormalized = false) {
     loc = wherefrom;
     dir = (dirNormalized || _type == LINE_SEGMENT) ? whichdir: Normalize(whichdir) ;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h	(revision 2571)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.h	(revision 2575)
@@ -20,5 +20,5 @@
 class Preprocessor;
 struct SimpleRay;
-
+class RayPacket2x2;
 
 /** This class provides an interface for ray casting.
@@ -29,167 +29,174 @@
 public:
 	
-	enum {
-	  INTERNAL_RAYCASTER = 0,
-	  INTEL_RAYCASTER
-	};
-
-	RayCaster(const Preprocessor &preprocessor);
-
-	virtual ~RayCaster();
-
-	virtual int Type() const = 0;
-
-	/** Wrapper for casting single ray.
-		@returns ray or NULL if invalid
-	*/
-	VssRay *CastRay(const SimpleRay &simpleRay,
-					const AxisAlignedBox3 &box,
-					const bool castDoubleRay);
-
-	virtual int CastRay(const SimpleRay &simpleRay,
-						VssRayContainer &vssRays,
-						const AxisAlignedBox3 &box,
-						const bool castDoubleRay,
-						const bool pruneInvalidRays = true) = 0;
-
-	virtual void CastRays16(SimpleRayContainer &rays,
-							VssRayContainer &vssRays,
-							const AxisAlignedBox3 &sbox,
-							const bool castDoubleRay,
-							const bool pruneInvalidRays = true) = 0;
-
+  enum {
+    INTERNAL_RAYCASTER = 0,
+    INTEL_RAYCASTER = 1,
+    HAVRAN_RAYCASTER = 2
+  };
+
+  RayCaster(const Preprocessor &preprocessor);
+
+  virtual ~RayCaster();
+  
+  virtual int Type() const = 0;
+
+  /** Wrapper for casting single ray.
+      @returns ray or NULL if invalid
+  */
+  VssRay *CastRay(const SimpleRay &simpleRay,
+		  const AxisAlignedBox3 &box,
+		  const bool castDoubleRay);
+
+  virtual int CastRay(const SimpleRay &simpleRay,
+		      VssRayContainer &vssRays,
+		      const AxisAlignedBox3 &box,
+		      const bool castDoubleRay,
+		      const bool pruneInvalidRays = true) = 0;
+
+  virtual void CastRays16(SimpleRayContainer &rays,
+			  VssRayContainer &vssRays,
+			  const AxisAlignedBox3 &sbox,
+			  const bool castDoubleRay,
+			  const bool pruneInvalidRays = true) = 0;
+  
   virtual void CastRays(
-						SimpleRayContainer &rays,
-						VssRayContainer &vssRays,
-						const AxisAlignedBox3 &sbox,
-						const bool castDoubleRay,
-						const bool pruneInvalidRays = true);
-
+			SimpleRayContainer &rays,
+			VssRayContainer &vssRays,
+			const AxisAlignedBox3 &sbox,
+			const bool castDoubleRay,
+			const bool pruneInvalidRays = true);
+
+  // Just for testing concept
+  virtual void CastRaysPacket2x2(RayPacket2x2 &raysPack,
+				 bool castDoubleRay,
+				 const bool pruneInvalidRays = true)
+  { }
+  
   /*virtual void CastRaysEye4(SimpleRayContainer &rays,
-							  VssRayContainer &vssRays,
-							  const AxisAlignedBox3 &sbox,
-							  const bool castDoubleRay,
-							  const bool pruneInvalidRays = true) = 0;
-*/
-	virtual void
-	SortRays(SimpleRayContainer &rays);
-
-
-	// pool of vss rays to be used in one pass of the sampling
-	struct VssRayPool 
-	{
-		VssRayPool(): mRays(NULL), mIndex(0), mNumber(0) 
-		{}
-
-		~VssRayPool() 
-		{
-			DEL_PTR(mRays);
-		}
-
-		void Reserve(const int number) 
-		{
-			DEL_PTR(mRays);
-			mRays = new VssRay[number];
-			mNumber = number;
-		}
-
-		void Clear() 
-		{
-			mIndex = 0;
-		}
-		
-		VssRay *Alloc() 
-		{
-			// reset pool
-			if (mIndex == mNumber)
-				mIndex = 0;
-			return mRays + mIndex ++;
-		}
-
-	protected:
-
-		VssRay *mRays;
-		int mIndex;
-		int mNumber;
-	};
-
-	VssRayPool mVssRayPool;
-
-	void ReserveVssRayPool(const int n) 
-	{
-		mVssRayPool.Reserve(n);
-	}
-
-	void InitPass() 
-	{
-		mVssRayPool.Clear();
-	}
-
-
+    VssRayContainer &vssRays,
+    const AxisAlignedBox3 &sbox,
+    const bool castDoubleRay,
+    const bool pruneInvalidRays = true) = 0;
+  */
+
+  virtual void
+  SortRays(SimpleRayContainer &rays);
+
+
+  // pool of vss rays to be used in one pass of the sampling
+  struct VssRayPool 
+  {
+    VssRayPool(): mRays(NULL), mIndex(0), mNumber(0) 
+    {}
+    
+    ~VssRayPool() 
+    {
+      delete []mRays;
+    }
+    
+    void Reserve(const int number) 
+    {
+      DEL_PTR(mRays);
+      mRays = new VssRay[number];
+      mNumber = number;
+    }
+    
+    void Clear() 
+    {
+      mIndex = 0;
+    }
+    
+    VssRay *Alloc() 
+    {
+      // reset pool
+      if (mIndex == mNumber)
+	mIndex = 0;
+      return mRays + mIndex ++;
+    }
+  protected:
+    VssRay *mRays;
+    int mIndex;
+    int mNumber;
+  };
+
+
+  VssRayPool mVssRayPool;
+  
+  void ReserveVssRayPool(const int n) 
+  {
+    mVssRayPool.Reserve(n);
+  }
+  
+  void InitPass() 
+  {
+    mVssRayPool.Clear();
+  }
+  
+  
 protected:
-
-	VssRay *RequestRay(const Vector3 &origin, 
-		const Vector3 &termination, 
-		Intersectable *originObject, 
-		Intersectable *terminationObject, 
-		const int pass, 
-		const float pdf);
-
-	void _SortRays(SimpleRayContainer &rays,
-		const int l,
-		const int r,
-		const int depth,
-		float box[12]);
-
-	struct Intersection
-	{
-		Intersection(): mObject(NULL), mFaceId(0)
-		{}
-
-		Intersection(const Vector3 &p, const Vector3 &n, Intersectable *o, const int f):
-		mPoint(p), mNormal(n), mObject(o), mFaceId(f)
-		{}
-
-		Intersection(const Vector3 &p): mPoint(p), mObject(NULL), mFaceId(0)
-		{}
-
-
-		////////////
-
-		Vector3 mPoint;
-		Vector3 mNormal;
-		Intersectable *mObject;
-		int mFaceId;
-	};
-
-
-	int ProcessRay(const SimpleRay &ray,
-		           Intersection &hitA,
-				   Intersection &hitB,
-				   VssRayContainer &vssRays,
-				   const AxisAlignedBox3 &box,
-				   const bool castDoubleRay,
-				   const bool pruneInvalidRays = true);
-
-	/** Checks if ray is valid.
-	I.e., the ray is in valid view space.
-	@note: clamps the ray to valid view space.
-	*/
-	bool ValidateRay(const Vector3 &origin,
-		             const Vector3 &direction,
-					 const AxisAlignedBox3 &box,
-					 Intersection &hit);
-
-	bool ClipToViewSpaceBox(const Vector3 &origin,
-                            const Vector3 &termination,
-							Vector3 &clippedOrigin,
-							Vector3 &clippedTermination);
-
-
-
-
-
-
-	const Preprocessor &mPreprocessor;
+  
+  VssRay *RequestRay(const Vector3 &origin, 
+		     const Vector3 &termination, 
+		     Intersectable *originObject, 
+		     Intersectable *terminationObject, 
+		     const int pass, 
+		     const float pdf);
+  
+  void _SortRays(SimpleRayContainer &rays,
+		 const int l,
+		 const int r,
+		 const int depth,
+		 float box[12]);
+  
+  struct Intersection
+  {
+    Intersection(): mObject(NULL), mFaceId(0)
+    {}
+    
+    Intersection(const Vector3 &p, const Vector3 &n, Intersectable *o, const int f):
+      mPoint(p), mNormal(n), mObject(o), mFaceId(f)
+    {}
+    
+    Intersection(const Vector3 &p): mPoint(p), mObject(NULL), mFaceId(0)
+    {}
+    
+    
+    ////////////
+    
+    Vector3 mPoint;
+    Vector3 mNormal;
+    Intersectable *mObject;
+    int mFaceId;
+  };
+
+
+  int ProcessRay(const SimpleRay &ray,
+		 Intersection &hitA,
+		 Intersection &hitB,
+		 VssRayContainer &vssRays,
+		 const AxisAlignedBox3 &box,
+		 const bool castDoubleRay,
+		 const bool pruneInvalidRays = true);
+  
+  /** Checks if ray is valid.
+      I.e., the ray is in valid view space.
+      @note: clamps the ray to valid view space.
+  */
+  bool ValidateRay(const Vector3 &origin,
+		   const Vector3 &direction,
+		   const AxisAlignedBox3 &box,
+		   Intersection &hit);
+  
+  bool ClipToViewSpaceBox(const Vector3 &origin,
+			  const Vector3 &termination,
+			  Vector3 &clippedOrigin,
+			  Vector3 &clippedTermination);
+  
+  const Preprocessor &mPreprocessor;
+#if 1
+public:
+  // Added by VH for debugging
+  Intersection intersect;
+#endif  
 };
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 2542)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.cpp	(revision 2575)
@@ -519,6 +519,6 @@
 bool
 Environment::GetStringValue(const char *name,
-							char *value,
-							const bool isFatal) const
+			    char *value,
+			    const bool isFatal) const
 {
   int i = FindOption(name, isFatal);
@@ -538,4 +538,27 @@
   return true;
 }
+
+bool
+Environment::GetStringValue(const char *name,
+			    string &stringVariable,
+			    const bool isFatal) const
+{
+  int i = FindOption(name, isFatal);
+
+  if (i<0)
+    return false;
+
+  
+  if (options[i].value != NULL) {
+    // option was not read, so use the default
+    stringVariable = options[i].value;
+  }
+  else {
+    // option was explicitly specified
+    stringVariable = options[i].defaultValue;
+  }
+  return true;
+}
+
 
 void
@@ -1069,5 +1092,5 @@
   numParams = 0;
   params = NULL;
-  maxOptions = 500;
+  maxOptions = 600;
 
   
@@ -2846,6 +2869,62 @@
 				 "true");
 
-	/////////////////////////////////////////////////////////////////
-
+  /////////////////////////////////////////////////////////////////
+  // By Vlastimil Havran
+  RegisterOption("BSP.splitclip", optBool,
+		 "kd_splitclip=", "false");
+  RegisterOption("BSP.emptyCut", optBool,
+		 "kd_emptycut=", "true");
+  RegisterOption("BSP.termCrit", optString,
+		 "kd_termcrit=", "auto");
+  RegisterOption("BSP.maxDepthAllowed", optInt,
+		 "kd_maxDepth=", "16");
+  RegisterOption("BSP.maxEmptyCutDepth", optInt,
+		 "kd_maxEmptyCutDepth=", "4");
+  RegisterOption("BSP.absMaxAllowedDepth", optInt,
+		 "kd_absMaxAllowedDepth=", "20");
+  RegisterOption("BSP.maxListLength", optInt,
+		 "kd_maxListLength=", "16");
+  RegisterOption("BSP.useRadixSort", optBool,
+		 "kd_useRadixSort=", "false");
+  RegisterOption("BSP.printCuts", optBool,
+		 "kd_printCuts=", "false");
+  RegisterOption("BSP.algAutoTermination", optInt,
+		 "kd_algAutoTermination=", "0");
+  RegisterOption("BSP.axisSelectionAlg", optInt,
+		 "kd_axisSelectAlg=", "0");
+  
+  RegisterOption("BSP.decisionCost", optFloat,
+		 "kd_decCost=", "0.3");
+  RegisterOption("BSP.intersectionCost", optFloat,
+		 "kd_intersectCost=", "0.9");
+  RegisterOption("BSP.traversalCost", optFloat,
+		 "kd_travCost=", "0.2");
+  RegisterOption("BSP.biasFreeCuts", optFloat,
+		 "kd_biasFreeCuts=", "0.9");
+
+  RegisterOption("BSP.minBoxes.use", optBool,
+		 "kd_minBoxesUse=", "false");
+  RegisterOption("BSP.minBoxes.tight", optBool,
+		 "kd_minBoxesTight=", "false");
+  RegisterOption("BSP.minBoxes.minObjects", optInt,
+		 "kd_minBoxesMinObjects=", "10");
+  RegisterOption("BSP.minBoxes.minDepthDistance", optInt,
+		 "kd_minBoxesMinDist=", "3");
+  RegisterOption("BSP.minBoxes.minSA2ratio", optFloat,
+		 "kd_minBoxesSA2ratio=", "1.0");
+
+  // The object used for testing
+  RegisterOption("Rays.file",
+		 optString,
+		 "rays_filename=",
+		 "data/fileRays_arena.txt");
+  RegisterOption("Rays.cnt",
+		 optInt,
+		 "rays_cnt=", "100000");
+  
+  RegisterOption("TestDoubleRays", optBool,
+		 "test_doublrays=", "false");
+
+  /////////////////////////////////////////////////////////////////
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/FromPointVisibilityTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/FromPointVisibilityTree.h	(revision 1006)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/FromPointVisibilityTree.h	(revision 2575)
@@ -1,9 +1,11 @@
 #ifndef _FromPointVisibilityTree_H__
 #define _FromPointVisibilityTree_H__
+
+#include <stack>
+#include <fstream>
 
 #include "Mesh.h"
 #include "Containers.h"
 #include "Polygon3.h"
-#include <stack>
 #include "Statistics.h"
 #include "VssRay.h"
@@ -256,4 +258,6 @@
 	*/
 	int CastRay(Ray &ray);
+        int CastSimpleRay(const SimpleRay &ray) { return 0;}
+        int CastSimpleRay(const SimpleRay &ray, int IndexRay) { return 0;}
 
 	/// bsp tree construction types
@@ -329,5 +333,5 @@
 	/** Writes tree to output stream
 	*/
-	bool Export(ofstream &stream);
+        bool Export(std::ofstream &stream);
 
 	/** Casts beam, i.e. a 5D frustum of rays, into tree.
@@ -690,5 +694,5 @@
 		@note: should be implemented as visitor
 	*/
-	void ExportNode(BspNode *node, ofstream &stream);
+  void ExportNode(BspNode *node, std::ofstream &stream);
 
 	/** Returns estimated memory usage of tree.
@@ -782,5 +786,5 @@
 	int mMaxViewCells;
 	
-	ofstream  mSubdivisionStats;
+  std::ofstream  mSubdivisionStats;
 
 	// if rays should be stored in leaves
@@ -812,5 +816,5 @@
 	//int mSplits;
 	/// subdivision stats output file
-	ofstream mSubdivsionStats;
+        std::ofstream mSubdivsionStats;
 	/// if random split axis should be used
 	bool mUseRandomAxis;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.cpp	(revision 2543)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.cpp	(revision 2575)
@@ -1,9 +1,21 @@
 #include "Intersectable.h"
+#include "SimpleRay.h"
+//#include "ktbconf.h"
 
 using namespace std;
 
+#if _WIN32
+#define ALIGN16 __declspec(align(16))
+#else
+ALIGN16 GALIGN16
+#endif
 
 namespace GtpVisibilityPreprocessor {
 
+
+// This is the result of computing intersection
+// static data member
+  ALIGN16  IntersectionStr
+  SimpleRay::IntersectionRes[32];
 
 Intersectable::Intersectable(): 
@@ -16,4 +28,5 @@
 #endif
 {}
+
 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 2575)
@@ -20,4 +20,5 @@
 #include "VssRay.h"
 #include "IntelRayCaster.h"
+#include "HavranRayCaster.h"
 #include "InternalRayCaster.h"
 #include "GlobalLinesRenderer.h"
@@ -408,5 +409,7 @@
 	// intel ray caster can only trace triangles
 	int rayCastMethod;
-	Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
+	Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod",
+						 rayCastMethod);
+
 	vector<FaceParentInfo> *fi = 
 	  ((rayCastMethod == RayCaster::INTEL_RAYCASTER) && mLoadMeshes) ?
@@ -1044,8 +1047,21 @@
 
 	if (!mUseKdTree) {
-		// create just a dummy KdTree
-		mKdTree = new KdTree;
-		return true;
-	}
+	  // create just a dummy KdTree
+	  mKdTree = new KdTree;
+	  return true;
+	}
+
+	int rayCastMethod;
+	Environment::GetSingleton()->
+	  GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
+
+	if (rayCastMethod == 2) {
+	  //HavranRayCaster *hr =
+	  //  dynamic_cast<HavranRayCaster*>(mRayCaster);
+	  HavranRayCaster *hr =
+	    reinterpret_cast<HavranRayCaster*>(mRayCaster);
+	  hr->Build(this->mObjects);
+	  return true;
+	}	
 
 	// always try to load the kd tree
@@ -1117,12 +1133,12 @@
 	int rayCastMethod;
 	Environment::GetSingleton()->
-		GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
+	  GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
 
 	if (rayCastMethod == 0)
 	{
-		cout << "ray cast method: internal" << endl;
-		mRayCaster = new InternalRayCaster(*this);
-	}
-	else
+	  cout << "ray cast method: internal" << endl;
+	  mRayCaster = new InternalRayCaster(*this);
+	}
+	if (rayCastMethod == 1) 
 	{
 #ifdef GTP_INTERNAL
@@ -1130,4 +1146,9 @@
 	  mRayCaster = new IntelRayCaster(*this, externKdTree);
 #endif
+	}
+	if (rayCastMethod == 2) 
+	{
+	  cout << "ray cast method: havran" << endl;
+	  mRayCaster = new HavranRayCaster(*this);
 	}
 	
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 2543)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h	(revision 2575)
@@ -536,8 +536,8 @@
 protected:
 
-	friend VspTree;
-	friend OspTree;
-	friend BvHierarchy;
-	friend ViewCellsParseHandlers;
+	friend class VspTree;
+	friend class OspTree;
+	friend class BvHierarchy;
+	friend class ViewCellsParseHandlers;
 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.h	(revision 2575)
@@ -49,4 +49,5 @@
 	friend class IntelRayCaster;
 	friend class InternalRayCaster;
+	friend class HavranRayCaster;
 
 public:
@@ -193,6 +194,6 @@
 
 	static bool LoadObjects(const string &filename,
-		                    ObjectContainer &pvsObjects, 
-							const ObjectContainer &preprocessorObject);
+				ObjectContainer &pvsObjects, 
+				const ObjectContainer &preprocessorObject);
 
 
@@ -275,5 +276,6 @@
 	bool ExportBinaryObj(const std::string &filename, SceneGraphNode *root);
 
-	void SetupRay(Ray &ray, const Vector3 &point, const Vector3 &direction) const;
+	void SetupRay(Ray &ray, const Vector3 &point,
+		      const Vector3 &direction) const;
 
 	void EvalPvsStat();
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 2547)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 2575)
@@ -12,5 +12,7 @@
 #include "SubdivisionCandidate.h"
 #include "HierarchyManager.h"
+#ifdef PERFTIMER
 #include "Timer/PerfTimer.h"
+#endif // PERFTIMER
 
 
@@ -294,5 +296,5 @@
 class VspLeaf: public VspNode 
 {
-	friend VspTree;
+  friend class VspTree;
 
 public:
@@ -670,4 +672,5 @@
 	////////////
 
+#ifdef PERFTIMER  
 	PerfTimer mSortTimer;
 	PerfTimer mSplitTimer;
@@ -677,5 +680,6 @@
 	PerfTimer mPlaneTimer;
 	PerfTimer mViewCellsTimer;
-
+#endif 
+  
 protected:
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h	(revision 2575)
@@ -9,4 +9,5 @@
 class AxisAlignedBox3;
 class Ray;
+class SimpleRay;
 class Plane3;
 
@@ -32,4 +33,6 @@
 	int CastRay(const Ray &ray, float &t, const float nearestT, Vector3 &normal) const;
 
+	int CastSimpleRay(const SimpleRay &ray, float &t, const float nearestT) const;
+  
 	friend std::ostream& operator<< (std::ostream &s, const Triangle3 &A);
 	friend std::istream& operator>> (std::istream &s, Triangle3 &A);
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Material.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Material.cpp	(revision 2515)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Material.cpp	(revision 2575)
@@ -3,4 +3,13 @@
 
 namespace GtpVisibilityPreprocessor {
+
+
+RgbColor
+RandomColor(const float a, const float b)
+{
+  return RgbColor(a + Random(b),
+				  a + Random(b),
+				  a + Random(b));
+}
 
 
@@ -15,13 +24,4 @@
 
   return m;
-}
-
-
-RgbColor
-RandomColor(const float a, const float b)
-{
-  return RgbColor(a + Random(b),
-				  a + Random(b),
-				  a + Random(b));
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Trackball.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Trackball.cpp	(revision 2347)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Trackball.cpp	(revision 2575)
@@ -50,6 +50,6 @@
  * Gavin Bell
  */
-#include <math.h>
-#include "trackball.h"
+#include <cmath>
+#include "Trackball.h"
 
 /*
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h	(revision 2548)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.h	(revision 2575)
@@ -48,4 +48,5 @@
 		HW_GLOBAL_LINES_DISTRIBUTION,
 		VIEWCELL_BASED_DISTRIBUTION,
+		FILTER_BASED_DISTRIBUTION,
 		DIFFERENCE_SAMPLING_BASED_DISTRIBUTION,
 	};
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 2560)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 2575)
@@ -525,6 +525,8 @@
 	//TestEvaluation(sc);
 
+#ifdef PERFTIMER   
 	// fill view cells cache
 	mNodeTimer.Entry();
+#endif	
 
 	const BvhTraversalData &tData = sc.mParentData;
@@ -634,6 +636,8 @@
 	UpdateViewCells(sc);
 
+#ifdef PERFTIMER  
 	mNodeTimer.Exit();
-
+#endif
+	
 	// return the new interior node
 	return node;
@@ -647,6 +651,8 @@
 								)
 {
+#ifdef PERFTIMER  
 	mSubdivTimer.Entry();
-
+#endif
+	
 	BvhSubdivisionCandidate *sc = 
 		static_cast<BvhSubdivisionCandidate *>(splitCandidate);
@@ -718,6 +724,8 @@
 	}
 	
+#ifdef PERFTIMER  
 	mSubdivTimer.Exit();
-
+#endif
+	
 	return currentNode;
 }
@@ -780,5 +788,7 @@
 										   const bool preprocessViewCells)
 {
-	mPlaneTimer.Entry();
+#ifdef PERFTIMER  
+  mPlaneTimer.Entry();
+#endif
 
 	const BvhTraversalData &tData = splitCandidate.mParentData;
@@ -824,11 +834,14 @@
 	}
 
+#ifdef PERFTIMER  
 	mPlaneTimer.Exit();
-
+#endif
 
 	///////////////////
 
+#ifdef PERFTIMER  
 	mEvalTimer.Entry();
-
+#endif
+	
 	// mark view cells according to what part of the split they see
 	// and compute volume
@@ -984,5 +997,7 @@
 #endif
 
+#ifdef PERFTIMER  
 	mEvalTimer.Exit();
+#endif
 }
 
@@ -1676,6 +1691,7 @@
 													const int axis)											
 {
+#ifdef PERFTIMER  
 	mSortTimer.Entry();
-	
+#endif	
 	//-- insert object queries
 	ObjectContainer *objects = mUseGlobalSorting ? 
@@ -1684,5 +1700,7 @@
 	CreateLocalSubdivisionCandidates(*objects, &mSubdivisionCandidates, !mUseGlobalSorting, axis);
 	
+#ifdef PERFTIMER  
 	mSortTimer.Exit();
+#endif
 }
 
@@ -1840,6 +1858,8 @@
 										 bool useVisibilityBasedHeuristics)
 {
+#ifdef PERFTIMER  
 	mSplitTimer.Entry();
-
+#endif
+	
 	if (mIsInitialSubdivision)
 	{
@@ -1925,6 +1945,8 @@
 	backObjects = nBackObjects[bestAxis];
 
+#ifdef PERFTIMER  
 	mSplitTimer.Exit();
-
+#endif
+	
 	//cout << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl;
 	return nCostRatio[bestAxis];
@@ -2276,6 +2298,8 @@
 	//-- use view cells cache
 
+#ifdef PERFTIMER  
 	mCollectTimer.Entry();
-
+#endif
+	
 	ViewCellContainer *objViewCells = obj->GetOrCreateViewCells();
 
@@ -2308,6 +2332,7 @@
 	}
 
+#ifdef PERFTIMER  
 	mCollectTimer.Exit();
-
+#endif
 	return (int)objViewCells->size();
 }
@@ -2320,5 +2345,7 @@
 										  const bool onlyUnmailedRays)
 {
+#ifdef PERFTIMER  
 	mCollectTimer.Entry();
+#endif
 	VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
 
@@ -2362,5 +2389,7 @@
 	}
 
+#ifdef PERFTIMER  
 	mCollectTimer.Exit();
+#endif
 	return numRays;
 }
@@ -2436,5 +2465,7 @@
 								  const bool onlyUnmailedRays)
 {
+#ifdef PERFTIMER  
 	mCollectTimer.Entry();
+#endif
 	VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
 
@@ -2478,5 +2509,7 @@
 	}
 
+#ifdef PERFTIMER  
 	mCollectTimer.Exit();
+#endif
 	return numRays;
 }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ply.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ply.h	(revision 749)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ply.h	(revision 2575)
@@ -132,5 +132,5 @@
 
 /* memory allocation */
-extern char *my_alloc();
+extern char *my_alloc(int,int,char *);
 #define myalloc(mem_size) my_alloc((mem_size), __LINE__, __FILE__)
 
@@ -202,5 +202,4 @@
 extern int equal_strings(char *, char *);
 
-
 #ifdef __cplusplus
 }
@@ -208,3 +207,2 @@
 #endif /* !__PLY_H__ */
 
-
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/BoostPreprocessorThread.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/BoostPreprocessorThread.cpp	(revision 1867)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/BoostPreprocessorThread.cpp	(revision 2575)
@@ -4,9 +4,13 @@
 #include "SceneGraph.h"
 #include "Preprocessor.h"
-#include <boost/thread/thread.hpp>
+
+// ??????????????? commented by VH ????????????
+//#include <boost/thread/thread.hpp>
 
 namespace GtpVisibilityPreprocessor {
 
 
+#ifdef THREADS1
+  
 BoostPreprocessorThread::BoostPreprocessorThread(Preprocessor *p):
 PreprocessorThread(p), mThread(NULL)
@@ -51,3 +55,6 @@
 }
 
+#endif // THREADS1
+
+  
 }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 2571)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 2575)
@@ -24,6 +24,8 @@
 #include "SamplingStrategy.h"
 #include "SceneGraph.h"
+
+#ifdef PERFTIMER  
 #include "Timer/PerfTimer.h"
-
+#endif // PERFTIMER
 
 #define USE_RAY_LENGTH_AS_CONTRIBUTION 0
@@ -39,8 +41,10 @@
 
 
+#ifdef PERFTIMER  
 PerfTimer viewCellCastTimer;
 PerfTimer pvsTimer;
 PerfTimer objTimer;
-
+#endif
+  
 // HACK
 const static bool SAMPLE_AFTER_SUBDIVISION = true;
@@ -66,4 +70,22 @@
 };
 
+
+
+struct SortableViewCellEntry {
+
+	SortableViewCellEntry() {}
+	SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
+
+	float mValue;
+	ViewCell *mViewCell;
+
+  friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b);
+};
+
+
+inline bool
+operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
+  return a.mValue < b.mValue;
+}
 
 ViewCellsManager::ViewCellsManager(ViewCellsTree *viewCellsTree):
@@ -1059,9 +1081,10 @@
 	int id;
 
+#ifdef PERFTIMER  
 	PerfTimer boxTimer;
 
 	boxTimer.Start();
 	boxTimer.Entry();
-	
+#endif	
 	for (int i = 0; i < numBoxes; ++ i)
 	{
@@ -1074,7 +1097,9 @@
 
 
+#ifdef PERFTIMER  
 	boxTimer.Exit();
 
 	Debug << numBoxes << " boxes loaded in " << boxTimer.TotalTime() << " secs" << endl;
+#endif
 }
 
@@ -1699,5 +1724,5 @@
 inline float EvalMergeCost(ViewCell *root, ViewCell *candidate)
 {
-	return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
+  return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
 }
 
@@ -1773,17 +1798,4 @@
 }
 
-
-struct SortableViewCellEntry {
-
-	SortableViewCellEntry() {}
-	SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
-
-	float mValue;
-	ViewCell *mViewCell;
-
-	friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
-		return a.mValue < b.mValue;
-	}
-};
 
 
@@ -2114,4 +2126,5 @@
 	}
 
+#ifdef PERFTIMER  
 	cout << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
 	Debug << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
@@ -2119,5 +2132,5 @@
 	cout << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
 	Debug << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
-	
+#endif	
 	return sum;
 }
@@ -2869,6 +2882,7 @@
 	ViewCell::NewMail();
 
+#ifdef PERFTIMER  
 	viewCellCastTimer.Entry();
-
+#endif
 	static ViewCellContainer viewCells;
 	static VssRay *lastVssRay = NULL;
@@ -2889,6 +2903,7 @@
 	}
 
+#ifdef PERFTIMER  
 	viewCellCastTimer.Exit();
-
+#endif
 	mSamplesStat.mViewCells += (int)viewCells.size();
 
@@ -2908,13 +2923,16 @@
 	Intersectable *terminationObj;
 
+#ifdef PERFTIMER  
 	objTimer.Entry();
-
+#endif
 	// obtain pvs entry (can be different from hit object)
 	terminationObj = ray.mTerminationObject;
 
+#ifdef PERFTIMER  
 	objTimer.Exit();
 
 	pvsTimer.Entry();
-
+#endif
+	
 	ViewCellContainer::const_iterator it = viewCells.begin();
 
@@ -2929,6 +2947,8 @@
 	}
 
+#ifdef PERFTIMER  
 	pvsTimer.Exit();
-
+#endif
+	
 	mSamplesStat.mPvsContributions += ray.mPvsContribution;
 	if (ray.mPvsContribution)
@@ -3460,5 +3480,6 @@
 							   const float filterSize,
 							   ObjectPvs &pvs,
-							   vector<AxisAlignedBox3> *filteredBoxes
+							   vector<AxisAlignedBox3> *filteredBoxes,
+							   const bool onlyNewObjects
 							   )
 {
@@ -3480,9 +3501,10 @@
 
 	if (!mUseKdPvs)
-	{	// first mark all objects from this pvs
-		while (pit.HasMoreEntries()) 	
-			pit.Next()->Mail();
-	}
-
+	{
+	  // first mark all objects from this pvs
+	  while (pit.HasMoreEntries()) 	
+		pit.Next()->Mail();
+	}
+	
 	int pvsSize = 0;
 	int nPvsSize = 0;
@@ -3548,5 +3570,15 @@
 
 		pit = basePvs.GetIterator();
-
+		
+		if (onlyNewObjects) {
+		  while (pit.HasMoreEntries()) {
+			// mail all objects from the original not to include them in the
+			// resulting pvs
+			Intersectable *obj = pit.Next(pvsData);
+			obj->Mail();
+		  }
+		  pit = basePvs.GetIterator();
+		}
+		
 		while (pit.HasMoreEntries()) 
 		{		
@@ -3631,8 +3663,8 @@
 		stats.mAvgFilterRadius /= (stats.mLocalFilterCount + stats.mGlobalFilterCount);
 	}
-
+	
 	//Debug << " nPvs size = " << pvs.GetSize() << endl;
 
-	if (!mUseKdPvs)
+	if (!mUseKdPvs && !onlyNewObjects)
 	{
 		PvsData pvsData;
@@ -7162,9 +7194,10 @@
 	CLEAR_CONTAINER(tmpRays);
 
+#ifdef PERFTIMER  
 	cout << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
 	Debug << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
-
 	cout << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
 	Debug << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
+#endif
 	
 	return sum;
@@ -7174,12 +7207,13 @@
 
 
-ViewCellsManager *ViewCellsManager::LoadViewCellsBinary(const string &filename, 
-														ObjectContainer &pvsObjects,
-														bool finalizeViewCells,
-														BoundingBoxConverter *bconverter)												 
-{
-	IN_STREAM stream(filename.c_str());
-
-	if (!stream.is_open())
+ViewCellsManager *
+ViewCellsManager::LoadViewCellsBinary(const string &filename, 
+									  ObjectContainer &pvsObjects,
+									  bool finalizeViewCells,
+									  BoundingBoxConverter *bconverter)												 
+{
+  IN_STREAM stream(filename.c_str());
+  
+  if (!stream.is_open())
 	{
 		Debug << "View cells loading failed: could not open file" << endl;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 2572)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 2575)
@@ -5,5 +5,5 @@
 #include "ViewCellsManager.h"
 #include "SceneGraph.h"
-#include "Viewcell.h"
+#include "ViewCell.h"
 #include "Beam.h"
 #include "KdTree.h"
@@ -126,12 +126,12 @@
 void GlRenderer::RenderTriangle(TriangleIntersectable *object)
 {
-	Triangle3 &t = object->GetItem();
+  Triangle3 *t = &(object->GetItem());
 
 	glBegin(GL_TRIANGLES);
-	Vector3 normal = t.GetNormal();
+	Vector3 normal = t->GetNormal();
 	glNormal3f(normal.x, normal.y, normal.z);
-	glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
-	glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
-	glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
+	glVertex3f(t->mVertices[0].x, t->mVertices[0].y, t->mVertices[0].z);
+	glVertex3f(t->mVertices[1].x, t->mVertices[1].y, t->mVertices[1].z);
+	glVertex3f(t->mVertices[2].x, t->mVertices[2].y, t->mVertices[2].z);
 	glEnd();
 }
@@ -420,11 +420,11 @@
 		if ((*oi)->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
 			TriangleIntersectable *object = (TriangleIntersectable *)*oi;
-			Triangle3 &t = object->GetItem();
-
-			Vector3 normal = t.GetNormal();
+			Triangle3 *t = &(object->GetItem());
+
+			Vector3 normal = t->GetNormal();
 			glNormal3f(normal.x, normal.y, normal.z);
-			glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
-			glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
-			glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
+			glVertex3f(t->mVertices[0].x, t->mVertices[0].y, t->mVertices[0].z);
+			glVertex3f(t->mVertices[1].x, t->mVertices[1].y, t->mVertices[1].z);
+			glVertex3f(t->mVertices[2].x, t->mVertices[2].y, t->mVertices[2].z);
 
 		}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/common.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/common.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/common.h	(revision 2575)
@@ -21,8 +21,10 @@
 #include <limits.h>
 
-
+// use perftimer
+#define PERFTIMER
 
 namespace GtpVisibilityPreprocessor {
 
+  
 
 
@@ -45,5 +47,5 @@
 
 #if defined(__GNUC__) || defined(_MSC_VER)
-#define DIRCAT '.'
+//#define DIRCAT '.'
 #endif
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/BitVectorPvs.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/BitVectorPvs.h	(revision 2530)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/BitVectorPvs.h	(revision 2575)
@@ -79,5 +79,5 @@
 class BitVectorPvs//: public PvsBase<T>
 {
-	template<typename T, typename S> friend class BitVectorPvsIterator;
+  template<typename T1, typename S1> friend class BitVectorPvsIterator;
 
 public:
@@ -121,5 +121,5 @@
 	bool Find(T sample);
 
-	typename BitVectorPvsIterator<T, S> GetIterator() const;
+        BitVectorPvsIterator<T, S> GetIterator() const;
 
 	/** Compute continuous PVS difference 
@@ -145,5 +145,6 @@
 	void MergeInPlace(const BitVectorPvs<T, S> &a)
 	{
-		cerr << "bitvector: merge in place not implemented yet" << endl;
+	  std::cerr << "bitvector: merge in place not implemented yet"
+		    << std::endl;
 	}
 
@@ -167,6 +168,6 @@
 	int SubtractPvs(const BitVectorPvs<T, S> &pvs)
 	{
-		cerr << "not yet implemented" << endl;
-		return 0;
+	  std::cerr << "not yet implemented" << std::endl;
+	  return 0;
 	}
 
@@ -177,5 +178,5 @@
 										float &pvsEnlargement)
 	{
-		cerr << "not yet implemented" << endl;
+	  std::cerr << "not yet implemented" << std::endl;
 	}
 
@@ -284,5 +285,5 @@
 
 template <typename T, typename S>
-void BitVectorPvs<T, S>::Clear(const bool trim = true)
+void BitVectorPvs<T, S>::Clear(const bool trim)
 {
 	bit_vector::iterator bit, bit_end = mEntries.end();
@@ -309,9 +310,7 @@
 
 template <typename T, typename S>
-typename BitVectorPvsIterator<T, S> BitVectorPvs<T, S>::GetIterator() const
-{
-	BitVectorPvsIterator<T, S> pit(mEntries.begin(), mEntries.end());
-
-	return pit;
+BitVectorPvsIterator<T, S> BitVectorPvs<T, S>::GetIterator() const
+{
+  return BitVectorPvsIterator<T, S>(mEntries.begin(), mEntries.end());
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Material.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Material.h	(revision 2173)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Material.h	(revision 2575)
@@ -30,4 +30,13 @@
 };
 
+
+// Forward declarations
+RgbColor RandomColor(const float a, const float b);
+
+// Mapping from interval 0.0-1.0 to RGB using "rainbow" color map
+// (range of hue from 0-240)
+RgbColor RainbowColorMapping(const float value);
+
+  
 
 class Material 
@@ -68,4 +77,6 @@
 
 
+extern Material RandomMaterial();
+
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 2394)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 2575)
@@ -8,4 +8,5 @@
 #include "Polygon3.h"
 #include "TraversalTree.h"
+#include "Material.h"
 
 
@@ -71,5 +72,5 @@
 		else
 		{
-			SetForcedMaterial(RandomMaterial());
+		  SetForcedMaterial(RandomMaterial());
 		}
 		if (0) ExportGeometry(leaf->mObjects);	
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Matrix4x4.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Matrix4x4.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Matrix4x4.h	(revision 2575)
@@ -103,5 +103,52 @@
 };
 
+// forward declaration
+Matrix4x4 IdentityMatrix();
+Matrix4x4 Invert(const Matrix4x4 &M);	// Invert a given matrix
+Matrix4x4 Transpose(const Matrix4x4 &M);	// Transpose a given matrix
+
+// Create various types of matrix.
+Matrix4x4 IdentityMatrix();
+Matrix4x4 ZeroMatrix();
+Matrix4x4 TranslationMatrix(const Vector3 &Location);
+Matrix4x4 RotationXMatrix(float Angle);
+Matrix4x4 RotationYMatrix(float Angle);
+Matrix4x4 RotationZMatrix(float Angle);
+Matrix4x4 RotationYPRMatrix(float Yaw, float Pitch, float Roll);
+// about axis 'axis' by angle 'Angle'
+Matrix4x4 RotationAxisMatrix(const Vector3 &axis, float Angle);
+// create the rotation matrix that rotates 'vecFrom' to 'vecTo'
+Matrix4x4 RotationVectorsMatrix(const Vector3 &vecFrom,
+				const Vector3 &vecTo);
+  
+Matrix4x4 ScaleMatrix(float X, float Y, float Z);
+Matrix4x4 GenRotation(const Vector3 &x, const Vector3 &y,
+		      const Vector3 &z);
+Matrix4x4 QuadricMatrix(float a, float b, float c, float d, float e,
+			float f, float g, float h, float j, float k);
+// returns matrix for transforming normal
+Matrix4x4 NormalTransformMatrix(const Matrix4x4 &M);
+
+Matrix4x4 MirrorX();
+Matrix4x4 MirrorY();
+Matrix4x4 MirrorZ();
+Matrix4x4 RotationOnly(const Matrix4x4 &x);
+
+// Binary operators
+Matrix4x4 operator+ (const Matrix4x4 &A, const Matrix4x4 &B);
+Matrix4x4 operator- (const Matrix4x4 &A, const Matrix4x4 &B);
+Matrix4x4 operator* (const Matrix4x4 &A, float B);
+Matrix4x4 operator* (const Matrix4x4 &A, const Matrix4x4 &B);
+
+// friends returning Vector3
+Vector3 operator*(const Matrix4x4 &M, const Vector3 &v);
+Vector3 RotateOnly(const Matrix4x4 &M, const Vector3 &v);
+Vector3 TransformNormal(const Matrix4x4 &M, const Vector3 &v);
+Vector3 GetTranslation(const Matrix4x4 &M);
+
+  
 }
 
+
+
 #endif
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp	(revision 2569)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp	(revision 2575)
@@ -3,5 +3,5 @@
 #include <stack>
 
-
+#include "Material.h"
 #include "ViewCell.h"
 #include "Mesh.h"
@@ -14,6 +14,8 @@
 #include "Exporter.h"
 #include "BvHierarchy.h"
+
+#ifdef PERFTIMER  
 #include "Timer/PerfTimer.h"
-
+#endif
 
 namespace GtpVisibilityPreprocessor {
@@ -23,8 +25,8 @@
 #define TYPE_LEAF -3
 
+#ifdef PERFTIMER  
 static PerfTimer sPvsTimer;
 static PerfTimer sSearchTimer;
-
-
+#endif
 
 static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
@@ -45,8 +47,8 @@
 
 typedef priority_queue<ViewCell *, vector<ViewCell *>, 
-					   myless<vector<ViewCell *>::value_type> > TraversalQueue;
-
-int ViewCell::sMailId = 10000;//2147483647;
-int ViewCell::sReservedMailboxes = 1;
+		       myless<vector<ViewCell *>::value_type> > TraversalQueue;
+
+int Intersectable::sMailId = 10000;//2147483647;
+int Intersectable::sReservedMailboxes = 1;
 
 float MergeCandidate::sRenderCostWeight = 0;
@@ -55,6 +57,6 @@
 // pvs penalty can be different from pvs size
 inline static float EvalPvsPenalty(const float pvs, 
-								   const float lower, 
-								   const float upper)
+				   const float lower, 
+				   const float upper)
 {
 	// clamp to minmax values
@@ -2686,6 +2688,7 @@
 	Intersectable *obj;
 
+#ifdef PERFTIMER  
 	sPvsTimer.Entry();
-
+#endif
 	int pvsSize;
 	stream.read(reinterpret_cast<char *>(&pvsSize), sizeof(int));
@@ -2703,5 +2706,7 @@
 	}
 
+#ifdef PERFTIMER
 	sPvsTimer.Exit();
+#endif	
 
 	return leaf;
@@ -2738,6 +2743,8 @@
 	queue<ViewCell *> tStack;
 
+#ifdef PERFTIMER  
 	sPvsTimer.Start();
-
+#endif
+	
 	mPvsIds = new int[pvsObjects.size()];
 
@@ -2774,6 +2781,8 @@
 	}
 
+#ifdef PERFTIMER  
 	Debug << "needed " << sPvsTimer.TotalTime() << " secs for pvs loading" << endl;
-
+#endif
+	
 	delete mPvsIds;
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/SimpleRay.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/SimpleRay.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/SimpleRay.h	(revision 2575)
@@ -5,9 +5,23 @@
 using namespace std;
 #include "Vector3.h"
+#include "Ray.h"
 
 namespace GtpVisibilityPreprocessor {
 
+class Intersectable;
+
+// This is the result of ray tracing with a simple ray
+struct IntersectionStr {
+  Intersectable *intersectable;
+  float          tdist;
+  float          maxt;
+  int            pad1; // aligned to 16 bytes
+};
+  
 struct SimpleRay
 {
+  // This is stored result for the rays in the container
+  // having 16 rays - shooting rays in both directions
+  static IntersectionStr IntersectionRes[32];
   
   Vector3 mOrigin;
@@ -29,5 +43,6 @@
   // 4B
 
-  // TOTAL = 40B
+  // TOTAL = 40B - aligned by 8 Bytes only! - it might be
+  // padding to 48 Bytes here !
 
 
@@ -39,42 +54,59 @@
   
   SimpleRay(const Vector3 &o,
-			const Vector3 &d,
-			const unsigned char distribution,
-			const float weight,
-			const unsigned char flags = F_BIDIRECTIONAL
-			):
-	mOrigin(o),
-	mDirection(d),
-	mFlags(flags),
-	mType(Ray::LOCAL_RAY),
-	mDistribution(distribution)
-	//	, mWeight(weight)
+	    const Vector3 &d,
+	    const unsigned char distribution,
+	    const float weight,
+	    const unsigned char flags = F_BIDIRECTIONAL
+	    ):
+    mOrigin(o),
+    mDirection(d),
+    mFlags(flags),
+    mType(Ray::LOCAL_RAY),
+    mDistribution(distribution)
+    //	, mWeight(weight)
   {	
-	//	mId = sSimpleRayId++;
+    //	mId = sSimpleRayId++;
   }
 
+  void
+  Set(const Vector3 &o,
+      const Vector3 &d,
+      const unsigned char distribution,
+      const float weight,
+      const unsigned char flags = F_BIDIRECTIONAL
+      )
+  {
+    mOrigin = o;
+    mDirection = d,
+    mFlags = flags;
+    mType = Ray::LOCAL_RAY;
+    mDistribution = distribution;
+    //	, mWeight(weight)
+    //	mId = sSimpleRayId++;
+  }
+  
   bool IsBidirectional() const { return mFlags & F_BIDIRECTIONAL; }
 
   void SetBidirectional(const bool b) {
-	if (b)
-	  mFlags |= F_BIDIRECTIONAL;
-	else
-	  mFlags &= ~F_BIDIRECTIONAL;
+    if (b)
+      mFlags |= F_BIDIRECTIONAL;
+    else
+      mFlags &= ~F_BIDIRECTIONAL;
   }
   
   float GetParam(const int axis) const {
-	if (axis < 3)
-	  return mOrigin[axis];
-	else
-	  return mDirection[axis-3];
+    if (axis < 3)
+      return mOrigin[axis];
+    else
+      return mDirection[axis-3];
   }
   
   Vector3 Extrap(const float t) const {
-	  return mOrigin + mDirection * t;
+    return mOrigin + mDirection * t;
   }
 
   friend std::ostream &operator<<(std::ostream &s, const SimpleRay &r)
   {
-	  return s << "origin=" << r.mOrigin << " dir=" << r.mDirection;
+    return s << "origin=" << r.mOrigin << " dir=" << r.mDirection;
   };
 };
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h	(revision 2350)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.h	(revision 2575)
@@ -14,6 +14,8 @@
 #include "IntersectableWrapper.h"
 #include "HierarchyManager.h"
+
+#ifdef PERFTIMER
 #include "Timer/PerfTimer.h"
-
+#endif // PERFTIMER
 
 namespace GtpVisibilityPreprocessor {
@@ -213,4 +215,6 @@
 	
 	int CastRay(Ray &ray) { return 0; }
+        int CastSimpleRay(const SimpleRay &ray) { return 0;}
+        int CastSimpleRay(const SimpleRay &ray, int IndexRay) { return 0;}
 	
 	bool IsConvex() const { return true; }
@@ -677,4 +681,5 @@
 	void CreateUniqueObjectIds();
 
+#ifdef PERFTIMER  
 	PerfTimer mNodeTimer;
 	PerfTimer mSubdivTimer;
@@ -684,4 +689,5 @@
 	PerfTimer mSortTimer;
 	PerfTimer mCollectTimer;
+#endif  
 
 protected:
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.cpp	(revision 2124)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Plane3.cpp	(revision 2575)
@@ -42,5 +42,5 @@
   const float det = md.Det3x3();
 
-  if (abs(det)<TRASH)
+  if (fabs(det) < TRASH)
     return false;
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp	(revision 2571)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp	(revision 2575)
@@ -4,4 +4,5 @@
 #include "KdTree.h"
 #include "BvHierarchy.h"
+#include "SimpleRay.h"
 
 
@@ -11,41 +12,77 @@
 AxisAlignedBox3 TriangleIntersectable::GetBox() const
 {	
-	return mItem.GetBoundingBox();
-}
-
-
+  return mItem.GetBoundingBox();
+}
+
+
+int
+TriangleIntersectable::CastSimpleRay(const SimpleRay &ray)
+{
+  static Vector3 nearestNormal;
+  // std::cout << "To be done - ray triangle intersection\n" << std::endl;
+  const int hitCode = mItem.CastSimpleRay(ray,
+					  SimpleRay::IntersectionRes[0].tdist,
+					  SimpleRay::IntersectionRes[0].maxt);
+  if (hitCode == Ray::INTERSECTION) {
+    SimpleRay::IntersectionRes[0].intersectable = this;
+    SimpleRay::IntersectionRes[0].maxt = SimpleRay::IntersectionRes[0].tdist;
+    return 1; // intersection occured
+  }
+  return 0; // no intersection
+}
+
+int
+TriangleIntersectable::CastSimpleRay(const SimpleRay &ray, int rayIndex)
+{
+  const int hitCode =
+    mItem.CastSimpleRay(ray,
+			SimpleRay::IntersectionRes[rayIndex].tdist,
+			SimpleRay::IntersectionRes[rayIndex].maxt);
+  if (hitCode == Ray::INTERSECTION) {
+    SimpleRay::IntersectionRes[rayIndex].intersectable = this;
+    // we copy the closest distance so far - it prunes the search
+    // when more triangles in the same leaf and assures the
+    // correctness.
+    SimpleRay::IntersectionRes[rayIndex].maxt =
+      SimpleRay::IntersectionRes[rayIndex].tdist;
+    return 1; // intersection occured
+  }
+  return 0; // no intersection
+}
+
+  
 int TriangleIntersectable::CastRay(Ray &ray)
 {	
-	float nearestT = MAX_FLOAT;
-	float t;
-	Vector3 nearestNormal;
-
-	if (ray.GetType() == Ray::LOCAL_RAY && !ray.intersections.empty())
-		nearestT = ray.intersections[0].mT;
+  float nearestT = MAX_FLOAT;
+  float t;
+  Vector3 nearestNormal;
+  
+  if (ray.GetType() == Ray::LOCAL_RAY && !ray.intersections.empty())
+    nearestT = ray.intersections[0].mT;
+  
+  const int hitCode = mItem.CastRay(ray, t, nearestT, nearestNormal);
+  
+  nearestT = t;
+  
+  if (hitCode == Ray::INTERSECTION) {
+    if (ray.GetType() == Ray::LOCAL_RAY && !ray.intersections.empty()) {
+      ray.intersections[0] = Ray::Intersection(nearestT,
+					       nearestNormal,
+					       this,
+					       0);
+    }
+    else {
+      ray.intersections.push_back(Ray::Intersection(nearestT,
+						    nearestNormal,
+						    this,
+						    0));
+    }
+    
+    return 1;
+  }
+  
+  return 0;
+}
 	
-	const int hitCode = mItem.CastRay(ray, t, nearestT, nearestNormal);
-
-	nearestT = t;
-
-	if (hitCode == Ray::INTERSECTION) {
-		if (ray.GetType() == Ray::LOCAL_RAY && !ray.intersections.empty()) {
-			ray.intersections[0] = Ray::Intersection(nearestT,
-													 nearestNormal,
-													 this,
-													 0);
-		}
-		else {
-			ray.intersections.push_back(Ray::Intersection(nearestT,
-														  nearestNormal,
-														  this,
-														  0));
-		}
-		
-		return 1;
-	}
-	
-	return 0;
-}
-	
 
 int TriangleIntersectable::NumberOfFaces() const
@@ -55,7 +92,8 @@
 
 
-Vector3 TriangleIntersectable::GetNormal(const int idx) const
-{
-	return mItem.GetNormal();
+Vector3
+TriangleIntersectable::GetNormal(const int idx) const
+{
+  return mItem.GetNormal();
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.h	(revision 2575)
@@ -61,4 +61,6 @@
   void Enlarge (const Vector3 &v);
 
+  void EnlargeToMinSize();
+  
   void SetMin(const Vector3 &v);
 
@@ -232,7 +234,7 @@
   
   int  ComputeMinMaxT(const Vector3 &origin,
-					  const Vector3 &direction,
-					  float *tmin,
-					  float *tmax) const;
+		      const Vector3 &direction,
+		      float *tmin,
+		      float *tmax) const;
 	
   // Compute tmin and tmax for a ray, whenever required .. need not pierce box
@@ -241,8 +243,8 @@
   // Compute tmin and tmax for a ray, whenever required .. need not pierce box
   int ComputeMinMaxT(const Ray &ray,
-					 float *tmin,
-					 float *tmax,
-					 EFaces &entryFace,
-					 EFaces &exitFace) const;
+		     float *tmin,
+		     float *tmax,
+		     EFaces &entryFace,
+		     EFaces &exitFace) const;
   
   // If a ray pierces the box .. returns 1, otherwise 0.
@@ -251,5 +253,5 @@
   // computes the signed distances for case: tmin < tmax and tmax > 0
   int GetMinMaxT(const Ray &ray, float *tmin, float *tmax,
-				 EFaces &entryFace, EFaces &exitFace) const;
+		 EFaces &entryFace, EFaces &exitFace) const;
   
   // Writes a brief description of the object, indenting by the given
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/IntelRayCaster.cpp	(revision 2575)
@@ -14,9 +14,10 @@
 
 FILE *fileOut = 0;
-bool saveRays = true;
-  const int saveRaysStart = 3000000;
+bool saveRays = false;
+const int saveRaysStart = 3000000;
 int cntSavedRaysFLUSH = 0;
 unsigned long int cntSavedRays = 0;
 const int intSavedLIMIT = 1024;
+
 void
 InitSaving()
@@ -33,6 +34,4 @@
   fclose(fileOut);
 }
-
-  
 
 IntelRayCaster::IntelRayCaster(const Preprocessor &preprocessor, 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Makefile
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Makefile	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Makefile	(revision 2575)
@@ -1,5 +1,5 @@
 #############################################################################
 # Makefile for building: preprocessor
-# Generated by qmake (2.00a) (Qt 4.1.2) on: so 22. XII 21:22:31 2007
+# Generated by qmake (2.00a) (Qt 4.1.2) on: ?t 3. I 15:47:31 2008
 # Project:  preprocessor.pro
 # Template: app
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.h	(revision 2575)
@@ -1099,6 +1099,8 @@
   PushRoots(std::stack<RssTreeNode *> &st) const;
 
-  void
-  PushRoots(std::stack<RayTraversalData> &st, RssTreeNode::RayInfo &info) const;
+  typedef std::stack<RayTraversalData> TstackEntry;
+
+  void
+  PushRoots(TstackEntry &st, RssTreeNode::RayInfo &info) const;
 
   void
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.h	(revision 2575)
@@ -9,5 +9,5 @@
 class KdTree;
 class SceneGraph;
-
+class RayCaster;
 
 class Camera
@@ -30,4 +30,11 @@
     mFovy = 90.0f*(float)M_PI/180.0f;
   }
+
+  Camera(int width, int height) {
+    mWidth = width;
+    mHeight = height;
+    mFovy = 90.0f*(float)M_PI/180.0f;
+  }
+
   
   void Precompute() {
@@ -46,5 +53,5 @@
   }
 
-	void SetDirection(const Vector3 &dir) {
+  void SetDirection(const Vector3 &dir) {
     mDirection = dir;
     Precompute();
@@ -53,5 +60,5 @@
   void LookInBox(const AxisAlignedBox3 &box)
   {
-    mDirection = Vector3(0,0,1); 
+    mDirection = Vector3(0,0,1);
     mPosition = box.Center();
     Precompute();
@@ -67,11 +74,26 @@
   
   bool
-	  SnapImage(std::string filename,
-			KdTree *tree,
-			SceneGraph *sceneGraph
-			);
+  SnapImage(std::string filename,
+	    KdTree *tree,
+	    SceneGraph *sceneGraph
+	    );
 
+  bool
+  SnapImage(std::string filename,
+	    RayCaster *raycaster,
+	    AxisAlignedBox3 &bbox,
+	    SceneGraph *sceneGraph
+	    );
+
+  bool
+  SnapImagePacket(std::string filename,
+		  RayCaster *raycaster,
+		  AxisAlignedBox3 &bbox,
+		  SceneGraph *sceneGraph
+		  );
+  
   void SetupRay(Ray &ray, const int x, const int y);
 
+  void SetupRay(SimpleRay &ray, const int x, const int y);
 };
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.h	(revision 2575)
@@ -493,7 +493,5 @@
   };
   
-  friend bool GreaterContribution(const VssTreeLeaf * a, const VssTreeLeaf *b) {
-	return a->GetAvgRayContribution() > b->GetAvgRayContribution();
-  }
+  friend bool GreaterContribution(const VssTreeLeaf * a, const VssTreeLeaf *b);
   
 };
@@ -504,5 +502,8 @@
   parent(p), axis(-1), depth(p ? p->depth + 1 : 0) {}
 
-
+inline bool GreaterContribution(const VssTreeLeaf * a, const VssTreeLeaf *b) {
+  return a->GetAvgRayContribution() > b->GetAvgRayContribution();
+}
+  
 
 // ---------------------------------------------------------------
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 2569)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 2575)
@@ -268,4 +268,7 @@
 
 	virtual int CastRay(Ray &ray);
+        virtual int CastSimpleRay(const SimpleRay &ray) { return 0;}
+        virtual int CastSimpleRay(const SimpleRay &ray, int IndexRay)
+        { return 0; }
 
 	virtual bool IsConvex() const { return mMesh->mIsConvex; }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 2571)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 2575)
@@ -26,5 +26,5 @@
 inline static bool ilt(Intersectable *obj1, Intersectable *obj2)
 {
-	return obj1->mId < obj2->mId;
+  return obj1->mId < obj2->mId;
 }
 
@@ -33,8 +33,8 @@
 mParent(parent), mMailbox(0), mIntersectable(NULL)
 {
-	if (parent)
-		mDepth = parent->mDepth+1;
-	else
-		mDepth = 0;
+  if (parent)
+    mDepth = parent->mDepth+1;
+  else
+    mDepth = 0;
 }
 
@@ -42,7 +42,7 @@
 KdInterior::~KdInterior()
 {
-	// recursivly destroy children
-	DEL_PTR(mFront);
-	DEL_PTR(mBack);
+  // recursivly destroy children
+  DEL_PTR(mFront);
+  DEL_PTR(mBack);
 }
 
@@ -50,5 +50,5 @@
 KdLeaf::~KdLeaf()
 {
-	DEL_PTR(mViewCell);  
+  DEL_PTR(mViewCell);  
 }
 
@@ -57,13 +57,21 @@
 { 
   mRoot = new KdLeaf(NULL, 0);
-  Environment::GetSingleton()->GetIntValue("KdTree.Termination.maxNodes", mTermMaxNodes);
-  Environment::GetSingleton()->GetIntValue("KdTree.Termination.maxDepth", mTermMaxDepth);
-  Environment::GetSingleton()->GetIntValue("KdTree.Termination.minCost", mTermMinCost);
-  Environment::GetSingleton()->GetFloatValue("KdTree.Termination.maxCostRatio", mMaxCostRatio);
-  Environment::GetSingleton()->GetFloatValue("KdTree.Termination.ct_div_ci", mCt_div_ci);
-  Environment::GetSingleton()->GetFloatValue("KdTree.splitBorder", mSplitBorder);
-  Environment::GetSingleton()->GetFloatValue("KdTree.pvsArea", mKdPvsArea);
-
-  Environment::GetSingleton()->GetBoolValue("KdTree.sahUseFaces", mSahUseFaces);
+  Environment::GetSingleton()->GetIntValue("KdTree.Termination.maxNodes",
+					   mTermMaxNodes);
+  Environment::GetSingleton()->GetIntValue("KdTree.Termination.maxDepth",
+					   mTermMaxDepth);
+  Environment::GetSingleton()->GetIntValue("KdTree.Termination.minCost",
+					   mTermMinCost);
+  Environment::GetSingleton()->GetFloatValue("KdTree.Termination.maxCostRatio",
+					     mMaxCostRatio);
+  Environment::GetSingleton()->GetFloatValue("KdTree.Termination.ct_div_ci",
+					     mCt_div_ci);
+  Environment::GetSingleton()->GetFloatValue("KdTree.splitBorder",
+					     mSplitBorder);
+  Environment::GetSingleton()->GetFloatValue("KdTree.pvsArea",
+					     mKdPvsArea);
+
+  Environment::GetSingleton()->GetBoolValue("KdTree.sahUseFaces",
+					    mSahUseFaces);
 
   char splitType[64];
@@ -97,5 +105,4 @@
 KdTree::Construct()
 {
-
   if (!splitCandidates)
     splitCandidates = new vector<SortableEntry *>;
@@ -158,14 +165,13 @@
     
     KdNode *node = SubdivideNode((KdLeaf *) data.mNode,
-								 data.mBox,
-								 backBox,
-								 frontBox
-								 );
-
-	if (result == NULL)
+				 data.mBox,
+				 backBox,
+				 frontBox
+				 );
+
+    if (result == NULL)
       result = node;
     
     if (!node->IsLeaf()) {
-
       KdInterior *interior = (KdInterior *) node;
       // push the children on the stack
@@ -173,5 +179,6 @@
       tStack.push(TraversalData(interior->mFront, frontBox, data.mDepth+1));
       
-    } else {
+    }
+    else {
       EvaluateLeafStats(data);
     }
@@ -186,12 +193,12 @@
 KdTree::TerminationCriteriaMet(const KdLeaf *leaf)
 {
-	const bool criteriaMet =
-		((int)leaf->mObjects.size() <= mTermMinCost) ||
-		 (leaf->mDepth >= mTermMaxDepth);
- 
-	if (0 && criteriaMet)
-		cerr<<"\n OBJECTS="<<(int)leaf->mObjects.size()<<endl;
-
-	return criteriaMet;
+  const bool criteriaMet =
+    ((int)leaf->mObjects.size() <= mTermMinCost) ||
+    (leaf->mDepth >= mTermMaxDepth);
+  
+  if (0 && criteriaMet)
+    cerr<<"\n OBJECTS="<<(int)leaf->mObjects.size()<<endl;
+  
+  return criteriaMet;
 }
 
@@ -199,7 +206,7 @@
 int
 KdTree::SelectPlane(KdLeaf *leaf,
-					const AxisAlignedBox3 &box,
-					float &position
-					)
+		    const AxisAlignedBox3 &box,
+		    float &position
+		    )
 {
   int axis = -1;
@@ -217,33 +224,35 @@
       bool mOnlyDrivingAxis = true;
 
-	  if (mOnlyDrivingAxis) {
-		axis = box.Size().DrivingAxis();
-		costRatio = BestCostRatio(leaf,
-								  box,
-								  axis,
-								  position,
-								  objectsBack,
-								  objectsFront);
-      } else {
-		costRatio = MAX_FLOAT;
-		for (int i=0; i < 3; i++) {
-		  float p;
-		  float r = BestCostRatio(leaf,
-								  box,
-								  i,
-								  p,
-								  objectsBack,
-								  objectsFront);
-		  if (r < costRatio) {
-			costRatio = r;
-			axis = i;
-			position = p;
-		  }
-		}
+      if (mOnlyDrivingAxis) {
+	axis = box.Size().DrivingAxis();
+	costRatio = BestCostRatio(leaf,
+				  box,
+				  axis,
+				  position,
+				  objectsBack,
+				  objectsFront);
+      }
+      else {
+	// for all 3 axes
+	costRatio = MAX_FLOAT;
+	for (int i=0; i < 3; i++) {
+	  float p;
+	  float r = BestCostRatio(leaf,
+				  box,
+				  i,
+				  p,
+				  objectsBack,
+				  objectsFront);
+	  if (r < costRatio) {
+	    costRatio = r;
+	    axis = i;
+	    position = p;
+	  }
+	}
       }
       
       if (costRatio > mMaxCostRatio) {
-		//cout<<"Too big cost ratio "<<costRatio<<endl;
-		axis = -1;
+	//cout<<"Too big cost ratio "<<costRatio<<endl;
+	axis = -1;
       }
       break;
@@ -254,5 +263,5 @@
 }
 
-KdNode *
+KdNode*
 KdTree::SubdivideNode(
 		      KdLeaf *leaf,
@@ -261,8 +270,7 @@
 		      AxisAlignedBox3 &frontBBox
 		      )
-{
-  
+{  
   if (TerminationCriteriaMet(leaf))
-	  return leaf;
+    return leaf;
 
   float position;
@@ -275,5 +283,5 @@
   }
   
-  mStat.nodes+=2;
+  mStat.nodes += 2;
   mStat.splits[axis]++;
   
@@ -309,8 +317,6 @@
   }
 
-  
   KdLeaf *back = new KdLeaf(node, objectsBack);
   KdLeaf *front = new KdLeaf(node, objectsFront);
-
  
   // replace a link from node's parent
@@ -336,16 +342,16 @@
 
 
-	if (box.Max(axis) >= position )
-	{
+    if (box.Max(axis) >= position )
+    {
       front->mObjects.push_back(*mi);
-	  //++ (*mi)->mReferences;
-	}
+      //++ (*mi)->mReferences;
+    }
 	
     if (box.Min(axis) < position )
-	{
+    {
       back->mObjects.push_back(*mi);
-	// matt: no more ref
-	//  ++ (*mi)->mReferences;
-	}
+      // matt: no more ref
+      //  ++ (*mi)->mReferences;
+    }
 
     mStat.objectRefs -= (int)leaf->mObjects.size();
@@ -353,11 +359,11 @@
   }
 
-	// store objects referenced in more than one leaf
-	// for easy access
-	ProcessMultipleRefs(back);
-	ProcessMultipleRefs(front);
-
-	delete leaf;
-	return node;
+  // store objects referenced in more than one leaf
+  // for easy access
+  ProcessMultipleRefs(back);
+  ProcessMultipleRefs(front);
+  
+  delete leaf;
+  return node;
 }
 
@@ -365,17 +371,18 @@
 void KdTree::ProcessMultipleRefs(KdLeaf *leaf) const
 {
-	// find objects from multiple kd-leaves
-	ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
-
-	for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
-	{
-		Intersectable *object = *oit;
+  // find objects from multiple kd-leaves
+  ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
+
+  for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
+  {
+    Intersectable *object = *oit;
 		
-		// matt: no more ref
-		/*if (object->mReferences > 1)
-		{
-			leaf->mMultipleObjects.push_back(object);
-		}*/
-	}
+    // matt: no more ref
+    /*
+      if (object->mReferences > 1) {
+        leaf->mMultipleObjects.push_back(object);
+      }
+    */
+  }
 }
 
@@ -464,18 +471,18 @@
 void
 KdTree::SortSubdivisionCandidates(
-			    KdLeaf *node,
-			    const int axis
-			    )
-{
-	CLEAR_CONTAINER(*splitCandidates);
-	//splitCandidates->clear();
-
-    int requestedSize = 2*(int)node->mObjects.size();
-	
-	// creates a sorted split candidates array
-	if (splitCandidates->capacity() > 500000 &&
-		requestedSize < (int)(splitCandidates->capacity()/10) ) {		
-			delete splitCandidates;
-			splitCandidates = new vector<SortableEntry *>;
+				  KdLeaf *node,
+				  const int axis
+				  )
+{
+  CLEAR_CONTAINER(*splitCandidates);
+  //splitCandidates->clear();
+  
+  int requestedSize = 2*(int)node->mObjects.size();
+  
+  // creates a sorted split candidates array
+  if (splitCandidates->capacity() > 500000 &&
+      requestedSize < (int)(splitCandidates->capacity()/10) ) {		
+    delete splitCandidates;
+    splitCandidates = new vector<SortableEntry *>;
   }
   
@@ -487,15 +494,15 @@
       mi++) 
   {
-	  AxisAlignedBox3 box = (*mi)->GetBox();
-
-	  splitCandidates->push_back(new SortableEntry(SortableEntry::BOX_MIN,
-								 box.Min(axis),
-								 *mi)
-								 );
+    AxisAlignedBox3 box = (*mi)->GetBox();
+
+    splitCandidates->push_back(new SortableEntry(SortableEntry::BOX_MIN,
+						 box.Min(axis),
+						 *mi)
+			       );
     
-      splitCandidates->push_back(new SortableEntry(SortableEntry::BOX_MAX,
-								 box.Max(axis),
-								 *mi)
-								 );
+    splitCandidates->push_back(new SortableEntry(SortableEntry::BOX_MAX,
+						 box.Max(axis),
+						 *mi)
+			       );
   }
   
@@ -506,11 +513,11 @@
 float
 KdTree::BestCostRatio(
-					  KdLeaf *node,
-					  const AxisAlignedBox3 &box,
-					  const int axis,
-					  float &position,
-					  int &objectsBack,
-					  int &objectsFront
-					  )
+		      KdLeaf *node,
+		      const AxisAlignedBox3 &box,
+		      const int axis,
+		      float &position,
+		      int &objectsBack,
+		      int &objectsFront
+		      )
 {
 
@@ -531,5 +538,5 @@
   
   if (nodeId < 100)
-	costStream.open(filename);
+    costStream.open(filename);
 
 #endif
@@ -577,5 +584,5 @@
       intersectionsRight -= (*ci)->intersectable->IntersectionComplexity();
       break;
-    }
+    } // switch
 
     if ((*ci)->value > minBand && (*ci)->value < maxBand) {
@@ -587,7 +594,7 @@
       float sum;
       if (mSahUseFaces)
-		sum = intersectionsLeft*lbox.SurfaceArea() + intersectionsRight*rbox.SurfaceArea();
+	sum = intersectionsLeft*lbox.SurfaceArea() + intersectionsRight*rbox.SurfaceArea();
       else
-		sum = objectsLeft*lbox.SurfaceArea() + objectsRight*rbox.SurfaceArea();
+	sum = objectsLeft*lbox.SurfaceArea() + objectsRight*rbox.SurfaceArea();
       
       //      cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
@@ -595,21 +602,21 @@
 
 #if DEBUG_COST
-  if (nodeId < 100) {
+      if (nodeId < 100) {
 	float oldCost = mSahUseFaces ? totalIntersections : node->mObjects.size();
 	float newCost = mCt_div_ci + sum/boxArea;
 	float ratio = newCost/oldCost;
 	costStream<<(*ci)->value<<" "<<ratio<<endl;
-  }
+      }
 #endif
-	  
+      
       if (sum < minSum) {
-		minSum = sum;
-		position = (*ci)->value;
-		
-		objectsBack = objectsLeft;
-		objectsFront = objectsRight;
-      }
-    }
-  }
+	minSum = sum;
+	position = (*ci)->value;
+	
+	objectsBack = objectsLeft;
+	objectsFront = objectsRight;
+      }
+    }
+  } // for ci
   
   float oldCost = mSahUseFaces ? totalIntersections : node->mObjects.size();
@@ -627,6 +634,6 @@
 int
 KdTree::CastRay(
-				Ray &ray
-				)
+		Ray &ray
+		)
 {
   
@@ -666,25 +673,27 @@
 
       if (entp[axis] <= position) {
-		if (extp[axis] <= position) {
-		  node = in->mBack;
-		  // cases N1,N2,N3,P5,Z2,Z3
-		  continue;
-		} else {
-		  // case N4
-		  node = in->mBack;
-		  farChild = in->mFront;
-		}
+	if (extp[axis] <= position) {
+	  node = in->mBack;
+	  // cases N1,N2,N3,P5,Z2,Z3
+	  continue;
+	}
+	else {
+	  // case N4
+	  node = in->mBack;
+	  farChild = in->mFront;
+	}
       }
       else {
-		if (position <= extp[axis]) {
-		  node = in->mFront;
-		  // cases P1,P2,P3,N5,Z1
-		  continue;
-		} else {
-		  node = in->mFront;
-		  farChild = in->mBack;
-		  // case P4
-		}
-	  }
+	if (position <= extp[axis]) {
+	  node = in->mFront;
+	  // cases P1,P2,P3,N5,Z1
+	  continue;
+	}
+	else {
+	  node = in->mFront;
+	  farChild = in->mBack;
+	  // case P4
+	}
+      }
       // $$ modification 3.5.2004 - hints from Kamil Ghais
       // case N4 or P4
@@ -693,54 +702,55 @@
       extp = ray.GetLoc() + ray.GetDir()*tdist;
       maxt = tdist;
-	} else {
-	  // compute intersection with all objects in this leaf
-	  KdLeaf *leaf = (KdLeaf *) node;
-	  if (ray.mFlags & Ray::STORE_KDLEAVES)
-		ray.kdLeaves.push_back(leaf);
+    }
+    else {
+      // compute intersection with all objects in this leaf
+      KdLeaf *leaf = (KdLeaf *) node;
+      if (ray.mFlags & Ray::STORE_KDLEAVES)
+	ray.kdLeaves.push_back(leaf);
 	  
-	  ObjectContainer::const_iterator mi;
-	  for ( mi = leaf->mObjects.begin();
-			mi != leaf->mObjects.end();
-			mi++) {
-		Intersectable *object = *mi;
-		if (!object->Mailed() ) {
-		  object->Mail();
-		  if (ray.mFlags & Ray::STORE_TESTED_OBJECTS)
+      ObjectContainer::const_iterator mi;
+      for ( mi = leaf->mObjects.begin();
+	    mi != leaf->mObjects.end();
+	    mi++) {
+	Intersectable *object = *mi;
+	if (!object->Mailed() ) {
+	  object->Mail();
+	  if (ray.mFlags & Ray::STORE_TESTED_OBJECTS)
 			ray.testedObjects.push_back(object);
 		  
-		  static int oi=1;
-		  if (MeshDebug) 
-			cout<<"Object "<<oi++;
-		  
-		  hits += object->CastRay(ray);
-		  
-		  if (MeshDebug) {
-			if (!ray.intersections.empty()) 
-			  cout<<"nearest t="<<ray.intersections[0].mT<<endl;
-			else
-			  cout<<"nearest t=-INF"<<endl;
-		  }	  
-		}
-	  }
+	  static int oi=1;
+	  if (MeshDebug) 
+	    cout<<"Object "<<oi++;
 	  
-	  if (hits && ray.GetType() == Ray::LOCAL_RAY)
-		if (ray.intersections[0].mT <= maxt)
-		  break;
+	  hits += object->CastRay(ray);
 	  
-	  // get the next node from the stack
-	  if (tStack.empty())
-		break;
+	  if (MeshDebug) {
+	    if (!ray.intersections.empty()) 
+	      cout<<"nearest t="<<ray.intersections[0].mT<<endl;
+	    else
+	      cout<<"nearest t=-INF"<<endl;
+	  }	  
+	}
+      }
 	  
-	  entp = extp;
-	  mint = maxt;
-	  if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
-		break;
-	  
-	  RayTraversalData &s  = tStack.top();
-	  node = s.mNode;
-	  extp = s.mExitPoint;
-	  maxt = s.mMaxT;
-	  tStack.pop();
-	}
+      if (hits && ray.GetType() == Ray::LOCAL_RAY)
+	if (ray.intersections[0].mT <= maxt)
+	  break;
+      
+      // get the next node from the stack
+      if (tStack.empty())
+	break;
+      
+      entp = extp;
+      mint = maxt;
+      if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
+	break;
+      
+      RayTraversalData &s  = tStack.top();
+      node = s.mNode;
+      extp = s.mExitPoint;
+      maxt = s.mMaxT;
+      tStack.pop();
+    }
   }
   return hits;
@@ -748,110 +758,109 @@
 
 int KdTree::CastLineSegment(const Vector3 &origin,
-							const Vector3 &termination,
-							ViewCellContainer &viewcells)
-{
-	int hits = 0;
-
-	float mint = 0.0f, maxt = 1.0f;
-	const Vector3 dir = termination - origin;
-
-	stack<RayTraversalData> tStack;
-
-	Intersectable::NewMail();
-
-	//maxt += Limits::Threshold;
-
-	Vector3 entp = origin;
-	Vector3 extp = termination;
-
-	KdNode *node = mRoot;
-	KdNode *farChild;
-
-	float position;
-	int axis;
-
-	while (1)
+			    const Vector3 &termination,
+			    ViewCellContainer &viewcells)
+{
+  int hits = 0;
+
+  float mint = 0.0f, maxt = 1.0f;
+  const Vector3 dir = termination - origin;
+  
+  stack<RayTraversalData> tStack;
+  
+  Intersectable::NewMail();
+  
+  //maxt += Limits::Threshold;
+  
+  Vector3 entp = origin;
+  Vector3 extp = termination;
+  
+  KdNode *node = mRoot;
+  KdNode *farChild;
+  
+  float position;
+  int axis;
+
+  while (1)
+  {
+    if (!node->IsLeaf())
+    {
+      KdInterior *in = static_cast<KdInterior *>(node);
+      position = in->mPosition;
+      axis = in->mAxis;
+      
+      if (entp[axis] <= position)
+      {
+	if (extp[axis] <= position)
 	{
-		if (!node->IsLeaf())
-		{
-			KdInterior *in = static_cast<KdInterior *>(node);
-			position = in->mPosition;
-			axis = in->mAxis;
-
-			if (entp[axis] <= position)
-			{
-				if (extp[axis] <= position)
-				{
-					node = in->mBack;
-					// cases N1,N2,N3,P5,Z2,Z3
-					continue;
-				} 
-				else
-				{
-					// case N4
-					node = in->mBack;
-					farChild = in->mFront;
-				}
-			}
-			else
-			{
-				if (position <= extp[axis])
-				{
-					node = in->mFront;
-					// cases P1,P2,P3,N5,Z1
-					continue;
-				}
-				else
-				{
-					node = in->mFront;
-					farChild = in->mBack;
-					// case P4
-				}
-			}
-
- 			// $$ modification 3.5.2004 - hints from Kamil Ghais
-			// case N4 or P4
-			float tdist = (position - origin[axis]) / dir[axis];
-			//tStack.push(RayTraversalData(farChild, extp, maxt)); //TODO
-			extp = origin + dir * tdist;
-			maxt = tdist;
-		}
-		else
-		{
-			// compute intersection with all objects in this leaf
-			KdLeaf *leaf = static_cast<KdLeaf *>(node);
-
-			// add view cell to intersections
-			ViewCell *vc = leaf->mViewCell;
-
-			if (!vc->Mailed())
-			{
-				vc->Mail();
-				viewcells.push_back(vc);
-				++ hits;
-			}
-
-			// get the next node from the stack
-			if (tStack.empty())
-				break;
-
-			entp = extp;
-			mint = maxt;
-			
-			RayTraversalData &s  = tStack.top();
-			node = s.mNode;
-			extp = s.mExitPoint;
-			maxt = s.mMaxT;
-			tStack.pop();
-		}
-	}
-
-	return hits;
+	  node = in->mBack;
+	  // cases N1,N2,N3,P5,Z2,Z3
+	  continue;
+	} 
+	else
+	{
+	  // case N4
+	  node = in->mBack;
+	  farChild = in->mFront;
+	}
+      }
+      else
+      {
+	if (position <= extp[axis])
+	{
+	  node = in->mFront;
+	  // cases P1,P2,P3,N5,Z1
+	  continue;
+	}
+	else
+	{
+	  node = in->mFront;
+	  farChild = in->mBack;
+	  // case P4
+	}
+      }
+      
+      // $$ modification 3.5.2004 - hints from Kamil Ghais
+      // case N4 or P4
+      float tdist = (position - origin[axis]) / dir[axis];
+      //tStack.push(RayTraversalData(farChild, extp, maxt)); //TODO
+      extp = origin + dir * tdist;
+      maxt = tdist;
+    }
+    else
+    {
+      // compute intersection with all objects in this leaf
+      KdLeaf *leaf = static_cast<KdLeaf *>(node);
+      
+      // add view cell to intersections
+      ViewCell *vc = leaf->mViewCell;
+      
+      if (!vc->Mailed())
+      {
+	vc->Mail();
+	viewcells.push_back(vc);
+	++ hits;
+      }
+      
+      // get the next node from the stack
+      if (tStack.empty())
+	break;
+      
+      entp = extp;
+      mint = maxt;
+      
+      RayTraversalData &s  = tStack.top();
+      node = s.mNode;
+      extp = s.mExitPoint;
+      maxt = s.mMaxT;
+      tStack.pop();
+    }
+  }
+  return hits;
 }
 
 void
 KdTree::CollectKdObjects(const AxisAlignedBox3 &box,
-						 ObjectContainer &objects
-						 )
+			 ObjectContainer &objects
+			)
 {
   stack<KdNode *> nodeStack;
@@ -862,25 +871,26 @@
     KdNode *node = nodeStack.top();
     nodeStack.pop();
-	if (node->IsLeaf() || node->mPvsTermination == 1)  {
-	  Intersectable *object = GetOrCreateKdIntersectable(node);
-	  if (!node->Mailed()) {
-		node->Mail();
-		objects.push_back(object);
-	  }
-	} else {
+    if (node->IsLeaf() || node->mPvsTermination == 1)  {
+      Intersectable *object = GetOrCreateKdIntersectable(node);
+      if (!node->Mailed()) {
+	node->Mail();
+	objects.push_back(object);
+      }
+    }
+    else {
       KdInterior *interior = (KdInterior *)node;
 	  
-	  if ( box.Max()[interior->mAxis] > interior->mPosition )
-		nodeStack.push(interior->mFront);
-	  
-	  if (box.Min()[interior->mAxis] < interior->mPosition)
-		nodeStack.push(interior->mBack);
-    }
-  }
+      if ( box.Max()[interior->mAxis] > interior->mPosition )
+	nodeStack.push(interior->mFront);
+      
+      if (box.Min()[interior->mAxis] < interior->mPosition)
+	nodeStack.push(interior->mBack);
+    }
+  } // while
 }
 
 void
 KdTree::CollectObjects(const AxisAlignedBox3 &box,
-					   ObjectContainer &objects)
+		       ObjectContainer &objects)
 {
   stack<KdNode *> nodeStack;
@@ -894,18 +904,18 @@
       KdLeaf *leaf = (KdLeaf *)node;
       for (int j=0; j < leaf->mObjects.size(); j++) {
-		Intersectable *object = leaf->mObjects[j];
-		if (!object->Mailed() && Overlap(box, object->GetBox())) {
-		  object->Mail();
-		  objects.push_back(object);
-		}
+	Intersectable *object = leaf->mObjects[j];
+	if (!object->Mailed() && Overlap(box, object->GetBox())) {
+	  object->Mail();
+	  objects.push_back(object);
+	}
       }
     } else {
       KdInterior *interior = (KdInterior *)node;
 
-	  if ( box.Max()[interior->mAxis] > interior->mPosition )
-		nodeStack.push(interior->mFront);
- 
-	  if (box.Min()[interior->mAxis] < interior->mPosition)
-		nodeStack.push(interior->mBack);
+      if ( box.Max()[interior->mAxis] > interior->mPosition )
+	nodeStack.push(interior->mFront);
+      
+      if (box.Min()[interior->mAxis] < interior->mPosition)
+	nodeStack.push(interior->mBack);
     }
   }
@@ -925,9 +935,9 @@
       KdLeaf *leaf = (KdLeaf *)node;
       for (int j=0; j < leaf->mObjects.size(); j++) {
-				Intersectable *object = leaf->mObjects[j];
-				if (!object->Mailed()) {
-					object->Mail();
-					objects.push_back(object);
-				}
+	Intersectable *object = leaf->mObjects[j];
+	if (!object->Mailed()) {
+	  object->Mail();
+	  objects.push_back(object);
+	}
       }
     } else {
@@ -942,6 +952,6 @@
 KdNode *
 KdTree::FindRandomNeighbor(KdNode *n,
-						   bool onlyUnmailed
-						   )
+			   bool onlyUnmailed
+			   )
 {
   stack<KdNode *> nodeStack;
@@ -997,16 +1007,18 @@
       if ( node != n && (!onlyUnmailed || !node->Mailed()) ) 
 	neighbors.push_back(node);
-    } else {
+    }
+    else {
       KdInterior *interior = (KdInterior *)node;
       if (interior->mPosition > box.Max(interior->mAxis))
-				nodeStack.push(interior->mBack);
-      else
-				if (interior->mPosition < box.Min(interior->mAxis))
-					nodeStack.push(interior->mFront);
-				else {
-					// random decision
-					nodeStack.push(interior->mBack);
-					nodeStack.push(interior->mFront);
-				}
+	nodeStack.push(interior->mBack);
+      else {
+	if (interior->mPosition < box.Min(interior->mAxis))
+	  nodeStack.push(interior->mFront);
+	else {
+	  // random decision
+	  nodeStack.push(interior->mBack);
+	  nodeStack.push(interior->mFront);
+	}
+      }
     }
   }
@@ -1181,53 +1193,53 @@
 void KdTree::ExportBinLeaf(OUT_STREAM &stream, KdLeaf *leaf)
 {
-	ObjectContainer::const_iterator it, it_end = leaf->mObjects.end();
+  ObjectContainer::const_iterator it, it_end = leaf->mObjects.end();
+  
+  int type = TYPE_LEAF;
+  int size = (int)leaf->mObjects.size();
+  
+  stream.write(reinterpret_cast<char *>(&type), sizeof(int));
+  stream.write(reinterpret_cast<char *>(&size), sizeof(int));
+  
+  for (it = leaf->mObjects.begin(); it != it_end; ++ it)
+    {	
+      Intersectable *obj = *it;
+      int id = obj->mId;		
+      
+      //stream.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
+      stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+    }
+}
+
+
+KdLeaf *KdTree::ImportBinLeaf(IN_STREAM &stream, 
+			      KdInterior *parent,
+			      const ObjectContainer &objects)
+{
+  int leafId = TYPE_LEAF;
+  int objId = leafId;
+  int size;
+  
+  stream.read(reinterpret_cast<char *>(&size), sizeof(int));
+  KdLeaf *leaf = new KdLeaf(parent, size);
+
+  MeshInstance dummyInst(NULL);
 	
-	int type = TYPE_LEAF;
-	int size = (int)leaf->mObjects.size();
-
-	stream.write(reinterpret_cast<char *>(&type), sizeof(int));
-	stream.write(reinterpret_cast<char *>(&size), sizeof(int));
-
-	for (it = leaf->mObjects.begin(); it != it_end; ++ it)
-	{	
-		Intersectable *obj = *it;
-		int id = obj->mId;		
-	
-		//stream.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
-		stream.write(reinterpret_cast<char *>(&id), sizeof(int));
-    }
-}
-
-
-KdLeaf *KdTree::ImportBinLeaf(IN_STREAM &stream, 
-							  KdInterior *parent,
-							  const ObjectContainer &objects)
-{
-	int leafId = TYPE_LEAF;
-	int objId = leafId;
-	int size;
-
-	stream.read(reinterpret_cast<char *>(&size), sizeof(int));
-	KdLeaf *leaf = new KdLeaf(parent, size);
-
-	MeshInstance dummyInst(NULL);
-	
-	// read object ids
-	// note: this can also be done geometrically
-	for (int i = 0; i < size; ++ i)
-	{	
-		stream.read(reinterpret_cast<char *>(&objId), sizeof(int));
-		dummyInst.SetId(objId);
-
-		ObjectContainer::const_iterator oit =
-			lower_bound(objects.begin(), objects.end(), (Intersectable *)&dummyInst, ilt);
-								
-		if ((oit != objects.end()) && ((*oit)->GetId() == objId))
-			leaf->mObjects.push_back(*oit);
-		else
-			Debug << "error: object with id " << objId << " does not exist" << endl;
-	}
-
-	return leaf;
+  // read object ids
+  // note: this can also be done geometrically
+  for (int i = 0; i < size; ++ i)
+    {	
+      stream.read(reinterpret_cast<char *>(&objId), sizeof(int));
+      dummyInst.SetId(objId);
+      
+      ObjectContainer::const_iterator oit =
+	lower_bound(objects.begin(), objects.end(), (Intersectable *)&dummyInst, ilt);
+      
+      if ((oit != objects.end()) && ((*oit)->GetId() == objId))
+	leaf->mObjects.push_back(*oit);
+      else
+	Debug << "error: object with id " << objId << " does not exist" << endl;
+    }
+  
+  return leaf;
 }
 
@@ -1319,82 +1331,82 @@
 bool KdTree::ImportBinTree(const string &filename, ObjectContainer &objects)
 {
-	// export binary version of mesh
-	queue<TraversalData> tStack;
-	IN_STREAM stream(filename.c_str(), IN_BIN_MODE);
-
-	if (!stream.is_open()) return false;
-
-	// sort objects by their id
-//	if (!is_sorted(objects.begin(), objects.end(), ilt))
-		sort(objects.begin(), objects.end(), ilt);
-
-	mBox.Initialize();
-	ObjectContainer::const_iterator oit, oit_end = objects.end();
-
-	///////////////////////////
-	//-- compute bounding box of object space
-
-    for (oit = objects.begin(); oit != oit_end; ++ oit)
-	{
-		const AxisAlignedBox3 box = (*oit)->GetBox();
-		mBox.Include(box);
-	}
-
-	// hack: we make a new root
-	DEL_PTR(mRoot);
-  
-	mRoot = ImportNextNode(stream, NULL, objects);
-
-	tStack.push(TraversalData(mRoot, mBox, 0));
-	mStat.Reset();
-	mStat.nodes = 1;
-
-	while(!tStack.empty())
-	{
-		TraversalData tData = tStack.front();
-		tStack.pop();
-
-		KdNode *node = tData.mNode;
-
-		if (!node->IsLeaf())
-		{
-			mStat.nodes += 2;
-
-			//Debug << "i" ;
-			KdInterior *interior = static_cast<KdInterior *>(node);
-			interior->mBox = tData.mBox;
-
-            KdNode *front = ImportNextNode(stream, interior, objects);
-			KdNode *back = ImportNextNode(stream, interior, objects);
-	
-			interior->SetupChildLinks(back, front);
-
-			++ mStat.splits[interior->mAxis];
-
-			// compute new bounding box
-			AxisAlignedBox3 frontBox, backBox;
-			
-			tData.mBox.Split(interior->mAxis, 
-							 interior->mPosition, 
-							 frontBox, 
-							 backBox);
-
-			tStack.push(TraversalData(front, frontBox, tData.mDepth + 1));			
-			tStack.push(TraversalData(back, backBox, tData.mDepth + 1));
-		}
-		else
-		{
-			EvaluateLeafStats(tData);
-			//cout << "l";
-		}
-	}
-
-	float area = GetBox().SurfaceArea()*mKdPvsArea;
-	
-	SetPvsTerminationNodes(area);
-
-	Debug << mStat << endl;
-
-	return true;
+  // export binary version of mesh
+  queue<TraversalData> tStack;
+  IN_STREAM stream(filename.c_str(), IN_BIN_MODE);
+  
+  if (!stream.is_open()) return false;
+  
+  // sort objects by their id
+  //	if (!is_sorted(objects.begin(), objects.end(), ilt))
+  sort(objects.begin(), objects.end(), ilt);
+  
+  mBox.Initialize();
+  ObjectContainer::const_iterator oit, oit_end = objects.end();
+  
+  ///////////////////////////
+  //-- compute bounding box of object space
+  
+  for (oit = objects.begin(); oit != oit_end; ++ oit)
+  {
+    const AxisAlignedBox3 box = (*oit)->GetBox();
+    mBox.Include(box);
+  }
+  
+  // hack: we make a new root
+  DEL_PTR(mRoot);
+  
+  mRoot = ImportNextNode(stream, NULL, objects);
+  
+  tStack.push(TraversalData(mRoot, mBox, 0));
+  mStat.Reset();
+  mStat.nodes = 1;
+  
+  while(!tStack.empty())
+  {
+    TraversalData tData = tStack.front();
+    tStack.pop();
+    
+    KdNode *node = tData.mNode;
+    
+    if (!node->IsLeaf())
+    {
+      mStat.nodes += 2;
+      
+      //Debug << "i" ;
+      KdInterior *interior = static_cast<KdInterior *>(node);
+      interior->mBox = tData.mBox;
+      
+      KdNode *front = ImportNextNode(stream, interior, objects);
+      KdNode *back = ImportNextNode(stream, interior, objects);
+      
+      interior->SetupChildLinks(back, front);
+      
+      ++ mStat.splits[interior->mAxis];
+      
+      // compute new bounding box
+      AxisAlignedBox3 frontBox, backBox;
+      
+      tData.mBox.Split(interior->mAxis, 
+		       interior->mPosition, 
+		       frontBox, 
+		       backBox);
+      
+      tStack.push(TraversalData(front, frontBox, tData.mDepth + 1));			
+      tStack.push(TraversalData(back, backBox, tData.mDepth + 1));
+    }
+    else
+    {
+      EvaluateLeafStats(tData);
+      //cout << "l";
+    }
+  }
+
+  float area = GetBox().SurfaceArea()*mKdPvsArea;
+  
+  SetPvsTerminationNodes(area);
+  
+  Debug << mStat << endl;
+  
+  return true;
 }
 
@@ -1403,6 +1415,6 @@
 KdTree::GetOrCreateKdIntersectable(KdNode *node)
 {
-	if (node == NULL)
-		return NULL;
+  if (node == NULL)
+    return NULL;
 
 	if (node->mIntersectable == NULL) 
@@ -1415,18 +1427,16 @@
 		mKdIntersectables.push_back(kdObj);
 		kdObj->SetId(id);
-
 #ifdef USE_BIT_PVS
-		// hack: for kd pvs the kd intersecables are the pvs objects
-		ObjectPvsIterator::sObjects.push_back(kdObj);
+    // hack: for kd pvs the kd intersecables are the pvs objects
+    ObjectPvsIterator::sObjects.push_back(kdObj);
 #endif
-	}
-
-	return node->mIntersectable;
+  }
+
+  return node->mIntersectable;
 }
 
 
 void
-KdTree::SetPvsTerminationNodes(
-							   const float maxArea)
+KdTree::SetPvsTerminationNodes(const float maxArea)
 {
   stack<KdNode *> nodeStack;
@@ -1440,28 +1450,28 @@
   while (!nodeStack.empty()) {
     KdNode *node = nodeStack.top();
-	nodeStack.pop();
-
-	node->mPvsTermination = 0;
-	if (node->IsLeaf() || (GetSurfaceArea(node) <= maxArea) ) {
-	  area += GetSurfaceArea(node);
-	  radius += GetBox(node).Radius();
-	  nodes++;
-	  node->mPvsTermination = 1;
-	  // create dummy kd intersectable
-	  Intersectable *object = GetOrCreateKdIntersectable(node);
-	} else {
-	  KdInterior *interior = (KdInterior *)node;
-	  nodeStack.push(interior->mFront);
-	  nodeStack.push(interior->mBack);
-    }
-  }
-
+    nodeStack.pop();
+
+    node->mPvsTermination = 0;
+    if (node->IsLeaf() || (GetSurfaceArea(node) <= maxArea) ) {
+      area += GetSurfaceArea(node);
+      radius += GetBox(node).Radius();
+      nodes++;
+      node->mPvsTermination = 1;
+      // create dummy kd intersectable
+      Intersectable *object = GetOrCreateKdIntersectable(node);
+    } else {
+      KdInterior *interior = (KdInterior *)node;
+      nodeStack.push(interior->mFront);
+      nodeStack.push(interior->mBack);
+    }
+  }
+  
   if (nodes) {
-	area /= nodes;
-	radius /= nodes;
-	cout<<"Number of nodes for storing in the PVS = "<<nodes<<endl;
-	cout<<"Average rel. node area = "<<area/GetSurfaceArea(mRoot)<<endl;
-	cout<<"Average rel. node radius = "<<radius/GetBox(mRoot).Radius()<<endl;
-	cout<<"Avg node radius = "<<radius<<endl;
+    area /= nodes;
+    radius /= nodes;
+    cout<<"Number of nodes for storing in the PVS = "<<nodes<<endl;
+    cout<<"Average rel. node area = "<<area/GetSurfaceArea(mRoot)<<endl;
+    cout<<"Average rel. node radius = "<<radius/GetBox(mRoot).Radius()<<endl;
+    cout<<"Avg node radius = "<<radius<<endl;
   }
   
@@ -1474,9 +1484,9 @@
   
   while (node->mPvsTermination == 0 ) {
-	KdInterior *inter = (KdInterior *)node;
-	if (point[inter->mAxis] < inter->mPosition)
-	  node = inter->mBack;
-	else
-	  node = inter->mFront;
+    KdInterior *inter = (KdInterior *)node;
+    if (point[inter->mAxis] < inter->mPosition)
+      node = inter->mBack;
+    else
+      node = inter->mFront;
   }
   
@@ -1491,9 +1501,9 @@
   
   while (!node->IsLeaf() && (GetSurfaceArea(node) > maxArea) ) {
-	KdInterior *inter = (KdInterior *)node;
-	if (point[inter->mAxis] < inter->mPosition)
-	  node = inter->mBack;
-	else
-	  node = inter->mFront;
+    KdInterior *inter = (KdInterior *)node;
+    if (point[inter->mAxis] < inter->mPosition)
+      node = inter->mBack;
+    else
+      node = inter->mFront;
   }
   
@@ -1503,37 +1513,37 @@
 
 void KdTree::GetBoxIntersections(const AxisAlignedBox3 &box,
-								 vector<KdLeaf *> &leaves)
-{
-	stack<KdNode *> tStack;
-
-	tStack.push(mRoot);
-
-	while (!tStack.empty())
+				 vector<KdLeaf *> &leaves)
+{
+  stack<KdNode *> tStack;
+  
+  tStack.push(mRoot);
+  
+  while (!tStack.empty())
+    {
+      KdNode *node = tStack.top();
+      tStack.pop();
+      
+      if (node->IsLeaf())
 	{
-		KdNode *node = tStack.top();
-		tStack.pop();
-		
-		if (node->IsLeaf())
-		{
-			leaves.push_back(static_cast<KdLeaf *>(node));
-		}
-		else // interior
-		{
-			KdInterior *interior = static_cast<KdInterior *>(node);
-
-			if (box.Max(interior->mAxis) >= interior->mPosition)
-			{
-				tStack.push(interior->mFront);
-			}
-
-			if (box.Min(interior->mAxis) < interior->mPosition)
-			{
-				tStack.push(interior->mBack);
-			}
-		}
-	}
-}
-
-
-
-}
+	  leaves.push_back(static_cast<KdLeaf *>(node));
+	}
+      else // interior
+	{
+	  KdInterior *interior = static_cast<KdInterior *>(node);
+	  
+	  if (box.Max(interior->mAxis) >= interior->mPosition)
+	    {
+	      tStack.push(interior->mFront);
+	    }
+	  
+	  if (box.Min(interior->mAxis) < interior->mPosition)
+	    {
+	      tStack.push(interior->mBack);
+	    }
+	}
+    }
+}
+
+
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/DifferenceSampling.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/DifferenceSampling.cpp	(revision 2560)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/DifferenceSampling.cpp	(revision 2575)
@@ -1,2 +1,3 @@
+
 #include "SamplingStrategy.h"
 #include "Intersectable.h"
@@ -5,6 +6,7 @@
 #include "ViewCellsManager.h"
 #include "Preprocessor.h"
+#ifdef PERFTIMER  
 #include "Timer/PerfTimer.h"
-
+#endif
 
 #ifdef GTP_INTERNAL
@@ -12,6 +14,8 @@
 #endif
 
+
+#ifdef PERFTIMER  
 PerfTimer sFilterTimer;
-
+#endif
 
 namespace GtpVisibilityPreprocessor {
@@ -63,6 +67,9 @@
 	ObjectPvs filteredPvs;
 
+	
+#ifdef PERFTIMER  
 	sFilterTimer.Entry();
-    
+#endif
+	
 	PvsFilterStatistics pvsStats = mPreprocessor.
 		mViewCellsManager->ApplyFilter2(vc, 
@@ -71,6 +78,8 @@
 										filteredPvs);
 
+#ifdef PERFTIMER  
 	sFilterTimer.Exit();
-
+#endif
+	
 	//mDifferencePvs.Clear(false);
 	//mDifferencePvs.Reserve(filteredPvs.GetSize());
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.cpp	(revision 2227)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Halton.cpp	(revision 2575)
@@ -1,5 +1,7 @@
 #include "Halton.h"
+
+#ifdef PERFTIMER  
 #include "Timer/PerfTimer.h"
-
+#endif
 
 #define PREGENERATE_HALTON 0
@@ -7,6 +9,9 @@
 namespace GtpVisibilityPreprocessor {
 
+  
+#ifdef PERFTIMER  
 PerfTimer haltonTimer;
-
+#endif
+  
 // global halton generator
 
@@ -14,12 +19,8 @@
   float Halton2::_invBases[2];
 
-  float Halton<1>::_invBases[1];
-  float Halton<2>::_invBases[2];
-  float Halton<3>::_invBases[3];
-  float Halton<4>::_invBases[4];
-  float Halton<5>::_invBases[5];
-  float Halton<6>::_invBases[6];
+  //float Halton<6>::_invBases[6];
   
-
+  template<int T> float Halton<T>::_invBases[T];
+  
   Halton<1> dummmyHalton1(true);
   Halton<2> dummmyHalton2(true);
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.cpp	(revision 1883)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Vector3.cpp	(revision 2575)
@@ -2,6 +2,5 @@
 #include "Vector3.h"
 #include "Halton.h"
-#include "float.h"
-
+#include <float.h>
 
 namespace GtpVisibilityPreprocessor {
@@ -316,7 +315,11 @@
 bool Vector3::CheckValidity() const
 {
-	return !(_isnan(x) || _isnan(y) || _isnan(z));
-	 //return ((x != x) || (y != y) || (z != z));
-}
-
-}
+#ifdef _WIN32
+  return !(_isnan(x) || _isnan(y) || _isnan(z));
+#else
+  return !(isnan(x) || isnan(y) || isnan(z));
+#endif  
+  //return ((x != x) || (y != y) || (z != z));
+}
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp	(revision 2130)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RssTree.cpp	(revision 2575)
@@ -1481,12 +1481,12 @@
 void
 RssTree::RemoveRay(VssRay *ray,
-				   vector<RssTreeLeaf *> *affectedLeaves,
-				   const bool removeAllScheduledRays
-				   )
-{
-	
-  stack<RayTraversalData> tstack;
-
-  PushRoots(tstack, RssTreeLeaf::RayInfo(ray));
+		   vector<RssTreeLeaf *> *affectedLeaves,
+		   const bool removeAllScheduledRays
+		   )
+{	
+  TstackEntry tstack;
+
+  RssTreeNode::RayInfo ri(ray);
+  PushRoots(tstack, ri);
   
   RayTraversalData data;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp	(revision 2542)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp	(revision 2575)
@@ -1,4 +1,5 @@
 #include "Triangle3.h"
 #include "Ray.h"
+#include "SimpleRay.h"
 #include "AxisAlignedBox3.h"
 #include "Containers.h"
@@ -33,98 +34,196 @@
 int
 Triangle3::CastRay(const Ray &ray,
-				   float &t,
-				   const float nearestT,
-				   Vector3 &normal) const
-{
-	//////////////
-	// specialised triangle ray casting version
-	// using ray-plane intersection
-	
-	// get triangle edge vectors and plane normal
-	const Vector3 u = mVertices[0] - mVertices[1];
-    const Vector3 v = mVertices[2] - mVertices[1];
-
-	// cross product
-    normal = Normalize(CrossProd(v, u));
-
-	// ray direction vector
-    const Vector3 dir = ray.GetDir();
-    const Vector3 w0 = ray.GetLoc() - mVertices[1];
-
-	// params to calc ray-plane intersect
-    const float a = -DotProd(normal, w0);
-    const float b = DotProd(normal, dir);
-
-	// check for division by zero
-	if (fabs(b) < Limits::Small) 
-	{   
-		// ray is parallel to triangle plane
-        if (a == 0)
-		{
-			// ray lies in triangle plane
-            return Ray::INTERSECTION_OUT_OF_LIMITS;
-		}
-        else
-		{
-			// ray disjoint from plane
-			return Ray::NO_INTERSECTION;
-		}
-    }
-
-    // distance from origin of ray to plane
-    t = a / b;
-
-    if (t <= Limits::Small) // ray goes away from triangle
-	{
+		   float &t,
+		   const float nearestT,
+		   Vector3 &normal) const
+{
+  //////////////
+  // specialised triangle ray casting version
+  // using ray-plane intersection
+  
+  // get triangle edge vectors and plane normal
+  const Vector3 u = mVertices[0] - mVertices[1];
+  const Vector3 v = mVertices[2] - mVertices[1];
+  
+  // cross product
+  normal = Normalize(CrossProd(v, u));
+  
+  // ray direction vector
+  const Vector3 dir = ray.GetDir();
+  const Vector3 w0 = ray.GetLoc() - mVertices[1];
+  
+  // params to calc ray-plane intersect
+  const float a = -DotProd(normal, w0);
+  const float b = DotProd(normal, dir);
+  
+  // check for division by zero
+  if (fabs(b) < Limits::Small) 
+    {   
+      // ray is parallel to triangle plane
+      if (a == 0)
+	{
+	  // ray lies in triangle plane
 	  return Ray::INTERSECTION_OUT_OF_LIMITS;
 	}
-	// already found nearer intersection
-	else if ((ray.GetType() == Ray::LOCAL_RAY) && (t >= nearestT))
-	{
-		return Ray::NO_INTERSECTION;
-	}
-
-	/////////////////
+      else
+	{
+	  // ray disjoint from plane
+	  return Ray::NO_INTERSECTION;
+	}
+    }
+
+  // distance from origin of ray to plane
+  t = a / b;
+  
+  if (t <= Limits::Small) // ray goes away from triangle
+    {
+      return Ray::INTERSECTION_OUT_OF_LIMITS;
+    }
+  // already found nearer intersection
+  else if ((ray.GetType() == Ray::LOCAL_RAY) && (t >= nearestT))
+    {
+      return Ray::NO_INTERSECTION;
+    }
+  
+  /////////////////
     //-- found intersection point
-	//-- check if it is inside triangle
-  
-	const Vector3 pt = ray.GetLoc() + t * dir; 
+  //-- check if it is inside triangle
+  
+  const Vector3 pt = ray.GetLoc() + t * dir; 
 #if GTP_DEBUG
-	if (!pt.CheckValidity())
-	{
-		cout << "tr: " << *this << endl;
-		cout << "v: " << pt << " t: " << t << " a: " << a << " b: " << b << " n: " << normal << endl;
-	}
+  if (!pt.CheckValidity())
+    {
+      cout << "tr: " << *this << endl;
+      cout << "v: " << pt << " t: " << t << " a: " << a << " b: " << b << " n: " << normal << endl;
+    }
 #endif
-	const Vector3 w = pt - mVertices[1];
-
-	const float uu = DotProd(u, u);
-    const float uv = DotProd(u, v);
-    const float vv = DotProd(v, v);
+  const Vector3 w = pt - mVertices[1];
+  
+  const float uu = DotProd(u, u);
+  const float uv = DotProd(u, v);
+  const float vv = DotProd(v, v);
+  
+  const float wu = DotProd(w, u);
+  const float wv = DotProd(w, v);
+  
+  
+  const float D = uv * uv - uu * vv;
+  
+  // get and test parametric coords
+  const float s = (uv * wv - vv * wu) / D;
+  
+  if ((s < -Limits::Small) || (s > 1.0f + Limits::Small)) // pt is outside triangle
+    {	
+      return Ray::NO_INTERSECTION;
+    }
+  
+  const float s2 = (uv * wu - uu * wv) / D;
+  
+  if ((s2 < -Limits::Small) || ((s + s2) > 1.0f + Limits::Small)) // pt is outside triangle
+    {	
+      return Ray::NO_INTERSECTION;
+    }
+  
+  return Ray::INTERSECTION; // I is in T
+}
+
+
+int
+Triangle3::CastSimpleRay(const SimpleRay &ray,
+			 float &t,
+			 const float nearestT) const
+{
+  //////////////
+  // specialised triangle ray casting version
+  // using ray-plane intersection
+  
+  // get triangle edge vectors and plane normal
+  const Vector3 u = mVertices[0] - mVertices[1];
+  const Vector3 v = mVertices[2] - mVertices[1];
+
+  // cross product
+  const Vector3 normal = Normalize(CrossProd(v, u));
+
+  // ray direction vector
+  const Vector3 dir = ray.mDirection;
+  const Vector3 w0 = ray.mOrigin - mVertices[1];
+
+  // params to calc ray-plane intersect
+  const float a = -DotProd(normal, w0);
+  const float b = DotProd(normal, dir);
+
+  // check for division by zero
+  if (fabs(b) < Limits::Small) 
+  {   
+    // ray is parallel to triangle plane
+    if (a == 0)
+    {
+      // ray lies in triangle plane
+      return Ray::INTERSECTION_OUT_OF_LIMITS;
+    }
+    else {
+      // ray disjoint from plane
+      return Ray::NO_INTERSECTION;
+    }
+  }
+
+  // distance from origin of ray to plane
+  t = a / b;
+
+  if (t <= Limits::Small) // ray goes away from triangle
+  {
+    return Ray::INTERSECTION_OUT_OF_LIMITS;
+  }
+
+  // already found nearer intersection
+  if (t > nearestT + 1e-5)
+  {
+    return Ray::NO_INTERSECTION;
+  }
+
+  /////////////////
+  //-- found intersection point
+  //-- check if it is inside triangle
+  
+  const Vector3 pt = ray.mOrigin + t * dir; 
+#if GTP_DEBUG
+  if (!pt.CheckValidity())
+  {
+    cout << "tr: " << *this << endl;
+    cout << "v: " << pt << " t: " << t << " a: " << a << " b: " << b << " n: " << normal << endl;
+  }
+#endif
+  const Vector3 w = pt - mVertices[1];
+
+  const float uu = DotProd(u, u);
+  const float uv = DotProd(u, v);
+  const float vv = DotProd(v, v);
     
-	const float wu = DotProd(w, u);
-    const float wv = DotProd(w, v);
-
-
-	const float D = uv * uv - uu * vv;
-
-    // get and test parametric coords
-    const float s = (uv * wv - vv * wu) / D;
-
-    if ((s < -Limits::Small) || (s > 1.0f + Limits::Small)) // pt is outside triangle
-	{	
-        return Ray::NO_INTERSECTION;
-	}
-
-	const float s2 = (uv * wu - uu * wv) / D;
-
-    if ((s2 < -Limits::Small) || ((s + s2) > 1.0f + Limits::Small)) // pt is outside triangle
-	{	
-        return Ray::NO_INTERSECTION;
-	}
-
-	return Ray::INTERSECTION; // I is in T
-}
-
+  const float wu = DotProd(w, u);
+  const float wv = DotProd(w, v);
+  
+  
+  const float D = uv * uv - uu * vv;
+  
+  // get and test parametric coords
+  const float s = (uv * wv - vv * wu) / D;
+  
+  if ((s < -Limits::Small) ||
+      (s > 1.0f + Limits::Small)) // pt is outside triangle
+  {	
+    return Ray::NO_INTERSECTION;
+  }
+
+  const float s2 = (uv * wu - uu * wv) / D;
+  
+  if ((s2 < -Limits::Small) ||
+      ((s + s2) > 1.0f + Limits::Small)) // pt is outside triangle
+  {	
+    return Ray::NO_INTERSECTION;
+  }
+  
+  return Ray::INTERSECTION; // I is in T
+}
+  
 
 AxisAlignedBox3 Triangle3::GetBoundingBox() const
@@ -137,4 +236,6 @@
 	box.Include(mVertices[2]);
 
+	box.EnlargeToMinSize();
+	
 	return box;
 }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 2547)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 2575)
@@ -709,6 +709,8 @@
 							const bool globalCriteriaMet)
 {
+#ifdef PERFTIMER  
 	mSubdivTimer.Entry();
-
+#endif
+	
 	// todo remove dynamic cast
 	VspSubdivisionCandidate *sc = 
@@ -788,6 +790,7 @@
 	}
 
+#ifdef PERFTIMER  
 	mSubdivTimer.Exit();
-
+#endif
 	return newNode;
 }
@@ -797,6 +800,8 @@
 									   bool computeSplitPlane)
 {
+#ifdef PERFTIMER  
 	mPlaneTimer.Entry();
-
+#endif
+	
 	if (computeSplitPlane)
 	{
@@ -818,7 +823,9 @@
 	}
 	
+#ifdef PERFTIMER  
 	mPlaneTimer.Exit();
 	mEvalTimer.Entry();
-
+#endif
+	
 	VspLeaf *leaf = static_cast<VspLeaf *>(splitCandidate.mParentData.mNode);
 
@@ -917,5 +924,7 @@
 
 	//cout << "vsp render cost decrease=" << renderCostDecr << endl;
+#ifdef PERFTIMER  
 	mEvalTimer.Exit();
+#endif
 }
 
@@ -948,6 +957,7 @@
 									VspTraversalData &backData)
 {
+#ifdef PERFTIMER  
 	mNodeTimer.Entry();
-	
+#endif	
 	VspLeaf *leaf = static_cast<VspLeaf *>(sc.mParentData.mNode);
 
@@ -1042,6 +1052,7 @@
 	interior->mTimeStamp = mHierarchyManager->mTimeStamp ++;
 
+#ifdef PERFTIMER  
 	mNodeTimer.Exit();
-
+#endif
 	return interior;
 }
@@ -1103,6 +1114,7 @@
 										float maxBand)
 {
+#ifdef PERFTIMER  
 	mSortTimer.Entry();
-
+#endif
 	mLocalSubdivisionCandidates->clear();
 
@@ -1154,5 +1166,7 @@
 		sort(mLocalSubdivisionCandidates->begin(), mLocalSubdivisionCandidates->end());
 
+#ifdef PERFTIMER  
 	mSortTimer.Exit();
+#endif
 }
 
@@ -1573,6 +1587,7 @@
 								float &pBack)
 {
+#ifdef PERFTIMER  
 	mSplitTimer.Entry();
-
+#endif
 	float nPosition[3];
 	float nCostRatio[3];
@@ -1670,6 +1685,7 @@
 	pBack = nProbBack[bestAxis];
 
+#ifdef PERFTIMER  
 	mSplitTimer.Exit();
-
+#endif
 	return nCostRatio[bestAxis];
 }
@@ -3158,5 +3174,7 @@
 void VspTree::GetViewCells(const VssRay &ray, ViewCellContainer &viewCells)
 {
+#ifdef PERFTIMER  
 	mViewCellsTimer.Entry();
+#endif
 	
 	static Ray hray;
@@ -3175,5 +3193,7 @@
 	CastLineSegment(origin, termination, viewCells, false);
 
+#ifdef PERFTIMER  
 	mViewCellsTimer.Exit();
+#endif
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.cpp	(revision 2105)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VssTree.cpp	(revision 2575)
@@ -1771,6 +1771,6 @@
 	
   sort(leaves.begin(),
-	   leaves.end(),
-	   GreaterContribution);
+       leaves.end(),
+       GreaterContribution);
 			 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.h	(revision 2353)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VssRay.h	(revision 2575)
@@ -151,6 +151,6 @@
   float GetOpositeDirParametrization(const int axis) const;
 
-  static float VssRay::GetDirParam(const int axis, const Vector3 dir);
-  static Vector3 VssRay::GetInvDirParam(const float alpha, const float beta);
+  static float GetDirParam(const int axis, const Vector3 dir);
+  static Vector3 GetInvDirParam(const float alpha, const float beta);
 
   float GetSize() const { return  1.0f/mInvSize; }
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 2539)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 2575)
@@ -270,10 +270,10 @@
 int
 RayCaster::ProcessRay(const SimpleRay &simpleRay,
-					  Intersection &hitA,
-					  Intersection &hitB,
-					  VssRayContainer &vssRays,
-					  const AxisAlignedBox3 &box,
-					  const bool castDoubleRay,
-					  const bool pruneInvalidRays)
+		      Intersection &hitA,
+		      Intersection &hitB,
+		      VssRayContainer &vssRays,
+		      const AxisAlignedBox3 &box,
+		      const bool castDoubleRay,
+		      const bool pruneInvalidRays)
 {
   int hits = 0;
@@ -325,4 +325,8 @@
 	Debug<<"PR2"<<flush;
 #endif
+
+	// VH - I do not know what this is for, commented out temporarily
+	// !!!!!!!!!!!!!! !!!!!!!!!!!! !!!!!!!!!!
+#if 1
 	const bool validSample = true;
 	if (validSample) {
@@ -363,11 +367,11 @@
 	{
 		VssRay *vssRay = RequestRay(
-									clipA,
-									hitB.mPoint,
-									hitA.mObject,
-									hitB.mObject,
-									mPreprocessor.mPass,
-									1.0f //simpleRay.mPdf
-									);
+					    clipA,
+					    hitB.mPoint,
+					    hitA.mObject,
+					    hitB.mObject,
+					    mPreprocessor.mPass,
+					    1.0f //simpleRay.mPdf
+					    );
 
 		if (validB)
@@ -383,5 +387,10 @@
 	  Debug<<"PR4"<<flush;
 #endif
-	}
+	} // validSample
+#else
+	// Just pass if intersected or not
+	hits = (hitA.mObject != 0) ? 1 : 0;
+	intersect = hitA;
+#endif	
 	
 	return hits;
@@ -391,23 +400,23 @@
 void
 RayCaster::CastRays(
-					SimpleRayContainer &rays,
-					VssRayContainer &vssRays,
-					const AxisAlignedBox3 &sbox,
-					const bool castDoubleRay,
-					const bool pruneInvalidRays )
-{
-	SimpleRayContainer::const_iterator rit, rit_end = rays.end();
-
-	for (rit = rays.begin(); rit != rit_end; ++ rit) {
-		
-		CastRay(
-			*rit,				
-			vssRays,
-			sbox,
-			castDoubleRay,
-			pruneInvalidRays);
-	}
-}
-
-
-}
+		    SimpleRayContainer &rays,
+		    VssRayContainer &vssRays,
+		    const AxisAlignedBox3 &sbox,
+		    const bool castDoubleRay,
+		    const bool pruneInvalidRays )
+{
+  SimpleRayContainer::const_iterator rit, rit_end = rays.end();
+  
+  for (rit = rays.begin(); rit != rit_end; ++ rit) {
+    
+    CastRay(
+	    *rit,				
+	    vssRays,
+	    sbox,
+	    castDoubleRay,
+	    pruneInvalidRays);
+	}
+}
+  
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Environment.h	(revision 2575)
@@ -17,9 +17,10 @@
 
 #include "common.h"
+#include <cstring>
+
 
 namespace GtpVisibilityPreprocessor {
 
 class Vector3;
-
 
 /// Enumeration type used to distinguish the type of the environment variable
@@ -314,6 +315,10 @@
   /// returns named option as a character string.
   bool GetStringValue(const char *name,
-					  char *value,
-					  const bool isFatal = false) const;
+		      char *value,
+		      const bool isFatal = false) const;
+
+  bool GetStringValue(const char *name,
+		      std::string &stringVariable,
+		      const bool isFatal = false) const;
   
   //@}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h	(revision 2539)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h	(revision 2575)
@@ -9,5 +9,5 @@
 #include "Ray.h"
 //#include "ObjectPvs.h"
-#include "Viewcell.h"
+#include "ViewCell.h"
 #include "VssRay.h"
 //#include "IntersectableWrapper.h"
@@ -96,6 +96,6 @@
 /** Abstract class for kd-tree node */
 class KdNode {
-public:
-  
+
+public:  
   static int sMailId;
   static int sReservedMailboxes;
@@ -109,9 +109,9 @@
  
   static void NewMail(const int reserve = 1) {
-		sMailId += sReservedMailboxes;
-		sReservedMailboxes = reserve;
-	}
-	void Mail(const int mailbox) { mMailbox = sMailId + mailbox; }
-	bool Mailed(const int mailbox) const { return mMailbox == sMailId + mailbox; }
+    sMailId += sReservedMailboxes;
+    sReservedMailboxes = reserve;
+  }
+  void Mail(const int mailbox) { mMailbox = sMailId + mailbox; }
+  bool Mailed(const int mailbox) const { return mMailbox == sMailId + mailbox; }
 
   virtual ~KdNode(){};
@@ -183,5 +183,6 @@
 public:
   KdLeaf(KdInterior *parent, const int objects):
-	  KdNode(parent), mViewCell(NULL), mVboId(-1), mIndexBufferStart(0), mIndexBufferSize(0) {
+	  KdNode(parent), mViewCell(NULL), mVboId(-1),
+	  mIndexBufferStart(0), mIndexBufferSize(0) {
     mObjects.reserve(objects);
   }
@@ -194,8 +195,8 @@
   ~KdLeaf();
 	
-	void AddPassingRay2(const Ray &ray,
-						const int objects,
-						const int viewcells
-						) {
+  void AddPassingRay2(const Ray &ray,
+		      const int objects,
+		      const int viewcells
+		      ) {
     mPassingRays.AddRay2(ray, objects, viewcells);
 		//		Debug << "adding passing ray" << endl;
@@ -246,17 +247,16 @@
     
     TraversalData(KdNode *n,
-		   const AxisAlignedBox3 &b,
-		   const int d):
+		  const AxisAlignedBox3 &b,
+		  const int d):
       mNode(n), mBox(b), mDepth(d) {}
     
 
-    bool operator<(
-				   const TraversalData &b) const {
+    bool operator<(const TraversalData &b) const {
       KdLeaf *leafa = (KdLeaf *) mNode;
       KdLeaf *leafb = (KdLeaf *) b.mNode;
       return 
-		leafa->mObjects.size()*mBox.SurfaceArea()
-		<
-		leafb->mObjects.size()*b.mBox.SurfaceArea();
+	leafa->mObjects.size()*mBox.SurfaceArea()
+	<
+	leafb->mObjects.size()*b.mBox.SurfaceArea();
     }
 
@@ -267,5 +267,5 @@
       
       bool operator()(const TraversalData a, const TraversalData b) {
-				return a.mPriority < b.mPriority;
+	return a.mPriority < b.mPriority;
       }
       
@@ -329,6 +329,6 @@
   */
   int CastLineSegment(const Vector3 &origin,
-					  const Vector3 &termination,
-					  vector<ViewCell *> &viewcells);
+		      const Vector3 &termination,
+		      vector<ViewCell *> &viewcells);
 
 
@@ -351,6 +351,6 @@
   void
   CollectKdObjects(const AxisAlignedBox3 &box,
-				   ObjectContainer &objects
-				   );
+		   ObjectContainer &objects
+		   );
 
   void
@@ -359,5 +359,5 @@
   void
   CollectObjects(const AxisAlignedBox3 &box,
-				 ObjectContainer &objects);
+		 ObjectContainer &objects);
 
   void
@@ -388,5 +388,5 @@
 
   float GetSurfaceArea(const KdNode *node) const {
-	return GetBox(node).SurfaceArea();
+    return GetBox(node).SurfaceArea();
   }
 
@@ -394,9 +394,9 @@
   KdNode *
   FindRandomNeighbor(KdNode *n,
-					 bool onlyUnmailed
-					 );
+		     bool onlyUnmailed
+		     );
   
   KdNode *
-  KdTree::GetRandomLeaf(const Plane3 &halfspace);
+  GetRandomLeaf(const Plane3 &halfspace);
 
   KdNode *
@@ -408,11 +408,11 @@
 
   void GetBoxIntersections(const AxisAlignedBox3 &box, 
-						   vector<KdLeaf *> &leaves);
+			   vector<KdLeaf *> &leaves);
 
   int
   FindNeighbors(KdNode *n,
-				vector<KdNode *> &neighbors,
-				bool onlyUnmailed
-				);
+		vector<KdNode *> &neighbors,
+		bool onlyUnmailed
+		);
 
   bool ExportBinTree(const std::string &filename);
@@ -439,6 +439,6 @@
 #if USE_FIXEDPOINT_T
 #define FIXEDPOINT_ONE 0x7FFE
-			  //			  tmax(0xFFFF)
-			  tmax(FIXEDPOINT_ONE)
+		    //			  tmax(0xFFFF)
+		    tmax(FIXEDPOINT_ONE)
 #else
       tmax(1.0f)
@@ -531,7 +531,7 @@
     
     SortableEntry() {}
-    SortableEntry(const int t, const float v, Intersectable *i):type(t),
-								value(v),
-								intersectable(i) {}
+    SortableEntry(const int t, const float v, Intersectable *i):
+      type(t), value(v), intersectable(i)
+    { }
     
     bool operator<(const SortableEntry &b) const {
@@ -561,7 +561,7 @@
   void
   SortSubdivisionCandidates(
-		      KdLeaf *node,
-		      const int axis
-		      );
+			    KdLeaf *node,
+			    const int axis
+			   );
 
   void
@@ -585,26 +585,28 @@
 	      );
 
-	/** does some post processing on the objects in the new child leaves.
-	*/
-	void ProcessMultipleRefs(KdLeaf *leaf) const;
-
-
-	//////////
-	// binary import / export
-
-	void ExportBinLeaf(OUT_STREAM  &stream, KdLeaf *leaf);
+  /** does some post processing on the objects in the new child leaves.
+   */
+  void ProcessMultipleRefs(KdLeaf *leaf) const;
+
+
+  //////////
+  // binary import / export
+  
+  void ExportBinLeaf(OUT_STREAM  &stream, KdLeaf *leaf);
 	
-	void ExportBinInterior(OUT_STREAM &stream, KdInterior *interior);
-
-	KdLeaf *ImportBinLeaf(IN_STREAM &stream, KdInterior *parent, const ObjectContainer &objects);
+  void ExportBinInterior(OUT_STREAM &stream, KdInterior *interior);
+  
+  KdLeaf *ImportBinLeaf(IN_STREAM &stream, KdInterior *parent,
+			const ObjectContainer &objects);
 	
-	KdInterior *ImportBinInterior(IN_STREAM  &stream, KdInterior *parent);
+  KdInterior *ImportBinInterior(IN_STREAM  &stream, KdInterior *parent);
+  
+  KdNode *ImportNextNode(IN_STREAM  &stream, KdInterior *parent,
+			 const ObjectContainer &objects);
 	
-	KdNode *ImportNextNode(IN_STREAM  &stream, KdInterior *parent, const ObjectContainer &objects);
-	
-	/** Adds this objects to the kd leaf objects.
-		@warning: Can corrupt the tree
-	*/
-	void InsertObjects(KdNode *node, const ObjectContainer &objects);
+  /** Adds this objects to the kd leaf objects.
+      @warning: Can corrupt the tree
+  */
+  void InsertObjects(KdNode *node, const ObjectContainer &objects);
 
   int mTermMaxNodes;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 2569)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 2575)
@@ -6,8 +6,13 @@
 
 #define NOMINMAX
+#ifdef __WINDOWS__
 #include <windows.h>
-#include <stdio.h>
+#ifdef _CRT_SET
 #include <crtdbg.h>
-
+#endif // _CRT_SET
+#endif
+#include <cstdio>
+
+#include "Camera.h"
 #include "PreprocessorFactory.h"
 #include "Parser.h"
@@ -20,4 +25,6 @@
 #include "SceneGraph.h"
 #include "GlobalLinesRenderer.h"
+#include "RayCaster.h"
+//#include "testrt.h"
 
 #include "ViewCellsManager.h"
@@ -152,9 +159,27 @@
 }
 
-
 int
 main(int argc, char **argv)
 {
-	int returnCode = 0;
+#if 0
+  // Test code by VH
+  //TestRTcamera(argc, argv);
+  //TestRTfromFile(argc, argv);
+  TestRTfromFilePackets(argc, argv);
+  return 0;
+#endif
+
+  int returnCode = 0;
+
+  //Now just call this function at the start of your program and if you're
+  //compiling in debug mode (F5), any leaks will be displayed in the Output
+  //window when the program shuts down. If you're not in debug mode this will
+  //be ignored. Use it as you will!
+  //note: from GDNet Direct [3.8.04 - 3.14.04] void detectMemoryLeaks() {
+#ifdef _CRT_SET
+  _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF);
+  _CrtSetReportMode(_CRT_ASSERT,_CRTDBG_MODE_FILE);
+  _CrtSetReportFile(_CRT_ASSERT,_CRTDBG_FILE_STDERR); 
+#endif
 
 	//Now just call this function at the start of your program and if you're
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 2539)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 2575)
@@ -209,5 +209,7 @@
 	const Vector3 cross_a_b = CrossProd(a, b);
 
-	if (SqrMagnitude(cross_a_b) <= 0.000001 * FLT_EPSILON * FLT_EPSILON) 
+#define SMALL_FLT   1e-5
+	
+	if (SqrMagnitude(cross_a_b) <= 0.0001 * SMALL_FLT * SMALL_FLT) 
 	{
 		// v0, v1 & v2 lies on a line (area == 0)
@@ -293,9 +295,10 @@
 					for (tit = triangles.begin(); tit != tit_end; ++ tit)
 					{
-						// test if it is a valid triangle
-						if (0 && !TriangleValid(*tit)) continue;
-
-						TriangleIntersectable *obj = new TriangleIntersectable(*tit);	
-						root->mGeometry.push_back(obj);
+					  // test if it is a valid triangle
+					  if (!TriangleValid(*tit))
+					    continue;
+
+					  TriangleIntersectable *obj = new TriangleIntersectable(*tit);	
+					  root->mGeometry.push_back(obj);
 					}
 				}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ResourceManager.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ResourceManager.h	(revision 2542)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ResourceManager.h	(revision 2575)
@@ -4,4 +4,8 @@
 #include <vector>
 #include <string>
+#include <iterator>
+#include <fstream>
+#include <ostream>
+#include <iostream>
 
 //#include "Containers.h"
@@ -13,4 +17,7 @@
 namespace GtpVisibilityPreprocessor {
 
+using std::iterator;
+using std::map;
+  
 
 /** Resource manager controlling loading and destroying of resources.
@@ -25,5 +32,10 @@
 template <typename T> class ResourceManager
 {
+protected:
+  typedef map<unsigned int, T* > maptype;
 
+  /// the resource container
+  maptype mEntries;
+  
 public:
 
@@ -65,10 +77,10 @@
 	T *FindEntry(const unsigned int id) const
 	{
-		std::map<unsigned int, T *>::const_iterator mit = mEntries.find(id);
+	  typename maptype::const_iterator mit = mEntries.find(id);
 
-		if (mit != mEntries.end()) 
-		{
-			return (*mit).second;
-		}
+	  if (mit != mEntries.end()) 
+	    {
+	      return (*mit).second;
+	    }
 
 		return NULL;
@@ -95,10 +107,10 @@
 	bool ExportEntries(const std::string &filename)
 	{
-		ofstream stream(filename.c_str(), ios::binary);
+	  std::ofstream stream(filename.c_str(), std::ios::binary);
 	
 		if (!stream.is_open())
 			return false;
 
-		std::map<unsigned int, T *>::const_iterator mit, mit_end = mEntries.end();
+		typename std::map<unsigned int, T *>::const_iterator mit, mit_end = mEntries.end();
 
 		for (mit = mEntries.begin(); mit != mit_end; ++ mit)
@@ -130,5 +142,5 @@
 	~ResourceManager<T>()
 	{
-		std::map<unsigned int, T *>::iterator mit, mit_end = mEntries.end();
+	  typename std::map<unsigned int, T *>::iterator mit, mit_end = mEntries.end();
 
 		for (mit = mEntries.begin(); mit != mEntries.end(); ++ mit)
@@ -152,7 +164,4 @@
 protected:
 
-	/// the resource container
-	std::map<unsigned int, T *> mEntries;
-
 private:
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h	(revision 2543)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h	(revision 2575)
@@ -21,12 +21,12 @@
 struct FaceParentInfo 
 {
-	/// intersectable
-	Intersectable *mObject;
-	/// face index
-	int mFaceIndex;
-
-	FaceParentInfo(Intersectable *obj, const int fi):
-	mObject(obj), mFaceIndex(fi)
-	{}
+  /// intersectable
+  Intersectable *mObject;
+  /// face index
+  int mFaceIndex;
+  
+  FaceParentInfo(Intersectable *obj, const int fi):
+    mObject(obj), mFaceIndex(fi)
+  {}
 };
 
@@ -89,4 +89,6 @@
 	virtual AxisAlignedBox3 GetBox() const = 0;
 	virtual int CastRay(Ray &ray) = 0;
+	virtual int CastSimpleRay(const SimpleRay &ray) = 0;
+        virtual int CastSimpleRay(const SimpleRay &ray, int indexRay) = 0;
 
 	virtual bool IsConvex() const = 0;
@@ -157,5 +159,4 @@
 	BvhLeaf *mBvhLeaf;
 
-
 protected:
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParserXerces.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParserXerces.h	(revision 2227)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParserXerces.h	(revision 2575)
@@ -8,7 +8,14 @@
 #include "Mesh.h"
 #include "BoundingBoxConverter.h"
+
+#ifdef __WINDOWS__
 #include <hash_map>
-
+#else
+#include <map>
+#endif
+
+#ifdef PERFTIMER  
 #include "Timer/PerfTimer.h"
+#endif
 
 namespace GtpVisibilityPreprocessor {
@@ -54,6 +61,9 @@
 
 
+#ifdef __WINDOWS__
 typedef stdext::hash_map<int, Intersectable *> pvs_hash;
-
+#else
+typedef std::map<int, Intersectable *> pvs_hash;
+#endif  
 
 class ViewCellsParseHandlers: public HandlerBase
@@ -158,8 +168,10 @@
   int nObjects;
   
+#ifdef PERFTIMER  
   PerfTimer mBoxTimer;
   PerfTimer mPvsTimer;
   PerfTimer mObjectTimer;
-
+#endif
+  
   pvs_hash mHashPvs;
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.cpp	(revision 2105)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/InternalRayCaster.cpp	(revision 2575)
@@ -22,11 +22,11 @@
 
 int InternalRayCaster::CastRay(const SimpleRay &simpleRay,
-							   VssRayContainer &vssRays,
-							   const AxisAlignedBox3 &box,
-							   const bool castDoubleRay,
-							   const bool pruneInvalidRays)
+			       VssRayContainer &vssRays,
+			       const AxisAlignedBox3 &box,
+			       const bool castDoubleRay,
+			       const bool pruneInvalidRays)
 {
   if (simpleRay.mType == Ray::GLOBAL_RAY)
-	  return CastGlobalRay(simpleRay, vssRays, box, pruneInvalidRays);
+    return CastGlobalRay(simpleRay, vssRays, box, pruneInvalidRays);
   
   //cout << "internal ray" << endl;
@@ -51,8 +51,8 @@
   
   if (mPreprocessor.mKdTree->CastRay(ray)) {
-	hitA.mObject = ray.intersections[0].mObject;
-	hitA.mPoint = ray.Extrap(ray.intersections[0].mT);
-	hitA.mNormal = ray.intersections[0].mNormal; 
-	//	cout << "hita: " << hitA.mPoint << " !obj: " << hitA.mObject << endl;
+    hitA.mObject = ray.intersections[0].mObject;
+    hitA.mPoint = ray.Extrap(ray.intersections[0].mT);
+    hitA.mNormal = ray.intersections[0].mNormal; 
+    //	cout << "hita: " << hitA.mPoint << " !obj: " << hitA.mObject << endl;
   }
   
@@ -61,18 +61,18 @@
   
   if (castDoubleRay && mPreprocessor.mKdTree->CastRay(ray)) {
-	hitB.mObject = ray.intersections[0].mObject;
-	hitB.mPoint = ray.Extrap(ray.intersections[0].mT);
-	hitB.mNormal = ray.intersections[0].mNormal;
+    hitB.mObject = ray.intersections[0].mObject;
+    hitB.mPoint = ray.Extrap(ray.intersections[0].mT);
+    hitB.mNormal = ray.intersections[0].mNormal;
   }
   
   return ProcessRay(
-					simpleRay,
-					hitA,
-					hitB,
-					vssRays,
-					box,
-					castDoubleRay,
-					pruneInvalidRays
-					);
+		    simpleRay,
+		    hitA,
+		    hitB,
+		    vssRays,
+		    box,
+		    castDoubleRay,
+		    pruneInvalidRays
+		    );
 }
 
@@ -80,8 +80,8 @@
 int
 InternalRayCaster::CastGlobalRay(const SimpleRay &simpleRay,
-								 VssRayContainer &vssRays,
-								 const AxisAlignedBox3 &box,
-								 const bool pruneInvalidRays
-								)
+				 VssRayContainer &vssRays,
+				 const AxisAlignedBox3 &box,
+				 const bool pruneInvalidRays
+				 )
 {
   static Ray ray;
@@ -103,23 +103,79 @@
   
   if (mPreprocessor.mKdTree->CastRay(ray)) {
-	// sort intersections
-	ray.SortIntersections();
-	//	cout<<"I="<<ray.intersections.size()<<endl;
-	
-	
-	Ray::Intersection &hit = ray.intersections[0];
-	
-	if (DotProd(hit.mNormal, ray.GetDir()) < 0) {
-	  //	  cout<<"F:"<<tmin<<" "<<hit.mT<<endl;
-	  // insert intial segment
+    // sort intersections
+    ray.SortIntersections();
+    //	cout<<"I="<<ray.intersections.size()<<endl;
+	
+	
+    Ray::Intersection &hit = ray.intersections[0];
+	
+    if (DotProd(hit.mNormal, ray.GetDir()) < 0) {
+      //	  cout<<"F:"<<tmin<<" "<<hit.mT<<endl;
+      // insert intial segment
+      vssRay = new VssRay(
+			  ray.Extrap(tmin),
+			  ray.Extrap(hit.mT),
+			  NULL,
+			  hit.mObject,
+			  mPreprocessor.mPass,
+			  1.0f //simpleRay.mPdf
+			  );
+
+      vssRay->mFlags |= VssRay::Valid;
+      vssRay->mDistribution = simpleRay.mDistribution;
+      vssRays.push_back(vssRay);
+      ++hits;
+    }
+				
+    hit = ray.intersections[ray.intersections.size()-1];
+    if (DotProd(hit.mNormal, ray.GetDir()) > 0) {
+      //	  cout<<"L:"<<tmax<<" "<<hit.mT<<endl;
+      
+      // insert termination segment
+      vssRay = new VssRay(
+			  ray.Extrap(tmax),
+			  ray.Extrap(hit.mT),
+			  NULL,
+			  hit.mObject,
+			  mPreprocessor.mPass,
+			  1.0f //simpleRay.mPdf
+			  );
+      vssRay->mFlags |= VssRay::Valid;
+      vssRay->mDistribution = simpleRay.mDistribution;
+      vssRays.push_back(vssRay);
+      ++hits;
+    }
+	
+    // insert the rest of segments
+    for (int i=0; i < ray.intersections.size() - 1; i++) {
+      Ray::Intersection &hitA = ray.intersections[i];
+      Ray::Intersection &hitB = ray.intersections[i + 1];
+      if (hitB.mT - hitA.mT > Limits::Small) {
+	if (DotProd(hitA.mNormal, ray.GetDir()) > 0 &&
+	    DotProd(hitB.mNormal, ray.GetDir()) < 0
+	    ) {
+	  
 	  vssRay = new VssRay(
-						  ray.Extrap(tmin),
-						  ray.Extrap(hit.mT),
-						  NULL,
-						  hit.mObject,
-						  mPreprocessor.mPass,
-						  1.0f //simpleRay.mPdf
-						  );
-
+			      ray.Extrap(hitA.mT),
+			      ray.Extrap(hitB.mT),
+			      hitA.mObject,
+			      hitB.mObject,
+			      mPreprocessor.mPass,
+			      1.0f //simpleRay.mPdf
+			      );
+	  vssRay->mFlags |= VssRay::Valid;
+	  vssRay->mDistribution = simpleRay.mDistribution;
+	  vssRays.push_back(vssRay);
+	  ++hits;
+	  
+	  vssRay = new VssRay(
+			      ray.Extrap(hitB.mT),
+			      ray.Extrap(hitA.mT),
+			      hitB.mObject,
+			      hitA.mObject,
+			      mPreprocessor.mPass,
+			      1.0f //simpleRay.mPdf
+			      );
+	  
 	  vssRay->mFlags |= VssRay::Valid;
 	  vssRay->mDistribution = simpleRay.mDistribution;
@@ -127,62 +183,6 @@
 	  ++hits;
 	}
-				
-	hit = ray.intersections[ray.intersections.size()-1];
-	if (DotProd(hit.mNormal, ray.GetDir()) > 0) {
-	  //	  cout<<"L:"<<tmax<<" "<<hit.mT<<endl;
-	  
-	  // insert termination segment
-	  vssRay = new VssRay(
-						  ray.Extrap(tmax),
-						  ray.Extrap(hit.mT),
-						  NULL,
-						  hit.mObject,
-						  mPreprocessor.mPass,
-						  1.0f //simpleRay.mPdf
-						  );
-	  vssRay->mFlags |= VssRay::Valid;
-	  vssRay->mDistribution = simpleRay.mDistribution;
-	  vssRays.push_back(vssRay);
-	  ++hits;
-	}
-	
-	// insert the rest of segments
-	for (int i=0; i < ray.intersections.size() - 1; i++) {
-	  Ray::Intersection &hitA = ray.intersections[i];
-	  Ray::Intersection &hitB = ray.intersections[i + 1];
-	  if (hitB.mT - hitA.mT > Limits::Small) {
-		if (DotProd(hitA.mNormal, ray.GetDir()) > 0 &&
-			DotProd(hitB.mNormal, ray.GetDir()) < 0
-			) {
-		  
-		  vssRay = new VssRay(
-							  ray.Extrap(hitA.mT),
-							  ray.Extrap(hitB.mT),
-							  hitA.mObject,
-							hitB.mObject,
-							  mPreprocessor.mPass,
-							  1.0f //simpleRay.mPdf
-							  );
-		  vssRay->mFlags |= VssRay::Valid;
-		  vssRay->mDistribution = simpleRay.mDistribution;
-		  vssRays.push_back(vssRay);
-		  ++hits;
-		  
-		  vssRay = new VssRay(
-							  ray.Extrap(hitB.mT),
-							  ray.Extrap(hitA.mT),
-							  hitB.mObject,
-							  hitA.mObject,
-							  mPreprocessor.mPass,
-							  1.0f //simpleRay.mPdf
-							  );
-		  
-		  vssRay->mFlags |= VssRay::Valid;
-		  vssRay->mDistribution = simpleRay.mDistribution;
-		  vssRays.push_back(vssRay);
-		  ++hits;
-		}
-	  }
-	}
+      }
+    }
   }
   
@@ -192,21 +192,21 @@
 
 void InternalRayCaster::CastRays16(SimpleRayContainer &rays, 
-								   VssRayContainer &vssRays,
-								   const AxisAlignedBox3 &sbox,
-								   const bool castDoubleRays,
-								   const bool pruneInvalidRays)
+				   VssRayContainer &vssRays,
+				   const AxisAlignedBox3 &sbox,
+				   const bool castDoubleRays,
+				   const bool pruneInvalidRays)
 {
 #if DEBUG_RAYCAST
 	Debug << "C16 " << flush;
 #endif
-
-	SimpleRayContainer::const_iterator sit, sit_end = rays.end();
-
-	// no acceleration for ray bundles implemented right now
-	for (sit = rays.begin(); sit != sit_end; ++ sit) 
-	{
-		CastRay(*sit, vssRays, sbox, castDoubleRays, pruneInvalidRays);
-	}
-
+	
+  SimpleRayContainer::const_iterator sit, sit_end = rays.end();
+
+  // no acceleration for ray bundles implemented right now
+  for (sit = rays.begin(); sit != sit_end; ++ sit) 
+  {
+    CastRay(*sit, vssRays, sbox, castDoubleRays, pruneInvalidRays);
+  }
+  
 #if DEBUG_RAYCAST
 	Debug<<"C16F\n"<<flush;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Rectangle3.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Rectangle3.h	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Rectangle3.h	(revision 2575)
@@ -51,5 +51,5 @@
       v += CrossProd(mVertices[i], mVertices[i+1]);
     
-    return 0.5f*abs(DotProd(GetNormal(), v));
+    return 0.5f * fabs(DotProd(GetNormal(), v));
   }
   
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro	(revision 2574)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/preprocessor.pro	(revision 2575)
@@ -117,5 +117,5 @@
 Timer/BenchTimer.cpp Timer/merror.cpp \
 Intersectable.cpp TraversalTree.cpp ObjectPvs.cpp ObjectsParser.cpp \
-FilterBasedDistribution.cpp DifferenceSampling.cpp
+FilterBasedDistribution.cpp DifferenceSampling.cpp HavranRayCaster.cpp
 
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 2543)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 2575)
@@ -409,4 +409,5 @@
 	double sortTime, evalTime, nodeTime, splitTime, subdTime, planeTime, collectTime, viewCellsTime;
 
+#ifdef PERFTIMER  	
 	sortTime = mBvHierarchy->mSortTimer.TotalTime();
 	evalTime = mBvHierarchy->mEvalTimer.TotalTime();
@@ -416,5 +417,6 @@
 	planeTime = mBvHierarchy->mPlaneTimer.TotalTime();
 	collectTime = mBvHierarchy->mCollectTimer.TotalTime();
-
+#endif // #ifdef PERFTIMER 
+	
 	cout << "bvh times"
 		 << " sort : " << sortTime
@@ -437,4 +439,5 @@
 		 << endl;
 
+#ifdef PERFTIMER  
 	sortTime = mVspTree->mSortTimer.TotalTime();
 	evalTime = mVspTree->mEvalTimer.TotalTime();
@@ -444,5 +447,6 @@
 	planeTime = mVspTree->mPlaneTimer.TotalTime();
 	viewCellsTime = mVspTree->mViewCellsTimer.TotalTime();
-
+#endif
+	
 	cout << "vsp times"
 		 << " sort : " << sortTime
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 2543)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 2575)
@@ -147,5 +147,7 @@
 		EndObjectSpaceHierarchy();
 		Debug << "object space hierarchy parsed" << endl;
+#ifdef PERFTIMER  
 		mObjectTimer.Exit();
+#endif
 	}
 	// finished paring, create view cells manager
@@ -154,8 +156,9 @@
 		CreateViewCellsManager();
 
+#ifdef PERFTIMER  
 		Debug << "pvs time: " << mPvsTimer.TotalTime() << endl;
 		Debug << "object time: " << mObjectTimer.TotalTime() << endl;
 		Debug << "box time: " << mBoxTimer.TotalTime() << endl;
-
+#endif
 	}
 	else if (element == "Interior")
@@ -298,6 +301,7 @@
 	const long startTime = GetTime();
 	
+#ifdef PERFTIMER  
 	mBoxTimer.Entry();
-
+#endif
 	if (mBoundingBoxConverter)
 	{
@@ -320,5 +324,7 @@
 		  << TimeDiff(startTime, GetTime()) * 1e-6 << " secs" << endl;
 
+#ifdef PERFTIMER  
 	mBoxTimer.Exit();
+#endif
 }
 
@@ -481,5 +487,7 @@
 
 		mCurrentState = PARSE_OBJECTSPACE_HIERARCHY;
+#ifdef PERFTIMER  
 		mObjectTimer.Entry();
+#endif
 		StartObjectSpaceHierarchy(attributes);
 	}
@@ -539,6 +547,7 @@
 	}
 
+#ifdef PERFTIMER  
 	mPvsTimer.Entry();
-
+#endif
 	Intersectable::NewMail();
 
@@ -582,5 +591,7 @@
 	}
 	
+#ifdef PERFTIMER  
 	mPvsTimer.Exit();
+#endif
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp	(revision 2575)
@@ -1,6 +1,6 @@
 #include <iostream>
-#include <ply.h>
-#include <stdio.h>
-
+#include <cstdio>
+
+#include "ply.h"
 #include "PlyParser.h"
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.cpp	(revision 2332)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.cpp	(revision 2575)
@@ -1,5 +1,3 @@
 
-// GOLEM library
-#include <assert.h>
 #include <iostream>
 #include "AxisAlignedBox3.h"
@@ -10,4 +8,8 @@
 #include "Triangle3.h"
 #include "VssRay.h"
+
+
+
+#include <cassert>
 
 
@@ -210,6 +212,6 @@
 int
 AxisAlignedBox3::ComputeMinMaxT(const Ray &ray,
-								float *tmin,
-								float *tmax) const
+				float *tmin,
+				float *tmax) const
 {
   float minx, maxx, miny, maxy, minz, maxz;
@@ -302,6 +304,6 @@
 int
 AxisAlignedBox3::ComputeMinMaxT(const Ray &ray,
-								float *tmin,
-								float *tmax) const
+				float *tmin,
+				float *tmax) const
 {
   const float dirEps = 1e-8f;
@@ -398,5 +400,5 @@
 // the bounding box and 0 if it does not.
 int AxisAlignedBox3::ComputeMinMaxT(const Ray &ray, float *tmin, float *tmax,
-									EFaces &entryFace, EFaces &exitFace) const
+				    EFaces &entryFace, EFaces &exitFace) const
 {
   float minx, maxx, miny, maxy, minz, maxz;
@@ -1840,9 +1842,8 @@
 int
 AxisAlignedBox3::ComputeMinMaxT(const Vector3 &origin,
-								const Vector3 &direction,
-								float *tmin,
-								float *tmax) const
-{
-
+				const Vector3 &direction,
+				float *tmin,
+				float *tmax) const
+{
   register float minx, maxx;
 
@@ -2235,7 +2236,53 @@
 
 
+void AxisAlignedBox3::EnlargeToMinSize()
+{
+  const float epsMin = 1e-7;
+  const float epsAdd = 1e-6;
+  const float epsMul = 1.000005;
+  float dir = mMax.x - mMin.x;
+  assert(dir >= 0.f);
+  if (dir < epsMin) {
+    if (mMax.x > 0) {
+      mMax.x *= epsMul;
+      mMax.x += epsAdd;
+    }
+    else {
+      mMin.x *= epsMul;
+      mMin.x -= epsAdd;
+    }
+    assert(mMin.x < mMax.x);
+  }
+  dir = mMax.y - mMin.y;
+  assert(dir >= 0.f);
+  if (dir < epsMin) {
+    if (mMax.y > 0) {
+      mMax.y *= epsMul;
+      mMax.y += epsAdd;
+    }
+    else {
+      mMin.y *= epsMul;
+      mMin.y -= epsAdd;
+    }
+    assert(mMin.y < mMax.y);
+  }
+  dir = mMax.z - mMin.z;
+  assert(dir >= 0.f);
+  if (dir < epsMin) {
+    if (mMax.z > 0) {
+      mMax.z *= epsMul;
+      mMax.z += epsAdd;
+    }
+    else {
+      mMin.z *= epsMul;
+      mMin.z -= epsAdd;
+    }
+    assert(mMin.z < mMax.z);
+  }
+}
+
 void AxisAlignedBox3::SetMin(const Vector3 &v) 
 {
-	mMin = v;
+  mMin = v;
 }
 
@@ -2243,5 +2290,5 @@
 void AxisAlignedBox3::SetMax(const Vector3 &v) 
 {
-	mMax = v;
+  mMax = v;
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.cpp	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Camera.cpp	(revision 2575)
@@ -5,11 +5,20 @@
 #include <IL/ilu.h>
 #include <IL/ilut.h>
+#include <cassert>
 
 #include "Camera.h"
 #include "Ray.h"
+#include "SimpleRay.h"
 #include "KdTree.h"
 #include "Mesh.h"
 #include "Exporter.h"
 #include "SceneGraph.h"
+#include "Preprocessor.h"
+#include "RayCaster.h"
+
+#ifdef USE_HAVRAN_RAYCASTER 
+//#include "timer.h"
+#include "raypack.h"
+#endif
 
 using namespace std;
@@ -36,7 +45,7 @@
 bool
 Camera::SnapImage(string filename,
-				  KdTree *tree,
-				  SceneGraph *sceneGraph
-				  )
+		  KdTree *tree,
+		  SceneGraph *sceneGraph
+		 )
 {
   int x;
@@ -167,3 +176,207 @@
 }
 
-}
+
+void
+Camera::SetupRay(SimpleRay &ray, const int x, const int y)
+{
+  Vector3 xv = mRight*((x - mWidth/2)/(float)mWidth);
+  Vector3 yv = mUp*((y - mHeight/2)/(float)mHeight);
+  Vector3 target = xv + yv + mDirection;
+  Vector3 dir = target - mPosition;
+  dir.Normalize();
+  
+  ray.Set(mPosition, dir, 0,
+	  1.0f, ~(SimpleRay::F_BIDIRECTIONAL));
+}
+
+bool
+Camera::SnapImage(string filename,
+		  RayCaster *raycaster,
+		  AxisAlignedBox3 &bbox,
+		  SceneGraph *sceneGraph
+		  )
+{
+  int x;
+  int y;
+
+  bool exportRays = false;
+
+  
+  InitDevIl();
+  int components = 4;
+  float *buffer = new float[components*mWidth*mHeight];
+  assert(buffer);
+  float *pbuffer = buffer;
+  //  - components*mWidth;
+  
+  vector<Ray *> rays;
+
+  long t1 = GetTime();
+
+  SimpleRay ray;
+  VssRayContainer vssRays;
+
+  //CTimer timer;
+  //timer.Start();
+  
+  for (y = 0; y < mHeight; y++) {
+    cout<<"+";
+    for (x = 0; x < mWidth; x++) {
+      SetupRay(ray, mWidth - (x + 1), mHeight - (y + 1));
+
+      bool debug = true;
+      //	  (y == mHeight/2) && (x== mWidth/3);
+      //	  MeshDebug = debug;
+      
+
+      int res = raycaster->CastRay(ray,
+				   vssRays,
+				   bbox,
+				   false, // castDoubleRay,
+				   false); // pruneInvalidRays
+      
+      if (res) {
+	Vector3 normal = raycaster->intersect.mNormal;
+	float v =
+	  ray.mDirection.x * normal.x +
+	  ray.mDirection.y * normal.y +
+	  ray.mDirection.z * normal.z;
+	v *= 1.0f;
+	pbuffer[0] = v;
+	pbuffer[1] = v;
+	pbuffer[2] = v;
+	pbuffer[3] = 1.0f;		  
+      }
+      else {
+	pbuffer[0] = 0.0;
+	pbuffer[1] = 0.0;
+	pbuffer[2] = 0.0;
+	pbuffer[3] = 1.0f;
+      }
+      pbuffer+=components;
+      
+      if (debug) {
+	Ray *nray = new Ray(ray.mOrigin, ray.mDirection,
+			    Ray::LOCAL_RAY);
+	rays.push_back(nray);
+      }
+    }
+    //    pbuffer-=2*components*mWidth;
+  } // for y
+
+  //timer.Stop();
+  
+  long t2 = GetTime();
+  cout<<"\n#RAY_CAST_TIME = ";
+  cout << TimeDiff(t1, t2)<<" [mikrosec]\n";  
+  
+  cout<<"Saving image"<<endl;
+  
+  ilRegisterType(IL_FLOAT);
+  ilTexImage(mWidth, mHeight, 1, 4, IL_RGBA, IL_FLOAT, buffer);
+  ilSaveImage((char *const)filename.c_str());
+  delete buffer;
+
+  cout<<"done."<<endl<<flush;
+    
+  return true;
+}
+
+bool
+Camera::SnapImagePacket(string filename,
+			RayCaster *raycaster,
+			AxisAlignedBox3 &bbox,
+			SceneGraph *sceneGraph
+			)
+{
+#ifdef USE_HAVRAN_RAYCASTER 
+  
+  int x;
+  int y;
+
+  bool exportRays = false;
+
+  
+  InitDevIl();
+  int components = 4;
+  float *buffer = new float[components*mWidth*mHeight];
+  assert(buffer);
+  float *pbuffer = buffer;
+  //  - components*mWidth;
+  
+  vector<Ray *> rays;
+
+  long t1 = GetTime();
+
+  SimpleRay ray;
+  VssRayContainer vssRays;
+
+  //CTimer timer;
+  //timer.Start();
+
+  RayPacket2x2 rp;
+  for (y = 0; y < mHeight-1; y+=2) {
+    float *pppbuffer = pbuffer;
+    cout<<"+";
+    for (x = 0; x < mWidth-1; x+=2) {
+      int i = 0;
+      for (int yi = 0; yi < 2; yi++) {
+	for (int xi = 0; xi < 2; xi++) {
+	  SetupRay(ray, mWidth - (x+xi + 1), mHeight - (y+yi + 1));
+	  rp.SetLoc(i, ray.mOrigin);
+	  rp.SetDir(i, ray.mDirection);
+	  i++;
+	} // for xi
+      } // for yi      
+
+      raycaster->CastRaysPacket2x2(rp, false, false);
+
+      i = 0;
+      float *ppbuffer = pbuffer;
+      for (int yi = 0; yi < 2; yi++) {
+	for (int xi = 0; xi < 2; xi++) {
+	  Intersectable* res = rp.GetObject(i);
+	  if (res) {
+	    pbuffer[0] = 1.0f;
+	    pbuffer[1] = 1.0f;
+	    pbuffer[2] = 1.0f;
+	    pbuffer[3] = 1.0f;		  
+	  }
+	  else {
+	    pbuffer[0] = 0.0;
+	    pbuffer[1] = 0.0;
+	    pbuffer[2] = 0.0;
+	    pbuffer[3] = 1.0f;
+	  }
+	  i++;
+	  ppbuffer += components;
+	} // xi
+	ppbuffer += components * (mWidth-2);
+      } // yi
+
+      pbuffer = ppbuffer + 2 * components;
+    } // for x
+    pbuffer = pppbuffer + mWidth * 2 * components;
+    pppbuffer = pbuffer; // for the next time;
+  } // for y
+
+  //timer.Stop();
+  
+  long t2 = GetTime();
+  cout<<"\n#RAY_CAST_TIME = ";
+  cout << TimeDiff(t1, t2)<<" [mikrosec]\n";  
+  
+  cout<<"Saving image"<<endl;
+  
+  ilRegisterType(IL_FLOAT);
+  ilTexImage(mWidth, mHeight, 1, 4, IL_RGBA, IL_FLOAT, buffer);
+  ilSaveImage((char *const)filename.c_str());
+  delete buffer;
+#endif
+  cout<<"done."<<endl<<flush;
+    
+  return true;
+}
+  
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h	(revision 2569)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h	(revision 2575)
@@ -40,4 +40,7 @@
 	
 	int CastRay(Ray &ray);
+	int CastSimpleRay(const SimpleRay &ray) { return 0;}
+        int CastSimpleRay(const SimpleRay &ray, int RayIndex) { return 0;}
+  
 	
 	bool IsConvex() const;
@@ -193,7 +196,12 @@
 
 	int CastRay(Ray &ray);
+
+	int CastSimpleRay(const SimpleRay &ray);
+        int CastSimpleRay(const SimpleRay &ray, int rayIndex);
+	
 	AxisAlignedBox3 GetBox() const;
 	int NumberOfFaces() const;
 	Vector3 GetNormal(const int idx) const;
+	Vector3 GetNormal() const { return mItem.GetNormal();}
 
 	float GetArea() const {return mItem.GetArea();}
@@ -207,12 +215,12 @@
 
 	int GetRandomSurfacePoint(const float u,
-							  const float v,
-							  Vector3 &point, Vector3 &normal);
+				  const float v,
+				  Vector3 &point, Vector3 &normal);
 
 	
 	int GetRandomVisibleSurfacePoint(Vector3 &point,
-									 Vector3 &normal,
-									 const Vector3 &viewpoint,
-									 const int maxTries);
+					 Vector3 &normal,
+					 const Vector3 &viewpoint,
+					 const int maxTries);
 
 	int GetRandomEdgePoint(Vector3 &point, Vector3 &normal);
@@ -244,5 +252,5 @@
 
 	// hack
-	ContainerIntersectable::~ContainerIntersectable() 
+	~ContainerIntersectable() 
 	{
 		delete mItem;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp	(revision 2566)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/SamplingStrategy.cpp	(revision 2575)
@@ -1,2 +1,3 @@
+
 #include "SamplingStrategy.h"
 #include "Ray.h"
@@ -7,15 +8,21 @@
 #include "RssTree.h"
 #include "Mutation.h"
+#include "FilterBasedDistribution.h"
+#include "DifferenceSampling.h"
+
+
+#ifdef PERFTIMER
 #include "Timer/PerfTimer.h"
-#include "DifferenceSampling.h"
-
-
+#endif
 
 namespace GtpVisibilityPreprocessor {
 
+
+#ifdef PERFTIMER
 extern PerfTimer haltonTimer;
 extern PerfTimer pvsTimer;
 extern PerfTimer viewCellCastTimer;
-
+#endif
+  
 //HaltonSequence SamplingStrategy::sHalton;
 
@@ -221,5 +228,5 @@
 																	   r[4],
 																	   r[5])
-																	   ) - origin;
+															   ) - origin;
 	
 	const float c = Magnitude(direction);
@@ -591,8 +598,9 @@
   if (1)
   {
+#ifdef PERFTIMER
 	  const float vcTime = viewCellCastTimer.TotalTime();
 	  const float pvsTime = pvsTimer.TotalTime();
 	  const float haltonTime = haltonTimer.TotalTime();
-
+	  
 	  cout << "view cell cast time: " << vcTime << " s" << endl;
 	  cout << "pvs time: " << pvsTime << " s" << endl;
@@ -602,4 +610,8 @@
 	  Debug << "pvs time: " << pvsTime << " s" << endl;
 	  Debug << "halton time: "<< haltonTime << " s" << endl;
+#else
+	  cout << "Timers not supported" << endl;
+	  Debug << "Timers for PVS,Halton,Viewcell not supported" << endl;
+#endif
   }
 }
@@ -712,8 +724,12 @@
 					if (strcmp(curr, "mutation")==0) {
 					 mDistributions.push_back(new MutationBasedDistribution(mPreprocessor));
-					}
+					} else
+					  if (strcmp(curr, "filter_based")==0) {
+						mDistributions.push_back(new FilterBasedDistribution(mPreprocessor));
+					  }
 					else if (strcmp(curr, "difference")==0) {
 					 mDistributions.push_back(new DifferenceSampling(mPreprocessor));
 					}
+	
 	
 	
