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

Revision 840, 15.2 KB checked in by mattausch, 18 years ago (diff)

implementing bounding box hack

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