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

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