source: GTP/trunk/Lib/Vis/Preprocessing/src/VssPreprocessor.cpp @ 1563

Revision 1563, 17.1 KB checked in by mattausch, 18 years ago (diff)

fixed bug with view space box

Line 
1#include "SceneGraph.h"
2#include "KdTree.h"
3#include "VssPreprocessor.h"
4#include "X3dExporter.h"
5#include "Environment.h"
6#include "MutualVisibility.h"
7#include "Polygon3.h"
8#include "ViewCell.h"
9#include "VssRay.h"
10#include "VssTree.h"
11#include "ViewCellsManager.h"
12#include "RenderSimulator.h"
13#include "Beam.h"
14#include "GlRenderer.h"
15#include "Intersectable.h"
16#include "RayCaster.h"
17
18
19namespace GtpVisibilityPreprocessor {
20
21bool use2dSampling = false;
22bool useViewspacePlane = false;
23
24VssPreprocessor::VssPreprocessor():
25  mVssRays()
26{
27  // this should increase coherence of the samples
28  Environment::GetSingleton()->GetIntValue("VssPreprocessor.samplesPerPass", mSamplesPerPass);
29  Environment::GetSingleton()->GetIntValue("VssPreprocessor.initialSamples", mInitialSamples);
30  Environment::GetSingleton()->GetIntValue("VssPreprocessor.vssSamples", mVssSamples);
31  Environment::GetSingleton()->GetIntValue("VssPreprocessor.vssSamplesPerPass", mVssSamplesPerPass);
32  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.useImportanceSampling", mUseImportanceSampling);
33 
34  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.loadInitialSamples", mLoadInitialSamples);
35  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.storeInitialSamples", mStoreInitialSamples);
36  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.useViewSpaceBox", mUseViewSpaceBox);
37  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.testBeamSampling", mTestBeamSampling);
38  Environment::GetSingleton()->GetBoolValue("VssPreprocessor.enlargeViewSpace", mEnlargeViewSpace);
39  Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
40 
41  useViewspacePlane = mUseViewSpaceBox; //hack
42 
43  Debug << "*********** vss preprocessor options **************" << endl;
44  Debug << "use view space box=" << mUseViewSpaceBox << endl;
45  Debug << "enlarge view space=" << mEnlargeViewSpace << endl;
46  Debug << "*********** end vss preprocessor options **************" << endl;
47
48  mStats.open("stats.log");
49}
50
51
52VssPreprocessor::~VssPreprocessor()
53{
54        CLEAR_CONTAINER(mVssRays);
55}
56
57
58Vector3
59VssPreprocessor::GetViewpoint(AxisAlignedBox3 *viewSpaceBox)
60{
61  AxisAlignedBox3 box;
62
63  if (viewSpaceBox)
64        box =*viewSpaceBox;
65  else
66        box = mKdTree->GetBox();
67
68  // shrink the box in the y direction
69  return box.GetRandomPoint();
70}
71
72Vector3
73VssPreprocessor::GetDirection(const Vector3 &viewpoint,
74                                                          AxisAlignedBox3 *viewSpaceBox
75                                                          )
76{
77  Vector3 point;
78  if (!use2dSampling)
79  {
80          if (0)
81          {
82                  Vector3 normal;
83                  int i = Random((int)mObjects.size());
84                  Intersectable *object = mObjects[i];
85                  object->GetRandomSurfacePoint(point, normal);
86          }
87          else
88                  point = mKdTree->GetBox().GetRandomPoint();
89        //        point = viewpoint + UniformRandomVector();
90  }
91  else
92  {
93          AxisAlignedBox3 box;
94
95          if (viewSpaceBox)
96                  box =*viewSpaceBox;
97          else
98                  box = mKdTree->GetBox();
99
100          point = box.GetRandomPoint();
101          point.y = viewpoint.y;
102  }
103
104  return point - viewpoint;
105}
106
107int
108VssPreprocessor::GenerateImportanceRays(VssTree *vssTree,
109                                                                                const int desiredSamples,
110                                                                                SimpleRayContainer &rays
111                                                                                )
112{
113  int num;
114  if (0) {
115        float minRayContribution;
116        float maxRayContribution;
117        float avgRayContribution;
118
119        vssTree->GetRayContributionStatistics(minRayContribution,
120                                                                                  maxRayContribution,
121                                                                                  avgRayContribution);
122
123        cout<<
124          "#MIN_RAY_CONTRIB\n"<<minRayContribution<<endl<<
125          "#MAX_RAY_CONTRIB\n"<<maxRayContribution<<endl<<
126          "#AVG_RAY_CONTRIB\n"<<avgRayContribution<<endl;
127
128        float p = desiredSamples/(float)(avgRayContribution*vssTree->stat.Leaves());
129        num = vssTree->GenerateRays(p, rays);
130  } else {
131        int leaves = vssTree->stat.Leaves();
132        num = vssTree->GenerateRays(desiredSamples, leaves, rays);
133  }
134
135  cout<<"Generated "<<num<<" rays."<<endl;
136
137  return num;
138}
139
140
141bool
142VssPreprocessor::ExportRays(const char *filename,
143                                                        const VssRayContainer &vssRays,
144                                                        const int number
145                                                        )
146{
147  cout<<"Exporting vss rays..."<<endl<<flush;
148
149  Exporter *exporter = NULL;
150  exporter = Exporter::GetExporter(filename);
151  exporter->SetWireframe();
152  exporter->ExportKdTree(*mKdTree);
153  exporter->SetFilled();
154  exporter->ExportScene(mSceneGraph->GetRoot());
155  exporter->SetWireframe();
156
157  exporter->SetForcedMaterial(RgbColor(1,0,1));
158  exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
159  exporter->ResetForcedMaterial();
160
161
162  VssRayContainer rays;
163  vssRays.SelectRays(number, rays);
164 
165  //exporter->ExportRays(rays, RgbColor(1, 0, 0));
166
167  delete exporter;
168
169  cout<<"done."<<endl<<flush;
170
171  return true;
172}
173
174
175bool
176VssPreprocessor::ExportVssTree(char *filename,
177                                                           VssTree *tree,
178                                                           const Vector3 &dir
179                                                           )
180{
181  Exporter *exporter = Exporter::GetExporter(filename);
182  exporter->SetFilled();
183  exporter->ExportScene(mSceneGraph->GetRoot());
184  //  exporter->SetWireframe();
185  bool result = exporter->ExportVssTree2( *tree, dir );
186  delete exporter;
187  return result;
188}
189
190bool
191VssPreprocessor::ExportVssTreeLeaf(char *filename,
192                                                                   VssTree *tree,
193                                                                   VssTreeLeaf *leaf)
194{
195  Exporter *exporter = NULL;
196  exporter = Exporter::GetExporter(filename);
197  exporter->SetWireframe();
198  exporter->ExportKdTree(*mKdTree);
199
200  exporter->SetForcedMaterial(RgbColor(1,0,0));
201  exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
202  exporter->ResetForcedMaterial();
203
204  exporter->SetForcedMaterial(RgbColor(0,0,1));
205  exporter->ExportBox(tree->GetBBox(leaf));
206  exporter->ResetForcedMaterial();
207
208  VssRayContainer rays[4];
209  for (int i=0; i < leaf->rays.size(); i++) {
210        int k = leaf->rays[i].GetRayClass();
211        rays[k].push_back(leaf->rays[i].mRay);
212  }
213
214  // SOURCE RAY
215  exporter->ExportRays(rays[0], RgbColor(1, 0, 0));
216  // TERMINATION RAY
217  exporter->ExportRays(rays[1], RgbColor(1, 1, 1));
218  // PASSING_RAY
219  exporter->ExportRays(rays[2], RgbColor(1, 1, 0));
220  // CONTAINED_RAY
221  exporter->ExportRays(rays[3], RgbColor(0, 0, 1));
222
223  delete exporter;
224  return true;
225}
226
227void
228VssPreprocessor::ExportVssTreeLeaves(VssTree *tree, const int number)
229{
230  vector<VssTreeLeaf *> leaves;
231  tree->CollectLeaves(leaves);
232
233  int num = 0;
234  int i;
235  float p = number / (float)leaves.size();
236  for (i=0; i < leaves.size(); i++) {
237        if (RandomValue(0,1) < p) {
238          char filename[64];
239          sprintf(filename, "vss-leaf-%04d.x3d", num);
240          ExportVssTreeLeaf(filename, tree, leaves[i]);
241          num++;
242        }
243        if (num >= number)
244          break;
245  }
246}
247
248
249void VssPreprocessor::TestBeamCasting(VssTree *tree,
250                                                                          ViewCellsManager *vm,
251                                                                          const ObjectContainer &objects)
252{
253        //debuggerWidget = new GlDebuggerWidget(renderer);
254        //  renderer->resize(640, 480);
255        //debuggerWidget->resize(640, 480);
256
257        vector<VssTreeLeaf *> leaves;
258        tree->CollectLeaves(leaves);
259
260        Exporter *exporter = Exporter::GetExporter("shafts.x3d");
261
262        exporter->SetWireframe();
263        exporter->ExportGeometry(objects);
264        exporter->SetFilled();
265        //Randomize();
266// §§matt
267//      debuggerWidget = new GlDebuggerWidget(renderer);
268
269        /*debuggerWidget->mBeam = beam;
270        debuggerWidget->mSourceObject = sourceObj;
271        debuggerWidget->mSamples = 10000;
272       
273        Debug << "showing window" << endl;
274        debuggerWidget->show();
275       
276        renderer->makeCurrent();*/
277
278        for (int i = 0; i < 10; ++ i)
279        {
280                Beam beam;
281                Intersectable *sourceObj = mObjects[5];
282
283                const int index = (int)RandomValue(0, (Real)((int)leaves.size() - 1));
284                VssTreeLeaf *leaf = leaves[index];
285
286                AxisAlignedBox3 dirBox = tree->GetDirBBox(leaf);
287                AxisAlignedBox3 box = tree->GetBBox(leaf);
288               
289                beam.Construct(box, dirBox);
290
291                // collect kd leaves and view cells
292                mKdTree->CastBeam(beam);
293                vm->CastBeam(beam);
294
295                Debug << "found " << (int)beam.mViewCells.size() << " view cells and "
296                          << (int)beam.mKdNodes.size() << " kd nodes" << endl;
297
298                BeamSampleStatistics stats;
299// §§matt
300/*              renderer->SampleBeamContributions(sourceObj,
301                                                                                  beam,
302                                                                                  200000,
303                                                                                  stats);
304
305                char s[64]; sprintf(s, "shaft%04d.png", i);
306
307                QImage image = renderer->toImage();
308                image.save(s, "PNG");
309                Debug << "beam statistics: " << stats << endl << endl;
310*/
311                if (1)
312                {
313                        AxisAlignedBox3 sbox = mSceneGraph->GetBox();
314                        Vector3 bmin = sbox.Min() - 150.0f;
315                        Vector3 bmax = sbox.Max() + 150.0f;
316                        AxisAlignedBox3 vbox(bmin, bmax);
317               
318                        exporter->ExportBeam(beam, vbox);
319                }
320
321                bool exportViewCells = false;
322                if (exportViewCells)
323                {
324                        ViewCellContainer::const_iterator it, it_end = beam.mViewCells.end();
325                       
326                        for (it = beam.mViewCells.begin(); it != beam.mViewCells.end(); ++ it)
327                        {
328                                BspNodeGeometry geom;
329                                AxisAlignedBox3 vbox;
330                                vbox.Initialize();
331                                vbox.Include((*it)->GetMesh());
332                       
333                                exporter->SetWireframe();
334                                exporter->ExportBox(vbox);
335                                exporter->SetFilled();
336                                exporter->ExportViewCell(*it);
337                        }
338
339                        /*vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
340                       
341                        for (it = beam.mKdNodes.begin(); it != beam.mKdNodes.end(); ++ it)
342                        {
343                                exporter->ExportBox(mKdTree->GetBox((*it)));
344                        }*/
345                }
346        }
347        /*while (1)
348        { debuggerWidget->repaint();
349        };*/
350        delete exporter;
351}
352
353
354float
355VssPreprocessor::GetAvgPvsSize(VssTree *tree,
356                                                           const vector<AxisAlignedBox3> &viewcells
357                                                           )
358{
359  vector<AxisAlignedBox3>::const_iterator it, it_end = viewcells.end();
360
361  int sum = 0;
362  for (it = viewcells.begin(); it != it_end; ++ it)
363        sum += tree->GetPvsSize(*it);
364
365  return sum/(float)viewcells.size();
366}
367
368bool
369VssPreprocessor::ComputeVisibility()
370{
371        Debug << "type: vss" << endl;
372
373        const long startTime = GetTime();
374        int totalSamples = 0;
375
376        if (mUseViewSpaceBox)
377        {
378                AxisAlignedBox3 viewSpaceBox;
379                viewSpaceBox.Initialize();
380
381                viewSpaceBox = AxisAlignedBox3(mKdTree->GetBox());
382                AxisAlignedBox3 tbox(mViewCellsManager->GetViewSpaceBox());
383
384                const Vector3 size = tbox.Size();
385                viewSpaceBox.SetMax(0, tbox.Max(0) + size[0] * 0.5f);
386                viewSpaceBox.SetMin(0, tbox.Min(0) + size[0]);
387                 
388                // change the view space of the view cells manager
389                mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
390        }
391
392
393        mSceneGraph->CollectObjects(&mObjects);
394
395        if (!mLoadViewCells)
396        {
397                //-- generate new view cells from the scratch
398                //-- for construction the manager uses it's own set of samples
399                ConstructViewCells();
400        }
401#if 0
402        else
403        {       
404                //-- load view cells from file
405                //-- test successful view cells loading by exporting them again
406                VssRayContainer dummies;
407                mViewCellsManager->Visualize(mObjects, dummies);
408                mViewCellsManager->ExportViewCells("test.xml.zip", mViewCellsManager->GetExportPvs(), mObjects);
409        }
410#endif
411
412        VssTree *vssTree = NULL;
413        const long initialTime = GetTime();
414
415        if (mLoadInitialSamples)
416        {
417                cout << "Loading samples from file ... ";
418                LoadSamples(mVssRays, mObjects);
419                cout << "finished\n" << endl;
420                totalSamples = (int)mVssRays.size();
421        }
422        else
423        {
424                while (totalSamples < mInitialSamples) {
425                        int passContributingSamples = 0;
426                        int passSampleContributions = 0;
427                        int passSamples = 0;
428
429                        int index = 0;
430
431                        int sampleContributions;
432
433                        int s = Min(mSamplesPerPass, mInitialSamples);
434                        for (int k=0; k < s; k++)
435                        {
436                                Vector3 viewpoint;
437
438                                mViewCellsManager->GetViewPoint(viewpoint);
439                                const Vector3 direction = GetDirection(viewpoint, &mViewCellsManager->GetViewSpaceBox());
440
441                                const SimpleRay sray(viewpoint, direction);
442                                sampleContributions = mRayCaster->CastRay(sray, mVssRays, mViewCellsManager->GetViewSpaceBox(), true);
443
444                                if (sampleContributions) {
445                                        passContributingSamples ++;
446                                        passSampleContributions += sampleContributions;
447                                }
448                                passSamples++;
449                                totalSamples++;
450                        }
451
452                        mPass++;
453                        int pvsSize = 0;
454                        float avgRayContrib = (passContributingSamples > 0) ?
455                                passSampleContributions/(float)passContributingSamples : 0;
456
457                        cout << "#Pass " << mPass << " : t = " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
458                        cout << "#TotalSamples=" << totalSamples/1000
459                                << "#SampleContributions=" << passSampleContributions << " ("
460                                << 100*passContributingSamples/(float)passSamples<<"%)" << " avgPVS="
461                                << pvsSize/(float)mObjects.size() << endl
462                                << "avg ray contrib=" << avgRayContrib << endl;
463
464                        mStats <<
465                                "#Pass\n" <<mPass<<endl<<
466                                "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl<<
467                                "#TotalSamples\n" << totalSamples<< endl<<
468                                "#SampleContributions\n" << passSampleContributions << endl <<
469                                "#PContributingSamples\n"<<100*passContributingSamples/(float)passSamples<<endl <<
470                                "#AvgPVS\n"<< pvsSize/(float)mObjects.size() << endl <<
471                                "#AvgRayContrib\n" << avgRayContrib << endl;
472                }
473
474                cout << "#totalPvsSize=" << mKdTree->CollectLeafPvs() << endl;
475
476
477
478        }
479
480
481        cout << "#totalRayStackSize=" << (int)mVssRays.size() << endl << flush;
482        Debug << (int)mVssRays.size() << " rays generated in "
483                << TimeDiff(initialTime, GetTime()) * 1e-3 << " seconds" << endl;
484
485        if (mStoreInitialSamples)
486        {
487                cout << "Writing " << (int)mVssRays.size() << " samples to file ... ";
488                ExportSamples(mVssRays);
489                cout << "finished\n" << endl;
490
491                /*VssRayContainer dummyRays;
492                LoadSamples(dummyRays, mObjects);
493                Debug << "rays " << (int)mVssRays.size() << " " << dummyRays.size() << endl;
494
495                for (int i = 0; i < (int)mVssRays.size(); ++ i)
496                {
497                Debug << mVssRays[i]->GetOrigin() << " " << mVssRays[i]->GetTermination() << " " << mVssRays[i]->mOriginObject << " " << mVssRays[i]->mTerminationObject << endl;
498                Debug << dummyRays[i]->GetOrigin() << " " << dummyRays[i]->GetTermination() << " " << dummyRays[i]->mOriginObject << " " << dummyRays[i]->mTerminationObject << endl << endl;
499                }*/
500        }
501
502
503        //int numExportRays = 2000;
504        int numExportRays = 0;
505
506        if (numExportRays) {
507                char filename[64];
508                sprintf(filename, "vss-rays-initial.x3d");
509                ExportRays(filename, mVssRays, numExportRays);
510        }
511
512        vssTree = new VssTree;
513        // viewcells = Construct(mVssRays);
514
515        vssTree->Construct(mVssRays, NULL);
516        cout<<"VssTree root PVS size = "<<vssTree->GetRootPvsSize()<<endl;
517
518        if (0) ExportRays("kdtree.x3d", mVssRays, 10);
519
520        if (0)
521        {
522                ExportVssTree("vss-tree-100.x3d", vssTree, Vector3(1,0,0));
523                ExportVssTree("vss-tree-001.x3d", vssTree, Vector3(0,0,1));
524                ExportVssTree("vss-tree-101.x3d", vssTree, Vector3(1,0,1));
525                ExportVssTree("vss-tree-101m.x3d", vssTree, Vector3(-1,0,-1));
526                ExportVssTreeLeaves(vssTree, 10);
527        }
528
529        // viewcells->UpdatePVS(newVssRays);
530        // get viewcells as kd tree boxes
531        vector<AxisAlignedBox3> kdViewcells;
532        if (0) {
533                vector<KdLeaf *> leaves;
534                mKdTree->CollectLeaves(leaves);
535                vector<KdLeaf *>::const_iterator it;
536                int targetLeaves = 50;
537                float prob = targetLeaves/(float)leaves.size();
538                for (it = leaves.begin(); it != leaves.end(); ++it)
539                        if (RandomValue(0.0f,1.0f) < prob)
540                                kdViewcells.push_back(mKdTree->GetBox(*it));
541
542                float avgPvs = GetAvgPvsSize(vssTree, kdViewcells);
543                cout<<"Initial average PVS size = "<<avgPvs<<endl;
544        }
545
546
547        int samples = 0;
548        int pass = 0;
549
550
551        // cast view cell samples
552        while (samples < mVssSamples)
553        {
554
555                int num = mVssSamplesPerPass;
556                SimpleRayContainer rays;
557                VssRayContainer vssRays;
558
559                if (!mUseImportanceSampling) {
560                        for (int j=0; j < num; j++) {
561                                Vector3 viewpoint;
562                                mViewCellsManager->GetViewPoint(viewpoint);
563                                Vector3 direction = GetDirection(viewpoint, NULL);
564                                rays.push_back(SimpleRay(viewpoint, direction));
565                        }
566                } else {
567                        num = GenerateImportanceRays(vssTree, num, rays);
568                }
569
570                CastRays(rays, vssRays, true);
571                vssTree->AddRays(vssRays);
572
573                if (0) {
574                        int subdivided = vssTree->UpdateSubdivision();
575                        cout<<"subdivided leafs = "<<subdivided<<endl;
576                }
577
578                float avgPvs = GetAvgPvsSize(vssTree, kdViewcells);
579                cout<<"Average PVS size = "<<avgPvs<<endl;
580
581                /// compute view cell contribution of rays
582                mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
583
584                if (numExportRays) {
585                        char filename[64];
586                        if (mUseImportanceSampling)
587                                sprintf(filename, "vss-rays-i%04d.x3d", pass);
588                        else
589                                sprintf(filename, "vss-rays-%04d.x3d", pass);
590
591                        ExportRays(filename, vssRays, numExportRays);
592                }
593
594                samples+=num;
595                float pvs = vssTree->GetAvgPvsSize();
596                cout<<"*****************************\n";
597                cout<<samples<<" avgPVS ="<<pvs<<endl;
598                cout<<"VssTree root PVS size = "<<vssTree->GetRootPvsSize()<<endl;
599                cout<<"*****************************\n";
600                //      if (samples >= mVssSamples) break;
601                pass ++;
602        }
603
604        if (mTestBeamSampling && mUseGlRenderer)
605        {       
606                TestBeamCasting(vssTree, mViewCellsManager, mObjects);
607        }
608
609        if (0)  Debug << vssTree->stat << endl;
610
611        if (0)
612        {
613                VssRayContainer viewCellRays;
614                // compute rays used for view cells construction
615                const int numRays = mViewCellsManager->GetVisualizationSamples();
616                vssTree->CollectRays(viewCellRays, numRays);
617        }
618
619
620        ////////////////////
621        //-- render simulation after construction
622
623        mRenderSimulator->RenderScene();
624        SimulationStatistics ss;
625        mRenderSimulator->GetStatistics(ss);
626        Debug << "\nFinal view cells partition render time\n" << ss << endl;
627        cout << "\nFinal view cells partition render time\n" << ss << endl;
628
629        delete vssTree;
630
631        return true;
632}
633
634}
Note: See TracBrowser for help on using the repository browser.