Index: /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 574)
@@ -30,5 +30,5 @@
 VssPreprocessor {
 	samplesPerPass  100000
-	initialSamples 6000000
+	initialSamples 0
 	vssSamples 0
 	vssSamplesPerPass 500000
@@ -78,6 +78,9 @@
 RssPreprocessor {
 	samplesPerPass  100000
-	initialSamples 500000
-	vssSamples 10000000
+	#initialSamples 500000
+	#vssSamples 10000000
+	#for view cell construction
+	initialSamples 0
+	vssSamples 0
 	vssSamplesPerPass 500000
 	useImportanceSampling true
@@ -171,4 +174,10 @@
 
 ViewCells {
+	# samples used for view cell construction
+	Construction {
+		samples 5000000
+		samplesPerPass 500000
+	}
+	
 	loadFromFile false
 	exportToFile false
@@ -196,5 +205,5 @@
 	Visualization {
 		# how much samples we use for visualization
-		samples 5000
+		samples 100000
 		#colorCode PVS
 		#colorCode MergedLeaves
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h	(revision 574)
@@ -307,8 +307,13 @@
 
 	
-	/** Checks validy of view cells.
-		if not valid, sets regions invalid and deletes view cell.
+	/** Checks if tree validity-flags are right 
+		with respect to view cell valitiy.
+		If not, marks subtree as invalid.
 	*/
 	void ValidateTree();
+
+	/** Invalid view cells are added to the unbounded space
+	*/
+	void CollapseViewCells();
 
 protected:
@@ -626,5 +631,5 @@
 	BspNode *mRoot;
 		
-	BspTreeStatistics mStat;
+	BspTreeStatistics mBspStats;
 
 	/// Strategies for choosing next split plane.
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h	(revision 508)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.h	(revision 574)
@@ -150,4 +150,6 @@
 	static int ParentObjectsSize(const PolygonContainer &polys);
 
+	/** Area of the accumulated polygons.
+	*/
 	static float GetArea(const PolygonContainer &cell);
 };
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.h	(revision 564)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.h	(revision 574)
@@ -19,4 +19,15 @@
 	float avgRtWithoutOverhead;
   
+	//-- options counting only valid view cells
+
+	/// view cell with the biggest "cost"
+	float validMaxCost;
+	/// view cell with the minimal "cost"
+    float validMinCost;
+	/// average render time
+	float validAvgRenderTime;
+	/// average render time with the overhead when crossing view cells
+	float validAvgRtWithoutOverhead;
+
 	void Reset() 
 	{
@@ -25,4 +36,9 @@
 		avgRenderTime = 0;
 		avgRtWithoutOverhead = 0;
+
+		validMaxCost = 0;
+		validMinCost = 999999;
+		validAvgRenderTime = 0;
+		validAvgRtWithoutOverhead = 0;
 	}
 
@@ -99,7 +115,4 @@
 	/// Simulation statistics
 	SimulationStatistics mSimulationStatistics;
-
-	/// if only valid view space should be rendered
-	bool mOnlyValid;
 };
 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h	(revision 547)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h	(revision 574)
@@ -29,4 +29,6 @@
 	BspNodeGeometry(const BspNodeGeometry &rhs);
 
+	//BspNodeGeometry(const PolygonContainer &polys);
+
 	~BspNodeGeometry();
 
@@ -67,4 +69,5 @@
 	PolygonContainer mPolys;
 };
+
 
 /** Data structure used for optimized ray casting.
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h	(revision 574)
@@ -47,7 +47,10 @@
   enum {BSP, KD, VSP_KD, VSP_BSP};
   
-	/** Constructor taking the maximal number of samples used for construction
-	*/
-	ViewCellsManager(const int constructionSamples);
+	/** Constructor taking the initial and construction samples.
+		@param initialSamples the maximal number of samples used for creating the hierarchy
+		of view cells
+		@param constructionSamples the maximal number of samples used for construction
+	*/
+	ViewCellsManager(const int initialSamples, const int constructionSamples);
 
 	ViewCellsManager();
@@ -62,5 +65,5 @@
 	/** Constructs view cell container with a given number of samples.
 	*/
-	virtual int Construct(const ObjectContainer &objects, 
+	virtual int ConstructSubdivision(const ObjectContainer &objects, 
 						  const VssRayContainer &rays) = 0;
 
@@ -70,7 +73,10 @@
 		adding the contribution
 		@param addRays true if rays should be added to the PVSs of the viewcells they
-		intersect */
+		intersect 
+		@param storeViewCells true if view cells should be stored in the ray
+	*/
   float ComputeSampleContributions(const VssRayContainer &rays,
-								   const bool addContributions = true);
+								   const bool addContributions,
+								   const bool storeViewCells);
 
   /** Add sample contributions to the viewcells they intersect */
@@ -85,5 +91,5 @@
 		@returns number of sample contributions
 	*/
-	virtual float ComputeSampleContributions(VssRay &ray, const bool addRays = true);
+	virtual float ComputeSampleContributions(VssRay &ray, const bool addRays, const bool storeViewCells);
 
   virtual void AddSampleContributions(VssRay &ray);
@@ -147,7 +153,11 @@
 	void SetVisualizationSamples(const int visSamples);
 
+	/** Sets maximal number of samples used for the construction of the view cells.
+	*/
+	void SetConstructionSamples(const int constructionSamples);
+
 	/** Sets maximal number of samples used for the visualization of the view cells.
 	*/
-	void SetConstructionSamples(const int constructionSamples);
+	void SetInitialSamples(const int initialSamples);
 
 	/** Sets maximal number of samples used for the post processing of the view cells.
@@ -306,7 +316,7 @@
 protected:
 
-	int CastPassSamples(int samplesPerPass, 
-						int sampleType, 
-						VssRayContainer *outRays) const;
+	int CastPassSamples(const int samplesPerPass, 
+						const int sampleType, 
+						VssRayContainer &vssRays) const;
 
 	void ParseEnvironment();
@@ -367,4 +377,6 @@
 	/// maximum number of samples taken for construction of the view cells
 	int mConstructionSamples;
+	int mSamplesPerPass;
+	int mInitialSamples;
 	int mPostProcessSamples;
 	int mVisualizationSamples;
@@ -409,9 +421,9 @@
 		used to construct the bsp tree.
 	*/
-	BspViewCellsManager(BspTree *tree, int constructionSamples);
+	BspViewCellsManager(BspTree *tree);
 
 	~BspViewCellsManager();
 
-	int Construct(const ObjectContainer &objects, 
+	int ConstructSubdivision(const ObjectContainer &objects, 
 				  const VssRayContainer &rays);
 
@@ -482,5 +494,5 @@
 	KdViewCellsManager(KdTree *tree);
 
-	int Construct(const ObjectContainer &objects, 
+	int ConstructSubdivision(const ObjectContainer &objects, 
 				  const VssRayContainer &rays);
 
@@ -536,7 +548,7 @@
 public:
 
-	VspKdViewCellsManager(VspKdTree *vspKdTree, int constructionSamples);
-
-	int Construct(const ObjectContainer &objects, 
+	VspKdViewCellsManager(VspKdTree *vspKdTree);
+
+	int ConstructSubdivision(const ObjectContainer &objects, 
 				  const VssRayContainer &rays);
 
@@ -595,8 +607,8 @@
 public:
 
-	VspBspViewCellsManager(VspBspTree *tree, int constructionSamples);
+	VspBspViewCellsManager(VspBspTree *tree);
 	~VspBspViewCellsManager();
 
-	int Construct(const ObjectContainer &objects, 
+	int ConstructSubdivision(const ObjectContainer &objects, 
 				  const VssRayContainer &rays);
 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp	(revision 574)
@@ -178,5 +178,5 @@
 const BspTreeStatistics &VspBspTree::GetStatistics() const
 {
-	return mStat;
+	return mBspStats;
 }
 
@@ -273,5 +273,5 @@
 						   AxisAlignedBox3 *forcedBoundingBox)
 {
-	mStat.nodes = 1;
+	mBspStats.nodes = 1;
 	mBox.Initialize(); 	// initialise BSP tree bounding box
 
@@ -353,5 +353,5 @@
 		mTermMinProbability *= mBox.GetVolume();
 
-	mStat.polys = (int)polys.size();
+	mBspStats.polys = (int)polys.size();
 
 	cout << "finished" << endl;
@@ -373,7 +373,7 @@
 	return
 		(sizeof(VspBspTree) +
-		 mStat.Leaves() * sizeof(BspLeaf) +
-		 mStat.Interior() * sizeof(BspInterior) +
-		 mStat.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
+		 mBspStats.Leaves() * sizeof(BspLeaf) +
+		 mBspStats.Interior() * sizeof(BspInterior) +
+		 mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
 }
 
@@ -405,5 +405,5 @@
 	tStack.push(tData);
 
-	mStat.Start();
+	mBspStats.Start();
 	cout << "Contructing vsp bsp tree ... \n";
 
@@ -439,9 +439,9 @@
 				  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
 
-		if (mStat.Leaves() >= nleaves)
+		if (mBspStats.Leaves() >= nleaves)
 		{
 			nleaves += 500;
 				
-			cout << "leaves=" << mStat.Leaves() << endl;
+			cout << "leaves=" << mBspStats.Leaves() << endl;
 			Debug << "needed "
 			  << TimeDiff(interTime, GetTime())*1e-3 << " secs to create 500 leaves" << endl;
@@ -453,5 +453,5 @@
 	cout << "finished\n";
 
-	mStat.Stop();
+	mBspStats.Stop();
 }
 
@@ -463,5 +463,5 @@
 		 (data.mPvs <= mTermMinPvs)   ||
 		 (data.mProbability <= mTermMinProbability) ||
-		 (mStat.Leaves() >= mMaxViewCells) ||
+		 (mBspStats.Leaves() >= mMaxViewCells) ||
 		 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
 		 (data.mDepth >= mTermMaxDepth));
@@ -509,6 +509,6 @@
 		AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
 
-		mStat.contributingSamples += conSamp;
-		mStat.sampleContributions +=(int) sampCon;
+		mBspStats.contributingSamples += conSamp;
+		mBspStats.sampleContributions +=(int) sampCon;
 
 		//-- store additional info
@@ -526,5 +526,5 @@
 			PropagateUpValidity(leaf);
 
-			++ mStat.invalidLeaves;
+			++ mBspStats.invalidLeaves;
 		}
 		
@@ -572,10 +572,10 @@
 		{
 			// terminate branch because of max cost
-			++ mStat.maxCostNodes;
+			++ mBspStats.maxCostNodes;
             return leaf;
 		}
 	}
 
-	mStat.nodes += 2;
+	mBspStats.nodes += 2;
 
 	//-- subdivide further
@@ -1160,5 +1160,5 @@
 		
 		//! error also computed if cost ratio is missed
-		++ mStat.splits[axis];
+		++ mBspStats.splits[axis];
 		isAxisAlignedSplit = true;
 	}
@@ -1509,32 +1509,32 @@
 
 	// store maximal and minimal depth
-	if (data.mDepth > mStat.maxDepth)
-		mStat.maxDepth = data.mDepth;
-
-	if (data.mPvs > mStat.maxPvs)
-		mStat.maxPvs = data.mPvs;
-	
-	if (data.mDepth < mStat.minDepth)
-		mStat.minDepth = data.mDepth;
+	if (data.mDepth > mBspStats.maxDepth)
+		mBspStats.maxDepth = data.mDepth;
+
+	if (data.mPvs > mBspStats.maxPvs)
+		mBspStats.maxPvs = data.mPvs;
+	
+	if (data.mDepth < mBspStats.minDepth)
+		mBspStats.minDepth = data.mDepth;
 
 	if (data.mDepth >= mTermMaxDepth)
-		++ mStat.maxDepthNodes;
+		++ mBspStats.maxDepthNodes;
 	// accumulate rays to compute rays /  leaf
-	mStat.accumRays += (int)data.mRays->size();
+	mBspStats.accumRays += (int)data.mRays->size();
 
 	if (data.mPvs < mTermMinPvs)
-		++ mStat.minPvsNodes;
+		++ mBspStats.minPvsNodes;
 
 	if ((int)data.mRays->size() < mTermMinRays)
-		++ mStat.minRaysNodes;
+		++ mBspStats.minRaysNodes;
 
 	if (data.GetAvgRayContribution() > mTermMaxRayContribution)
-		++ mStat.maxRayContribNodes;
+		++ mBspStats.maxRayContribNodes;
 
 	if (data.mProbability <= mTermMinProbability)
-		++ mStat.minProbabilityNodes;
+		++ mBspStats.minProbabilityNodes;
 	
 	// accumulate depth to compute average depth
-	mStat.accumDepth += data.mDepth;
+	mBspStats.accumDepth += data.mDepth;
 
 #ifdef _DEBUG
@@ -1655,5 +1655,5 @@
 
 
-void VspBspTree::ValidateTree()
+void VspBspTree::CollapseViewCells()
 {
 	stack<BspNode *> nodeStack;
@@ -1664,6 +1664,4 @@
 	nodeStack.push(mRoot);
 	
-	const bool addToUnbounded = false;
-
 	while (!nodeStack.empty()) 
 	{
@@ -1672,40 +1670,22 @@
 		
 		if (node->IsLeaf())
-		{
-			BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
-
-			if (!addToUnbounded && node->TreeValid())
+        {
+			BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
+
+			if (!viewCell->GetValid())
 			{
 				BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
 			
-				if (!mViewCellsManager->CheckValidity(viewCell,
-													  mViewCellsManager->GetMinPvsSize(), 
-													  mViewCellsManager->GetMaxPvsSize()))
+				vector<BspLeaf *>::const_iterator it, it_end = viewCell->mLeaves.end();
+				for (it = viewCell->mLeaves.begin();it != it_end; ++ it)
 				{
-					vector<BspLeaf *>::const_iterator it, it_end = viewCell->mLeaves.end();
-					for (it = viewCell->mLeaves.begin();it != it_end; ++ it)
-					{
-						BspLeaf *l = *it;
-						
-						l->SetTreeValid(false);
-						PropagateUpValidity(l);
-						
-						if (addToUnbounded)
-							l->SetViewCell(GetOrCreateOutOfBoundsCell());
-
-						++ mStat.invalidLeaves;
-					}
-
-					// add to unbounded view cell or set to invalid
-					if (addToUnbounded)
-					{
-						GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
-						DEL_PTR(viewCell);
-					}
-					else
-					{
-						viewCell->SetValid(false);
-					}
+					BspLeaf *l = *it;
+					l->SetViewCell(GetOrCreateOutOfBoundsCell());
+					++ mBspStats.invalidLeaves;
 				}
+
+				// add to unbounded view cell
+				GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
+				DEL_PTR(viewCell);
 			}
 		}
@@ -1719,6 +1699,49 @@
 	}
 
-	Debug << "invalid leaves: " << mStat.invalidLeaves << endl;
-}
+	Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
+}
+
+
+void VspBspTree::ValidateTree()
+{
+	stack<BspNode *> nodeStack;
+
+	if (!mRoot)
+		return;
+
+	nodeStack.push(mRoot);
+	
+	mBspStats.invalidLeaves = 0;
+	while (!nodeStack.empty()) 
+	{
+		BspNode *node = nodeStack.top();
+		nodeStack.pop();
+		
+		if (node->IsLeaf())
+		{
+			BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
+
+			if (!leaf->GetViewCell()->GetValid())
+				++ mBspStats.invalidLeaves;
+
+			// validity flags don't match => repair
+			if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
+			{
+				leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
+				PropagateUpValidity(leaf);
+			}
+		}
+		else
+		{
+			BspInterior *interior = dynamic_cast<BspInterior *>(node);
+		
+			nodeStack.push(interior->GetFront());
+			nodeStack.push(interior->GetBack());
+		}
+	}
+
+	Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
+}
+
 
 
@@ -1784,9 +1807,10 @@
 	int splits = 0;
 
-	while (!rays.empty())
-	{
-		RayInfo bRay = rays.back();
-		rays.pop_back();
-
+	RayInfoContainer::const_iterator it, it_end = rays.end();
+
+	for (it = rays.begin(); it != it_end; ++ it)
+	{
+		RayInfo bRay = *it;
+		
 		VssRay *ray = bRay.mRay;
 		float t;
@@ -2213,8 +2237,9 @@
 	int splits = 0;
 
-	while (!polys.empty())
-	{
-		Polygon3 *poly = polys.back();
-		polys.pop_back();
+	PolygonContainer::const_iterator it, it_end = polys.end();
+
+	for (it = polys.begin(); it != polys.end(); ++ it)	
+	{
+		Polygon3 *poly = *it;
 
 		// classify polygon
@@ -2632,5 +2657,5 @@
 		BspLeaf *leaf = *it;
 		
-		/// create leaf pvs (needed for post processing
+		/// create leaf pvs (needed for post processing)
 		leaf->mPvs = new ObjectPvs(leaf->GetViewCell()->GetPvs());
 
@@ -2674,14 +2699,9 @@
 int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays)
 {
-	vector<BspRay *> bspRays;
-
 	ViewCell::NewMail();
 	long startTime = GetTime();
-	ConstructBspRays(bspRays, rays);
-	Debug << (int)bspRays.size() << " bsp rays constructed in " 
-		  << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
-
+	
 	map<BspLeaf *, vector<BspLeaf*> > neighborMap;
-	vector<BspIntersection>::const_iterator iit;
+	ViewCellContainer::const_iterator iit;
 
 	int numLeaves = 0;
@@ -2689,15 +2709,16 @@
 	BspLeaf::NewMail();
 
-	for (int i = 0; i < (int)bspRays.size(); ++ i)
+	for (int i = 0; i < (int)rays.size(); ++ i)
 	{  
-		BspRay *ray = bspRays[i];
+		VssRay *ray = rays[i];
 	
 		// traverse leaves stored in the rays and compare and 
 		// merge consecutive leaves (i.e., the neighbors in the tree)
-		if (ray->intersections.size() < 2)
+		if (ray->mViewCells.size() < 2)
 			continue;
 	  
-		iit = ray->intersections.begin();
-		BspLeaf *leaf = (*(iit ++)).mLeaf;
+		iit = ray->mViewCells.begin();
+		BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
+		BspLeaf *leaf = bspVc->mLeaves[0];
 		
 		// create leaf pvs (needed for post processing)
@@ -2715,9 +2736,10 @@
 		// traverse intersections 
 		// consecutive leaves are neighbors => add them to queue
-		for (; iit != ray->intersections.end(); ++ iit)
+		for (; iit != ray->mViewCells.end(); ++ iit)
 		{
 			// next pair
 			BspLeaf *prevLeaf = leaf;
-            leaf = (*iit).mLeaf;
+			bspVc = dynamic_cast<BspViewCell *>(*iit);
+            leaf = bspVc->mLeaves[0];
 
 			// view space not valid or same view cell
@@ -2781,6 +2803,4 @@
 	Debug << "overall cost: " << BspMergeCandidate::sOverallCost << endl;
 
-	CLEAR_CONTAINER(bspRays);
-
 	//-- collect the leaves which haven't been found by ray casting
 	if (0)
@@ -2857,8 +2877,8 @@
 	mergeStats.Start();
 	
-	//BspMergeCandidate::sOverallCost = mBox.SurfaceArea() * mStat.maxPvs;
+	//BspMergeCandidate::sOverallCost = mBox.SurfaceArea() * mBspStats.maxPvs;
 	long startTime = GetTime();
 
-	cout << "collecting merge candidates ... ";
+	cout << "collecting merge candidates ... " << endl;
 	
 	if (mUseRaysForMerge)
@@ -2880,5 +2900,5 @@
 
 	// number of view cells withouth the invalid ones
-	int nViewCells = mStat.Leaves() - mStat.invalidLeaves;
+	int nViewCells = mBspStats.Leaves() - mBspStats.invalidLeaves;
 	
 	
@@ -3370,8 +3390,27 @@
 void VspBspTree::PropagateUpValidity(BspNode *node)
 {
-	while (!node->IsRoot() && node->GetParent()->TreeValid())
-	{
-		node = node->GetParent();
-		node->SetTreeValid(false);
+	const bool isValid = node->TreeValid();
+
+	// propagative up invalid flag until only invalid nodes exist over this node
+	if (!isValid)
+	{
+		while (!node->IsRoot() && node->GetParent()->TreeValid())
+		{
+			node = node->GetParent();
+			node->SetTreeValid(false);
+		}
+	}
+	else
+	{
+		// propagative up valid flag until one of the subtrees is invalid
+		while (!node->IsRoot() && !node->TreeValid())
+		{
+            node = node->GetParent();
+			BspInterior *interior = dynamic_cast<BspInterior *>(node);
+			
+			// the parent is valid iff both leaves are valid
+			node->SetTreeValid(interior->GetBack()->TreeValid() && 
+							   interior->GetFront()->TreeValid());
+		}
 	}
 }
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 564)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 574)
@@ -1206,4 +1206,14 @@
 			"bspTree");
 
+	RegisterOption("ViewCells.Construction.samples",
+					optInt,
+					"view_cells_construction_samples=",
+					"5000000");
+
+	RegisterOption("ViewCells.Construction.samplesPerPass",
+					optInt,
+					"view_cells_construction_samples_per_pass=",
+					"500000");
+
 	RegisterOption("ViewCells.PostProcess.samples",
 					optInt,
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp	(revision 574)
@@ -314,9 +314,10 @@
 	Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
 #endif
-	while (!polys.empty())
-	{
-		Polygon3 *poly = polys.back();
-		polys.pop_back();
-
+	PolygonContainer::const_iterator it, it_end = polys.end();
+
+	for (it = polys.begin(); it != polys.end(); ++ it)	
+	{
+		Polygon3 *poly = *it;
+	
 		//-- classify polygon
 		const int cf = poly->ClassifyPlane(plane, mEpsilon);
@@ -2538,4 +2539,6 @@
 BspNodeGeometry::BspNodeGeometry(const BspNodeGeometry &rhs)
 {
+	mPolys.reserve(rhs.mPolys.size());
+	
 	PolygonContainer::const_iterator it, it_end = rhs.mPolys.end();
 	for (it = rhs.mPolys.begin(); it != it_end; ++ it)
@@ -2545,4 +2548,5 @@
 	}
 }
+
 
 BspNodeGeometry::~BspNodeGeometry()
@@ -2700,4 +2704,5 @@
 }
 
+
 Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
 										const float epsilon) const
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.cpp	(revision 564)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/RenderSimulator.cpp	(revision 574)
@@ -24,4 +24,13 @@
 		<< avgRtWithoutOverhead << "\n";
 	
+	app << "#VALID_MAX_COST ( maximal cost of a valid view cell )\n" << validMaxCost << "\n";
+
+	app << "#VALID_MIN_COST ( minimal cost of a valid view cell )\n" << validMinCost << "\n";
+
+	app << "#VALID_AVG_RENDER_TIME ( average render time )\n" << validAvgRenderTime << "\n";
+
+	app << "#VALID_AVG_RENDER_TIME_NO_OVERHEAD ( valid average render time without overhead )\n" 
+		<< validAvgRtWithoutOverhead << "\n";
+	
 	app << "===== END OF Render Simulation statistics ==========\n";
 }
@@ -31,6 +40,5 @@
 mObjRenderCost(0.0f), 
 mVcOverhead(0.0f), 
-mMoveSpeed(0.0f),
-mOnlyValid(false)
+mMoveSpeed(0.0f)
 {}
 
@@ -43,6 +51,5 @@
 mObjRenderCost(objRenderCost), 
 mVcOverhead(vcOverhead), 
-mMoveSpeed(moveSpeed),
-mOnlyValid(false)
+mMoveSpeed(moveSpeed)
 {
 }
@@ -55,10 +62,4 @@
 
 
-void RenderSimulator::SetRenderOnlyValid(const bool renderOnlyValid)
-{
-	mOnlyValid = renderOnlyValid;
-}
-
-
 void RenderSimulator::SetVcOverhead(const float vcOverhead)
 {
@@ -66,8 +67,10 @@
 }
 
+
 void RenderSimulator::SetMoveSpeed(const float moveSpeed)
 {
 	mMoveSpeed = moveSpeed;
 }
+
 
 bool RenderSimulator::RenderScene()
@@ -77,8 +80,10 @@
 
 	Real renderTime = 0;
-	
+	Real validRenderTime = 0;
+
 	// overhead for loading the PVS of the view cells
 	float loadPvsOverhead = 0;
-	
+	float validLoadPvsOverhead = 0;
+
 	ViewCellContainer::const_iterator it, 
 		it_end = mViewCellsManager->GetViewCells().end();
@@ -89,6 +94,6 @@
 		ViewCell *vc = *it;
 
-		if (mOnlyValid && !vc->GetValid())
-			continue;
+		const bool valid = !vc->GetValid();
+	
 
 		// probability of view cell
@@ -103,19 +108,31 @@
 		// speed and the probability that a view cell border is crossed
 		loadPvsOverhead += GetCrossVcProbability() * mVcOverhead;
-
-		//Debug << "vccost: " << vcCost << " p in vc " << pInVc
-		//<< " cross vc " << GetCrossVcProbability() << endl;
+		renderTime += vcCost;
 
 		//-- update statistics
-		renderTime += vcCost;
-	
+
 		if (vcCost > mSimulationStatistics.maxCost)
 			mSimulationStatistics.maxCost = vcCost;
 		else if (vcCost < mSimulationStatistics.minCost)
 			mSimulationStatistics.minCost = vcCost;
+
+		//-- different statistics for only valid view cells
+		if (valid)
+		{
+			validLoadPvsOverhead += GetCrossVcProbability() * mVcOverhead;
+			validRenderTime += vcCost;
+		
+			if (vcCost > mSimulationStatistics.validMaxCost)
+				mSimulationStatistics.validMaxCost = vcCost;
+			else if (vcCost < mSimulationStatistics.validMinCost)
+				mSimulationStatistics.validMinCost = vcCost;
+		}
 	}
 	
 	mSimulationStatistics.avgRtWithoutOverhead = renderTime;
 	mSimulationStatistics.avgRenderTime = renderTime + loadPvsOverhead;
+
+	mSimulationStatistics.validAvgRtWithoutOverhead = renderTime;
+	mSimulationStatistics.validAvgRenderTime = renderTime + loadPvsOverhead;
 	
 	mSimulationStatistics.Stop();
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp	(revision 567)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Preprocessor.cpp	(revision 574)
@@ -194,5 +194,5 @@
 	environment->GetStringValue("ViewCells.type", viewCellsStr);
 
-	int constructionSamples = 0;
+	int initialSamples = 0;
 	
 	if (strcmp(viewCellsStr, "kdTree") == 0)
@@ -206,6 +206,5 @@
 		Debug << "view cell type: Bsp" << endl;
 
-		environment->GetIntValue("BspTree.Construction.samples", constructionSamples);
-		mViewCellsManager = new BspViewCellsManager(mBspTree, constructionSamples);
+		mViewCellsManager = new BspViewCellsManager(mBspTree);
 	}
 	else if (strcmp(viewCellsStr, "vspBspTree") == 0)
@@ -215,6 +214,5 @@
 		Debug << "view cell type: VspBsp" << endl;
 
-		environment->GetIntValue("VspBspTree.Construction.samples", constructionSamples);
-		mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, constructionSamples);
+		mViewCellsManager = new VspBspViewCellsManager(mVspBspTree);
 	}
 	else if (strcmp(viewCellsStr, "vspKdTree") == 0)
