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

Revision 1272, 24.5 KB checked in by bittner, 18 years ago (diff)

mlrta configuration changes

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