Index: /GTP/trunk/Lib/Vis/OnlineCullingCHC/src/RandomUpdateCullingManager.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/OnlineCullingCHC/src/RandomUpdateCullingManager.cpp	(revision 2538)
+++ /GTP/trunk/Lib/Vis/OnlineCullingCHC/src/RandomUpdateCullingManager.cpp	(revision 2539)
@@ -106,6 +106,6 @@
 					int nodesTested = 0;
 
-					// use different algorithm to find random candidates
 #if 1
+					// test a certain ratio of random candidates
 					HierarchyNodeContainer mynodes;
 					mHierarchyInterface->CollectLeaves(node, mynodes);
@@ -144,5 +144,5 @@
 
 #else
-					
+					// always test one random candidate
 					HierarchyNode *leaf = mHierarchyInterface->GetRandomLeaf(node);
 					
Index: /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.sh
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.sh	(revision 2535)
+++ /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.sh	(revision 2539)
@@ -8,5 +8,5 @@
 
 PROGRAM=../bin/$TARGET/Preprocessor.exe
-#PROGRAM=../bin/$TARGET/Preprocessor_itl.exe
+
 
 EXT=obj
@@ -15,6 +15,10 @@
 SCENE_PATH=../data/vienna
 
+#SCENE=arena-high-lods
+#SCENE_PATH=../data/Arena
+
+
 ENVIRONMENT=generate_viewcells.env
-LOG_PREFIX=../scripts/$SCENE
+LOG_PREFIX=$SCENE
 
 echo "starting $TARGET mode for $SCENE scene ($PROGRAM)"
@@ -22,5 +26,4 @@
 SCENE_FILENAME=$SCENE_PATH/$SCENE.$EXT
 
-OBJ_WEIGHT=20
 
 #######################################################
@@ -28,6 +31,9 @@
 METHOD=seq
 
-# the # of bvh nodes
-NODES=3000
+NODES=4000
+VIEWCELLS=4000
+#USE_HEUR=true
+USE_HEUR=false
+OBJ_WEIGHT=20
 
  
@@ -42,6 +48,10 @@
  -hierarchy_subdivision_stats=$LOG_PREFIX-$METHOD-hierarchy-subdivisionStats.log \
  -hierarchy_construction_type=0 \
- -vsp_use_cost_heuristics=false \
- -bvh_term_max_leaves=$NODES
+ -view_cells_triangle_weight=1.0 \
+ -view_cells_object_weight=$OBJ_WEIGHT \
+ -vsp_use_cost_heuristics=$USE_HEUR \
+ -bvh_term_max_leaves=$NODES \
+ -vsp_term_max_view_cells=$VIEWCELLS
 
 sh movefiles.sh $LOG_PREFIX-$METHOD
+
Index: /GTP/trunk/Lib/Vis/Preprocessing/scripts/gi_final.sh
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/scripts/gi_final.sh	(revision 2535)
+++ /GTP/trunk/Lib/Vis/Preprocessing/scripts/gi_final.sh	(revision 2539)
@@ -8,5 +8,4 @@
 
 PROGRAM=../bin/$TARGET/Preprocessor.exe
-#PROGRAM=../bin/$TARGET/Preprocessor_itl.exe
 
 EXT=obj
Index: /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.env
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.env	(revision 2537)
+++ /GTP/trunk/Lib/Vis/Preprocessing/scripts/generate_viewcells.env	(revision 2539)
@@ -7,9 +7,4 @@
 
 	filename ../data/vienna/vienna_cropped.obj
-#	filename ../data/soda/soda.dat
-#	filename ../data/soda/soda5.dat
-#	filename ../data/artificial/cube_test.x3d
-#	filename ../data/CityModel.obj
-#	filename ../data/arena/arena-low-lods.obj
 }
 
@@ -21,8 +16,6 @@
 	loadMeshes false
 	
-	# internal raycaster
+	# internal raycaster: 0, intel: 1
 	rayCastMethod 0  
-	# intel raycaster
-	#rayCastMethod 1
 	
 	exportVisibility false
@@ -32,53 +25,12 @@
 
 
-RssPreprocessor {
-	distributions mutation+spatial+object_direction
-	#distributions spatial
-
-
-	useImportanceSampling true
-
-	Export {
-		pvs false
-		rssTree false
-	}
-
-	useViewcells true
-	updateSubdivision true
-	loadInitialSamples false
-	storeInitialSamples false
-
-	useRssTree true
-}
-
-
-
 VssTree {
-	useRss    	false
-	epsilon		1e-6
-	
 	maxDepth 	2
-	minPvs		30
-	minRays		800
-	minSize		0.001
- 	maxCostRatio	1.5
-	maxRayContribution 0.5
-		
+	
 	maxTotalMemory	50
 	maxStaticMemory	20
 	
 	splitType regular
-	#	splitType heuristic
-	#	splitType hybrid
 	splitUseOnlyDrivingAxis true
-	
-	interleaveDirSplits	true
-    	dirSplitDepth 0
-	
-	numberOfEndPointDomains	10000
-	ct_div_ci	0.0
-	randomize	false
-	
-	refDirBoxMaxSize	0.1
 }
 
@@ -88,9 +40,4 @@
        small		1e-6
        infinity		1e9
-}
-
-
-Unigraphics {
-	meshGrouping 1
 }
 
@@ -107,5 +54,4 @@
 	}
 
-#	splitMethod spatialMedian
 	splitMethod SAH
 	splitBorder 0.01
@@ -120,5 +66,4 @@
 	}
 
-#	splitMethod spatialMedian
 	splitMethod SAH
 	splitBorder 0.01
@@ -146,5 +91,5 @@
 	type vspOspTree
 	
-	#percentage of total visible objects where pvs is considered invalid
+	#this ratio of the biggest pvs gives the threshold when a pvs is considered invalid
 	maxPvsRatio 1.0
 		
@@ -175,9 +120,9 @@
 	}
 
-	showVisualization true
-	#showVisualization false
+	#showVisualization true
+	showVisualization false
 	evaluateViewCells false
 	
-	
+
 	Evaluation {
 		samples         80000000
@@ -210,9 +155,9 @@
 	Termination {
 		minPvs 0
-		maxViewCells 500000
-	}
-
+		maxViewCells 4000
+	}
+
+	# heuristics for computing local split planes
 	useCostHeuristics false
-	splitUseOnlyDrivingAxis false
 
 	# maximum number of tests per node
@@ -230,14 +175,16 @@
 	Construction {		
 		renderCostDecreaseWeight 0.999
-	}
-
-	Termination {
-		maxLeaves 3000
+		#renderCostDecreaseWeight 1.0
+	}
+
+	Termination {
+		maxLeaves 4000
 	}
 
 	minRaysForVisibility 3
-	#minRaysForVisibility 15
-
-	useCostHeuristics false
+
+	# heuristics for computing local split planes
+	useCostHeuristics true
+	# surface area or visibility based heuristics
 	useSah false
 
@@ -281,7 +228,8 @@
 	Termination {
 		# maximal number of leaves
-		maxLeaves 30000
+		maxLeaves 300000
 		# maximal memory in MB
-		maxMemory 17
+                # maxMemory 4
+		maxMemory 200
 		# minimum ratio of global cost decrease
 		minGlobalCostRatio -1
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj	(revision 2530)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj	(revision 2539)
@@ -131,5 +131,5 @@
 			ConfigurationType="1"
 			CharacterSet="2"
-			WholeProgramOptimization="TRUE">
+			WholeProgramOptimization="FALSE">
 			<Tool
 				Name="VCCLCompilerTool"
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 2176)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 2539)
@@ -357,8 +357,7 @@
 				MeshManager::GetSingleton()->FindEntry(meshIdx);
 
-			//Debug << "retrieving mesh definition: " << mCurrentMeshName << endl;
 			cout << "u";
 		}
-		else if (attrName == "DEF") //-- a definition of a mesh
+		else if (attrName == "DEF") // a definition of a mesh
 		{
 			const StrX attrValue(attributes.getValue(i));
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 2538)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.h	(revision 2539)
@@ -65,9 +65,6 @@
 	/// root of view cells tree
 	ViewCell *mViewCell;
-
 	// input parameter is the render budget for the PrVs
 	float mRenderBudget;
-
-	// some characteristic values could be stored as well
 };
 
@@ -142,7 +139,7 @@
 	*/
 	ViewCellsManager(ViewCellsTree *viewCellsTree);
-
+	/** Destructor.
+	*/
 	virtual ~ViewCellsManager();
-
 	/** Constructs view cells container taking a preprocessor
 		@returns the output rays (if not null)
@@ -178,5 +175,4 @@
 											const bool storeViewCells,
 											const bool useHitObject = false);
-
 	/** Compute sample contribution only for current view cell.
 	*/
@@ -185,27 +181,21 @@
 											ViewCell *currentViewCell,
 											const bool useHitObject = false);
-
 	/** Prints out statistics of the view cells.
 	*/
 	virtual void PrintStatistics(std::ostream &s) const;
-
 	/** Post processes view cells givemŽa number of rays.
 	*/
 	virtual int PostProcess(const ObjectContainer &objects, 
 							const VssRayContainer &rays) = 0;
-
 	/** Show visualization of the view cells.
 	*/
 	virtual void Visualize(const ObjectContainer &objects,
 						   const VssRayContainer &sampleRays) = 0;
-
 	/** collect objects intersecting a given spatial box.
 	*/
 	virtual void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
-
 	/** type of the view cell container.
 	*/
 	virtual int GetType() const = 0;
-
 	/** Load the input viewcells. The input viewcells should be given as a collection
 		of meshes. Each mesh is assume to form a bounded polyhedron 
@@ -217,5 +207,4 @@
 	*/
 	virtual bool LoadViewCellsGeometry(const string filename, const bool extrudeBaseTriangle);
-	
 	/** Merges two view cells.
 		@note the piercing rays of the front and back will be ordered	
@@ -223,14 +212,11 @@
 	*/
 	ViewCellInterior *MergeViewCells(ViewCell *front, ViewCell *back) const;
-
 	/** Merges a container of view cells.
 		@returns new view cell based on the merging.
 	*/
 	ViewCellInterior *MergeViewCells(ViewCellContainer &children) const;
-	
 	/** Generates view cell of the type specified by this manager
 	*/
 	virtual ViewCell *GenerateViewCell(Mesh *mesh = NULL) const = 0;
-
 	/** Constructs view cell from base triangle. 
 		The view cell is extruded along the normal vector.
@@ -239,48 +225,38 @@
 	*/
 	ViewCell *ExtrudeViewCell(const Triangle3 &baseTri, const float height) const;
-
+	/** Returns the intersectable that was hit by the ray.
+	*/
 	virtual Intersectable *GetIntersectable(const VssRay &ray, const bool isTermination) const;
-
 	/** Sets maximal number of samples used for the 
 		construction of the view cells.
 	*/
 	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 SetInitialSamples(const int initialSamples);
-
 	/** Sets maximal number of samples used for the post processing of the view cells.
 	*/
 	void SetPostProcessSamples(const int postProcessingSamples);
-
 	/** See set.
 	*/
 	int GetVisualizationSamples() const;
-
 	/** See set.
 	*/
 	int GetConstructionSamples() const;
-
 	/** See set.
 	*/
 	int GetPostProcessSamples() const;
-
 	/** Returns true if view cells are already constructed.
 	*/
 	virtual bool ViewCellsConstructed() const = 0;
-
 	/** cast line segment to get a list of unique viewcells which are intersected
 		by this line segment 
 	*/
   	virtual int CastLineSegment(const Vector3 &origin,
-							  const Vector3 &termination,
-							  ViewCellContainer &viewcells
-							  ) = 0;
-
+							    const Vector3 &termination,
+							    ViewCellContainer &viewcells) = 0;
 	/** Tests if this line segment intersects a particular view cell.
 	*/
@@ -288,36 +264,32 @@
 									   const Vector3 &termination,
 									   ViewCell *viewCell) = 0;
-
 	/** Returns a stats about the global pvs.
 	*/
 	virtual void GetPvsStatistics(PvsStatistics &stat);
-
+	/** Returns the probably visible set of the view space filtered pvs.
+	*/
 	virtual void GetPrVS(const Vector3 &viewPoint, PrVs &prvs, const float filterWidth);
-  
 	/** Get a viewcell containing the specified view point.
 		@param active if the active or elementary view cell should be returned.
 	*/
 	virtual ViewCell *GetViewCell(const Vector3 &point, const bool active = false) const = 0;
-  
+	/** Returns the view cell with the given index (different from the id).
+	*/
 	ViewCell *GetViewCell(const int idx) const {return mViewCells[idx];}
-
+	/** Prints the statistics over the view cell pvss.
+	*/
 	virtual void PrintPvsStatistics(std::ostream &s);
-
 	/** Updates pvs of the view cell hierarchy if necessary.
 	*/
 	void UpdatePvs();
-
 	/** Returns probability that view point lies in one view cell.
 	*/
 	virtual float GetProbability(ViewCell *viewCell) = 0;
