Index: GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.h	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.h	(revision 1344)
@@ -16,5 +16,5 @@
   
   virtual bool ParseFile(const std::string filename, 
-						 SceneGraphNode **root, 
+						 SceneGraphNode *root, 
 						 const bool loadPolygonsAsMeshes = false,
 						 vector<FaceParentInfo> *parents = NULL);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj	(revision 1292)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/TestPreprocessor.vcproj	(revision 1344)
@@ -187,4 +187,10 @@
 				Name="VCCLCompilerTool"
 				Optimization="3"
+				GlobalOptimizations="TRUE"
+				InlineFunctionExpansion="2"
+				FavorSizeOrSpeed="1"
+				EnableFiberSafeOptimizations="TRUE"
+				OptimizeForProcessor="3"
+				OptimizeForWindowsApplication="TRUE"
 				AdditionalIncludeDirectories="..\include;..\..\..\..\..\..\NonGTP\Boost;&quot;$(QTDIR)\include\QtOpenGl&quot;;..\src;..\..\..\..\..\..\NonGTP\Devil\include;..\..\..\..\..\..\NonGTP\Zlib\include;..\..\..\..\..\..\NonGTP\Xerces"
 				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;GTP_INTERNAL"
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.cpp	(revision 1315)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.cpp	(revision 1344)
@@ -15,4 +15,5 @@
 #include "Beam.h"
 #include "IntersectableWrapper.h"
+#include "Triangle3.h"
 
 
@@ -20,5 +21,5 @@
 
 
-VrmlExporter::VrmlExporter(const string filename):Exporter(filename)
+VrmlExporter::VrmlExporter(const string filename): Exporter(filename)
 {
 	stream.open(mFilename.c_str());
@@ -159,59 +160,4 @@
   
 	stream<<"</Group>"<<endl;
-}
-
-
-void VrmlExporter::ExportIntersectable(Intersectable *object)
-{
-	switch (object->Type()) 
-	{
-	case Intersectable::MESH_INSTANCE:
-		ExportMeshInstance((MeshInstance *)object);
-		break;
-	case Intersectable::TRANSFORMED_MESH_INSTANCE:
-		ExportTransformedMeshInstance(dynamic_cast<TransformedMeshInstance *>(object));
-		break;
-	case Intersectable::VIEW_CELL:
-		ExportViewCell(dynamic_cast<ViewCell *>(object));
-		break;
-	case Intersectable::KD_INTERSECTABLE:
-		ExportKdIntersectable(*(dynamic_cast<KdIntersectable *>(object)));
-		break;
-	default:
-		cerr << "Sorry the export for object type " << Intersectable::GetTypeName(object) << " is not available yet" << endl;
-		break;
-	}
-}
-
-
-void VrmlExporter::ExportMeshInstance(MeshInstance *object)
-{
-	// $$JB$$
-	// in the future check whether the mesh was not already exported
-	// and use a reference to the that mesh instead
-	ExportMesh(object->GetMesh());
-}
-
-
-void VrmlExporter::ExportTransformedMeshInstance(TransformedMeshInstance *mi)
-{
-	Mesh mesh(*mi->GetMesh());
-
-	Matrix4x4 m;
-	mi->GetWorldTransform(m);
-	mesh.ApplyTransformation(m);
-
-	ExportMesh(&mesh);
-}
-
-
-void VrmlExporter::ExportViewCells(const ViewCellContainer &viewCells)
-{
-	ViewCellContainer::const_iterator it, it_end = viewCells.end();
-
-	for (it = viewCells.begin(); it != it_end; ++ it)
-	{
-		ExportViewCell(*it);
-	}
 }
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.cpp	(revision 1344)
@@ -649,11 +649,11 @@
 /*******************+*****************************************************/
 
-X3dParser::X3dParser():
-mViewCellHeight(DEFAULT_VIEWCELL_HEIGHT) 
+X3dParser::X3dParser(): mViewCellHeight(DEFAULT_VIEWCELL_HEIGHT) 
 {}
+
 
 bool
 X3dParser::ParseFile(const string filename,
-					 SceneGraphNode **root,
+					 SceneGraphNode *root,
 					 const bool loadPolygonsAsMeshes,
 					 vector<FaceParentInfo> *parents)
@@ -689,6 +689,5 @@
   //  to do.
   //
-  *root = new SceneGraphNode;
-  X3dParseHandlers handler(*root, loadPolygonsAsMeshes);
+  X3dParseHandlers handler(root, loadPolygonsAsMeshes);
   parser->setDocumentHandler(&handler);
   parser->setErrorHandler(&handler);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.h	(revision 1221)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsParser.h	(revision 1344)
@@ -17,6 +17,6 @@
   ViewCellsParser():Parser() {}
   
-  //bool ParseFile(const string filename, ViewCellsManager &viewCells);
-  bool ParseViewCellsFile(const string filename, 
+  bool ParseViewCellsFile(
+	  const string filename, 
 	  ViewCellsManager **viewCells,
 	  ObjectContainer *objects,
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h	(revision 1287)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.h	(revision 1344)
@@ -30,4 +30,6 @@
 class KdIntersectable;
 class BvHierarchy;
+class TransformedMeshInstance;
+
 
 class Exporter
@@ -95,9 +97,11 @@
 
   virtual void 
-  ExportViewCells(const ViewCellContainer &viewCells) = 0;
+  ExportViewCells(const ViewCellContainer &viewCells);
+  
   virtual void 
   ExportViewCell(ViewCell *viewCell) = 0;
+
   virtual void
-  ExportIntersectable(Intersectable *object) = 0;
+  ExportIntersectable(Intersectable *object);
 
   virtual void 
@@ -150,4 +154,11 @@
   void ExportKdIntersectable(const KdIntersectable &kdObj);
   bool ExportBvHierarchy(const BvHierarchy &bvHierarchy, const int maxPvs);
+
+  virtual void ExportMeshInstance(MeshInstance *mi);
+
+  virtual void
+  ExportTransformedMeshInstance(TransformedMeshInstance *mi);
+
+  virtual void ExportPolygon(Polygon3 *poly) = 0;
 };
  
Index: GTP/trunk/Lib/Vis/Preprocessing/src/SceneGraph.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/SceneGraph.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/SceneGraph.cpp	(revision 1344)
@@ -31,5 +31,4 @@
 {
 	CLEAR_CONTAINER(mGeometry);
-	
 	// recursivly delete all children
 	CLEAR_CONTAINER(mChildren);
@@ -78,19 +77,18 @@
 		SceneGraphNode *node = nodeStack.top();
 		nodeStack.pop();
-		cout << "here3.958" << endl;cout << "here3.9587654" << endl;
-		ObjectContainer::const_iterator mi = node->mGeometry.begin();	cout << "here3.958" << endl;
+		
+		ObjectContainer::const_iterator mi = node->mGeometry.begin();
 		for (; mi != node->mGeometry.end(); mi++)
 		{
-			cout << "here3.9886" << endl;
 			instances->push_back(*mi);
 		}
-		cout << "here3.969999" << endl;
+	
 		SceneGraphNodeContainer::iterator ni = node->mChildren.begin();
 		for (; ni != node->mChildren.end(); ni++) {
-			nodeStack.push(*ni);	cout << "here3.959" << endl;
+			nodeStack.push(*ni);	
 			number++;
 		}
-		cout << "here3.96" << endl;
 	}
+
 	return number;
 }
