source: trunk/VUT/GtpVisibilityPreprocessor/src/VssPreprocessor.cpp @ 501

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