-
 	/** Returns render cost of a single view cell given the render cost of an object.
 	*/
 	float GetRendercost(ViewCell *viewCell) const;
-
 	/** Returns reference to container of loaded / generated view cells.
 	*/
 	ViewCellContainer &GetViewCells();
-
 	/** Helper function used to split ray sets uniformly 
 		into one that is currently used and the other that 
@@ -332,42 +304,35 @@
 					VssRayContainer &usedRays, 
 					VssRayContainer *savedRays = NULL) const;
-	
 	/** Returns accumulated area of all view cells.
 	*/
 	float GetAccVcArea();
-
 	/** Returns area of one view cell.
 	*/
 	virtual float GetArea(ViewCell *viewCell) const;
-
 	/** Returns volume of view cell.
 	*/
 	virtual float GetVolume(ViewCell *viewCell) const;
-
 	/** Sets the current renderer mainly for view cells statistics.
 	*/
 	void SetRenderer(Renderer *renderer);
-
 	/** Computes a (random) view point in the valid view space.
 		@returns true if valid view point was found
 	*/
 	virtual bool GetViewPoint(Vector3 &viewPoint) const;
-  
+	/** Returns the current view point given a vector for activating the halton sequence.
+	*/
 	virtual bool GetViewPoint(Vector3 &viewPoint, const Vector3 &params) const;
-
 	/** Returns true if this view point is in the valid view space.
 	*/
 	virtual bool ViewPointValid(const Vector3 &viewPoint) const;
-
 	/** Sets a view space boundary.
 	*/
 	void SetViewSpaceBox(const AxisAlignedBox3 &box);
-
+	/** Returns the boundaries of the view space.
+	*/
 	AxisAlignedBox3 GetViewSpaceBox() const;
-
 	/** Creates mesh for this view cell.
 	*/
 	virtual void CreateMesh(ViewCell *vc) = NULL;
-
 	/** Writes view cells to disc.
 	*/
@@ -375,9 +340,7 @@
 								 const bool exportPvs, 
 								 const ObjectContainer &objects);
-
 	/** Casts beam to collect view cells.
 	*/
 	virtual int CastBeam(Beam &beam);
-
 	/** Checks if view cell is considered as valid.
 	*/
@@ -385,13 +348,11 @@
 							   int minPvsSize, 
 							   int maxPvsSize) const;
-
-
-	// resort pvss after a pass of the algorithm
+	/** Resort pvss after a pass of the algorithm.
+	*/
 	void  SortViewCellPvs();
-
-	// map the ray intersection objects from triangles to high level objects...
+	/** Map the ray intersection objects from triangles to high level objects.
+	*/
 	void DeterminePvsObjects(VssRayContainer &rays,
 							 const bool useHitObjects = false);
-	
 	/** Sets validity of view cell
 	*/
@@ -399,33 +360,24 @@
 							 int minPvsSize, 
 							 int maxPvsSize) const;
-
 	/** sets validy of all viewcells 
 	*/
-  	virtual void SetValidity(int minPvsSize, 
-							 int maxPvsSize) const;
-
-
+  	virtual void SetValidity(int minPvsSize, int maxPvsSize) const;
 	/** Set valid viewcells in the range of pvs. sorts the viewcells
 		according to the pvs and then pickups those in the ranges 
 	*/
 	void SetValidityPercentage(const float minValid, const float maxValid);
-
 	/** Returns number of valid view cells.
 	*/
     int CountValidViewcells() const;
-
 	/** Returns maximal allowed pvs size.
 	*/
 	int GetMaxPvsSize() const;
-
 	/** Returns maximal allowed pvs size.
 	*/
 	int GetMinPvsSize() const;
-
 	/** Returns maximal ratio. i.e., currentPVs / maxPvs,
 		where pvs is still considered valid.
 	*/
 	float GetMaxPvsRatio() const;
-
 	/** Exports view cell geometry.
 	*/
@@ -435,9 +387,7 @@
 										const AxisAlignedPlane *clipPlane = NULL
 										) const = 0;
-
 	/** Brings the view cells into their final state, computes meshes and volume.
 	*/
 	virtual void FinalizeViewCells(const bool createMesh);
-
 	/** Evaluates statistics values on view cells.
 	*/
@@ -448,54 +398,43 @@
 								  float &totalPvs,
 								  float &avgRenderCost);
-
 	/** Returns hierarchy of the view cells.
 	*/
 	ViewCellsTree *GetViewCellsTree();
-
 	/** Collect candidates for the view cell merge.
 	*/
 	virtual void CollectMergeCandidates(const VssRayContainer &rays, 
 										vector<MergeCandidate> &candidates);
-
 	/** Collects n view cells and stores it as the active view cells.
 	*/
 	void CollectViewCells(const int n);
-
 	/** Sets current view cells set to active, 
 		i.e., the sampling is done in this view cell set.
 	*/
 	void SetViewCellsActive();
-
 	/** Evaluates render cost statistics of current view cell hierarchy.
 	*/
 	virtual void EvalViewCellPartition();
-
 	/** Sets maximal size of a view cell filter.
 	*/
 	void SetMaxFilterSize(const int size);
-
 	/** Returns maximal filter size.
 	*/
 	int GetMaxFilterSize() const;
-
 	/** Deletes interior nodes from the tree which have negative 
 		merge cost set (local merge).
 	*/  
 	void DeleteLocalMergeTree(ViewCell *vc) const;
-  
 	/** Evaluautes histogram for a given number of view cells.
 	*/
 	void EvalViewCellHistogram(const string filename, const int nViewCells);
-
 	/** Evaluautes histogram for a given number of view cells.
 	*/
 	void EvalViewCellHistogramForPvsSize(const string filename, 
 										 const int nViewCells);
-
+	/** Evaluautes histogram for a given vector of view cells.
+	*/
 	void EvalViewCellHistogramForPvsSize(const string filename, 
 										 ViewCellContainer &viewCells);
-
 	float ComputeRenderCost(const int tri, const int obj); //const
-
 	/** Sets pvs size of view cell as a scalar. Used when storing pvs only in the leaves
 		of the hierarchy.
@@ -504,34 +443,28 @@
 							 const float pvsCost, 
 							 const int entriesInPvs) const;
-
 	/** Returns bounding box of a view cell.
 	*/
 	AxisAlignedBox3 GetViewCellBox(ViewCell *vc);
-
 	/** Exports bounding boxes of objects to file.
 	*/
 	bool ExportBoundingBoxes(const string filename, 
 							 const ObjectContainer &objects) const;
-    
 	/** Load the bounding boxes into the container.
 	*/
 	bool LoadBoundingBoxes(const string filename, 
 						  IndexedBoundingBoxContainer &boxes) const;
-
 	/** Returns true if pvs should be exported together with the view cells.
 	*/
 	bool GetExportPvs() const;
-
 	/** Efficiently merges the view cells in the container.
 	*/
 	void MergeViewCellsRecursivly(ObjectPvs &pvs, 
 								  const ViewCellContainer &viewCells) const;
-
-	/** Compress the view cells.
+	/** Compresses the view cells.
 	*/
 	virtual void CompressViewCells();
-
+	/** Returns view cell with the given id.
+	*/
 	ViewCell *GetViewCellById(const int id);
-
 	/** Returns number of view cells.
 	*/
@@ -620,5 +553,4 @@
 
 	float GetAbsFilterWidth();
-
 	/** Returns the bounding box of filter width.
 	*/
@@ -688,19 +620,15 @@
 								  const int leftIdx, 
 								  const int rightIdx) const;
-
 	/** Intersects box with the tree and returns the number of intersected boxes.
-	@returns number of view cells found
+		@returns number of view cells found
 	*/
 	virtual int ComputeBoxIntersections(const AxisAlignedBox3 &box, 
 										ViewCellContainer &viewCells) const;
-
 	/** Tests the visibility filter functionality.
 	*/
 	virtual void TestFilter(const ObjectContainer &objects) {};
-
 	/** If the view cells tree was already constructed or not.
 	*/
 	bool ViewCellsTreeConstructed() const;
-
 	/** Requests preprocessor to cast samplesPerPass samples of a specific type.
 	*/
@@ -711,31 +639,23 @@
 	int CastEvaluationSamples(const int samplesPerPass, 
 							  VssRayContainer &passSamples);// const;
-
 	/** Parse the options from the environment file.
 	*/
 	void ParseEnvironment();
-
 	/** Creates unique view cell ids.
 	*/
 	void CreateUniqueViewCellIds();
-
 	/** Finalizes, i.e., creates mesh, volume, area etc. for the view cell.
 	*/
 	virtual void Finalize(ViewCell *viewCell, const bool createMesh);
-
 	/** Recollects view cells and resets statistics.
 	*/
 	void ResetViewCells();
-
 	/** Sets this view cell to active.
 	*/
 	void SetViewCellActive(ViewCell *vc) const;
-
 	/** Collects the view cells in the view cell container.
 	*/
 	virtual void CollectViewCells() = 0;
-
-	/** Evaluates view cells statistics and stores it in
-	mViewCellsStatistics.
+	/** Evaluates view cells statistics and stores it in mViewCellsStatistics.
 	*/
 	void EvaluateViewCellsStats();
@@ -751,5 +671,4 @@
 							   const bool colorCode,
 							   const AxisAlignedPlane *clipPlane) const;
-
 	/** Sets exporter color.
 	*/
@@ -757,9 +676,7 @@
 							 ViewCell *vc, 
 							 const int colorCode) const;
-
 	/** Creates meshes from the view cells.
 	*/
 	void CreateViewCellMeshes();
-
 	/** Creates clip plane for visualization.
 	*/
@@ -776,14 +693,11 @@
 	*/
 	virtual float GetViewSpaceVolume();
-
 	/** Prepares the view cells for sampling after loading them from disc.
 	*/
 	virtual void PrepareLoadedViewCells() {};
-	
 	/** Constructs local view cell merge hierarchy.
 	*/
 	ViewCell *ConstructLocalMergeTree(ViewCell *currentViewCell, 
-		const ViewCellContainer &viewCells);
-
+	                                  const ViewCellContainer &viewCells);
 	/** Constructs local view cell merge hierarchy based solely on similarity with the
 		current viewcell
@@ -791,5 +705,4 @@
   	ViewCell *ConstructLocalMergeTree2(ViewCell *currentViewCell, 
 									   const ViewCellContainer &viewCells);
-  
 	/** Updates pvs of all view cells for statistical evaluation after some more sampling
 	*/
@@ -797,4 +710,9 @@
 
 	virtual void ExportStats(const string &mergeStats);
+
+	friend ViewCellsManager *LoadViewCellsBinary(const string &filename, 
+												 ObjectContainer &pvsObjects,
+												 bool finalizeViewCells,
+                                                 BoundingBoxConverter *bconverter);
 
 
@@ -804,20 +722,14 @@
 	ofstream mStats;
 	Preprocessor *mPreprocessor;
-	
 	/// if bounding boxes should be exported together with the view cells
 	bool mExportBboxesForPvs;
-	
 	/// the clip plane for visualization
 	AxisAlignedPlane mClipPlaneForViz;
-	
 	/// if the visualization is using the clip plane
 	bool mUseClipPlaneForViz;
-	
 	/// Renders the view cells.
 	Renderer *mRenderer;
-	
 	/// Loaded view cells
 	ViewCellContainer mViewCells;
-	
 	/// the view cell hierarchy (i.e., the logical description of view cells)
 	ViewCellsTree *mViewCellsTree;
@@ -998,9 +910,7 @@
 	*/
 	ViewCell *ConstructDummyMergeTree(BspNode *root);
-
 	/** Exports visualization of the BSP splits.
 	*/
 	void ExportSplits(const ObjectContainer &objects);
-
 	/** test if subdivision is valid in terms of volume / area.
 	*/
@@ -1246,10 +1156,9 @@
 	ViewCell *GenerateViewCell(Mesh *mesh = NULL) const;
 
-	virtual Intersectable *GetIntersectable(
-		const VssRay &ray, const bool isTermination) const;
+	virtual Intersectable *GetIntersectable(const VssRay &ray, 
+											const bool isTermination) const;
 
 	bool ViewCellsConstructed() const;
 
-	
 	int CastLineSegment(const Vector3 &origin,
 						const Vector3 &termination,
@@ -1288,7 +1197,12 @@
 							   VssRayContainer *visRays = NULL);
 	
-	float UpdateObjectCosts();
-
+	;
+	/** See parent class.
+	*/
 	virtual void FinalizeViewCells(const bool createMesh);
+
+	bool ExportBinaryViewCells(const string filename, 
+							   const bool exportPvs, 
+							   const ObjectContainer &objects);
 
 #if TEST_PACKETS
@@ -1300,10 +1214,12 @@
 #endif
 
+
 protected:
 
+	/** View cells manager taking a view cells tree and a hierarchy as input.
+	*/
 	VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm);
 	
 	virtual void EvalViewCellPartition();
-
 	/** Exports view cell geometry.
 	*/
@@ -1334,5 +1250,20 @@
 	*/
 	virtual void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
