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

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