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

Revision 501, 16.2 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
14bool use2dSampling = false;
15bool useViewspacePlane = true;
16
17VssPreprocessor::VssPreprocessor():
18  mPass(0),
19  mVssRays()
20{
21  // this should increase coherence of the samples
22  environment->GetIntValue("VssPreprocessor.samplesPerPass", mSamplesPerPass);
23  environment->GetIntValue("VssPreprocessor.initialSamples", mInitialSamples);
24  environment->GetIntValue("VssPreprocessor.vssSamples", mVssSamples);
25  environment->GetIntValue("VssPreprocessor.vssSamplesPerPass", mVssSamplesPerPass);
26  environment->GetBoolValue("VssPreprocessor.useImportanceSampling", mUseImportanceSampling);
27
28  environment->GetBoolValue("VssPreprocessor.loadInitialSamples", mLoadInitialSamples);
29  environment->GetBoolValue("VssPreprocessor.storeInitialSamples", mStoreInitialSamples);
30  environment->GetBoolValue("VssPreprocessor.useViewSpaceBox", mUseViewSpaceBox);
31
32  mStats.open("stats.log");
33}
34
35VssPreprocessor::~VssPreprocessor()
36{
37  CLEAR_CONTAINER(mVssRays);
38}
39
40void
41VssPreprocessor::SetupRay(Ray &ray,
42                                                  const Vector3 &point,
43                                                  const Vector3 &direction
44                                                  )
45{
46  ray.Clear();
47  // do not store anything else then intersections at the ray
48  ray.Init(point, direction, Ray::LOCAL_RAY);
49}
50
51int
52VssPreprocessor::CastRay(
53                                                 Vector3 &viewPoint,
54                                                 Vector3 &direction,
55                                                 VssRayContainer &vssRays
56                                                 )
57{
58
59    int hits = 0;
60  static Ray ray;
61  AxisAlignedBox3 box = mKdTree->GetBox();
62
63  AxisAlignedBox3 sbox = box;
64  sbox.Enlarge(Vector3(-Limits::Small));
65  if (!sbox.IsInside(viewPoint))
66        return 0;
67       
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());
73
74 
75  if (mKdTree->CastRay(ray)) {
76        objectA = ray.intersections[0].mObject;
77        pointA = ray.Extrap(ray.intersections[0].mT);
78  } else {
79        objectA = NULL;
80        // compute intersection with the scene bounding box
81        float tmin, tmax;
82        if (box.ComputeMinMaxT(ray, &tmin, &tmax) && tmin < tmax)
83          pointA = ray.Extrap(tmax);
84        else
85          return 0;
86  }
87
88  bool detectEmptyViewSpace = true;
89       
90  if (detectEmptyViewSpace) {
91        SetupRay(ray, pointA, -direction);
92  } else
93        SetupRay(ray, viewPoint, -direction);
94       
95       
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;
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);
115        }
116  }
117 
118 
119  VssRay *vssRay  = NULL;
120
121  bool validSample = (objectA != objectB);
122  if (0 && detectEmptyViewSpace) {   // consider all samples valid
123        // check if the viewpoint lies on the line segment AB
124        if (Distance(pointA, pointB) <
125                Distance(viewPoint, pointA) + Distance(viewPoint, pointB) - Limits::Small) {
126          validSample = false;
127        }
128  }
129       
130  if (validSample) {
131        if (objectA) {
132          vssRay = new VssRay(pointB,
133                                                  pointA,
134                                                  objectB,
135                                                  objectA,
136                                                  mPass
137                                                  );
138          vssRays.push_back(vssRay);
139          hits ++;
140        }
141       
142        if (objectB) {
143          vssRay = new VssRay(pointA,
144                                                  pointB,
145                                                  objectA,
146                                                  objectB,
147                                                  mPass
148                                                  );
149          vssRays.push_back(vssRay);
150          hits ++;
151        }
152  }
153       
154  return hits;
155}
156
157
158Vector3
159VssPreprocessor::GetViewpoint(AxisAlignedBox3 *viewSpaceBox)
160{
161  AxisAlignedBox3 box;
162
163  if (viewSpaceBox)
164        box =*viewSpaceBox;
165  else
166        box = mKdTree->GetBox();
167
168  // shrink the box in the y direction
169  return box.GetRandomPoint();
170}
171
172Vector3
173VssPreprocessor::GetDirection(const Vector3 &viewpoint,
174                                                          AxisAlignedBox3 *viewSpaceBox
175                                                          )
176{
177  Vector3 point;
178  if (!use2dSampling) {
179        Vector3 normal;
180        int i = (int)RandomValue(0, (Real)((int)mObjects.size()-1));
181        Intersectable *object = mObjects[i];
182        object->GetRandomSurfacePoint(point, normal);
183  } else {
184        AxisAlignedBox3 box;
185
186        if (viewSpaceBox)
187          box =*viewSpaceBox;
188        else
189          box = mKdTree->GetBox();
190
191        point = box.GetRandomPoint();
192        point.y = viewpoint.y;
193  }
194
195  return point - viewpoint;
196}
197
198int
199VssPreprocessor::GenerateImportanceRays(VssTree *vssTree,
200                                                                                const int desiredSamples,
201                                                                                SimpleRayContainer &rays
202                                                                                )
203{
204  int num;
205  if (0) {
206        float minRayContribution;
207        float maxRayContribution;
208        float avgRayContribution;
209
210        vssTree->GetRayContributionStatistics(minRayContribution,
211                                                                                  maxRayContribution,
212                                                                                  avgRayContribution);
213
214        cout<<
215          "#MIN_RAY_CONTRIB\n"<<minRayContribution<<endl<<
216          "#MAX_RAY_CONTRIB\n"<<maxRayContribution<<endl<<
217          "#AVG_RAY_CONTRIB\n"<<avgRayContribution<<endl;
218
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  }
225
226  cout<<"Generated "<<num<<" rays."<<endl;
227
228  return num;
229}
230
231
232bool
233VssPreprocessor::ExportRays(const char *filename,
234                                                        const VssRayContainer &vssRays,
235                                                        const int number
236                                                        )
237{
238  cout<<"Exporting vss rays..."<<endl<<flush;
239
240  float prob = number/(float)vssRays.size();
241
242
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();
250
251  if (mViewSpaceBox) {
252        exporter->SetForcedMaterial(RgbColor(1,0,1));
253        exporter->ExportBox(*mViewSpaceBox);
254        exporter->ResetForcedMaterial();
255  }
256
257  VssRayContainer rays; for (int i=0; i < vssRays.size(); i++)
258        if (RandomValue(0,1) < prob)
259          rays.push_back(vssRays[i]);
260
261  exporter->ExportRays(rays, RgbColor(1, 0, 0));
262
263  delete exporter;
264
265  cout<<"done."<<endl<<flush;
266
267  return true;
268}
269
270
271bool
272VssPreprocessor::ExportVssTree(char *filename,
273                                                           VssTree *tree,
274                                                           const Vector3 &dir
275                                                           )
276{
277  Exporter *exporter = Exporter::GetExporter(filename);
278  exporter->SetFilled();
279  exporter->ExportScene(mSceneGraph->mRoot);
280  //  exporter->SetWireframe();
281  bool result = exporter->ExportVssTree2( *tree, dir );
282  delete exporter;
283  return result;
284}
285
286bool
287VssPreprocessor::ExportVssTreeLeaf(char *filename,
288                                                                   VssTree *tree,
289                                                                   VssTreeLeaf *leaf)
290{
291  Exporter *exporter = NULL;
292  exporter = Exporter::GetExporter(filename);
293  exporter->SetWireframe();
294  exporter->ExportKdTree(*mKdTree);
295
296  if (mViewSpaceBox) {
297        exporter->SetForcedMaterial(RgbColor(1,0,0));
298        exporter->ExportBox(*mViewSpaceBox);
299        exporter->ResetForcedMaterial();
300  }
301
302  exporter->SetForcedMaterial(RgbColor(0,0,1));
303  exporter->ExportBox(tree->GetBBox(leaf));
304  exporter->ResetForcedMaterial();
305
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  }
311
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));
320
321  delete exporter;
322  return true;
323}
324
325void
326VssPreprocessor::ExportVssTreeLeaves(VssTree *tree, const int number)
327{
328  vector<VssTreeLeaf *> leaves;
329  tree->CollectLeaves(leaves);
330
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++;
340        }
341        if (num >= number)
342          break;
343  }
344}
345
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);
357
358  return sum/(float)viewcells.size();
359}
360
361bool
362VssPreprocessor::ComputeVisibility()
363{
364
365
366  long startTime = GetTime();
367
368  int totalSamples = 0;
369
370
371  AxisAlignedBox3 *box = new AxisAlignedBox3(mKdTree->GetBox());
372
373  if (!useViewspacePlane) {
374        float size = 0.05f;
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 {
382
383        // sample city like heights
384        box->SetMin(1, box->Min(1) + box->Size(1)*0.2f);
385        box->SetMax(1, box->Min(1) + box->Size(1)*0.3f);
386  }
387
388  if (use2dSampling)
389        box->SetMax(1, box->Min(1));
390
391  if (mUseViewSpaceBox)
392  {
393        mViewSpaceBox = box;
394        mViewCellsManager->SetViewSpaceBox(*box);
395  }
396  else
397  {
398        mViewSpaceBox = NULL;
399        mViewCellsManager->SetViewSpaceBox(mKdTree->GetBox());
400  }
401  VssTree *vssTree = NULL;
402
403  mSceneGraph->CollectObjects(&mObjects);
404
405  long initialTime = GetTime();
406
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;
420
421                int index = 0;
422
423                int sampleContributions;
424
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);
434
435                        if (sampleContributions) {
436                                passContributingSamples ++;
437                                passSampleContributions += sampleContributions;
438                        }
439                        passSamples++;
440                        totalSamples++;
441                }
442
443                mPass++;
444                int pvsSize = 0;
445                float avgRayContrib = (passContributingSamples > 0) ?
446                        passSampleContributions/(float)passContributingSamples : 0;
447
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;
454
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;
471
472  if (mStoreInitialSamples)
473  {
474          cout << "Writing " << (int)mVssRays.size() << " samples to file ... ";
475          WriteSamples(mVssRays);
476          cout << "finished\n" << endl;
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          }*/
487  }
488
489  //int numExportRays = 10000;
490  int numExportRays = 0;
491
492  if (numExportRays) {
493        char filename[64];
494        sprintf(filename, "vss-rays-initial.x3d");
495        ExportRays(filename, mVssRays, numExportRays);
496  }
497
498  // construct view cells
499  mViewCellsManager->Construct(mObjects, mVssRays);
500
501  vssTree = new VssTree;
502  // viewcells = Construct(mVssRays);
503
504  vssTree->Construct(mVssRays, mViewSpaceBox);
505  cout<<"VssTree root PVS size = "<<vssTree->GetRootPvsSize()<<endl;
506
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  }
515
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));
528
529        float avgPvs = GetAvgPvsSize(vssTree, kdViewcells);
530        cout<<"Initial average PVS size = "<<avgPvs<<endl;
531  }
532
533
534  int samples = 0;
535  int pass = 0;
536
537  /// Rays used for post processing and visualizations
538  RayContainer storedRays;
539  // cast view cell samples
540  while (1) {
541        int num = mVssSamplesPerPass;
542        SimpleRayContainer rays;
543        VssRayContainer vssRays;
544
545        if (!mUseImportanceSampling) {
546          for (int j=0; j < num; j++) {
547            // changed by matt
548                //Vector3 viewpoint = GetViewpoint(mViewSpaceBox);
549                Vector3 viewpoint;
550                mViewCellsManager->GetViewPoint(viewpoint);
551                Vector3 direction = GetDirection(viewpoint, mViewSpaceBox);
552                rays.push_back(SimpleRay(viewpoint, direction));
553          }
554        } else {
555          num = GenerateImportanceRays(vssTree, num, rays);
556        }
557
558        for (int i=0; i < rays.size(); i++)
559          CastRay(rays[i].mOrigin, rays[i].mDirection, vssRays);
560
561        vssTree->AddRays(vssRays);
562
563        if (0) {
564          int subdivided = vssTree->UpdateSubdivision();
565          cout<<"subdivided leafs = "<<subdivided<<endl;
566        }
567
568        float avgPvs = GetAvgPvsSize(vssTree, kdViewcells);
569        cout<<"Average PVS size = "<<avgPvs<<endl;
570
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);
577
578          ExportRays(filename, vssRays, numExportRays);
579        }
580
581        //-- prepare traversal rays for view cell intersections
582        /// compute view cell contribution of rays
583        mViewCellsManager->ComputeSampleContributions(vssRays);
584
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  }
595
596
597  {
598        VssRayContainer storedRays;
599        vssTree->CollectRays(storedRays, Max(
600                                                                                 mViewCellsManager->GetPostProcessSamples(),
601                                                                                 mViewCellsManager->GetVisualizationSamples()));
602
603    //-- post process view cells
604        mViewCellsManager->PostProcess(mObjects, storedRays);
605
606        //-- several visualizations and statistics
607        Debug << "\nview cells after post processing: " << endl;
608        mViewCellsManager->PrintStatistics(Debug);
609
610        mViewCellsManager->Visualize(mObjects, storedRays);
611  }
612
613  //-- render simulation after merge
614  cout << "\nevaluating bsp view cells render time after merge ... ";
615 
616  mRenderSimulator->RenderScene();
617 
618  SimulationStatistics ss;
619  mRenderSimulator->GetStatistics(ss);
620 
621  cout << " finished" << endl;
622  cout << ss << endl;
623  Debug << ss << endl;
624
625  delete vssTree;
626 
627  return true;
628}
Note: See TracBrowser for help on using the repository browser.