Index: /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 326)
+++ /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 329)
@@ -56,14 +56,16 @@
 
 Sampling {
-	totalSamples	100
+	totalSamples	1000000
 	samplesPerPass  20
 }
 
 ViewCells {
-	hierarchyType bspTree
+	# hierarchy kdTree
+	hierarchy bspTree
+	# hierarchy sceneDependent
+	
 	height 5.0
 	maxViewCells 0
-	#hierarchyType kdTree
-	#hierarchyType sceneDependent
+	
 #	filename ../data/atlanta/atlanta_viewcells_large.x3d
 #	filename ../data/vienna/viewcells-25-sel.x3d
@@ -73,7 +75,12 @@
 
 BspTree {
-#       constructionMethod fromRays
-#	constructionMethod fromViewCells
-	constructionMethod fromSceneGeometry
+	Construction {
+	        input fromRays
+	#	input fromViewCells
+	#	input fromSceneGeometry
+		samples 50000
+		sideTolerance 0.002
+	}
+
 
 	# random polygon       = 1
@@ -101,5 +108,5 @@
 	#splitPlaneStrategy 72
 	
-	splitPlaneStrategy 66
+	splitPlaneStrategy 8
 	
 	maxCandidates 50
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h	(revision 327)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h	(revision 329)
@@ -104,4 +104,7 @@
 	/// Rays piercing this polygon
 	RayContainer *mPiercingRays;
+
+	static float sSideTolerance;
+	static float sSideToleranceSqrt;
 };
 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h	(revision 328)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h	(revision 329)
@@ -276,20 +276,5 @@
 		{}
     };
-
-	/** given as argument for a node subdivision.
-		Stores the polyons and rays and the returned 
-		front and back fragments.
-	*/
-	struct BspSplitData
-	{
-		PolygonContainer *mPolys;
-		PolygonContainer *mFrontPolys;
-		PolygonContainer *mBackPolys;
-		PolygonContainer *mCoincident;
-		RayContainer *mRays;
-		RayContainer *mBackRays;
-		RayContainer *mFrontRays;
-	};
-
+	
 	typedef std::stack<BspTraversalData> BspTraversalStack;
 
@@ -427,9 +412,23 @@
 	/** Subdivide leaf.
 		@param leaf the leaf to be subdivided
-		@param splitData data relevant for the splti
+		
+		@param polys the polygons to be split
+		@param frontPolys returns the polygons in front of the split plane
+		@param backPolys returns the polygons in the back of the split plane
+		
+		@param rays the polygons to be filtered
+		@param frontRays returns the polygons in front of the split plane
+		@param backRays returns the polygons in the back of the split plane
+
 		@returns the root of the subdivision
 	*/
 	BspInterior *SubdivideNode(BspLeaf *leaf, 
-							   BspSplitData &splitData);
+							   PolygonContainer &polys,
+							   PolygonContainer &frontPolys,
+							   PolygonContainer &backPolys,
+							   PolygonContainer &coincident,
+							   RayContainer &rays,
+							   RayContainer &backRays,
+							   RayContainer &frontRays);
 
 	/** Filters polygons down the tree.
@@ -528,4 +527,8 @@
 
 
+	/** Generates new view cell for a leaf and stores it back in the container.
+	*/
+	void BspTree::GenerateViewCell(BspLeaf *leaf, ViewCellContainer &viewCells) const;
+
 	/// Pointer to the root of the tree
 	BspNode *mRoot;
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 321)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 329)
@@ -1150,7 +1150,7 @@
 		 "10");
 
-  RegisterOption("ViewCells.hierarchyType",
+  RegisterOption("ViewCells.hierarchy",
 		 optString,
-		 "-view_cells_hierarchy_type",
+		 "-view_cells_hierarchy",
 		 "bspTree");
 
@@ -1165,8 +1165,19 @@
 		 "5.0");
 