@@ -222,6 +220,5 @@
 		mVspKdTree = new VspKdTree();		
 	
-		environment->GetIntValue("VspKdTree.Construction.samples", constructionSamples);
-        mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, constructionSamples);
+		mViewCellsManager = new VspKdViewCellsManager(mVspKdTree);
 	}
 	else if (strcmp(viewCellsStr, "sceneDependent") == 0)
@@ -231,6 +228,6 @@
 
 		Debug << "view cell type: Bsp" << endl;
-		environment->GetIntValue("BspTree.Construction.samples", constructionSamples);
-		mViewCellsManager = new BspViewCellsManager(mBspTree, constructionSamples);
+		
+		mViewCellsManager = new BspViewCellsManager(mBspTree);
 	}
 	else
@@ -248,19 +245,11 @@
 	mRenderSimulator = 
 		new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
-	
-	int postProcessSamples = 0;
-	int visSamples = 0;
-
-	environment->GetIntValue("ViewCells.PostProcess.samples", postProcessSamples);
- 	environment->GetIntValue("ViewCells.Visualization.samples", visSamples);
-
-	mViewCellsManager->SetPostProcessSamples(postProcessSamples);
-	mViewCellsManager->SetVisualizationSamples(visSamples);
+
 	mViewCellsManager->SetRenderer(mRenderSimulator);
 
