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

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