-
+	/** Update the cost of pvss for hierarchy objects.
+	*/
+	float UpdateObjectCosts();
+
+
+	////////////////
+
+	/** Fast view cell loader in binary mode.
+	*/
+	friend ViewCellsManager *LoadViewCellsBinary(const string &filename, 
+												 ObjectContainer &pvsObjects,
+												 bool finalizeViewCells,
+												 BoundingBoxConverter *bconverter);
+
+	/** Print statistics about the view cells compression.
+	*/
 	static void PrintCompressionStats(HierarchyManager *hm, const int pvsEntries);
 
@@ -1340,6 +1271,8 @@
 	////////////////////
 
+	/// if we should compress the objects after view cell evaluation: this makes
+	/// only sense for testing purpose
 	bool mCompressObjects;
-
+	/// pointer to the hierarchy manager responsible for view space / object space subdivision.
 	HierarchyManager *mHierarchyManager;
 };
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 2452)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 2539)
@@ -816,6 +816,5 @@
 {
 	mKdTree = new KdTree();
-
-	return mKdTree->LoadBinTree(filename.c_str(), mObjects);
+	return mKdTree->ImportBinTree(filename.c_str(), mObjects);
 }
 
@@ -1191,5 +1190,5 @@
 	if (rays.size() > 10000)
 	{
-	
+
 		mRayCaster->SortRays(rays);
 		cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" ms."<<endl;
@@ -1199,19 +1198,19 @@
 	if (mUseHwGlobalLines) 
 	{
-	  CastRaysWithHwGlobalLines(
-								rays,
-								vssRays,
-								castDoubleRays,
-								pruneInvalidRays
-								);
+		CastRaysWithHwGlobalLines(
+			rays,
+			vssRays,
+			castDoubleRays,
+			pruneInvalidRays
+			);
 	}
 	else
 	{
-	  mRayCaster->CastRays(
-						 rays,				
-						 vssRays,
-						 mViewCellsManager->GetViewSpaceBox(),
-						 castDoubleRays,
-						 pruneInvalidRays);
+		mRayCaster->CastRays(
+			rays,				
+			vssRays,
+			mViewCellsManager->GetViewSpaceBox(),
+			castDoubleRays,
+			pruneInvalidRays);
 	}
 
@@ -1219,5 +1218,5 @@
 	{
 		cout << endl;
-        long t2 = GetTime();
+		long t2 = GetTime();
 
 #if SHOW_RAYCAST_TIMING
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/Timer/merror.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/Timer/merror.h	(revision 2066)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/Timer/merror.h	(revision 2539)
@@ -249,5 +249,5 @@
 #define CHKGL _BLBEGIN GLenum error; \
 	if ( (error = glGetError()) != GL_NO_ERROR) \
-	EOUT("here4 " << gluErrorString(error)); _BLEND;
+	EOUT("gl error " << gluErrorString(error)); _BLEND;
 
 #ifdef WIN32
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 2353)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.h	(revision 2539)
@@ -147,9 +147,10 @@
 
 
-/**
-    VspNode abstract class serving for interior and leaf node implementation
+/** VspNode abstract class serving for interior and leaf node implementation
 */
 class VspNode
 {
+	friend class VspTree;
+
 public:
 	
@@ -172,31 +173,27 @@
 	*/
 	virtual bool IsRoot() const;
-	
 	/** Returns parent node.
 	*/
 	VspInterior *GetParent();
-	
 	/** Sets parent node.
 	*/
 	void SetParent(VspInterior *parent);
-
 	/** Returns true if this node is a sibling of node n.
 	*/
 	bool IsSibling(VspNode *n) const;
-	
 	/** returns depth of the node.
 	*/
 	int GetDepth() const;
-	
-	/** returns true if the whole subtree is valid
+	/** Returns true if this node (which represents the whole subtree) is valid
 	*/
 	bool TreeValid() const;
-
+	/** Sets this node to valid.
+	*/
 	void SetTreeValid(const bool v);
-	
 	/** Cost of mergin this node.
 	*/
 	float GetMergeCost() {return (float)-mTimeStamp; }
 
+	/// timestamp of this node
 	int mTimeStamp;
 
@@ -212,13 +209,9 @@
 	int mMailbox;
 
-	//int mPvsEntriesIncr;
-	//float mMemoryIncr;
-	//float mRenderCostDecr;
-
+	
 protected:
 
 	/// if this sub tree is a completely valid view space region
 	bool mTreeValid;
-	
 	/// parent of this node
 	VspInterior *mParent;
@@ -230,4 +223,6 @@
 class VspInterior: public VspNode 
 {
+	friend class VspTree;
+
 public:
 
@@ -237,49 +232,42 @@
 
 	~VspInterior();
-	
 	/** @return false since it is an interior node 
 	*/
-  bool IsLeaf() const {
-	return false; 
-  }
-
+	bool IsLeaf() const { return false; }
 
 	int Type() const;
-
-  VspNode *GetBack() {
-	return mBack;
-  }
-
-
-  VspNode *GetFront() {
-	return mFront;
-  }
-
+	/** Returns back child.
+	*/
+	VspNode *GetBack() { return mBack; }
+	/** Returns front child.
+	*/
+	VspNode *GetFront() { return mFront; }
 	/** Returns split plane.
 	*/
-  AxisAlignedPlane GetPlane() const {
-	return mPlane;
-  }
-  
-
+	AxisAlignedPlane GetPlane() const { return mPlane; }
 	/** Returns position of split plane.
 	*/
-  float GetPosition() const {
-	return mPlane.mPosition;
-  }
-
+	float GetPosition() const { return mPlane.mPosition; }
 	/** Returns split axis.
 	*/
-  int GetAxis() const {
-	return mPlane.mAxis;
-  }
-
+	int GetAxis() const { return mPlane.mAxis; }
 	/** Replace front or back child with new child.
 	*/
 	void ReplaceChildLink(VspNode *oldChild, VspNode *newChild);
-
 	/** Replace front and back child.
 	*/
 	void SetupChildLinks(VspNode *front, VspNode *back);
+	/** Returns boundiŽng box of this node.
+	*/
+	AxisAlignedBox3 GetBoundingBox() const;
+	/** Sets boundiong box of this node.
+	*/
+	void SetBoundingBox(const AxisAlignedBox3 &box);
+	/** Computes intersection of this plane with the ray segment.
+	*/
+	int ComputeRayIntersection(const RayInfo &rayData, float &t) const
+	{
+		return rayData.ComputeRayIntersection(mPlane.mAxis, mPlane.mPosition, t);
+	}
 
 	friend std::ostream &operator<<(std::ostream &s, const VspInterior &A)
@@ -288,22 +276,11 @@
 	}
 
-	AxisAlignedBox3 GetBoundingBox() const;
-	void SetBoundingBox(const AxisAlignedBox3 &box);
-
-	/** Computes intersection of this plane with the ray segment.
-	*/
-	int ComputeRayIntersection(const RayInfo &rayData, float &t) const
-	{
-		return rayData.ComputeRayIntersection(mPlane.mAxis, mPlane.mPosition, t);
-	}
-
 
 protected:
+
 	/// bounding box for this interior node: should we really store this?
 	AxisAlignedBox3 mBoundingBox;
-
 	/// Splitting plane corresponding to this node
 	AxisAlignedPlane mPlane;
-
 	/// back node
 	VspNode *mBack;
@@ -329,7 +306,5 @@
 	/** @return true since it is an interior node 
 	*/
-  bool IsLeaf() const {
-	return true;
-  }
+	bool IsLeaf() const { return true; }
 	
 	int Type() const;
@@ -337,8 +312,5 @@
 	/** Returns pointer of view cell.
 	*/
-  ViewCellLeaf *GetViewCell() const {
-	return mViewCell;
-  }
-
+	ViewCellLeaf *GetViewCell() const { return mViewCell; }
 	/** Sets pointer to view cell.
 	*/
@@ -383,35 +355,14 @@
 public:
 	
+	///////////
+	//-- Helper structs / classes
+
 	/** Additional data which is passed down the BSP tree during traversal.
 	*/
-	class VspTraversalData
+	struct VspTraversalData
 	{  
 	public:
 		
-		/** Returns average ray contribution.
-		*/
-		float GetAvgRayContribution() const
-		{
-			return (float)mPvs / ((float)mRays->size() + Limits::Small);
-		}
-
-
-		/** Returns average rays per object.
-		*/
-		float GetAvgRaysPerObject() const
-		{
-			return (float)mRays->size() / ((float)mPvs + Limits::Small);
-		}
-
-		VspTraversalData():
-			mNode(NULL),
-			mDepth(0),
-			mRays(NULL),
-			mPvs(0),
-			mProbability(0.0),
-			mMaxCostMisses(0), 
-			mPriority(0),
-			mCorrectedPvs(0)
-		{}
+		VspTraversalData();
 		
 		VspTraversalData(VspLeaf *node, 
@@ -420,54 +371,22 @@
 						 const float pvs,
 						 const float p,
-						 const AxisAlignedBox3 &box):
-			mNode(node), 
-			mDepth(depth), 
-			mRays(rays),
-			mProbability(p),
-			mBoundingBox(box),
-			mMaxCostMisses(0),
-			mPriority(0),
-			mCorrectedPvs(0),
-			mPvs(pvs),
-			mRenderCost(0),
-			mCorrectedRenderCost(0)
-		{}
-
-		VspTraversalData(const int depth, 
-						 RayInfoContainer *rays,
-						 const AxisAlignedBox3 &box): 
-			mNode(NULL), 
-			mDepth(depth), 
-			mRays(rays),
-			mProbability(0),
-			mMaxCostMisses(0),
-			mBoundingBox(box),
-			mCorrectedPvs(0),
-			mPvs(0)	,
-			mRenderCost(0),
-			mCorrectedRenderCost(0)	
-		{}
-
+						 const AxisAlignedBox3 &box);
+
+	
 		/** Returns cost of the traversal data.
 		*/
-		float GetCost() const
-		{
-			return mPriority;
-		}
-
-		/// deletes contents and sets them to NULL
-		void Clear()
-		{
-			DEL_PTR(mRays);
-
-			if (mNode)
-			{
-				// delete old view cell
-				delete mNode->GetViewCell();
-
-				delete mNode;
-				mNode = NULL;
-			}
-		}
+		inline float GetCost() const;
+		/** Returns average ray contribution.
+		*/
+		inline float GetAvgRayContribution() const;
+		/** Returns average rays per object.
+		*/
+		inline float GetAvgRaysPerObject() const;
+		/** deletes contents and sets them to NULL.
+		*/
+		void Clear();
+
+
+		//////////////////////
 
 		/// the current node
@@ -500,4 +419,6 @@
     };
 
+	/** Helper struct for data that comes with a split of a node.
+	*/
 	struct SplitData 
 	{
@@ -511,6 +432,8 @@
 		mFrontTriangles(0),
 		mBackTriangles(0),
-		mTotalTriangles(0) {}
-
+		mTotalTriangles(0) 
+		{}
+
+		//////////////
 
 		float mFrontRenderCost;
@@ -580,13 +503,10 @@
 		{}
 
-		float GetPriority() const
-		{
-			return mPriority;
-		}
+		float GetPriority() const {	return mPriority; }
+
 
 		////////////////////
 
 		static VspTree* sVspTree;
-
 		/// the current split plane
 		AxisAlignedPlane mSplitPlane;
@@ -623,4 +543,8 @@
 	};
 
+
+	//////////////////////
+
+
 	/** Default constructor creating an empty tree.
 	*/ 
@@ -629,13 +553,10 @@
 	*/
 	~VspTree();
-
 	/** Returns BSP Tree statistics.
 	*/
 	const VspTreeStatistics &GetStatistics() const; 
-  
 	/** Returns bounding box of the specified node.
 	*/
 	AxisAlignedBox3 GetBoundingBox(VspNode *node) const;
-
 	/** Returns list of BSP leaves with pvs smaller than
 		a certain threshold.
@@ -646,18 +567,14 @@
 					   const bool onlyUnmailed = false,
 					   const int maxPvs = -1) const;
-
 	/** Returns box which bounds the whole tree.
 	*/
 	AxisAlignedBox3 GetBoundingBox() const;
-
 	/** Returns root of the view space partitioning tree.
 	*/
 	VspNode *GetRoot() const;
-
 	/** Collects the leaf view cells of the tree
 		@param viewCells returns the view cells 
 	*/
 	void CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const;
-
 	/** A ray is cast possible intersecting the tree.
 		@param the ray that is cast.
@@ -665,6 +582,4 @@
 	*/
 	int CastRay(Ray &ray);
-
-
 	/** finds neighbouring leaves of this tree node.
 	*/
@@ -672,5 +587,4 @@
 					  vector<VspLeaf *> &neighbors, 
 					  const bool onlyUnmailed) const;
-
 	/** Returns random leaf of BSP tree.
 		@param halfspace defines the halfspace from which the leaf is taken.
@@ -682,9 +596,7 @@
 	*/
 	VspLeaf *GetRandomLeaf(const bool onlyUnmailed = false);
-
 	/** Returns epsilon of this tree.
 	*/
 	float GetEpsilon() const;