-	
 	//-- parse view cells construction method
 	environment->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
 	char buf[100];
+
 	if (mLoadViewCells)
 	{
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/RssPreprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/RssPreprocessor.cpp	(revision 572)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/RssPreprocessor.cpp	(revision 574)
@@ -441,4 +441,13 @@
 
   }
+  else
+  {
+	  // construct view cells using it's own set of samples
+	  mViewCellsManager->Construct(this);
+
+	  //-- several visualizations and statistics
+	  Debug << "view cells after construction: " << endl;
+	  mViewCellsManager->PrintStatistics(Debug);
+  }
   
   int rssPass = 0;
@@ -476,12 +485,7 @@
 	
   if (mUseViewcells) {
-	// construct view cells
-	if (!mLoadViewCells)
-	  mViewCellsManager->Construct(mObjects, mVssRays);
-
-	
 
 	// evaluate contributions of the intitial rays
-	mViewCellsManager->ComputeSampleContributions(mVssRays);
+	mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
 	
 	
@@ -502,21 +506,4 @@
 	mViewCellsManager->PrintPvsStatistics(mStats);
 	  
-	VssRayContainer selectedRays;
-	int desired = Max(
-					  mViewCellsManager->GetPostProcessSamples(),
-					  mViewCellsManager->GetVisualizationSamples());
-	
-	mVssRays.SelectRays(desired, selectedRays);
-	  
-	//-- post process view cells
-	mViewCellsManager->PostProcess(mObjects, selectedRays);
-	  
-	//-- several visualizations and statistics
-	Debug << "view cells after post processing: " << endl;
-	mViewCellsManager->PrintStatistics(Debug);
-	
-	if (1) 
-	  mViewCellsManager->Visualize(mObjects, selectedRays);
-
 	// viewcells->UpdatePVS(newVssRays);
 	Debug<<"Valid viewcells before set validity: "<<mViewCellsManager->CountValidViewcells()<<endl;
@@ -534,5 +521,5 @@
   
   /// compute view cell contribution of rays if view cells manager already constructed
-  mViewCellsManager->ComputeSampleContributions(mVssRays);
+  mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
 
   if (mUseImportanceSampling) {
@@ -571,5 +558,5 @@
 	  CastRays(rays, tmpVssRays);
 	  castRays += rays.size();
-	  float c1 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false);
+	  float c1 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false, true);
 	  mStats<<"#RssRelContrib"<<endl<<c1/rays.size()<<endl;
 