-  RegisterOption("BspTree.constructionMethod",
+  RegisterOption("BspTree.Construction.input",
 	  optString,
-	  "-bsp_construction_method=",
+	  "-bsp_construction_input=",
 	  "fromViewCells");
+  
+  RegisterOption("BspTree.Construction.samples",
+	  optInt,
+	  "-bsp_construction_samples=",
+	  "100000");
+
+  RegisterOption("BspTree.Construction.sideTolerance",
+	  optFloat,
+	  "-bsp_construction_side_tolerance=",
+	  "0.002");
+
 
   RegisterOption("BspTree.Termination.maxPolygons",
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp	(revision 328)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp	(revision 329)
@@ -286,4 +286,5 @@
 	return splits;
 }
+
 void BspInterior::InheritRays(const Polygon3 &poly, 
 						      Polygon3 &front_piece, 
@@ -427,7 +428,7 @@
 {	
 	std::stack<BspTraversalData> tStack;
-		
-	// traverse tree or create new one
-	BspNode *firstNode = mRoot ? mRoot : new BspLeaf();
+	
+	// traverse existing tree or create new tree
+    BspNode *firstNode = mRoot ? mRoot : new BspLeaf();
 
 	tStack.push(BspTraversalData(firstNode, polys, 0, mRootCell, new RayContainer()));
@@ -497,19 +498,20 @@
 		else // reached leaf => subdivide current viewcell
 		{
-			BspNode *root = Subdivide(tStack, tData);		
-
-			if (viewCells && root->IsLeaf())
-			{	
-				// generate new view cell for each leaf
-				ViewCell *viewCell = new ViewCell();
-				viewCells->push_back(viewCell);
+			// root of the new subtree
+			BspNode *subRoot = Subdivide(tStack, tData);		
+
+			// generate new view cell for each leaf
+			if (viewCells && subRoot->IsLeaf())
+				GenerateViewCell(dynamic_cast<BspLeaf *>(subRoot), *viewCells);
+		}
+	}
+}
+
+void BspTree::GenerateViewCell(BspLeaf *leaf, ViewCellContainer &viewCells) const
+{
+	ViewCell *viewCell = new ViewCell();
+	viewCells.push_back(viewCell);
 				
-				dynamic_cast<BspLeaf *>(root)->SetViewCell(viewCell);
-			}
-
-			if (!mRoot) // tree empty => new root
-				mRoot = root;
-		}
-	}
+	leaf->SetViewCell(viewCell);
 }
 
@@ -593,5 +595,5 @@
 
 	// construct tree from the view cell polygons
-	Construct(polys, NULL);
+	Construct(polys, new RayContainer());
 }
 
@@ -608,5 +610,5 @@
 
 	// construct tree from polygon soup
-	Construct(polys, NULL, viewCells);
+	Construct(polys, new RayContainer(), viewCells);
 }
 
@@ -664,10 +666,12 @@
 {
 	std::stack<BspTraversalData> tStack;
-	
+
 	BspTraversalData tData(new BspLeaf(), polys, 0, mRootCell, rays);
+
 	tStack.push(tData);
 
 	long startTime = GetTime();
-	Debug << "**** Contructing tree using scene geometry ****\n";
+	cout << "**** Contructing tree using scene geometry ****\n";
+
 	while (!tStack.empty()) 
 	{
@@ -676,20 +680,11 @@
 
 		// subdivide leaf node
-		BspNode *root = Subdivide(tStack, tData);
-
-		if (viewCells && root->IsLeaf())
-		{	// generate new view cell for each leaf
-			ViewCell *viewCell = new ViewCell();
-			viewCells->push_back(viewCell);
-
-			dynamic_cast<BspLeaf *>(root)->SetViewCell(viewCell);
-		}
-
-		// empty tree => new root corresponding to unbounded space
-		if (!mRoot) 
-			mRoot = root;
-	}
-
-	Debug << "**** Finished tree construction ****\n";
+		BspNode *subRoot = Subdivide(tStack, tData);
+
+		if (viewCells && subRoot->IsLeaf())
+			GenerateViewCell(dynamic_cast<BspLeaf *>(subRoot), *viewCells);
+	}
+
+	cout << "**** Finished tree construction ****\n";
 	Debug << "BSP tree contruction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
 }