-
 	/** Casts line segment into the tree.
 		@param origin the origin of the line segment
@@ -696,10 +608,7 @@
 						ViewCellContainer &viewcells,
 						const bool useMailboxing = true);
-
-		
 	/** Sets pointer to view cells manager.
 	*/
 	void SetViewCellsManager(ViewCellsManager *vcm);
-
 	/** Returns view cell the current point is located in.
 		@param point the current view point
@@ -708,20 +617,12 @@
 	*/
 	ViewCell *GetViewCell(const Vector3 &point, const bool active = false);
-
-
 	/** Returns true if this view point is in a valid view space,
 		false otherwise.
 	*/
 	bool ViewPointValid(const Vector3 &viewPoint) const;
-
 	/** Returns view cell corresponding to 
 		the invalid view space.
 	*/
 	VspViewCell *GetOutOfBoundsCell();
-
-	/** Writes tree to output stream
-	*/
-	bool Export(OUT_STREAM &stream);
-
 	/** Casts beam, i.e. a 5D frustum of rays, into tree.
 		Tests conservative using the bounding box of the nodes.
@@ -729,5 +630,4 @@
 	*/
 	int CastBeam(Beam &beam);
-
 	/** Checks if tree validity-flags are right 
 		with respect to view cell valitiy.
@@ -735,9 +635,7 @@
 	*/
 	void ValidateTree();
-
 	/** Collects rays stored in the leaves.
 	*/
 	void CollectRays(VssRayContainer &rays);
-
 	/** Intersects box with the tree and returns the number of intersected boxes.
 		@returns number of view cells found
@@ -745,18 +643,26 @@
 	int ComputeBoxIntersections(const AxisAlignedBox3 &box, 
 								ViewCellContainer &viewCells) const;
-
 	/** Returns view cells of this ray, either taking precomputed cells
 		or by recomputation.
 	*/
 	void GetViewCells(const VssRay &ray, ViewCellContainer &viewCells);
-
 	/** Returns view cells tree.
 	*/
 	ViewCellsTree *GetViewCellsTree() const { return mViewCellsTree; }
-
 	/** Sets the view cells tree.
 	*/
 	void SetViewCellsTree(ViewCellsTree *vt) { mViewCellsTree = vt; }
-
+	/** Writes vsp tree to output stream
+	*/
+	bool Export(OUT_STREAM &stream);
+	/** Writes vsp tree to binary output stream.
+	*/
+	bool ExportBinary(OUT_STREAM &stream);
+	/** Imports tree from binary format.
+	*/
+	bool ImportBinary(IN_STREAM &stream, ObjectContainer &pvsObjects);
+
+
+	////////////
 
 	PerfTimer mSortTimer;
@@ -808,19 +714,19 @@
 							 float &pFront,
 							 float &pBack) const;
-
+	/** If != NULL, sets the bounding box to the forced  bounding box.
+		Else computes the bounding box of the view space using the
+		hit points gathered from the ray-object intersections.
+	*/
 	void ComputeBoundingBox(const VssRayContainer &rays,
 							AxisAlignedBox3 *forcedBoundingBox);
-
 	/** Evaluates candidate for splitting.
 	*/
-	void EvalSubdivisionCandidate(VspSubdivisionCandidate &splitData, 
+	void EvalSubdivisionCandidate(VspSubdivisionCandidate &candidate, 
 								  bool computeSplitPlane = true);
-
 	/** Evaluates render cost decrease of next split.
 	*/
-	float EvalRenderCostDecrease(VspSubdivisionCandidate &splitData, 
+	float EvalRenderCostDecrease(VspSubdivisionCandidate &candidate, 
 								 float &normalizedOldRenderCost,
 								 const SplitData &data) const;
-
 	/** Collects view cells in the subtree under root.
 	*/
@@ -829,10 +735,8 @@
 						  ViewCellContainer &viewCells,
 						  bool onlyUnmailed = false) const;
-
 	/** Returns view cell corresponding to 
 		the invalid view space. If it does not exist, it is created.
 	*/
 	VspViewCell *GetOrCreateOutOfBoundsCell();
-
 	/** Collapses the tree with respect to the view cell partition,
 		i.e. leaves having the same view cell are collapsed.
@@ -843,9 +747,7 @@
 	*/
 	VspNode *CollapseTree(VspNode *node, int &collapsed);
-
 	/** Helper function revalidating the view cell leaf list after merge.
 	*/
 	void RepairViewCellsLeafLists();
-
 	/** Evaluates tree stats in the BSP tree leafs.
 	*/
@@ -861,5 +763,4 @@
 					   SubdivisionCandidate *splitCandidate,
 					   const bool globalCriteriaMet);
-
 	/** Adds stats to subdivision log file.
 	*/
@@ -868,13 +769,8 @@
 							 const float totalRenderCost,
 							 const float avgRenderCost);
-	
 	/** Subdivides leaf.
-			
 		@param tData data object holding, e.g., a pointer to the leaf
 		@param frontData returns the data (e.g., pointer to the leaf) in front of the split plane
 		@param backData returns the data (e.g., pointer to the leaf) 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
 	
 		@returns the root of the subdivision
@@ -891,5 +787,4 @@
 						   float &pFront,
 						   float &pBack);
-
 	/** Sorts split candidates along the specified axis.
 		The split candidates are generated on possible visibility
@@ -905,5 +800,4 @@
 								   float minBand, 
 								   float maxBand);
-
 	/** Evaluate render cost of this pvs.
 	*/
@@ -912,5 +806,4 @@
 	int EvalPvsEntriesIncr(VspSubdivisionCandidate &splitCandidate,
 						   const SplitData &sData) const;
-
 	/** Returns number of effective entries in the pvs.
 	*/
@@ -918,5 +811,4 @@
 
 	int EvalPvsEntriesContribution(const VssRay &ray, const bool isTermination) const;
-
 	/** Computes best cost for axis aligned planes.
 	*/
@@ -928,6 +820,6 @@
 
 
-	//////////////////////////////////////////
-	// Helper function for computing heuristics
+	///////////////////////
+	//-- Helper function for computing heuristics
 
 	/** Evaluates the contribution to left and right pvs at a visibility event ve.
@@ -937,43 +829,51 @@
 	*/
 	inline void EvalHeuristics(const SortableEntry &ve, float &pvsLeft, float &pvsRight) const;
-
 	/** Evaluates contribution of min event to pvs
 	*/
 	inline float EvalMinEventContribution(const VssRay &ray, const bool isTermination) const;
-
 	/** Evaluates contribution of max event to pvs
 	*/
 	inline float EvalMaxEventContribution(const VssRay &ray, const bool isTermination) const;
-
 	/** Evaluates contribution of kd leaf when encountering a min event
 	*/
 	inline float EvalMinEventContribution(KdLeaf *leaf) const;
-
 	/**  Evaluates contribution of kd leaf when encountering a max event
 	*/
 	inline float EvalMaxEventContribution(KdLeaf *leaf) const;
-
 	/** Prepares objects for the heuristics.
 		@returns pvs size as seen by the rays.
 	*/
 	float PrepareHeuristics(const RayInfoContainer &rays);
-	
 	/** Prepare a single ray for heuristics.
 	*/
 	float PrepareHeuristics(const VssRay &ray, const bool isTermination);
-
 	/** Prepare a single kd leaf for heuristics.
 	*/
 	float PrepareHeuristics(KdLeaf *leaf);
-
+	/** Evaluates minimal and maximal depth in the tree.
+	*/
 	void EvalMinMaxDepth(int &minDepth, int &maxDepth);
-
-
-
-	/////////////////////////////////////////////////////////////
-
+	/** Writes the node to disk
+		@note: should be implemented as visitor.
+	*/
+	void ExportNode(VspNode *node, OUT_STREAM &stream);
+	
+
+	////////////////
+
+	void ExportBinInterior(OUT_STREAM &stream, VspInterior *interior);
+	void ExportBinLeaf(OUT_STREAM &stream, VspLeaf *leaf);
+
+	VspInterior *ImportBinInterior(IN_STREAM  &stream, VspInterior *parent);
+	VspLeaf *ImportBinLeaf(IN_STREAM &stream, VspInterior *parent, const ObjectContainer &pvsObjects);
+
+	VspNode *ImportNextNode(IN_STREAM &stream, 
+							VspInterior *parent,
+							const ObjectContainer &pvsObjects);
+
+
+	//////////////////////////////////////////////////
 
 	/** Subdivides the rays into front and back rays according to the split plane.
-		
 		@param plane the split plane
 		@param rays contains the rays to be split. The rays are 
@@ -988,6 +888,6 @@
 			      RayInfoContainer &frontRays, 
 				  RayInfoContainer &backRays) const;
-
-
+	/** Add contributions of this ray to fron, back, and overall pvs of the parent.
+	*/
 	inline void UpdatePvsEntriesContribution(const VssRay &ray,
 											 const bool isTermination,
@@ -996,5 +896,4 @@
 											 float &backPvs,
 											 float &totalPvs) const;
-
 	/** Classfifies the object with respect to the 
 		pvs of the front and back leaf and updates pvs size
@@ -1013,5 +912,4 @@
 										 float &backPvs,
 										 float &totalPvs) const;
-
 	/** Evaluates the contribution for objects.
 	*/
@@ -1021,5 +919,4 @@
 										 float &backPvs, 
 										 float &totalPvs) const;
-
 	/** Evaluates the contribution for bounding volume leaves.
 	*/
@@ -1030,9 +927,9 @@
 										 float &totalPvs,
 										 const bool countEntries) const;
-
+	/** Updates contribution to pvs caused by this bvh leaf.
+	*/
 	inline void UpdateContributionsToPvs(BvhLeaf *leaf,
 										 const int cf,
 										 SplitData &sdata) const;
-
 	/** Evaluates the contribution for kd leaves.
 	*/
@@ -1042,13 +939,10 @@
 										 float &backPvs,
 										 float &totalPvs) const;
-
 	/** Returns true if tree can be terminated.
 	*/
 	inline bool LocalTerminationCriteriaMet(const VspTraversalData &data) const;
-
 	/** Returns true if global tree can be terminated.
 	*/
 	bool GlobalTerminationCriteriaMet(const VspTraversalData &data) const;
-
 	/** Adds ray sample contributions to the PVS.
 		@param sampleContributions the number contributions of the samples
@@ -1060,18 +954,10 @@
 						 float &sampleContributions,
 						 int &contributingSamples);
-
 	/** Propagates valid flag up the tree.
 	*/
 	void PropagateUpValidity(VspNode *node);
-
-	/** Writes the node to disk
-		@note: should be implemented as visitor.
-	*/
-	void ExportNode(VspNode *node, OUT_STREAM &stream);
-
 	/** Returns estimated memory usage of tree.
 	*/
 	float GetMemUsage() const;
-
 	/** Updates view cell pvs of objects.
 	*/
@@ -1079,10 +965,10 @@
 								ViewCell *front, 
 								ViewCell *back) const;
-
+	/** Creates a new view cell from the traversal data.
+	*/
 	void CreateViewCell(VspTraversalData &tData, 
 						const bool updatePvs,
 						const float renderCost,
 						const int pvs);
-
 	/** Collect split candidates which are affected by the last split
 		and must be reevaluated.
@@ -1091,30 +977,27 @@
 								vector<SubdivisionCandidate *> &dirtyList,
 								const bool onlyUnmailed);
-
-	void CollectDirtyCandidate(const VssRay &ray, 
+	/** Adds the split candidate associated with this ray to the dirty list.
+	*/
+	void AddCandidateToDirtyList(const VssRay &ray, 
 							   const bool isTermination,
 							   vector<SubdivisionCandidate *> &dirtyList,
 							   const bool onlyUnmailed) const;
-
 	/** Rays will be clipped to the bounding box.
 	*/
 	void PreprocessRays(const VssRayContainer &sampleRays, RayInfoContainer &rays);
-
 	/** Evaluate subdivision statistics.
 	*/
 	void EvalSubdivisionStats(const SubdivisionCandidate &tData);
-
+	/** Prepares the construction of the vsp tree.
+	*/
 	void PrepareConstruction(SplitQueue &tQueue,
 							 const VssRayContainer &sampleRays,
 							 RayInfoContainer &rays);
-
 	/** Evaluates pvs contribution of this ray.
 	*/
 	float EvalContributionToPvs(const VssRay &ray, const bool isTermination) const;
-
 	/** Evaluates pvs contribution of a kd node.
 	*/
 	float EvalContributionToPvs(KdLeaf *leaf) const;