@@ -582,5 +569,5 @@
 		CastRays(rays, tmpVssRays);
 		castRays += rays.size();
-		float c2 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false);
+		float c2 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false, true);
 		mStats<<"#SpatialRelContrib"<<endl<<c2/rays.size()<<endl;
 		
@@ -596,5 +583,5 @@
 		CastRays(rays, tmpVssRays);
 		castRays += rays.size();
-		float c3 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false);
+		float c3 = mViewCellsManager->ComputeSampleContributions(tmpVssRays, false, true);
 		mStats<<"#DirectionalRelContrib"<<endl<<c3/rays.size()<<endl;
 		
@@ -622,5 +609,5 @@
 	  if (mUseViewcells) {
 		/// compute view cell contribution of rays
-		mViewCellsManager->ComputeSampleContributions(vssRays);
+		mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
 	  }
 	  	
@@ -646,6 +633,5 @@
 	  mViewCellsManager->PrintPvsStatistics(mStats);
 	}
-
-
+	
 	ComputeRenderError();
 	
@@ -709,15 +695,27 @@
   if (mUseViewcells) {
 
-	
-	//-- render simulation after merge
-	cout << "\nevaluating bsp view cells render time after merge ... ";
-	
-	mRenderSimulator->RenderScene();
-	SimulationStatistics ss;
-	mRenderSimulator->GetStatistics(ss);
-	
-	cout << " finished" << endl;
-	cout << ss << endl;
-	Debug << ss << endl;
+	  if(0)
+	  {
+		  VssRayContainer selectedRays;
+		  int desired = mViewCellsManager->GetVisualizationSamples();
+
+		  mVssRays.SelectRays(desired, selectedRays);
+
+		  mViewCellsManager->Visualize(mObjects, selectedRays);
+	  }
+	  
+	  // view cells after sampling
+	  mViewCellsManager->PrintStatistics(Debug);
+      
+	  //-- render simulation after merge
+	  cout << "\nevaluating bsp view cells render time after sampling ... ";
+	  
+	  mRenderSimulator->RenderScene();
+	  SimulationStatistics ss;
+	  mRenderSimulator->GetStatistics(ss);
+	  
+	  cout << " finished" << endl;
+	  cout << ss << endl;
+	  Debug << ss << endl;
 	
   }
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp	(revision 564)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp	(revision 574)
@@ -27,6 +27,5 @@
   environment->GetIntValue("VssPreprocessor.vssSamplesPerPass", mVssSamplesPerPass);
   environment->GetBoolValue("VssPreprocessor.useImportanceSampling", mUseImportanceSampling);
-  environment->GetBoolValue("ViewCells.delayedConstruction", mDelayedViewCellsConstruction);
-
+ 
   environment->GetBoolValue("VssPreprocessor.loadInitialSamples", mLoadInitialSamples);
   environment->GetBoolValue("VssPreprocessor.storeInitialSamples", mStoreInitialSamples);
@@ -54,4 +53,16 @@
   ray.Init(point, direction, Ray::LOCAL_RAY);
 }