@@ -716,7 +711,4 @@
 		leaf->ProcessPolygons(tData.mPolygons, sStoreSplitPolys);
 		DEL_PTR(tData.mPolygons);
-
-		if (tData.mRays)
-			CLEAR_CONTAINER(*tData.mRays);
 		DEL_PTR(tData.mRays);
 
@@ -724,22 +716,24 @@
 	}
 
-
 	//-- continue subdivision
+
 	PolygonContainer coincident;
-
-	BspSplitData splitData;
-		
-	splitData.mPolys = tData.mPolygons;
-	splitData.mFrontPolys = new PolygonContainer(),
-	splitData.mBackPolys = new PolygonContainer();
-	splitData.mCoincident = &coincident;
-	
-	splitData.mRays = tData.mRays;
-	splitData.mFrontRays = new RayContainer();
-	splitData.mBackRays = new RayContainer();
+	
+	PolygonContainer *frontPolys = new PolygonContainer();
+	PolygonContainer *backPolys = new PolygonContainer();
+
+	RayContainer *frontRays = new RayContainer();
+	RayContainer *backRays = new RayContainer();
+	
 
 	// create new interior node and two leaf nodes
-	BspInterior *interior = 
-		SubdivideNode(dynamic_cast<BspLeaf *>(tData.mNode), splitData);
+	BspInterior *interior = SubdivideNode(dynamic_cast<BspLeaf *>(tData.mNode), 
+										  *tData.mPolygons,
+										  *frontPolys,
+										  *backPolys,
+										   coincident,
+										   *tData.mRays,
+										   *frontRays,
+										   *backRays);
 
 	ViewCell *frontViewCell = mRootCell;
@@ -757,8 +751,8 @@
    	ExtractViewCells(&backViewCell,
 					 &frontViewCell,
-					 *splitData.mCoincident,
+					 coincident,
 					 interior->mPlane,
-					 splitData.mBackPolys->empty(),
-					 splitData.mFrontPolys->empty());
+					 backPolys->empty(),
+					 frontPolys->empty());
 	
 	// don't need coincident polygons anymore
@@ -767,14 +761,14 @@
 	// push the children on the stack
 	tStack.push(BspTraversalData(interior->GetBack(), 
-								 splitData.mBackPolys, 
+								 backPolys, 
 								 tData.mDepth + 1, 
 								 backViewCell, 
-								 splitData.mBackRays));
+								 backRays));
 
 	tStack.push(BspTraversalData(interior->GetFront(), 
-								 splitData.mFrontPolys, 
+								 frontPolys, 
 								 tData.mDepth + 1, 
 								 frontViewCell, 
-								 splitData.mFrontRays));
+								 frontRays));
 
 	// cleanup
