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

RevLine 
[372]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"
[439]8#include "ViewCellsManager.h"
[445]9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
11#include "VspKdTree.h"
[469]12#include "RenderSimulator.h"
[496]13#include "GlRenderer.h"
[749]14#include "PlyParser.h"
[372]15
[863]16namespace GtpVisibilityPreprocessor {
[860]17
18
[492]19Preprocessor *preprocessor;
20
[750]21
[1001]22// HACK: Artificially modify scene to watch rendercost changes
[750]23static void AddGeometry(SceneGraph *scene)
24{
[752]25        scene->mRoot->UpdateBox();
26
[750]27        AxisAlignedBox3 sceneBox = scene->GetBox();
28
29        int n = 200;
30
31        if (0){
[840]32        // form grid of boxes
[750]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               
[840]39                        const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
[750]40               
[840]41                        const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
[750]42                        AxisAlignedBox3 box(pt2, pt2 + boxSize);
[991]43                        Mesh *mesh = CreateMeshFromBox(box);
[750]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);
[991]62                        Mesh *mesh = CreateMeshFromBox(box);
[750]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);
[991]80                Mesh *mesh = CreateMeshFromBox(box);
[750]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       
[840]91        // plane separating view space regions
92        if (1)
93        {
94                const Vector3 scale(1.0, 0.0, 0);
[750]95
[840]96                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
[750]97
[840]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        }       
[750]109}
110
111
[372]112Preprocessor::Preprocessor():
113mKdTree(NULL),
[409]114mBspTree(NULL),
[422]115mVspKdTree(NULL),
[445]116mVspBspTree(NULL),
[1002]117mViewCellsManager(NULL),
118mRenderSimulator(NULL)
[308]119{
[840]120        environment->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
[538]121 
[840]122        // renderer will be constructed when the scene graph and viewcell manager will be known
123        renderer = NULL;
[496]124 
[840]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);
[871]130        environment->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
[599]131
[871]132        char buffer[256];
133        environment->GetStringValue("Preprocessor.visibilityFile",  buffer);
134        mVisibilityFileName = buffer;
[878]135        environment->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
[904]136        environment->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
137                                                          mApplyVisibilitySpatialFilter );
[878]138        environment->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
139
[840]140        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
141        Debug << "load polygons as meshes: " << mLoadPolygonsAsMeshes << endl;
[372]142}
143
144
145Preprocessor::~Preprocessor()
146{
[752]147  cout << "cleaning up" << endl;
148
149  cout << "Deleting view cells manager ... \n";
[496]150  DEL_PTR(mViewCellsManager);
[752]151  cout << "done.\n";
152
153  cout << "Deleting bsp tree ... \n";
[496]154  DEL_PTR(mBspTree);
[752]155  cout << "done.\n";
156
[840]157  cout << "Deleting kd tree...\n";
[496]158  DEL_PTR(mKdTree);
[840]159  cout << "done.\n";
[752]160 
[840]161  cout << "Deleting vspkd tree...\n";
[496]162  DEL_PTR(mVspKdTree);
[840]163  cout << "done.\n";
[752]164
[840]165  cout << "Deleting vspbsp tree...\n";
[496]166  DEL_PTR(mVspBspTree);
[840]167  cout << "done.\n";
[1002]168
169   cout << "Deleting scene graph...\n";
170  DEL_PTR(mSceneGraph);
171  cout << "done.\n";
172
173  DEL_PTR(mRenderSimulator);
174  DEL_PTR(renderer);
[372]175}
176
[387]177int
[419]178SplitFilenames(const string str, vector<string> &filenames)
[387]179{
180        int pos = 0;
181
182        while(1) {
[469]183                int npos = (int)str.find(';', pos);
[387]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));
[440]192        return (int)filenames.size();
[387]193}
194
[750]195
[372]196bool
197Preprocessor::LoadScene(const string filename)
198{
[925]199        // use leaf nodes of the original spatial hierarchy as occludees
[508]200        mSceneGraph = new SceneGraph;
[372]201 
[508]202        Parser *parser;
[387]203        vector<string> filenames;
204        int files = SplitFilenames(filename, filenames);
[712]205        cout << "number of input files: " << files << endl;
[387]206        bool result = false;
207        if (files == 1) {
208               
209                if (strstr(filename.c_str(), ".x3d"))
[749]210                  parser = new X3dParser;
[387]211                else
[811]212                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
[749]213                        parser = new PlyParser;
214                  else
[387]215                        parser = new UnigraphicsParser;
[372]216
[387]217                cout<<filename<<endl;
[658]218                result = parser->ParseFile(filename, &mSceneGraph->mRoot, mLoadPolygonsAsMeshes);
[372]219
[387]220                delete parser;
[372]221
[387]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        }
[372]240       
241
[752]242        if (result)
[925]243        {
[752]244                // HACK
245                //AddGeometry(mSceneGraph);
[492]246          mSceneGraph->AssignObjectIds();
[752]247               
[492]248          int intersectables, faces;
249          mSceneGraph->GetStatistics(intersectables, faces);
[752]250
[492]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);
[752]255          mSceneGraph->mRoot->UpdateBox();
[658]256
[659]257         /* Exporter *exporter = Exporter::GetExporter("testload.x3d");
[658]258
[659]259          if (exporter)
260          {
261                  exporter->ExportGeometry(mObjects);
262                  delete exporter;
263          }*/
[658]264
[387]265        }
[372]266       
[492]267       
268        return result;
[372]269}
270
271bool
272Preprocessor::ExportPreprocessedData(const string filename)
273{
[871]274 
[931]275  mViewCellsManager->ExportViewCells(filename, true, mObjects);
[871]276 
277  return true;
[372]278}
279
280bool
[871]281Preprocessor::PostProcessVisibility()
282{
283 
[904]284  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
[997]285        cout<<"Applying visibility filter ...";
[1002]286        cout<<"filter width = " << mVisibilityFilterWidth << endl;
[904]287       
[1002]288        if (!mViewCellsManager)
289                return false;
290
[871]291        mViewCellsManager->ApplyFilter(mKdTree,
[904]292                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
293                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
[997]294        cout << "done." << endl;
[871]295  }
296 
297  // export the preprocessed information to a file
298  if (mExportVisibility)
299        ExportPreprocessedData(mVisibilityFileName);
300 
301  return true;
302}
303
304
305bool
[372]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,
[492]331                                          const bool scene,
332                                          const bool kdtree,
333                                          const bool bsptree
334                                          )
[372]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}
[429]358
[508]359
[463]360bool Preprocessor::PrepareViewCells()
361{
[577]362        //-- parse view cells construction method
363        environment->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
364        char buf[100];
365       
366        if (mLoadViewCells)
[997]367        {       
[577]368                environment->GetStringValue("ViewCells.filename", buf);
[944]369                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, environment, true);
[577]370        }
371        else
372        {
373                //-- parse type of view cell container
[1002]374                environment->GetStringValue("ViewCells.type", buf);             
375            mViewCellsManager = CreateViewCellsManager(buf);
[577]376        }
[439]377
[997]378        //-- parameters for render heuristics evaluation
[473]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);
[694]384       
[473]385        mRenderSimulator =
386                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]387
[480]388        mViewCellsManager->SetRenderer(mRenderSimulator);
[440]389
[997]390        // default view space is the extent of the scene
391        mViewCellsManager->SetViewSpaceBox(mSceneGraph->GetBox());
[574]392
[538]393        if (mUseGlRenderer || mUseGlDebugger)
[540]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);
[556]398                //              renderer->makeCurrent();
[746]399               
[540]400        }
[496]401       
[463]402        return true;
[490]403}
404
405
[575]406ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
407{
408        if (strcmp(name, "kdTree") == 0)
409        {
[938]410                mViewCellsManager = new KdViewCellsManager(mKdTree, environment);
[575]411        }
412        else if (strcmp(name, "bspTree") == 0)
413        {
414                Debug << "view cell type: Bsp" << endl;
415
[577]416                mBspTree = new BspTree();
[938]417                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
[575]418        }
419        else if (strcmp(name, "vspBspTree") == 0)
420        {
421                Debug << "view cell type: VspBsp" << endl;
422
[870]423                mVspBspTree = new VspBspTree(environment);
[938]424                mViewCellsManager = new VspBspViewCellsManager(mVspBspTree, environment);
[575]425        }
426        else if (strcmp(name, "vspKdTree") == 0)
427        {
428                mVspKdTree = new VspKdTree();           
429       
[938]430                mViewCellsManager = new VspKdViewCellsManager(mVspKdTree, environment);
[575]431        }
432        else if (strcmp(name, "sceneDependent") == 0)
433        {
434                //TODO
435                mBspTree = new BspTree();
436
437                Debug << "view cell type: Bsp" << endl;
438               
[938]439                mViewCellsManager = new BspViewCellsManager(mBspTree, environment);
[575]440        }
441        else
442        {
[664]443                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]444                exit(1);
445        }
446
447        return mViewCellsManager;
448}
449
450
[491]451// use ascii format to store rays
452#define USE_ASCII 0
453
454
[490]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       
[491]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);
[490]473
[491]474#if USE_ASCII
[656]475        ifstream samplesIn(fileName);
[490]476        if (!samplesIn.is_open())
477                return false;
478
479        string buf;
480        while (!(getline(samplesIn, buf)).eof())
481        {
[491]482                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]483                           &origin.x, &origin.y, &origin.z,
[491]484                           &termination.x, &termination.y, &termination.z,
485                           &(sObj.mId), &(tObj.mId));
[490]486               
[491]487                Intersectable *sourceObj = NULL;
488                Intersectable *termObj = NULL;
489               
490                if (sObj.mId >= 0)
[490]491                {
492                        ObjectContainer::iterator oit =
[491]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                }
[490]503
[491]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;
[490]529                }
[491]530               
531                if (tObj.mId >= 0)
[490]532                {
[491]533                        ObjectContainer::iterator oit =
534                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
535                        termObj = *oit;
[490]536                }
[491]537
538                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]539        }
[491]540
541#endif
[490]542        samplesIn.close();
543
544        return true;
545}
546
[508]547
548bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]549{
[491]550        char fileName[100];
551        environment->GetStringValue("Preprocessor.samplesFilename", fileName);
552       
[490]553
554        VssRayContainer::const_iterator it, it_end = samples.end();
555       
[491]556#if USE_ASCII
557        ofstream samplesOut(fileName);
[490]558        if (!samplesOut.is_open())
559                return false;
560
561        for (it = samples.begin(); it != it_end; ++ it)
562        {
563                VssRay *ray = *it;
[491]564                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
565                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
566
[490]567                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
568                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]569                                   << sourceid << " " << termid << "\n";
[490]570        }
[491]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
[490]591        samplesOut.close();
592        return true;
593}
[563]594
595
596
597bool
598Preprocessor::GenerateRays(
599                                                   const int number,
600                                                   const int sampleType,
601                                                   SimpleRayContainer &rays
602                                                   )
603{
604  Vector3 origin, direction;
[837]605  int startSize = (int)rays.size();
606  for (int i=0; (int)rays.size() - startSize  < number; i ++) {
[563]607        // now get the direction
608        switch (sampleType) {
609        case OBJECT_BASED_DISTRIBUTION: {
[576]610          mViewCellsManager->GetViewPoint(origin);
[563]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;
[576]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;
[563]628        case DIRECTION_BASED_DISTRIBUTION:
[576]629          mViewCellsManager->GetViewPoint(origin);
[563]630          direction = UniformRandomVector();
631          break;
632        case DIRECTION_BOX_BASED_DISTRIBUTION: {
[576]633          mViewCellsManager->GetViewPoint(origin);
[563]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:
[576]640          mViewCellsManager->GetViewPoint(origin);
[563]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}
[860]657
[878]658}
Note: See TracBrowser for help on using the repository browser.