+
+
+void
+VssPreprocessor::CastRays(
+						  SimpleRayContainer &rays,
+						  VssRayContainer &vssRays
+						  )
+{
+  for (int i=0; i < rays.size(); i++)
+	CastRay(rays[i].mOrigin, rays[i].mDirection, vssRays);
+}
+
 
 int
@@ -529,5 +540,14 @@
 	  mViewCellsManager->LoadViewCells(mViewCellsFilename, &mObjects);
   }
-
+  else
+  {
+	  // construct view cells using it's own set of samples
+	  mViewCellsManager->Construct(this);
+
+	  //-- several visualizations and statistics
+	  Debug << "view cells after construction: " << endl;
+	  mViewCellsManager->PrintStatistics(Debug);
+  }
+	
 
   VssTree *vssTree = NULL;
@@ -634,11 +654,4 @@
   }
 
-  /// compute view cell contribution of rays if view cells manager already constructed
-  mViewCellsManager->ComputeSampleContributions(mVssRays);
-
-  // construct view cells
-  if (!mDelayedViewCellsConstruction)
-	mViewCellsManager->Construct(mObjects, mVssRays);
- 
   vssTree = new VssTree;
   // viewcells = Construct(mVssRays);
@@ -712,21 +725,6 @@
 	cout<<"Average PVS size = "<<avgPvs<<endl;
 
-	// construct view cells after vss
-	if (!mViewCellsManager->ViewCellsConstructed() && 
-		(samples + mInitialSamples >= mViewCellsManager->GetConstructionSamples()))
-	{
-		Debug << "samples " << samples << " initial " << mInitialSamples << " " << samples + mInitialSamples << endl;
-		VssRayContainer constructionRays;
-		vssTree->CollectRays(constructionRays, mViewCellsManager->GetConstructionSamples());
-
-		Debug << "collected rays: " << constructionRays.size() << endl;
-
-		// test if we really have enough rays
-		//if (constructionRays.size() >= nSamples) 
-		mViewCellsManager->Construct(mObjects, constructionRays);
-	}
-
 	/// compute view cell contribution of rays
-	mViewCellsManager->ComputeSampleContributions(vssRays);
+	mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
 	
 	if (numExportRays) {
@@ -750,29 +748,4 @@
   }
 
-
-  // at the latest create view cells here
-  if (!mViewCellsManager->ViewCellsConstructed())
-  {
-	  VssRayContainer constructionRays;
-
-	  vssTree->CollectRays(constructionRays, 
-						   mViewCellsManager->GetConstructionSamples());
-	  Debug << "collected rays: " << constructionRays.size() << endl;
-
-	  mViewCellsManager->Construct(mObjects, constructionRays);
-  }
-
-  Debug << vssTree->stat << endl;
-  VssRayContainer viewCellRays;
-  
-  // compute rays used for view cells construction
-  int numRays = Max(mViewCellsManager->GetPostProcessSamples(),
-					mViewCellsManager->GetVisualizationSamples());
-
-  vssTree->CollectRays(viewCellRays, numRays);
-  
-  //-- post process view cells
-  mViewCellsManager->PostProcess(mObjects, viewCellRays);
-
   if (mTestBeamSampling && mUseGlRenderer)
   {	
@@ -780,12 +753,18 @@
   }
 
-  //-- several visualizations and statistics
-  Debug << "\nview cells after post processing: " << endl;
-  mViewCellsManager->PrintStatistics(Debug);
-
-  mViewCellsManager->Visualize(mObjects, viewCellRays);
-  
+  Debug << vssTree->stat << endl;
+
+  if (0)
+  {
+	VssRayContainer viewCellRays;
+  
+	// compute rays used for view cells construction
+	const int numRays = mViewCellsManager->GetVisualizationSamples();
+
+	vssTree->CollectRays(viewCellRays, numRays);
+  }
+
   //-- render simulation after merge
-  cout << "\nevaluating bsp view cells render time after merge ... ";
+  cout << "\nevaluating bsp view cells render time after sampling ... ";
   mRenderSimulator->RenderScene();
   SimulationStatistics ss;
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp	(revision 570)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/main.cpp	(revision 574)
@@ -67,5 +67,5 @@
 
   QApplication *app = NULL;
-  
+
   if (p->mUseGlRenderer) {
 	// create a qt application first (must be created before any opengl widget...
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp	(revision 544)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/Polygon3.cpp	(revision 574)
@@ -7,9 +7,16 @@
 Polygon3::Polygon3(): 
 mMaterial(NULL), mParent(NULL), mPiercingRays(0)
-{}
+{
+	// mostly there will be triangles
+	//mVertices.reserve(3);
+}
 
 Polygon3::Polygon3(const VertexContainer &vertices): 
-mVertices(vertices), mMaterial(NULL), mParent(NULL), mPiercingRays(0)
-{}
+mMaterial(NULL), mParent(NULL), mPiercingRays(0)
+{
+	mVertices.reserve(vertices.size());
+	mVertices = vertices;
+}
+
 
 Polygon3::Polygon3(MeshInstance *parent): 
@@ -17,14 +24,19 @@
 {}
 
+
 Polygon3::Polygon3(Face *face, Mesh *parentMesh):
 mMaterial(NULL), mParent(NULL), mPiercingRays(0)
 {	
+	mVertices.reserve(face->mVertexIndices.size());
+	
 	VertexIndexContainer::iterator it = face->mVertexIndices.begin();
 	for (; it != face->mVertexIndices.end();  ++it)
 	{
 		mVertices.push_back(parentMesh->mVertices[*it]);
-		mMaterial = parentMesh->mMaterial;
-	}
-}
+	}
+
+	mMaterial = parentMesh->mMaterial;
+}
+
 
 Plane3 Polygon3::GetSupportingPlane() const
@@ -32,4 +44,5 @@
 	return Plane3(mVertices[0], mVertices[1], mVertices[2]);
 }
+
 
 Vector3 Polygon3::GetNormal() const 
@@ -113,4 +126,5 @@
 }
 
+
 float Polygon3::GetArea() const
 {
@@ -123,4 +137,5 @@
 }
 
+
 int Polygon3::Side(const Plane3 &plane, 
 				   const float epsilon) const
@@ -136,8 +151,9 @@
 }
 
+
 int Polygon3::ClassifyPlane(const Plane3 &plane, 
 							const float epsilon) const
 {
-	VertexContainer::const_iterator it;
+	VertexContainer::const_iterator it, it_end = mVertices.end();
 
 	bool onFrontSide = false;
@@ -146,5 +162,5 @@
 	int count = 0;
 	// find possible line-plane intersections
-	for (it = mVertices.begin(); it != mVertices.end(); ++ it)
+	for (it = mVertices.begin(); it != it_end; ++ it)
 	{
 		const int side = plane.Side(*it, epsilon);
@@ -179,9 +195,4 @@
 }
 
-/*int Polygon3::ClassifyPlane(const Plane3 &plane) const
-{
-	return ClassifyPlane(plane, Limits::Small);
-}*/
-
 
 Vector3
@@ -212,27 +223,35 @@
 		return false;
 
-#if 1
-	// check if area exceeds certain size
-	if (AREA_LIMIT > GetArea())
-	{
-		//Debug << "area too small: " << GetArea() << endl;
-		return false;
-	}
-#else
-	Vector3 vtx = mVertices.back();
-	VertexContainer::const_iterator it, it_end = mVertices.end();
-
-	for (it = mVertices.begin(); it != it_end; ++it)
-	{
-		if (!(EpsilonEqual(vtx, *it)))
-		{
-			//Debug << "Malformed vertices:\n" << *this << endl;
+	//TODO: remove for performance
+#if 0
+	if (1)
+	{
+		// check if area exceeds certain size
+		if (GetArea() < AREA_LIMIT)
+		{
+			Debug << "area too small: " << GetArea() << endl;
 			return false;
 		}
-		vtx = *it;
-	}
-#endif	
+	}
+	else
+	{
+		Vector3 vtx = mVertices.back();
+		VertexContainer::const_iterator it, it_end = mVertices.end();
+
+		for (it = mVertices.begin(); it != it_end; ++it)
+		{
+			if (!(EpsilonEqualV3(vtx, *it)))
+			{
+				//Debug << "Malformed vertices:\n" << *this << endl;
+				return false;
+			}
+			vtx = *it;
+		}
+	}
+#endif
+
 	return true;
 }
+
 
 void Polygon3::IncludeInBox(const PolygonContainer &polys, AxisAlignedBox3 &box)
@@ -243,4 +262,5 @@
 		box.Include(*(*it));
 }
+
 
 // int_lineseg returns 1 if the given line segment intersects a 2D
@@ -283,4 +303,5 @@
 }
 
+
 int Polygon3::CastRay(const Ray &ray, float &t, const float nearestT)
 {
@@ -353,4 +374,5 @@
 	return (count & 1) ? Ray::INTERSECTION : Ray::NO_INTERSECTION;
 }