@@ -817,5 +811,11 @@
 
 BspInterior *BspTree::SubdivideNode(BspLeaf *leaf, 
-									BspSplitData &splitData)
+									PolygonContainer &polys,
+									PolygonContainer &frontPolys,
+									PolygonContainer &backPolys,
+									PolygonContainer &coincident,
+									RayContainer &rays,
+									RayContainer &backRays,
+									RayContainer &frontRays)
 {
 	mStat.nodes += 2;
@@ -823,29 +823,30 @@
 	// select subdivision plane
 	BspInterior *interior = 
-		new BspInterior(SelectPlane(leaf, *splitData.mPolys, *splitData.mRays)); 
+		new BspInterior(SelectPlane(leaf, polys, rays)); 
 
 #ifdef _DEBUG
 	Debug << interior << endl;
 #endif
-
+	
 	// partition rays
-	interior->SplitRays(*splitData.mRays, 
-						*splitData.mFrontRays, 
-						*splitData.mBackRays);
-	
+	interior->SplitRays(rays, frontRays, backRays);
+	Debug << "jdfjfj43" << endl;
 	// split polygons with split plane
-	mStat.splits +=interior->SplitPolygons(*splitData.mPolys, 
-									       *splitData.mFrontPolys, 
-							               *splitData.mBackPolys, 
-							               *splitData.mCoincident, 
+	mStat.splits +=interior->SplitPolygons(polys, 
+									       frontPolys, 
+							               backPolys, 
+							               coincident, 
 							               sStoreSplitPolys);
-
 	BspInterior *parent = leaf->GetParent();
 
 	// replace a link from node's parent
-	if (parent)
+	if (!leaf->IsRoot())
 	{
 		parent->ReplaceChildLink(leaf, interior);
 		interior->SetParent(parent);
+	}
+	else // new root
+	{
+		mRoot = interior;
 	}
 
@@ -1199,5 +1200,5 @@
 	char constructionMethodStr[60];
 	
-	environment->GetStringValue("BspTree.constructionMethod", constructionMethodStr);
+	environment->GetStringValue("BspTree.Construction.input", constructionMethodStr);
 
 	sConstructionMethod = FROM_INPUT_VIEW_CELLS;
@@ -1230,4 +1231,7 @@
 
 	environment->GetBoolValue("BspTree.storeSplitPolys", sStoreSplitPolys);
+
+	environment->GetFloatValue("BspTree.Construction.sideTolerance", Polygon3::sSideTolerance);
+	Polygon3::sSideToleranceSqrt = Polygon3::sSideTolerance * Polygon3::sSideTolerance;
 
     Debug << "BSP max depth: " << sTermMaxDepth << endl;
@@ -1471,3 +1475,4 @@
 }
 
+
 //} // GtpVisibilityPreprocessor
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp	(revision 327)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp	(revision 329)
@@ -48,14 +48,22 @@
 	// parse type of view cells
 	char viewCellsStr[64];
-	environment->GetStringValue("ViewCells.hierarchyType", viewCellsStr);
+	environment->GetStringValue("ViewCells.hierarchy", viewCellsStr);
 
 	int vcType = BSP_VIEW_CELLS;
   
 	if (strcmp(viewCellsStr, "bspTree") == 0)
-		vcType = BSP_VIEW_CELLS;
+	{
+		Debug << "here bsp" << endl;
+    	mViewCellsType = BSP_VIEW_CELLS;
+	}
 	else if (strcmp(viewCellsStr, "kdTree") == 0)
-		vcType = KD_VIEW_CELLS;
+		{
+		Debug << "here kd" << endl;
+    	mViewCellsType = KD_VIEW_CELLS;
+	}
 	else if (strcmp(viewCellsStr, "sceneDependent") == 0)
-		vcType = SCENE_DEPENDENT;
+	{
+		//TODO
+	}
 	else
 	{
@@ -64,15 +72,8 @@
 	}
 
-	// decide about view cell subdivision type used for preprocessing
-	switch (vcType)
-	{
-	case BSP_VIEW_CELLS:
-	case KD_VIEW_CELLS:
-		mViewCellsType = vcType;
-		break;
-	case SCENE_DEPENDENT:
-		mViewCellsType = BSP_VIEW_CELLS; // TODO
-		break;
-	}
+	if (mViewCellsType == KD_VIEW_CELLS)
+		Debug << "kdtree" << endl;
+	else if (mViewCellsType == BSP_VIEW_CELLS)
+		Debug << "bsptree" << endl;
 
 	return true;
@@ -143,39 +144,4 @@
 }
 