-
 	/** Creates new root of hierarchy and computes bounding box.
 		Has to be called before the preparation of the subdivision.
@@ -1197,5 +1080,4 @@
 		int mStackPtr;
 		int mDepth;
-
 	};
 
@@ -1207,20 +1089,19 @@
 	/// pointer to the hierarchy of view cells
 	ViewCellsTree *mViewCellsTree;
-
+	/// Pointer to the hierarchy manager which is responsible for both 
+	/// view and object space
 	HierarchyManager *mHierarchyManager;
+	/// Pointer to the bv hierarchy
 	BvHierarchy *mBvHierarchy;
-	
+	/// Pointer to the view cells manager
 	ViewCellsManager *mViewCellsManager;
-	
+	/// Buffer for subdivision candidates used for split heuristics evaluation
 	vector<SortableEntry> *mLocalSubdivisionCandidates;
-
 	/// Pointer to the root of the tree
 	VspNode *mRoot;
-		
+	/// The statistics
 	VspTreeStatistics mVspStats;
-	
 	/// View cell corresponding to the space outside the valid view space
 	VspViewCell *mOutOfBoundsCell;
-
 	/// box around the whole view domain
 	AxisAlignedBox3 mBoundingBox;
@@ -1281,12 +1162,11 @@
 	// if rays should be stored in leaves
 	bool mStoreRays;
-
 	/// epsilon for geometric comparisons
 	float mEpsilon;
-
 	/// subdivision stats output file
 	std::ofstream mSubdivisionStats;
 	/// keeps track of cost during subdivision
 	float mTotalCost;
+	/// keeps track of #pvs entries during subdivison
 	int mPvsEntries;
 	/// keeps track of overall pvs size during subdivision
@@ -1297,7 +1177,6 @@
 	/// weight between render cost decrease and node render cost
 	float mRenderCostDecreaseWeight;
-
+	/// maximal #of rays used for heuristics evalution
 	int mMaxTests;
-
 	/// constant value for driving the heuristics
 	float mMemoryConst;
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 2538)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 2539)
@@ -1021,4 +1021,7 @@
 												 
 {
+	// give just an empty container as parameter:
+	// this loading function is used in the engine, thus it
+	// does not need to load the entities the preprocessor works on
 	ObjectContainer preprocessorObjects;
 
@@ -1058,5 +1061,5 @@
 	}
 	
-	if (0)
+	if (0) //hack: should work with reset function, but something is wrong ..
 	{
 		vm->ResetViewCells();
@@ -1064,5 +1067,4 @@
 	else
 	{
-		//hack: should work with reset function
 		ViewCellContainer leaves;
 
@@ -1111,5 +1113,5 @@
 	OUT_STREAM stream(filename.c_str());
 
-	// for output we need unique ids for each view cell
+	// we need unique ids for each view cell
 	CreateUniqueViewCellIds();
 
@@ -1287,8 +1289,10 @@
 
 	ViewCellContainer viewCells;
+
 #ifdef USE_BIT_PVS
 	cout << "objects size: " << (int)ObjectPvsIterator::sObjects.size() << endl;
 	cout << "pvs size: " <<  ObjectPvs::sPvsSize << endl;
 #endif
+
 	// $$ JB hack - the collect best viewcells does not work?
 #if 0
@@ -1297,11 +1301,10 @@
 	viewCells = mViewCells;
 #endif
+
 	ViewCellContainer::iterator it = viewCells.begin(), it_end = viewCells.end();		
+	
 	for (; it != it_end; ++it) 
 	{
-		if (1)
-			(*it)->UpdatePvsCost();
-		else
-			(*it)->SetTrianglesInPvs((float)(*it)->GetFilteredPvsSize());
+		(*it)->UpdatePvsCost();
 	}
 
@@ -1364,8 +1367,4 @@
 			++ smallerSum;
 		}
-		
-		//		if (0 && (i < (int)viewCells.size()))
-		//		  Debug << "new pvs cost increase: " << mViewCellsTree->GetTrianglesInPvs(viewCells[i]) 
-		//				<< " " << currentPvs << endl;
 		
 		const float volRatioDif = volDif / totalVol;
@@ -1843,26 +1842,26 @@
 							   const float filterWidth)
 {
-  ViewCell *currentViewCell = GetViewCell(viewPoint);
-
-  if (mMaxFilterSize < 1) {
-	prvs.mViewCell = currentViewCell;
-	return;
-  }
-  
-  const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
-  
-  if (currentViewCell) 
-	{
-	  ViewCellContainer viewCells;
-	  ComputeBoxIntersections(box, viewCells);
-	  
-	  ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
-	  prvs.mViewCell = root;
-	  
+	ViewCell *currentViewCell = GetViewCell(viewPoint);
+
+	if (mMaxFilterSize < 1) {
+		prvs.mViewCell = currentViewCell;
+		return;
+	}
+
+	const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
+
+	if (currentViewCell) 
+	{
+		ViewCellContainer viewCells;
+		ComputeBoxIntersections(box, viewCells);
+
+		ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
+		prvs.mViewCell = root;
+
 	} 
-  else
-	{
-	  prvs.mViewCell = NULL;
-	  //prvs.mPvs = root->GetPvs();
+	else
+	{
+		prvs.mViewCell = NULL;
+		//prvs.mPvs = root->GetPvs();
 	}
 }
@@ -4077,5 +4076,5 @@
 
 	//////////
-	//-- some view cells for output
+	//-- export visualizations of some view cells
 
 	ViewCell::NewMail();
@@ -4116,5 +4115,5 @@
        		for (vit = leaves.begin(); vit != vit_end; ++ vit)
 			{	
-				// prepare some rays for output
+				// prepare some rays for visualization
 				VssRayContainer::const_iterator rit, rit_end = (*vit)->GetOrCreateRays()->end();
 				for (rit = (*vit)->GetOrCreateRays()->begin(); rit != rit_end; ++ rit)
@@ -4126,5 +4125,5 @@
 			const int raysOut = min((int)collectRays.size(), maxRays);
 
-			// prepare some rays for output
+			// prepare some rays for visualization
 			VssRayContainer::const_iterator rit, rit_end = collectRays.end();
 			for (rit = collectRays.begin(); rit != rit_end; ++ rit)
@@ -4381,5 +4380,5 @@
 	OUT_STREAM stream(filename.c_str());
 
-	// for output we need unique ids for each view cell
+	// we need unique ids for each view cell
 	CreateUniqueViewCellIds();
 
@@ -4611,9 +4610,9 @@
 		ViewCell::NewMail();
 
-		//-- some rays for output
+		//-- some rays for visualization
 		const int raysOut = min((int)sampleRays.size(), mVisualizationSamples);
 		Debug << "visualization using " << raysOut << " samples" << endl;
 
-		//-- some random view cells and rays for output
+		//-- some random view cells and rays for visualization
 		vector<KdLeaf *> kdLeaves;
 
@@ -5400,5 +5399,5 @@
 
 	//////////
-	//-- some view cells for output
+	//-- export some view cells for visualization
 
 	ViewCell::NewMail();
@@ -5453,5 +5452,5 @@
 			const int raysOut = min((int)collectRays.size(), maxRays);
 		
-			// prepare some rays for output
+			// prepare some rays for visualization
 			VssRayContainer::const_iterator rit, rit_end = collectRays.end();
 			for (rit = collectRays.begin(); rit != rit_end; ++ rit)
@@ -5483,5 +5482,4 @@
 		{
 			Intersectable::NewMail();
-
 			ObjectPvsIterator pit = pvs.GetIterator();
 
@@ -6585,5 +6583,5 @@
 	OUT_STREAM stream(filename.c_str());
 
-	// for output we need unique ids for each view cell
+	// we need unique ids for each view cell
 	CreateUniqueViewCellIds();
 
@@ -6600,8 +6598,9 @@
 		{
 			stream << "<BoundingBoxes>" << endl;
+
+			int id = 0;
+
 			vector<KdIntersectable *>::const_iterator kit, kit_end = mPreprocessor->mKdTree->mKdIntersectables.end();
-
-			int id = 0;
-
+			
 			for (kit = mPreprocessor->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
 			{
@@ -6657,4 +6656,72 @@
 }
 
+
+bool VspOspViewCellsManager::ExportBinaryViewCells(const string filename, 
+												   const bool exportPvs, 
+												   const ObjectContainer &objects)
+{
+	if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
+		return false;
+
+	const long starttime = GetTime();
+	cout << "exporting view cells to binary format ... ";
+	
+	OUT_STREAM stream(filename.c_str());
+
+	// we need unique ids for each view cell
+	CreateUniqueViewCellIds();
+
+	int numBoundingBoxes = mPreprocessor->mKdTree->mKdIntersectables.size();
+	stream.write(reinterpret_cast<char *>(&numBoundingBoxes), sizeof(int));
+
+
+    ///////////////
+	//-- export bounding boxes
+	//-- we need the boxes to identify objects in the target engine
+
+	vector<KdIntersectable *>::const_iterator kit, kit_end = mPreprocessor->mKdTree->mKdIntersectables.end();
+
+	int id = 0;
+
+	for (kit = mPreprocessor->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
+	{
+		Intersectable *obj = (*kit);
+		const AxisAlignedBox3 &box = obj->GetBox();
+
+		// set kd node id
+		obj->SetId(id);
+		Vector3 bmin = box.Min();
+		Vector3 bmax = box.Max();
+
+		stream.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
+		stream.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
+		stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+	}
+
+
+	///////////////
+	//-- export the view cells and the pvs
+
+
+	int numViewCells = mCurrentViewCellsStats.viewCells;
+	stream.write(reinterpret_cast<char *>(&numViewCells), sizeof(int));
+
+	Vector3 vmin = mViewSpaceBox.Min();
+	Vector3 vmax = mViewSpaceBox.Max();
+
+	stream.write(reinterpret_cast<char *>(&vmin), sizeof(Vector3));
+	stream.write(reinterpret_cast<char *>(&vmax), sizeof(Vector3));
+
+
+	//////////////////////
+	//-- export the view space hierarchy
+	
+	mHierarchyManager->GetVspTree()->ExportBinary(stream);
+	
+	stream.close();
+	
+	cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
+	return true;
+}
 
 
@@ -6966,14 +7033,11 @@
 				//////////
 				// compare results
-
 				cout << "ray " << i << ": " << (int)tmpRays[i]->mViewCells.size() << " " << (int)packet.mViewCells[i].size() << endl;
 			}
-
-			
 			
 			CLEAR_CONTAINER(tmpRays);
 		}
 	}
-cout << "=================\nhere6"<<endl;
+	
 	CLEAR_CONTAINER(tmpRays);
 
@@ -6990,3 +7054,54 @@
 
 
-}
+
+ViewCellsManager *LoadViewCellsBinary(const string &filename, 
+									  ObjectContainer &pvsObjects,
+									  bool finalizeViewCells,
+									  BoundingBoxConverter *bconverter)												 
+{
+	ViewCellsParser parser;
+	ViewCellsManager *vm = NULL;
+
+	const long startTime = GetTime();
+	const bool success = false;
+
+	if (!success)
+	{
+		Debug << "Error: loading view cells failed!" << endl;
+		DEL_PTR(vm);
+
+		return NULL;
+	}
+	
+	ViewCellContainer leaves;
+
+	vm->mViewCells.clear();
+	vm->mViewCellsTree->CollectLeaves(vm->mViewCellsTree->GetRoot(), leaves);
+
+	ViewCellContainer::const_iterator it, it_end = leaves.end();
+
+	for (it = leaves.begin(); it != it_end; ++ it)
+	{
+		vm->mViewCells.push_back(*it);
+	}
+
+	vm->mViewCellsFinished = true;
+	vm->mMaxPvsSize = (int)pvsObjects.size();
+
+	if (finalizeViewCells)
+	{
+		// create the meshes and compute view cell volumes
+		const bool createMeshes = true;
+		vm->FinalizeViewCells(createMeshes);
+	}
+
+	cout << (int)vm->mViewCells.size() << " view cells loaded in "
+		 << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
+
+	Debug << (int)vm->mViewCells.size() << " view cells loaded in "
+		  << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
+	
+	return vm;
+}
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 2538)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp	(revision 2539)
@@ -407,5 +407,5 @@
 		glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
 
-	int offset = mObjects.size() * 3;
+	int offset = (int)mObjects.size() * 3;
 	char *arrayPtr = mUseVbos ? NULL : (char *)mData;
 	
@@ -413,5 +413,5 @@
 	glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
 	
-	glDrawArrays(GL_TRIANGLES, 0, mObjects.size() * 3);
+	glDrawArrays(GL_TRIANGLES, 0, (int)mObjects.size() * 3);
 	//DisableDrawArrays();
 }
@@ -1651,5 +1651,5 @@
 		return;
 
-	unsigned int offset = mObjects.size() * 3;
+	size_t offset = mObjects.size() * 3;
 	char *arrayPtr = mUseVbos ? NULL : (char *)mData;
 	
@@ -1667,5 +1667,5 @@
 	mIndices = new unsigned int[mObjects.size() * 3];
 
-	const int offset = mObjects.size() * 3;
+	size_t offset = mObjects.size() * 3;
 
 	for (size_t i = 0; i < mObjects.size(); ++ i)
@@ -1703,5 +1703,5 @@
 	}
 
-	cout << "\n**************\ndraw arrays created\n" << endl;	
+	cout << "\n******** created vertex buffer objects **********" << endl;	
 }
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp	(revision 2342)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.cpp	(revision 2539)
@@ -19,4 +19,13 @@
 namespace GtpVisibilityPreprocessor {
 
+
+#define TYPE_INTERIOR -2
+#define TYPE_LEAF -3
+
+
+static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
+{
+	return obj1->mId < obj2->mId;
+}
 
 
@@ -121,4 +130,5 @@
 }
 
+
 ViewCell::ViewCell(Mesh *mesh): 
 MeshInstance(mesh), 
@@ -131,5 +141,4 @@
 mPvsSizeValid(false),
 mFilteredPvsSize(0)
-//mMailbox(0)
 {
 	mId = -100;
@@ -302,14 +311,10 @@
 	// erase leaf from old view cell
 	ViewCellContainer::iterator it = mChildren.begin();
-
 	for (; (*it) != prev; ++ it);
+
 	if (it == mChildren.end())
-	{
 		Debug << "error: child link not found" << endl;
-	}
 	else
-	{
 		(*it) = cur;
-	}
 }
 
@@ -428,5 +433,4 @@
 
 	stack<ViewCell *> tstack;
-
 	tstack.push(vc);
 
@@ -443,5 +447,4 @@
 		{
 			ViewCellInterior *interior = static_cast<ViewCellInterior *>(vc);
-
 			ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
 			
@@ -450,5 +453,4 @@
 				tstack.push(*it);
 			}
-			
 		}
 	}
@@ -2020,5 +2022,5 @@
 }
 
-//#if HAS_TO_BE_REDONE
+
 int ViewCellsTree::CountStoredPvsEntries(ViewCell *root) const
 {
@@ -2029,5 +2031,4 @@
 	{
 		ViewCellInterior *interior = static_cast<ViewCellInterior *>(root);
-
 		ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
 
@@ -2040,5 +2041,5 @@
 	return pvsSize;    	
 }
-//#endif
+
 
 int ViewCellsTree::ViewCellsStorage() const
@@ -2587,3 +2588,203 @@
 
 
-}
+///////////////////
+// Binary export
+
+void ViewCellsTree::ExportBinInterior(OUT_STREAM &stream, ViewCellInterior *interior)
+{
+#if TODO
+	int interiorid = TYPE_INTERIOR;
+	stream.write(reinterpret_cast<char *>(&interiorid), sizeof(int));
+
+	int axis = interior->GetAxis();
+	float pos = interior->GetPosition();
+
+	stream.write(reinterpret_cast<char *>(&axis), sizeof(int));
+	stream.write(reinterpret_cast<char *>(&pos), sizeof(float));
+#endif
+}
+
+
+void ViewCellsTree::ExportBinLeaf(OUT_STREAM &stream, ViewCell *leaf)
+{
+#if TODO
+	int type = TYPE_LEAF;
+
+	int id = -1;
+	if (viewCell != mOutOfBoundsCell)
+		id = viewCell->GetId();
+
+	stream.write(reinterpret_cast<char *>(&type), sizeof(int));
+	stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+
+	int pvsSize = viewCell->GetPvs().GetSize();
+	stream.write(reinterpret_cast<char *>(&pvsSize), sizeof(int));
+
+	ObjectPvsIterator pit = viewCell->GetPvs().GetIterator();
+
+	// write PVS of view cell
+	while (pit.HasMoreEntries())
+	{
+		Intersectable *intersect = pit.Next();
+		id = intersect->GetId();
+		stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+	}
+#endif
+}
+
+
+bool ViewCellsTree::ExportBinary(OUT_STREAM &stream)
+{
+#if TODO
+	// export binary version of mesh
+	queue<ViewCell *> tStack;
+	tStack.push(mRoot);
+
+	while(!tStack.empty())
+	{
+		ViewCell *node = tStack.front();
+		tStack.pop();
+		
+		if (node->IsLeaf())
+		{
+			ExportBinLeaf(stream, static_cast<ViewCellLeaf *>(node));
+		}
+		else
+		{
+			VspInterior *interior = static_cast<ViewCellInterior *>(node);
+
+			ExportBinInterior(stream, interior);
+			
+			tStack.push(interior->GetFront());
+			tStack.push(interior->GetBack());
+		}
+	}
+#endif
+	return true;
+}
+
+
+//////////////////
+// import binary
+
+ViewCellInterior *ViewCellsTree::ImportBinInterior(IN_STREAM  &stream, ViewCellInterior *parent)
+{
+	ViewCellInterior *interior = new ViewCellInterior();
+	return interior;
+}
+
+
+ViewCellLeaf *ViewCellsTree::ImportBinLeaf(IN_STREAM &stream, 
+										   ViewCellInterior *parent,
+										   const ObjectContainer &pvsObjects)
+{
+	int leafId = TYPE_LEAF;
+	int objId = leafId;
+	int size;
+
+	stream.read(reinterpret_cast<char *>(&size), sizeof(int));
+	VspViewCell *leaf = new VspViewCell();
+
+	MeshInstance dummyInst(NULL);
+	
+	// read object ids
+	for (int i = 0; i < size; ++ i)
+	{	
+		stream.read(reinterpret_cast<char *>(&objId), sizeof(int));
+		dummyInst.SetId(objId);
+
+		ObjectContainer::const_iterator oit =
+			lower_bound(pvsObjects.begin(), pvsObjects.end(), (Intersectable *)&dummyInst, ilt);
+								
+		if ((oit != pvsObjects.end()) && ((*oit)->GetId() == objId))
+			leaf->GetPvs().AddSample(*oit, 0);
+		else
+			Debug << "error: object with id " << objId << " does not exist" << endl;
+	}
+
+	return leaf;
+}
+
+
+ViewCell *ViewCellsTree::ImportNextNode(IN_STREAM &stream, 
+										ViewCellInterior *parent,
+										const ObjectContainer &objects)
+{
+	int nodeType;
+	stream.read(reinterpret_cast<char *>(&nodeType), sizeof(int));
+
+	if (nodeType == TYPE_LEAF)
+		return ImportBinLeaf(stream, static_cast<ViewCellInterior *>(parent), objects);
+
+	if (nodeType == TYPE_INTERIOR)
+		return ImportBinInterior(stream, static_cast<ViewCellInterior *>(parent));
+
+	Debug << "error! loading failed!" << endl;
+	return NULL;
+}
+
+
+/** Data used for tree traversal
+*/
+struct MyTraversalData
+{  
+public:
+
+	MyTraversalData(ViewCell *node, const int depth, const AxisAlignedBox3 &box):
+	mNode(node), mDepth(depth), mBox(box)
+	{}
+
+
+	//////////////////////
+
+	/// the current node
+	ViewCell *mNode;
+	/// current depth
+	int mDepth;
+	/// the bounding box
+	AxisAlignedBox3 mBox;
+};
+
+
+bool ViewCellsTree::ImportBinary(IN_STREAM &stream, const ObjectContainer &pvsObjects)
+{
+	// export binary version of mesh
+	queue<ViewCell *> tStack;
+
+	// hack: we make a new root
+	DEL_PTR(mRoot);
+  
+	mRoot = ImportNextNode(stream, NULL, pvsObjects);
+
+	tStack.push(mRoot);
+
+	while(!tStack.empty())
+	{
+		ViewCell *viewCell = tStack.front();
+		tStack.pop();
+
+		if (!viewCell->IsLeaf())
+		{
+			ViewCellInterior *interior = static_cast<ViewCellInterior *>(viewCell);
+
+            ViewCell *front = ImportNextNode(stream, interior, pvsObjects);
+			ViewCell *back = ImportNextNode(stream, interior, pvsObjects);
+	
+			interior->mChildren.push_back(front);
+			interior->mChildren.push_back(back);
+
+			tStack.push(front);			
+			tStack.push(back);
+		}
+		else
+		{
+			//cout << "l";
+		}
+	}
+
+	return true;
+}
+
+
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 2524)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 2539)
@@ -13,6 +13,4 @@
 using namespace std;
 
