source: trunk/VUT/GtpVisibilityPreprocessor/src/SamplingPreprocessor.cpp @ 409

Revision 409, 27.4 KB checked in by mattausch, 19 years ago (diff)

worked on kd view space partitioning structure
worked on render simulation

Line 
1#include "SceneGraph.h"
2#include "KdTree.h"
3#include "SamplingPreprocessor.h"
4#include "X3dExporter.h"
5#include "Environment.h"
6#include "MutualVisibility.h"
7#include "Polygon3.h"
8#include "ViewCell.h"
9#include "RenderSimulator.h"
10
11SamplingPreprocessor::SamplingPreprocessor(): mPass(0), mSampleRays(NULL)
12{
13  // this should increase coherence of the samples
14  environment->GetIntValue("Sampling.samplesPerPass", mSamplesPerPass);
15  environment->GetIntValue("Sampling.totalSamples", mTotalSamples);
16  environment->GetIntValue("BspTree.Construction.samples", mBspConstructionSamples);
17  environment->GetIntValue("ViewCells.PostProcessing.samples", mPostProcessSamples);
18  environment->GetIntValue("BspTree.Visualization.samples", mVisualizationSamples);
19 
20  mKdPvsDepth = 100;
21  mStats.open("stats.log");
22}
23
24SamplingPreprocessor::~SamplingPreprocessor()
25{
26        CLEAR_CONTAINER(mSampleRays);
27}
28
29void
30SamplingPreprocessor::SetupRay(Ray &ray,
31                                                                                                                         const Vector3 &point,
32                                                                                                                         const Vector3 &direction,
33                                                                                                                         const int type)
34{
35  ray.intersections.clear();
36  ray.kdLeaves.clear();
37  ray.testedObjects.clear();
38  ray.bspIntersections.clear();
39        ray.mFlags |= Ray::STORE_KDLEAVES | Ray::STORE_BSP_INTERSECTIONS;
40  //  cout<<point<<" "<<direction<<endl;
41  ray.Init(point, direction, type);
42}
43
44KdNode *
45SamplingPreprocessor::GetNodeForPvs(KdLeaf *leaf)
46{
47  KdNode *node = leaf;
48  while (node->mParent && node->mDepth > mKdPvsDepth)
49    node = node->mParent;
50  return node;
51}
52
53bool
54SamplingPreprocessor::BuildBspTree()
55{
56        // delete old tree
57        DEL_PTR(mBspTree);
58        mBspTree = new BspTree(&mUnbounded);
59        ObjectContainer objects;
60       
61        switch (BspTree::sConstructionMethod)
62        {
63        case BspTree::FROM_INPUT_VIEW_CELLS:
64                mBspTree->SetGenerateViewCells(false);
65                mBspTree->Construct(mViewCells);
66                break;
67        case BspTree::FROM_SCENE_GEOMETRY:
68                DeleteViewCells(); // we generate new view cells
69                mBspTree->SetGenerateViewCells(true);
70                mSceneGraph->CollectObjects(&objects);
71                mBspTree->Construct(objects);
72                break;
73        case BspTree::FROM_RAYS:
74                DeleteViewCells(); // we generate new view cells
75                mBspTree->SetGenerateViewCells(true);
76                mBspTree->Construct(mSampleRays);
77                break;
78        default:
79                Debug << "Error: Method not available\n";
80                break;
81        }
82       
83       
84        return true;
85}
86
87int
88SamplingPreprocessor::AddNodeSamples(const Ray &ray,
89                                                                                                                                                 Intersectable *sObject,
90                                                                                                                                                 Intersectable *tObject
91                                                                                                                                                 )
92{
93  int contributingSamples = 0;
94  int j;
95        int objects = 0;
96        if (sObject)
97                objects++;
98        if (tObject)
99                objects++;
100
101        if (objects) {
102                for (j=0; j < ray.kdLeaves.size(); j++) {
103                        KdNode *node = GetNodeForPvs( ray.kdLeaves[j] );
104                        if (sObject)
105                                contributingSamples += sObject->mKdPvs.AddSample(node);
106                        if (tObject)
107                                contributingSamples += tObject->mKdPvs.AddSample(node);
108                }
109        }
110       
111        for (j=1; j < ((int)ray.kdLeaves.size() - 1); j++) {
112                ray.kdLeaves[j]->AddPassingRay2(ray,
113                                                                                                                                                objects,
114                                                                                                                                                ray.kdLeaves.size()
115                                                                                                                                                );
116  }
117 
118  return contributingSamples;
119}
120
121
122int SamplingPreprocessor::AddObjectSamples(Intersectable *obj, const Ray &ray)
123{
124        int contributingSamples = 0;
125        int j;
126 
127        // object can be seen from the view cell => add to view cell pvs
128        for (j=0; j < ray.bspIntersections.size(); ++ j)
129        {       
130                BspLeaf *leaf = ray.bspIntersections[j].mLeaf;
131                // if ray not in unbounded space
132                if (leaf->GetViewCell() != &mUnbounded)
133                        contributingSamples +=
134                                leaf->GetViewCell()->GetPvs().AddSample(obj);
135        }
136 
137        // rays passing through this viewcell
138        if (mPass > 1)
139                for (j=1; j < ((int)ray.bspIntersections.size() - 1); ++ j)
140                {
141                        BspLeaf *leaf = ray.bspIntersections[j].mLeaf;
142
143                        if (leaf->GetViewCell() != &mUnbounded)
144                                leaf->GetViewCell()->
145                                        AddPassingRay(ray, contributingSamples ? 1 : 0);
146                }
147 
148        return contributingSamples;
149}
150
151
152void
153SamplingPreprocessor::HoleSamplingPass()
154{
155  vector<KdLeaf *> leaves;
156  mKdTree->CollectLeaves(leaves);
157 
158  // go through all the leaves and evaluate their passing contribution
159  for (int i=0 ; i < leaves.size(); i++) {
160    KdLeaf *leaf = leaves[i];
161    cout<<leaf->mPassingRays<<endl;
162  }
163}
164
165
166int
167SamplingPreprocessor::CastRay(Intersectable *object,
168                                                                                                                        Ray &ray
169                                                                                                                        )
170{
171        int sampleContributions = 0;
172
173        long t1 = GetRealTime();
174        // cast ray to KD tree to find intersection with other objects
175        mKdTree->CastRay(ray);
176        long t2 = GetRealTime();
177
178        if (0 && object && object->GetId() > 2197) {
179                object->Describe(cout)<<endl;
180                cout<<ray<<endl;
181        }
182
183        if (ViewCell::sHierarchy == ViewCell::BSP)
184        {
185                // cast ray to BSP tree to get intersection with view cells
186                if (mBspTree)
187                {
188                        mBspTree->CastRay(ray);
189                       
190                        if (object)
191                                sampleContributions += AddObjectSamples(object, ray);
192                       
193                        if (!ray.intersections.empty()) // second intersection found
194                        {
195                                sampleContributions +=
196                                        AddObjectSamples(ray.intersections[0].mObject, ray);
197                        }
198                }
199        }
200        else
201                {
202                        if (ray.kdLeaves.size()) {
203                                Intersectable *terminator =
204                                        ray.intersections.size() ? ray.intersections[0].mObject: NULL;
205
206                                sampleContributions += AddNodeSamples(ray,
207                                                                                                                                                                                        object,
208                                                                                                                                                                                        terminator);
209                        }
210                }
211       
212        return sampleContributions;
213}
214
215//  void
216//  SamplingPreprocessor::AvsGenerateRandomRay(Ray &ray)
217//  {
218//    int objId = RandomValue(0, mObjects.size());
219//    Intersectable *object = objects[objId];
220//    object->GetRandomSurfacePoint(point, normal);
221//    direction = UniformRandomVector(normal);
222//    SetupRay(ray, point, direction);
223//  }
224
225//  void
226//  SamplingPreprocessor::AvsHandleRay(Ray &ray)
227//  {
228//    int sampleContributions = 0;
229
230//    mKdTree->CastRay(ray);
231 
232//    if (ray.leaves.size()) {
233//      sampleContributions += AddNodeSamples(object, ray, pass);
234   
235//      if (ray.intersections.size()) {
236//        sampleContributions += AddNodeSamples(ray.intersections[0].mObject, ray, pass);
237//      }
238//    }
239//  }
240
241//  void
242//  SamplingPreprocessor::AvsBorderSampling(Ray &ray)
243//  {
244 
245
246//  }
247
248//  void
249//  SamplingPreprocessor::AvsPass()
250//  {
251//    Ray ray;
252//    while (1) {
253//      AvsGenerateRay(ray);
254//      HandleRay(ray);
255//      while ( !mRayQueue.empty() ) {
256//        Ray ray = mRayQueue.pop();
257//        mRayQueue.pop();
258//        AdaptiveBorderSampling(ray);
259//      }
260//    }
261 
262 
263
264//  }
265
266
267int
268SamplingPreprocessor::CastEdgeSamples(
269                                                                                                                                                        Intersectable *object,
270                                                                                                                                                        const Vector3 &point,
271                                                                                                                                                        MeshInstance *mi,
272                                                                                                                                                        const int samples
273                                                                                                                                                        )
274{
275        Ray ray;
276        int maxTries = samples*10;
277        int i;
278        int rays = 0;
279        int edgeSamplesContributions = 0;
280        for (i=0; i < maxTries && rays < samples; i++) {
281                // pickup a random face of each mesh
282                Mesh *mesh = mi->GetMesh();
283                int face = RandomValue(0, mesh->mFaces.size()-1);
284               
285                Polygon3 poly(mesh->mFaces[face], mesh);
286                poly.Scale(1.001);
287                // now extend a random edge of the face
288                int edge = RandomValue(0, poly.mVertices.size()-1);
289                float t = RandomValue(0.0f,1.0f);
290                Vector3 target = t*poly.mVertices[edge] + (1.0f-t)*poly.mVertices[(edge + 1)%
291                                                                                                                                                                                                                                                                                 poly.mVertices.size()];
292                SetupRay(ray, point, target - point, Ray::LOCAL_RAY);
293                if (!mesh->CastRay(ray, mi)) {
294                        // the rays which intersect the mesh have been discarded since they are not tangent
295                        // to the mesh
296                        rays++;
297                        edgeSamplesContributions += CastRay(object, ray);
298                }
299        }
300        return edgeSamplesContributions;
301}
302
303KdNode *
304SamplingPreprocessor::GetNodeToSample(Intersectable *object)
305{
306        int pvsSize = object->mKdPvs.GetSize();
307        KdNode *nodeToSample = NULL;
308       
309        bool samplePvsBoundary = false;
310        if (pvsSize && samplePvsBoundary) {
311                // this samples the nodes from the boundary of the current PVS
312                // mail all nodes from the pvs
313                Intersectable::NewMail();
314                KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
315               
316                for (; i != object->mKdPvs.mEntries.end(); i++) {
317                        KdNode *node = (*i).first;
318                        node->Mail();
319                }
320               
321                int maxTries = 2*pvsSize;
322                Debug << "Finding random neighbour" << endl;   
323                for (int tries = 0; tries < 10; tries++) {
324                        int index = RandomValue(0, pvsSize - 1);
325                        KdPvsData data;
326                        KdNode *node;
327                        object->mKdPvs.GetData(index, node, data);
328                        nodeToSample = mKdTree->FindRandomNeighbor(node, true);
329                        if (nodeToSample)
330                                break;
331                }
332        } else {
333                // just pickup a random node
334                //              nodeToSample = mKdTree->GetRandomLeaf(Plane3(normal, point));
335                nodeToSample = mKdTree->GetRandomLeaf();
336        }
337        return nodeToSample;
338}
339
340void
341SamplingPreprocessor::VerifyVisibility(Intersectable *object)
342{
343        // mail all nodes from the pvs
344        Intersectable::NewMail();
345        KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
346        for (; i != object->mKdPvs.mEntries.end(); i++) {
347                KdNode *node = (*i).first;
348                node->Mail();
349        }
350        Debug << "Get all neighbours from PVS" << endl;
351        vector<KdNode *> invisibleNeighbors;
352        // get all neighbors of all PVS nodes
353        i = object->mKdPvs.mEntries.begin();
354        for (; i != object->mKdPvs.mEntries.end(); i++) {
355                KdNode *node = (*i).first;
356                mKdTree->FindNeighbors(node, invisibleNeighbors, true);
357                AxisAlignedBox3 box = object->GetBox();
358                for (int j=0; j < invisibleNeighbors.size(); j++) {
359                        int visibility = ComputeBoxVisibility(mSceneGraph,
360                                                              mKdTree,
361                                                              box,
362                                                              mKdTree->GetBox(invisibleNeighbors[j]),
363                                                              1e-6f);
364                        //            exit(0);
365                }
366                // now rank all the neighbors according to probability that a new
367                // sample creates some contribution
368        }
369}
370
371bool
372SamplingPreprocessor::ComputeVisibility()
373{
374 
375  // pickup an object
376  ObjectContainer objects;
377 
378  mSceneGraph->CollectObjects(&objects);
379
380  Vector3 point, normal, direction;
381  Ray ray;
382
383  long startTime = GetTime();
384 
385  int i;
386  int totalSamples = 0;
387
388  int pvsOut = Min((int)objects.size(), 10);
389
390  RayContainer rays[10];
391
392  while (totalSamples < mTotalSamples) {
393                int passContributingSamples = 0;
394                int passSampleContributions = 0;
395                int passSamples = 0;
396                int index = 0;
397               
398                int reverseSamples = 0;
399               
400                       
401                //cout << "totalSamples: "  << totalSamples << endl;
402
403                for (i = 0; i < objects.size(); i++) {
404                                               
405                        KdNode *nodeToSample = NULL;
406                        Intersectable *object = objects[i];
407               
408                        int pvsSize = 0;
409                        if (ViewCell::sHierarchy == ViewCell::KD)
410                                pvsSize = object->mKdPvs.GetSize();
411                                               
412                       
413                        if (0 && pvsSize && mPass == 1000 ) {
414                                VerifyVisibility(object);
415                        }
416                       
417                        int faceIndex = object->GetRandomSurfacePoint(point, normal);
418                       
419                        bool viewcellSample = true;
420                        int sampleContributions;
421                        bool debug = false; //(object->GetId() >= 2199);
422                        if (viewcellSample) {
423                                //mKdTree->GetRandomLeaf(Plane3(normal, point));
424
425                                nodeToSample = GetNodeToSample(object);
426
427                                for (int k=0; k < mSamplesPerPass; k++) {
428                                        bool reverseSample = false;
429                                       
430
431                                        if (nodeToSample) {
432                                                AxisAlignedBox3 box = mKdTree->GetBox(nodeToSample);
433                                                Vector3 pointToSample = box.GetRandomPoint();
434                                                //                                              pointToSample.y = 0.9*box.Min().y + 0.1*box.Max().y;
435                                                if (object->GetRandomVisibleSurfacePoint( point, normal, pointToSample, 3 )) {
436                                                        direction = pointToSample - point;
437                                                } else {
438                                                        reverseSamples++;
439                                                        reverseSample = true;
440                                                        direction = point - pointToSample;
441                                                        point = pointToSample;
442                                                }
443                                        }
444                                        else {
445                                                direction = UniformRandomVector(normal);
446                                        }
447                                       
448                                        // construct a ray
449                                        SetupRay(ray, point, direction, Ray::LOCAL_RAY);
450                                       
451                                        sampleContributions = CastRay(reverseSample ? NULL : object, ray);
452                                       
453                                        //-- CORR matt: put block inside loop
454                                        if (sampleContributions) {
455                                                passContributingSamples ++;
456                                                passSampleContributions += sampleContributions;
457                                        }
458
459                                        if ( i < pvsOut ) {
460                                                Ray *nray = new Ray(ray);
461                                                rays[i].push_back(nray);
462                                        }
463               
464                                        if (!ray.intersections.empty()) {
465                                                // check whether we can add this to the rays
466                                                for (int j = 0; j < pvsOut; j++) {
467                                                        if (objects[j] == ray.intersections[0].mObject) {
468                                                                Ray *nray = new Ray(ray);
469                                                                rays[j].push_back(nray);
470                                                        }
471                                                }
472                                        }
473                                        //-------------------
474                                        if (ViewCell::sHierarchy == ViewCell::BSP)
475                                        {
476                                                ProcessBspViewCells(ray,
477                                                                                        reverseSample ? NULL : object,
478                                                                                        faceIndex,
479                                                                                        passContributingSamples,
480                                                                                        passSampleContributions);
481                                        }
482                                }
483                        } else {
484                                // edge samples
485                                // get random visible mesh
486                                //                              object->GetRandomVisibleMesh(Plane3(normal, point));
487                        }
488       
489                        // CORR matt: must add all samples
490                        passSamples += mSamplesPerPass;
491                }
492       
493                totalSamples += passSamples;
494               
495                //    if (pass>10)
496                //      HoleSamplingPass();
497   
498                mPass++;
499
500                int pvsSize = 0;
501       
502                if (ViewCell::sHierarchy == ViewCell::BSP) {
503                        for (i=0; i < mViewCells.size(); i++) {
504                                ViewCell *vc = mViewCells[i];
505                                pvsSize += vc->GetPvs().GetSize();
506                        }
507                } else  {
508                        for (i=0; i < objects.size(); i++) {
509                                Intersectable *object = objects[i];
510                                pvsSize += object->mKdPvs.GetSize();
511                        }
512                }
513
514                float avgRayContrib = (passContributingSamples > 0) ?
515                        passSampleContributions/(float)passContributingSamples : 0;
516
517                cout << "#Pass " << mPass << " : t = " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
518                cout << "#TotalSamples=" << totalSamples/1000
519                                 << "k   #SampleContributions=" << passSampleContributions << " ("
520                                 << 100*passContributingSamples/(float)passSamples<<"%)" << " avgPVS="
521                                 << pvsSize /(float)objects.size() << endl
522                                 << "avg ray contrib=" << avgRayContrib << endl
523                                 << "reverse samples [%]" << reverseSamples/(float)passSamples*100.0f << endl;
524
525                mStats <<
526                        "#Pass\n" <<mPass<<endl<<
527                        "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl<<
528                        "#TotalSamples\n" << totalSamples<< endl<<
529                        "#SampleContributions\n" << passSampleContributions << endl <<
530                        "#PContributingSamples\n"<<100*passContributingSamples/(float)passSamples<<endl <<
531                        "#AvgPVS\n"<< pvsSize/(float)objects.size() << endl <<
532                        "#AvgRayContrib\n" << avgRayContrib << endl;
533        }
534       
535        if (ViewCell::sHierarchy == ViewCell::KD)       
536                cout << "#totalKdPvsSize=" << mKdTree->CollectLeafPvs() << endl;
537 
538        if (mBspTree)
539        {
540                //-- render simulation
541                cout << "\nevaluating bsp view cells render time before merge ... ";
542                Real rt = GetRenderSimulator()->SimulateRendering();
543               
544                cout << "avg render time: " << rt * 1e-3 << endl;
545                Debug << "avg render time: " << rt * 1e-3 << endl;
546
547                //-- post processing of bsp view cells
548        int vcSize = 0;
549                int pvsSize = 0;
550
551                BspViewCellsStatistics stat;
552               
553                Debug << "overall scene size: " << (int)objects.size() << endl;
554                mBspTree->EvaluateViewCellsStats(stat);
555               
556                Debug << "original view cell partition:\n" << stat << endl;
557               
558                if (1) // export view cells
559                {
560                        cout << "exporting initial view cells (=leaves) ... ";
561                        Exporter *exporter = Exporter::GetExporter("view_cells.x3d");
562                        if (exporter)
563                        {
564                                exporter->ExportBspLeaves(*mBspTree, stat.maxPvs);
565                                //exporter->ExportBspViewCellPartition(*mBspTree, 0);
566                                delete exporter;
567                        }
568                        cout << "finished" << endl;
569                }
570
571                cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
572               
573                long startTime = GetTime();
574                int merged = PostprocessViewCells(mSampleRays);
575               
576                cout << "finished" << endl;
577                cout << "merged " << merged << " view cells in "
578                         << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
579
580                //-- recount pvs
581                mBspTree->EvaluateViewCellsStats(stat);
582               
583                Debug << "after post processing:\n" << stat << endl;
584
585                //-- render simulation
586                cout << "\nevaluating render time after merge ... ";
587                       
588                rt = GetRenderSimulator()->SimulateRendering();
589
590                cout << "render time: " << rt * 1e-3 << endl;
591                Debug << "render time: " << rt * 1e-3 << endl;
592
593                if (1) // export view cells
594                {
595                        cout << "exporting view cells after merge ... ";
596                        Exporter *exporter = Exporter::GetExporter("merged_view_cells.x3d");
597                        if (exporter)
598                        {
599                                exporter->ExportBspViewCellPartition(*mBspTree, stat.maxPvs);
600                                //exporter->ExportBspViewCellPartition(*mBspTree, 0);
601                                delete exporter;
602                        }
603
604                        cout << "finished" << endl;
605                }
606
607                //-- visualization of the BSP splits
608                bool exportSplits = false;
609                environment->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
610               
611                cout << "exporting splits ... ";
612                if (exportSplits)
613                        ExportSplits(objects);
614                cout << "finished" << endl;
615
616                // export the PVS of sample view cells
617                if (1)
618                        ExportBspPvs(objects);
619        }
620       
621  //  HoleSamplingPass();
622        if (0) {
623                Exporter *exporter = Exporter::GetExporter("ray-density.x3d");
624                exporter->SetExportRayDensity(true);
625                exporter->ExportKdTree(*mKdTree);
626
627                if (mBspTree && (ViewCell::sHierarchy == ViewCell::BSP))
628                        exporter->ExportBspTree(*mBspTree);
629
630                delete exporter;
631        }
632 
633        bool exportRays = false;
634        if (exportRays) {
635                Exporter *exporter = NULL;
636                exporter = Exporter::GetExporter("sample-rays.x3d");
637                exporter->SetWireframe();
638                exporter->ExportKdTree(*mKdTree);
639                exporter->ExportBspTree(*mBspTree);
640
641                for (i=0; i < pvsOut; i++)
642                        exporter->ExportRays(rays[i], 1000, RgbColor(1, 0, 0));
643                exporter->SetFilled();
644               
645                delete exporter;
646        }
647
648        //-- several visualizations and statistics
649        if (1) {
650       
651        if (ViewCell::sHierarchy == ViewCell::KD)
652        {
653                cout << "\nevaluating kd view cells render time ... ";
654                Real rt = GetRenderSimulator()->SimulateRendering();
655               
656                cout << "avg render time: " << rt * 1e-3 << endl;
657                Debug << "avg render time: " << rt * 1e-3 << endl;
658        }
659
660   for (int k=0; k < pvsOut; k++) {
661                 Intersectable *object = objects[k];
662                 char s[64];
663                 sprintf(s, "sample-pvs%04d.x3d", k);
664                 Exporter *exporter = Exporter::GetExporter(s);
665                 exporter->SetWireframe();
666                 
667                 
668                 KdPvsMap::iterator i = object->mKdPvs.mEntries.begin();
669                 Intersectable::NewMail();
670                 
671                 // avoid adding the object to the list
672                 object->Mail();
673                 ObjectContainer visibleObjects;
674                 
675                 for (; i != object->mKdPvs.mEntries.end(); i++)
676                         {
677                                 KdNode *node = (*i).first;
678                                 exporter->ExportBox(mKdTree->GetBox(node));
679                                 mKdTree->CollectObjects(node, visibleObjects);
680                         }
681                 
682                 exporter->ExportRays(rays[k], 1000, RgbColor(0, 1, 0));
683                 exporter->SetFilled();
684                 
685                 for (int j = 0; j < visibleObjects.size(); j++)
686                         exporter->ExportIntersectable(visibleObjects[j]);
687                 
688                 
689                 Material m;
690                 m.mDiffuseColor = RgbColor(1, 0, 0);
691                 exporter->SetForcedMaterial(m);
692                 exporter->ExportIntersectable(object);
693                 
694                 delete exporter;
695         }
696  }
697 
698  return true;
699}
700
701void SamplingPreprocessor::ProcessBspViewCells(const Ray &ray,
702                                               Intersectable *object,
703                                                                                           const int faceIndex,
704                                                                                           int &contributingSamples,
705                                                                                           int &sampleContributions)
706{
707        // save rays for bsp tree construction
708        if (!mBspTree)
709        {
710                if ((BspTree::sConstructionMethod == BspTree::FROM_RAYS) &&
711                        ((int)mSampleRays.size() < mBspConstructionSamples))
712                {
713                        MeshInstance *mi = dynamic_cast<MeshInstance *>(object);
714                       
715                        Ray *sRay = new Ray(ray);
716                        mSampleRays.push_back(sRay);
717               
718                        // also add origin to sample
719                        sRay->sourceObject = Ray::Intersection(0.0, object, faceIndex);
720                }
721                else
722                {
723                        // construct BSP tree using the collected samples
724                        cout << "building bsp tree from " << (int)mSampleRays.size() << " samples " << endl;
725                        BuildBspTree();
726               
727                        // add contributions of saved samples to PVS
728                        contributingSamples += mBspTree->GetStat().contributingSamples;
729                        sampleContributions += mBspTree->GetStat().sampleContributions;
730
731                        BspTreeStatistics(Debug);       
732
733                        if (0) Export("vc_bsptree.x3d", false, false, true);
734
735                        // throw away samples because BSP leaves not stored in order
736                        // Need ordered rays for post processing => collect new rays
737                        CLEAR_CONTAINER(mSampleRays);
738                }
739        }
740        // save rays for post processing
741        else if (((int)mSampleRays.size() < mPostProcessSamples) ||
742                         ((int)mSampleRays.size() < mVisualizationSamples))
743        {
744                mSampleRays.push_back(new Ray(ray));
745        }
746}
747
748// merge or subdivide view cells
749int SamplingPreprocessor::PostprocessViewCells(const RayContainer &rays)
750{
751        int merged = 0;
752
753        RayContainer::const_iterator rit, rit_end = rays.end();
754        vector<Ray::BspIntersection>::const_iterator iit;
755
756        int limit = min((int)mSampleRays.size(), mPostProcessSamples);
757
758        for (int i = 0; i < limit; ++i)
759        { 
760                Ray *ray = mSampleRays[i];
761
762                // traverse leaves stored in the rays and compare and merge consecutive
763                // leaves (i.e., the neighbors in the tree)
764                if (ray->bspIntersections.empty())
765                        continue;
766
767                iit = ray->bspIntersections.begin();
768
769                BspLeaf *previousLeaf = (*iit).mLeaf;
770                ++ iit;
771               
772                for (; iit != (*rit)->bspIntersections.end(); ++ iit)
773                {
774                        BspLeaf *leaf = (*iit).mLeaf;
775
776                        if (mBspTree->ShouldMerge(leaf, previousLeaf))
777                        {                       
778                                mBspTree->MergeViewCells(leaf, previousLeaf);
779
780                                ++ merged;
781                        }
782                        previousLeaf = leaf;
783                }
784        }
785
786        return merged;
787}
788
789void SamplingPreprocessor::ExportSplits(const ObjectContainer &objects)
790{
791        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
792
793        if (exporter)
794        {       
795                Material m;
796                m.mDiffuseColor = RgbColor(1, 0, 0);
797                exporter->SetForcedMaterial(m);
798                exporter->SetWireframe();
799                exporter->ExportBspSplits(*mBspTree, true);
800
801                // take forced material, else big scenes cannot be viewed
802                m.mDiffuseColor = RgbColor(0, 1, 0);
803                exporter->SetForcedMaterial(m);
804                exporter->SetFilled();
805
806                exporter->ResetForcedMaterial();
807               
808                // export rays
809                if (0)
810                {
811                        RayContainer outRays;
812               
813                        for (int i = 0; i < mSampleRays.size(); ++ i)
814                        {
815                                // only rays piercing geometry
816                                if (!mSampleRays[i]->intersections.empty())
817                                        outRays.push_back(mSampleRays[i]);
818                        }
819                        if (BspTree::sConstructionMethod == BspTree::FROM_RAYS)
820                        {
821                                // export rays
822                                exporter->ExportRays(outRays, 1000, RgbColor(1, 1, 0));
823                        }
824                }
825
826                // export scene geometry
827                if (0)
828                {
829                        Material m;//= RandomMaterial();
830                        m.mDiffuseColor = RgbColor(0, 1, 0);
831                        exporter->SetForcedMaterial(m);
832            exporter->SetWireframe();
833
834                        for (int j = 0; j < objects.size(); ++ j)
835                                exporter->ExportIntersectable(objects[j]);
836                }
837
838                delete exporter;
839        }
840}
841
842inline bool vc_gt(ViewCell *a, ViewCell *b)
843{
844        return a->GetPvs().GetSize() > b->GetPvs().GetSize();
845}
846
847void SamplingPreprocessor::ExportBspPvs(const ObjectContainer &objects)
848{
849        const int leafOut = 10;
850       
851        ViewCell::NewMail();
852
853        //-- some rays for output
854        const int raysOut = min((int)mSampleRays.size(), mVisualizationSamples);
855        cout << "visualization using " << mVisualizationSamples << " samples" << endl;
856        vector<Ray *> vcRays[leafOut];
857
858        if (0){
859                //-- some random view cells and rays for output
860                vector<BspLeaf *> bspLeaves;
861
862                for (int i = 0; i < leafOut; ++ i)
863                        bspLeaves.push_back(mBspTree->GetRandomLeaf());
864               
865                for (int i = 0; i < bspLeaves.size(); ++ i)
866                {
867                        cout << "creating output for view cell " << i << " ... ";
868                        // check whether we can add the current ray to the output rays
869                        for (int k = 0; k < raysOut; ++ k)
870                        {
871                                Ray *ray = mSampleRays[k];
872
873                                for     (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
874                                {
875                                        BspLeaf *leaf = ray->bspIntersections[j].mLeaf;
876
877                                        if (bspLeaves[i]->GetViewCell() == leaf->GetViewCell())
878                                        {
879                                                vcRays[i].push_back(ray);
880                                        }
881                                }
882                        }
883
884                        Intersectable::NewMail();
885
886                        BspViewCell *vc = dynamic_cast<BspViewCell *>(bspLeaves[i]->GetViewCell());
887
888                        //bspLeaves[j]->Mail();
889                        char s[64]; sprintf(s, "bsp-pvs%04d.x3d", i);
890
891                        Exporter *exporter = Exporter::GetExporter(s);
892                        exporter->SetFilled();
893
894                        ViewCellPvsMap::iterator it = vc->GetPvs().mEntries.begin();
895
896                        exporter->SetWireframe();
897                        //exporter->SetFilled();
898
899                        Material m;//= RandomMaterial();
900                        m.mDiffuseColor = RgbColor(0, 1, 0);
901                        exporter->SetForcedMaterial(m);
902
903                        if (vc->GetMesh())
904                                exporter->ExportViewCell(vc);
905                        else
906                        {
907                                PolygonContainer cell;
908                                // export view cell geometry
909                                mBspTree->ConstructGeometry(vc, cell);
910                                exporter->ExportPolygons(cell);
911                                CLEAR_CONTAINER(cell);
912                        }
913
914                        Debug << i << ": pvs size=" << (int)vc->GetPvs().GetSize()
915                                        << ", piercing rays=" << (int)vcRays[i].size() << endl;
916
917                        // export rays piercing this view cell
918                        exporter->ExportRays(vcRays[i], 1000, RgbColor(0, 1, 0));
919
920                        m.mDiffuseColor = RgbColor(1, 0, 0);
921                        exporter->SetForcedMaterial(m);
922
923                        // exporter->SetWireframe();
924                        exporter->SetFilled();
925
926                        // output PVS of view cell
927                        for (; it != vc->GetPvs().mEntries.end(); ++ it)
928                        {
929                                Intersectable *intersect = (*it).first;
930                                if (!intersect->Mailed())
931                                {
932                                        exporter->ExportIntersectable(intersect);
933                                        intersect->Mail();
934                                }                       
935                        }
936                               
937                        // output rest of the objects
938                        if (0)
939                        {
940                                Material m;//= RandomMaterial();
941                                m.mDiffuseColor = RgbColor(0, 0, 1);
942                                exporter->SetForcedMaterial(m);
943
944                                for (int j = 0; j < objects.size(); ++ j)
945                                        if (!objects[j]->Mailed())
946                                        {
947                                                exporter->SetForcedMaterial(m);
948                                                exporter->ExportIntersectable(objects[j]);
949                                                objects[j]->Mail();
950                                        }
951                        }
952                        DEL_PTR(exporter);
953                        cout << "finished" << endl;
954                }
955        }
956        else
957        {
958                ViewCellContainer viewCells;
959
960                mBspTree->CollectViewCells(viewCells);
961                stable_sort(viewCells.begin(), viewCells.end(), vc_gt);
962
963                int limit = min(leafOut, (int)viewCells.size());
964               
965                for (int i = 0; i < limit; ++ i)
966                {
967                        cout << "creating output for view cell " << i << " ... ";
968                       
969            Intersectable::NewMail();
970                        BspViewCell *vc = dynamic_cast<BspViewCell *>(viewCells[i]);
971
972                        cout << "creating output for view cell " << i << " ... ";
973                        // check whether we can add the current ray to the output rays
974                        for (int k = 0; k < raysOut; ++ k)
975                        {
976                                Ray *ray = mSampleRays[k];
977
978                                for     (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
979                                {
980                                        BspLeaf *leaf = ray->bspIntersections[j].mLeaf;
981
982                                        if (vc == leaf->GetViewCell())
983                                        {
984                                                vcRays[i].push_back(ray);
985                                        }
986                                }
987                        }
988
989                        //bspLeaves[j]->Mail();
990                        char s[64]; sprintf(s, "bsp-pvs%04d.x3d", i);
991
992                        Exporter *exporter = Exporter::GetExporter(s);
993                       
994                        exporter->SetWireframe();
995
996                        Material m;//= RandomMaterial();
997                        m.mDiffuseColor = RgbColor(0, 1, 0);
998                        exporter->SetForcedMaterial(m);
999
1000                        if (vc->GetMesh())
1001                                exporter->ExportViewCell(vc);
1002                        else
1003                        {
1004                                PolygonContainer cell;
1005                                // export view cell
1006                                mBspTree->ConstructGeometry(vc, cell);
1007                                exporter->ExportPolygons(cell);
1008                                CLEAR_CONTAINER(cell);
1009                        }
1010
1011                       
1012                        Debug << i << ": pvs size=" << (int)vc->GetPvs().GetSize()
1013                                        << ", piercing rays=" << (int)vcRays[i].size() << endl;
1014
1015                       
1016                        // export rays piercing this view cell
1017                        exporter->ExportRays(vcRays[i], 1000, RgbColor(0, 1, 0));
1018       
1019                        m.mDiffuseColor = RgbColor(1, 0, 0);
1020                        exporter->SetForcedMaterial(m);
1021
1022                        ViewCellPvsMap::const_iterator it,
1023                                it_end = vc->GetPvs().mEntries.end();
1024
1025                        // output PVS of view cell
1026                        for (it = vc->GetPvs().mEntries.begin(); it != it_end; ++ it)
1027                        {
1028                                Intersectable *intersect = (*it).first;
1029                                if (!intersect->Mailed())
1030                                {
1031                                        Material m = RandomMaterial();
1032                       
1033                                        exporter->SetForcedMaterial(m);
1034
1035                                        exporter->ExportIntersectable(intersect);
1036                                        intersect->Mail();
1037                                }                       
1038                        }
1039                               
1040                        DEL_PTR(exporter);
1041                        cout << "finished" << endl;
1042                }
1043        }
1044}
Note: See TracBrowser for help on using the repository browser.