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

Revision 446, 13.7 KB checked in by bittner, 19 years ago (diff)

non-functional merged version

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