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

Revision 468, 14.6 KB checked in by mattausch, 19 years ago (diff)

updated rendersimulator

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