+
 
 void Polygon3::InheritRays(Polygon3 &front_piece, 
@@ -385,4 +407,5 @@
 }
 
+
 int Polygon3::ClassifyPlane(const PolygonContainer &polys, 
 							const Plane3 &plane,
@@ -422,4 +445,5 @@
 }
 
+
 int Polygon3::ParentObjectsSize(const PolygonContainer &polys)
 {
@@ -441,4 +465,5 @@
 }
 
+
 float Polygon3::GetArea(const PolygonContainer &cell)
 {
@@ -448,7 +473,4 @@
 	for (pit = cell.begin(); pit != cell.end(); ++ pit)
 	{
-		if ((*pit)->mVertices.size() < 3)
-			Debug << "ERROR" << endl;
-
 		area += (*pit)->GetArea();
 	}
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp	(revision 563)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp	(revision 574)
@@ -67,5 +67,5 @@
   }
   
-  mViewCellsManager->ComputeSampleContributions(vssRays, true);
+  mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
   CLEAR_CONTAINER(vssRays);
 }
@@ -78,5 +78,5 @@
 	VssRay vssRay(ray);
 
-	mViewCellsManager->ComputeSampleContributions(vssRay);
+	mViewCellsManager->ComputeSampleContributions(vssRay, true, false);
 	
 	return vssRay.mPvsContribution;
@@ -384,5 +384,5 @@
 	// construct view cells if not already constructed
 	if (!mViewCellsManager->ViewCellsConstructed())
-	  mViewCellsManager->Construct(mObjects, mVssSampleRays);
+	  mViewCellsManager->ConstructSubdivision(mObjects, mVssSampleRays);
 
 	// $$JB temporary removed
@@ -394,7 +394,4 @@
 
 	//-- render simulation after merge
-	cout << "\nevaluating bsp view cells render time after merge ... ";
-		 
-	 //-- render simulation after merge
 	cout << "\nevaluating bsp view cells render time after merge ... ";
 	
@@ -434,5 +431,5 @@
 		{
 		  // construct view cells
-		  mViewCellsManager->Construct(objects, mVssSampleRays);
+		  mViewCellsManager->ConstructSubdivision(objects, mVssSampleRays);
 		  
 		  // throw away samples 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h	(revision 535)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h	(revision 574)
@@ -37,6 +37,4 @@
   VssRayContainer mVssRays;
 	
-  bool mDelayedViewCellsConstruction;
-
   VssPreprocessor();
   ~VssPreprocessor();
@@ -52,4 +50,6 @@
 			   );
 	