-
-bool
-Preprocessor::BuildBspTree()
-{
-	DEL_PTR(mBspTree);
-	
-	mBspTree = new BspTree(&mUnbounded);
-
-	ObjectContainer objects;
-	RayContainer *rays = new RayContainer();
-
-	switch (BspTree::sConstructionMethod)
-	{
-	case BspTree::FROM_INPUT_VIEW_CELLS:
-		mBspTree->Construct(mViewCells);
-		break;
-	case BspTree::FROM_SCENE_GEOMETRY:
-		DeleteViewCells(); // we generate new view cells
-		mSceneGraph->CollectObjects(&objects);
-		mBspTree->Construct(objects, &mViewCells);
-		break;
-	case BspTree::FROM_RAYS:
-		DeleteViewCells(); // we generate new view cells
-		mSceneGraph->CollectObjects(&objects);
-		mBspTree->Construct(rays, &mViewCells);
-		break;
-	default:
-		Debug << "Error: Method not available\n";
-		break;
-	}
-	return true;
-}
-
-
-
 void
 Preprocessor::KdTreeStatistics(ostream &s)
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.h	(revision 313)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.h	(revision 329)
@@ -78,4 +78,5 @@
   static ViewCellContainer foundViewCells; // todo: remove this
 protected:
+
   virtual void
   ExportSceneNode(SceneGraphNode *node);
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/KdTree.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/KdTree.h	(revision 311)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/KdTree.h	(revision 329)
@@ -162,7 +162,6 @@
   
   void AddPassingRay(const Ray &ray, const int contributions) {
-	  Debug << "here2" << endl;
     mPassingRays.AddRay(ray, contributions);
-	Debug << "here4" << endl;
+	Debug << "adding passing ray" << endl;
   }
   
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp	(revision 322)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp	(revision 329)
@@ -42,4 +42,5 @@
 	  !(BspTree::sConstructionMethod == BspTree::FROM_RAYS)) // construct tree later
   {
+	  Debug << "do1" << endl;
 	  if (BspTree::sConstructionMethod == BspTree::FROM_INPUT_VIEW_CELLS)
 	  {
@@ -56,4 +57,5 @@
 	  }
 	
+	  Debug << "do2" << endl;
 	  p->BuildBspTree();
 	  p->Export("vc_bsptree.x3d", false, false, true);
@@ -62,5 +64,5 @@
 	  bool exportSplits = false;
 	  environment->GetBoolValue("BspTree.exportSplits", exportSplits);
-
+Debug << "do3" << endl;
 	  // export the bsp splits
 	  if (exportSplits)
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.h	(revision 308)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.h	(revision 329)
@@ -23,6 +23,10 @@
   ofstream mStats;
   ObjectContainer mObjects;
+  RayContainer *mSampleRays;
+  int mBspConstructionSamples;
 
   SamplingPreprocessor();
+
+  ~SamplingPreprocessor();
 
   virtual bool ComputeVisibility();
@@ -54,4 +58,6 @@
 	*/
 	int AddObjectSamples(Intersectable *obj, const Ray &ray);
+
+	bool BuildBspTree();
 };
 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.cpp	(revision 327)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/X3dExporter.cpp	(revision 329)
@@ -615,4 +615,5 @@
 }
 
+
 struct BspSplitData
 {
@@ -628,7 +629,7 @@
 	{};	
 	BspSplitData(BspNode *node, 
-				 vector<Plane3 *> planes, 
-				 vector<bool> sides, 
-				 bool isFront): 
+				vector<Plane3 *> planes, 
+				vector<bool> sides, 
+				bool isFront): 
 	mNode(node), mPlanes(planes), 
 	mSides(sides), mIsFront(isFront)
@@ -686,4 +687,5 @@
 
 			tData.mPlanes.push_back(interior->GetPlane()); // add plane to split planes
+
 			if (planePoly->Valid())
 				polys.push_back(planePoly);
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.h	(revision 321)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.h	(revision 329)
@@ -30,5 +30,5 @@
 	Preprocessor();
 
