source: GTP/trunk/Lib/Vis/Preprocessing/src/RssPreprocessor.cpp @ 1867

Revision 1867, 23.8 KB checked in by bittner, 18 years ago (diff)

merge, global lines, rss sampling updates

Line 
1#include "SceneGraph.h"
2#include "KdTree.h"
3#include "RssPreprocessor.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 "RssTree.h"
11#include "ViewCellsManager.h"
12#include "RenderSimulator.h"
13#include "GlRenderer.h"
14#include "SamplingStrategy.h"
15#include "PreprocessorThread.h"
16
17
18namespace GtpVisibilityPreprocessor {
19
20
21  const bool pruneRays = false;
22 
23
24
25#define ADD_RAYS_IN_PLACE 1
26 
27RssPreprocessor::RssPreprocessor():
28  mVssRays()
29{
30  // this should increase coherence of the samples
31  Environment::GetSingleton()->GetIntValue("RssPreprocessor.samplesPerPass", mSamplesPerPass);
32  Environment::GetSingleton()->GetIntValue("RssPreprocessor.initialSamples", mInitialSamples);
33  Environment::GetSingleton()->GetIntValue("RssPreprocessor.vssSamples", mRssSamples);
34  Environment::GetSingleton()->GetIntValue("RssPreprocessor.vssSamplesPerPass", mRssSamplesPerPass);
35  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useImportanceSampling", mUseImportanceSampling);
36
37  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useRssTree",
38                                                                                        mUseRssTree);
39
40  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.pvs", mExportPvs);
41  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.rssTree", mExportRssTree);
42  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.Export.rays", mExportRays);
43  Environment::GetSingleton()->GetIntValue("RssPreprocessor.Export.numRays", mExportNumRays);
44  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.useViewcells", mUseViewcells);
45  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.objectBasedSampling", mObjectBasedSampling);
46  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.directionalSampling", mDirectionalSampling);
47
48  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.loadInitialSamples", mLoadInitialSamples);
49
50  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.storeInitialSamples", mStoreInitialSamples);
51
52  Environment::GetSingleton()->GetBoolValue("RssPreprocessor.updateSubdivision", mUpdateSubdivision);
53 
54  mRssTree = NULL;
55}
56
57
58int
59RssPreprocessor::GenerateRays(
60                                                          const int number,
61                                                          SamplingStrategy &strategy,
62                                                          SimpleRayContainer &rays)
63{
64  int result = 0;
65 
66  Debug<<"Generate rays...\n"<<flush;
67
68  switch (strategy.mType) {
69  case SamplingStrategy::RSS_BASED_DISTRIBUTION:
70  case SamplingStrategy::RSS_SILHOUETTE_BASED_DISTRIBUTION:
71                if (mRssTree) {
72                  result = GenerateImportanceRays(mRssTree, number, rays);
73                }
74                break;
75               
76  default:
77        result = Preprocessor::GenerateRays(number, strategy, rays);
78  }
79 
80  //  rays.NormalizePdf();
81  Debug<<"done.\n"<<flush;
82
83  return result;
84}
85
86
87
88
89RssPreprocessor::~RssPreprocessor()
90{
91  // mVssRays get deleted in the tree
92  //  CLEAR_CONTAINER(mVssRays);
93}
94
95
96
97void
98RssPreprocessor::ExportObjectRays(VssRayContainer &rays,
99                                                                  const int objectId)
100{
101  ObjectContainer::const_iterator oi;
102
103  Intersectable *object = NULL;
104  for (oi = mObjects.begin(); oi != mObjects.end(); ++oi)
105        if (objectId == (*oi)->GetId()) {
106          object = *oi;
107          break;
108        }
109
110  if (object == NULL)
111        return;
112 
113  VssRayContainer selectedRays;
114  VssRayContainer::const_iterator it= rays.begin(), it_end = rays.end();
115
116 
117  for (; it != it_end; ++it) {
118        if ((*it)->mTerminationObject == object)
119          selectedRays.push_back(*it);
120  }
121 
122
123  Exporter *exporter = Exporter::GetExporter("object-rays.x3d");
124  //    exporter->SetWireframe();
125  //    exporter->ExportKdTree(*mKdTree);
126  exporter->SetFilled();
127  exporter->ExportIntersectable(object);
128  exporter->ExportRays(selectedRays, RgbColor(1, 0, 0));
129 
130  delete exporter;
131 
132}
133
134
135int
136RssPreprocessor::GenerateImportanceRays(RssTree *rssTree,
137                                                                                const int desiredSamples,
138                                                                                SimpleRayContainer &rays
139                                                                                )
140{
141  int num;
142
143  rssTree->UpdateTreeStatistics();
144
145  cout<<
146        "#RSS_AVG_PVS_SIZE\n"<<rssTree->stat.avgPvsSize<<endl<<
147        "#RSS_AVG_RAYS\n"<<rssTree->stat.avgRays<<endl<<
148        "#RSS_AVG_RAY_CONTRIB\n"<<rssTree->stat.avgRayContribution<<endl<<
149        "#RSS_AVG_PVS_ENTROPY\n"<<rssTree->stat.avgPvsEntropy<<endl<<
150        "#RSS_AVG_RAY_LENGTH_ENTROPY\n"<<rssTree->stat.avgRayLengthEntropy<<endl<<
151        "#RSS_AVG_IMPORTANCE\n"<<rssTree->stat.avgImportance<<endl;
152 
153  if (0) {
154        float p = desiredSamples/(float)(rssTree->stat.avgRayContribution*rssTree->stat.Leaves());
155        num = rssTree->GenerateRays(p, rays);
156  } else {
157        int leaves = rssTree->stat.Leaves()/1;
158       
159        num = rssTree->GenerateRays(desiredSamples, leaves, rays);
160  }
161       
162       
163  return num;
164}
165
166
167bool
168RssPreprocessor::ExportRays(const char *filename,
169                                                        const VssRayContainer &vssRays,
170                                                        const int number
171                                                        )
172{
173  cout<<"Exporting vss rays..."<<endl<<flush;
174       
175  Exporter *exporter = NULL;
176  exporter = Exporter::GetExporter(filename);
177  if (0) {
178        exporter->SetWireframe();
179        exporter->ExportKdTree(*mKdTree);
180  }
181  exporter->SetFilled();
182  // $$JB temporarily do not export the scene
183  if (0)
184        exporter->ExportScene(mSceneGraph->GetRoot());
185  exporter->SetWireframe();
186
187  if (1) {
188        exporter->SetForcedMaterial(RgbColor(1,0,1));
189        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
190        exporter->ResetForcedMaterial();
191  }
192 
193  VssRayContainer rays;
194 
195  vssRays.SelectRays(number, rays);
196
197  exporter->ExportRays(rays, RgbColor(1, 0, 0));
198       
199  delete exporter;
200
201  cout<<"done."<<endl<<flush;
202
203  return true;
204}
205
206bool
207RssPreprocessor::ExportRayAnimation(const char *filename,
208                                                                        const vector<VssRayContainer> &vssRays
209                                                                        )
210{
211  cout<<"Exporting vss rays..."<<endl<<flush;
212       
213  Exporter *exporter = NULL;
214  exporter = Exporter::GetExporter(filename);
215  if (0) {
216        exporter->SetWireframe();
217        exporter->ExportKdTree(*mKdTree);
218  }
219  exporter->SetFilled();
220  // $$JB temporarily do not export the scene
221  if (1)
222        exporter->ExportScene(mSceneGraph->GetRoot());
223  exporter->SetWireframe();
224
225  if (1) {
226        exporter->SetForcedMaterial(RgbColor(1,0,1));
227        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
228        exporter->ResetForcedMaterial();
229  }
230 
231  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
232       
233  delete exporter;
234
235  cout<<"done."<<endl<<flush;
236
237  return true;
238}
239
240
241bool
242RssPreprocessor::ExportRssTree(char *filename,
243                                                           RssTree *tree,
244                                                           const Vector3 &dir
245                                                           )
246{
247  Exporter *exporter = Exporter::GetExporter(filename);
248  exporter->SetFilled();
249  exporter->ExportScene(mSceneGraph->GetRoot());
250  //  exporter->SetWireframe();
251  bool result = exporter->ExportRssTree2( *tree, dir );
252  delete exporter;
253  return result;
254}
255
256bool
257RssPreprocessor::ExportRssTreeLeaf(char *filename,
258                                                                   RssTree *tree,
259                                                                   RssTreeLeaf *leaf)
260{
261  Exporter *exporter = NULL;
262  exporter = Exporter::GetExporter(filename);
263  exporter->SetWireframe();
264  exporter->ExportKdTree(*mKdTree);
265       
266  exporter->SetForcedMaterial(RgbColor(0,0,1));
267  exporter->ExportBox(tree->GetBBox(leaf));
268  exporter->ResetForcedMaterial();
269       
270  VssRayContainer rays[4];
271  for (int i=0; i < leaf->rays.size(); i++) {
272        int k = leaf->rays[i].GetRayClass();
273        rays[k].push_back(leaf->rays[i].mRay);
274  }
275       
276  // SOURCE RAY
277  exporter->ExportRays(rays[0], RgbColor(1, 0, 0));
278  // TERMINATION RAY
279  exporter->ExportRays(rays[1], RgbColor(1, 1, 1));
280  // PASSING_RAY
281  exporter->ExportRays(rays[2], RgbColor(1, 1, 0));
282  // CONTAINED_RAY
283  exporter->ExportRays(rays[3], RgbColor(0, 0, 1));
284
285  delete exporter;
286  return true;
287}
288
289void
290RssPreprocessor::ExportRssTreeLeaves(RssTree *tree, const int number)
291{
292  vector<RssTreeLeaf *> leaves;
293  tree->CollectLeaves(leaves);
294
295  int num = 0;
296  int i;
297  float p = number / (float)leaves.size();
298  for (i=0; i < leaves.size(); i++) {
299        if (RandomValue(0,1) < p) {
300          char filename[64];
301          sprintf(filename, "rss-leaf-%04d.x3d", num);
302          ExportRssTreeLeaf(filename, tree, leaves[i]);
303          num++;
304        }
305        if (num >= number)
306          break;
307  }
308}
309
310
311float
312RssPreprocessor::GetAvgPvsSize(RssTree *tree,
313                                                           const vector<AxisAlignedBox3> &viewcells
314                                                           )
315{
316  vector<AxisAlignedBox3>::const_iterator it, it_end = viewcells.end();
317
318  int sum = 0;
319  for (it = viewcells.begin(); it != it_end; ++ it)
320        sum += tree->GetPvsSize(*it);
321       
322  return sum/(float)viewcells.size();
323}
324
325
326void
327RssPreprocessor::ExportPvs(char *filename,
328                                                   RssTree *rssTree
329                                                   )
330{
331  ObjectContainer pvs;
332  if (rssTree->CollectRootPvs(pvs)) {
333        Exporter *exporter = Exporter::GetExporter(filename);
334        exporter->SetFilled();
335        exporter->ExportGeometry(pvs);
336        exporter->SetWireframe();
337        exporter->ExportBox(rssTree->bbox);
338        exporter->ExportViewpoint(rssTree->bbox.Center(), Vector3(1,0,0));
339        delete exporter;
340  }
341}
342
343
344void
345RssPreprocessor::ComputeRenderError()
346{
347  // compute rendering error
348       
349  if (renderer && renderer->mPvsStatFrames) {
350        //      emit EvalPvsStat();
351        //      QMutex mutex;
352        //      mutex.lock();
353        //      renderer->mRenderingFinished.wait(&mutex);
354        //      mutex.unlock();
355       
356        renderer->EvalPvsStat();
357
358        mStats <<
359          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
360          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
361          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
362          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
363  }
364}
365
366void
367NormalizeRatios(vector<SamplingStrategy *> &distributions)
368{
369  int i;
370  float sumRatios = 0.0f;
371 
372  for (i=0; i < distributions.size(); i++)
373        sumRatios += distributions[i]->mRatio;
374
375 
376  if (sumRatios == 0.0f) {
377        for (i=0; i < distributions.size(); i++) {
378          distributions[i]->mRatio = 1.0f;
379          sumRatios += 1.0f;
380        }
381  }
382
383  for (i=0 ; i < distributions.size(); i++)
384        distributions[i]->mRatio/=sumRatios;
385
386#define MIN_RATIO 0.1f
387 
388  for (i = 0; i < distributions.size(); i++)
389        if (distributions[i]->mRatio < MIN_RATIO)
390          distributions[i]->mRatio = MIN_RATIO;
391
392
393  sumRatios = 0.0f;
394  for (i=0; i < distributions.size(); i++)
395        sumRatios += distributions[i]->mRatio;
396
397  for (i=0 ; i < distributions.size(); i++)
398        distributions[i]->mRatio/=sumRatios;
399 
400 
401  cout<<"New ratios: ";
402  for (i=0 ; i < distributions.size(); i++)
403        cout<<distributions[i]->mRatio<<" ";
404  cout<<endl;
405}
406
407void
408EvaluateRatios(vector<SamplingStrategy *> &distributions)
409{
410  // now evaluate the ratios for the next pass
411#define TIME_WEIGHT 0.0f
412  for (int i=0; i < distributions.size(); i++) {
413        distributions[i]->mRatio = distributions[i]->mContribution/
414          (TIME_WEIGHT*distributions[i]->mTime +
415           (1 - TIME_WEIGHT)*distributions[i]->mRays);
416
417#if 1
418        distributions[i]->mRatio = sqr(distributions[i]->mRatio);
419#endif
420  }
421}
422
423
424
425bool
426RssPreprocessor::ComputeVisibility()
427{
428
429  Debug << "type: rss" << endl;
430
431  cout<<"Rss Preprocessor started\n"<<flush;
432  //  cout<<"Memory/ray "<<sizeof(VssRay)+sizeof(RssTreeNode::RayInfo)<<endl;
433
434  Randomize(0);
435
436  if (1) {
437        Exporter *exporter = Exporter::GetExporter("samples.wrl");
438    exporter->SetFilled();
439        Halton<4> halton;
440
441//      for (int i=1; i < 7; i++)
442//        cout<<i<<" prime= "<<FindPrime(i)<<endl;
443       
444        Material mA, mB;
445        mA.mDiffuseColor = RgbColor(1, 0, 0);
446        mB.mDiffuseColor = RgbColor(0, 1, 0);
447       
448        for (int i=0; i < 10000; i++) {
449          float r[4];
450          halton.GetNext(r);
451          Vector3 v1 = UniformRandomVector(r[0], r[1]);
452          Vector3 v2 = UniformRandomVector(r[2], r[3]);
453
454          const float size =0.002f;
455          AxisAlignedBox3 box(v1-Vector3(size), v1+Vector3(size));
456          exporter->SetForcedMaterial(mA);
457          exporter->ExportBox(box);
458          AxisAlignedBox3 box2(v2-Vector3(size), v2+Vector3(size));
459
460          exporter->SetForcedMaterial(mB);
461          exporter->ExportBox(box2);
462        }
463        delete exporter;
464  }
465 
466 
467  cout<<"COMPUTATION THREAD="<<GetThread()->GetCurrentThreadId()<<endl<<flush;
468 
469  // use ray buffer to export ray animation
470  const bool useRayBuffer = true;
471 
472  vector<VssRayContainer> rayBuffer(50);
473 
474  long startTime = GetTime();
475  long lastTime;
476  float totalTime;
477 
478  int totalSamples = 0;
479
480  // if not already loaded, construct view cells from file
481  if (!mLoadViewCells)
482  {
483          // construct view cells using it's own set of samples
484          mViewCellsManager->Construct(this);
485
486          //-- several visualizations and statistics
487          Debug << "view cells construction finished: " << endl;
488          mViewCellsManager->PrintStatistics(Debug);
489  }
490
491 
492  int rssPass = 0;
493  int rssSamples = 0;
494
495  if (mUseRssTree)
496                mDistributions.push_back(new RssBasedDistribution(*this));
497
498 
499  if (1) {
500        mDistributions.push_back(new SpatialBoxBasedDistribution(*this));
501//      //  mDistributions.push_back(new DirectionBasedDistribution(*this));
502//      mDistributions.push_back(new ObjectDirectionBasedDistribution(*this));
503//      //  mDistributions.push_back(new ReverseObjectBasedDistribution(*this));
504//      mDistributions.push_back(new ObjectBasedDistribution(*this));
505//      mDistributions.push_back(new ReverseViewSpaceBorderBasedDistribution(*this));
506  } else {
507        mDistributions.push_back(new GlobalLinesDistribution(*this));
508        mDistributions.push_back(new SpatialBoxBasedDistribution(*this));
509  }
510 
511  if (mLoadInitialSamples) {
512        cout << "Loading samples from file ... ";
513        LoadSamples(mVssRays, mObjects);
514        cout << "finished\n" << endl;
515  } else {
516        SimpleRayContainer rays;
517       
518        cout<<"Generating initial rays..."<<endl<<flush;
519       
520        if (mUseImportanceSampling) {
521          int count = 0;
522          int i;
523
524          // Generate initial samples
525          for (i=0; i < mDistributions.size(); i++)
526                if (mDistributions[i]->mType != SamplingStrategy::RSS_BASED_DISTRIBUTION)
527                  count++;
528         
529          for (i=0; i < mDistributions.size(); i++)
530                if (mDistributions[i]->mType != SamplingStrategy::RSS_BASED_DISTRIBUTION)
531                  GenerateRays(mInitialSamples/count,
532                                           *mDistributions[i],
533                                           rays);
534         
535        } else {
536          int rayType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
537          if (mObjectBasedSampling)
538                rayType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
539          else
540                if (mDirectionalSampling)
541                  rayType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
542          cout<<"Generating rays..."<<endl;
543
544          Preprocessor::GenerateRays(mRssSamplesPerPass, rayType, rays);
545        }
546       
547       
548        cout<<"Casting initial rays..."<<endl<<flush;
549        CastRays(rays, mVssRays, true, pruneRays);
550
551        ExportObjectRays(mVssRays, 1546);
552  }
553 
554  cout << "#totalRayStackSize=" << (int)mVssRays.size() << endl <<flush;
555 
556  rssSamples += (int)mVssRays.size();
557  totalSamples += mInitialSamples;
558  mPass++;
559 
560  if (mExportRays) {
561       
562        char filename[64];
563        sprintf(filename, "rss-rays-initial.x3d");
564        ExportRays(filename, mVssRays, mExportNumRays);
565
566        if (useRayBuffer)
567          mVssRays.SelectRays(mExportNumRays, rayBuffer[0], true);
568       
569  }
570 
571  if (mStoreInitialSamples) {
572        cout << "Writing samples to file ... ";
573        ExportSamples(mVssRays);
574        cout << "finished\n" << endl;
575  }
576       
577  if (mUseViewcells) {
578
579        cout<<"Computing sample contributions..."<<endl<<flush;
580        // evaluate contributions of the intitial rays
581        mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
582        cout<<"done.\n"<<flush;
583
584        long time = GetTime();
585        totalTime = TimeDiff(startTime, time)*1e-3f;
586        lastTime = time;
587       
588        mStats <<
589          "#Pass\n" <<mPass<<endl<<
590          "#RssPass\n" <<rssPass<<endl<<
591          "#Time\n" << totalTime <<endl<<
592          "#TotalSamples\n" <<totalSamples<<endl<<
593          "#RssSamples\n" <<rssSamples<<endl;
594
595        {
596          VssRayContainer contributingRays;
597          mVssRays.GetContributingRays(contributingRays, 0);
598          mStats<<"#NUM_CONTRIBUTING_RAYS\n"<<(int)contributingRays.size()<<endl;
599          if (mExportRays) {
600                char filename[64];
601                sprintf(filename, "rss-crays-%04d.x3d", 0);
602                ExportRays(filename, contributingRays, mExportNumRays);
603          }
604        }
605       
606         
607        // viewcells->UpdatePVS(newVssRays);
608        Debug<<"Valid viewcells before set validity: "<<mViewCellsManager->CountValidViewcells()<<endl;
609        // cull viewcells with PVS > median (0.5f)
610        //mViewCellsManager->SetValidityPercentage(0, 0.5f);
611        //      mViewCellsManager->SetValidityPercentage(0, 1.0f);
612        Debug<<"Valid viewcells after set validity: "<<mViewCellsManager->CountValidViewcells()<<endl;
613
614        mVssRays.PrintStatistics(mStats);
615        mViewCellsManager->PrintPvsStatistics(mStats);
616
617
618        if (0) {
619          char str[64];
620          sprintf(str, "tmp/v-");
621         
622          // visualization
623          const bool exportRays = true;
624          const bool exportPvs = true;
625          ObjectContainer objects;
626          mViewCellsManager->ExportSingleViewCells(objects,
627                                                                                           1000,
628                                                                                           false,
629                                                                                           exportPvs,
630                                                                                           exportRays,
631                                                                                           10000,
632                                                                                           str);
633        }
634         
635        ComputeRenderError();
636  }
637
638  //  return 1;
639 
640  rssPass++;
641
642        //      mDistributions.resize(1);
643
644  mRssTree = new RssTree;
645  mRssTree->SetPass(mPass);
646 
647  /// compute view cell contribution of rays if view cells manager already constructed
648  //  mViewCellsManager->ComputeSampleContributions(mVssRays, true, false);
649
650  if (mUseImportanceSampling) {
651
652        if (mUseRssTree) {
653          mRssTree->Construct(mObjects, mVssRays);
654       
655          mRssTree->stat.Print(mStats);
656          cout<<"RssTree root PVS size = "<<mRssTree->GetRootPvsSize()<<endl;
657         
658          if (mExportRssTree) {
659                ExportRssTree("rss-tree-100.x3d", mRssTree, Vector3(1,0,0));
660                ExportRssTree("rss-tree-001.x3d", mRssTree, Vector3(0,0,1));
661                ExportRssTree("rss-tree-101.x3d", mRssTree, Vector3(1,0,1));
662                ExportRssTree("rss-tree-101m.x3d", mRssTree, Vector3(-1,0,-1));
663                ExportRssTreeLeaves(mRssTree, 10);
664          }
665        }
666
667        if (mExportPvs) {
668          ExportPvs("rss-pvs-initial.x3d", mRssTree);
669        }
670  }
671
672  // keep only rss
673  mDistributions.resize(1);
674
675  while (1) {
676
677        static SimpleRayContainer rays;
678        static VssRayContainer vssRays;
679        static VssRayContainer tmpVssRays;
680
681        rays.reserve((int)(1.1f*mRssSamplesPerPass));
682
683        rays.clear();
684        vssRays.clear();
685        tmpVssRays.clear();
686
687        int castRays = 0;
688        if (mUseImportanceSampling) {
689
690          NormalizeRatios(mDistributions);
691         
692          long t1;
693
694          for (int i=0; i < mDistributions.size(); i++) {
695                t1 = GetTime();
696                rays.clear();
697                tmpVssRays.clear();
698                if (mDistributions[i]->mRatio != 0) {
699                  GenerateRays(int(mRssSamplesPerPass*mDistributions[i]->mRatio),
700                                           *mDistributions[i],
701                                           rays);
702                 
703                  rays.NormalizePdf((float)rays.size());
704                 
705                  CastRays(rays, tmpVssRays, true, pruneRays);
706                  castRays += (int)rays.size();
707
708                  cout<<"Computing sample contributions..."<<endl<<flush;
709
710#if ADD_RAYS_IN_PLACE
711                  mDistributions[i]->mContribution =
712                        mViewCellsManager->ComputeSampleContributions(tmpVssRays, true, false);
713#else
714                  mDistributions[i]->mContribution =
715                        mViewCellsManager->ComputeSampleContributions(tmpVssRays, false, true);
716#endif
717                  cout<<"done."<<endl;
718                }
719
720                mDistributions[i]->mTime = TimeDiff(t1, GetTime());
721                //              mDistributions[i]->mRays = (int)rays.size();
722                mDistributions[i]->mRays = (int)tmpVssRays.size() + 1;
723                //              mStats<<"#RssRelContrib"<<endl<<contributions[0]/nrays[0]<<endl;
724                vssRays.insert(vssRays.end(), tmpVssRays.begin(), tmpVssRays.end() );
725          }
726
727          EvaluateRatios(mDistributions);
728         
729          // add contributions of all rays at once...
730#if !ADD_RAYS_IN_PLACE
731          mViewCellsManager->AddSampleContributions(vssRays);
732#endif   
733        }
734        else {
735                int rayType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
736          if (mObjectBasedSampling)
737                  rayType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
738          else
739                if (mDirectionalSampling)
740                        rayType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
741
742          cout<<"Generating rays..."<<endl;
743
744          Preprocessor::GenerateRays(mRssSamplesPerPass, rayType, rays);
745          cout<<"done."<<endl;
746
747          cout<<"Casting rays..."<<endl;          CastRays(rays, vssRays, true);
748          cout<<"done."<<endl;
749          castRays += (int)rays.size();
750          if (mUseViewcells) {
751                /// compute view cell contribution of rays
752                cout<<"Computing sample contributions..."<<endl;
753                mViewCellsManager->ComputeSampleContributions(vssRays, true, false);
754                cout<<"done."<<endl;
755          }
756               
757         
758        }
759        totalSamples += castRays;
760        rssSamples += (int)vssRays.size();
761
762        cout<<"Generated "<<castRays<<" rays, progress "<<100.0f*totalSamples/((float) mRssSamples +
763                                                                                                                                                   mInitialSamples)<<"%\n";
764       
765
766        long time = GetTime();
767        totalTime += TimeDiff(lastTime, time);
768        lastTime = time;
769       
770        mStats <<
771          "#Pass\n" <<mPass<<endl<<
772          "#RssPass\n" <<rssPass<<endl<<
773          "#Time\n" << TimeDiff(startTime, GetTime())*1e-3<<endl<<
774          "#TotalSamples\n" <<totalSamples<<endl<<
775          "#RssSamples\n" <<rssSamples<<endl;
776
777
778        if (mUseViewcells) {
779          Debug<<"Print statistics...\n"<<flush;
780          vssRays.PrintStatistics(mStats);
781          mViewCellsManager->PrintPvsStatistics(mStats);
782          Debug<<"done.\n"<<flush;
783        }
784
785
786        if (renderer && mPass > 0) {
787          char buf[100];
788          if (mUseImportanceSampling)
789                {
790                  sprintf(buf, "snap/i-%02d-", mPass);
791                 
792                  renderer->SetSnapPrefix(buf);
793                }
794          else
795                {
796                  sprintf(buf, "snap/r-%02d-", mPass);
797                 
798                  renderer->SetSnapPrefix(buf);
799                }
800         
801          renderer->SetSnapErrorFrames(true);
802        }
803       
804        ComputeRenderError();
805       
806        // epxort rays before adding them to the tree -> some of them can be deleted
807
808        if (mExportRays) {
809          char filename[64];
810          if (mUseImportanceSampling)
811                sprintf(filename, "rss-rays-i%04d.x3d", rssPass);
812          else
813                sprintf(filename, "rss-rays-%04d.x3d", rssPass);
814         
815         
816
817          if (useRayBuffer)
818                vssRays.SelectRays(mExportNumRays, rayBuffer[mPass], true);
819         
820          ExportRays(filename, vssRays, mExportNumRays);
821         
822          // now export all contributing rays
823          VssRayContainer contributingRays;
824          vssRays.GetContributingRays(contributingRays, mPass);
825          mStats<<"#NUM_CONTRIBUTING_RAYS\n"<<(int)contributingRays.size()<<endl;
826          sprintf(filename, "rss-crays-%04d.x3d", rssPass);
827          ExportRays(filename, contributingRays, mExportNumRays);
828        }
829
830       
831        // add rays to the tree after the viewcells have been cast to have their contributions
832        // already when adding into the tree
833        // do not add those rays which have too low or no contribution....
834
835       
836        if (mUseRssTree && mUseImportanceSampling) {
837          Debug<<"Adding rays...\n"<<flush;
838          mRssTree->AddRays(vssRays);
839          Debug<<"done.\n"<<flush;
840          if (mUpdateSubdivision) {
841                int updatePasses = 1;
842                if (mPass % updatePasses == 0) {
843                  Debug<<"Updating rss tree...\n"<<flush;
844                  int subdivided = mRssTree->UpdateSubdivision();
845                  Debug<<"done.\n"<<flush;
846                  cout<<"subdivided leafs = "<<subdivided<<endl;
847                  cout<<"#total leaves = "<<mRssTree->stat.Leaves()<<endl;
848                }
849          }
850        }
851       
852        if (mExportPvs) {
853          char filename[64];
854          sprintf(filename, "rss-pvs-%04d.x3d", rssPass);
855          ExportPvs(filename, mRssTree);
856        }
857       
858       
859        if (!mUseImportanceSampling || !mUseRssTree)
860          CLEAR_CONTAINER(vssRays);
861        // otherwise the rays get deleted by the rss tree update according to RssTree.maxRays ....
862       
863        if (totalSamples >= mRssSamples + mInitialSamples)
864          break;
865       
866       
867        rssPass++;
868        mPass++;
869        mRssTree->SetPass(mPass);
870  }
871 
872  if (mUseViewcells) {
873
874        if(0) {
875          VssRayContainer selectedRays;
876          int desired = mViewCellsManager->GetVisualizationSamples();
877         
878          mVssRays.SelectRays(desired, selectedRays);
879         
880          mViewCellsManager->Visualize(mObjects, selectedRays);
881          }
882       
883        // view cells after sampling
884        mViewCellsManager->PrintStatistics(Debug);
885       
886        EvalViewCellHistogram();
887       
888        //-- render simulation after merge
889        cout << "\nevaluating bsp view cells render time after sampling ... ";
890       
891        mRenderSimulator->RenderScene();
892        SimulationStatistics ss;
893        mRenderSimulator->GetStatistics(ss);
894       
895        cout << " finished" << endl;
896        cout << ss << endl;
897        Debug << ss << endl;
898  }
899
900
901  if (useRayBuffer && mExportRays && mUseImportanceSampling) {
902        char filename[64];
903        sprintf(filename, "rss-rays-i.x3d");
904       
905        rayBuffer.resize(mPass);
906        ExportRayAnimation(filename, rayBuffer);
907  }
908         
909
910  // do not delete rss tree now - can be used for visualization..
911#if 0
912  Debug<<"Deleting RSS tree...\n";
913  delete mRssTree;
914  Debug<<"Done.\n";
915#endif
916
917  //mViewCellsManager->ExportViewCells("visibility.xml",
918  //                                                                     true);
919 
920 
921  return true;
922}
923
924}
Note: See TracBrowser for help on using the repository browser.