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

Revision 1001, 16.7 KB checked in by mattausch, 18 years ago (diff)

added mesh instance support
improved support for occlusion queries + other extensions

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