@@ -104,5 +102,5 @@
   
   nodeStack.push(mRoot);
-  
+
   while (!nodeStack.empty()) {
     SceneGraphNode *node = nodeStack.top();
@@ -111,12 +109,5 @@
     ObjectContainer::iterator mi = node->mGeometry.begin();
     for (; mi != node->mGeometry.end(); mi++) {
-	  // $$ JB remove object id=2601 (for debugging purposes in atlanta scene)
-	  if (1) //id != 2601)
-		(*mi)->SetId(id++);
-	  else {
-		node->mGeometry.erase(mi);
-		--mi;
-		id++;
-	  }
+	 	(*mi)->SetId(id++);
 	}
     
@@ -126,5 +117,6 @@
     }
   }
-	// return max id
+  
+  // return max id
   return id;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp	(revision 1344)
@@ -162,4 +162,9 @@
 	Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
 	Debug << "load polygons as meshes: " << mLoadPolygonsAsMeshes << endl;
+
+	if (mRayCastMethod == 0)
+		cout << "ray cast method: internal" << endl;
+	else
+		cout << "ray cast method: intel" << endl;
 }
 
@@ -231,4 +236,8 @@
 	cout << "number of input files: " << files << endl;
 	bool result = false;
+
+	// root for different files
+	mSceneGraph->SetRoot(new SceneGraphNode());
+
 	if (files == 1) {
 		
@@ -245,24 +254,21 @@
 		cout << filename << endl;
 
-		SceneGraphNode *sroot = mSceneGraph->GetRoot();
-
 		if (mRayCastMethod == Preprocessor::INTEL_RAYCASTER)
-		{ cout << "here5800" << endl;
+		{ 
 			result = parser->ParseFile(
 				filename, 
-				&sroot,
+				mSceneGraph->GetRoot(),
 				mLoadPolygonsAsMeshes,
 				&mFaceParents);
 		}
 		else
-		{ cout << "here776645" << endl;
-			result = parser->ParseFile(filename, &sroot, mLoadPolygonsAsMeshes);
+		{ 
+			result = parser->ParseFile(filename, mSceneGraph->GetRoot(), mLoadPolygonsAsMeshes);
 		}
-		 cout << "here98809845" << endl;
+		
 		delete parser;
 
 	} else {
-		// root for different files
-		mSceneGraph->SetRoot(new SceneGraphNode());
+		
 		for (int i= 0; i < filenames.size(); i++) {
 		  if (strstr(filenames[i].c_str(), ".x3d"))
@@ -271,12 +277,12 @@
 			parser = new UnigraphicsParser;
 		  
-		  SceneGraphNode *node;
+		  SceneGraphNode *node = new SceneGraphNode();
 		  bool success;
 		  
 		  if (mRayCastMethod == Preprocessor::INTEL_RAYCASTER)
-		  { cout << "here4500" << endl;
+		  { 
 			  success = parser->ParseFile(
 				  filename, 
-				  &node,
+				  node,
 				  mLoadPolygonsAsMeshes,
 				  &mFaceParents);
@@ -284,13 +290,11 @@
 		  else
 		  {
-			  cout << "here45" << endl;
-			  success = parser->ParseFile(filename, &node, mLoadPolygonsAsMeshes);
+			  success = parser->ParseFile(filename, node, mLoadPolygonsAsMeshes);
 		  }
 
 		  if (success) 
-		  { cout << "here4509999" << endl;
+		  { 
 			  mSceneGraph->GetRoot()->mChildren.push_back(node);
-			  // at least one file parsed
-			  result = true;
+			  result = true; // at least one file parsed
 		  }
 		  
@@ -298,8 +302,7 @@
 		}
 	}
-	 cout << "here8888" << endl;
-
+	
 	if (result) 
-	{ cout << "here199" << endl;
+	{ 
 		// HACK 
 		if (ADDITIONAL_GEOMETRY_HACK)
@@ -307,8 +310,8 @@
 
 		mSceneGraph->AssignObjectIds();
- cout << "here99" << endl;
+ 
 		int intersectables, faces;
 		mSceneGraph->GetStatistics(intersectables, faces);
- cout << "here999" << endl;
+ 
 		cout<<filename<<" parsed successfully."<<endl;
 		cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
@@ -316,5 +319,5 @@
 		mSceneGraph->CollectObjects(&mObjects);
 		mSceneGraph->GetRoot()->UpdateBox();
- cout << "here9999" << endl;
+ 
 		if (0)
 		{
@@ -369,14 +372,17 @@
 {
   mKdTree = new KdTree;
+
   // add mesh instances of the scene graph to the root of the tree
   KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
-  	cout << "here3.95" << endl;
+ 	
   mSceneGraph->CollectObjects(&root->mObjects);
-  	cout << "here3.97" << endl;
+  
   long startTime = GetTime();
-
   cout << "building kd tree ... " << endl;
+
   mKdTree->Construct();
+
   cout << "construction finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs " << endl;
+
   return true;
 }
@@ -847,5 +853,5 @@
 	case INTEL_RAYCASTER:
 #ifdef GTP_INTERNAL
-	  cout<<"Ray Cast file: "<<externKdTree<<endl;
+	  cout<<"Ray Cast file: " << externKdTree << endl;
 	  return mlrtaLoadAS(externKdTree.c_str());
 #endif
@@ -868,4 +874,5 @@
 {
 #ifdef GTP_INTERNAL
+	//cout << "intel ray" << endl;
 	VssRay *vssRay  = NULL;
 	int hits = 0;
@@ -875,55 +882,54 @@
 	Intersectable *objectA = NULL, *objectB = NULL;
 	float dist;
-	
 	double normal[3];
 
 	hittriangle = mlrtaIntersectAS(&viewPoint.x,
-								   &direction.x,
-								   normal,
-								   dist);
-
-	if (hittriangle !=-1 ) {
-	  if (hittriangle >= mFaceParents.size())
-		cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
-	  else {
-		objectA = mFaceParents[hittriangle].mObject;
-		normalA = Vector3(normal[0], normal[1], normal[2]);
-		// Get the normal of that face
-		//		Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
-		//		normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
-		//-rays[index+i].mDirection; // $$ temporary
-		pointA = viewPoint + direction*dist;
-	  }
-	}
-
-	
+		&direction.x,
+		normal,
+		dist);
+
+	if (hittriangle != -1 ) {
+		if (hittriangle >= mFaceParents.size())
+			cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
+		else {
+			objectA = mFaceParents[hittriangle].mObject;
+			normalA = Vector3(normal[0], normal[1], normal[2]);
+			// Get the normal of that face
+			//		Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
+			//		normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
+			//-rays[index+i].mDirection; // $$ temporary
+			pointA = viewPoint + direction*dist;
+		}
+	}
+
+
 	Vector3 dir = -direction;
 	hittriangle = mlrtaIntersectAS(&viewPoint.x,
-								   &dir.x,
-								   normal,
-								   dist);
-
-	if (hittriangle !=-1 ) {
-	  if (hittriangle >= mFaceParents.size())
-		cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
-	  else {
-		objectB = mFaceParents[hittriangle].mObject;
-		normalB = Vector3(normal[0], normal[1], normal[2]);
-		// Get the normal of that face
-		//		Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
-		//		normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
-		//-rays[index+i].mDirection; // $$ temporary
-		pointB = viewPoint + dir*dist;
-	}
+		&dir.x,
+		normal,
+		dist);
+
+	if (hittriangle != -1 ) {
+		if (hittriangle >= mFaceParents.size())
+			cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
+		else {
+			objectB = mFaceParents[hittriangle].mObject;
+			normalB = Vector3(normal[0], normal[1], normal[2]);
+			// Get the normal of that face
+			//		Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
+			//		normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
+			//-rays[index+i].mDirection; // $$ temporary
+			pointB = viewPoint + dir * dist;
+		}
 	}
 
 	return ProcessRay(viewPoint,
-					  direction,
-					  objectA, pointA, normalA,
-					  objectB, pointB, normalB,
-					  probability,
-					  vssRays,
-					  box
-					  );
+		direction,
+		objectA, pointA, normalA,
+		objectB, pointB, normalB,
+		probability,
+		vssRays,
+		box
+		);
 #else
 	return -1;
@@ -971,5 +977,5 @@
 	else {
 	  if (hittriangle >= mFaceParents.size()) {
-		cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
+		cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
 		return NULL;
 	  }
@@ -989,6 +995,4 @@
 #endif
 
-	
-	
 }
 
@@ -1002,5 +1006,5 @@
 								  )
 {
-
+  cout << "internal ray" << endl;
   int hits = 0;
   static Ray ray;
@@ -1009,6 +1013,4 @@
 
   //  AxisAlignedBox3 box = Union(mKdTree->GetBox(), mViewCellsManager->GetViewSpaceBox());
-  
-
   AxisAlignedBox3 sbox = box;
   sbox.Enlarge(Vector3(-Limits::Small));
@@ -1042,5 +1044,4 @@
   }
 
-  
   SetupRay(ray, viewPoint, -direction);
   ray.mFlags &= ~Ray::CULL_BACKFACES;
@@ -1076,4 +1077,5 @@
 						  );
 	  vssRays.push_back(vssRay);
+	  //cout << "ray: " << *vssRay << endl;
 	  hits ++;
 	}
@@ -1088,4 +1090,5 @@
 						  );
 	  vssRays.push_back(vssRay);
+	  //cout << "ray: " << *vssRay << endl;
 	  hits ++;
 	}
@@ -1172,4 +1175,5 @@
 						  );
 	  vssRays.push_back(vssRay);
+	  //cout << "ray: " << *vssRay << endl;
 	  hits ++;
 	}