+  void CastRays(SimpleRayContainer &rays, VssRayContainer &vssRays);
+
   void
   SetupRay(Ray &ray, 
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp	(revision 573)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp	(revision 574)
@@ -20,4 +20,5 @@
 ViewCellsManager::ViewCellsManager():
 mRenderer(NULL),
+mInitialSamples(0),
 mConstructionSamples(0),
 mPostProcessSamples(0),
@@ -35,21 +36,4 @@
 
 
-ViewCellsManager::ViewCellsManager(int constructionSamples):
-mConstructionSamples(constructionSamples),
-mRenderer(NULL),
-mPostProcessSamples(0),
-mVisualizationSamples(0),
-mTotalAreaValid(false),
-mTotalArea(0.0f),
-mViewCellsFinished(false),
-mMaxPvsSize(9999999),
-mMinPvsSize(0), // one means only empty view cells are invalid
-mMaxPvsRatio(1.0)
-{
-	mViewSpaceBox.Initialize();
-	ParseEnvironment();
-}
-
-
 void ViewCellsManager::ParseEnvironment()
 {
@@ -61,4 +45,10 @@
 	environment->GetBoolValue("ViewCells.pruneEmptyViewCells", emptyViewCells);
 	environment->GetBoolValue("ViewCells.processOnlyValidViewCells", mOnlyValidViewCells);
+
+	environment->GetIntValue("ViewCells.Construction.samples", mConstructionSamples);
+	environment->GetIntValue("ViewCells.PostProcess.samples", mPostProcessSamples);
+ 	environment->GetIntValue("ViewCells.Visualization.samples", mVisualizationSamples);
+
+	environment->GetIntValue("ViewCells.Construction.samplesPerPass", mSamplesPerPass);
 
 	mMinPvsSize = emptyViewCells ? 1 : 0;
@@ -88,9 +78,8 @@
 
 
-int ViewCellsManager::CastPassSamples(int samplesPerPass, 
-									  int sampleType, 
-									  VssRayContainer *outRays) const
-{
-	VssRayContainer passSamples;
+int ViewCellsManager::CastPassSamples(const int samplesPerPass, 
+									  const int sampleType, 
+									  VssRayContainer &passSamples) const
+{
 	SimpleRayContainer simpleRays;
 
@@ -102,17 +91,26 @@
 	preprocessor->CastRays(simpleRays, passSamples);
 
-	const int numSamples = (int)passSamples.size();
-
+	return (int)passSamples.size();
+}
+
+
+/// helper function which destroys rays or copies them into the output ray container
+inline void addOutRays(VssRayContainer &rays, VssRayContainer *outRays)
+{
+	cout << "disposing samples ... ";
 	if (outRays)
 	{
-		while (!passSamples.empty())
-			outRays->push_back(passSamples.back());
+		VssRayContainer::const_iterator it, it_end = rays.end();
+
+		for (it = rays.begin(); it != it_end; ++ it)
+		{
+			outRays->push_back(*it);
+		}
 	}
 	else
 	{
-		CLEAR_CONTAINER(passSamples);
-	}
-
-	return numSamples;
+		CLEAR_CONTAINER(rays);
+	}
+	cout << "finished" << endl;
 }
 
@@ -123,39 +121,57 @@
 	SimpleRayContainer simpleRays;
 	
-	VssRayContainer constructionSamples;
-
+	VssRayContainer initialSamples;
+
+	cout << "view cell construction: casting " << mInitialSamples << " initial samples ... ";
 	//-- construction rays => we use uniform samples for this
-	CastPassSamples(mConstructionSamples, 
-					Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION, 
-					&constructionSamples);
+	CastPassSamples(mInitialSamples, 
+					Preprocessor::DIRECTION_BASED_DISTRIBUTION,
+					//Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION, 
+					initialSamples);
 	
+	cout << "finished" << endl;
+
 	// construct view cells
-	const int initialSamples = Construct(preprocessor->mObjects, constructionSamples);
-
-	numSamples += initialSamples;
-
-	if (outRays)
-	{
-		while (!constructionSamples.empty())
-			outRays->push_back(constructionSamples.back());
-	}
-	else
-	{
-		CLEAR_CONTAINER(constructionSamples);
-	}
-
+	const int numInitialSamples = 
+		ConstructSubdivision(preprocessor->mObjects, initialSamples);
+
+	numSamples += numInitialSamples;
+
+	// rays can be passed or deleted
+	addOutRays(initialSamples, outRays);
+	
 
 	//-- guided rays are used for further sampling
-	const int desiredImportanceSamples = 5000000;
-	const int importanceRayPerPass = 1000000;
-
-	const int n = desiredImportanceSamples; //+initialSamples;
+	const int n = mConstructionSamples; //+initialSamples;
+
+	bool dirSamples = false;
 
 	while (numSamples < n)
 	{
-		numSamples += CastPassSamples(importanceRayPerPass, 
-									  Preprocessor::RSS_BASED_DISTRIBUTION, 
-									  //Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION,
-									  outRays);
+		cout << "casting " << mSamplesPerPass << " samples ... ";
+		VssRayContainer constructionSamples;
+
+		const int samplingType = 
+			dirSamples ? 
+						Preprocessor::DIRECTION_BASED_DISTRIBUTION :
+				 		Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION;
+
+		dirSamples = !dirSamples; // toggle sampling
+		numSamples += CastPassSamples(mSamplesPerPass, 
+									  samplingType,
+									  constructionSamples);
+
+		cout << "finished" << endl;
+
+		cout << "computing sample contribution for " << (int)constructionSamples.size() << " samples ... ";
+
+		// TODO: leak?
+		ComputeSampleContributions(constructionSamples, true, false);
+		cout << "finished" << endl;
+
+
+		addOutRays(constructionSamples, outRays);
+
+		cout << "total samples: " << numSamples << endl;
 	}
 	
@@ -165,22 +181,32 @@
 
 	//-- construction rays => we use uniform samples for this
-	CastPassSamples(max(mPostProcessSamples, mVisualizationSamples),
-				    Preprocessor::SPATIAL_BOX_BASED_DISTRIBUTION, 
-					&postProcessSamples);
+	CastPassSamples(mPostProcessSamples,
+				    Preprocessor::DIRECTION_BASED_DISTRIBUTION, 
+					postProcessSamples);
 	
+	cout << "starting post processing and visualization" << endl;
+
+	// store viewCells for postprocessing
+	const bool storeViewCells = true;
+	ComputeSampleContributions(postProcessSamples, true, storeViewCells);
 	// merge the view cells
 	PostProcess(preprocessor->mObjects, postProcessSamples);
-	// several visualizations
-	Visualize(preprocessor->mObjects, postProcessSamples);
-
-	if (outRays)
-	{
-		while (!postProcessSamples.empty())
-			outRays->push_back(postProcessSamples.back());
-	}
-	else
-	{
-		CLEAR_CONTAINER(postProcessSamples);
-	}
+
+
+	//-- visualization
+	VssRayContainer visualizationSamples;
+
+	//-- construction rays => we use uniform samples for this
+	CastPassSamples(mVisualizationSamples,
+				    Preprocessor::DIRECTION_BASED_DISTRIBUTION, 
+					visualizationSamples);
+
+	ComputeSampleContributions(visualizationSamples, true, storeViewCells);
+
+	//Debug << "visualizationsamples: " << mVisualizationSamples << " " << visualizationSamples.size() << endl;
+	// different visualizations
+	Visualize(preprocessor->mObjects, visualizationSamples);
+
+	addOutRays(visualizationSamples, outRays);
 
 	return numSamples;
@@ -293,5 +319,6 @@
 float
 ViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
-											 const bool addRays
+											 const bool addRays,
+											 const bool storeViewCells
 											 )
 {
@@ -304,5 +331,5 @@
   float sum = 0.0f;
   for (it = rays.begin(); it != it_end; ++ it) {
-	sum += ComputeSampleContributions(*(*it), addRays);
+	sum += ComputeSampleContributions(*(*it), addRays, storeViewCells);
 	//ComputeSampleContributions(*(*it), addRays);
 	//	sum += (*it)->mPvsContribution;
@@ -466,4 +493,10 @@
 {
 	mConstructionSamples = constructionSamples;
+}
+
+
+void ViewCellsManager::SetInitialSamples(const int initialSamples)
+{
+	mInitialSamples = initialSamples;
 }
 
@@ -554,5 +587,4 @@
 {
 	mViewCells.clear();
-
 	CollectViewCells();
 
@@ -610,6 +642,8 @@
 }
 
+
 float ViewCellsManager::ComputeSampleContributions(VssRay &ray,
-												   const bool addRays)
+												   const bool addRays,
+												   const bool storeViewCells)
 {
 	ViewCellContainer viewcells;
@@ -635,7 +669,7 @@
 
 	// copy viewcells memory efficiently
-	const bool storeViewcells = !addRays;
-
-	if (storeViewcells)
+	//const bool storeViewcells = !addRays;
+
+	if (storeViewCells)
 	{
 		ray.mViewCells.reserve(viewcells.size());
@@ -732,6 +766,9 @@
 	for (it = mViewCells.begin(); it != it_end; ++ it)
 	{
-		ExportColor(exporter, *it);
-		ExportVcGeometry(exporter, *it);
+		if (!mOnlyValidViewCells || (*it)->GetValid())
+		{
+			ExportColor(exporter, *it);
+			ExportVcGeometry(exporter, *it);
+		}
 	}
 }
@@ -778,9 +815,8 @@
 
 
-BspViewCellsManager::BspViewCellsManager(BspTree *bspTree,
-										 int constructionSamples):
-ViewCellsManager(constructionSamples),
-mBspTree(bspTree)
-{
+BspViewCellsManager::BspViewCellsManager(BspTree *bspTree):
+ViewCellsManager(), mBspTree(bspTree)
+{
+	environment->GetIntValue("BspTree.Construction.samples", mInitialSamples);
 }
 
@@ -798,6 +834,6 @@
 
 
-int BspViewCellsManager::Construct(const ObjectContainer &objects,
-								   const VssRayContainer &rays)
+int BspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
+											  const VssRayContainer &rays)
 {
 	// if view cells were already constructed
@@ -811,5 +847,5 @@
 	VssRayContainer savedRays;
 
-	const int limit = min(mConstructionSamples, (int)rays.size());
+	const int limit = min(mInitialSamples, (int)rays.size());
 
 	VssRayContainer::const_iterator it, it_end = rays.end();
@@ -846,5 +882,5 @@
 
 	// recast rest of the rays
-	ComputeSampleContributions(savedRays);
+	ComputeSampleContributions(savedRays, true, false);
 
 
@@ -937,44 +973,9 @@
 
 
-	// $$JB we do not have connectivity information from the ray in the moment
-	// perhaps we could recast the rays or remember the cells traversed inside the
-	// vssray (which would on other hand create some overhead)
 	//-- merge or subdivide view cells
 	int merged = 0;
 
-	vector<BspIntersection>::const_iterator iit;
-	CLEAR_CONTAINER(mBspRays);
-	ConstructBspRays(rays, mPostProcessSamples);
-
-	for (int i = 0; i < (int)mBspRays.size(); ++ i)
-	{
-		BspRay *ray = mBspRays[i];
-
-		// traverse leaves stored in the rays and compare and merge consecutive
-		// leaves (i.e., the neighbors in the tree)
-		if (ray->intersections.size() < 2)
-			continue;
-#if 0
-		iit = ray->intersections.begin();
-
-		BspLeaf *previousLeaf = (*iit).mLeaf;
-		++ iit;
-
-		for (; iit != ray->intersections.end(); ++ iit)
-		{
-			BspLeaf *leaf = (*iit).mLeaf;
-
-			if (ShouldMerge(leaf, previousLeaf))
-			{
-				MergeBspLeafViewCells(leaf, previousLeaf);
-
-				++ merged;
-			}
-
-			previousLeaf = leaf;
-		}
-#endif
-	}
-
+	// TODO
+	
 	//-- stats and visualizations
 	cout << "finished" << endl;
@@ -984,7 +985,5 @@
 	Debug << "Postprocessing: Merged " << merged << " view cells in "
 		  << TimeDiff(startTime, GetTime()) *1e-3 << " secs"
-		  << "using " << (int)mBspRays.size() << " samples" << endl << endl;
-
-	CLEAR_CONTAINER(mBspRays);
+		  << "using " << (int)rays.size() << " samples" << endl << endl;
 
 	// reset view cells and stats
@@ -997,5 +996,4 @@
 BspViewCellsManager::~BspViewCellsManager()
 {
-	CLEAR_CONTAINER(mBspRays);
 }
 
@@ -1012,7 +1010,5 @@
 	if (!ViewCellsConstructed())
 		return;
-	CLEAR_CONTAINER(mBspRays);
-	ConstructBspRays(sampleRays, mVisualizationSamples);
-
+	
 	if (1) // export view cells
 	{
@@ -1070,19 +1066,4 @@
 
 		exporter->SetFilled();
-
-		// export rays
-		if (0)
-		{
-			VssRayContainer outRays;
-
-			int raysSize = min((int)mBspRays.size(), mVisualizationSamples);
-
-			for (int i = 0; i < raysSize; ++ i)
-				// only rays piercing geometry
-				outRays.push_back(mBspRays[i]->vssRay);
-
-			// export rays
-			exporter->ExportRays(outRays, RgbColor(1, 1, 0));
-		}
 
 		if (mExportGeometry)
@@ -1345,5 +1326,5 @@
 
 
-int KdViewCellsManager::Construct(const ObjectContainer &objects,
+int KdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
 								  const VssRayContainer &rays)
 {
@@ -1359,5 +1340,5 @@
 
 	// cast rays
-	ComputeSampleContributions(rays);
+	ComputeSampleContributions(rays, true, false);
 
 	EvaluateViewCellsStats();
@@ -1605,9 +1586,8 @@
 
 
-VspKdViewCellsManager::VspKdViewCellsManager(VspKdTree *vspKdTree,
-											 int constructionSamples):
-ViewCellsManager(constructionSamples),
-mVspKdTree(vspKdTree)
-{
+VspKdViewCellsManager::VspKdViewCellsManager(VspKdTree *vspKdTree):
+ViewCellsManager(), mVspKdTree(vspKdTree)
+{
+	environment->GetIntValue("VspKdTree.Construction.samples", mInitialSamples);
 	mVspKdTree->SetViewCellsManager(this);
 }
@@ -1636,6 +1616,6 @@
 
 
-int VspKdViewCellsManager::Construct(const ObjectContainer &objects,
-									 const VssRayContainer &rays)
+int VspKdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
+												const VssRayContainer &rays)
 {
 	// if view cells already constructed
@@ -1647,5 +1627,5 @@
 
 	GetRaySets(rays,
-			   mConstructionSamples,
+			   mInitialSamples,
 			   constructionRays,
 			   &savedRays);
@@ -1676,5 +1656,5 @@
 	long startTime = GetTime();
 	// recast rest of rays
-	ComputeSampleContributions(savedRays);
+	ComputeSampleContributions(savedRays, true, false);
 
 	Debug << "Computed remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
@@ -1950,4 +1930,6 @@
 }
 
+
+
 /**************************************************************************/
 /*                   VspBspViewCellsManager implementation                */
@@ -1955,9 +1937,8 @@
 
 
-VspBspViewCellsManager::VspBspViewCellsManager(VspBspTree *vspBspTree,
-											   int constructionSamples):
-ViewCellsManager(constructionSamples),
-mVspBspTree(vspBspTree)
-{
+VspBspViewCellsManager::VspBspViewCellsManager(VspBspTree *vspBspTree):
+ViewCellsManager(), mVspBspTree(vspBspTree)
+{
+	environment->GetIntValue("VspBspTree.Construction.samples", mInitialSamples);
 	mVspBspTree->SetViewCellsManager(this);
 }
@@ -1980,5 +1961,5 @@
 void VspBspViewCellsManager::CollectViewCells()
 {
-	mVspBspTree->CollectViewCells(mViewCells, mOnlyValidViewCells);
+	mVspBspTree->CollectViewCells(mViewCells, true);
 }
 
@@ -2003,5 +1984,5 @@
 
 
-int VspBspViewCellsManager::Construct(const ObjectContainer &objects,
+int VspBspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
 									  const VssRayContainer &rays)
 {
@@ -2016,13 +1997,13 @@
 	VssRayContainer sampleRays;
 
-	int limit = min (mConstructionSamples, (int)rays.size());
+	int limit = min (mInitialSamples, (int)rays.size());
 
 	VssRayContainer constructionRays;
 	VssRayContainer savedRays;
 
-	Debug << "construction samples: " << mConstructionSamples << " rays: " << (int)rays.size() << endl;
-	GetRaySets(rays, mConstructionSamples, constructionRays, &savedRays);
-
-	Debug << "construction rays: " << (int)constructionRays.size() << endl;
+	Debug << "samples used for subdivision: " << mInitialSamples << " rays: " << (int)rays.size() << endl;
+	GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
+
+	Debug << "initial rays: " << (int)constructionRays.size() << endl;
 	Debug << "saved rays: " << (int)savedRays.size() << endl;
 
@@ -2075,5 +2056,5 @@
 	cout << "Computing remaining ray contributions ... ";
 	// recast rest of rays
-	ComputeSampleContributions(savedRays);
+	ComputeSampleContributions(savedRays, true, false);
 	cout << "finished" << endl;
 
@@ -2116,11 +2097,13 @@
 		  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
 
-	cout << "reseting view cell stats ... ";
-	ResetViewCells();
-	cout << "finished" << endl;
 
 	//BspLeaf::NewMail();
 	if (1) // export merged view cells
 	{
+
+		cout << "reseting view cells ... ";
+		ResetViewCells();
+		cout << "finished" << endl;
+
 		Exporter *exporter = Exporter::GetExporter("merged_view_cells.x3d");
 		Debug << "\nView cells after merge:\n" << mViewCellsStats << endl;
@@ -2198,6 +2181,13 @@
 
 	// check if new view cells turned invalid
+	SetValidity(mMinPvsSize, mMaxPvsSize); 
+	// update valid view space according to valid view cells
 	mVspBspTree->ValidateTree();
-	ResetViewCells();
+
+	// recompute view cell statistics
+	mViewCellsStats.Reset();
+	EvaluateViewCellsStats();
+	// has to be recomputed
+	mTotalAreaValid = false;
 
 
@@ -2283,5 +2273,5 @@
 	// collapse sibling leaves that share the same view cell
 	mVspBspTree->CollapseTree();
-
+	// recompute view cell list and statistics
 	ResetViewCells();
 
@@ -2447,8 +2437,6 @@
 #if 1
 	//-- some rays for output
-	vector<BspRay *> bspRays;
-	mVspBspTree->ConstructBspRays(bspRays, rays);
-
-	const int raysOut = min((int)bspRays.size(), mVisualizationSamples);
+	const int raysOut = min((int)rays.size(), mVisualizationSamples);
+
 #endif
 
@@ -2459,24 +2447,32 @@
 		VssRayContainer vcRays;
 		Intersectable::NewMail();
-#if 0 // largest view cell pvs first
-		BspViewCell *vc = dynamic_cast<BspViewCell *>(mViewCells[i]);
-#else
-		BspViewCell *vc = dynamic_cast<BspViewCell *>
-			(mViewCells[Random((int)mViewCells.size())]);
-#endif
-
-#if 1
-		// check whether we can add the current ray to the output rays
-		for (int k = 0; k < raysOut; ++ k)
-		{
-			BspRay *ray = bspRays[k];
-			for	(int j = 0; j < (int)ray->intersections.size(); ++ j)
+		BspViewCell *vc;
+	
+		if (0) // largest view cell pvs first
+		{
+			vc = dynamic_cast<BspViewCell *>(mViewCells[i]);
+		}
+		else
+		{
+			vc = dynamic_cast<BspViewCell *>
+				(mViewCells[Random((int)mViewCells.size())]);
+		}
+
+        if (1)
+		{
+			// check whether we can add the current ray to the output rays
+			for (int k = 0; k < raysOut; ++ k)
 			{
-				BspLeaf *leaf = ray->intersections[j].mLeaf;
-				if (vc == leaf->GetViewCell())
-					vcRays.push_back(ray->vssRay);
+				VssRay *ray = rays[k];
+				for	(int j = 0; j < (int)ray->mViewCells.size(); ++ j)
+				{
+					BspViewCell *bspVc = dynamic_cast<BspViewCell *>(ray->mViewCells[j]);
+					BspLeaf *leaf = bspVc->mLeaves[0];
+					if (vc == bspVc)
+						vcRays.push_back(ray);
+				}
 			}
 		}
-#endif
+
 		//bspLeaves[j]->Mail();
 		char s[64]; sprintf(s, "bsp-pvs%04d.x3d", i);
@@ -2495,14 +2491,19 @@
 			  << ", leaves=" << (int)vc->mLeaves.size() << endl;
 
+		
 		//-- export rays piercing this view cell
-#if 1
-		exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
-#endif
-#if 0
-		vector<BspLeaf *>::const_iterator lit, lit_end = vc->mLeaves.end();
-
-		for (lit = vc->mLeaves.begin(); lit != lit_end; ++ lit)
-			exporter->ExportRays((*lit)->mVssRays);
-#endif
+		if (1)
+		{
+			exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
+		}
+		else
+		{
+			vector<BspLeaf *>::const_iterator lit, lit_end = vc->mLeaves.end();
+
+			for (lit = vc->mLeaves.begin(); lit != lit_end; ++ lit)
+				exporter->ExportRays((*lit)->mVssRays);
+		}
+
+	
 		m.mDiffuseColor = RgbColor(1, 0, 0);
 		exporter->SetForcedMaterial(m);
@@ -2513,7 +2514,9 @@
 		exporter->SetFilled();
 
+	
 		// output PVS of view cell
 		for (it = vc->GetPvs().mEntries.begin(); it != it_end; ++ it)
 		{
+		
 			Intersectable *intersect = (*it).first;
 
@@ -2528,11 +2531,9 @@
 		}
 
+		
 		DEL_PTR(exporter);
 		cout << "finished" << endl;
 	}
 
-#if 1
-	CLEAR_CONTAINER(bspRays);
-#endif
 	Debug << endl;
 }
Index: /trunk/VUT/GtpVisibilityPreprocessor/src/common.h
===================================================================
--- /trunk/VUT/GtpVisibilityPreprocessor/src/common.h	(revision 434)
+++ /trunk/VUT/GtpVisibilityPreprocessor/src/common.h	(revision 574)
@@ -138,4 +138,5 @@
 #endif
 // Clears a container (i.e., a vector of pointers) and deletes the pointers
+#if 0
 #ifndef CLEAR_CONTAINER
 #define CLEAR_CONTAINER(co) do { while (!(co).empty()) {   \
@@ -143,4 +144,12 @@
 								   (co).pop_back();}}      \
 							while (0)
+#endif
+#endif
+
+#ifndef CLEAR_CONTAINER
+#define CLEAR_CONTAINER(co) do { for (int _i = 0; _i < (int)(co).size(); ++ _i) { \
+	DEL_PTR((co)[_i]);} \
+	(co).clear(); } \
+while (0)
 #endif
 