-// $$JB HACK
-//#define KD_PVS_AREA (1e-4f)
 
 #define TYPE_INTERIOR -2
@@ -32,11 +30,11 @@
 
 
-KdNode::KdNode(KdInterior *parent):mParent(parent), mMailbox(0), mIntersectable(NULL)
-
-{
-  if (parent)
-    mDepth = parent->mDepth+1;
-  else
-    mDepth = 0;
+KdNode::KdNode(KdInterior *parent):
+mParent(parent), mMailbox(0), mIntersectable(NULL)
+{
+	if (parent)
+		mDepth = parent->mDepth+1;
+	else
+		mDepth = 0;
 }
 
@@ -57,7 +55,5 @@
 
 KdTree::KdTree()
-{
-
-  
+{ 
   mRoot = new KdLeaf(NULL, 0);
   Environment::GetSingleton()->GetIntValue("KdTree.Termination.maxNodes", mTermMaxNodes);
@@ -194,5 +190,5 @@
 		 (leaf->mDepth >= mTermMaxDepth);
  
-	if (criteriaMet)
+	if (0 && criteriaMet)
 		cerr<<"\n OBJECTS="<<(int)leaf->mObjects.size()<<endl;
 
@@ -1132,8 +1128,5 @@
 
 
-int
-KdTree::CastBeam(
-				 Beam &beam
-				 )
+int KdTree::CastBeam(Beam &beam)
 {
   stack<KdNode *> nodeStack;
@@ -1221,5 +1214,5 @@
 	
 	// read object ids
-	// note: could also do this geometrically
+	// note: this can also be done geometrically
 	for (int i = 0; i < size; ++ i)
 	{	
@@ -1231,11 +1224,7 @@
 								
 		if ((oit != objects.end()) && ((*oit)->GetId() == objId))
-		{
-			if (1) leaf->mObjects.push_back(*oit);
-		}
+			leaf->mObjects.push_back(*oit);
 		else
-		{
 			Debug << "error: object with id " << objId << " does not exist" << endl;
-		}
 	}
 
@@ -1261,6 +1250,6 @@
 	KdInterior *interior = new KdInterior(parent);
 
-	int axis = interior->mAxis;
-	float pos = interior->mPosition;
+	int axis;
+	float pos;
 
 	stream.read(reinterpret_cast<char *>(&axis), sizeof(int));
@@ -1310,7 +1299,7 @@
 
 
-KdNode *KdTree::LoadNextNode(IN_STREAM &stream, 
-							 KdInterior *parent,
-							 const ObjectContainer &objects)
+KdNode *KdTree::ImportNextNode(IN_STREAM &stream, 
+							   KdInterior *parent,
+							   const ObjectContainer &objects)
 {
 	int nodeType;
@@ -1318,20 +1307,15 @@
 
 	if (nodeType == TYPE_LEAF)
-	{
 		return ImportBinLeaf(stream, static_cast<KdInterior *>(parent), objects);
-	}
 
 	if (nodeType == TYPE_INTERIOR)
-	{
 		return ImportBinInterior(stream, static_cast<KdInterior *>(parent));
-	}
 
 	Debug << "error! loading failed!" << endl;
-	
 	return NULL;
 }
 
 
-bool KdTree::LoadBinTree(const string &filename, ObjectContainer &objects)
+bool KdTree::ImportBinTree(const string &filename, ObjectContainer &objects)
 {
 	// export binary version of mesh
@@ -1342,5 +1326,6 @@
 
 	// sort objects by their id
-	sort(objects.begin(), objects.end(), ilt);
+//	if (!is_sorted(objects.begin(), objects.end(), ilt))
+		sort(objects.begin(), objects.end(), ilt);
 
 	mBox.Initialize();
@@ -1359,5 +1344,5 @@
 	DEL_PTR(mRoot);
   
-	mRoot = LoadNextNode(stream, NULL, objects);
+	mRoot = ImportNextNode(stream, NULL, objects);
 
 	tStack.push(TraversalData(mRoot, mBox, 0));
@@ -1380,6 +1365,6 @@
 			interior->mBox = tData.mBox;
 
-            KdNode *front = LoadNextNode(stream, interior, objects);
-			KdNode *back = LoadNextNode(stream, interior, objects);
+            KdNode *front = ImportNextNode(stream, interior, objects);
+			KdNode *back = ImportNextNode(stream, interior, objects);
 	
 			interior->SetupChildLinks(back, front);
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.h	(revision 2387)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCell.h	(revision 2539)
@@ -547,42 +547,49 @@
 	*/
 	ViewCell *GetActiveViewCell(ViewCellLeaf *vc) const;
-
 	/** Sets the leaves to be the currently active view cells.
 	*/
     void SetActiveSetToLeaves();
-
 	/** Propagates pvs up the tree to the root and downwards the tree.
 	*/
 	void PropagatePvs(ViewCell *vc);
-
 	/** Exports view cells to file.
 	*/
 	bool Export(OUT_STREAM &stream, const bool exportPvs = false);
-
 	/** Export statistics of this view cell tree.
 	*/
 	void ExportStats(const std::string &mergeStats);
-
 	/** Sets root of hierarchy.
 	*/
 	void SetRoot(ViewCell *root);
-
 	/** Assignes unique ids to view cells.
 	*/
 	void CreateUniqueViewCellsIds();
-
 	/** Resets pvs of whole tree.
 	*/
 	void ResetPvs();
-
 	/** Counts pvs of the view cell taking the kd cells into account.
 	*/
 	int CountKdPvs(const ViewCellLeaf *vc) const;
-
 	/** Sets pointer to view cells manager.
 	*/
 	void SetViewCellsManager(ViewCellsManager *vcm);
 
-	void Update();
+	ViewCellInterior *ImportBinInterior(IN_STREAM  &stream, ViewCellInterior *parent);
+
+	ViewCellLeaf *ImportBinLeaf(IN_STREAM &stream, 
+		                        ViewCellInterior *parent,
+								const ObjectContainer &pvsObjects);
+
+	void ExportBinInterior(OUT_STREAM &stream, ViewCellInterior *interior);
+
+	void ExportBinLeaf(OUT_STREAM &stream, ViewCell *leaf);
+
+	bool ExportBinary(OUT_STREAM &stream);
+	
+	bool ImportBinary(IN_STREAM &stream, const ObjectContainer &pvsObjects);
+
+	ViewCell *ImportNextNode(IN_STREAM &stream, 
+							 ViewCellInterior *parent,
+							 const ObjectContainer &objects);
 
 protected:
@@ -601,45 +608,35 @@
 	*/
 	float ComputeMergedPvsCost(const ObjectPvs &pvs1, const ObjectPvs &pvs2) const;
-
 	/** Returns cost of this leaf according to current heuristics.
 	*/
 	float GetCostHeuristics(ViewCell *vc) const;
-
 	/** Returns cost of leaf.
 	*/
 	float GetRenderCost(ViewCell *vc) const;
-
 	/** Evaluates the merge cost of this merge candidate pair.
 	*/
 	void EvalMergeCost(MergeCandidate &mc) const;
-
 	/** Variance of leaf.
 	*/
 	float GetVariance(ViewCell *vc) const;
-
 	/** Standard deviation of leaf.
 	*/
 	float GetDeviation(ViewCell *vc) const;
-
 	/** Tries to set this merge candidate to valid. 
 		@returns false if both view cells are the same
 	*/
 	bool ValidateMergeCandidate(MergeCandidate &mc) const;
-
 	/** Merge view cells of leaves l1 and l2.
 		@returns difference in pvs size
 	*/
 	ViewCellInterior *MergeViewCells(ViewCell *l, ViewCell *r, float &pvsDiff);
-
 	/** Shuffles, i.e. takes border leaf from view cell 1 and adds it 
 		to view cell 2.
 	*/
 	void ShuffleLeaf(ViewCell *leaf, ViewCellInterior *vc1, ViewCellInterior *vc2) const;	
-		
 	/** Shuffles the leaves, i.e., tests if exchanging
 		the leaves helps in improving the view cells.
 	*/
 	bool ShuffleLeaves(MergeCandidate &mc) const;
-
 	/** Calculates cost for merge of view cell 1 and 2.
 	*/
@@ -647,5 +644,4 @@
 						  ViewCellInterior *vc1, 
 						  ViewCellInterior *vc2) const;
-
 	/** Exports a snapshot of the merged view cells to disc.
 	*/
@@ -653,61 +649,48 @@
 							   const ObjectContainer &objects,
 							   const int numNewViewCells);
-
 	/** Merge queue must be reset after some time because expected value
 		may not be valid.
 	*/
 	void ResetMergeQueue();
-
 	/** Updates the current cut of view cells.
 		@returns number of newly merged view cells
 	*/
 	int UpdateActiveViewCells(ViewCellContainer &viewCells);
-
 	/** Helper function pullling pvs as high up in the tree as possible.
 	*/ 
 	void PullUpVisibility(ViewCellInterior *interior);
-
 	/** Compress pvs of view cell and children.
 	*/
 	void CompressViewCellsPvs(ViewCell *root);
-
 	/** Returns memory usage of view cells.
 	*/
 	float GetMemUsage() const;
-
 	/**	Exports single view cell.
 		NOTE: should be in exporter!!
 	*/
 	void ExportViewCell(ViewCell *viewCell, OUT_STREAM &stream, const bool exportPvs);	
-
 	/** Exports pvs of a view cell.
 	*/
 	void ExportPvs(ViewCell *viewCell, OUT_STREAM &stream);
-
 	/** Counts the logical number of entries in the pvs this view cell.
 		The pvs is assumed to be stored using lossless compression.
 	*/
 	int GetEntriesInPvsForCompressedStorage(ViewCell *vc) const;
-
 	/** Computes pvs size of this view cell.
 		The pvs is assumed to be stored using lossless compression.
 	*/
 	float GetPvsCostForCompressedStorage(ViewCell *vc) const;
-	
 	/** Computes pvs size of this view cell.
 		The pvs is assumed to be stored in the leaves.
 	*/
 	float GetPvsCostForLeafStorage(ViewCell *vc) const;
-
 	/** Counts the logical number of entries in the pvs this view cell.
 		The pvs is assumed to be stored using the leaves.
 	*/
 	int GetEntriesInPvsForLeafStorage(ViewCell *vc) const;
-
 	/** Update stats for the log.
 	*/
 	void UpdateStats(std::ofstream &stats,
 					 const ViewCellsTreeStats &vcStats);
-
 	
 
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 2529)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp	(revision 2539)
@@ -32,4 +32,8 @@
 
 
+#define TYPE_INTERIOR -2
+#define TYPE_LEAF -3
+
+
 /////////////
 //-- static members
@@ -114,4 +118,67 @@
 }
 
+
+
+VspTree::VspTraversalData::VspTraversalData():
+mNode(NULL),
+mDepth(0),
+mRays(NULL),
+mPvs(0),
+mProbability(0.0),
+mMaxCostMisses(0), 
+mPriority(0),
+mCorrectedPvs(0)
+{}
+
+
+VspTree::VspTraversalData::VspTraversalData(VspLeaf *node, 
+											const int depth, 
+											RayInfoContainer *rays,
+											const float pvs,
+											const float p,
+											const AxisAlignedBox3 &box):
+mNode(node), 
+mDepth(depth), 
+mRays(rays),
+mProbability(p),
+mBoundingBox(box),
+mMaxCostMisses(0),
+mPriority(0),
+mCorrectedPvs(0),
+mPvs(pvs),
+mRenderCost(0),
+mCorrectedRenderCost(0)
+{}
+
+
+float VspTree::VspTraversalData::GetAvgRayContribution() const
+{
+	return (float)mPvs / ((float)mRays->size() + Limits::Small);
+}
+
+
+float VspTree::VspTraversalData::GetAvgRaysPerObject() const
+{
+	return (float)mRays->size() / ((float)mPvs + Limits::Small);
+}
+
+	
+float VspTree::VspTraversalData::GetCost() const 
+{
+	return mPriority; 
+}
+	
+
+void VspTree::VspTraversalData::Clear()
+{
+	DEL_PTR(mRays);
+
+	if (mNode)
+	{	// delete old view cell
+		delete mNode->GetViewCell();
+		delete mNode;
+		mNode = NULL;
+	}
+}
 
 
@@ -3159,10 +3226,10 @@
 
 
-void VspTree::CollectDirtyCandidate(const VssRay &ray, 
-									const bool isTermination,
-									vector<SubdivisionCandidate *> &dirtyList,
-									const bool onlyUnmailed) const
-{
-	
+void VspTree::AddCandidateToDirtyList(const VssRay &ray, 
+								const bool isTermination,
+								vector<SubdivisionCandidate *> &dirtyList,
+								const bool onlyUnmailed) const
+
+{
 #if HACK_PERFORMANCE
 
@@ -3172,5 +3239,4 @@
 
 	BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
-
 	SubdivisionCandidate *candidate;
 
@@ -3254,8 +3320,8 @@
 		VssRay *ray = (*rit).mRay;
 		
-		CollectDirtyCandidate(*ray, true, dirtyList, onlyUnmailed);
+		AddCandidateToDirtyList(*ray, true, dirtyList, onlyUnmailed);
 
 #if COUNT_ORIGIN_OBJECTS
-        CollectDirtyCandidate(*ray, false, dirtyList, onlyUnmailed);
+        AddCandidateToDirtyList(*ray, false, dirtyList, onlyUnmailed);
 #endif
 	}
@@ -3788,5 +3854,228 @@
 
 
-
-
-}
+//////////
+// Binary export
+
+void VspTree::ExportBinInterior(OUT_STREAM &stream, VspInterior *interior)
+{
+	int interiorid = TYPE_INTERIOR;
+	stream.write(reinterpret_cast<char *>(&interiorid), sizeof(int));
+
+	int axis = interior->GetAxis();
+	float pos = interior->GetPosition();
+
+	stream.write(reinterpret_cast<char *>(&axis), sizeof(int));
+	stream.write(reinterpret_cast<char *>(&pos), sizeof(float));
+}
+
+
+void VspTree::ExportBinLeaf(OUT_STREAM &stream, VspLeaf *leaf)
+{
+	ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
+
+	int type = TYPE_LEAF;
+
+	int id = -1;
+	if (viewCell != mOutOfBoundsCell)
+		id = viewCell->GetId();
+
+	stream.write(reinterpret_cast<char *>(&type), sizeof(int));
+	stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+
+	int pvsSize = viewCell->GetPvs().GetSize();
+	stream.write(reinterpret_cast<char *>(&pvsSize), sizeof(int));
+
+	ObjectPvsIterator pit = viewCell->GetPvs().GetIterator();
+
+	// write PVS of view cell
+	while (pit.HasMoreEntries())
+	{
+		Intersectable *intersect = pit.Next();
+		id = intersect->GetId();
+		stream.write(reinterpret_cast<char *>(&id), sizeof(int));
+	}
+}
+
+
+bool VspTree::ExportBinary(OUT_STREAM &stream)
+{
+	// export binary version of mesh
+	queue<VspNode *> tStack;
+	tStack.push(mRoot);
+
+	while(!tStack.empty())
+	{
+		VspNode *node = tStack.front();
+		tStack.pop();
+		
+		if (node->IsLeaf())
+		{
+			ExportBinLeaf(stream, static_cast<VspLeaf *>(node));
+		}
+		else
+		{
+			VspInterior *interior = static_cast<VspInterior *>(node);
+
+			ExportBinInterior(stream, interior);
+			
+			tStack.push(interior->GetFront());
+			tStack.push(interior->GetBack());
+		}
+	}
+
+	return true;
+}
+
+
+//////////////////
+// import binary
+
+VspInterior *VspTree::ImportBinInterior(IN_STREAM  &stream, VspInterior *parent)
+{
+	AxisAlignedPlane plane;
+
+	stream.read(reinterpret_cast<char *>(&plane.mAxis), sizeof(int));
+	stream.read(reinterpret_cast<char *>(&plane.mPosition), sizeof(float));
+
+	VspInterior *interior = new VspInterior(plane);
+
+	return interior;
+}
+
+
+VspLeaf *VspTree::ImportBinLeaf(IN_STREAM &stream, 
+								VspInterior *parent,
+								const ObjectContainer &pvsObjects)
+{
+#if TODO
+	int leafId = TYPE_LEAF;
+	int objId = leafId;
+	int size;
+
+	stream.read(reinterpret_cast<char *>(&size), sizeof(int));
+	KdLeaf *leaf = new KdLeaf(parent, size);
+
+	MeshInstance dummyInst(NULL);
+	
+	// read object ids
+	// note: could also do this geometrically
+	for (int i = 0; i < size; ++ i)
+	{	
+		stream.read(reinterpret_cast<char *>(&objId), sizeof(int));
+		dummyInst.SetId(objId);
+
+		ObjectContainer::const_iterator oit =
+			lower_bound(objects.begin(), objects.end(), (Intersectable *)&dummyInst, ilt);
+								
+		if ((oit != objects.end()) && ((*oit)->GetId() == objId))
+			leaf->mObjects.push_back(*oit);
+		else
+			Debug << "error: object with id " << objId << " does not exist" << endl;
+	}
+	return leaf;
+#endif
+return NULL;
+}
+
+
+VspNode *VspTree::ImportNextNode(IN_STREAM &stream, 
+								 VspInterior *parent,
+								 const ObjectContainer &objects)
+{
+	int nodeType;
+	stream.read(reinterpret_cast<char *>(&nodeType), sizeof(int));
+
+	if (nodeType == TYPE_LEAF)
+		return ImportBinLeaf(stream, static_cast<VspInterior *>(parent), objects);
+
+	if (nodeType == TYPE_INTERIOR)
+		return ImportBinInterior(stream, static_cast<VspInterior *>(parent));
+
+	Debug << "error! loading failed!" << endl;
+	return NULL;
+}
+
+
+/** Data used for tree traversal
+*/
+struct MyTraversalData
+{  
+public:
+
+	MyTraversalData(VspNode *node, const int depth, const AxisAlignedBox3 &box):
+	mNode(node), mDepth(depth), mBox(box)
+	{}
+
+
+	//////////////////////
+
+	/// the current node
+	VspNode *mNode;
+	/// current depth
+	int mDepth;
+	/// the bounding box
+	AxisAlignedBox3 mBox;
+};
+
+
+bool VspTree::ImportBinary(IN_STREAM &stream, ObjectContainer &pvsObjects)
+{
+	// export binary version of mesh
+	queue<MyTraversalData> tStack;
+
+	// sort objects by their id
+	//sort(objects.begin(), objects.end(), ilt);
+
+	// hack: we make a new root
+	DEL_PTR(mRoot);
+  
+	mRoot = ImportNextNode(stream, NULL, pvsObjects);
+
+	tStack.push(MyTraversalData(mRoot, 0, mBoundingBox));
+	mVspStats.Reset();
+	mVspStats.nodes = 1;
+
+	while(!tStack.empty())
+	{
+		MyTraversalData tData = tStack.front();
+		tStack.pop();
+
+		VspNode *node = tData.mNode;
+
+		if (!node->IsLeaf())
+		{
+			mVspStats.nodes += 2;
+
+			//Debug << "i" ;
+			VspInterior *interior = static_cast<VspInterior *>(node);
+			interior->SetBoundingBox(tData.mBox);
+
+            VspNode *front = ImportNextNode(stream, interior, pvsObjects);
+			VspNode *back = ImportNextNode(stream, interior, pvsObjects);
+	
+			interior->SetupChildLinks(back, front);
+
+			++ mVspStats.splits[interior->GetAxis()];
+
+			// compute new bounding box
+			AxisAlignedBox3 frontBox, backBox;
+			
+			tData.mBox.Split(interior->GetAxis(), 
+                			 interior->GetPosition(), 
+							 frontBox, 
+							 backBox);
+
+			tStack.push(MyTraversalData(front, tData.mDepth + 1, frontBox));			
+			tStack.push(MyTraversalData(back, tData.mDepth + 1,  backBox));
+		}
+		else
+		{
+			//EvaluateLeafStats(tData);
+			//cout << "l";
+		}
+	}
+	return true;
+}
+
+
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 2198)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/RayCaster.cpp	(revision 2539)
@@ -400,4 +400,5 @@
 
 	for (rit = rays.begin(); rit != rit_end; ++ rit) {
+		
 		CastRay(
 			*rit,				
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h	(revision 2538)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.h	(revision 2539)
@@ -417,7 +417,7 @@
 
   bool ExportBinTree(const std::string &filename);
-
-  /// loads kd tree from disk. note: sorts objects by id
-  bool LoadBinTree(const std::string &filename, ObjectContainer &object);
+  /** loads kd tree from disk. note: sorts objects by id
+  */
+  bool ImportBinTree(const std::string &filename, ObjectContainer &object);
 
 protected:
@@ -589,9 +589,17 @@
 	void ProcessMultipleRefs(KdLeaf *leaf) const;
 
+
+	//////////
+	// binary import / export
+
 	void ExportBinLeaf(OUT_STREAM  &stream, KdLeaf *leaf);
+	
 	void ExportBinInterior(OUT_STREAM &stream, KdInterior *interior);
+
 	KdLeaf *ImportBinLeaf(IN_STREAM &stream, KdInterior *parent, const ObjectContainer &objects);
+	
 	KdInterior *ImportBinInterior(IN_STREAM  &stream, KdInterior *parent);
-	KdNode *LoadNextNode(IN_STREAM  &stream, KdInterior *parent, const ObjectContainer &objects);
+	
+	KdNode *ImportNextNode(IN_STREAM  &stream, KdInterior *parent, const ObjectContainer &objects);
 	
 	/** Adds this objects to the kd leaf objects.
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 2307)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 2539)
@@ -79,32 +79,46 @@
 						  const int line)
 {
+	vector<char *> substrings;
+
+	// extract the triples of the form v/t/n v/t/n ...
 	char *pch = strtok(str + 1, " ");
-	 
+
+	while (pch != NULL)
+	{
+		substrings.push_back(pch);
+		pch = strtok(NULL, " ");	  
+	}
+
+	//for (int i = 0; i < substrings.size(); ++ i)
+	//	cout << "sub: " << substrings[i] << " ";
+
 	VertexIndexContainer indices;
-	int i = 0;
-	while (pch != NULL)
-	{++ i;
-	  const int index = (int)strtol(pch, NULL, 10) - 1;
-						
-	  // store vertex in hash table
-	  //hashTable[index] = vertices[index];
-	  if (index >= 0)
-		indices.push_back(index);
-		
-	  pch = strtok(NULL, " ");
-	  
-	  // problem: don't know how intel ray tracer tesselates
-	  if ((int)indices.size() > 2)
+
+	for (int i = 0; i < substrings.size(); ++ i)
+	{
+		// discard normal and texture indices
+		// and only keep first index
+	
+		char *str = strtok(substrings[i], "/");	  
+		const int index = (int)strtol(str, NULL, 10) - 1;
+
+		// store indices
+		if (index >= 0)
+			indices.push_back(index);
+
+		//cout << "i " << index << " ";
+
+		// new triangle found
+		// problem: don't know how intel ray tracer tesselates
+		if ((int)indices.size() > 2)
 		{
-			const int index_2 = (int)indices.size() - 2;
-			const int index_3 = (int)indices.size() - 1;
+			const int idx2 = (int)indices.size() - 2;
+			const int idx3 = (int)indices.size() - 1;
 
 			triangles.push_back(Triangle3(vertices[indices[0]], 
-										  vertices[indices[index_2]], 		
-										  vertices[indices[index_3]]));
+										  vertices[indices[idx2]], 		
+										  vertices[indices[idx3]]));
 		}
 	}
-	//if (line == 451703)
-	//	cout << "t: " << triangles.size() << endl;
 }
 
@@ -230,21 +244,24 @@
 	while (fgets(str, 100000, file) != NULL)
 	{
-	  switch (str[0]) 
+		switch (str[0]) 
 		{
 		case 'v': // vertex  or normal
-		  {
-			switch (str[1]) 
 			{
-			case 'n' :
-				// normal do nothing
+				switch (str[1]) 
+				{
+				case 'n' :
+					// do nothing for normals
+					break;
+				case 't':
+					// do nothing for textures
+					break;
+				default:
+					float x, y, z; //cout << "v";	
+					sscanf(str + 1, "%f %f %f", &x, &y, &z);
+					vertices.push_back(Vector3(x,y,z));
+
+				}
 				break;
-			default:
-				float x, y, z; //cout << "v";	
-				sscanf(str + 1, "%f %f %f", &x, &y, &z);
-				vertices.push_back(Vector3(x,y,z));
-			 
 			}
-			break;
-		  }
 		case 'f': 
 			{
@@ -254,5 +271,5 @@
 
 					if (!face) break;
-	
+
 					faces.push_back(face);
 
@@ -265,6 +282,9 @@
 				{
 					++ line;
+
+					//////////
+					// construct the triangles given in the current line
+
 					vector<Triangle3> triangles;
-					
 					LoadTriangles(str, vertices, triangles, line);
 
@@ -273,8 +293,9 @@
 					for (tit = triangles.begin(); tit != tit_end; ++ tit)
 					{
+						// test if it is a valid triangle
 						if (0 && !TriangleValid(*tit)) continue;
 
 						TriangleIntersectable *obj = new TriangleIntersectable(*tit);	
-                        root->mGeometry.push_back(obj);
+						root->mGeometry.push_back(obj);
 					}
 				}
@@ -285,5 +306,5 @@
 		}
 	}
-	
+
 	//cout << "\n**** " << root->mGeometry.size() << " " << " lines: " << line << endl;
 	if (loadMeshes)
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 2353)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 2539)
@@ -1750,4 +1750,6 @@
 
 
+/** Deletes the ray refs from the all the objects in the container.
+*/
 static void RemoveRayRefs(const ObjectContainer &objects)
 {
@@ -1826,4 +1828,5 @@
 	else
 	{
+		// just output boxes of objects
 		ObjectContainer::const_iterator oit, oit_end = objects.end();
 
@@ -1842,4 +1845,8 @@
 
 
+
+
+/////////////////////////
+
 class HierarchyNodeWrapper;
 
@@ -1858,4 +1865,7 @@
 					   myless<vector<HierarchyNodeWrapper *>::value_type> > HierarchyNodeQueue;
 
+/** A wrapper for a hierarchy node. This class let's us treat vsp and bvh nodes
+	as if they were inherited from the same class.
+*/
 class HierarchyNodeWrapper
 {
@@ -1871,4 +1881,6 @@
 
 
+/** Class wrapping a vsp node.
+*/
 class VspNodeWrapper: public HierarchyNodeWrapper
 {
@@ -1893,8 +1905,12 @@
 	}
 
+	//////////
+
 	VspNode *mNode;
 };
 
 
+/** Class wrapping a bvh node.
+*/
 class BvhNodeWrapper: public HierarchyNodeWrapper
 {
@@ -1918,4 +1934,6 @@
 		}
 	}
+
+	////////////
 
 	BvhNode *mNode;
@@ -1950,6 +1968,11 @@
 	}
 
+	//////////
+
 	ViewCell *mViewCell;
 };
+
+//////////////////////////////
+
 
 
@@ -1960,5 +1983,5 @@
 {
 	HierarchyNodeQueue tqueue;
-	//tqueue.push(new VspNodeWrapper(mVspTree->GetRoot()));
+
 	tqueue.push(new ViewCellWrapper(mVspTree->mViewCellsTree->GetRoot()));
 	tqueue.push(new BvhNodeWrapper(mBvHierarchy->GetRoot()));
@@ -1970,7 +1993,9 @@
 		HierarchyNodeWrapper *nodeWrapper = tqueue.top();
 		tqueue.pop();
-		//cout << "priority: " << nodeWrapper->GetMergeCost() << endl;
-		// save the view cells if it is a leaf or if enough view cells have already been traversed
-		// because of the priority queue, this will be the optimal set of view cells
+
+		// save the view cells if it is a leaf or if enough view cells 
+		// have already been traversed because of the priority queue, 
+		// this will be the optimal set of view cells
+
 		if (nodeWrapper->IsLeaf() || 
 			((viewCells.size() + bvhNodes.size() + tqueue.size() + 1) >= maxSplits) ||
@@ -2517,4 +2542,3 @@
 }
 
-
-}
+}
Index: /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp
===================================================================
--- /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 2332)
+++ /GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.cpp	(revision 2539)
@@ -122,16 +122,6 @@
 	//Debug<<"\nhsize: " << mHashPvs.size() << endl;
 }