@@ -1184,4 +1188,5 @@
 						  );
 	  vssRays.push_back(vssRay);
+	  //cout << "ray: " << *vssRay << endl;
 	  hits ++;
 	}
@@ -1199,5 +1204,5 @@
 {
   int i;
-  int num = 16;
+  const int num = 16;
 
 #if DEBUG_RAYCAST
@@ -1214,8 +1219,7 @@
 
 
-  
-
   Vector3 min = sbox.Min();
   Vector3 max = sbox.Max();
+  
   for (i=0; i < num; i++) {
 	mlrtaStoreRayAS16(&rays[index + i].mOrigin.x,
@@ -1223,5 +1227,4 @@
 					  i);
   }
-  
   
   mlrtaTraverseGroupAS16(&min.x,
@@ -1237,5 +1240,4 @@
   }
   
-  
   mlrtaTraverseGroupAS16(&min.x,
 						 &max.x,
@@ -1244,5 +1246,4 @@
   
 
-
   for (i=0; i < num; i++) {
 	Intersectable *objectA = NULL, *objectB = NULL;
@@ -1250,33 +1251,28 @@
 	Vector3 normalA, normalB;
 
-
-  
-	if (forward_hit_triangles[i] !=-1 ) {
+	if (forward_hit_triangles[i] != -1 ) {
 	  if (forward_hit_triangles[i] >= mFaceParents.size())
-		cerr<<"Warning: traingle index out of range! "<<forward_hit_triangles[i]<<endl;
-	  else {
+		cerr<<"Warning: triangle index out of range! "<<forward_hit_triangles[i]<<endl;
+	  else { 
 		objectA = mFaceParents[forward_hit_triangles[i]].mObject;
 		// Get the normal of that face
-		Mesh *mesh = ((MeshInstance *)objectA)->GetMesh();
-		normalA = mesh->GetFacePlane(mFaceParents[forward_hit_triangles[i]].mFaceIndex).mNormal;
+		normalA = objectA->GetNormal(mFaceParents[forward_hit_triangles[i]].mFaceIndex);
 		//-rays[index+i].mDirection; // $$ temporary
 		pointA = rays[index+i].Extrap(forward_dist[i]);
 	  }
 	}
-	
+	 
 	if (backward_hit_triangles[i]!=-1) {
 	  if (backward_hit_triangles[i] >= mFaceParents.size())
-		cerr<<"Warning: traingle index out of range! "<<backward_hit_triangles[i]<<endl;
-	  else {
+		cerr<<"Warning: triangle  index out of range! "<<backward_hit_triangles[i]<<endl;
+	  else { 
 		objectB = mFaceParents[backward_hit_triangles[i]].mObject;
-		Mesh *mesh = ((MeshInstance *)objectB)->GetMesh();
-		
-		normalB = mesh->GetFacePlane(mFaceParents[backward_hit_triangles[i]].mFaceIndex).mNormal;
-		
-		//	  normalB = rays[index+i].mDirection; // $$ temporary
+		normalB = objectB->GetNormal(mFaceParents[forward_hit_triangles[i]].mFaceIndex);
+		
+		// normalB = rays[index+i].mDirection; // $$ temporary
 		pointB = rays[index+i].Extrap(-backward_dist[i]);
 	  }
 	}
-
+ 
 	ProcessRay(rays[index+i].mOrigin,
 			   rays[index+i].mDirection,
@@ -1288,4 +1284,5 @@
 			   );
   }
+  
 #endif
   
@@ -1312,6 +1309,9 @@
 {
   long t1 = GetTime();
-  for (int i=0; i < rays.size(); ) {
-	if (i + 16 < rays.size()) {
+  
+  for (int i = 0; i < (int)rays.size(); ) {
+	  // method only available for intel raycaster yet
+	if (i + 16 < (int)rays.size()) {
+
 	  CastRays16(
 				 i,
@@ -1321,5 +1321,4 @@
 	  i += 16;
 	} else {
-
 	  CastRay(rays[i].mOrigin,
 			  rays[i].mDirection,
@@ -1327,5 +1326,4 @@
 			  vssRays,
 			  mViewCellsManager->GetViewSpaceBox());
-
 	  i++;
 	}
@@ -1335,5 +1333,4 @@
 
   long t2 = GetTime();
-  
   cout<<2*rays.size()/(1e3*TimeDiff(t1, t2))<<"M rays/s"<<endl;
 }
@@ -1354,5 +1351,4 @@
 	 
 	  int hittriangle;
-	  
 
 #ifdef GTP_INTERNAL
@@ -1367,5 +1363,5 @@
 	   if (hittriangle !=-1 ) {
 		if (hittriangle >= mFaceParents.size())
-		  cerr<<"Warning: traingle index out of range! "<<hittriangle<<endl;
+		  cerr<<"Warning: triangle index out of range! "<<hittriangle<<endl;
 		else {
 		  result = mFaceParents[hittriangle].mObject;
@@ -1375,8 +1371,7 @@
 	  }
 #else
-	hittriangle = -1;
+	  hittriangle = -1;
 #endif
 
-	 
 	  break;
 	}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.h	(revision 1221)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.h	(revision 1344)
@@ -81,20 +81,8 @@
 
   virtual void
-  ExportMeshInstance(MeshInstance *mi);
-
-  virtual void
-  ExportTransformedMeshInstance(TransformedMeshInstance *mi);
-
-  virtual void
-  ExportIntersectable(Intersectable *object);
-
-  virtual void
   ExportMesh(Mesh *mesh);
 
   virtual void
   ExportViewCell(ViewCell *viewCell);
-
-  virtual void
-  ExportViewCells(const ViewCellContainer &viewCells);
 
   virtual void
@@ -105,4 +93,5 @@
 			 const float length=1000,
 			 const RgbColor &color = RgbColor(1,1,1));
+
   bool
   ExportRays(const VssRayContainer &rays,
@@ -121,5 +110,4 @@
   ExportBspLeaves(const BspTree &tree, const int maxPvs = 0);
 
-
   virtual void
   ExportBspSplits(const VspBspTree &tree, const bool exportDepth);
@@ -132,5 +120,4 @@
 
 protected:
-
 
   virtual void
Index: GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.h	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.h	(revision 1344)
@@ -15,5 +15,5 @@
   
   bool ParseFile(const string filename,
-				 SceneGraphNode **root,
+				 SceneGraphNode *root,
 				 const bool loadPolygonsAsMeshes = false,
 				 vector<FaceParentInfo> *parents = NULL);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp	(revision 1233)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dExporter.cpp	(revision 1344)
@@ -200,56 +200,4 @@
 
 }
-void
-X3dExporter::ExportIntersectable(Intersectable *object)
-{
-	switch (object->Type()) 
-	{
-	case Intersectable::MESH_INSTANCE:
-		ExportMeshInstance((MeshInstance *)object);
-		break;
-	case Intersectable::TRANSFORMED_MESH_INSTANCE:
-		ExportTransformedMeshInstance(dynamic_cast<TransformedMeshInstance *>(object));
-		break;
-	case Intersectable::VIEW_CELL:
-		ExportViewCell((ViewCell *)object);
-		break;
-	default:
-		cerr << "Sorry the export for object not yet defined" << endl;
-		break;
-	}
-}
-
-
-void
-X3dExporter::ExportMeshInstance(MeshInstance *object)
-{
-  // $$JB$$
-  // in the future check whether the mesh was not already exported
-  // and use a reference to the that mesh instead
-  ExportMesh(object->GetMesh());
-}
-
-
-void
-X3dExporter::ExportTransformedMeshInstance(TransformedMeshInstance *mi)
-{
-	Mesh mesh(*mi->GetMesh());
-
-	Matrix4x4 m;
-	mi->GetWorldTransform(m);
-	mesh.ApplyTransformation(m);
-
-	ExportMesh(&mesh);
-}
-
-
-void 
-X3dExporter::ExportViewCells(const ViewCellContainer &viewCells)
-{
-	ViewCellContainer::const_iterator it, it_end = viewCells.end();
-
-	for (it = viewCells.begin(); it != it_end; ++ it)
-		ExportViewCell(*it);
-}
 
 
@@ -303,8 +251,6 @@
 				mForcedMaterial.mDiffuseColor.g = 1.0f - mForcedMaterial.mDiffuseColor.r;
 			}
-
 			ExportPolygons(cell->GetPolys());
-		}
-		
+		}		
 		DEL_PTR(cell);
 	}
@@ -315,5 +261,7 @@
 {
 	if (viewCell->GetMesh())
+	{
 		ExportMesh(viewCell->GetMesh());
+	}
 }
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.h	(revision 1344)
@@ -30,11 +30,32 @@
 
 	/// Casts ray into this triangle. Returns hit
-	int CastRay(const Ray &ray, float &t, const float nearestT) const;
+	int CastRay(const Ray &ray, float &t, const float nearestT, Vector3 &normal) const;
 
-	//////////////////////////////
+	 friend ostream& operator<< (ostream &s, const Triangle3 &A);
+	 friend istream& operator>> (istream &s, Triangle3 &A);
 
-	/// the triangle vertices
-	Vector3 mVertices[3];
+
+	 //////////////////////////////
+	 /// the triangle vertices
+	 Vector3 mVertices[3];
 };
+
+
+// Overload << operator for C++-style output
+inline ostream&
+operator<< (ostream &s, const Triangle3 &A)
+{
+  return s << "(" << A.mVertices[0] << ", " << A.mVertices[1] << ", " << A.mVertices[2] << ")";
+}
+
+// Overload >> operator for C++-style input
+inline istream&
+operator>> (istream &s, Triangle3 &A)
+{
+  char a;
+  // read "(x, y, z)"
+  return s >> a >> A.mVertices[0] >> a >> A.mVertices[1] >> a >> A.mVertices[2] >> a;
+}
+
 
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 1323)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp	(revision 1344)
@@ -1085,5 +1085,4 @@
 {
 	VssRay::NewMail();
-	
 	ObjectContainer::const_iterator oit, oit_end = objects.end();
 
@@ -1093,5 +1092,4 @@
 	{
 		Intersectable *obj = *oit;
-		
 		VssRayContainer::const_iterator rit, rit_end = obj->mVssRays.end();
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Containers.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Containers.h	(revision 1184)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Containers.h	(revision 1344)
@@ -18,4 +18,5 @@
 class Mesh;
 class KdLeaf;
+class Vector3;
 
 struct IndexedBoundingBox;
@@ -32,15 +33,16 @@
 
 /** Container for Mesh pointers primarily for the use within the kDTree and
-    BSP hierarchies */
+    BSP hierarchies 
+*/
 typedef vector<Intersectable *> ObjectContainer;
 
 /** Container for ViewCell pointers primarily for the use within the kDTree and
-    BSP hierarchies */
-
+    BSP hierarchies 
+*/
 typedef vector<ViewCell *> ViewCellContainer;
 
 /** Container for HierarchyNodes pointers primarily for the use within the kDTree and
     BSP hierarchies 
-	*/
+*/
 typedef vector<HierarchyNode *> NodeContainer;
 
@@ -57,10 +59,16 @@
 
 /** Container for ViewCell pointers primarily for the use within the kDTree and
-    BSP hierarchies */
-
+    BSP hierarchies 
+*/
 typedef vector<KdLeaf *> KdLeafContainer;
 
+typedef std::map<int, Intersectable *> ObjectMap;
 
-typedef std::map<int, Intersectable *> ObjectMap;
+/// default vertex container for Mesh
+typedef std::vector<Vector3> VertexContainer;
+
+/// vertex index container
+//typedef std::vector<short> VertexIndexContainer;
+typedef std::vector<int> VertexIndexContainer;
 
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp	(revision 1344)
@@ -10,13 +10,15 @@
 
 Polygon3::Polygon3(): 
-mMaterial(NULL), mParent(NULL), mPiercingRays(0)
+mMaterial(NULL), 
+mParent(NULL), 
+mPiercingRays(0)
 , mPlane(NULL)
 {
-	// mostly there will be triangles
-	//mVertices.reserve(3);
 }
 
 Polygon3::Polygon3(const VertexContainer &vertices): 
-mMaterial(NULL), mParent(NULL), mPiercingRays(0)
+mMaterial(NULL), 
+mParent(NULL), 
+mPiercingRays(0)
 , mPlane(NULL)
 {
@@ -27,5 +29,7 @@
 
 Polygon3::Polygon3(MeshInstance *parent): 
-mMaterial(NULL), mParent(parent), mPiercingRays(0)
+mMaterial(NULL), 
+mParent(parent), 
+mPiercingRays(0)
 , mPlane(NULL)
 {}
@@ -33,11 +37,14 @@
 
 Polygon3::Polygon3(Face *face, Mesh *parentMesh):
-mMaterial(NULL), mParent(NULL), mPiercingRays(0)
-, mPlane(NULL)
+mMaterial(NULL), 
+mParent(NULL), 
+mPiercingRays(0), 
+mPlane(NULL)
 {	
 	mVertices.reserve(face->mVertexIndices.size());
 	
-	VertexIndexContainer::iterator it = face->mVertexIndices.begin();
-	for (; it != face->mVertexIndices.end();  ++it)
+	VertexIndexContainer::iterator it, it_end = face->mVertexIndices.end();
+
+	for (it = face->mVertexIndices.begin(); it != it_end;  ++ it)
 	{
 		mVertices.push_back(parentMesh->mVertices[*it]);
@@ -54,5 +61,8 @@
 #else
 	if (!mPlane)
+	{
 		mPlane = new Plane3(mVertices[0], mVertices[1], mVertices[2]);
+	}
+
 	return *mPlane;
 #endif
@@ -65,4 +75,5 @@
 							   mVertices[0] - mVertices[1]));
 }
+
 
 void Polygon3::Split(const Plane3 &partition, 
@@ -72,15 +83,13 @@
 {
 	Vector3 ptA = mVertices.back();
-	
 	int sideA = partition.Side(ptA, epsilon);
-	
-	VertexContainer::const_iterator it;
-	
-	Vector3 lastSplit;
-
 	bool foundSplit = false;
-
+    Vector3 lastSplit;
+		
 	//-- find line - plane intersections
-	for (it = mVertices.begin(); it != mVertices.end(); ++ it)
+
+	VertexContainer::const_iterator it, it_end = mVertices.end();
+
+	for (it = mVertices.begin(); it != it_end; ++ it)
 	{
 		Vector3 ptB = *it;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.h	(revision 1197)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/VrmlExporter.h	(revision 1344)
@@ -84,20 +84,8 @@
 
   virtual void
-  ExportMeshInstance(MeshInstance *mi);
-
-  virtual void
-  ExportTransformedMeshInstance(TransformedMeshInstance *mi);
-
-  virtual void
-  ExportIntersectable(Intersectable *object);
-
-  virtual void
   ExportMesh(Mesh *mesh);
 
   virtual void
   ExportViewCell(ViewCell *viewCell);
-
-  virtual void
-  ExportViewCells(const ViewCellContainer &viewCells);
 
   virtual void
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1315)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp	(revision 1344)
@@ -276,14 +276,11 @@
 {
 	SimpleRayContainer simpleRays;
-
 	const long startTime = GetTime();
 
 	mPreprocessor->GenerateRays(samplesPerPass, sampleType, simpleRays);
-
 	Debug << "generated " <<  mInitialSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
 
 	// shoot simple ray and add it to importance samples
 	mPreprocessor->CastRays(simpleRays, passSamples);
-
 	Debug << "cast " <<  mInitialSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
 
@@ -5359,17 +5356,16 @@
 
 
+	//////////////////////////////////////////////////////////////
 	//-- export bounding boxes
 
 	stream << "<BoundingBoxes>" << endl;
-
 	ObjectContainer::const_iterator oit, oit_end = objects.end();
 
 	for (oit = objects.begin(); oit != oit_end; ++ oit)
 	{
-			MeshInstance *mi = dynamic_cast<MeshInstance *>(*oit);
-			const AxisAlignedBox3 box = mi->GetBox();
+			const AxisAlignedBox3 box = (*oit)->GetBox();
 
 			//-- the bounding boxes
-			stream << "<BoundingBox" << " id=\"" << mi->GetId() << "\""
+			stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
 				   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
 				   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
@@ -5378,5 +5374,5 @@
 	stream << "</BoundingBoxes>" << endl;
 
-
+	////////////////////////////////////////////////////////////////
 	//-- export the view cells and the pvs
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 1315)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Exporter.cpp	(revision 1344)
@@ -5,4 +5,6 @@
 #include "IntersectableWrapper.h"
 #include "BvHierarchy.h"
+#include "Triangle3.h"
+#include "Polygon3.h"
 
 
@@ -152,3 +154,71 @@
 
 
-}
+void Exporter::ExportIntersectable(Intersectable *object)
+{
+	switch (object->Type()) 
+	{
+	case Intersectable::MESH_INSTANCE:
+		ExportMeshInstance((MeshInstance *)object);
+		break;
+	case Intersectable::TRANSFORMED_MESH_INSTANCE:
+		ExportTransformedMeshInstance(dynamic_cast<TransformedMeshInstance *>(object));
+		break;
+	case Intersectable::VIEW_CELL:
+		ExportViewCell(dynamic_cast<ViewCell *>(object));
+		break;
+	case Intersectable::KD_INTERSECTABLE:
+		ExportKdIntersectable(*(dynamic_cast<KdIntersectable *>(object)));
+		break;
+	case Intersectable::TRIANGLE_INTERSECTABLE:
+		{
+			const Triangle3 triangle = dynamic_cast<TriangleIntersectable *>(object)->GetItem();
+
+			VertexContainer vertices;
+			vertices.push_back(triangle.mVertices[0]);
+			vertices.push_back(triangle.mVertices[1]);
+			vertices.push_back(triangle.mVertices[2]);
+
+			Polygon3 poly(vertices);
+			ExportPolygon(&poly);
+			break;
+		}
+	default:
+		cerr << "Sorry the export for object type " << Intersectable::GetTypeName(object) << " is not available yet" << endl;
+		break;
+	}
+}
+
+void Exporter::ExportMeshInstance(MeshInstance *object)
+{
+	// $$JB$$
+	// in the future check whether the mesh was not already exported
+	// and use a reference to the that mesh instead
+	ExportMesh(object->GetMesh());
+}
+
+
+void Exporter::ExportTransformedMeshInstance(TransformedMeshInstance *mi)
+{
+	Mesh mesh(*mi->GetMesh());
+
+	Matrix4x4 m;
+	mi->GetWorldTransform(m);
+	mesh.ApplyTransformation(m);
+
+	ExportMesh(&mesh);
+}
+
+
+void Exporter::ExportViewCells(const ViewCellContainer &viewCells)
+{
+	ViewCellContainer::const_iterator it, it_end = viewCells.end();
+
+	for (it = viewCells.begin(); it != it_end; ++ it)
+	{
+		ExportViewCell(*it);
+	}
+}
+
+
+
+}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.cpp	(revision 1344)
@@ -9,10 +9,35 @@
 AxisAlignedBox3 TriangleIntersectable::GetBox() const
 {	
-	return mItem->GetBoundingBox();
+	return mItem.GetBoundingBox();
 }
 
 
 int TriangleIntersectable::CastRay(Ray &ray)
-{	// TODO matt
+{	
+	float nearestT = MAX_FLOAT;
+	float t;
+	Vector3 nearestNormal;
+
+	if (ray.GetType() == Ray::LOCAL_RAY && !ray.intersections.empty())
+		nearestT = ray.intersections[0].mT;
+
+	const int hitCode = mItem.CastRay(ray, t, nearestT, nearestNormal);
+
+	nearestT = t;
+
+	if ((hitCode == Ray::INTERSECTION) && (ray.GetType() == Ray::LOCAL_RAY))
+	{
+		if (!ray.intersections.empty())
+		{
+			ray.intersections[0] = Ray::Intersection(nearestT, nearestNormal, this, 0);
+		}
+		else
+		{
+			ray.intersections.push_back(Ray::Intersection(nearestT, nearestNormal, this, 0));
+		}
+		
+		return 1;
+	}
+
 	return 0;
 }
@@ -23,5 +48,11 @@
 	return 1;
 }
-  
 
+
+Vector3 TriangleIntersectable::GetNormal(const int idx) const
+{
+	return mItem.GetNormal();
 }
+
+ 
+}
Index: GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/UnigraphicsParser.cpp	(revision 1344)
@@ -43,5 +43,5 @@
 bool
 UnigraphicsParser::ParseFile(const string filename,
-							 SceneGraphNode **proot,
+							 SceneGraphNode *root,
 							 const bool loadPolygonsAsMeshes,
 							 vector<FaceParentInfo> *parents)
@@ -61,5 +61,4 @@
     return false;
 
-  SceneGraphNode *root = new SceneGraphNode;
   Mesh *currentMesh = MeshManager::GetSingleton()->CreateResource();
 
@@ -186,7 +185,4 @@
   
   fclose(file);
-  
-  *proot = root;
-
   return true;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Parser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Parser.h	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Parser.h	(revision 1344)
@@ -18,6 +18,6 @@
   Parser() {}
 
-  virtual bool ParseFile(const std::string filename, 
-						 SceneGraphNode **root, 
+  virtual bool ParseFile(const std::string filename,
+						 SceneGraphNode *root,
 						 const bool loadPolygonsAsMeshes = false,
 						 std::vector<FaceParentInfo> *parents = NULL) 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.h	(revision 1344)
@@ -20,12 +20,7 @@
 class MeshKdTree;
 
-/// default vertex container for Mesh
-typedef std::vector<Vector3> VertexContainer;
-
-/// vertex index container
-//typedef std::vector<short> VertexIndexContainer;
-typedef std::vector<int> VertexIndexContainer;
-
-/** Patch used as an element of the mesh */
+
+/** Patch used as an element of the mesh 
+*/
 struct Face {
 
@@ -284,4 +279,6 @@
 	Material *GetMaterial() const;
 
+	virtual Vector3 GetNormal(const int idx) const;
+
 protected:
 
@@ -329,4 +326,6 @@
   void GetTransformedMesh(Mesh &transformedMesh) const;
 
+  Vector3 GetNormal(const int idx) const;
+
 protected:
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 1286)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/KdTree.cpp	(revision 1344)
@@ -654,10 +654,9 @@
 
 		  if (MeshDebug) {
-			if (ray.intersections.size()) 
+			if (!ray.intersections.empty()) 
 			cout<<"nearest t="<<ray.intersections[0].mT<<endl;
 		  else
 			cout<<"nearest t=-INF"<<endl;
-		  }
-		  
+		  }	  
 		}
 	  }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Triangle3.cpp	(revision 1344)
@@ -2,4 +2,6 @@
 #include "Ray.h"
 #include "AxisAlignedBox3.h"
+#include "Containers.h"
+#include "Polygon3.h"
 
 
@@ -18,5 +20,4 @@
 	mVertices[1] = b;
 	mVertices[2] = c;
-
 }
 
@@ -28,19 +29,36 @@
 
 
-int Triangle3::CastRay(const Ray &ray, float &t, const float nearestT) const
+int Triangle3::CastRay(const Ray &ray, float &t, const float nearestT, Vector3 &normal) const
 {
+	/*VertexContainer vertices;
+	vertices.push_back(mVertices[0]);
+	vertices.push_back(mVertices[1]);
+	vertices.push_back(mVertices[2]);
+
+	Polygon3 poly(vertices);
+	
+	int dummy = poly.CastRay(ray, t, nearestT);
+
+	 cout << "polyversion code: " << dummy << " t: " << t << " nearestT: " << nearestT << endl;
+return dummy;*/
+	/////////////////////////////////////////////
+	// specialised ray casting version
+
+	//-- calc ray-plane intersection
+	
 	// get triangle edge vectors and plane normal
-	const Vector3 u = mVertices[1] - mVertices[0];
-    const Vector3 v = mVertices[2] - mVertices[0];
+	const Vector3 u = mVertices[0] - mVertices[1];
+    const Vector3 v = mVertices[2] - mVertices[1];
 
-    const Vector3 n = u * v;  // cross product
+    normal = Normalize(CrossProd(v, u)); // cross product
 
-    const Vector3 dir = ray.GetDir();           // ray direction vector
-    const Vector3 w0 = ray.GetLoc() - mVertices[0];
+    const Vector3 dir = ray.GetDir(); // ray direction vector
+    const Vector3 w0 = ray.GetLoc() - mVertices[1];
 
 	// params to calc ray-plane intersect
-    const float a = - DotProd(n, w0);
-    const float b = DotProd(n, dir);
+    const float a = -DotProd(normal, w0);
+    const float b = DotProd(normal, dir);
 
+	// check for division by zero
 	if (fabs(b) < Limits::Small) 
 	{   
@@ -56,22 +74,24 @@
     }
 
-    // get intersect point of ray with triangle plane
+    // distance from origin of ray to plane
     t = a / b;
 
     if (t < 0.0) // ray goes away from triangle
 	{
-        return Ray::NO_INTERSECTION; // => no intersect
+		return Ray::NO_INTERSECTION; // => no intersect
+	}
+	// already found nearer intersection
+	else if ((ray.GetType() == Ray::LOCAL_RAY) && (t >= nearestT))
+	{
+		return Ray::NO_INTERSECTION;
 	}
 
-    // for a segment, also test if (r > 1.0) => no intersect
+	///////////////////////////////////////////////
+    //-- found intersection point
+	//-- check if it is inside triangle
+  
+	const Vector3 pt = ray.GetLoc() + t * dir; 
 
-	// intersect point of ray and plane
-    const Vector3 pt = ray.GetLoc() + t * dir; 
-
-
-	///////////////////////////////////////////////
-    //-- is point inside triangle?
-   
-	const Vector3 w = pt - mVertices[0];
+	const Vector3 w = pt - mVertices[1];
 
 	const float uu = DotProd(u, u);
@@ -86,6 +106,6 @@
     const float s = (uv * wv - vv * wu) / D;
 
-    if (s < 0.0 || s > 1.0) // pt is outside triangle
-	{
+    if ((s < 0.0) || (s > 1.0)) // pt is outside triangle
+	{	
         return Ray::NO_INTERSECTION;
 	}
@@ -93,6 +113,6 @@
 	const float s2 = (uv * wu - uu * wv) / D;
 
-    if (s2 < 0.0 || (s + s2) > 1.0) // pt is outside triangle
-	{
+    if ((s2 < 0.0) || ((s + s2) > 1.0)) // pt is outside triangle
+	{	
         return Ray::NO_INTERSECTION;
 	}
@@ -118,5 +138,5 @@
 {
 	const Vector3 v1 = mVertices[0] - mVertices[1];
-	const Vector3 v2 = mVertices[2]-mVertices[1];
+	const Vector3 v2 = mVertices[2] - mVertices[1];
 
 	return Normalize(CrossProd(v2, v1));
@@ -132,5 +152,5 @@
 float Triangle3::GetArea() const 
 {
-	Vector3 v1=mVertices[0]-mVertices[1], v2=mVertices[2]-mVertices[1];
+	Vector3 v1 = mVertices[0] - mVertices[1], v2=mVertices[2] - mVertices[1];
 	return 0.5f * Magnitude(CrossProd(v2, v1));
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.h	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.h	(revision 1344)
@@ -16,5 +16,5 @@
   
   virtual bool ParseFile(const std::string filename, 
-						 SceneGraphNode **root, 
+						 SceneGraphNode *root,
 						 const bool loadPolygonsAsMeshes = false,
 						 vector<FaceParentInfo> *parents = NULL);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/main.cpp	(revision 1344)
@@ -214,9 +214,9 @@
 		exit(1);
 	}
-	cout << "here3.9" << endl;
+
 	//-- build kd tree from scene geometry
 	preprocessor->BuildKdTree();
 	preprocessor->KdTreeStatistics(cout);
-	cout << "here3" << endl;
+
 	/*preprocessor->mKdTree->ExportBinTree("kd.bin.gz");
 	MeshManager::GetSingleton()->ExportEntries("meshes.bin");
@@ -242,5 +242,5 @@
 
 	DEL_PTR(kdTree2);
-*/cout << "here4" << endl;
+*/
 	// parse view cells related options
 	preprocessor->PrepareViewCells();
@@ -251,5 +251,5 @@
 		preprocessor->Export(filename + "-kdtree.x3d", false, true, false);	
 	}
-cout << "here5" << endl;
+
 	// create a preprocessor thread (note: capsulates calls to boost fuctions!)
 	//PreprocessorThread *pt = PreprocessorThreadFactory::Create(preprocessor);
@@ -260,5 +260,5 @@
 	bool guiSupported = false;
 	if (preprocessor->mUseGlRenderer || preprocessor->mUseGlDebugger)
-	  {
+	{
 		cout << "using gl widget" << endl;
 		// create and run the preprocessor application in a parallel thread
@@ -267,18 +267,18 @@
 #endif
 		//pt.RunThread();
-		
+
 		// display the render widget
-		if (!rendererWidget) {
-
+		if (!rendererWidget) 
+		{
 #if !USE_QT
-		  guiSupported = LoadMyDll();
+			guiSupported = LoadMyDll();
 #else
-		  rendererWidget = new QtGlRendererWidget(preprocessor->mSceneGraph,
-												  preprocessor->mViewCellsManager,
-												  preprocessor->mKdTree);
+			rendererWidget = new QtGlRendererWidget(preprocessor->mSceneGraph,
+				preprocessor->mViewCellsManager,
+				preprocessor->mKdTree);
 #endif
 		}
-		
-	  }
+
+	}
 	
 	if (!guiSupported) {
Index: GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/ObjParser.cpp	(revision 1344)
@@ -19,5 +19,5 @@
 namespace GtpVisibilityPreprocessor {
 
-#define CONNECT_SEQUENTIAL_FACES 1
+#define CONNECT_SEQUENTIAL_FACES 0
 #define ROTATE_SCENE 0
 
@@ -36,4 +36,5 @@
 }
 
+
 struct ltstr
 {
@@ -43,6 +44,4 @@
 	}
 };
-
-//const static int nMaxFaces = 6;
 
 
@@ -71,7 +70,7 @@
 
 
-static Triangle3 *LoadTriangle(char *str, 
-							   const VertexContainer &vertices, 
-							   map<int, Vector3> &hashTable)
+static Triangle3 LoadTriangle(char *str, 
+							  const VertexContainer &vertices, 
+							  map<int, Vector3> &hashTable)
 {
 	char *pch = strtok(str + 1, " ");
@@ -92,5 +91,5 @@
 	//if (indices.size() > 4) return NULL;
 
-	return new Triangle3(indices[0], indices[1], indices[2]); 
+    return Triangle3(vertices[indices[0]], vertices[indices[1]], vertices[indices[2]]); 
 }
 
@@ -143,11 +142,11 @@
 									   vector<FaceParentInfo> &parents)
 {
-  Mesh *mesh = mi->GetMesh();
-  
-  FaceContainer::const_iterator fit, fit_end = mesh->mFaces.end();
-  int i = 0;
-  for (fit = mesh->mFaces.begin(); fit != fit_end; ++ fit, i++)
-	{
-	  parents.push_back(FaceParentInfo(mi, i));
+	Mesh *mesh = mi->GetMesh();
+
+	FaceContainer::const_iterator fit, fit_end = mesh->mFaces.end();
+	int i = 0;
+	for (fit = mesh->mFaces.begin(); fit != fit_end; ++ fit, i++)
+	{
+		parents.push_back(FaceParentInfo(mi, i));
 	}
 }
@@ -160,5 +159,4 @@
 {
 	Mesh *mesh = CreateMesh(faces, hashTable);
-
 	// make an instance of this mesh
 	MeshInstance *mi = new MeshInstance(mesh);
@@ -178,5 +176,5 @@
 
 bool ObjParser::ParseFile(const string filename,
-						  SceneGraphNode **proot,
+						  SceneGraphNode *root,
 						  const bool loadPolygonsAsMeshes,
 						  vector<FaceParentInfo> *parents)
@@ -184,12 +182,11 @@
 	FILE *file;
 	if ((file = fopen(filename.c_str(), "rt")) == NULL)
+	{	
 		return false;
-	cout << "here2" << endl;
+	}
+
 	map<int, Vector3> hashTable; // table associating indices with vectors
-	
 	VertexContainer vertices; // table for vertices
 	FaceContainer faces;
-
-	SceneGraphNode *root = new SceneGraphNode;
 
 	char str[100];
@@ -203,9 +200,7 @@
 		switch (str[0]) 
 		{
-		case 'v':
+		case 'v': // vertex 
 			{
-				float x,y,z; //cout << "v";
-				
-				// vertex 
+				float x, y, z; //cout << "v";	
 				sscanf(str + 1, "%f %f %f", &x, &y, &z);
 				vertices.push_back(Vector3(x,y,z));
@@ -219,5 +214,5 @@
 				Face *face = LoadFace(str, vertices, hashTable);
 				if (!face) break;
-
+	
 				faces.push_back(face);
 
@@ -227,7 +222,16 @@
 				}
 #else
+				Triangle3 triangle = LoadTriangle(str, vertices, hashTable);
 				
-				Triangle3 *triangle = LoadTriangle(str, vertices, hashTable);
-				root->mGeometry.push_back(new TriangleIntersectable(triangle));
+				TriangleIntersectable *obj = new TriangleIntersectable(triangle);
+				root->mGeometry.push_back(obj);
+
+				// matt: we don't really need to keep an additional data structure
+				// if working with triangles => remove this
+				if (parents) 
+				{
+					FaceParentInfo info(obj, 0);
+					parents->push_back(info);
+				}
 #endif
 				break;
@@ -245,8 +249,9 @@
 	}
 #endif
-
+	// reset tables
+	hashTable.clear();
+	faces.clear();
 	fclose(file);
-	*proot = root;
-
+	
 	return true;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Intersectable.h	(revision 1344)
@@ -16,16 +16,16 @@
 struct Face;
 
+
 struct FaceParentInfo {
-  // intersectable
-  Intersectable *mObject;
-  // face index
-  int mFaceIndex;
-  
-  FaceParentInfo(Intersectable *obj,
-				 const int fi):
-	mObject(obj),
-	mFaceIndex(fi)
-  {}
+	/// intersectable
+	Intersectable *mObject;
+	/// face index
+	int mFaceIndex;
+
+	FaceParentInfo(Intersectable *obj, const int fi):
+	mObject(obj), mFaceIndex(fi)
+	{}
 };
+
 
 class Intersectable {
@@ -147,4 +147,9 @@
 		}
 	}
+
+	/** returns normal from the face with the specified index.
+		PROBLEM: Does not fit to all intersectable types (e.g., spheres)
+	*/
+	virtual Vector3 GetNormal(const int idx) const { return Vector3(0, 0, 0); }
 };
 
Index: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1329)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp	(revision 1344)
@@ -450,5 +450,5 @@
 		return mOspTree && mOspTree->GetRoot();
 	case BV_BASED_OBJ_SUBDIV:
-		return mBvHierarchy && mOspTree->GetRoot();
+		return mBvHierarchy && mBvHierarchy->GetRoot();
 	default:
         return false;
Index: GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.h	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/X3dParser.h	(revision 1344)
@@ -17,5 +17,5 @@
 	bool ParseFile(
 				   const string filename, 
-				   SceneGraphNode **root, 
+				   SceneGraphNode *root, 
 				   const bool loadPolygonsAsMeshes = false,
 				   vector<FaceParentInfo> *parents = NULL);
Index: GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp	(revision 1281)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/PlyParser.cpp	(revision 1344)
@@ -259,5 +259,5 @@
 bool
 PlyParser::ParseFile(const string filename,
-					 SceneGraphNode **root,
+					 SceneGraphNode *root,
 					 const bool loadPolygonsAsMeshes,
 					 vector<FaceParentInfo> *parents)
@@ -283,12 +283,11 @@
 	filelist.push_back(filename);
 
-  *root = new SceneGraphNode;
-
   for (int i=0; i < filelist.size(); i++) {
-	if (!ParseSingleFile(filelist[i], *root)) {
+	if (!ParseSingleFile(filelist[i], root)) {
 	  cerr<<"Ply parse error. Quiting ...\n";
 	  exit(1);
 	}
   }
+
   return true;
 }
Index: GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/IntersectableWrapper.h	(revision 1344)
@@ -4,7 +4,9 @@
 #include "AxisAlignedBox3.h"
 #include "Intersectable.h"
+#include "Triangle3.h"
 
 
 namespace GtpVisibilityPreprocessor {
+
 
 struct VssRayContainer;
@@ -24,14 +26,16 @@
 {
 public:
-	IntersectableWrapper(T *item);
+	IntersectableWrapper(T item);
 
 	/** Returns node associated with this instance. 
 	*/
-	T *GetItem() const;
+	T GetItem() const;
 
 	/** See get.
 	*/
-	void SetItem(T *item);
+	void SetItem(T item);
 
+
+	/////////////////////////////////////////////
 	//-- inherited functions from Intersectable
 
@@ -45,6 +49,5 @@
   
 	int NumberOfFaces() const;
-	//int Type() const;
-
+	
 	int GetRandomSurfacePoint(GtpVisibilityPreprocessor::Vector3 &point, 
 							  GtpVisibilityPreprocessor::Vector3 &normal);
@@ -60,10 +63,10 @@
 protected:
 	
-	T *mItem;
+	T mItem;
 };
 
 
 template<typename T>
-IntersectableWrapper<T>::IntersectableWrapper(T *item):
+IntersectableWrapper<T>::IntersectableWrapper(T item):
 Intersectable(), mItem(item)
 {
@@ -71,5 +74,5 @@
 
 template<typename T>
-void IntersectableWrapper<T>::SetItem(T *item)
+void IntersectableWrapper<T>::SetItem(T item)
 {
 	mItem = item;
@@ -77,5 +80,5 @@
 
 template<typename T>
-T *IntersectableWrapper<T>::GetItem() const
+T IntersectableWrapper<T>::GetItem() const
 { 
 	return mItem; 
@@ -120,5 +123,5 @@
 template<typename T>
 int IntersectableWrapper<T>::GetRandomSurfacePoint(Vector3 &point,
-												Vector3 &normal)
+												   Vector3 &normal)
 {
 	return 0;
@@ -127,7 +130,7 @@
 template<typename T>
 int IntersectableWrapper<T>::GetRandomVisibleSurfacePoint(Vector3 &point,
-													   Vector3 &normal,
-													   const Vector3 &viewpoint,
-													   const int maxTries)
+														  Vector3 &normal,
+														  const Vector3 &viewpoint,
+														  const int maxTries)
 {
 	return 0;
@@ -142,9 +145,9 @@
 
 
-class KdIntersectable: public IntersectableWrapper<KdNode>
+class KdIntersectable: public IntersectableWrapper<KdNode *>
 {
 public:
 	KdIntersectable(KdNode *item):
-	IntersectableWrapper<KdNode>(item) {}
+	IntersectableWrapper<KdNode *>(item) {}
 
 	int Type() const
@@ -155,9 +158,9 @@
 
 
-class BvhIntersectable: public IntersectableWrapper<BvhNode>
+class BvhIntersectable: public IntersectableWrapper<BvhNode *>
 {
 public:
 	BvhIntersectable(BvhNode *item):
-	IntersectableWrapper<BvhNode>(item) {}
+	IntersectableWrapper<BvhNode *>(item) {}
 
 	int Type() const
@@ -167,14 +170,15 @@
 };
 
+
 class TriangleIntersectable: public IntersectableWrapper<Triangle3>
 {
 public:
-	TriangleIntersectable(Triangle3 *item):
+	TriangleIntersectable(Triangle3 item):
 	IntersectableWrapper<Triangle3>(item) {}
 
 	int CastRay(Ray &ray);
 	AxisAlignedBox3 GetBox() const;
-
 	int NumberOfFaces() const;
+	Vector3 GetNormal(const int idx) const;
 
 	int Type() const
Index: GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp
===================================================================
--- GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp	(revision 1328)
+++ GTP/trunk/Lib/Vis/Preprocessing/src/Mesh.cpp	(revision 1344)
@@ -726,7 +726,15 @@
 
 
+Vector3 MeshInstance::GetNormal(const int idx) const
+{
+	return mMesh->GetFacePlane(idx).mNormal;
+}
+
+
+
 /*************************************************************/
 /*           TransformedMeshInstance implementation          */
 /*************************************************************/
+
 
 TransformedMeshInstance::TransformedMeshInstance(Mesh *mesh): 
@@ -756,4 +764,5 @@
 }
 
+
 int TransformedMeshInstance::CastRay(Ray &ray, const vector<int> &faces)
 {
@@ -799,3 +808,10 @@
 
 
-}
+Vector3 TransformedMeshInstance::GetNormal(const int idx) const
+{
+	Mesh mesh;
+	GetTransformedMesh(mesh);
+	return mesh.GetFacePlane(idx).mNormal;
+}
+
+}
