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

Revision 492, 15.9 KB checked in by bittner, 19 years ago (diff)

Large merge - viewcells seem not functional now

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