Index: trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 513)
+++ trunk/VUT/GtpVisibilityPreprocessor/scripts/default.env	(revision 517)
@@ -13,5 +13,5 @@
 #;../data/vienna/vienna-plane.x3d
 #	filename ../data/vienna/viewcells-25-sel.x3d
-	filename ../data/atlanta/atlanta2.x3d
+#	filename ../data/atlanta/atlanta2.x3d
 #	filename ../data/soda/soda.dat
 	filename ../data/soda/soda5.dat
@@ -28,7 +28,7 @@
 
 VssPreprocessor {
-	samplesPerPass  500000
-	initialSamples 200000
-	vssSamples 200000
+	samplesPerPass  100000
+	initialSamples 300000
+	vssSamples 500000
 	vssSamplesPerPass 100000
 	useImportanceSampling true
@@ -169,6 +169,6 @@
 
 ViewCells {
-	loadFromFile false
-	exportToFile true
+	loadFromFile true
+	exportToFile false
 	#type kdTree
 	#type vspKdTree
@@ -179,7 +179,10 @@
 	
 	height 5.0
-	maxViewCells 500
+	maxViewCells 100
 	#percentage of total visible objects where pvs is considered invalid
-	maxPvsRatio 0.1
+	maxPvsRatio 1
+		
+	delayedConstruction true
+		
 		
 	PostProcess {
@@ -203,5 +206,5 @@
 #	filename ../data/vienna/viewcells-25.x3d
 #	filename ../data/vienna/viewcells-large-sel.x3d
-	filename ../scripts/viewcells.xml
+	filename ../scripts/viewcells_soda.xml
 }
 
@@ -266,9 +269,9 @@
 	# pvs                  = 1024
 	
-	splitPlaneStrategy 1026
+	splitPlaneStrategy 1024
 	
 	# maximal candidates for split planes
 	maxPolyCandidates 100
-	maxRayCandidates 100
+	#maxRayCandidates 100
 	
 	# maximal tested rays for split cost heuristics
@@ -284,13 +287,13 @@
 	Termination {
 		# parameters used for autopartition
-		minRays 		500
+		minRays 		900
 		minPolygons 		-1
 		maxDepth		30
-		minPvs 			20
+		minPvs 			10
 		minArea 		0.0001
 		#minArea 		0.000
-		maxRayContribution	0.5
-		maxCostRatio		0.95
-		missTolerance		5
+		maxRayContribution	0.4
+		maxCostRatio		0.93
+		missTolerance		3
 		#maxAccRayLength	100
 		
@@ -301,5 +304,5 @@
 		
 		AxisAligned {
-			minRays 		2000
+			minRays 		200000
 			maxRayContribution	0.5
 		}
@@ -315,5 +318,5 @@
 	PostProcess {
 		maxCostRatio 0.1
-		minViewCells 200
+		minViewCells 100
 		maxPvsSize   1000
 		useRaysForMerge true
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h	(revision 511)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.h	(revision 517)
@@ -336,5 +336,5 @@
 	/** Helper function revalidating the view cell leaf list after merge.
 	*/
-	void RepairVcLeafLists();
+	void RepairViewCellsLeafLists();
 
 	/** Evaluates tree stats in the BSP tree leafs.
@@ -692,5 +692,5 @@
 	int mMaxPvs;
 
-	int mMaxPvsRatio;
+	float mMaxPvsRatio;
 
 	/// View cell corresponding to the space outside the valid view space
@@ -704,6 +704,7 @@
 	/// maximal tree memory
 	float mMaxMemory;
-
+	/// the tree is out of memory
 	bool mOutOfMemory;
+
 private:
 	
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.cpp	(revision 503)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.cpp	(revision 517)
@@ -2360,5 +2360,5 @@
 
 
-void VspKdTree::RepairVcLeafLists()
+void VspKdTree::RepairViewCellsLeafLists()
 {
 	// list not valid anymore => clear
@@ -2446,5 +2446,5 @@
 	CollapseTree(mRoot, collapsed);
 	// revalidate leaves
-	RepairVcLeafLists();
+	RepairViewCellsLeafLists();
 
 	return collapsed;
Index: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h	(revision 508)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.h	(revision 517)
@@ -277,5 +277,5 @@
 	/** Creates meshes from the view cells.
 	*/
-	void CreateViewCellsMeshes();
+	void CreateViewCellMeshes();
 
 	/**
@@ -320,4 +320,6 @@
 	bool mExportGeometry;
 	bool mExportRays;
+
+	bool mViewCellsFinished;
 };
 
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp	(revision 511)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp	(revision 517)
@@ -88,5 +88,5 @@
 	environment->GetBoolValue("VspBspTree.PostProcess.useRaysForMerge", mUseRaysForMerge);
 
-	environment->GetIntValue("ViewCells.pvsInvalid", mMaxPvsRatio);
+	environment->GetFloatValue("ViewCells.maxPvsRatio", mMaxPvsRatio);
 
 	//-- termination criteria for axis aligned split
@@ -311,5 +311,5 @@
 
 	mMaxPvs = (int)(mMaxPvsRatio * (float)numObj);
-
+	Debug << "maximal pvs where view cell is valid: " << mMaxPvs << endl;
 	//-- store rays
 	for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
@@ -938,5 +938,6 @@
 	Plane3 plane;
 	float lowestCost = MAX_FLOAT;
-		
+	
+	// decides if the first few splits should be only axisAligned
 	const bool onlyAxisAligned  = 
 		(mSplitPlaneStrategy & AXIS_ALIGNED) &&
@@ -944,5 +945,4 @@
 		((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
 	
-	// split polygons if no axis aligned splits
 	const int limit = onlyAxisAligned ? 0 : 
 		Min((int)data.mPolygons->size(), mMaxPolyCandidates);
@@ -2084,5 +2084,7 @@
 			if (leaf->GetParent())
 				leaf->GetParent()->ReplaceChildLink(node, leaf);
-						
+			else
+				mRoot = leaf;
+
 			++ collapsed;
 			delete interior;
@@ -2099,7 +2101,9 @@
 {
 	int collapsed = 0;
+	
 	(void)CollapseTree(mRoot, collapsed);
+
 	// revalidate leaves
-	RepairVcLeafLists();
+	RepairViewCellsLeafLists();
 
 	return collapsed;
@@ -2107,5 +2111,5 @@
 
 
-void VspBspTree::RepairVcLeafLists()
+void VspBspTree::RepairViewCellsLeafLists()
 {
 	// list not valid anymore => clear
Index: trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 516)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/Environment.cpp	(revision 517)
@@ -1246,15 +1246,20 @@
 	RegisterOption("ViewCells.Visualization.colorCode",
 		optString,
-		"-view_cells_visualization.color_code",
+		"-view_cells_visualization_color_code",
 		"PVS");
 
 	RegisterOption("ViewCells.Visualization.exportRays",
 		optBool,
-		"-bsp_visualization.export_rays",
+		"-view_cells_delayed_construction",
+		"false");
+
+	RegisterOption("ViewCells.delayedConstruction",
+		optBool,
+		"-view_cells_delayed_construction",
 		"false");
 
 	RegisterOption("ViewCells.Visualization.exportGeometry",
 		optBool,
-		"-bsp_visualization.export_geometry",
+		"-view_cells_visualization_export_geometry",
 		"false");
 
@@ -1826,4 +1831,5 @@
 		"vsp_bsp_max_static_mem=", 
 		"8.0");
+	
 	//////////////////////////////////////////////////////////////////////////////////
 }
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp	(revision 508)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp	(revision 517)
@@ -25,4 +25,5 @@
   environment->GetIntValue("VssPreprocessor.vssSamplesPerPass", mVssSamplesPerPass);
   environment->GetBoolValue("VssPreprocessor.useImportanceSampling", mUseImportanceSampling);
+  environment->GetBoolValue("ViewCells.delayedConstruction", mDelayedViewCellsConstruction);
 
   environment->GetBoolValue("VssPreprocessor.loadInitialSamples", mLoadInitialSamples);
@@ -498,6 +499,7 @@
 
   // construct view cells
-  mViewCellsManager->Construct(mObjects, mVssRays);
-
+  if (!mDelayedViewCellsConstruction)
+	mViewCellsManager->Construct(mObjects, mVssRays);
+ 
   vssTree = new VssTree;
   // viewcells = Construct(mVssRays);
@@ -536,6 +538,4 @@
   int pass = 0;
 
-  /// Rays used for post processing and visualizations
-  RayContainer storedRays;
   // cast view cell samples
   while (1) {
@@ -570,4 +570,18 @@
 	cout<<"Average PVS size = "<<avgPvs<<endl;
 
+	//Debug << "samples: " << samples << " construction samples " << mViewCellsManager->GetConstructionSamples() << endl;
+	// construct view cells after vss
+	if (!mViewCellsManager->ViewCellsConstructed() &&
+		(samples + mInitialSamples >  mViewCellsManager->GetConstructionSamples()))
+	{
+		VssRayContainer constructionRays;
+		vssTree->CollectRays(constructionRays, 
+							 mViewCellsManager->GetConstructionSamples());
+		mViewCellsManager->Construct(mObjects, constructionRays);
+	}
+
+	/// compute view cell contribution of rays
+	mViewCellsManager->ComputeSampleContributions(vssRays);
+	
 	if (numExportRays) {
 	  char filename[64];
@@ -579,8 +593,4 @@
 	  ExportRays(filename, vssRays, numExportRays);
 	}
-
-	//-- prepare traversal rays for view cell intersections
-	/// compute view cell contribution of rays
-	mViewCellsManager->ComputeSampleContributions(vssRays);
 
 	samples+=num;
@@ -596,20 +606,21 @@
 
 
-  {
-	VssRayContainer storedRays;
-	vssTree->CollectRays(storedRays, Max(
-										 mViewCellsManager->GetPostProcessSamples(),
-										 mViewCellsManager->GetVisualizationSamples()));
-
-    //-- post process view cells
-	mViewCellsManager->PostProcess(mObjects, storedRays);
-
-	//-- several visualizations and statistics
-	Debug << "\nview cells after post processing: " << endl;
-	mViewCellsManager->PrintStatistics(Debug);
-
-	mViewCellsManager->Visualize(mObjects, storedRays);
-  }
-
+  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);
+
+  //-- several visualizations and statistics
+  Debug << "\nview cells after post processing: " << endl;
+  mViewCellsManager->PrintStatistics(Debug);
+
+  mViewCellsManager->Visualize(mObjects, viewCellRays);
+  
   //-- render simulation after merge
   cout << "\nevaluating bsp view cells render time after merge ... ";
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.h
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.h	(revision 501)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VspKdTree.h	(revision 517)
@@ -790,5 +790,5 @@
 	/** Helper function revalidating the view cell leaf list after merge.
 	*/
-	void RepairVcLeafLists();
+	void RepairViewCellsLeafLists();
 
 	/** Shuffles the leaves, i.e., tests if exchanging
Index: trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h	(revision 501)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.h	(revision 517)
@@ -37,4 +37,6 @@
   VssRayContainer mVssRays;
 	
+  bool mDelayedViewCellsConstruction;
+
   VssPreprocessor();
   ~VssPreprocessor();
Index: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp	(revision 508)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellsManager.cpp	(revision 517)
@@ -13,4 +13,5 @@
 #include "ViewCellsParser.h"
 
+
 ViewCellsManager::ViewCellsManager():
 mRenderer(NULL),
@@ -19,9 +20,11 @@
 mVisualizationSamples(0),
 mTotalAreaValid(false),
-mTotalArea(0.0f)
+mTotalArea(0.0f),
+mViewCellsFinished(false)
 {
 	mSceneBox.Initialize();
 	ParseEnvironment();
 }
+
 
 ViewCellsManager::ViewCellsManager(int constructionSamples):
@@ -29,9 +32,11 @@
 mRenderer(NULL),
 mPostProcessSamples(0),
-mVisualizationSamples(0)
+mVisualizationSamples(0),
+mViewCellsFinished(false)
 {
 	mSceneBox.Initialize();
 	ParseEnvironment();
 }
+
 
 void ViewCellsManager::ParseEnvironment()
@@ -348,5 +353,5 @@
 				  termination,
 				  viewcells);
-
+  //Debug << "constribution: " << (int)viewcells.size() << endl;
   // copy viewcells memory efficiently
   const bool storeViewcells = false;
@@ -462,5 +467,5 @@
 
 
-void ViewCellsManager::CreateViewCellsMeshes()
+void ViewCellsManager::CreateViewCellMeshes()
 {
 	// convert to meshes
@@ -469,5 +474,6 @@
 	for (it = mViewCells.begin(); it != it_end; ++ it)
 	{
-		CreateMesh(*it);
+		if (!(*it)->GetMesh())
+			CreateMesh(*it);
 	}
 }
@@ -1860,11 +1866,4 @@
 	startTime = GetTime();
 
-	//-- merge the individual view cells: Should be done here because it makes
-	MergeViewCells(rays, objects);
-	//-- refines the merged view cells
-	RefineViewCells(rays);
-	// collapse sibling leaves that share the same view cell
-	mVspBspTree->CollapseTree();
-
 	// reset view cells and stats
 	ResetViewCells();
@@ -1891,11 +1890,4 @@
 	int pvsSize = 0;
 
-	VssRayContainer postProcessRays;
-	GetRaySets(rays, mPostProcessSamples, postProcessRays);
-
-	Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
-	EvaluateViewCellsStats();
-	Debug << "\noriginal view cell partition:\n" << mViewCellsStats << endl << endl;
-
 	mRenderer->RenderScene();
 	SimulationStatistics ss;
@@ -1910,5 +1902,5 @@
 
 	// TODO: should be done BEFORE the ray casting
-	merged = mVspBspTree->MergeViewCells(postProcessRays);
+	merged = mVspBspTree->MergeViewCells(rays);
 
 	//-- stats and visualizations
@@ -1978,4 +1970,5 @@
 }
 
+
 int VspBspViewCellsManager::PostProcess(const ObjectContainer &objects,
 										const VssRayContainer &rays)
@@ -1983,14 +1976,37 @@
 	if (!ViewCellsConstructed())
 	{
-		Debug << "view cells not constructed" << endl;
+		Debug << "postprocess error: no view cells constructed" << endl;
 		return 0;
 	}
+	// view cells already finished
+	else if (mViewCellsFinished)
+		return 0;
+
+	VssRayContainer postProcessRays;
+	GetRaySets(rays, mPostProcessSamples, postProcessRays);
+
+	Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
+	EvaluateViewCellsStats();
+	Debug << "\nview cell partition after sampling:\n" << mViewCellsStats << endl << endl;
+
+
+	//-- merge the individual view cells: Should be done here because it makes
+	MergeViewCells(postProcessRays, objects);
+	//-- refines the merged view cells
+	RefineViewCells(postProcessRays);
+	// collapse sibling leaves that share the same view cell
+	mVspBspTree->CollapseTree();
 
 	// real meshes are only contructed only at this stage
-	CreateViewCellsMeshes();
+	CreateViewCellMeshes();
+
 	// write view cells to disc
 	if (mExportViewCells)
 	{
-		ExportViewCells("viewcells.xml");
+		char buff[100];
+		environment->GetStringValue("ViewCells.filename", buff);
+		string vcFilename(buff);
+
+		ExportViewCells(buff);
 	}
 
@@ -2371,6 +2387,9 @@
 	bool success = parser.ParseFile(filename, mVspBspTree, this, objects);
 	ResetViewCells();
-	
+	CreateViewCellMeshes();
+
 	Debug << (int)mViewCells.size() << " view cells loaded" << endl;
+
+	mViewCellsFinished = true;
 
 	return success;
Index: trunk/VUT/GtpVisibilityPreprocessor/src/GlRenderer.cpp
===================================================================
--- trunk/VUT/GtpVisibilityPreprocessor/src/GlRenderer.cpp	(revision 516)
+++ trunk/VUT/GtpVisibilityPreprocessor/src/GlRenderer.cpp	(revision 517)
@@ -48,4 +48,11 @@
 GlRenderer::~GlRenderer()
 {
+}
+
+
+static void handleCgError() 
+{
+    fprintf(stderr, "Cg error: %s\n", cgGetErrorString(cgGetError()));
+    exit(1);
 }
 
@@ -147,4 +154,5 @@
 
   // cg initialization
+  cgSetErrorCallback(handleCgError);
   sCgContext = cgCreateContext();
 
@@ -406,7 +414,9 @@
 {
   static int glList = -1;
-  if (glList == -1) {
+  if (glList != -1) {
+	glCallList(glList);
+  } else {
 	glList = glGenLists(1);
-	glNewList(glList, GL_COMPILE);
+	glNewList(glList, GL_COMPILE_AND_EXECUTE);
 	ObjectContainer::const_iterator oi = mObjects.begin();
 	for (; oi != mObjects.end(); oi++)
@@ -414,5 +424,4 @@
 	glEndList();
   }
-  glCallList(glList);
   return true;
 }
@@ -570,5 +579,5 @@
 											   Beam &beam,
 											   const int desiredSamples,
-											   GlRendererBuffer::BeamSampleStatistics &stat)
+											   BeamSampleStatistics &stat)
 {
 	// TODO: should not be done every time here
