source: trunk/VUT/GtpVisibilityPreprocessor/src/RssPreprocessor.cpp @ 462

Revision 462, 16.3 KB checked in by mattausch, 19 years ago (diff)

worked on vsp kd view cells

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
14static bool useViewSpaceBox = true;
15static bool use2dSampling = false;
16static bool fromBoxVisibility = true;
17
18static bool exportPvs = false;
19static int numExportRays = 10000;
20// static int numExportRays = 0;
21
22RssPreprocessor::RssPreprocessor():
23  mPass(0),
24  mVssRays()
25{
26  // this should increase coherence of the samples
27  environment->GetIntValue("RssPreprocessor.samplesPerPass", mSamplesPerPass);
28  environment->GetIntValue("RssPreprocessor.initialSamples", mInitialSamples);
29  environment->GetIntValue("RssPreprocessor.vssSamples", mRssSamples);
30  environment->GetIntValue("RssPreprocessor.vssSamplesPerPass", mRssSamplesPerPass);
31  environment->GetBoolValue("RssPreprocessor.useImportanceSampling", mUseImportanceSampling);
32  environment->GetIntValue("BspTree.Construction.samples", mBspConstructionSamples);
33       
34  mStats.open("stats.log");
35}
36
37RssPreprocessor::~RssPreprocessor()
38{
39  CLEAR_CONTAINER(mVssRays);
40}
41
42void
43RssPreprocessor::SetupRay(Ray &ray,
44                                                  const Vector3 &point,
45                                                  const Vector3 &direction
46                                                  )
47{
48  ray.intersections.clear();
49  // do not store anything else then intersections at the ray
50  ray.Init(point, direction, Ray::LOCAL_RAY);
51}
52
53int
54RssPreprocessor::CastRay(
55                                                 Vector3 &viewPoint,
56                                                 Vector3 &direction,
57                                                 VssRayContainer &vssRays
58                                                 )
59{
60  int hits = 0;
61  static Ray ray;
62  AxisAlignedBox3 box = mKdTree->GetBox();
63
64  AxisAlignedBox3 sbox = box;
65  sbox.Enlarge(Vector3(-Limits::Small));
66  if (!sbox.IsInside(viewPoint))
67        return 0;
68       
69  SetupRay(ray, viewPoint, direction);
70  // cast ray to KD tree to find intersection with other objects
71  Intersectable *objectA, *objectB;
72  Vector3 pointA, pointB;
73  float bsize = Magnitude(box.Size());
74 
75  if (mKdTree->CastRay(ray)) {
76        objectA = ray.intersections[0].mObject;
77        pointA = ray.Extrap(ray.intersections[0].mT);
78  } else {
79        objectA = NULL;
80        // compute intersection with the scene bounding box
81        float tmin, tmax;
82        box.ComputeMinMaxT(ray, &tmin, &tmax);
83        if (tmax > bsize) {
84          //cerr<<"Warning: tmax > box size tmax="<<tmax<<" tmin="<<tmin<<" size="<<bsize<<endl;
85          //cerr<<"ray"<<ray<<endl;
86        }
87        pointA = ray.Extrap(tmax);
88  }
89
90  bool detectEmptyViewSpace = true;
91       
92  if (detectEmptyViewSpace) {
93        SetupRay(ray, pointA, -direction);
94  } else
95        SetupRay(ray, viewPoint, -direction);
96       
97       
98  if (mKdTree->CastRay(ray)) {
99        objectB = ray.intersections[0].mObject;
100        pointB = ray.Extrap(ray.intersections[0].mT);
101  } else {
102        objectB = NULL;
103        float tmin, tmax;
104        box.ComputeMinMaxT(ray, &tmin, &tmax);
105        if (tmax > bsize) {
106          //cerr<<"Warning: tmax > box size tmax="<<tmax<<" tmin="<<tmin<<" size="<<bsize<<endl;
107          //cerr<<"ray"<<ray<<endl;
108        }
109        pointB = ray.Extrap(tmax);
110  }
111
112  VssRay *vssRay  = NULL;
113
114  bool validSample = true;
115  if (detectEmptyViewSpace) {
116        // check if the viewpoint lies on the line segment AB
117        if (Distance(pointA, pointB) <
118                Distance(viewPoint, pointA) + Distance(viewPoint, pointB) - Limits::Small) {
119          validSample = false;
120        }
121  }
122       
123  if (validSample) {
124        if (objectA) {
125          vssRay = new VssRay(pointB,
126                                                  pointA,
127                                                  objectB,
128                                                  objectA);
129          vssRays.push_back(vssRay);
130          hits ++;
131        }
132       
133        if (objectB) {
134          vssRay = new VssRay(pointA,
135                                                  pointB,
136                                                  objectA,
137                                                  objectB);
138          vssRays.push_back(vssRay);
139          hits ++;
140        }
141  }
142       
143  return hits;
144}
145
146
147Vector3
148RssPreprocessor::GetViewpoint(AxisAlignedBox3 *viewSpaceBox)
149{
150  AxisAlignedBox3 box;
151       
152  if (viewSpaceBox)
153        box =*viewSpaceBox;
154  else
155        box = mKdTree->GetBox();
156       
157  // shrink the box in the y direction
158  return box.GetRandomPoint();
159}
160
161Vector3
162RssPreprocessor::GetDirection(const Vector3 &viewpoint,
163                                                          AxisAlignedBox3 *viewSpaceBox
164                                                          )
165{
166  Vector3 point;
167  if (!use2dSampling) {
168        Vector3 normal;
169        int i = RandomValue(0, mObjects.size()-1);
170        Intersectable *object = mObjects[i];
171        object->GetRandomSurfacePoint(point, normal);
172  } else {
173        AxisAlignedBox3 box;
174               
175        if (viewSpaceBox)
176          box =*viewSpaceBox;
177        else
178          box = mKdTree->GetBox();
179               
180        point = box.GetRandomPoint();
181        point.y = viewpoint.y;
182  }
183       
184  return point - viewpoint;
185}
186
187int
188RssPreprocessor::GenerateImportanceRays(RssTree *rssTree,
189                                                                                const int desiredSamples,
190                                                                                SimpleRayContainer &rays
191                                                                                )
192{
193  int num;
194 
195  float avgPvsSize;
196  float avgRayContribution;
197  float avgPvsEntropy;
198  float avgRayLengthEntropy;
199  float avgImportance;
200 
201  rssTree->GetTreeStatistics(
202                                                         avgPvsSize,
203                                                         avgRayContribution,
204                                                         avgPvsEntropy,
205                                                         avgRayLengthEntropy,
206                                                         avgImportance);
207 
208  cout<<
209        "#AVG_PVS_SIZE\n"<<avgPvsSize<<endl<<
210        "#AVG_RAY_CONTRIB\n"<<avgRayContribution<<endl<<
211        "#AVG_PVS_ENTROPY\n"<<avgPvsEntropy<<endl<<
212        "#AVG_RAY_LENGTH_ENTROPY\n"<<avgRayLengthEntropy<<endl<<
213        "#AVG_IMPORTANCE\n"<<avgImportance<<endl;
214 
215  if (0) {
216        float p = desiredSamples/(float)(avgRayContribution*rssTree->stat.Leaves());
217        num = rssTree->GenerateRays(p, rays);
218  } else {
219        int leaves = rssTree->stat.Leaves()/1;
220        num = rssTree->GenerateRays(desiredSamples, leaves, rays);
221  }
222       
223  cout<<"Generated "<<num<<" rays."<<endl;
224       
225  return num;
226}
227
228
229bool
230RssPreprocessor::ExportRays(const char *filename,
231                                                        const VssRayContainer &vssRays,
232                                                        const int number
233                                                        )
234{
235  cout<<"Exporting vss rays..."<<endl<<flush;
236       
237  float prob = number/(float)vssRays.size();
238
239
240  Exporter *exporter = NULL;
241  exporter = Exporter::GetExporter(filename);
242  //    exporter->SetWireframe();
243  //    exporter->ExportKdTree(*mKdTree);
244  exporter->SetFilled();
245  exporter->ExportScene(mSceneGraph->mRoot);
246  exporter->SetWireframe();
247
248  if (mViewSpaceBox) {
249        exporter->SetForcedMaterial(RgbColor(1,0,1));
250        exporter->ExportBox(*mViewSpaceBox);
251        exporter->ResetForcedMaterial();
252  }
253       
254  VssRayContainer rays; for (int i=0; i < vssRays.size(); i++)
255        if (RandomValue(0,1) < prob)
256          rays.push_back(vssRays[i]);
257
258  exporter->ExportRays(rays, RgbColor(1, 0, 0));
259       
260  delete exporter;
261
262  cout<<"done."<<endl<<flush;
263
264  return true;
265}
266
267
268bool
269RssPreprocessor::ExportRssTree(char *filename,
270                                                           RssTree *tree,
271                                                           const Vector3 &dir
272                                                           )
273{
274  Exporter *exporter = Exporter::GetExporter(filename);
275  exporter->SetFilled();
276  exporter->ExportScene(mSceneGraph->mRoot);
277  //  exporter->SetWireframe();
278  bool result = exporter->ExportRssTree2( *tree, dir );
279  delete exporter;
280  return result;
281}
282
283bool
284RssPreprocessor::ExportRssTreeLeaf(char *filename,
285                                                                   RssTree *tree,
286                                                                   RssTreeLeaf *leaf)
287{
288  Exporter *exporter = NULL;
289  exporter = Exporter::GetExporter(filename);
290  exporter->SetWireframe();
291  exporter->ExportKdTree(*mKdTree);
292       
293  if (mViewSpaceBox) {
294        exporter->SetForcedMaterial(RgbColor(1,0,0));
295        exporter->ExportBox(*mViewSpaceBox);
296        exporter->ResetForcedMaterial();
297  }
298       
299  exporter->SetForcedMaterial(RgbColor(0,0,1));
300  exporter->ExportBox(tree->GetBBox(leaf));
301  exporter->ResetForcedMaterial();
302       
303  VssRayContainer rays[4];
304  for (int i=0; i < leaf->rays.size(); i++) {
305        int k = leaf->rays[i].GetRayClass();
306        rays[k].push_back(leaf->rays[i].mRay);
307  }
308       
309  // SOURCE RAY
310  exporter->ExportRays(rays[0], RgbColor(1, 0, 0));
311  // TERMINATION RAY
312  exporter->ExportRays(rays[1], RgbColor(1, 1, 1));
313  // PASSING_RAY
314  exporter->ExportRays(rays[2], RgbColor(1, 1, 0));
315  // CONTAINED_RAY
316  exporter->ExportRays(rays[3], RgbColor(0, 0, 1));
317
318  delete exporter;
319  return true;
320}
321
322void
323RssPreprocessor::ExportRssTreeLeaves(RssTree *tree, const int number)
324{
325  vector<RssTreeLeaf *> leaves;
326  tree->CollectLeaves(leaves);
327
328  int num = 0;
329  int i;
330  float p = number / (float)leaves.size();
331  for (i=0; i < leaves.size(); i++) {
332        if (RandomValue(0,1) < p) {
333          char filename[64];
334          sprintf(filename, "rss-leaf-%04d.x3d", num);
335          ExportRssTreeLeaf(filename, tree, leaves[i]);
336          num++;
337        }
338        if (num >= number)
339          break;
340  }
341}
342
343
344float
345RssPreprocessor::GetAvgPvsSize(RssTree *tree,
346                                                           const vector<AxisAlignedBox3> &viewcells
347                                                           )
348{
349  vector<AxisAlignedBox3>::const_iterator it, it_end = viewcells.end();
350
351  int sum = 0;
352  for (it = viewcells.begin(); it != it_end; ++ it)
353        sum += tree->GetPvsSize(*it);
354       
355  return sum/(float)viewcells.size();
356}
357
358
359void
360RssPreprocessor::ExportPvs(char *filename,
361                                                   RssTree *rssTree
362                                                   )
363{
364  ObjectContainer pvs;
365  if (rssTree->CollectRootPvs(pvs)) {
366        Exporter *exporter = Exporter::GetExporter(filename);
367        exporter->SetFilled();
368        exporter->ExportGeometry(pvs);
369        exporter->SetWireframe();
370        exporter->ExportBox(rssTree->bbox);
371        exporter->ExportViewpoint(rssTree->bbox.Center(), Vector3(1,0,0));
372        delete exporter;
373  }
374}
375
376bool
377RssPreprocessor::ComputeVisibility()
378{
379 
380  mSceneGraph->CollectObjects(&mObjects);
381       
382  long startTime = GetTime();
383 
384  int totalSamples = 0;
385
386  /// Rays used for post processing and visualizations.
387  RayContainer storedRays;
388
389  AxisAlignedBox3 *box = new AxisAlignedBox3(mKdTree->GetBox());
390
391  if (fromBoxVisibility) {
392        float m = box->Min(1);
393        float bsize = box->Size(1);
394
395        float size = 0.02f;
396        float s = 0.5f - size;
397        float olds = Magnitude(box->Size());
398        box->Enlarge(box->Size()*Vector3(-s));
399        //      Vector3 translation = Vector3(-olds*0.2f, 0, 0);
400        Vector3 translation = Vector3(-0.05*olds, 0, 0);
401        box->SetMin(box->Min() + translation);
402        box->SetMax(box->Max() + translation);
403
404        box->SetMin(1,  m + bsize*0.1);
405        box->SetMax(1,  m + bsize*0.6);
406
407       
408  } else {
409               
410        // sample city like heights
411        float m = box->Min(1);
412        float bsize = box->Size(1);
413        box->SetMin(1,  m + bsize*0.2);
414        box->SetMax(1,  m + bsize*0.3);
415  }
416
417  if (use2dSampling)
418        box->SetMax(1, box->Min(1));
419       
420  if (useViewSpaceBox)
421        mViewSpaceBox = box;
422  else
423        mViewSpaceBox = NULL;
424               
425
426  RssTree *rssTree = NULL;
427
428  while (totalSamples < mInitialSamples) {
429        int passContributingSamples = 0;
430        int passSampleContributions = 0;
431        int passSamples = 0;
432        int index = 0;
433               
434        int sampleContributions;
435               
436        int s = Min(mSamplesPerPass, mInitialSamples);
437        for (int k=0; k < s; k++) {
438                       
439          Vector3 viewpoint = GetViewpoint(mViewSpaceBox);
440          Vector3 direction = GetDirection(viewpoint, mViewSpaceBox);
441                       
442          sampleContributions = CastRay(viewpoint, direction, mVssRays);
443                       
444                       
445          //-- CORR matt: put block inside loop
446          if (sampleContributions) {
447                passContributingSamples ++;
448                passSampleContributions += sampleContributions;
449          }
450          passSamples++;
451          totalSamples++;
452        }
453   
454        mPass++;
455               
456        int pvsSize = 0;
457        float avgRayContrib = (passContributingSamples > 0) ?
458          passSampleContributions/(float)passContributingSamples : 0;
459               
460        cout << "#Pass " << mPass << " : t = " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
461        cout << "#TotalSamples=" << totalSamples/1000
462                 << "k   #SampleContributions=" << passSampleContributions << " ("
463                 << 100*passContributingSamples/(float)passSamples<<"%)" << " avgPVS="
464                 << pvsSize/(float)mObjects.size() << endl
465                 << "avg ray contrib=" << avgRayContrib << endl;
466               
467        mStats <<
468          "#Pass\n" <<mPass<<endl<<
469          "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl<<
470          "#TotalSamples\n" << totalSamples<< endl<<
471          "#SampleContributions\n" << passSampleContributions << endl <<
472          "#PContributingSamples\n"<<100*passContributingSamples/(float)passSamples<<endl <<
473          "#AvgPVS\n"<< pvsSize/(float)mObjects.size() << endl <<
474          "#AvgRayContrib\n" << avgRayContrib << endl;
475  }
476 
477  cout << "#totalPvsSize=" << mKdTree->CollectLeafPvs() << endl;
478  cout << "#totalRayStackSize=" << mVssRays.size() << endl <<flush;
479 
480
481  if (numExportRays) {
482        char filename[64];
483        sprintf(filename, "rss-rays-initial.x3d");
484        ExportRays(filename, mVssRays, numExportRays);
485  }
486 
487
488  // construct view cells
489  mViewCellsManager->Construct(mObjects, mVssRays, mViewSpaceBox);
490
491  rssTree = new RssTree;
492  // viewcells = Construct(mVssRays);
493       
494  if (fromBoxVisibility)
495        rssTree->Construct(mVssRays, mViewSpaceBox);
496  else
497        rssTree->Construct(mVssRays, NULL);
498
499  cout<<"RssTree root PVS size = "<<rssTree->GetRootPvsSize()<<endl;
500 
501  ExportRssTree("rss-tree-100.x3d", rssTree, Vector3(1,0,0));
502  ExportRssTree("rss-tree-001.x3d", rssTree, Vector3(0,0,1));
503  ExportRssTree("rss-tree-101.x3d", rssTree, Vector3(1,0,1));
504  ExportRssTree("rss-tree-101m.x3d", rssTree, Vector3(-1,0,-1));
505
506  ExportRssTreeLeaves(rssTree, 10);
507
508  if (exportPvs) {
509        ExportPvs("rss-pvs-initial.x3d", rssTree);
510  }
511
512  // viewcells->UpdatePVS(newVssRays);
513  // get viewcells as kd tree boxes
514  vector<AxisAlignedBox3> kdViewcells;
515  if (0) {
516        vector<KdLeaf *> leaves;
517        mKdTree->CollectLeaves(leaves);
518        vector<KdLeaf *>::const_iterator it;
519        int targetLeaves = 50;
520        float prob = targetLeaves/(float)leaves.size();
521        for (it = leaves.begin(); it != leaves.end(); ++it)
522          if (RandomValue(0.0f,1.0f) < prob)
523                kdViewcells.push_back(mKdTree->GetBox(*it));
524               
525        float avgPvs = GetAvgPvsSize(rssTree, kdViewcells);
526        cout<<"Initial average PVS size = "<<avgPvs<<endl;
527  }
528
529       
530  int samples = 0;
531  int pass = 0;
532  while (1) {
533        int num = mRssSamplesPerPass;
534        SimpleRayContainer rays;
535        VssRayContainer vssRays;
536               
537        if (!mUseImportanceSampling) {
538          for (int j=0; j < num; j++) {
539                Vector3 viewpoint = GetViewpoint(mViewSpaceBox);
540                Vector3 direction = GetDirection(viewpoint, mViewSpaceBox);
541                rays.push_back(SimpleRay(viewpoint, direction));
542          }
543        } else {
544          num = GenerateImportanceRays(rssTree, num, rays);
545        }
546               
547               
548        for (int i=0; i < rays.size(); i++)
549          CastRay(rays[i].mOrigin, rays[i].mDirection, vssRays);
550               
551        rssTree->AddRays(vssRays);
552               
553        if (1) {
554          int subdivided = rssTree->UpdateSubdivision();
555          cout<<"subdivided leafs = "<<subdivided<<endl;
556          cout<<"#total leaves = "<<rssTree->stat.Leaves()<<endl;
557
558        }
559
560        float avgPvs = GetAvgPvsSize(rssTree, kdViewcells);
561        cout<<"Average PVS size = "<<avgPvs<<endl;
562
563        if (numExportRays) {
564          char filename[64];
565          if (mUseImportanceSampling)
566                sprintf(filename, "rss-rays-i%04d.x3d", pass);
567          else
568                sprintf(filename, "rss-rays-%04d.x3d", pass);
569         
570          ExportRays(filename, vssRays, numExportRays);
571        }
572
573        //-- prepare traversal rays for view cell intersections
574        RayContainer passRays;
575
576        VssRayContainer::const_iterator it, it_end = vssRays.end();
577       
578        for (it = vssRays.begin(); it != it_end; ++ it)
579                passRays.push_back(new Ray(*(*it)));
580       
581        int sampleContributions = 0;
582        int contributingSamples = 0;
583
584        /// compute view cell contribution of rays
585        mViewCellsManager->ComputeSampleContributions(passRays,
586                                                                                                  sampleContributions,
587                                                                                                  contributingSamples);
588       
589        //-- save rays for post processing
590        if (((int)storedRays.size() < mViewCellsManager->GetPostProcessSamples()) ||
591                ((int)storedRays.size() < mViewCellsManager->GetVisualizationSamples()))
592        {
593                RayContainer::const_iterator it, it_end = passRays.end();
594
595                for (it = passRays.begin(); it != it_end; ++ it)
596                        storedRays.push_back(new Ray(*(*it)));
597        }
598        else
599        {
600                CLEAR_CONTAINER(passRays);
601        }
602
603        samples+=num;
604        float pvs = rssTree->GetAvgPvsSize();
605        cout<<"*****************************\n";
606        cout<<samples<<" avgPVS ="<<pvs<<endl;
607        cout<<"sample contributions ="<<sampleContributions<<endl;
608        cout<<"contributing sample ="<<contributingSamples<<endl;
609        cout<<"RssTree root PVS size = "<<rssTree->GetRootPvsSize()<<endl;
610        cout<<"*****************************\n";
611
612        if (exportPvs) {
613          char filename[64];
614          sprintf(filename, "rss-pvs-%04d.x3d", pass);
615          ExportPvs(filename, rssTree);
616        }
617
618        if (samples >= mRssSamples)
619          break;
620
621       
622        pass++;
623  }
624 
625  //-- post process view cells
626  mViewCellsManager->PostProcess(mObjects, storedRays);
627
628  //-- several visualizations and statistics
629  mViewCellsManager->PrintStatistics(Debug);
630
631  //-- render simulation after merge
632  cout << "\nevaluating render time of final view cells ... ";
633                 
634  const SimulationStatistics ss = mViewCellsManager->SimulateRendering();
635                 
636  cout << " finished" << endl;
637
638  cout << ss << endl;
639  Debug << ss << endl;
640
641  mViewCellsManager->Visualize(mObjects, storedRays);
642
643  delete rssTree;
644 
645  return true;
646}
647
Note: See TracBrowser for help on using the repository browser.