-   ~Preprocessor();
+   virtual ~Preprocessor();
 
   /** Load the input scene. 
@@ -71,5 +71,5 @@
       entities should be used to drive the heuristical construction (only occluders by default)
   */
-  virtual bool BuildBspTree();
+  virtual bool BuildBspTree() = 0;
 
   /** Compute visibility method. This method has to be reimplemented by the actual
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp	(revision 327)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp	(revision 329)
@@ -6,4 +6,7 @@
 #include "Ray.h"
 
+float Polygon3::sSideTolerance = 0.002f;
+float Polygon3::sSideToleranceSqrt = 0.000004f;
+
 Polygon3::Polygon3(): 
 mMaterial(NULL), mParent(NULL), mPiercingRays(NULL)
@@ -15,8 +18,9 @@
 
 Polygon3::Polygon3(MeshInstance *parent): 
-mMaterial(NULL), mParent(parent)
+mMaterial(NULL), mParent(parent), mPiercingRays(NULL)
 {}
 
-Polygon3::Polygon3(Face *face, Mesh *parentMesh)
+Polygon3::Polygon3(Face *face, Mesh *parentMesh):
+mMaterial(NULL), mParent(NULL), mPiercingRays(NULL)
 {	
 	VertexIndexContainer::iterator it = face->mVertexIndices.begin();
@@ -51,5 +55,5 @@
 	Vector3 ptA = mVertices.back();
 	
-	int sideA = partition.Side(ptA, SIDE_TOLERANCE);
+	int sideA = partition.Side(ptA, sSideTolerance);
 	
 	VertexContainer::const_iterator it;
@@ -60,5 +64,5 @@
 	{
 		Vector3 ptB = *it;
-		int sideB = partition.Side(ptB, SIDE_TOLERANCE);
+		int sideB = partition.Side(ptB, sSideTolerance);
 	
 		// vertices on different sides => split
@@ -72,5 +76,5 @@
 				// test if split point not too close to previous split point
 				if (!foundSplit || 
-					(SqrDistance(splitPt, splitPts.back()) > SIDE_TOLERANCE_SQRD))
+					(SqrDistance(splitPt, splitPts.back()) > sSideToleranceSqrt))
 				{
 					// add vertex to both polygons
@@ -93,5 +97,5 @@
 					// test if split point not too close to previous split point
 				if (!foundSplit || 
-					(SqrDistance(splitPt, splitPts.back()) > SIDE_TOLERANCE_SQRD))
+					(SqrDistance(splitPt, splitPts.back()) > sSideToleranceSqrt))
 				{
 					// add vertex to both polygons
@@ -151,5 +155,5 @@
 	for (it = mVertices.begin(); it != mVertices.end(); ++ it)
 	{
-		int side = plane.Side(*it, SIDE_TOLERANCE);
+		int side = plane.Side(*it, sSideTolerance);
 		
 		if (side > 0)
@@ -361,8 +365,4 @@
 void Polygon3::AddPiercingRay(Ray *ray)
 {
-	if (!mPiercingRays)
-		mPiercingRays = new RayContainer();
-	//if (binary_search(mPiercingRays.begin(), mPiercingRays.end(), ray)) return false;
-	
-	mPiercingRays->push_back(ray);
-}
+	GetPiercingRays()->push_back(ray);
+}
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp	(revision 327)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp	(revision 329)
@@ -13,8 +13,19 @@
   environment->GetIntValue("Sampling.samplesPerPass", mSamplesPerPass);
   environment->GetIntValue("Sampling.totalSamples", mTotalSamples);
-  
+  environment->GetIntValue("BspTree.Construction.samples", mBspConstructionSamples);
+
   mKdPvsDepth = 100;
   mStats.open("stats.log");
 
+}
+
+SamplingPreprocessor::~SamplingPreprocessor()
+{
+	// clean up
+	if (mSampleRays)
+	{
+		CLEAR_CONTAINER (*mSampleRays);
+		DEL_PTR (mSampleRays);
+	}
 }
 
@@ -38,4 +49,38 @@
     node = node->mParent;
   return node;
+}
+
+bool
+SamplingPreprocessor::BuildBspTree()
+{
+	// delete old tree
+	DEL_PTR(mBspTree);
+	mBspTree = new BspTree(&mUnbounded);
+
+	ObjectContainer objects;
+	
+	switch (BspTree::sConstructionMethod)
+	{
+	case BspTree::FROM_INPUT_VIEW_CELLS:
+		mBspTree->Construct(mViewCells);
+		break;
+	case BspTree::FROM_SCENE_GEOMETRY:
+		
+		DeleteViewCells(); // we generate new view cells
+		mSceneGraph->CollectObjects(&objects);
+		mBspTree->Construct(objects, &mViewCells);
+		
+		break;
+	case BspTree::FROM_RAYS:
+		DeleteViewCells(); // we generate new view cells
+		mSceneGraph->CollectObjects(&objects);
+		mBspTree->Construct(mSampleRays, &mViewCells);
+		break;
+	default:
+		Debug << "Error: Method not available\n";
+		break;
+	}
+	
+	return true;
 }
 
@@ -106,20 +151,25 @@
 	// cast ray to KD tree to find intersection with other objects
 	mKdTree->CastRay(ray);
-
+	cout << "k";
 	if (mViewCellsType == BSP_VIEW_CELLS)
 	{
 		// cast ray to BSP tree to get intersection with view cells
-		mBspTree->CastRay(ray);
-		
-		sampleContributions += AddObjectSamples(object, ray);
+		if (mBspTree)
+		{
+			cout << "uhhhhhhh year" << endl;
+			mBspTree->CastRay(ray);
+		
+			sampleContributions += AddObjectSamples(object, ray);
 				
-		if (!ray.intersections.empty()) // second intersection found
-		{
-			sampleContributions += 
-				AddObjectSamples(ray.intersections[0].mObject, ray);
+			if (!ray.intersections.empty()) // second intersection found
+			{
+				sampleContributions += 
+					AddObjectSamples(ray.intersections[0].mObject, ray);
+			}
 		}
 	}
 	else
 	{
+		cout << "z" << endl;
 		if (ray.leaves.size()) {
 			sampleContributions += AddNodeSamples(object, ray);
@@ -238,5 +288,5 @@
   {
 	  int idx = Random((int)mViewCells.size());
-	  Debug << "output view cell no. " << idx << endl;
+	  Debug << "output view cell=" << idx << endl;
 	  pvsViewCells.push_back(mViewCells[Random((int)mViewCells.size())]);
   }
@@ -246,5 +296,7 @@
 
   vector<Ray> viewCellRays; // used for BSP tree construction
-  const int fromRaysBspThresh = 1000;
+ 
+  mSampleRays = new RayContainer();
+  //mSampleRays->reserve(mBspConstructionSamples);
 
   while (totalSamples < mTotalSamples) {
@@ -254,12 +306,8 @@
 		int index = 0;
 			
-		// construct Bsp tree if not
-		if ((mViewCellsType == Preprocessor::BSP_VIEW_CELLS) &&
-			!mBspTree->GetRoot() && (totalSamples >= fromRaysBspThresh))
-		{
-			BuildBspTree();
-		}
-
+		cout << "totalSamples: "  << totalSamples;
 		for (i = 0; i < objects.size(); i++) {
+			printf("\nsampling object %d of %d, samples %d\n", i, (int)objects.size(), passSamples);
+
 			KdNode *nodeToSample = NULL;
 			Intersectable *object = objects[i];
@@ -324,9 +372,9 @@
 			bool viewcellSample = true;
 			int sampleContributions;
+			
 			if (viewcellSample) {
 				nodeToSample = mKdTree->GetRandomLeaf(Plane3(normal, point));
 				
 				for (int k=0; k < mSamplesPerPass; k++) {
-					
 					if (nodeToSample) {
 						int maxTries = 5;
@@ -336,5 +384,5 @@
 							
 							if (DotProd(direction, normal) > Limits::Small)
-								break;
+								break;							
 						}
 						
@@ -348,22 +396,37 @@
 					// construct a ray
 					SetupRay(ray, point, direction);
-					
+					 cout << "s";
 					sampleContributions = CastRay(object, ray);
-					
+					cout << "r";
 					if (mViewCellsType == BSP_VIEW_CELLS) 
 					{
 						// save rays for bsp tree construction
-						if (!mBspTree->GetRoot() && (totalSamples < fromRaysBspThresh))
+						if ((BspTree::sConstructionMethod = BspTree::FROM_RAYS) &&
+							(totalSamples < mBspConstructionSamples))
 						{
-							viewCellRays.push_back(ray);
+							//cout << "pushing back sampling ray << " << mSampleRays->size() << endl;
+							mSampleRays->push_back(new Ray(ray));
 						}
-						// check whether we can add this to the rays
-						for (int k = 0; k < ray.viewCells.size(); ++ k)
-							for (int j = 0; j < (int)pvsViewCells.size(); ++ j) 
-								if (pvsViewCells[j] == ray.viewCells[k]) 
-								{
-									vcRays[j].push_back(ray);
-								}
+						else
+						{
+							// construct BSP tree using the samples
+							if (!mBspTree)
+							{
+								Debug << "Building bsp tree" << endl;
+								BuildBspTree();
+
+								CLEAR_CONTAINER (*mSampleRays);
+								DEL_PTR (mSampleRays);
+							}
+							// check whether we can add this to the rays
+							for (int k = 0; k < ray.viewCells.size(); ++ k)
+								for (int j = 0; j < (int)pvsViewCells.size(); ++ j) 
+									if (pvsViewCells[j] == ray.viewCells[k]) 
+									{
+										vcRays[j].push_back(ray);
+									}
+						}				
 					}
+		
 				}
 			} else {
@@ -371,12 +434,10 @@
 				// get random visible mesh
 				//				object->GetRandomVisibleMesh(Plane3(normal, point));
-				
-				
-			}
-				
+			}
+		
 			// NOTE: should be inside loop
 			if ( i < pvsOut )
 				rays[i].push_back(ray);
-			
+		
 			if (!ray.intersections.empty()) {
 					// check whether we can add this to the rays
@@ -387,7 +448,7 @@
 				}
 			}
-			
+		
 			passSamples++;
-			
+		
 			if (sampleContributions) {
 				passContributingSamples++;
@@ -395,5 +456,5 @@
 			}
 		}
-		
+		cout << "pass samples: " << passSamples << endl;
 		totalSamples += passSamples;
 		
@@ -439,5 +500,5 @@
 			<< endl;
 	}
-  
+
 	if (mViewCellsType == KD_VIEW_CELLS)	
 		cout << "#totalPvsSize=" << mKdTree->CollectLeafPvs() << endl;
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/AxisAlignedBox3.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/AxisAlignedBox3.cpp	(revision 321)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/AxisAlignedBox3.cpp	(revision 329)
@@ -1674,5 +1674,5 @@
 	{
 		GetVertex(i, vtx);
-		side[i] = plane.Side(vtx, SIDE_TOLERANCE);
+		side[i] = plane.Side(vtx);
 		if (side[i] > 0)
 			onFrontSide = true;
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/common.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/common.h	(revision 312)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/common.h	(revision 329)
@@ -127,7 +127,6 @@
 #define MAX_FLOAT  1e30f
 
-// tolerance value for side relation
-#define SIDE_TOLERANCE 0.002f // TODO: Test different values
-#define SIDE_TOLERANCE_SQRD 0.000004f
+
+// tolerance value for polygon area
 #define AREA_LIMIT 0.0001f
 