-/*
-void ViewCellsParseHandlers::CreateHashVector2()
-{
-	ObjectContainer::const_iterator oit, oit_end = mPvsObjects.end();
-
-	for (oit = mPvsObjects.begin(); oit != oit_end; ++ oit)
-	{
-		mHashPvs[(*oit)->GetId()] = (*oit);
-	}
-	Debug<<"\nhsize: " << mHashPvs.size() << endl;
-}
-*/
+
+
 // ---------------------------------------------------------------------------
 //  StdInParseHandlers: Implementation of the SAX DocumentHandler interface
@@ -324,13 +314,4 @@
 	{
 		sort(mPvsObjects.begin(), mPvsObjects.end(), ilt);
-
-		/*ObjectContainer::const_iterator oit, oit_end = mPvsObjects.end();
-        
-		int id = 0;
-		for (oit = mPvsObjects.begin(); oit != oit_end; ++ oit, ++ id)
-		{
-			if ((*oit)->GetId() != id)
-				Debug << "error" << endl;
-		}*/
 	}
 
@@ -540,20 +521,23 @@
 void ViewCellsParseHandlers::StartViewCellPvs(ObjectPvs &pvs, const char *ptr)
 {
-	// handle obect indices
+	// handle object indices
 	vector<int> objIndices;
 	char *endptr;
 			
 	while (1)
-	{	// read object ids
+	{	
+		// read object ids
 		const int index = strtol(ptr, &endptr, 10);
+		
 		if (ptr == endptr) 
 			break;
+		
 		objIndices.push_back(index);
 		ptr = endptr;
 	}
 
+	mPvsTimer.Entry();
+
 	Intersectable::NewMail();
-
-	mPvsTimer.Entry();
 
 	// TODO: 
@@ -561,9 +545,8 @@
 	// 2) get view cell with specified id
 	MeshInstance dummyInst(NULL);
+	pair<ObjectContainer::const_iterator, ObjectContainer::const_iterator> result;
 
 	vector<int>::const_iterator it, it_end = objIndices.end();
 	
-	pair<ObjectContainer::const_iterator, ObjectContainer::const_iterator> result;
-
 	for (it = objIndices.begin(); it != it_end; ++ it)
 	{
@@ -578,5 +561,5 @@
 		}
 #else
-#if 0
+	#if 0
 		dummyInst.SetId(objId);
 
@@ -584,5 +567,6 @@
 							lower_bound(mPvsObjects.begin(), 
 										mPvsObjects.end(), 
-										(Intersectable *)&dummyInst, ilt);	
+										(Intersectable *)&dummyInst, 
+										ilt);	
 
 		if ((oit != mPvsObjects.end()) && ((*oit)->GetId() == objId))
@@ -590,7 +574,7 @@
 			pvs.AddSample(*oit, 1.0f);
 		}
-#else
+	#else
 		pvs.AddSample(mPvsObjects[objId], 1.0f);
-#endif
+	#endif
 #endif
 	}
