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

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