source: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp @ 1002

Revision 1002, 16.9 KB checked in by mattausch, 18 years ago (diff)

debug run: fixing memory holes

Line 
1#include "SceneGraph.h"
2#include "Exporter.h"
3#include "UnigraphicsParser.h"
4#include "X3dParser.h"
5#include "Preprocessor.h"
6#include "ViewCell.h"
7#include "Environment.h"
8#include "ViewCellsManager.h"
9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
11#include "VspKdTree.h"
12#include "RenderSimulator.h"
13#include "GlRenderer.h"
14#include "PlyParser.h"
15
16namespace GtpVisibilityPreprocessor {
17
18
19Preprocessor *preprocessor;
20
21
22// HACK: Artificially modify scene to watch rendercost changes
23static void AddGeometry(SceneGraph *scene)
24{
25        scene->mRoot->UpdateBox();
26
27        AxisAlignedBox3 sceneBox = scene->GetBox();
28
29        int n = 200;
30
31        if (0){
32        // form grid of boxes
33        for (int i = 0; i < n; ++ i)
34        {
35                for (int j = 0; j < n; ++ j)
36                {
37                        const Vector3 scale2((float)j * 0.8 / n + 0.1,  0.05, (float)i * 0.8  / (float)n + 0.1);
38               
39                        const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
40               
41                        const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
42                        AxisAlignedBox3 box(pt2, pt2 + boxSize);
43                        Mesh *mesh = CreateMeshFromBox(box);
44
45                        mesh->Preprocess();
46               
47                        MeshInstance *mi = new MeshInstance(mesh);
48                        scene->mRoot->mGeometry.push_back(mi);
49                }
50        }
51
52        for (int i = 0; i < n; ++ i)
53        {
54                for (int j = 0; j < n; ++ j)
55                {
56                        const Vector3 scale2(0.15, (float)j * 0.8 / n + 0.1, (float)i * 0.8  / (float)n + 0.1);
57               
58                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
59               
60                        Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
61                        AxisAlignedBox3 box(pt2, pt2 + boxSize);
62                        Mesh *mesh = CreateMeshFromBox(box);
63
64                        mesh->Preprocess();
65               
66                        MeshInstance *mi = new MeshInstance(mesh);
67                        scene->mRoot->mGeometry.push_back(mi);
68                }
69        }
70
71        for (int i = 0; i < n; ++ i)
72        {
73                const Vector3 scale2(2, 0.2, (float)i * 0.8  / (float)n + 0.1);
74               
75                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
76               
77                //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
78                Vector3 boxSize = sceneBox.Size() * Vector3(0.005, 0.02, 0.005);
79                AxisAlignedBox3 box(pt2 + 0.1, pt2 + boxSize);
80                Mesh *mesh = CreateMeshFromBox(box);
81
82                mesh->Preprocess();
83               
84                MeshInstance *mi = new MeshInstance(mesh);
85                scene->mRoot->mGeometry.push_back(mi);
86        }
87       
88        scene->mRoot->UpdateBox();
89        }
90       
91        // plane separating view space regions
92        if (1)
93        {
94                const Vector3 scale(1.0, 0.0, 0);
95
96                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
97
98                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
99                Mesh *planeMesh = new Mesh();
100               
101                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
102                IncludePolyInMesh(*poly, *planeMesh);
103               
104                planeMesh->Preprocess();
105               
106                MeshInstance *planeMi = new MeshInstance(planeMesh);
107                scene->mRoot->mGeometry.push_back(planeMi);
108        }       
109}
110
111
112Preprocessor::Preprocessor():
113mKdTree(NULL),
114mBspTree(NULL),
115mVspKdTree(NULL),
116mVspBspTree(NULL),
117mViewCellsManager(NULL),
118mRenderSimulator(NULL)
119{
120        environment->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
121 
122        // renderer will be constructed when the scene graph and viewcell manager will be known
123        renderer = NULL;
124 
125        environment->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
126        environment->GetBoolValue("Preprocessor.loadPolygonsAsMeshes", mLoadPolygonsAsMeshes);
127        environment->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
128        environment->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
129        environment->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
130        environment->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
131
132        char buffer[256];
133        environment->GetStringValue("Preprocessor.visibilityFile",  buffer);
134        mVisibilityFileName = buffer;
135        environment->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
136        environment->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
137                                                          mApplyVisibilitySpatialFilter );
138        environment->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
139
140        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
141        Debug << "load polygons as meshes: " << mLoadPolygonsAsMeshes << endl;
142}
143
144
145Preprocessor::~Preprocessor()
146{
147  cout << "cleaning up" << endl;
148
149  cout << "Deleting view cells manager ... \n";
150  DEL_PTR(mViewCellsManager);
151  cout << "done.\n";
152
153  cout << "Deleting bsp tree ... \n";
154  DEL_PTR(mBspTree);
155  cout << "done.\n";
156
157  cout << "Deleting kd tree...\n";
158  DEL_PTR(mKdTree);
159  cout << "done.\n";
160 
161  cout << "Deleting vspkd tree...\n";
162  DEL_PTR(mVspKdTree);
163  cout << "done.\n";
164
165  cout << "Deleting vspbsp tree...\n";
166  DEL_PTR(mVspBspTree);
167  cout << "done.\n";
168
169   cout << "Deleting scene graph...\n";
170  DEL_PTR(mSceneGraph);
171  cout << "done.\n";
172
173  DEL_PTR(mRenderSimulator);
174  DEL_PTR(renderer);
175}
176
177int
178SplitFilenames(const string str, vector<string> &filenames)
179{
180        int pos = 0;
181
182        while(1) {
183                int npos = (int)str.find(';', pos);
184               
185                if (npos < 0 || npos - pos < 1)
186                        break;
187                filenames.push_back(string(str, pos, npos - pos));
188                pos = npos + 1;
189        }
190       
191        filenames.push_back(string(str, pos, str.size() - pos));
192        return (int)filenames.size();
193}
194
195
196bool
197Preprocessor::LoadScene(const string filename)
198{
199        // use leaf nodes of the original spatial hierarchy as occludees
200        mSceneGraph = new SceneGraph;
201 
202        Parser *parser;
203        vector<string> filenames;
204        int files = SplitFilenames(filename, filenames);
205        cout << "number of input files: " << files << endl;
206        bool result = false;
207        if (files == 1) {
208               
209                if (strstr(filename.c_str(), ".x3d"))
210                  parser = new X3dParser;
211                else
212                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
213                        parser = new PlyParser;
214                  else
215                        parser = new UnigraphicsParser;
216
217                cout<<filename<<endl;
218                result = parser->ParseFile(filename, &mSceneGraph->mRoot, mLoadPolygonsAsMeshes);
219
220                delete parser;
221
222        } else {
223                // root for different files
224                mSceneGraph->mRoot = new SceneGraphNode;
225                for (int i= 0; i < filenames.size(); i++) {
226                        if (strstr(filenames[i].c_str(), ".x3d"))
227                                parser = new X3dParser;
228                        else
229                                parser = new UnigraphicsParser;
230                       
231                        SceneGraphNode *node;
232                        if (parser->ParseFile(filenames[i], &node)) {
233                                mSceneGraph->mRoot->mChildren.push_back(node);
234                                // at least one file parsed
235                                result = true;
236                        }
237                        delete parser;
238                }
239        }
240       
241
242        if (result)
243        {
244                // HACK
245                //AddGeometry(mSceneGraph);
246          mSceneGraph->AssignObjectIds();
247               
248          int intersectables, faces;
249          mSceneGraph->GetStatistics(intersectables, faces);
250
251          cout<<filename<<" parsed successfully."<<endl;
252          cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
253          cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
254          mSceneGraph->CollectObjects(&mObjects);
255          mSceneGraph->mRoot->UpdateBox();
256
257         /* Exporter *exporter = Exporter::GetExporter("testload.x3d");
258
259          if (exporter)
260          {
261                  exporter->ExportGeometry(mObjects);
262                  delete exporter;
263          }*/
264
265        }
266       
267       
268        return result;
269}
270
271bool
272Preprocessor::ExportPreprocessedData(const string filename)
273{
274 
275  mViewCellsManager->ExportViewCells(filename, true, mObjects);
276 
277  return true;
278}
279
280bool
281Preprocessor::PostProcessVisibility()
282{
283 
284  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
285        cout<<"Applying visibility filter ...";
286        cout<<"filter width = " << mVisibilityFilterWidth << endl;
287       
288        if (!mViewCellsManager)
289                return false;
290
291        mViewCellsManager->ApplyFilter(mKdTree,
292                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
293                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
294        cout << "done." << endl;
295  }
296 
297  // export the preprocessed information to a file
298  if (mExportVisibility)
299        ExportPreprocessedData(mVisibilityFileName);
300 
301  return true;
302}
303
304
305bool
306Preprocessor::BuildKdTree()
307{
308  mKdTree = new KdTree;
309  // add mesh instances of the scene graph to the root of the tree
310  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
311  mSceneGraph->CollectObjects(&root->mObjects);
312 
313  mKdTree->Construct();
314  return true;
315}
316
317void
318Preprocessor::KdTreeStatistics(ostream &s)
319{
320  s<<mKdTree->GetStatistics();
321}
322
323void
324Preprocessor::BspTreeStatistics(ostream &s)
325{
326        s << mBspTree->GetStatistics();
327}
328
329bool
330Preprocessor::Export( const string filename,
331                                          const bool scene,
332                                          const bool kdtree,
333                                          const bool bsptree
334                                          )
335{
336  Exporter *exporter = Exporter::GetExporter(filename);
337       
338  if (exporter) {
339    if (scene)
340      exporter->ExportScene(mSceneGraph->mRoot);
341
342    if (kdtree) {
343      exporter->SetWireframe();
344      exporter->ExportKdTree(*mKdTree);
345    }
346
347        if (bsptree) {
348                //exporter->SetWireframe();
349                exporter->ExportBspTree(*mBspTree);
350        }
351
352    delete exporter;
353    return true;
354  }
355
356  return false;
357}
358
359
360bool Preprocessor::PrepareViewCells()
361{
362        //-- parse view cells construction method
363        environment->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
364        char buf[100];
365       
366        if (mLoadViewCells)
367        {       
368                environment->GetStringValue("ViewCells.filename", buf);
369                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, environment, true);
370        }
371        else
372        {
373                //-- parse type of view cell container
374                environment->GetStringValue("ViewCells.type", buf);             
375            mViewCellsManager = CreateViewCellsManager(buf);
376        }
377
378        //-- parameters for render heuristics evaluation
379        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
380
381        environment->GetFloatValue("Simulation.objRenderCost",objRenderCost);
382        environment->GetFloatValue("Simulation.vcOverhead", vcOverhead);
383        environment->GetFloatValue("Simulation.moveSpeed", moveSpeed);
384       
385        mRenderSimulator =
386                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
387
388        mViewCellsManager->SetRenderer(mRenderSimulator);
389
390        // default view space is the extent of the scene
391        mViewCellsManager->SetViewSpaceBox(mSceneGraph->GetBox());
392
393        if (mUseGlRenderer || mUseGlDebugger)
394        {
395                // NOTE: render texture should be power of 2 and square
396                // renderer must be initialised
397                renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
398                //              renderer->makeCurrent();
399               
400        }
401       
402        return true;
403}
404
405
406ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
407{
408        if (strcmp(name, "kdTree") == 0)
409        {
410                mViewCellsManager = new KdViewCellsManager(mKdTree, environment);
411        }
412        else if (strcmp(name, "bspTree") == 0)
413        {
414                Debug << "view cell type: Bsp" << endl;
415
416                mBspTree = new BspTree();
417                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
418        }
419        else if (strcmp(name, "vspBspTree") == 0)
420        {
421                Debug << "view cell type: VspBsp" << endl;
422
423                mVspBspTree = new VspBspTree(environment);
424                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, environment);
425        }
426        else if (strcmp(name, "vspKdTree") == 0)
427        {
428                mVspKdTree = new VspKdTree();           
429       
430                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, environment);
431        }
432        else if (strcmp(name, "sceneDependent") == 0)
433        {
434                //TODO
435                mBspTree = new BspTree();
436
437                Debug << "view cell type: Bsp" << endl;
438               
439                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
440        }
441        else
442        {
443                cerr << "Wrong view cells type " << name << "!!!" << endl;
444                exit(1);
445        }
446
447        return mViewCellsManager;
448}
449
450
451// use ascii format to store rays
452#define USE_ASCII 0
453
454
455inline bool ilt(Intersectable *obj1, Intersectable *obj2)
456{
457        return obj1->mId < obj2->mId;
458}
459
460
461bool Preprocessor::LoadSamples(VssRayContainer &samples,
462                                                           ObjectContainer &objects) const
463{
464        std::stable_sort(objects.begin(), objects.end(), ilt);
465        char fileName[100];
466        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
467       
468    Vector3 origin, termination;
469        // HACK: needed only for lower_bound algorithm to find the
470        // intersected objects
471        MeshInstance sObj(NULL);
472        MeshInstance tObj(NULL);
473
474#if USE_ASCII
475        ifstream samplesIn(fileName);
476        if (!samplesIn.is_open())
477                return false;
478
479        string buf;
480        while (!(getline(samplesIn, buf)).eof())
481        {
482                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
483                           &origin.x, &origin.y, &origin.z,
484                           &termination.x, &termination.y, &termination.z,
485                           &(sObj.mId), &(tObj.mId));
486               
487                Intersectable *sourceObj = NULL;
488                Intersectable *termObj = NULL;
489               
490                if (sObj.mId >= 0)
491                {
492                        ObjectContainer::iterator oit =
493                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
494                        sourceObj = *oit;
495                }
496               
497                if (tObj.mId >= 0)
498                {
499                        ObjectContainer::iterator oit =
500                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
501                        termObj = *oit;
502                }
503
504                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
505        }
506#else
507        ifstream samplesIn(fileName, ios::binary);
508        if (!samplesIn.is_open())
509                return false;
510
511        while (1)
512        {
513                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
514                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
515                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
516                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
517               
518                 if (samplesIn.eof())
519                        break;
520
521                Intersectable *sourceObj = NULL;
522                Intersectable *termObj = NULL;
523               
524                if (sObj.mId >= 0)
525                {
526                        ObjectContainer::iterator oit =
527                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
528                        sourceObj = *oit;
529                }
530               
531                if (tObj.mId >= 0)
532                {
533                        ObjectContainer::iterator oit =
534                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
535                        termObj = *oit;
536                }
537
538                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
539        }
540
541#endif
542        samplesIn.close();
543
544        return true;
545}
546
547
548bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
549{
550        char fileName[100];
551        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
552       
553
554        VssRayContainer::const_iterator it, it_end = samples.end();
555       
556#if USE_ASCII
557        ofstream samplesOut(fileName);
558        if (!samplesOut.is_open())
559                return false;
560
561        for (it = samples.begin(); it != it_end; ++ it)
562        {
563                VssRay *ray = *it;
564                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
565                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
566
567                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
568                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
569                                   << sourceid << " " << termid << "\n";
570        }
571#else
572        ofstream samplesOut(fileName, ios::binary);
573        if (!samplesOut.is_open())
574                return false;
575
576        for (it = samples.begin(); it != it_end; ++ it)
577        {       
578                VssRay *ray = *it;
579                Vector3 origin(ray->GetOrigin());
580                Vector3 termination(ray->GetTermination());
581               
582                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
583                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
584
585                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
586                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
587                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
588                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
589    }
590#endif
591        samplesOut.close();
592        return true;
593}
594
595
596
597bool
598Preprocessor::GenerateRays(
599                                                   const int number,
600                                                   const int sampleType,
601                                                   SimpleRayContainer &rays
602                                                   )
603{
604  Vector3 origin, direction;
605  int startSize = (int)rays.size();
606  for (int i=0; (int)rays.size() - startSize  < number; i ++) {
607        // now get the direction
608        switch (sampleType) {
609        case OBJECT_BASED_DISTRIBUTION: {
610          mViewCellsManager->GetViewPoint(origin);
611          Vector3 point;
612          Vector3 normal;
613          int i = RandomValue(0, mObjects.size() - 1);
614          Intersectable *object = mObjects[i];
615          object->GetRandomSurfacePoint(point, normal);
616          direction = point - origin;
617        }
618          break;
619        case OBJECT_DIRECTION_BASED_DISTRIBUTION: {
620          int i = RandomValue(0, mObjects.size() - 1);
621          Intersectable *object = mObjects[i];
622          Vector3 normal;
623          object->GetRandomSurfacePoint(origin, normal);
624          direction = UniformRandomVector(normal);
625          origin += 0.1f*direction;
626        }
627          break;
628        case DIRECTION_BASED_DISTRIBUTION:
629          mViewCellsManager->GetViewPoint(origin);
630          direction = UniformRandomVector();
631          break;
632        case DIRECTION_BOX_BASED_DISTRIBUTION: {
633          mViewCellsManager->GetViewPoint(origin);
634          float alpha = RandomValue(0.0f, 2*M_PI);
635          float beta = RandomValue(-M_PI/2, M_PI/2);
636          direction = VssRay::GetDirection(alpha, beta);
637          break;
638        }
639        case SPATIAL_BOX_BASED_DISTRIBUTION:
640          mViewCellsManager->GetViewPoint(origin);
641          direction = mKdTree->GetBox().GetRandomPoint() - origin;
642          break;
643        default:
644          // unsuported distribution type
645          return false;
646        }
647        // $$ jb the pdf is yet not correct for all sampling methods!
648        float pdf = 1.0f;
649        float c = Magnitude(direction);
650        if (c > Limits::Small) {
651          direction*=1.0f/c;
652          rays.AddRay(SimpleRay(origin, direction, pdf));
653        }
654  }
655  return true;
656}
657
658}
Note: See TracBrowser for help on using the repository browser.