source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp @ 1981

Revision 1981, 166.8 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include "ViewCellsManager.h"
2#include "RenderSimulator.h"
3#include "Mesh.h"
4#include "Triangle3.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "X3dParser.h"
8#include "ViewCellBsp.h"
9#include "KdTree.h"
10#include "HierarchyManager.h"
11#include "Exporter.h"
12#include "VspBspTree.h"
13#include "ViewCellsParser.h"
14#include "Beam.h"
15#include "VssPreprocessor.h"
16#include "RssPreprocessor.h"
17#include "BoundingBoxConverter.h"
18#include "GlRenderer.h"
19#include "ResourceManager.h"
20#include "IntersectableWrapper.h"
21#include "VspTree.h"
22#include "OspTree.h"
23#include "BvHierarchy.h"
24#include "SamplingStrategy.h"
25#include "SceneGraph.h"
26
27
28// $$JB HACK
29#define KD_PVS_AREA (1e-5f)
30
31#define USE_RAY_LENGTH_AS_CONTRIBUTION 0
32#define DIST_WEIGHTED_CONTRIBUTION 0
33#define SUM_RAY_CONTRIBUTIONS 1
34#define AVG_RAY_CONTRIBUTIONS 0
35#define CONTRIBUTION_RELATIVE_TO_PVS_SIZE 0
36#define PVS_ADD_DIRTY 1
37
38namespace GtpVisibilityPreprocessor {
39
40
41// HACK
42const static bool SAMPLE_AFTER_SUBDIVISION = true;
43//const static bool CLAMP_TO_BOX = false;
44const static bool CLAMP_TO_BOX = true;
45
46
47int ViewCellsManager::sRenderCostEvaluationType = 0;
48
49
50template <typename T> class myless
51{
52public:
53        //bool operator() (HierarchyNode *v1, HierarchyNode *v2) const
54        bool operator() (T v1, T v2) const
55        {
56                return (v1->GetMergeCost() < v2->GetMergeCost());
57        }
58};
59
60
61ViewCellsManager::ViewCellsManager(ViewCellsTree *viewCellsTree):
62mRenderer(NULL),
63mInitialSamples(0),
64mConstructionSamples(0),
65mPostProcessSamples(0),
66mVisualizationSamples(0),
67mTotalAreaValid(false),
68mTotalArea(0.0f),
69mViewCellsFinished(false),
70mMaxPvsSize(9999999),
71mMinPvsSize(0),
72mMaxPvsRatio(1.0),
73mViewCellPvsIsUpdated(false),
74mPreprocessor(NULL),
75mViewCellsTree(viewCellsTree),
76mUsePredefinedViewCells(false)
77{
78        mViewSpaceBox.Initialize();
79        ParseEnvironment();
80
81        mViewCellsTree->SetViewCellsManager(this);
82}
83
84
85int ViewCellsManager::CastPassSamples2(const int samplesPerPass,
86                                                                           VssRayContainer &passSamples) const
87{
88        long startTime = GetTime();
89
90        SimpleRayContainer simpleRays;
91       
92        simpleRays.reserve(samplesPerPass);
93        passSamples.reserve(samplesPerPass * 2); // always creates double rays
94
95        // create one third of each type
96        int castRays = 0;
97
98        mMixtureDistribution->GenerateSamples(mSamplesPerPass, simpleRays);
99
100        cout << "generated " << (int)simpleRays.size() << " samples in "
101                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
102
103        startTime = GetTime();
104
105        // shoot simple ray and add it to importance samples
106        mPreprocessor->CastRays(simpleRays, passSamples, true);
107
108    cout << "cast " <<  samplesPerPass << " samples in "
109                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
110
111        mMixtureDistribution->ComputeContributions(passSamples);
112
113        return (int)passSamples.size();
114}
115
116
117void ViewCellsManager::ParseEnvironment()
118{
119        // visualization stuff
120        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportRays", mExportRays);
121        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportGeometry", mExportGeometry);
122        Environment::GetSingleton()->GetFloatValue("ViewCells.maxPvsRatio", mMaxPvsRatio);
123       
124        Environment::GetSingleton()->GetBoolValue("ViewCells.processOnlyValidViewCells", mOnlyValidViewCells);
125
126        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samples", mConstructionSamples);
127        Environment::GetSingleton()->GetIntValue("ViewCells.PostProcess.samples", mPostProcessSamples);
128        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.useRaysForMerge", mUseRaysForMerge);
129
130        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.samples", mVisualizationSamples);
131
132        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samplesPerPass", mSamplesPerPass);
133        Environment::GetSingleton()->GetBoolValue("ViewCells.exportToFile", mExportViewCells);
134       
135        Environment::GetSingleton()->GetIntValue("ViewCells.active", mNumActiveViewCells);
136        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.compress", mCompressViewCells);
137        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.useClipPlane", mUseClipPlaneForViz);
138        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.merge", mMergeViewCells);
139        Environment::GetSingleton()->GetBoolValue("ViewCells.evaluateViewCells", mEvaluateViewCells);
140        Environment::GetSingleton()->GetBoolValue("ViewCells.showVisualization", mShowVisualization);
141        Environment::GetSingleton()->GetIntValue("ViewCells.Filter.maxSize", mMaxFilterSize);
142        Environment::GetSingleton()->GetFloatValue("ViewCells.Filter.width", mFilterWidth);
143        Environment::GetSingleton()->GetIntValue("ViewCells.renderCostEvaluationType", sRenderCostEvaluationType);
144
145        Environment::GetSingleton()->GetBoolValue("ViewCells.exportBboxesForPvs", mExportBboxesForPvs);
146        Environment::GetSingleton()->GetBoolValue("ViewCells.exportPvs", mExportPvs);
147
148        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
149
150        char buf[100];
151        Environment::GetSingleton()->GetStringValue("ViewCells.samplingType", buf);
152
153        // mix of sampling strategies
154        if (0)
155        {
156                mStrategies.push_back(SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION);
157        }
158        else
159        {
160                /*mStrategies.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
161                mStrategies.push_back(SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION);
162                mStrategies.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
163                */
164       
165                mStrategies.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
166        }
167               
168    Debug << "casting strategies: ";
169        for (int i = 0; i < (int)mStrategies.size(); ++ i)
170                Debug << mStrategies[i] << " ";
171        Debug << endl;
172
173        // now decode distribution string
174        char buff[1024];
175        Environment::GetSingleton()->GetStringValue("RssPreprocessor.distributions", buff);
176
177        mMixtureDistribution = new MixtureDistribution(*mPreprocessor);
178        mMixtureDistribution->Construct(buff);
179
180
181        // sampling type for view cells construction samples
182        if (strcmp(buf, "object") == 0)
183        {
184                mSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
185        }
186        else if (strcmp(buf, "box") == 0)
187        {
188                mSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
189        }
190        else if (strcmp(buf, "directional") == 0)
191        {
192                mSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
193        }
194        else if (strcmp(buf, "object_directional") == 0)
195        {
196                mSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
197        }
198        else if (strcmp(buf, "reverse_object") == 0)
199        {
200                mSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
201        }
202        /*else if (strcmp(buf, "interior") == 0)
203        {
204                mSamplingType = Preprocessor::OBJECTS_INTERIOR_DISTRIBUTION;
205        }*/
206        else
207        {
208                Debug << "error! wrong sampling type" << endl;
209                exit(0);
210        }
211
212        // sampling type for evaluation samples
213        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.samplingType", buf);
214       
215        if (strcmp(buf, "object") == 0)
216        {
217                mEvaluationSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
218        }
219        else if (strcmp(buf, "box") == 0)
220        {
221                mEvaluationSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
222        }
223        else if (strcmp(buf, "directional") == 0)
224        {
225                mEvaluationSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
226        }
227        else if (strcmp(buf, "object_directional") == 0)
228        {
229                mEvaluationSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
230        }
231        else if (strcmp(buf, "reverse_object") == 0)
232        {
233                mEvaluationSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
234        }
235        /*else if (strcmp(buf, "interior") == 0)
236        {
237                mEvaluationSamplingType = SamplingStrategy::OBJECTS_INTERIOR_DISTRIBUTION;
238        }*/
239        else
240        {
241                mEvaluationSamplingType = -1;
242                Debug << "error! wrong sampling type" << endl;
243                exit(0);
244        }
245
246        Environment::GetSingleton()->GetStringValue("ViewCells.renderCostEvaluationType", buf);
247       
248        if (strcmp(buf, "perobject") == 0)
249        {
250                sRenderCostEvaluationType = ViewCellsManager::PER_OBJECT;
251        }
252        else if (strcmp(buf, "pertriangle") == 0)
253        {
254                sRenderCostEvaluationType = ViewCellsManager::PER_TRIANGLE;
255        }
256        else
257        {
258                Debug << "error! wrong sampling type" << endl;
259                exit(0);
260        }
261
262    Environment::GetSingleton()->GetStringValue("ViewCells.Visualization.colorCode", buf);
263
264        if (strcmp(buf, "PVS") == 0)
265                mColorCode = 1;
266        else if (strcmp(buf, "MergedLeaves") == 0)
267                mColorCode = 2;
268        else if (strcmp(buf, "MergedTreeDiff") == 0)
269                mColorCode = 3;
270        else
271                mColorCode = 0;
272
273
274        Debug << "************ View Cells Manager options ***************" << endl;
275        Debug << "color code: " << mColorCode << endl;
276
277        Debug << "export rays: " << mExportRays << endl;
278        Debug << "export geometry: " << mExportGeometry << endl;
279        Debug << "max pvs ratio: " << mMaxPvsRatio << endl;
280       
281        Debug << "process only valid view cells: " << mOnlyValidViewCells << endl;
282        Debug << "construction samples: " << mConstructionSamples << endl;
283        Debug << "post process samples: " << mPostProcessSamples << endl;
284        Debug << "post process use rays for merge: " << mUseRaysForMerge << endl;
285        Debug << "visualization samples: " << mVisualizationSamples << endl;
286        Debug << "construction samples per pass: " << mSamplesPerPass << endl;
287        Debug << "export to file: " << mExportViewCells << endl;
288       
289        Debug << "active view cells: " << mNumActiveViewCells << endl;
290        Debug << "post process compress: " << mCompressViewCells << endl;
291        Debug << "visualization use clipPlane: " << mUseClipPlaneForViz << endl;
292        Debug << "post process merge: " << mMergeViewCells << endl;
293        Debug << "evaluate view cells: " << mEvaluateViewCells << endl;
294        Debug << "sampling type: " << mSamplingType << endl;
295        Debug << "render cost evaluation type: " << sRenderCostEvaluationType << endl;
296        Debug << "evaluation sampling type: " << mEvaluationSamplingType << endl;
297        Debug << "show visualization: " << mShowVisualization << endl;
298        Debug << "filter width: " << mFilterWidth << endl;
299        Debug << "sample after subdivision: " << SAMPLE_AFTER_SUBDIVISION << endl;
300
301        Debug << "export bounding boxes: " << mExportBboxesForPvs << endl;
302        Debug << "export pvs for view cells: " << mExportPvs << endl;
303        Debug << "use kd pvs " << mUseKdPvs << endl;
304        Debug << endl;
305}
306
307
308ViewCellsManager::~ViewCellsManager()
309{
310        // HACK: if view cells tree does not
311        // handle view cells, we have to do it here
312        // question: rather create view cells resource manager?
313        if (!ViewCellsTreeConstructed())
314        {
315                CLEAR_CONTAINER(mViewCells);
316        }
317        else
318        {
319                DEL_PTR(mViewCellsTree);
320        }
321
322        DEL_PTR(mMixtureDistribution);
323}
324
325
326Intersectable *
327ViewCellsManager::GetIntersectable(const VssRay &ray, const bool isTermination) const
328{
329        if (mUseKdPvs)
330        {
331                float area = GetPreprocessor()->mKdTree->GetBox().SurfaceArea()*KD_PVS_AREA;
332                KdNode *node = GetPreprocessor()->mKdTree->GetNode(isTermination ?
333                                                                                                                 ray.mTermination : ray.mOrigin,
334                                                                                                                 area);
335        return GetPreprocessor()->mKdTree->GetOrCreateKdIntersectable(node);
336        }
337        else
338        {
339                return isTermination ? ray.mTerminationObject : ray.mOriginObject;
340        }
341}
342
343
344void
345ViewCellsManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
346{
347  GetPreprocessor()->mKdTree->CollectObjects(box, objects);
348}
349
350AxisAlignedBox3 ViewCellsManager::GetViewCellBox(ViewCell *vc)
351{
352  Mesh *m = vc->GetMesh();
353 
354  if (m)
355  {
356          m->ComputeBoundingBox();
357          return m->mBox;
358  }
359
360  AxisAlignedBox3 box;
361  box.Initialize();
362 
363  if (!vc->IsLeaf()) {
364        ViewCellInterior *vci = (ViewCellInterior *) vc;
365       
366        ViewCellContainer::iterator it = vci->mChildren.begin();
367        for (; it != vci->mChildren.end(); ++it) {
368          box.Include(GetViewCellBox(*it));
369        }
370  }
371 
372  return box;
373}
374
375
376int ViewCellsManager::CastPassSamples(const int samplesPerPass,
377                                                                          const vector<int> &strategies,
378                                                                          VssRayContainer &passSamples
379                                                                          ) const
380{
381        long startTime = GetTime();
382
383        SimpleRayContainer simpleRays;
384       
385        simpleRays.reserve(samplesPerPass);
386        passSamples.reserve(samplesPerPass * 2); // always creates double rays
387
388        // create one third of each type
389        int castRays = 0;
390       
391        const int numRaysPerPass = samplesPerPass / (int)strategies.size();
392        vector<int>::const_iterator iit, iit_end = strategies.end();
393
394        for (iit = strategies.begin(); iit != iit_end; ++ iit)
395        {
396                const int stype = *iit;
397                const int newRays =
398                        mPreprocessor->GenerateRays(numRaysPerPass, stype, simpleRays);
399
400                cout << "cast " << newRays << " rays of strategy " << stype << endl;
401                castRays += newRays;
402        }
403
404        cout << "generated " << samplesPerPass << " samples in "
405                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
406
407        startTime = GetTime();
408
409        // shoot simple ray and add it to importance samples
410        mPreprocessor->CastRays(simpleRays, passSamples, true);
411        cout << "cast " <<  samplesPerPass << " samples in "
412                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
413
414        return (int)passSamples.size();
415}
416
417
418/// helper function which destroys rays or copies them into the output ray container
419inline void disposeRays(VssRayContainer &rays, VssRayContainer *outRays)
420{
421        cout << "disposing samples ... ";
422        long startTime = GetTime();
423        int n = (int)rays.size();
424
425        if (outRays)
426        {
427                VssRayContainer::const_iterator it, it_end = rays.end();
428                for (it = rays.begin(); it != it_end; ++ it)
429                {
430                        outRays->push_back(*it);
431                }
432        }
433        else
434        {
435                VssRayContainer::const_iterator it, it_end = rays.end();
436                for (it = rays.begin(); it != it_end; ++ it)
437                {
438                        if (!(*it)->IsActive())
439                                delete (*it);
440                }
441        }
442
443        cout << "finished" << endl;
444        Debug << "disposed " << n << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
445}
446
447
448int ViewCellsManager::Construct(Preprocessor *preprocessor, VssRayContainer *outRays)
449{
450        int numSamples = 0;
451
452        SimpleRayContainer simpleRays;
453        VssRayContainer initialSamples;
454
455        // store pointer to preprocessor for further use during construction
456        mPreprocessor = preprocessor;
457       
458
459        ///////////////////////////////////////////////////////
460        //-- Initial sampling for the construction of the view cell hierarchy.
461        //-- We use uniform sampling / box based sampling.
462       
463        long startTime = GetTime();
464        cout << "view cell construction: casting " << mInitialSamples << " initial samples ... " << endl;
465
466        // cast initial samples
467       
468        // mix of sampling strategies
469        vector<int>dummy;
470        //dummy.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
471        //dummy.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
472        //dummy.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
473
474        CastPassSamples(mInitialSamples, mStrategies, initialSamples);
475
476        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
477
478        // construct view cells
479        ConstructSubdivision(preprocessor->mObjects, initialSamples);
480
481        // initial samples count for overall samples ...
482        numSamples += mInitialSamples;
483
484        // rays can be passed or deleted
485        disposeRays(initialSamples, outRays);
486
487        cout << "time needed for initial construction: "
488                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
489
490        Debug << "time needed for initial construction: "
491                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
492
493        // collect view cells and compute statistics
494        ResetViewCells();
495
496
497        ///////////////////
498        //-- Initial hierarchy construction finished.
499        //-- We can do some stats and visualization
500       
501        if (0)
502        {
503                //-- export initial view cell partition
504                Debug << "\nView cells after initial sampling:\n" << mCurrentViewCellsStats << endl;
505
506                const string filename("viewcells.wrl");
507                Exporter *exporter = Exporter::GetExporter(filename.c_str());
508       
509                if (exporter)
510                {
511                        cout << "exporting initial view cells (=leaves) to " << filename.c_str() << " ... ";
512
513                        if (mExportGeometry)
514                        {
515                                exporter->ExportGeometry(preprocessor->mObjects);
516                        }
517
518                        exporter->SetWireframe();
519                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
520
521                        delete exporter;
522                        cout << "finished" << endl;
523                }
524        }
525
526
527        //////////////////////
528        //-- Cast some more sampling after initial construction.
529        //-- The additional rays can be used to gain
530        //-- some more information before the bottom-up merge
531        //-- note: guided rays could be used for this task
532
533        // time spent after construction of the initial partition
534        startTime = GetTime();
535        const int n = mConstructionSamples; //+initialSamples;
536
537        while (numSamples < n)
538        {
539                cout << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
540                Debug << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
541
542                VssRayContainer constructionSamples;
543
544                // cast new samples
545                numSamples += CastPassSamples(mSamplesPerPass,
546                                                                          mStrategies,
547                                                                          constructionSamples);
548
549                cout << "finished" << endl;
550                cout << "computing sample contribution for " << (int)constructionSamples.size() << " samples ... ";
551
552                // computes sample contribution of cast rays TODO: leak?
553                if (SAMPLE_AFTER_SUBDIVISION)
554                        ComputeSampleContributions(constructionSamples, true, false);
555
556                cout << "finished" << endl;
557
558                disposeRays(constructionSamples, outRays);
559                cout << "total samples: " << numSamples << endl;
560        }
561
562        if (0)
563        {
564                ///////////////
565                //-- Get stats after the additional sampling step
566                //-- and before the bottom-up merge step
567
568                EvaluateViewCellsStats();
569                Debug << "\noriginal view cell partition before post process:\n"
570                          << mCurrentViewCellsStats << endl;
571       
572                mRenderer->RenderScene();
573                SimulationStatistics ss;
574                dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
575
576                Debug << ss << endl;
577        }
578
579        ////////////////////
580        //-- post processing of the initial construction
581        //-- We can bottom-up merge the view cells in this step
582        //-- We can additionally cast some post processing sample rays.
583        //-- These rays can be used to store the view cells with the rays
584
585        VssRayContainer postProcessSamples;
586        cout << "casting " << mPostProcessSamples << " post processing samples ... ";
587       
588        CastPassSamples(mPostProcessSamples, mStrategies, postProcessSamples);
589
590        cout << "finished" << endl;
591        cout << "starting post processing and visualization" << endl;
592
593        // store view cells with rays for post processing?
594        const bool storeViewCells = true;
595
596        if (SAMPLE_AFTER_SUBDIVISION)
597                ComputeSampleContributions(postProcessSamples, true, storeViewCells);
598
599        PostProcess(preprocessor->mObjects, postProcessSamples);
600
601        const float secs = TimeDiff(startTime, GetTime()) * 1e-3f;
602        cout << "post processing (=merge) finished in " << secs << " secs" << endl;
603
604        Debug << "post processing time: " << secs << endl;
605        disposeRays(postProcessSamples, outRays);
606
607
608        ////////////////
609        //-- Evaluation of the resulting view cell partition.
610        //-- We cast a number of new samples and measure the render cost
611
612        if (mEvaluateViewCells)
613        {
614                EvalViewCellPartition();
615        }
616       
617        /////////////////
618        //-- Show some visualizations
619
620        if (mShowVisualization)
621        {
622                if (0)
623                {
624                        mStrategies.clear();
625                        mStrategies.push_back(SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION);
626                }
627
628                ///////////////
629                //-- visualization rays, e.g., to show some samples in the scene
630               
631                VssRayContainer visSamples;
632                int numSamples = CastPassSamples(mVisualizationSamples,
633                                                                                 mStrategies,
634                                                                                 visSamples);
635
636                if (SAMPLE_AFTER_SUBDIVISION)
637                        ComputeSampleContributions(visSamples, true, storeViewCells);
638
639                // various visualizations
640                Visualize(preprocessor->mObjects, visSamples);
641
642                disposeRays(visSamples, outRays);
643        }
644
645        // recalculate view cells
646        EvaluateViewCellsStats();
647
648        if (1) CompressViewCells();
649
650        // write view cells to disc
651        if (mExportViewCells)
652        {
653                char filename[100];
654
655                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
656                ExportViewCells(filename, mExportPvs, mPreprocessor->mObjects);
657        }
658
659        return numSamples;
660}
661
662
663AxisAlignedPlane *ViewCellsManager::GetClipPlane()
664{
665        return mUseClipPlaneForViz ? &mClipPlaneForViz : NULL;
666}
667
668
669
670
671ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
672                                                                                                  ObjectContainer *objects,
673                                                                                                  bool finalizeViewCells,
674                                                                                                  BoundingBoxConverter *bconverter)
675                                                                                                 
676{
677        ViewCellsParser parser;
678        ViewCellsManager *vm = NULL;
679
680        const long startTime = GetTime();
681        bool success = parser.ParseViewCellsFile(filename, &vm, objects, bconverter);
682
683        cout<<"viewcells parsed "<<endl<<flush;
684       
685        if (success)
686        {
687                //vm->ResetViewCells();
688                //hack
689                vm->mViewCells.clear();
690                ViewCellContainer leaves;
691                vm->mViewCellsTree->CollectLeaves(vm->mViewCellsTree->GetRoot(), leaves);
692
693                ViewCellContainer::const_iterator it, it_end = leaves.end();
694
695                for (it = leaves.begin(); it != it_end; ++ it)
696                {
697                        vm->mViewCells.push_back(*it);
698                }
699                vm->mViewCellsFinished = true;
700                vm->mMaxPvsSize = (int)objects->size();
701
702                if (finalizeViewCells)
703                {
704                        // create the meshes and compute volumes
705                        vm->FinalizeViewCells(true);
706                        // vm->mViewCellsTree->AssignRandomColors();
707                }
708
709                Debug << (int)vm->mViewCells.size() << " view cells loaded in "
710                          << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
711        }
712        else
713        {
714                Debug << "Error: loading view cells failed!" << endl;
715                DEL_PTR(vm);
716        }
717
718        return vm;
719}
720
721
722bool VspBspViewCellsManager::ExportViewCells(const string filename,
723                                                                                         const bool exportPvs,
724                                                                                         const ObjectContainer &objects)
725{
726        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
727        {
728                return false;
729        }
730
731        cout << "exporting view cells to xml ... ";
732
733        OUT_STREAM stream(filename.c_str());
734
735        // for output we need unique ids for each view cell
736        CreateUniqueViewCellIds();
737
738        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
739        stream << "<VisibilitySolution>" << endl;
740
741        if (exportPvs)
742        {
743                //-- export bounding boxes
744                stream << "<BoundingBoxes>" << endl;
745
746                if (mUseKdPvs)
747                {
748                        vector<KdIntersectable *>::iterator kit, kit_end = GetPreprocessor()->mKdTree->mKdIntersectables.end();
749
750                        int id = 0;
751                        for (kit = GetPreprocessor()->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
752                        {
753                                Intersectable *obj = *kit;
754                                const AxisAlignedBox3 box = obj->GetBox();
755                 
756                                obj->SetId(id);
757       
758                                stream << "<BoundingBox" << " id=\"" << id << "\""
759                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
760                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
761                        }
762                }
763                else
764                {
765                        ObjectContainer::const_iterator oit, oit_end = objects.end();
766               
767                        for (oit = objects.begin(); oit != oit_end; ++ oit)
768                        {
769                                const AxisAlignedBox3 box = (*oit)->GetBox();
770
771                                ////////////
772                                //-- the bounding boxes
773
774                                stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
775                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
776                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
777                        }
778                }
779
780                stream << "</BoundingBoxes>" << endl;
781        }
782
783       
784        /////////////
785        //-- export the view cells and the pvs
786
787        const int numViewCells = mCurrentViewCellsStats.viewCells;
788        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
789
790        mViewCellsTree->Export(stream, exportPvs);
791
792        stream << "</ViewCells>" << endl;
793
794
795        //////////
796        //-- export the view space hierarchy
797       
798        stream << "<ViewSpaceHierarchy type=\"bsp\""
799                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
800                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
801
802        mVspBspTree->Export(stream);
803        stream << "</ViewSpaceHierarchy>" << endl;
804
805        stream << "</VisibilitySolution>" << endl;
806
807        stream.close();
808        cout << "finished" << endl;
809
810        return true;
811}
812
813void ViewCellsManager::EvalViewCellHistogram(const string filename,
814                                                                                         const int nViewCells)
815{
816        std::ofstream outstream;
817        outstream.open(filename.c_str());
818
819        ViewCellContainer viewCells;
820        // $$ JB hack - the collect best viewcells does not work?
821#if 1
822        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
823#else
824        viewCells = mViewCells;
825#endif
826
827        float maxRenderCost, minRenderCost;
828
829        // sort by render cost
830        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerRenderCost);
831
832        minRenderCost = viewCells.front()->GetRenderCost();
833        maxRenderCost = viewCells.back()->GetRenderCost();
834
835        Debug << "histogram min rc: " << minRenderCost << " max rc: " << maxRenderCost << endl;
836
837    int histoIntervals;
838        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
839        const int intervals = min(histoIntervals, (int)viewCells.size());
840
841        int histoMaxVal;
842        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
843        maxRenderCost = min((float)histoMaxVal, maxRenderCost);
844
845       
846        const float range = maxRenderCost - minRenderCost;
847        const float stepSize = range / (float)intervals;
848
849        float currentRenderCost = minRenderCost;//(int)ceil(minRenderCost);
850
851        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
852        const float totalVol = GetViewSpaceBox().GetVolume();
853        //const float totalVol = mViewCellsTree->GetRoot()->GetVolume();
854
855        int j = 0;
856        int i = 0;
857       
858        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();             
859
860        // count for integral
861        float volSum = 0;
862        int smallerCostSum = 0;
863       
864        // note can skip computations for view cells already
865        // evaluated and delete them from vector ...
866    while (1)
867        {
868                // count for histogram value
869                float volDif = 0;
870                int smallerCostDif = 0;
871
872                while ((i < (int)viewCells.size()) && (viewCells[i]->GetRenderCost() < currentRenderCost))
873                {
874                        volSum += viewCells[i]->GetVolume();
875                        volDif += viewCells[i]->GetVolume();
876
877                        ++ i;
878                        ++ smallerCostSum;
879                        ++ smallerCostDif;
880                }
881               
882                if ((i >= (int)viewCells.size()) || (currentRenderCost >= maxRenderCost))
883                        break;
884               
885                const float rcRatio = currentRenderCost / maxRenderCost;
886                const float volRatioSum = volSum / totalVol;
887                const float volRatioDif = volDif / totalVol;
888
889                outstream << "#Pass\n" << j ++ << endl;
890                outstream << "#RenderCostRatio\n" << rcRatio << endl;
891                outstream << "#WeightedCost\n" << currentRenderCost / totalVol << endl;
892                outstream << "#ViewCellsDif\n" << smallerCostDif << endl;
893                outstream << "#ViewCellsSum\n" << smallerCostSum << endl;       
894                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
895                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
896
897                // increase current render cost
898                currentRenderCost += stepSize;
899        }
900
901        outstream.close();
902}
903
904void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
905                                                                                                           const int nViewCells)
906{
907        std::ofstream outstream;
908        outstream.open(filename.c_str());
909
910        ViewCellContainer viewCells;
911       
912        // $$ JB hack - the collect best viewcells does not work?
913#if 0
914        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
915#else
916        viewCells = mViewCells;
917#endif
918        ViewCellContainer::iterator it = viewCells.begin(), it_end = viewCells.end();           
919        for (; it != it_end; ++it)
920        {
921                if (1)
922                        (*it)->UpdatePvsCost();
923                else
924                        (*it)->SetPvsCost((float)(*it)->GetFilteredPvsSize());
925        }
926
927        float maxPvs, maxVal, minVal;
928       
929        // sort by pvs size
930        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerPvs);
931
932        maxPvs = viewCells.back()->GetPvsCost();
933        minVal = 0;
934
935        // hack: normalize pvs size
936        int histoMaxVal;
937        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
938        maxVal = max((float)histoMaxVal, maxPvs);
939               
940        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
941                << " real maxpvs " << maxPvs << endl;
942
943        int histoIntervals;
944        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
945        const int intervals = min(histoIntervals, (int)viewCells.size());
946
947        const float range = maxVal - minVal;
948        int stepSize = (int)(range / intervals);
949
950        // set step size to avoid endless loop
951        if (!stepSize) stepSize = 1;
952       
953        Debug << "intervals " << histoIntervals << endl;
954        Debug << "stepsize: " << stepSize << endl;
955        cout << "intervals " << histoIntervals << endl;
956        cout << "stepsize: " << stepSize << endl;
957
958        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
959        const float totalVol = GetViewSpaceBox().GetVolume();
960
961        float currentPvs = minVal;
962       
963        int i = 0;
964        int j = 0;
965        float volSum = 0;
966        int smallerSum = 0;
967
968        it = viewCells.begin();
969       
970        for (int j = 0; j < intervals; ++ j)
971        {
972                float volDif = 0;
973                int smallerDif = 0;
974
975                while ((i < (int)viewCells.size()) &&
976                           (viewCells[i]->GetPvsCost() < currentPvs))
977                {
978                        volDif += viewCells[i]->GetVolume();
979                        volSum += viewCells[i]->GetVolume();
980
981                        ++ i;
982                        ++ smallerDif;
983                        ++ smallerSum;
984                }
985               
986                //              if (0 && (i < (int)viewCells.size()))
987                //                Debug << "new pvs cost increase: " << mViewCellsTree->GetPvsCost(viewCells[i])
988                //                              << " " << currentPvs << endl;
989               
990                const float volRatioDif = volDif / totalVol;
991                const float volRatioSum = volSum / totalVol;
992
993                outstream << "#Pass\n" << j << endl;
994                outstream << "#Pvs\n" << currentPvs << endl;
995                outstream << "#ViewCellsDif\n" << smallerDif << endl;
996                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
997                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
998                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
999       
1000                //-- increase current pvs size to define next interval
1001                currentPvs += stepSize;
1002        }
1003
1004        outstream.close();
1005}
1006
1007
1008void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
1009                                                                                                           ViewCellContainer &viewCells)
1010{
1011        std::ofstream outstream;
1012        outstream.open(filename.c_str());
1013
1014        float maxPvs, maxVal, minVal;
1015       
1016        // sort by pvs size
1017        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerPvs);
1018
1019        maxPvs = viewCells.back()->GetPvsCost();
1020        minVal = 0;
1021
1022        // hack: normalize pvs size
1023        int histoMaxVal;
1024        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1025        maxVal = max((float)histoMaxVal, maxPvs);
1026               
1027        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
1028                << " real maxpvs " << maxPvs << endl;
1029
1030        int histoIntervals;
1031        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1032        const int intervals = min(histoIntervals, (int)viewCells.size());
1033
1034        const float range = maxVal - minVal;
1035        int stepSize = (int)(range / intervals);
1036
1037        // set step size to avoid endless loop
1038        if (!stepSize) stepSize = 1;
1039       
1040        Debug << "intervals " << histoIntervals << endl;
1041        Debug << "stepsize: " << stepSize << endl;
1042        cout << "intervals " << histoIntervals << endl;
1043        cout << "stepsize: " << stepSize << endl;
1044
1045        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1046        const float totalVol = GetViewSpaceBox().GetVolume();
1047
1048        float currentPvs = minVal;
1049       
1050        int i = 0;
1051        int j = 0;
1052        float volSum = 0;
1053        int smallerSum = 0;
1054
1055        //ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();   
1056       
1057        for (int j = 0; j < intervals; ++ j)
1058        {
1059                float volDif = 0;
1060                int smallerDif = 0;
1061
1062                while ((i < (int)viewCells.size()) &&
1063                           (viewCells[i]->GetPvsCost() < currentPvs))
1064                {
1065                        volDif += viewCells[i]->GetVolume();
1066                        volSum += viewCells[i]->GetVolume();
1067
1068                        ++ i;
1069                        ++ smallerDif;
1070                        ++ smallerSum;
1071                }
1072               
1073                //              if (0 && (i < (int)viewCells.size()))
1074                //                Debug << "new pvs cost increase: " << mViewCellsTree->GetPvsCost(viewCells[i])
1075                //                              << " " << currentPvs << endl;
1076               
1077                const float volRatioDif = volDif / totalVol;
1078                const float volRatioSum = volSum / totalVol;
1079
1080                outstream << "#Pass\n" << j << endl;
1081                outstream << "#Pvs\n" << currentPvs << endl;
1082                outstream << "#ViewCellsDif\n" << smallerDif << endl;
1083                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
1084                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1085                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1086       
1087                //-- increase current pvs size to define next interval
1088                currentPvs += stepSize;
1089        }
1090
1091        outstream.close();
1092}
1093
1094
1095bool ViewCellsManager::GetExportPvs() const
1096{
1097        return mExportPvs;
1098}
1099
1100
1101void ViewCellsManager::ResetPvs()
1102{
1103        if (ViewCellsTreeConstructed())
1104        {
1105                mViewCellsTree->ResetPvs();
1106        }
1107        else
1108        {
1109                cout << "view cells tree not constructed" << endl;
1110        }
1111}
1112
1113
1114void ViewCellsManager::ExportStats(const string &fileName)
1115{
1116        mViewCellsTree->ExportStats(fileName);
1117}
1118
1119
1120void ViewCellsManager::EvalViewCellPartition()
1121{
1122        int samplesPerPass;
1123        int numSamples;
1124        int castSamples = 0;
1125        char str[64];
1126        int oldSamples = 0;
1127
1128        int samplesForStats;
1129
1130        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
1131        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
1132        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
1133
1134        char statsPrefix[100];
1135        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
1136
1137        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
1138        Debug << "view cell evaluation samples: " << numSamples << endl;
1139        Debug << "view cell stats prefix: " << statsPrefix << endl;
1140
1141        cout << "reseting pvs ... ";
1142               
1143        const bool startFromZero = true;
1144
1145        // reset pvs and start over from zero
1146        if (startFromZero)
1147        {
1148                mViewCellsTree->ResetPvs();
1149        }
1150        else // start from current sampless
1151        {
1152                // statistics before casting more samples
1153                cout << "compute new statistics ... ";
1154                sprintf(str, "-%09d-eval.log", castSamples);
1155                string fName = string(statsPrefix) + string(str);
1156
1157                mViewCellsTree->ExportStats(fName);
1158                cout << "finished" << endl;
1159        }
1160
1161        cout << "finished" << endl;
1162    cout << "Evaluating view cell partition ... " << endl;
1163
1164        while (castSamples < numSamples)
1165        {               
1166                ///////////////
1167                //-- we have to use uniform sampling strategy for construction rays
1168
1169                VssRayContainer evaluationSamples;
1170                const int samplingType = mEvaluationSamplingType;
1171
1172                long startTime = GetTime();
1173
1174                cout << "casting " << samplesPerPass << " samples ... ";
1175                Debug << "casting " << samplesPerPass << " samples ... ";
1176
1177                CastPassSamples(samplesPerPass, mStrategies, evaluationSamples);
1178               
1179                castSamples += samplesPerPass;
1180
1181                Real timeDiff = TimeDiff(startTime, GetTime());
1182               
1183                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1184                cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1185               
1186                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1187                Debug << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1188
1189                startTime = GetTime();
1190
1191                ComputeSampleContributions(evaluationSamples, true, false);
1192
1193                timeDiff = TimeDiff(startTime, GetTime());
1194                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1195                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1196
1197                if ((castSamples >= samplesForStats + oldSamples) || (castSamples >= numSamples))
1198                {
1199                        oldSamples += samplesForStats;
1200
1201                        ///////////
1202                        //-- output stats
1203
1204                        sprintf(str, "-%09d-eval.log", castSamples);
1205                        string fileName = string(statsPrefix) + string(str);
1206
1207                        ///////////////
1208                        //-- propagate pvs or pvs size information
1209
1210                        startTime = GetTime();
1211                        ObjectPvs pvs;
1212
1213                        cout << "updating pvs for evaluation ... " << endl;
1214
1215                        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), pvs);
1216
1217                        timeDiff = TimeDiff(startTime, GetTime());
1218                        cout << "finished updating the pvs in " << timeDiff * 1e-3 << " secs" << endl;
1219                        Debug << "pvs evaluated in " << timeDiff * 1e-3 << " secs" << endl;
1220               
1221                        startTime = GetTime();
1222                        cout << "compute new statistics ... " << endl;
1223
1224                        ExportStats(fileName);
1225
1226                        timeDiff = TimeDiff(startTime, GetTime());
1227                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1228                        Debug << "statistis computed in " << timeDiff * 1e-3 << " secs" << endl;
1229                }
1230
1231                disposeRays(evaluationSamples, NULL);
1232        }
1233       
1234
1235        ////////////
1236        //-- histogram
1237
1238        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
1239        bool useHisto;
1240        int histoStepSize;
1241
1242        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
1243        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
1244
1245        if (useHisto)
1246        {
1247                // evaluate view cells in a histogram           
1248                char s[64];
1249
1250                for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
1251                {
1252                        string filename;
1253
1254                        cout << "computing histogram for " << pass << " view cells" << endl;
1255#if 0
1256                        //-- evaluate histogram for render cost
1257                        sprintf(s, "-%09d-histo.log", pass);
1258                        filename = string(statsPrefix) + string(s);
1259
1260                        EvalViewCellHistogram(filename, pass);
1261
1262#endif
1263                        //////////////////////////////////////////
1264            //-- evaluate histogram for pvs size
1265
1266                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
1267
1268                        sprintf(s, "-%09d-histo-pvs.log", pass);
1269                        filename = string(statsPrefix) + string(s);
1270
1271                        EvalViewCellHistogram(filename, pass);
1272                        //                      EvalViewCellHistogramForPvsSize(filename, pass);
1273                }
1274        }
1275}
1276
1277
1278inline float EvalMergeCost(ViewCell *root, ViewCell *candidate)
1279{
1280        return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
1281}
1282
1283
1284/// Returns index of the best view cells of the neighborhood
1285static int GetBestViewCellIdx(ViewCell *root, const ViewCellContainer &neighborhood)
1286{
1287        int bestViewCellIdx = 0;
1288
1289        float mergeCost = Limits::Infinity;
1290        int i = 0;
1291
1292        ViewCellContainer::const_iterator vit, vit_end = neighborhood.end();
1293
1294        for (vit = neighborhood.begin(); vit != vit_end; ++ vit, ++ i)
1295        {
1296                const float mc = EvalMergeCost(root, *vit);
1297               
1298                if (mc < mergeCost)
1299                {
1300                        mergeCost = mc;
1301                        bestViewCellIdx = i;
1302                }
1303        }
1304
1305        return bestViewCellIdx;
1306}
1307
1308
1309void ViewCellsManager::SetMaxFilterSize(const int size)
1310{
1311        mMaxFilterSize = size;
1312}
1313
1314
1315float ViewCellsManager::EvalRenderCost(Intersectable *obj) //const
1316{
1317        switch (sRenderCostEvaluationType)
1318        {
1319        case PER_OBJECT:
1320                return 1.0f;
1321       
1322        case PER_TRIANGLE:
1323                {
1324                        return (float)obj->NumberOfFaces();
1325                }
1326        default:
1327                cout << "default" << endl;
1328                return 1.0f;
1329        }
1330
1331        // should not come here
1332        return 0.0f;
1333}
1334
1335
1336ViewCell *ViewCellsManager::ConstructLocalMergeTree(ViewCell *currentViewCell,
1337                                                                                                        const ViewCellContainer &viewCells)
1338{
1339        ViewCell *root = currentViewCell;
1340        ViewCellContainer neighborhood = viewCells;
1341
1342        ViewCellContainer::const_iterator it, it_end = neighborhood.end();
1343
1344        const int n = min(mMaxFilterSize, (int)neighborhood.size());
1345       
1346        /////////////////
1347        //-- use priority queue to merge leaf pairs
1348       
1349        for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1350        {
1351                const int bestViewCellIdx = GetBestViewCellIdx(root, neighborhood);
1352               
1353                ViewCell *bestViewCell = neighborhood[bestViewCellIdx];
1354       
1355                // remove from vector
1356                swap(neighborhood[bestViewCellIdx], neighborhood.back());
1357                neighborhood.pop_back();
1358       
1359                if (!bestViewCell || !root)
1360            cout << "warning!!" << endl;
1361               
1362                // create new root of the hierarchy
1363                root = MergeViewCells(root, bestViewCell);
1364        }
1365
1366        return root;   
1367}
1368
1369
1370struct SortableViewCellEntry {
1371
1372        SortableViewCellEntry() {}
1373        SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
1374
1375        float mValue;
1376        ViewCell *mViewCell;
1377
1378        friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
1379                return a.mValue < b.mValue;
1380        }
1381};
1382
1383
1384ViewCell * ViewCellsManager::ConstructLocalMergeTree2(ViewCell *currentViewCell,
1385                                                                                                          const ViewCellContainer &viewCells)
1386{
1387 
1388  vector<SortableViewCellEntry> neighborhood(viewCells.size());
1389  int i, j;
1390  for (i = 0, j = 0; i < viewCells.size(); i++) {
1391        if (viewCells[i] != currentViewCell)
1392          neighborhood[j++] = SortableViewCellEntry(
1393                                                                                                EvalMergeCost(currentViewCell, viewCells[i]),
1394                                                                                                viewCells[i]);
1395  }
1396  neighborhood.resize(j);
1397 
1398  sort(neighborhood.begin(), neighborhood.end());
1399 
1400  ViewCell *root = currentViewCell;
1401 
1402  vector<SortableViewCellEntry>::const_iterator it, it_end = neighborhood.end();
1403 
1404  const int n = min(mMaxFilterSize, (int)neighborhood.size());
1405  //-- use priority queue to merge leaf pairs
1406 
1407  //cout << "neighborhood: " << neighborhood.size() << endl;
1408  for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1409  {
1410          ViewCell *bestViewCell = neighborhood[nMergedViewCells].mViewCell;
1411          //cout <<nMergedViewCells<<":"<<"homogenity=" <<neighborhood[nMergedViewCells].mValue<<endl;
1412          // create new root of the hierarchy
1413          root = MergeViewCells(root, bestViewCell);
1414          // set negative cost so that this view cell gets deleted
1415          root->SetMergeCost(-1.0f);
1416  }
1417 
1418  return root; 
1419}
1420
1421void
1422ViewCellsManager::DeleteLocalMergeTree(ViewCell *vc
1423                                                                           ) const
1424{
1425        if (!vc->IsLeaf() && vc->GetMergeCost() < 0.0f)
1426        {       
1427                ViewCellInterior *vci = (ViewCellInterior *) vc;
1428                ViewCellContainer::const_iterator it, it_end = vci->mChildren.end();
1429
1430        for (it = vci->mChildren.begin(); it != it_end; ++ it)
1431                        DeleteLocalMergeTree(*it);
1432               
1433                vci->mChildren.clear();
1434               
1435                delete vci;
1436  }
1437}
1438
1439
1440bool ViewCellsManager::CheckValidity(ViewCell *vc,
1441                                                                         int minPvsSize,
1442                                                                         int maxPvsSize) const
1443{
1444
1445        if ((vc->GetPvs().EvalPvsCost() > maxPvsSize) ||
1446                (vc->GetPvs().EvalPvsCost() < minPvsSize))
1447        {
1448                return false;
1449        }
1450
1451        return true;
1452}
1453
1454
1455int ViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
1456                                                                                          ViewCellContainer &viewCells) const
1457{
1458        return 0;
1459};
1460
1461
1462AxisAlignedBox3 ViewCellsManager::GetFilterBBox(const Vector3 &viewPoint,
1463                                                                                                const float width) const
1464{
1465  float w = Magnitude(mViewSpaceBox.Size())*width;
1466  Vector3 min = viewPoint - w * 0.5f;
1467  Vector3 max = viewPoint + w * 0.5f;
1468 
1469  return AxisAlignedBox3(min, max);
1470}
1471
1472
1473void ViewCellsManager::GetPrVS(const Vector3 &viewPoint,
1474                                                           PrVs &prvs,
1475                                                           const float filterWidth)
1476{
1477  ViewCell *currentViewCell = GetViewCell(viewPoint);
1478
1479  if (mMaxFilterSize < 1) {
1480        prvs.mViewCell = currentViewCell;
1481        return;
1482  }
1483 
1484  const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
1485 
1486  if (currentViewCell)
1487        {
1488          ViewCellContainer viewCells;
1489          ComputeBoxIntersections(box, viewCells);
1490         
1491          ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
1492          prvs.mViewCell = root;
1493         
1494        }
1495  else
1496        {
1497          prvs.mViewCell = NULL;
1498          //prvs.mPvs = root->GetPvs();
1499        }
1500}
1501
1502
1503bool ViewCellsManager::ViewCellsTreeConstructed() const
1504{
1505    return (mViewCellsTree && mViewCellsTree->GetRoot());
1506}
1507
1508
1509void ViewCellsManager::SetValidity(ViewCell *vc,
1510                                                                   int minPvs,
1511                                                                   int maxPvs) const
1512{
1513        vc->SetValid(CheckValidity(vc, minPvs, maxPvs));
1514}
1515
1516
1517void
1518ViewCellsManager::SetValidity(
1519                                                          int minPvsSize,
1520                                                          int maxPvsSize) const
1521{
1522        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1523
1524
1525        for (it = mViewCells.begin(); it != it_end; ++ it)
1526        {
1527                SetValidity(*it, minPvsSize, maxPvsSize);
1528        }
1529}
1530
1531void
1532ViewCellsManager::SetValidityPercentage(
1533                                                                                const float minValid,
1534                                                                                const float maxValid
1535                                                                                )
1536{
1537  ObjectPvs dummyPvs;
1538  // update pvs sizes
1539  for (int i = 0; i < (int)mViewCells.size(); ++ i) {
1540        UpdatePvsForEvaluation(mViewCells[i], dummyPvs);
1541  }
1542 
1543  sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
1544 
1545  int start = (int)(mViewCells.size() * minValid);
1546  int end = (int)(mViewCells.size() * maxValid);
1547 
1548  for (int i = 0; i < (int)mViewCells.size(); ++ i)
1549        {
1550          //      cout<<"pvs:"<<mViewCells[i]->GetCachedPvsCost()<<endl;
1551          mViewCells[i]->SetValid(i >= start && i <= end);
1552        }
1553}
1554
1555
1556int ViewCellsManager::CountValidViewcells() const
1557{
1558        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1559        int valid = 0;
1560
1561        for (it = mViewCells.begin(); it != it_end; ++ it)
1562        {       
1563                if ((*it)->GetValid())
1564                        ++ valid;
1565        }
1566
1567        return valid;
1568}
1569
1570
1571bool ViewCellsManager::LoadViewCellsGeometry(const string filename,
1572                                                                                         const bool extrudeBaseTriangles)
1573{
1574        /// we use predefined view cells from now on
1575        mUsePredefinedViewCells = true;
1576        X3dParser parser;
1577       
1578        if (extrudeBaseTriangles)
1579        {
1580                Environment::GetSingleton()->GetFloatValue("ViewCells.height", parser.mViewCellHeight);
1581                const bool success = parser.ParseFile(filename, *this);
1582
1583                if (!success)
1584                        return false;
1585        }
1586        else
1587        {
1588                // hack: use standard mesh loading
1589                // create temporary scene graph for loading the view cells geometry
1590                // note: delete the meshes as they are created two times for transformed mesh instances.
1591                SceneGraphNode *root = new SceneGraphNode();
1592                const bool success = parser.ParseFile(filename, root, true);
1593               
1594                if (!success)
1595                {
1596                        DEL_PTR(root);
1597                        return false;
1598                }
1599
1600                ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
1601               
1602                for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
1603                {
1604                        Mesh *mesh;
1605                        if ((*oit)->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
1606                        {
1607                                TransformedMeshInstance *mit = dynamic_cast<TransformedMeshInstance *>(*oit);
1608                                mesh = MeshManager::GetSingleton()->CreateResource();
1609                                mit->GetTransformedMesh(*mesh);
1610                        }
1611                        else if ((*oit)->Type() == Intersectable::MESH_INSTANCE)
1612                        {
1613                                MeshInstance *mit = dynamic_cast<MeshInstance *>(*oit);
1614                                mesh = mit->GetMesh();
1615                        }
1616                        mesh->ComputeBoundingBox();
1617                        mViewCells.push_back(GenerateViewCell(mesh));
1618                }
1619
1620                DEL_PTR(root);
1621        }
1622
1623        // set view space box to bounding box of the view cells
1624        AxisAlignedBox3 bbox;
1625        bbox.Initialize();
1626        ViewCellContainer::iterator it = mViewCells.begin(), it_end = mViewCells.end();
1627
1628        for (; it != it_end; ++ it)
1629        {
1630                bbox.Include((*it)->GetMesh()->mBox);
1631        }
1632
1633        SetViewSpaceBox(bbox);
1634        cout << "view space box: " << bbox << endl;
1635        cout << "generated " << (int)mViewCells.size() << " view cells using the geometry " << filename << endl;
1636
1637        return true;
1638}
1639
1640
1641bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
1642{
1643  viewPoint = mViewSpaceBox.GetRandomPoint();
1644  return true;
1645}
1646
1647bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint, const Vector3 &params) const
1648{
1649  viewPoint = mViewSpaceBox.GetRandomPoint(params);
1650  return true;
1651}
1652
1653
1654float ViewCellsManager::GetViewSpaceVolume()
1655{
1656        return mViewSpaceBox.GetVolume() * (2.0f * sqr((float)M_PI));
1657}
1658
1659
1660bool ViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
1661{
1662        if (!ViewCellsConstructed())
1663        {
1664                return mViewSpaceBox.IsInside(viewPoint);
1665        }
1666        else
1667        {
1668                if (!mViewSpaceBox.IsInside(viewPoint))
1669                        return false;
1670
1671                ViewCell *viewcell = GetViewCell(viewPoint);
1672
1673                if (!viewcell || !viewcell->GetValid())
1674                        return false;
1675        }
1676
1677        return true;
1678}
1679
1680
1681float
1682ViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
1683                                                                                         const bool addRays,
1684                                                                                         const bool storeViewCells)
1685{
1686  float sum = 0.0f;
1687
1688  VssRayContainer::const_iterator it, it_end = rays.end();
1689 
1690  for (it = rays.begin(); it != it_end; ++ it)
1691        {
1692          if (!ViewCellsConstructed()) {
1693                // view cells not yet constructed
1694                // just take the lenghts of the rays as contributions
1695                if ((*it)->mTerminationObject)
1696                  sum += (*it)->Length();
1697          } else {
1698                sum += ComputeSampleContribution(*(*it), addRays, storeViewCells);
1699          }
1700        }
1701
1702  return sum;
1703}
1704
1705
1706void ViewCellsManager::EvaluateViewCellsStats()
1707{
1708        mCurrentViewCellsStats.Reset();
1709        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1710
1711        for (it = mViewCells.begin(); it != it_end; ++ it)
1712        {
1713                mViewCellsTree->UpdateViewCellsStats(*it, mCurrentViewCellsStats);
1714        }
1715}
1716
1717
1718void ViewCellsManager::EvaluateRenderStatistics(float &totalRenderCost,
1719                                                                                                float &expectedRenderCost,
1720                                                                                                float &deviation,
1721                                                                                                float &variance,
1722                                                                                                float &totalCost,
1723                                                                                                float &avgRenderCost)
1724{
1725        ////////////
1726        //-- compute expected value
1727
1728        totalRenderCost = 0;
1729        totalCost = 0;
1730
1731        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1732
1733        for (it = mViewCells.begin(); it != it_end; ++ it)
1734        {
1735                ViewCell *vc = *it;
1736                totalRenderCost += vc->GetPvs().EvalPvsCost() * vc->GetVolume();
1737                totalCost += (int)vc->GetPvs().EvalPvsCost();
1738        }
1739
1740        // normalize with view space box
1741        totalRenderCost /= mViewSpaceBox.GetVolume();
1742        expectedRenderCost = totalRenderCost / (float)mViewCells.size();
1743        avgRenderCost = totalCost / (float)mViewCells.size();
1744
1745
1746        ///////////
1747        //-- compute standard defiation
1748
1749        variance = 0;
1750        deviation = 0;
1751
1752        for (it = mViewCells.begin(); it != it_end; ++ it)
1753        {
1754                ViewCell *vc = *it;
1755
1756                float renderCost = vc->GetPvs().EvalPvsCost() * vc->GetVolume();
1757                float dev;
1758
1759                if (1)
1760                        dev = fabs(avgRenderCost - (float)vc->GetPvs().EvalPvsCost());
1761                else
1762                        dev = fabs(expectedRenderCost - renderCost);
1763
1764                deviation += dev;
1765                variance += dev * dev;
1766        }
1767
1768        variance /= (float)mViewCells.size();
1769        deviation /= (float)mViewCells.size();
1770}
1771
1772
1773float ViewCellsManager::GetArea(ViewCell *viewCell) const
1774{
1775        return viewCell->GetArea();
1776}
1777
1778
1779float ViewCellsManager::GetVolume(ViewCell *viewCell) const
1780{
1781        return viewCell->GetVolume();
1782}
1783
1784
1785void ViewCellsManager::CompressViewCells()
1786{
1787        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
1788                return;
1789
1790        ////////////
1791        //-- compression
1792       
1793        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
1794
1795        cout << "number of entries before compress: " << pvsEntries << endl;
1796        Debug << "number of entries before compress: " << pvsEntries << endl;
1797
1798        mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
1799
1800        pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
1801
1802        Debug << "number of entries after compress: " << pvsEntries << endl;
1803        cout << "number of entries after compress: " << pvsEntries << endl;
1804}
1805
1806
1807ViewCell *ViewCellsManager::ExtrudeViewCell(const Triangle3 &baseTri,
1808                                                                                        const float height) const
1809{
1810        // one mesh per view cell
1811        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
1812
1813        ////////////
1814        //-- construct prism
1815
1816        // bottom
1817        mesh->mFaces.push_back(new Face(2,1,0));
1818        // top
1819    mesh->mFaces.push_back(new Face(3,4,5));
1820        // sides
1821        mesh->mFaces.push_back(new Face(1, 4, 3, 0));
1822        mesh->mFaces.push_back(new Face(2, 5, 4, 1));
1823        mesh->mFaces.push_back(new Face(3, 5, 2, 0));
1824
1825
1826        /////////////
1827        //-- extrude new vertices for top of prism
1828
1829        const Vector3 triNorm = baseTri.GetNormal();
1830        Triangle3 topTri;
1831
1832        // add base vertices and calculate top vertices
1833        for (int i = 0; i < 3; ++ i)
1834        {
1835                mesh->mVertices.push_back(baseTri.mVertices[i]);
1836        }
1837
1838        // add top vertices
1839        for (int i = 0; i < 3; ++ i)
1840        {
1841                mesh->mVertices.push_back(baseTri.mVertices[i] + height * triNorm);
1842        }
1843
1844        // do we have to preprocess this mesh (we don't want to trace view cells!)?
1845        mesh->ComputeBoundingBox();
1846       
1847        return GenerateViewCell(mesh);
1848}
1849
1850
1851void ViewCellsManager::FinalizeViewCells(const bool createMesh)
1852{
1853        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1854
1855        // volume and area of the view cells are recomputed
1856        // a view cell mesh is created
1857        for (it = mViewCells.begin(); it != it_end; ++ it)
1858        {
1859                Finalize(*it, createMesh);
1860        }
1861
1862        mViewCellsTree->AssignRandomColors();
1863
1864        mTotalAreaValid = false;
1865}
1866
1867
1868void ViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
1869{
1870        // implemented in subclasses
1871}
1872
1873
1874/** fast way of merging 2 view cells.
1875*/
1876ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCell *left, ViewCell *right) const
1877{
1878        // generate parent view cell
1879        ViewCellInterior *vc = new ViewCellInterior();
1880
1881        vc->GetPvs().Clear();
1882        ObjectPvs::Merge(vc->GetPvs(), left->GetPvs(), right->GetPvs());
1883
1884        // set only links to child (not from child to parent, maybe not wished!!)
1885        vc->mChildren.push_back(left);
1886        vc->mChildren.push_back(right);
1887
1888        // update pvs size
1889        UpdateScalarPvsSize(vc, vc->GetPvs().EvalPvsCost(), vc->GetPvs().GetSize());
1890
1891        return vc;
1892}
1893
1894
1895ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCellContainer &children) const
1896{
1897        ViewCellInterior *vc = new ViewCellInterior();
1898        ViewCellContainer::const_iterator it, it_end = children.end();
1899
1900        for (it = children.begin(); it != it_end; ++ it)
1901        {
1902                vc->GetPvs().MergeInPlace((*it)->GetPvs());
1903       
1904                vc->mChildren.push_back(*it);
1905        }
1906
1907        return vc;
1908}
1909
1910
1911void ViewCellsManager::SetRenderer(Renderer *renderer)
1912{
1913        mRenderer = renderer;
1914}
1915
1916
1917ViewCellsTree *ViewCellsManager::GetViewCellsTree()
1918{
1919        return mViewCellsTree;
1920}
1921
1922
1923void ViewCellsManager::SetVisualizationSamples(const int visSamples)
1924{
1925        mVisualizationSamples = visSamples;
1926}
1927
1928
1929void ViewCellsManager::SetConstructionSamples(const int constructionSamples)
1930{
1931        mConstructionSamples = constructionSamples;
1932}
1933
1934
1935void ViewCellsManager::SetInitialSamples(const int initialSamples)
1936{
1937        mInitialSamples = initialSamples;
1938}
1939
1940
1941void ViewCellsManager::SetPostProcessSamples(const int postProcessSamples)
1942{
1943        mPostProcessSamples = postProcessSamples;
1944}
1945
1946
1947int ViewCellsManager::GetVisualizationSamples() const
1948{
1949        return mVisualizationSamples;
1950}
1951
1952
1953int ViewCellsManager::GetConstructionSamples() const
1954{
1955        return mConstructionSamples;
1956}
1957
1958
1959int ViewCellsManager::GetPostProcessSamples() const
1960{
1961        return mPostProcessSamples;
1962}
1963
1964
1965void ViewCellsManager::UpdatePvs()
1966{
1967  if (mViewCellPvsIsUpdated || !ViewCellsTreeConstructed())
1968        return;
1969 
1970  mViewCellPvsIsUpdated = true;
1971 
1972  ViewCellContainer leaves;
1973  mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
1974 
1975  ViewCellContainer::const_iterator it, it_end = leaves.end();
1976 
1977  for (it = leaves.begin(); it != it_end; ++ it)
1978        {
1979          mViewCellsTree->PropagatePvs(*it);
1980        }
1981}
1982
1983
1984void ViewCellsManager::GetPvsStatistics(PvsStatistics &stat)
1985{
1986  // update pvs of view cells tree if necessary
1987  UpdatePvs();
1988 
1989  ViewCellContainer::const_iterator it = mViewCells.begin();
1990 
1991  stat.viewcells = 0;
1992  stat.minPvs = 100000000;
1993  stat.maxPvs = 0;
1994  stat.avgPvs = 0.0f;
1995  stat.avgPvsEntries = 0.0f;
1996  stat.avgFilteredPvs = 0.0f;
1997  stat.avgFilteredPvsEntries = 0.0f;
1998  stat.avgFilterContribution = 0.0f;
1999  stat.avgFilterRadius = 0;
2000  stat.avgFilterRatio = 0;
2001  stat.avgRelPvsIncrease = 0.0f;
2002  stat.devRelPvsIncrease = 0.0f;
2003 
2004  if (mPerViewCellStat.size() != mViewCells.size()) {
2005        // reset the pvs size array after the first call to this routine
2006        mPerViewCellStat.resize(mViewCells.size());
2007        for (int i=0; i < mPerViewCellStat.size(); i++) {
2008          mPerViewCellStat[i].pvsSize = 0.0f;
2009          mPerViewCellStat[i].relPvsIncrease = 0.0f;
2010        }
2011  }
2012  int i;
2013  bool evaluateFilter;
2014  Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
2015
2016  for (i=0; it != mViewCells.end(); ++ it, i++)
2017        {
2018          ViewCell *viewcell = *it;
2019          if (viewcell->GetValid()) {
2020                const float pvsCost = mViewCellsTree->GetPvsCost(viewcell);
2021
2022                if (pvsCost < stat.minPvs)
2023                  stat.minPvs = pvsCost;
2024                if (pvsCost > stat.maxPvs)
2025                  stat.maxPvs = pvsCost;
2026               
2027                stat.avgPvs += pvsCost;
2028
2029                const float pvsEntries = (float)mViewCellsTree->GetPvsEntries(viewcell);
2030                stat.avgPvsEntries += pvsEntries;
2031               
2032                if (mPerViewCellStat[i].pvsSize > 0.0f)
2033                  mPerViewCellStat[i].relPvsIncrease = (pvsCost - mPerViewCellStat[i].pvsSize)/mPerViewCellStat[i].pvsSize;
2034               
2035                stat.avgRelPvsIncrease += mPerViewCellStat[i].relPvsIncrease;
2036               
2037                // update the pvs size
2038                mPerViewCellStat[i].pvsSize = pvsCost;
2039               
2040               
2041               
2042                if (evaluateFilter) {
2043                  ObjectPvs filteredPvs;
2044                 
2045                  PvsFilterStatistics fstat = ApplyFilter2(viewcell,
2046                                                                                                   false,
2047                                                                                                   1.0f,
2048                                                                                                   filteredPvs);
2049                 
2050                  float filteredCost = filteredPvs.EvalPvsCost();
2051
2052                  stat.avgFilteredPvs += filteredCost;
2053                  stat.avgFilteredPvsEntries += filteredPvs.GetSize();
2054                 
2055                  stat.avgFilterContribution += filteredCost - pvsCost;
2056                 
2057                  stat.avgFilterRadius += fstat.mAvgFilterRadius;
2058                  int sum = fstat.mGlobalFilterCount + fstat.mLocalFilterCount;
2059                  if (sum) {
2060                        stat.avgFilterRatio += fstat.mLocalFilterCount /
2061                          (float) sum;
2062                  }
2063                 
2064                } else {
2065                  stat.avgFilteredPvs += pvsCost;
2066                  stat.avgFilterContribution += 0;
2067                }
2068               
2069                ++ stat.viewcells;
2070          }
2071        }
2072
2073 
2074 
2075  if (stat.viewcells) {
2076        stat.avgPvs/=stat.viewcells;
2077        stat.avgPvsEntries/=stat.viewcells;
2078        stat.avgFilteredPvs/=stat.viewcells;
2079        stat.avgFilterContribution/=stat.viewcells;
2080        stat.avgFilterRadius/=stat.viewcells;
2081        stat.avgFilterRatio/=stat.viewcells;
2082        stat.avgRelPvsIncrease/=stat.viewcells;
2083
2084        // evaluate std deviation of relPvsIncrease
2085        float sum=0.0f;
2086        for (i=0; i < stat.viewcells; i++) {
2087          sum += sqr(mPerViewCellStat[i].relPvsIncrease - stat.avgRelPvsIncrease);
2088        }
2089        stat.devRelPvsIncrease = sqrt(sum/stat.viewcells);
2090  }
2091 
2092}
2093
2094
2095void ViewCellsManager::PrintPvsStatistics(ostream &s)
2096{
2097  s<<"############# Viewcell PVS STAT ##################\n";
2098  PvsStatistics pvsStat;
2099  GetPvsStatistics(pvsStat);
2100  s<<"#AVG_PVS\n"<<pvsStat.avgPvs<<endl;
2101  s<<"#AVG_ENTRIES_PVS\n"<<pvsStat.avgPvsEntries<<endl;
2102  s<<"#AVG_FILTERED_PVS\n"<<pvsStat.avgFilteredPvs<<endl;
2103  s<<"#AVG_FILTERED_ENTRIES_PVS\n"<<pvsStat.avgFilteredPvsEntries<<endl;
2104  s<<"#AVG_FILTER_CONTRIBUTION\n"<<pvsStat.avgFilterContribution<<endl;
2105  s<<"#AVG_FILTER_RADIUS\n"<<pvsStat.avgFilterRadius<<endl;
2106  s<<"#AVG_FILTER_RATIO\n"<<pvsStat.avgFilterRatio<<endl;
2107  s<<"#MAX_PVS\n"<<pvsStat.maxPvs<<endl;
2108  s<<"#MIN_PVS\n"<<pvsStat.minPvs<<endl;
2109  s<<"#AVG_REL_PVS_INCREASE\n"<<pvsStat.avgRelPvsIncrease<<endl;
2110  s<<"#DEV_REL_PVS_INCREASE\n"<<pvsStat.devRelPvsIncrease<<endl;
2111}
2112
2113
2114int ViewCellsManager::CastBeam(Beam &beam)
2115{
2116        return 0;
2117}
2118
2119
2120ViewCellContainer &ViewCellsManager::GetViewCells()
2121{
2122        return mViewCells;
2123}
2124
2125
2126void ViewCellsManager::SetViewSpaceBox(const AxisAlignedBox3 &box)
2127{
2128        mViewSpaceBox = box;
2129       
2130        // hack: create clip plane relative to new view space box
2131        CreateClipPlane();
2132        // the total area of the view space has changed
2133        mTotalAreaValid = false;
2134}
2135
2136
2137void ViewCellsManager::CreateClipPlane()
2138{
2139        int axis = 0;
2140        float pos;
2141        bool orientation;
2142        Vector3 absPos;
2143
2144        Environment::GetSingleton()->GetFloatValue("ViewCells.Visualization.clipPlanePos", pos);
2145        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.clipPlaneAxis", axis);
2146
2147        if (axis < 0)
2148        {
2149                axis = -axis;
2150                orientation = false;
2151                absPos = mViewSpaceBox.Max() -  mViewSpaceBox.Size() * pos;
2152        }
2153        else
2154        {
2155                orientation = true;
2156                absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
2157        }
2158
2159        mClipPlaneForViz = AxisAlignedPlane(axis, absPos[axis]);
2160        mClipPlaneForViz.mOrientation = orientation;
2161}
2162
2163
2164AxisAlignedBox3 ViewCellsManager::GetViewSpaceBox() const
2165{
2166        return mViewSpaceBox;
2167}
2168
2169
2170void ViewCellsManager::ResetViewCells()
2171{
2172        // recollect view cells
2173        mViewCells.clear();
2174        CollectViewCells();
2175       
2176        // stats are computed once more
2177        EvaluateViewCellsStats();
2178
2179        // has to be recomputed
2180        mTotalAreaValid = false;
2181}
2182
2183
2184int ViewCellsManager::GetMaxPvsSize() const
2185{
2186        return mMaxPvsSize;
2187}
2188
2189
2190int ViewCellsManager::GetMinPvsSize() const
2191{
2192        return mMinPvsSize;
2193}
2194
2195
2196
2197float ViewCellsManager::GetMaxPvsRatio() const
2198{
2199        return mMaxPvsRatio;
2200}
2201
2202
2203inline static void AddSampleToPvs(ObjectPvs &pvs,
2204                                                                  Intersectable *obj,
2205                                                                  const float pdf)
2206{
2207#if PVS_ADD_DIRTY
2208        pvs.AddSampleDirtyCheck(obj, pdf);
2209
2210        if (pvs.RequiresResort())
2211        {
2212                pvs.SimpleSort();
2213        }
2214#else
2215        pvs.AddSample(obj, pdf);
2216#endif
2217}
2218
2219
2220void ViewCellsManager::ComputeViewCellContribution(ViewCell *viewCell,
2221                                                                                                   VssRay &ray,
2222                                                                                                   Intersectable *obj,
2223                                                                                                   const Vector3 &pt,
2224                                                                                                   const bool addRays)
2225{
2226  // check if we are outside of view space
2227        if (!obj || !viewCell->GetValid())
2228                return;
2229       
2230        // if ray not outside of view space
2231        float relContribution = 0.0f;
2232        float absContribution = 0.0f;
2233       
2234        if (obj)
2235          {
2236                // todo: maybe not correct for kd node pvs
2237                if (addRays) {
2238                  float pdf = viewCell->GetPvs().AddSampleDirtyCheck(obj, ray.mPdf);
2239                  if (pdf == ray.mPdf) {
2240                        absContribution = 1.0f;
2241                        if (viewCell->GetPvs().RequiresResort())
2242                          viewCell->GetPvs().SimpleSort();
2243                  }
2244                          } else {
2245                                if (viewCell->GetPvs().GetSampleContribution(
2246                                                                                                                         obj,
2247                                                                                                                         ray.mPdf,
2248                                                                                                                         relContribution))
2249                                  absContribution = 1.0f;
2250                          }
2251                // $$ clear the relative contribution as it is currently not correct anyway
2252                relContribution = 0.0f;
2253               
2254                if (absContribution == 1.0f) {
2255                  ++ ray.mPvsContribution;
2256                  relContribution = 1.0f;
2257                 
2258                 
2259#if CONTRIBUTION_RELATIVE_TO_PVS_SIZE
2260                  relContribution /= viewcell->GetPvs().GetSize();
2261#endif
2262                 
2263#if DIST_WEIGHTED_CONTRIBUTION
2264                  // recalculate the contribution - weight the 1.0f contribution by the sqr distance to the
2265                  // object-> a new contribution in the proximity of the viewcell has a larger weight!
2266                  relContribution /= SqrDistance(GetViewCellBox(viewcell).Center(),
2267                                                                                 ray.mTermination);
2268                 
2269#endif
2270                }
2271               
2272#if SUM_RAY_CONTRIBUTIONS || AVG_RAY_CONTRIBUTIONS
2273                ray.mRelativePvsContribution += relContribution;
2274#else
2275                // recalculate relative contribution - use max of Rel Contribution
2276                if (ray.mRelativePvsContribution < relContribution)
2277                  ray.mRelativePvsContribution = relContribution;
2278#endif
2279          }
2280       
2281}
2282
2283
2284float ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2285                                                                                                  const bool addRays,
2286                                                                                                  ViewCell *currentViewCell)
2287{
2288        ray.mPvsContribution = 0;
2289        ray.mRelativePvsContribution = 0.0f;
2290
2291        if (!ray.mTerminationObject)
2292                return 0.0f;
2293
2294        // optain pvs entry (can be different from hit object)
2295        Intersectable *terminationObj = GetIntersectable(ray, true);
2296
2297        ComputeViewCellContribution(currentViewCell,
2298                                                                ray,
2299                                                                terminationObj,
2300                                                                ray.mTermination,
2301                                                                addRays);
2302       
2303#if USE_RAY_LENGTH_AS_CONTRIBUTION
2304        float c = 0.0f;
2305        if (terminationObj)
2306                c = ray.Length();
2307
2308        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2309        return c;
2310#else
2311        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2312          (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2313#endif
2314}
2315
2316
2317float
2318ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2319                                                                                        const bool addRays,
2320                                                                                        const bool storeViewCells)
2321{
2322        ray.mPvsContribution = 0;
2323        ray.mRelativePvsContribution = 0.0f;
2324
2325        if (!ray.mTerminationObject)
2326                return 0.0f;
2327
2328        ViewCellContainer viewCells;
2329
2330        static Ray hray;
2331        hray.Init(ray);
2332
2333        float tmin = 0, tmax = 1.0;
2334
2335        if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax)) {
2336          //      cerr<<"ray outside view space box\n";
2337          return 0;
2338        }
2339
2340        Vector3 origin = hray.Extrap(tmin);
2341        Vector3 termination = hray.Extrap(tmax);
2342
2343        ViewCell::NewMail();
2344
2345        // traverse the view space subdivision
2346        CastLineSegment(origin, termination, viewCells);
2347
2348       
2349        if (storeViewCells)
2350        {       
2351          // copy viewcells memory efficiently
2352#if VSS_STORE_VIEWCELLS
2353          ray.mViewCells.reserve(viewCells.size());
2354          ray.mViewCells = viewCells;
2355#else
2356          cerr<<"Vss store viewcells not supported."<<endl;
2357          exit(1);
2358#endif
2359        }
2360
2361        // optain pvs entry (can be different from hit object)
2362        Intersectable *terminationObj = GetIntersectable(ray, true);
2363
2364        ViewCellContainer::const_iterator it = viewCells.begin();
2365
2366        for (; it != viewCells.end(); ++ it)
2367        {
2368                ComputeViewCellContribution(*it,
2369                                                                        ray,
2370                                                                        terminationObj,
2371                                                                        ray.mTermination,
2372                                                                        addRays);
2373        }
2374
2375#if AVG_RAY_CONTRIBUTIONS
2376        ray.mRelativePvsContribution /= (float)viewCells.size();
2377#endif
2378 
2379#if USE_RAY_LENGTH_AS_CONTRIBUTION
2380        float c = 0.0f;
2381        if (terminationObj)
2382          c = ray.Length();
2383        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2384        return c;
2385#else
2386        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2387          (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2388#endif
2389}
2390
2391
2392void ViewCellsManager::GetRaySets(const VssRayContainer &sourceRays,
2393                                                                  const int maxSize,
2394                                                                  VssRayContainer &usedRays,
2395                                                                  VssRayContainer *savedRays) const
2396{
2397        const int limit = min(maxSize, (int)sourceRays.size());
2398        const float prop = (float)limit / ((float)sourceRays.size() + Limits::Small);
2399
2400        VssRayContainer::const_iterator it, it_end = sourceRays.end();
2401        for (it = sourceRays.begin(); it != it_end; ++ it)
2402        {
2403                if (Random(1.0f) < prop)
2404                        usedRays.push_back(*it);
2405                else if (savedRays)
2406                        savedRays->push_back(*it);
2407        }
2408}
2409
2410
2411float ViewCellsManager::GetRendercost(ViewCell *viewCell) const
2412{
2413        return (float)mViewCellsTree->GetPvsCost(viewCell);
2414}
2415
2416
2417float ViewCellsManager::GetAccVcArea()
2418{
2419        // if already computed
2420        if (mTotalAreaValid)
2421        {
2422                return mTotalArea;
2423        }
2424
2425        mTotalArea = 0;
2426        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2427
2428        for (it = mViewCells.begin(); it != it_end; ++ it)
2429        {
2430                //Debug << "area: " << GetArea(*it);
2431        mTotalArea += GetArea(*it);
2432        }
2433
2434        mTotalAreaValid = true;
2435
2436        return mTotalArea;
2437}
2438
2439
2440void ViewCellsManager::PrintStatistics(ostream &s) const
2441{
2442        s << mCurrentViewCellsStats << endl;
2443}
2444
2445
2446void ViewCellsManager::CreateUniqueViewCellIds()
2447{
2448        if (ViewCellsTreeConstructed())
2449        {
2450                mViewCellsTree->CreateUniqueViewCellsIds();
2451        }
2452        else // no view cells tree, handle view cells "myself"
2453        {
2454                int i = 0;
2455                ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
2456                for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
2457                {
2458                        if ((*vit)->GetId() != OUT_OF_BOUNDS_ID)
2459                        {
2460                                mViewCells[i]->SetId(i ++);
2461                        }
2462                }
2463        }
2464}
2465
2466
2467void ViewCellsManager::ExportViewCellsForViz(Exporter *exporter,
2468                                                                                         const AxisAlignedBox3 *sceneBox,
2469                                                                                         const bool colorCode,
2470                                                                                         const AxisAlignedPlane *clipPlane
2471                                                                                         ) const
2472{
2473        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2474
2475        for (it = mViewCells.begin(); it != it_end; ++ it)
2476        {
2477                if (!mOnlyValidViewCells || (*it)->GetValid())
2478                {
2479                        ExportColor(exporter, *it, colorCode); 
2480                        ExportViewCellGeometry(exporter, *it, sceneBox, clipPlane);
2481                }
2482        }
2483}
2484
2485
2486void ViewCellsManager::CreateViewCellMeshes()
2487{
2488        // convert to meshes
2489        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2490
2491        for (it = mViewCells.begin(); it != it_end; ++ it)
2492        {
2493                if (!(*it)->GetMesh())
2494                {
2495                        CreateMesh(*it);
2496                }
2497        }
2498}
2499
2500
2501bool ViewCellsManager::ExportViewCells(const string filename,
2502                                                                           const bool exportPvs,
2503                                                                           const ObjectContainer &objects)
2504{
2505        return false;
2506}
2507
2508
2509void ViewCellsManager::CollectViewCells(const int n)
2510{
2511        mNumActiveViewCells = n;
2512        mViewCells.clear();
2513        // implemented in subclasses
2514        CollectViewCells();
2515}
2516
2517
2518void ViewCellsManager::SetViewCellActive(ViewCell *vc) const
2519{
2520        ViewCellContainer leaves;
2521        // sets the pointers to the currently active view cells
2522        mViewCellsTree->CollectLeaves(vc, leaves);
2523
2524        ViewCellContainer::const_iterator lit, lit_end = leaves.end();
2525        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2526        {
2527                dynamic_cast<ViewCellLeaf *>(*lit)->SetActiveViewCell(vc);
2528        }
2529}
2530
2531
2532void ViewCellsManager::SetViewCellsActive()
2533{
2534        // collect leaf view cells and set the pointers to
2535        // the currently active view cells
2536        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2537
2538        for (it = mViewCells.begin(); it != it_end; ++ it)
2539        {
2540                SetViewCellActive(*it);
2541        }
2542}
2543
2544
2545int ViewCellsManager::GetMaxFilterSize() const
2546{
2547        return mMaxFilterSize; 
2548}
2549
2550
2551static const bool USE_ASCII = true;
2552
2553
2554bool ViewCellsManager::ExportBoundingBoxes(const string filename,
2555                                                                                   const ObjectContainer &objects) const
2556{
2557        ObjectContainer::const_iterator it, it_end = objects.end();
2558       
2559        if (USE_ASCII)
2560        {
2561                ofstream boxesOut(filename.c_str());
2562                if (!boxesOut.is_open())
2563                        return false;
2564
2565                for (it = objects.begin(); it != it_end; ++ it)
2566                {
2567                        MeshInstance *mi = dynamic_cast<MeshInstance *>(*it);
2568                        const AxisAlignedBox3 box = mi->GetBox();
2569
2570                        boxesOut << mi->GetId() << " "
2571                                         << box.Min().x << " "
2572                                         << box.Min().y << " "
2573                                         << box.Min().z << " "
2574                                         << box.Max().x << " "
2575                                         << box.Max().y << " "
2576                     << box.Max().z << endl;   
2577                }
2578
2579                boxesOut.close();
2580        }
2581        else
2582        {
2583                ofstream boxesOut(filename.c_str(), ios::binary);
2584
2585                if (!boxesOut.is_open())
2586                        return false;
2587
2588                for (it = objects.begin(); it != it_end; ++ it)
2589                {       
2590                        MeshInstance *mi = dynamic_cast<MeshInstance *>(*it);
2591                        const AxisAlignedBox3 box = mi->GetBox();
2592                        Vector3 bmin = box.Min();
2593                        Vector3 bmax = box.Max();
2594                        int id = mi->GetId();
2595
2596                        boxesOut.write(reinterpret_cast<char *>(&id), sizeof(int));
2597                        boxesOut.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2598                        boxesOut.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2599                }
2600               
2601                boxesOut.close();
2602        }
2603
2604        return true;
2605}
2606
2607
2608bool ViewCellsManager::LoadBoundingBoxes(const string filename,
2609                                                                                 IndexedBoundingBoxContainer &boxes) const
2610{
2611        Vector3 bmin, bmax;
2612        int id;
2613
2614        if (USE_ASCII)
2615        {
2616                ifstream boxesIn(filename.c_str());
2617               
2618                if (!boxesIn.is_open())
2619                {
2620                        cout << "failed to open file " << filename << endl;
2621                        return false;
2622                }
2623
2624                string buf;
2625                while (!(getline(boxesIn, buf)).eof())
2626                {
2627                        sscanf(buf.c_str(), "%d %f %f %f %f %f %f",
2628                                   &id, &bmin.x, &bmin.y, &bmin.z,
2629                                   &bmax.x, &bmax.y, &bmax.z);
2630               
2631                        AxisAlignedBox3 box(bmin, bmax);
2632                        //      MeshInstance *mi = new MeshInstance();
2633                        // HACK: set bounding box to new box
2634                        //mi->mBox = box;
2635
2636                        boxes.push_back(IndexedBoundingBox(id, box));
2637                }
2638
2639                boxesIn.close();
2640        }
2641        else
2642        {
2643                ifstream boxesIn(filename.c_str(), ios::binary);
2644
2645                if (!boxesIn.is_open())
2646                        return false;
2647
2648                while (1)
2649                {
2650                        boxesIn.read(reinterpret_cast<char *>(&id), sizeof(Vector3));
2651                        boxesIn.read(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
2652                        boxesIn.read(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
2653                       
2654                        if (boxesIn.eof())
2655                                break;
2656
2657                       
2658                        AxisAlignedBox3 box(bmin, bmax);
2659                        MeshInstance *mi = new MeshInstance(NULL);
2660
2661                        // HACK: set bounding box to new box
2662                        //mi->mBox = box;
2663                        //boxes.push_back(mi);
2664                        boxes.push_back(IndexedBoundingBox(id, box));
2665                }
2666
2667                boxesIn.close();
2668        }
2669
2670        return true;
2671}
2672
2673
2674float ViewCellsManager::GetFilterWidth()
2675{
2676        return mFilterWidth;
2677}
2678
2679
2680float ViewCellsManager::GetAbsFilterWidth()
2681{
2682        return Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
2683}
2684
2685
2686void ViewCellsManager::UpdateScalarPvsSize(ViewCell *vc,
2687                                                                                   const float pvsCost,
2688                                                                                   const int entriesInPvs) const
2689{
2690        vc->mPvsCost = pvsCost;
2691        vc->mEntriesInPvs = entriesInPvs;
2692
2693        vc->mPvsSizeValid = true;
2694}
2695
2696
2697void
2698ViewCellsManager::ApplyFilter(ViewCell *viewCell,
2699                                                          KdTree *kdTree,
2700                                                          const float viewSpaceFilterSize,
2701                                                          const float spatialFilterSize,
2702                                                          ObjectPvs &pvs
2703                                                          )
2704{
2705  // extend the pvs of the viewcell by pvs of its neighbors
2706  // and apply spatial filter by including all neighbors of the objects
2707  // in the pvs
2708
2709  // get all viewcells intersecting the viewSpaceFilterBox
2710  // and compute the pvs union
2711 
2712  //Vector3 center = viewCell->GetBox().Center();
2713  //  Vector3 center = m->mBox.Center();
2714
2715        //  AxisAlignedBox3 box(center - Vector3(viewSpaceFilterSize/2),
2716        //                                        center + Vector3(viewSpaceFilterSize/2));
2717        if (!ViewCellsConstructed())
2718                return;
2719
2720        if (viewSpaceFilterSize >= 0.0f) {
2721
2722                const bool usePrVS = false;
2723
2724                if (!usePrVS) {
2725                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
2726                        box.Enlarge(Vector3(viewSpaceFilterSize/2));
2727
2728                        ViewCellContainer viewCells;
2729                        ComputeBoxIntersections(box, viewCells);
2730
2731                        //  cout<<"box="<<box<<endl;
2732                        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();
2733
2734                        for (; it != it_end; ++ it)
2735                        {
2736                                ObjectPvs interPvs;
2737                                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
2738                                ObjectPvs::Merge(interPvs, pvs, (*it)->GetPvs());
2739
2740                                pvs = interPvs;
2741                        }
2742                } else
2743                {
2744                        PrVs prvs;
2745                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
2746
2747                        //  mViewCellsManager->SetMaxFilterSize(1);
2748                        GetPrVS(box.Center(), prvs, viewSpaceFilterSize);
2749                        pvs = prvs.mViewCell->GetPvs();
2750                        DeleteLocalMergeTree(prvs.mViewCell);
2751                }
2752        }
2753        else
2754        {
2755                pvs = viewCell->GetPvs();
2756        }
2757
2758        if (spatialFilterSize >=0.0f)
2759                ApplySpatialFilter(kdTree, spatialFilterSize, pvs);
2760
2761}
2762
2763
2764
2765void
2766ViewCellsManager::ApplyFilter(KdTree *kdTree,
2767                                                          const float relViewSpaceFilterSize,
2768                                                          const float relSpatialFilterSize
2769                                                          )
2770{
2771
2772        if (!ViewCellsConstructed())
2773                return;
2774
2775        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2776
2777        ObjectPvs *newPvs;
2778        newPvs = new ObjectPvs[mViewCells.size()];
2779
2780        float viewSpaceFilterSize = Magnitude(mViewSpaceBox.Size())*relViewSpaceFilterSize;
2781        float spatialFilterSize = Magnitude(kdTree->GetBox().Size())*relSpatialFilterSize;
2782       
2783        int i;
2784        for (i=0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
2785          ApplyFilter(*it,
2786                                  kdTree,
2787                                  viewSpaceFilterSize,
2788                                  spatialFilterSize,
2789                                  newPvs[i]
2790                                  );
2791        }
2792       
2793        // now replace all pvss
2794        for (i = 0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
2795         
2796          ObjectPvs &pvs = (*it)->GetPvs();
2797          pvs.Clear();
2798          pvs = newPvs[i];
2799          newPvs[i].Clear();
2800        }
2801
2802        delete [] newPvs;
2803}
2804
2805
2806void
2807ViewCellsManager::ApplySpatialFilter(
2808                                                                         KdTree *kdTree,
2809                                                                         const float spatialFilterSize,
2810                                                                         ObjectPvs &pvs
2811                                                                         )
2812{
2813  // now compute a new Pvs by including also objects intersecting the
2814  // extended boxes of visible objects
2815  Intersectable::NewMail();
2816
2817  ObjectPvsIterator pit = pvs.GetIterator();
2818
2819  while (pit.HasMoreEntries())
2820  {             
2821          ObjectPvsEntry entry = pit.Next();
2822 
2823          Intersectable *object = entry.mObject;
2824      object->Mail();
2825  }
2826
2827  ObjectPvs nPvs;
2828  int nPvsSize = 0;
2829 
2830  ObjectPvsIterator pit2 = pvs.GetIterator();
2831
2832  while (pit2.HasMoreEntries())
2833  {             
2834          // now go through the pvs again
2835          ObjectPvsEntry entry = pit2.Next();
2836          Intersectable *object = entry.mObject;
2837
2838          //    Vector3 center = object->GetBox().Center();
2839          //    AxisAlignedBox3 box(center - Vector3(spatialFilterSize/2),
2840          //                                            center + Vector3(spatialFilterSize/2));
2841
2842          AxisAlignedBox3 box = object->GetBox();
2843          box.Enlarge(Vector3(spatialFilterSize/2));
2844
2845          ObjectContainer objects;
2846
2847          // $$ warning collect objects takes only unmailed ones!
2848          kdTree->CollectObjects(box, objects);
2849          //    cout<<"collected objects="<<objects.size()<<endl;
2850          ObjectContainer::const_iterator noi = objects.begin();
2851          for (; noi != objects.end(); ++ noi)
2852          {
2853                  Intersectable *o = *noi;
2854                 
2855                  // $$ JB warning: pdfs are not correct at this point!   
2856                  nPvs.AddSample(o, Limits::Small);
2857                  nPvsSize ++;
2858          }
2859  }
2860
2861  // cout<<"nPvs size = "<<nPvsSize<<endl;
2862  pvs.MergeInPlace(nPvs);
2863}
2864
2865
2866void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
2867                                                                                                const ViewCellContainer &viewCells) const
2868{
2869        MergeViewCellsRecursivly(pvs, viewCells, 0, (int)viewCells.size() - 1);
2870}
2871
2872
2873void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
2874                                                                                                const ViewCellContainer &viewCells,
2875                                                                                                const int leftIdx,
2876                                                                                                const int rightIdx) const
2877{
2878        if (leftIdx == rightIdx)
2879        {
2880                pvs = viewCells[leftIdx]->GetPvs();
2881        }
2882        else
2883        {
2884                const int midSplit = (leftIdx + rightIdx) / 2;
2885       
2886                ObjectPvs leftPvs, rightPvs;
2887                MergeViewCellsRecursivly(leftPvs, viewCells, leftIdx, midSplit);
2888                MergeViewCellsRecursivly(rightPvs, viewCells, midSplit, rightIdx);
2889
2890        ObjectPvs::Merge(pvs, leftPvs, rightPvs);
2891        }
2892}
2893
2894
2895PvsFilterStatistics
2896ViewCellsManager::ApplyFilter2(ViewCell *viewCell,
2897                                                           const bool useViewSpaceFilter,
2898                                                           const float filterSize,
2899                                                           ObjectPvs &pvs,
2900                                                           vector<AxisAlignedBox3> *filteredBoxes
2901                                                           )
2902{
2903  //cout<<"y";
2904  PvsFilterStatistics stats;
2905
2906  AxisAlignedBox3 vbox = GetViewCellBox(viewCell);
2907  Vector3 center = vbox.Center();
2908  // copy the PVS
2909  Intersectable::NewMail();
2910  ObjectPvs basePvs = viewCell->GetPvs();
2911  ObjectPvsIterator pit = basePvs.GetIterator();
2912
2913  pvs.Reserve(viewCell->GetFilteredPvsSize());
2914
2915  if (!mUseKdPvs)
2916  {
2917          // first mark all objects from this pvs
2918          while (pit.HasMoreEntries()) 
2919          {
2920                  ObjectPvsEntry entry = pit.Next();
2921                  Intersectable *object = entry.mObject;
2922                  object->Mail();
2923          }
2924  }
2925 
2926  int pvsSize = 0;
2927  int nPvsSize = 0;
2928  float samples = (float)basePvs.GetSamples();
2929 
2930  Debug<<"f #s="<<samples<<"  pvs size = "<<basePvs.GetSize();
2931  //  cout<<"Filter size = "<<filterSize<<endl;
2932  //  cout<<"vbox = "<<vbox<<endl;
2933  //  cout<<"center = "<<center<<endl;
2934
2935
2936   // Minimal number of local samples to take into account
2937   // the local sampling density.
2938   // The size of the filter is a minimum of the conservative
2939   // local sampling density estimate (#rays intersecting teh viewcell and
2940   // the object)
2941   // and gobal estimate for the view cell
2942   // (total #rays intersecting the viewcell)
2943  int minLocalSamples = 2;
2944 
2945  float viewCellRadius = 0.5f*Magnitude(vbox.Diagonal());
2946 
2947  // now compute the filter box around the current viewCell
2948 
2949  if (useViewSpaceFilter) {
2950        //      float radius = Max(viewCellRadius/100.0f, avgRadius - viewCellRadius);
2951        float radius = viewCellRadius/100.0f;
2952        vbox.Enlarge(radius);
2953        cout<<"vbox = "<<vbox<<endl;
2954        ViewCellContainer viewCells;
2955        ComputeBoxIntersections(vbox, viewCells);
2956       
2957        ViewCellContainer::const_iterator it = viewCells.begin(),
2958          it_end = viewCells.end();
2959        int i = 0;
2960        for (i=0; it != it_end; ++ it, ++ i)
2961          if ((*it) != viewCell) {
2962                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
2963                basePvs.MergeInPlace((*it)->GetPvs());
2964          }
2965       
2966        // update samples and globalC
2967        samples = (float)pvs.GetSamples();
2968        //      cout<<"neighboring viewcells = "<<i-1<<endl;
2969        //      cout<<"Samples' = "<<samples<<endl;
2970  }
2971 
2972  // Minimal number of samples so that filtering takes place
2973#define MIN_SAMPLES  50
2974 
2975  if (samples > MIN_SAMPLES) {
2976        float globalC = 2.0f*filterSize/sqrt(samples);
2977       
2978        pit = basePvs.GetIterator();
2979       
2980        ObjectContainer objects;
2981       
2982        while (pit.HasMoreEntries()) {         
2983          ObjectPvsEntry entry = pit.Next();
2984         
2985          Intersectable *object = entry.mObject;
2986          // compute filter size based on the distance and the numebr of samples
2987          AxisAlignedBox3 box = object->GetBox();
2988         
2989          float distance = Distance(center, box.Center());
2990          float globalRadius = distance*globalC;
2991         
2992          int objectSamples = (int)entry.mData.mSumPdf;
2993          float localRadius = MAX_FLOAT;
2994         
2995          localRadius = filterSize*0.5f*Magnitude(box.Diagonal())/
2996                sqrt((float)objectSamples);
2997         
2998          //      cout<<"os="<<objectSamples<<" lr="<<localRadius<<" gr="<<globalRadius<<endl;
2999         
3000          // now compute the filter size
3001          float radius;
3002         
3003#if 0
3004          if (objectSamples <= 1) {
3005                if (localRadius > globalRadius) {
3006                  radius = 0.5flRadius;
3007                  stats.mLocalFilterCount++;
3008                } else {
3009                  radius = globalRadius;
3010                  stats.mGlobalFilterCount++;
3011                }
3012          } else {
3013                radius = localRadius;
3014                stats.mLocalFilterCount++;
3015          }
3016#else
3017          radius = 0.5f*globalRadius + 0.5f*localRadius;
3018
3019          if (localRadius > globalRadius)
3020                stats.mLocalFilterCount++;
3021          else
3022                stats.mGlobalFilterCount++;
3023#endif
3024         
3025          stats.mAvgFilterRadius += radius;
3026         
3027          // cout<<"box = "<<box<<endl;
3028          //    cout<<"distance = "<<distance<<endl;
3029          //    cout<<"radiues = "<<radius<<endl;
3030         
3031          box.Enlarge(Vector3(radius));
3032
3033          if (filteredBoxes)
3034                filteredBoxes->push_back(box);
3035
3036          objects.clear();
3037          // $$ warning collect objects takes only unmailed ones!
3038          if (mUseKdPvsAfterFiltering) {
3039                float area = GetPreprocessor()->mKdTree->GetBox().SurfaceArea()*KD_PVS_AREA;
3040                GetPreprocessor()->mKdTree->CollectKdObjects(box, objects, area);
3041          } else
3042                CollectObjects(box, objects);
3043         
3044          //    cout<<"collected objects="<<objects.size()<<endl;
3045          ObjectContainer::const_iterator noi = objects.begin();
3046          for (; noi != objects.end(); ++ noi) {
3047                Intersectable *o = *noi;
3048                // $$ JB warning: pdfs are not correct at this point!     
3049                pvs.AddSampleDirty(o, Limits::Small);
3050          }
3051        }
3052        stats.mAvgFilterRadius /= (stats.mLocalFilterCount + stats.mGlobalFilterCount);
3053  }
3054 
3055  Debug<<" nPvs size = "<<pvs.GetSize()<<endl;
3056 
3057  if (!mUseKdPvs)
3058  {
3059          // copy the base pvs to the new pvs
3060          pit = basePvs.GetIterator();
3061          while (pit.HasMoreEntries())
3062          {             
3063                  ObjectPvsEntry entry = pit.Next();
3064                  pvs.AddSampleDirty(entry.mObject, entry.mData.mSumPdf);
3065          }
3066  }
3067 
3068  pvs.SimpleSort();
3069  viewCell->SetFilteredPvsSize(pvs.GetSize());
3070 
3071  Intersectable::NewMail();
3072  return stats;
3073}
3074
3075
3076
3077void ViewCellsManager::ExportColor(Exporter *exporter,
3078                                                                   ViewCell *vc,
3079                                                                   bool colorCode) const
3080{
3081        const bool vcValid = CheckValidity(vc, mMinPvsSize, mMaxPvsSize);
3082
3083        float importance = 0;
3084        static Material m;
3085        //cout << "color code: " << colorCode << endl;
3086        switch (mColorCode)
3087        {
3088        case 0: // Random
3089                {
3090                        if (vcValid)
3091                        {
3092                                m.mDiffuseColor.r = 0.2f + RandomValue(0.0f, 0.8f);
3093                                m.mDiffuseColor.g = 0.2f + RandomValue(0.0f, 0.8f);
3094                                m.mDiffuseColor.b = 0.2f + RandomValue(0.0f, 0.8f);
3095                        }
3096                        else
3097                        {
3098                                m.mDiffuseColor.r = 0.0f;
3099                                m.mDiffuseColor.g = 1.0f;
3100                                m.mDiffuseColor.b = 0.0f;
3101                        }
3102
3103                        exporter->SetForcedMaterial(m);
3104                        return;
3105                }
3106               
3107        case 1: // pvs
3108                {
3109                        if (mCurrentViewCellsStats.maxPvs)
3110                        {
3111                                importance = (float)mViewCellsTree->GetPvsCost(vc) /
3112                                                         (float)mCurrentViewCellsStats.maxPvs;
3113                        }
3114                }
3115                break;
3116        case 2: // merges
3117                {
3118            const int lSize = mViewCellsTree->GetNumInitialViewCells(vc);
3119                        importance = (float)lSize / (float)mCurrentViewCellsStats.maxLeaves;
3120                }
3121                break;
3122#if 0
3123        case 3: // merge tree differene
3124                {
3125                        importance = (float)GetMaxTreeDiff(vc) /
3126                                (float)(mVspBspTree->GetStatistics().maxDepth * 2);
3127
3128                }
3129                break;
3130#endif
3131        default:
3132                break;
3133        }
3134
3135        // special color code for invalid view cells
3136        m.mDiffuseColor.r = importance;
3137        m.mDiffuseColor.b = 1.0f;//vcValid ? 0.0f : 1.0f;
3138        m.mDiffuseColor.g = 1.0f - importance;
3139
3140        //Debug << "importance: " << importance << endl;
3141        exporter->SetForcedMaterial(m);
3142}
3143
3144
3145void ViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3146                                                                                          vector<MergeCandidate> &candidates)
3147{
3148        // implemented in subclasses
3149}
3150
3151
3152void ViewCellsManager::UpdatePvsForEvaluation()
3153{
3154        ObjectPvs objPvs;
3155        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), objPvs);
3156}
3157
3158void ViewCellsManager::UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs)
3159{
3160        // terminate traversal
3161        if (root->IsLeaf())
3162        {
3163                //cout << "updating leaf" << endl;
3164                // we assume that pvs is explicitly stored in leaves
3165                pvs = root->GetPvs();
3166                UpdateScalarPvsSize(root, pvs.EvalPvsCost(), pvs.GetSize());
3167                return;
3168        }
3169
3170        ////////////////
3171        //-- interior node => propagate pvs up the tree
3172
3173        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(root);
3174
3175        // reset interior pvs
3176        interior->GetPvs().Clear();
3177        // reset recursive pvs
3178        pvs.Clear();
3179
3180        // pvss of child nodes
3181        vector<ObjectPvs> pvsList;
3182        pvsList.resize((int)interior->mChildren.size());
3183
3184        ViewCellContainer::const_iterator vit, vit_end = interior->mChildren.end();
3185       
3186        int i = 0;
3187
3188        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ i)
3189        {
3190                //////////////////
3191                //-- recursivly compute child pvss
3192                UpdatePvsForEvaluation(*vit, pvsList[i]/*objPvs*/);
3193        }
3194
3195#if 1
3196        Intersectable::NewMail();
3197
3198        //-- faster way of computing pvs:
3199        //-- construct merged pvs by adding
3200        //-- and only those of the next pvs which were not mailed.
3201        //-- note: sumpdf is not correct!!
3202
3203        vector<ObjectPvs>::iterator oit = pvsList.begin();
3204
3205        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ oit)
3206        {
3207                ObjectPvsIterator pit = (*oit).GetIterator();
3208               
3209                // first mark all object from this pvs
3210                while (pit.HasMoreEntries())
3211                {               
3212                        ObjectPvsEntry entry = pit.Next();
3213
3214                        Intersectable *intersect = entry.mObject;
3215
3216                        if (!intersect->Mailed())
3217                        {
3218                                pvs.AddSample(intersect, entry.mData.mSumPdf);
3219                                intersect->Mail();
3220                        }
3221                }
3222        }
3223
3224        // store pvs in this node
3225        if (mViewCellsTree->ViewCellsStorage() == ViewCellsTree::PVS_IN_INTERIORS)
3226        {
3227                interior->SetPvs(pvs);
3228        }
3229       
3230        // set new pvs size
3231        UpdateScalarPvsSize(interior, pvs.EvalPvsCost(), pvs.GetSize());
3232       
3233#else
3234        // really merge cells: slow put sumPdf is correct
3235        viewCellInterior->GetPvs().Merge(backVc->GetPvs());
3236        viewCellInterior->GetPvs().Merge(frontVc->GetPvs());
3237#endif
3238}
3239
3240
3241
3242/*******************************************************************/
3243/*               BspViewCellsManager implementation                */
3244/*******************************************************************/
3245
3246
3247BspViewCellsManager::BspViewCellsManager(ViewCellsTree *vcTree, BspTree *bspTree):
3248ViewCellsManager(vcTree), mBspTree(bspTree)
3249{
3250        Environment::GetSingleton()->GetIntValue("BspTree.Construction.samples", mInitialSamples);
3251
3252        mBspTree->SetViewCellsManager(this);
3253        mBspTree->SetViewCellsTree(mViewCellsTree);
3254}
3255
3256
3257bool BspViewCellsManager::ViewCellsConstructed() const
3258{
3259        return mBspTree->GetRoot() != NULL;
3260}
3261
3262
3263ViewCell *BspViewCellsManager::GenerateViewCell(Mesh *mesh) const
3264{
3265        return new BspViewCell(mesh);
3266}
3267
3268
3269int BspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
3270                                                                                          const VssRayContainer &rays)
3271{
3272        // if view cells were already constructed, we can finish
3273        if (ViewCellsConstructed())
3274                return 0;
3275
3276        int sampleContributions = 0;
3277
3278        // construct view cells using the collected samples
3279        RayContainer constructionRays;
3280        VssRayContainer savedRays;
3281
3282        // choose a a number of rays based on the ratio of cast rays / requested rays
3283        const int limit = min(mInitialSamples, (int)rays.size());
3284        VssRayContainer::const_iterator it, it_end = rays.end();
3285
3286        const float prop = (float)limit / ((float)rays.size() + Limits::Small);
3287
3288        for (it = rays.begin(); it != it_end; ++ it)
3289        {
3290                if (Random(1.0f) < prop)
3291                        constructionRays.push_back(new Ray(*(*it)));
3292                else
3293                        savedRays.push_back(*it);
3294        }
3295
3296    if (!mUsePredefinedViewCells)
3297        {
3298                // no view cells loaded
3299                mBspTree->Construct(objects, constructionRays, &mViewSpaceBox);
3300                // collect final view cells
3301                mBspTree->CollectViewCells(mViewCells);
3302        }
3303        else
3304        {       
3305                // use predefined view cells geometry =>
3306                // contruct bsp hierarchy over them
3307                mBspTree->Construct(mViewCells);
3308        }
3309
3310        // destroy rays created only for construction
3311        CLEAR_CONTAINER(constructionRays);
3312
3313        Debug << mBspTree->GetStatistics() << endl;
3314        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
3315
3316        // recast rest of the rays
3317        if (SAMPLE_AFTER_SUBDIVISION)
3318                ComputeSampleContributions(savedRays, true, false);
3319
3320        // real meshes are contructed at this stage
3321        if (0)
3322        {
3323                cout << "finalizing view cells ... ";
3324                FinalizeViewCells(true);
3325                cout << "finished" << endl;     
3326        }
3327
3328        return sampleContributions;
3329}
3330
3331
3332void BspViewCellsManager::CollectViewCells()
3333{       
3334        if (!ViewCellsTreeConstructed())
3335        {       // view cells tree constructed 
3336                mBspTree->CollectViewCells(mViewCells);
3337        }
3338        else
3339        {       // we can use the view cells tree hierarchy to get the right set
3340                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
3341        }
3342}
3343
3344
3345float BspViewCellsManager::GetProbability(ViewCell *viewCell)
3346{
3347        if (1)
3348                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
3349        else
3350                // compute view cell area as subsititute for probability
3351                return GetArea(viewCell) / GetAccVcArea();
3352}
3353
3354
3355
3356int BspViewCellsManager::CastLineSegment(const Vector3 &origin,
3357                                                                                 const Vector3 &termination,
3358                                                                                 ViewCellContainer &viewcells)
3359{
3360        return mBspTree->CastLineSegment(origin, termination, viewcells);
3361}
3362
3363
3364bool BspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
3365                                                                                                const Vector3 &termination,
3366                                                                                                ViewCell *viewCell)
3367{
3368        return false;
3369}
3370
3371
3372void ViewCellsManager::ExportMergedViewCells(const ObjectContainer &objects)
3373{
3374        // save color code
3375        const int savedColorCode = mColorCode;
3376
3377        Exporter *exporter;
3378
3379#if 0
3380        // export merged view cells
3381        mColorCode = 0; // use random colors
3382
3383        exporter = Exporter::GetExporter("merged_view_cells.wrl");
3384
3385        cout << "exporting view cells after merge ... ";
3386
3387        if (exporter)
3388        {
3389                if (mExportGeometry)
3390                {
3391                        exporter->ExportGeometry(objects);
3392                }
3393
3394                exporter->SetFilled();
3395                ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
3396
3397                delete exporter;
3398        }
3399        cout << "finished" << endl;
3400#endif
3401
3402        // export merged view cells using pvs color coding
3403        exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
3404        cout << "exporting view cells after merge (pvs size) ... ";     
3405
3406        if (exporter)
3407        {
3408                if (mExportGeometry)
3409                {
3410                        exporter->ExportGeometry(objects);
3411                }
3412
3413                exporter->SetFilled();
3414                mColorCode = 1;
3415
3416                ExportViewCellsForViz(exporter, NULL,  mColorCode, GetClipPlane());
3417
3418                delete exporter;
3419        }
3420        cout << "finished" << endl;
3421       
3422        mColorCode = savedColorCode;
3423}
3424
3425
3426int BspViewCellsManager::PostProcess(const ObjectContainer &objects,
3427                                                                         const VssRayContainer &rays)
3428{
3429        if (!ViewCellsConstructed())
3430        {
3431                Debug << "view cells not constructed" << endl;
3432                return 0;
3433        }
3434       
3435        // view cells already finished before post processing step,
3436        // i.e., because they were loaded from disc
3437        if (mViewCellsFinished)
3438        {
3439                FinalizeViewCells(true);
3440                EvaluateViewCellsStats();
3441
3442                return 0;
3443        }
3444
3445        //////////////////
3446        //-- merge leaves of the view cell hierarchy   
3447       
3448        cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
3449        long startTime = GetTime();
3450       
3451        VssRayContainer postProcessRays;
3452        GetRaySets(rays, mPostProcessSamples, postProcessRays);
3453
3454        if (mMergeViewCells)
3455        {
3456                cout << "constructing visibility based merge tree" << endl;
3457                mViewCellsTree->ConstructMergeTree(rays, objects);
3458        }
3459        else
3460        {
3461                cout << "constructing spatial merge tree" << endl;
3462                ViewCell *root;
3463                // the spatial merge tree is difficult to build for
3464                // this type of construction, as view cells cover several
3465                // leaves => create dummy tree which is only 2 levels deep
3466                if (mUsePredefinedViewCells)
3467                {
3468                        root = ConstructDummyMergeTree(mBspTree->GetRoot());
3469                }
3470                else
3471                {
3472                        // create spatial merge hierarchy
3473                        root = ConstructSpatialMergeTree(mBspTree->GetRoot());
3474                }
3475               
3476                mViewCellsTree->SetRoot(root);
3477
3478                // recompute pvs in the whole hierarchy
3479                ObjectPvs pvs;
3480                UpdatePvsForEvaluation(root, pvs);
3481        }
3482
3483        cout << "finished" << endl;
3484        cout << "merged view cells in "
3485                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
3486
3487        Debug << "Postprocessing: Merged view cells in "
3488                << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl << endl;
3489
3490       
3491        ////////////////////////
3492        //-- visualization and statistics after merge
3493
3494        if (1)
3495        {
3496                char mstats[100];
3497                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
3498                mViewCellsTree->ExportStats(mstats);
3499        }
3500
3501        // recompute view cells and stats
3502        ResetViewCells();
3503        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
3504
3505        //  visualization of the view cells
3506        if (1) ExportMergedViewCells(objects);
3507
3508        // compute final meshes and volume / area
3509        if (1) FinalizeViewCells(true);
3510       
3511        return 0;
3512}
3513
3514
3515BspViewCellsManager::~BspViewCellsManager()
3516{
3517}
3518
3519
3520int BspViewCellsManager::GetType() const
3521{
3522        return BSP;
3523}
3524
3525
3526void BspViewCellsManager::Visualize(const ObjectContainer &objects,
3527                                                                        const VssRayContainer &sampleRays)
3528{
3529        if (!ViewCellsConstructed())
3530                return;
3531       
3532        const int savedColorCode = mColorCode;
3533       
3534        if (1) // export final view cells
3535        {
3536                mColorCode = 1; // hack color code
3537                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
3538       
3539                cout << "exporting view cells after merge (pvs size) ... ";     
3540
3541                if (exporter)
3542                {
3543                        if (mExportGeometry)
3544                        {
3545                                exporter->ExportGeometry(objects);
3546                        }
3547
3548                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
3549                        delete exporter;
3550                }
3551                cout << "finished" << endl;
3552        }
3553
3554        // reset color code
3555        mColorCode = savedColorCode;
3556
3557
3558        //////////////////
3559        //-- visualization of the BSP splits
3560
3561        bool exportSplits = false;
3562        Environment::GetSingleton()->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
3563
3564        if (exportSplits)
3565        {
3566                cout << "exporting splits ... ";
3567                ExportSplits(objects);
3568                cout << "finished" << endl;
3569        }
3570
3571        int leafOut;
3572        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
3573        const int raysOut = 100;
3574        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
3575}
3576
3577
3578void BspViewCellsManager::ExportSplits(const ObjectContainer &objects)
3579{
3580        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
3581
3582        if (exporter)
3583        {
3584                //exporter->SetFilled();
3585                if (mExportGeometry)
3586                {
3587                        exporter->ExportGeometry(objects);
3588                }
3589
3590                Material m;
3591                m.mDiffuseColor = RgbColor(1, 0, 0);
3592                exporter->SetForcedMaterial(m);
3593                exporter->SetWireframe();
3594
3595                exporter->ExportBspSplits(*mBspTree, true);
3596
3597                // NOTE: take forced material, else big scenes cannot be viewed
3598                m.mDiffuseColor = RgbColor(0, 1, 0);
3599                exporter->SetForcedMaterial(m);
3600                //exporter->ResetForcedMaterial();
3601
3602                delete exporter;
3603        }
3604}
3605
3606
3607void BspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
3608                                                                                                const int maxViewCells,
3609                                                                                                const bool sortViewCells,
3610                                                                                                const bool exportPvs,
3611                                                                                                const bool exportRays,
3612                                                                                                const int maxRays,
3613                                                                                                const string prefix,
3614                                                                                                VssRayContainer *visRays)
3615{
3616        if (sortViewCells)
3617        {       // sort view cells to visualize the largest view cells
3618                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
3619        }
3620
3621        //////////
3622        //-- some view cells for output
3623
3624        ViewCell::NewMail();
3625        const int limit = min(maxViewCells, (int)mViewCells.size());
3626       
3627        for (int i = 0; i < limit; ++ i)
3628        {
3629                const int idx = sortViewCells ? (int)RandomValue(0, (float)mViewCells.size() - 0.5f) : i;
3630                ViewCell *vc = mViewCells[idx];
3631
3632                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
3633                        continue;
3634
3635                vc->Mail();
3636
3637                ObjectPvs pvs;
3638                mViewCellsTree->GetPvs(vc, pvs);
3639
3640                char s[64]; sprintf(s, "%sviewcell-%04d.wrl", prefix.c_str(), i);
3641                Exporter *exporter = Exporter::GetExporter(s);
3642               
3643                cout << "view cell " << idx << ": pvs cost=" << (int)mViewCellsTree->GetPvsCost(vc) << endl;
3644
3645                if (exportRays)
3646                {
3647                        ////////////
3648                        //-- export rays piercing this view cell
3649
3650                        // use rays stored with the view cells
3651                        VssRayContainer vcRays, vcRays2, vcRays3;
3652            VssRayContainer collectRays;
3653
3654                        // collect initial view cells
3655                        ViewCellContainer leaves;
3656                        mViewCellsTree->CollectLeaves(vc, leaves);
3657
3658                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
3659                for (vit = leaves.begin(); vit != vit_end; ++ vit)
3660                        {       
3661                                // prepare some rays for output
3662                                VssRayContainer::const_iterator rit, rit_end = (*vit)->GetOrCreateRays()->end();
3663                                for (rit = (*vit)->GetOrCreateRays()->begin(); rit != rit_end; ++ rit)
3664                                {
3665                                        collectRays.push_back(*rit);
3666                                }
3667                        }
3668
3669                        const int raysOut = min((int)collectRays.size(), maxRays);
3670
3671                        // prepare some rays for output
3672                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
3673                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
3674                        {
3675                                const float p = RandomValue(0.0f, (float)collectRays.size());
3676                                if (p < raysOut)
3677                                {
3678                                        if ((*rit)->mFlags & VssRay::BorderSample)
3679                                        {
3680                                                vcRays.push_back(*rit);
3681                                        }
3682                                        else if ((*rit)->mFlags & VssRay::ReverseSample)
3683                                        {
3684                                                vcRays2.push_back(*rit);
3685                                        }
3686                                        else
3687                                        {
3688                                                vcRays3.push_back(*rit);
3689                                        }       
3690                                }
3691                        }
3692
3693                        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
3694                        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
3695                        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
3696                }
3697               
3698                ////////////////
3699                //-- export view cell geometry
3700
3701                exporter->SetWireframe();
3702
3703                Material m;//= RandomMaterial();
3704                m.mDiffuseColor = RgbColor(0, 1, 0);
3705                exporter->SetForcedMaterial(m);
3706
3707                ExportViewCellGeometry(exporter, vc, NULL, NULL);
3708                exporter->SetFilled();
3709
3710                if (exportPvs)
3711                {
3712                        Intersectable::NewMail();
3713                        ObjectPvsIterator pit = pvs.GetIterator();
3714
3715                        while (pit.HasMoreEntries())
3716                        {               
3717                                ObjectPvsEntry entry = pit.Next();
3718
3719                // output PVS of view cell
3720                                Intersectable *intersect = entry.mObject;
3721                               
3722                                if (!intersect->Mailed())
3723                                {
3724                                        intersect->Mail();
3725
3726                                        m = RandomMaterial();
3727                                        exporter->SetForcedMaterial(m);
3728                                        exporter->ExportIntersectable(intersect);
3729                                }
3730                        }
3731                        cout << endl;
3732                }
3733               
3734                DEL_PTR(exporter);
3735                cout << "finished" << endl;
3736        }
3737}
3738
3739
3740void BspViewCellsManager::TestSubdivision()
3741{
3742        ViewCellContainer leaves;
3743        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
3744
3745        ViewCellContainer::const_iterator it, it_end = leaves.end();
3746
3747        const float vol = mViewSpaceBox.GetVolume();
3748        float subdivVol = 0;
3749        float newVol = 0;
3750
3751        for (it = leaves.begin(); it != it_end; ++ it)
3752        {
3753                BspNodeGeometry geom;
3754                mBspTree->ConstructGeometry(*it, geom);
3755
3756                const float lVol = geom.GetVolume();
3757                newVol += lVol;
3758                subdivVol += (*it)->GetVolume();
3759
3760                const float thres = 0.9f;
3761                if ((lVol < ((*it)->GetVolume() * thres)) ||
3762                        (lVol * thres > ((*it)->GetVolume())))
3763                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
3764        }
3765       
3766        Debug << "exact volume: " << vol << endl;
3767        Debug << "subdivision volume: " << subdivVol << endl;
3768        Debug << "new volume: " << newVol << endl;
3769}
3770
3771
3772void BspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
3773                                                                                                 ViewCell *vc,
3774                                                                                                 const AxisAlignedBox3 *sceneBox,
3775                                                                                                 const AxisAlignedPlane *clipPlane
3776                                                                                                 ) const
3777{
3778        if (clipPlane)
3779        {
3780                const Plane3 plane = clipPlane->GetPlane();
3781
3782                ViewCellContainer leaves;
3783                mViewCellsTree->CollectLeaves(vc, leaves);
3784                ViewCellContainer::const_iterator it, it_end = leaves.end();
3785
3786                for (it = leaves.begin(); it != it_end; ++ it)
3787                {
3788                        BspNodeGeometry geom;
3789                        BspNodeGeometry front;
3790                        BspNodeGeometry back;
3791
3792                        mBspTree->ConstructGeometry(*it, geom);
3793
3794                        const float eps = 0.0001f;
3795                        const int cf = geom.Side(plane, eps);
3796
3797                        if (cf == -1)
3798                        {
3799                                exporter->ExportPolygons(geom.GetPolys());
3800                        }
3801                        else if (cf == 0)
3802                        {
3803                                geom.SplitGeometry(front,
3804                                                                   back,
3805                                                                   plane,
3806                                                                   mViewSpaceBox,
3807                                                                   eps);
3808
3809                                if (back.Valid())
3810                                {
3811                                        exporter->ExportPolygons(back.GetPolys());
3812                                }                       
3813                        }
3814                }
3815        }
3816        else
3817        {
3818                // export mesh if available
3819                // TODO: some bug here?
3820                if (1 && vc->GetMesh())
3821                {
3822                        exporter->ExportMesh(vc->GetMesh());
3823                }
3824                else
3825                {
3826                        BspNodeGeometry geom;
3827                        mBspTree->ConstructGeometry(vc, geom);
3828                        exporter->ExportPolygons(geom.GetPolys());
3829                }
3830        }
3831}
3832
3833
3834void BspViewCellsManager::CreateMesh(ViewCell *vc)
3835{
3836        // note: should previous mesh be deleted (via mesh manager?)
3837        BspNodeGeometry geom;
3838        mBspTree->ConstructGeometry(vc, geom);
3839
3840        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
3841
3842        IncludeNodeGeomInMesh(geom, *mesh);
3843        vc->SetMesh(mesh);
3844}
3845
3846
3847void BspViewCellsManager::Finalize(ViewCell *viewCell,
3848                                                                   const bool createMesh)
3849{
3850        float area = 0;
3851        float volume = 0;
3852
3853        ViewCellContainer leaves;
3854        mViewCellsTree->CollectLeaves(viewCell, leaves);
3855
3856        ViewCellContainer::const_iterator it, it_end = leaves.end();
3857
3858    for (it = leaves.begin(); it != it_end; ++ it)
3859        {
3860                BspNodeGeometry geom;
3861
3862                mBspTree->ConstructGeometry(*it, geom);
3863
3864                const float lVol = geom.GetVolume();
3865                const float lArea = geom.GetArea();
3866
3867                area += lArea;
3868                volume += lVol;
3869       
3870                CreateMesh(*it);
3871        }
3872
3873        viewCell->SetVolume(volume);
3874        viewCell->SetArea(area);
3875}
3876
3877
3878ViewCell *BspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
3879{
3880        if (!ViewCellsConstructed())
3881        {
3882                return NULL;
3883        }
3884        if (!mViewSpaceBox.IsInside(point))
3885        {
3886                return NULL;
3887        }
3888        return mBspTree->GetViewCell(point);
3889}
3890
3891
3892void BspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3893                                                                                                 vector<MergeCandidate> &candidates)
3894{
3895        cout << "collecting merge candidates ... " << endl;
3896
3897        if (mUseRaysForMerge)
3898        {
3899                mBspTree->CollectMergeCandidates(rays, candidates);
3900        }
3901        else
3902        {
3903                vector<BspLeaf *> leaves;
3904                mBspTree->CollectLeaves(leaves);
3905                mBspTree->CollectMergeCandidates(leaves, candidates);
3906        }
3907
3908        cout << "fininshed collecting candidates" << endl;
3909}
3910
3911
3912
3913bool BspViewCellsManager::ExportViewCells(const string filename,
3914                                                                                  const bool exportPvs,
3915                                                                                  const ObjectContainer &objects)
3916{
3917        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
3918        {
3919                return false;
3920        }
3921
3922        cout << "exporting view cells to xml ... ";
3923
3924        OUT_STREAM stream(filename.c_str());
3925
3926        // for output we need unique ids for each view cell
3927        CreateUniqueViewCellIds();
3928
3929        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
3930        stream << "<VisibilitySolution>" << endl;
3931
3932        if (exportPvs)
3933        {
3934                //////////
3935                //-- export bounding boxes: they are used to identify the objects from the pvs and
3936                //-- assign them to the entities in the rendering engine
3937
3938                stream << "<BoundingBoxes>" << endl;
3939                ObjectContainer::const_iterator oit, oit_end = objects.end();
3940
3941                for (oit = objects.begin(); oit != oit_end; ++ oit)
3942                {
3943                        const AxisAlignedBox3 box = (*oit)->GetBox();
3944                       
3945                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
3946                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
3947                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
3948                }
3949
3950                stream << "</BoundingBoxes>" << endl;
3951        }
3952
3953        ///////////
3954        //-- export the view cells and the pvs
3955
3956        const int numViewCells = mCurrentViewCellsStats.viewCells;
3957        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
3958
3959        mViewCellsTree->Export(stream, exportPvs);
3960       
3961        stream << "</ViewCells>" << endl;
3962
3963        /////////////
3964        //-- export the view space hierarchy
3965        stream << "<ViewSpaceHierarchy type=\"bsp\""
3966                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
3967                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
3968
3969        mBspTree->Export(stream);
3970
3971        // end tags
3972        stream << "</ViewSpaceHierarchy>" << endl;
3973        stream << "</VisibilitySolution>" << endl;
3974
3975        stream.close();
3976        cout << "finished" << endl;
3977
3978        return true;
3979}
3980
3981
3982ViewCell *BspViewCellsManager::ConstructDummyMergeTree(BspNode *root)
3983{
3984        ViewCellInterior *vcRoot = new ViewCellInterior();
3985               
3986        // evaluate merge cost for priority traversal
3987        const float mergeCost =  -(float)root->mTimeStamp;
3988        vcRoot->SetMergeCost(mergeCost);
3989
3990        float volume = 0;
3991        vector<BspLeaf *> leaves;
3992        mBspTree->CollectLeaves(leaves);
3993        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
3994        ViewCell::NewMail();
3995
3996        for (lit = leaves.begin(); lit != lit_end; ++ lit)
3997        {
3998                BspLeaf *leaf = *lit;
3999                ViewCell *vc = leaf->GetViewCell();
4000
4001                if (!vc->Mailed())
4002                {
4003                        vc->Mail();
4004                        vc->SetMergeCost(0.0f);
4005                        vcRoot->SetupChildLink(vc);
4006
4007                        volume += vc->GetVolume();
4008                        volume += vc->GetVolume();     
4009                        vcRoot->SetVolume(volume);
4010                }
4011        }
4012       
4013        return vcRoot;
4014}
4015
4016
4017ViewCell *BspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
4018{
4019        // terminate recursion
4020        if (root->IsLeaf())
4021        {
4022                BspLeaf *leaf = dynamic_cast<BspLeaf *>(root);
4023                leaf->GetViewCell()->SetMergeCost(0.0f);
4024                return leaf->GetViewCell();
4025        }
4026       
4027        BspInterior *interior = dynamic_cast<BspInterior *>(root);
4028        ViewCellInterior *viewCellInterior = new ViewCellInterior();
4029               
4030        // evaluate merge cost for priority traversal
4031        const float mergeCost = -(float)root->mTimeStamp;
4032        viewCellInterior->SetMergeCost(mergeCost);
4033
4034        float volume = 0;
4035       
4036        BspNode *front = interior->GetFront();
4037        BspNode *back = interior->GetBack();
4038
4039
4040        ////////////
4041        //-- recursivly compute child hierarchies
4042
4043        ViewCell *backVc = ConstructSpatialMergeTree(back);
4044        ViewCell *frontVc = ConstructSpatialMergeTree(front);
4045
4046        viewCellInterior->SetupChildLink(backVc);
4047        viewCellInterior->SetupChildLink(frontVc);
4048
4049        volume += backVc->GetVolume();
4050        volume += frontVc->GetVolume();
4051
4052        viewCellInterior->SetVolume(volume);
4053
4054        return viewCellInterior;
4055}
4056
4057
4058/************************************************************************/
4059/*                   KdViewCellsManager implementation                  */
4060/************************************************************************/
4061
4062
4063
4064KdViewCellsManager::KdViewCellsManager(ViewCellsTree *vcTree, KdTree *kdTree):
4065ViewCellsManager(vcTree), mKdTree(kdTree), mKdPvsDepth(100)
4066{
4067}
4068
4069
4070float KdViewCellsManager::GetProbability(ViewCell *viewCell)
4071{
4072        // compute view cell area / volume as subsititute for probability
4073        if (0)
4074                return GetArea(viewCell) / GetViewSpaceBox().SurfaceArea();
4075        else
4076                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
4077}
4078
4079
4080
4081
4082void KdViewCellsManager::CollectViewCells()
4083{
4084        //mKdTree->CollectViewCells(mViewCells); TODO
4085}
4086
4087
4088int KdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4089                                                                  const VssRayContainer &rays)
4090{
4091        // if view cells already constructed
4092        if (ViewCellsConstructed())
4093                return 0;
4094
4095        mKdTree->Construct();
4096
4097        mTotalAreaValid = false;
4098        // create the view cells
4099        mKdTree->CreateAndCollectViewCells(mViewCells);
4100        // cast rays
4101        ComputeSampleContributions(rays, true, false);
4102
4103        EvaluateViewCellsStats();
4104        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4105
4106        return 0;
4107}
4108
4109
4110bool KdViewCellsManager::ViewCellsConstructed() const
4111{
4112        return mKdTree->GetRoot() != NULL;
4113}
4114
4115
4116int KdViewCellsManager::PostProcess(const ObjectContainer &objects,
4117                                                                        const VssRayContainer &rays)
4118{
4119        return 0;
4120}
4121
4122
4123void KdViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4124                                                                                           const int maxViewCells,
4125                                                                                           const bool sortViewCells,
4126                                                                                           const bool exportPvs,
4127                                                                                           const bool exportRays,
4128                                                                                           const int maxRays,
4129                                                                                           const string prefix,
4130                                                                                           VssRayContainer *visRays)
4131{
4132        // TODO
4133}
4134
4135
4136void KdViewCellsManager::Visualize(const ObjectContainer &objects,
4137                                                                   const VssRayContainer &sampleRays)
4138{
4139        if (!ViewCellsConstructed())
4140                return;
4141
4142        // using view cells instead of the kd PVS of objects
4143        const bool useViewCells = true;
4144        bool exportRays = false;
4145
4146        int limit = min(mVisualizationSamples, (int)sampleRays.size());
4147        const int pvsOut = min((int)objects.size(), 10);
4148        VssRayContainer *rays = new VssRayContainer[pvsOut];
4149
4150        if (useViewCells)
4151        {
4152                const int leafOut = 10;
4153
4154                ViewCell::NewMail();
4155
4156                //-- some rays for output
4157                const int raysOut = min((int)sampleRays.size(), mVisualizationSamples);
4158                Debug << "visualization using " << raysOut << " samples" << endl;
4159
4160                //-- some random view cells and rays for output
4161                vector<KdLeaf *> kdLeaves;
4162
4163                for (int i = 0; i < leafOut; ++ i)
4164                        kdLeaves.push_back(dynamic_cast<KdLeaf *>(mKdTree->GetRandomLeaf()));
4165
4166                for (int i = 0; i < kdLeaves.size(); ++ i)
4167                {
4168                        KdLeaf *leaf = kdLeaves[i];
4169                        RayContainer vcRays;
4170
4171                        cout << "creating output for view cell " << i << " ... ";
4172#if 0
4173                        // check whether we can add the current ray to the output rays
4174                        for (int k = 0; k < raysOut; ++ k)
4175                        {
4176                                Ray *ray = sampleRays[k];
4177
4178                                for (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
4179                                {
4180                                        BspLeaf *leaf2 = ray->bspIntersections[j].mLeaf;
4181
4182                                        if (leaf->GetViewCell() == leaf2->GetViewCell())
4183                                        {
4184                                                vcRays.push_back(ray);
4185                                        }
4186                                }
4187                        }
4188#endif
4189                        Intersectable::NewMail();
4190
4191                        ViewCell *vc = leaf->mViewCell;
4192                        char str[64]; sprintf(str, "viewcell%04d.wrl", i);
4193
4194                        Exporter *exporter = Exporter::GetExporter(str);
4195                        exporter->SetFilled();
4196
4197                        exporter->SetWireframe();
4198                        //exporter->SetFilled();
4199
4200                        Material m;//= RandomMaterial();
4201                        m.mDiffuseColor = RgbColor(1, 1, 0);
4202                        exporter->SetForcedMaterial(m);
4203
4204                        AxisAlignedBox3 box = mKdTree->GetBox(leaf);
4205                        exporter->ExportBox(box);
4206
4207                        // export rays piercing this view cell
4208                        exporter->ExportRays(vcRays, 1000, RgbColor(0, 1, 0));
4209
4210                        m.mDiffuseColor = RgbColor(1, 0, 0);
4211                        exporter->SetForcedMaterial(m);
4212
4213                        // exporter->SetWireframe();
4214                        exporter->SetFilled();
4215
4216                        ObjectPvsIterator pit = vc->GetPvs().GetIterator();
4217                       
4218                        while (pit.HasMoreEntries())
4219                        {               
4220                                ObjectPvsEntry entry = pit.Next();
4221                               
4222                                //-- output PVS of view cell
4223                                Intersectable *intersect = entry.mObject;
4224                                if (!intersect->Mailed())
4225                                {
4226                                        exporter->ExportIntersectable(intersect);
4227                                        intersect->Mail();
4228                                }
4229                        }
4230
4231                        DEL_PTR(exporter);
4232                        cout << "finished" << endl;
4233                }
4234
4235                DEL_PTR(rays);
4236        }
4237        else // using kd PVS of objects
4238        {
4239                for (int i = 0; i < limit; ++ i)
4240                {
4241                        VssRay *ray = sampleRays[i];
4242
4243                        // check whether we can add this to the rays
4244                        for (int j = 0; j < pvsOut; j++)
4245                        {
4246                                if (objects[j] == ray->mTerminationObject)
4247                                {
4248                                        rays[j].push_back(ray);
4249                                }
4250                        }
4251                }
4252
4253                if (exportRays)
4254                {
4255                        Exporter *exporter = NULL;
4256                        exporter = Exporter::GetExporter("sample-rays.x3d");
4257                        exporter->SetWireframe();
4258                        exporter->ExportKdTree(*mKdTree);
4259
4260                        for (int i = 0; i < pvsOut; i++)
4261                                exporter->ExportRays(rays[i], RgbColor(1, 0, 0));
4262
4263                        exporter->SetFilled();
4264                        delete exporter;
4265                }
4266
4267                for (int k=0; k < pvsOut; k++)
4268                {
4269                        Intersectable *object = objects[k];
4270                        char str[64]; sprintf(str, "viewcell%04d.wrl", k);
4271
4272                        Exporter *exporter = Exporter::GetExporter(str);
4273                        exporter->SetWireframe();
4274
4275                        // matt: no kd pvs
4276                        /*
4277                        KdPvsMap::iterator kit = object->mKdPvs.mEntries.begin();
4278                        Intersectable::NewMail();
4279
4280                        // avoid adding the object to the list
4281                        object->Mail();
4282                        ObjectContainer visibleObjects;
4283
4284                        for (; kit != object->mKdPvs.mEntries.end(); i++)
4285                        {
4286                                KdNode *node = (*kit).first;
4287                                exporter->ExportBox(mKdTree->GetBox(node));
4288
4289                                mKdTree->CollectObjects(node, visibleObjects);
4290                        }
4291
4292                        exporter->ExportRays(rays[k],  RgbColor(0, 1, 0));
4293                        exporter->SetFilled();
4294
4295                        for (int j = 0; j < visibleObjects.size(); j++)
4296                                exporter->ExportIntersectable(visibleObjects[j]);
4297
4298                        Material m;
4299                        m.mDiffuseColor = RgbColor(1, 0, 0);
4300                        exporter->SetForcedMaterial(m);
4301                        exporter->ExportIntersectable(object);
4302*/
4303                        delete exporter;
4304                }
4305        }
4306}
4307
4308
4309ViewCell *KdViewCellsManager::GenerateViewCell(Mesh *mesh) const
4310{
4311        return new KdViewCell(mesh);
4312}
4313
4314
4315void KdViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4316                                                                                                ViewCell *vc,
4317                                                                                                const AxisAlignedBox3 *sceneBox,
4318                                                                                                const AxisAlignedPlane *clipPlane
4319                                                                                                ) const
4320{
4321        ViewCellContainer leaves;
4322        mViewCellsTree->CollectLeaves(vc, leaves);
4323        ViewCellContainer::const_iterator it, it_end = leaves.end();
4324
4325        for (it = leaves.begin(); it != it_end; ++ it)
4326        {
4327                KdViewCell *kdVc = dynamic_cast<KdViewCell *>(*it);
4328                exporter->ExportBox(mKdTree->GetBox(kdVc->mLeaves[0]));
4329        }
4330}
4331
4332
4333int KdViewCellsManager::GetType() const
4334{
4335        return ViewCellsManager::KD;
4336}
4337
4338
4339
4340KdNode *KdViewCellsManager::GetNodeForPvs(KdLeaf *leaf)
4341{
4342        KdNode *node = leaf;
4343
4344        while (node->mParent && node->mDepth > mKdPvsDepth)
4345                node = node->mParent;
4346
4347        return node;
4348}
4349
4350int KdViewCellsManager::CastLineSegment(const Vector3 &origin,
4351                                                                                const Vector3 &termination,
4352                                                                                ViewCellContainer &viewcells)
4353{
4354        return mKdTree->CastLineSegment(origin, termination, viewcells);
4355}
4356
4357
4358bool KdViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
4359                                                                                           const Vector3 &termination,
4360                                                                                           ViewCell *viewCell)
4361{
4362        return false;
4363}
4364
4365
4366void KdViewCellsManager::CreateMesh(ViewCell *vc)
4367{
4368        // TODO
4369}
4370
4371
4372
4373void KdViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4374                                                                                                vector<MergeCandidate> &candidates)
4375{
4376        // TODO
4377}
4378
4379
4380
4381/**************************************************************************/
4382/*                   VspBspViewCellsManager implementation                */
4383/**************************************************************************/
4384
4385
4386VspBspViewCellsManager::VspBspViewCellsManager(ViewCellsTree *vcTree, VspBspTree *vspBspTree):
4387ViewCellsManager(vcTree), mVspBspTree(vspBspTree)
4388{
4389        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", mInitialSamples);
4390        mVspBspTree->SetViewCellsManager(this);
4391        mVspBspTree->mViewCellsTree = mViewCellsTree;
4392}
4393
4394
4395VspBspViewCellsManager::~VspBspViewCellsManager()
4396{
4397}
4398
4399
4400float VspBspViewCellsManager::GetProbability(ViewCell *viewCell)
4401{
4402        if (0 && mVspBspTree->mUseAreaForPvs)
4403                return GetArea(viewCell) / GetAccVcArea();
4404        else
4405                return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
4406}
4407
4408
4409void VspBspViewCellsManager::CollectViewCells()
4410{
4411        // view cells tree constructed?
4412        if (!ViewCellsTreeConstructed())
4413        {
4414                mVspBspTree->CollectViewCells(mViewCells, false);
4415        }
4416        else
4417        {       
4418                // we can use the view cells tree hierarchy to get the right set
4419                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
4420        }
4421}
4422
4423
4424void VspBspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4425                                                                                                        vector<MergeCandidate> &candidates)
4426{       
4427        cout << "collecting merge candidates ... " << endl;
4428
4429        if (mUseRaysForMerge)
4430        {
4431                mVspBspTree->CollectMergeCandidates(rays, candidates);
4432        }
4433        else
4434        {
4435                vector<BspLeaf *> leaves;
4436                mVspBspTree->CollectLeaves(leaves);
4437       
4438                mVspBspTree->CollectMergeCandidates(leaves, candidates);
4439        }
4440
4441        cout << "fininshed collecting candidates" << endl;
4442}
4443
4444
4445bool VspBspViewCellsManager::ViewCellsConstructed() const
4446{
4447        return mVspBspTree->GetRoot() != NULL;
4448}
4449
4450
4451ViewCell *VspBspViewCellsManager::GenerateViewCell(Mesh *mesh) const
4452{
4453        return new BspViewCell(mesh);
4454}
4455
4456
4457int VspBspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4458                                                                                                 const VssRayContainer &rays)
4459{
4460        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
4461
4462        // if view cells were already constructed
4463        if (ViewCellsConstructed())
4464        {
4465                return 0;
4466        }
4467
4468        int sampleContributions = 0;
4469        VssRayContainer sampleRays;
4470
4471        const int limit = min(mInitialSamples, (int)rays.size());
4472
4473        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
4474                  << ", actual rays: " << (int)rays.size() << endl;
4475
4476        VssRayContainer savedRays;
4477
4478        if (SAMPLE_AFTER_SUBDIVISION)
4479        {
4480                VssRayContainer constructionRays;
4481               
4482                GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
4483
4484                Debug << "rays used for initial construction: " << (int)constructionRays.size() << endl;
4485                Debug << "rays saved for later use: " << (int)savedRays.size() << endl;
4486       
4487                mVspBspTree->Construct(constructionRays, &mViewSpaceBox);
4488        }
4489        else
4490        {
4491                Debug << "rays used for initial construction: " << (int)rays.size() << endl;
4492                mVspBspTree->Construct(rays, &mViewSpaceBox);
4493        }
4494
4495        // collapse invalid regions
4496        cout << "collapsing invalid tree regions ... ";
4497        long startTime = GetTime();
4498
4499        const int collapsedLeaves = mVspBspTree->CollapseTree();
4500        Debug << "collapsed in " << TimeDiff(startTime, GetTime()) * 1e-3
4501                  << " seconds" << endl;
4502
4503    cout << "finished" << endl;
4504
4505        /////////////////
4506        //-- stats after construction
4507
4508        Debug << mVspBspTree->GetStatistics() << endl;
4509
4510        ResetViewCells();
4511        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4512
4513
4514        //////////////////////
4515        //-- recast the rest of the rays
4516
4517        startTime = GetTime();
4518
4519        cout << "Computing remaining ray contributions ... ";
4520
4521        if (SAMPLE_AFTER_SUBDIVISION)
4522                ComputeSampleContributions(savedRays, true, false);
4523
4524        cout << "finished" << endl;
4525
4526        Debug << "Computed remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
4527                  << " secs" << endl;
4528
4529        cout << "construction finished" << endl;
4530
4531        if (0)
4532        {       ////////
4533                //-- real meshes are contructed at this stage
4534
4535                cout << "finalizing view cells ... ";
4536                FinalizeViewCells(true);
4537                cout << "finished" << endl;
4538        }
4539
4540        return sampleContributions;
4541}
4542
4543
4544void VspBspViewCellsManager::MergeViewCells(const VssRayContainer &rays,
4545                                                                                        const ObjectContainer &objects)
4546{
4547    int vcSize = 0;
4548        int pvsSize = 0;
4549
4550        //-- merge view cells
4551        cout << "starting merge using " << mPostProcessSamples << " samples ... " << endl;
4552        long startTime = GetTime();
4553
4554
4555        if (mMergeViewCells)
4556        {
4557                // TODO: should be done BEFORE the ray casting
4558                // compute tree by merging the nodes based on cost heuristics
4559                mViewCellsTree->ConstructMergeTree(rays, objects);
4560        }
4561        else
4562        {
4563                // compute tree by merging the nodes of the spatial hierarchy
4564                ViewCell *root = ConstructSpatialMergeTree(mVspBspTree->GetRoot());
4565                mViewCellsTree->SetRoot(root);
4566
4567                // compute pvs
4568                ObjectPvs pvs;
4569                UpdatePvsForEvaluation(root, pvs);
4570        }
4571
4572        if (1)
4573        {
4574                char mstats[100];
4575                ObjectPvs pvs;
4576
4577                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
4578                mViewCellsTree->ExportStats(mstats);
4579        }
4580
4581        cout << "merged view cells in "
4582                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
4583
4584        Debug << "Postprocessing: Merged view cells in "
4585                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
4586       
4587
4588        //////////////////
4589        //-- stats and visualizations
4590
4591        int savedColorCode = mColorCode;
4592       
4593        // get currently active view cell set
4594        ResetViewCells();
4595        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
4596       
4597        if (mShowVisualization) // export merged view cells
4598        {
4599                mColorCode = 0;
4600                Exporter *exporter = Exporter::GetExporter("merged_view_cells.wrl");
4601               
4602                cout << "exporting view cells after merge ... ";
4603
4604                if (exporter)
4605                {
4606                        if (0)
4607                                exporter->SetWireframe();
4608                        else
4609                                exporter->SetFilled();
4610
4611                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
4612
4613                        if (mExportGeometry)
4614                        {
4615                                Material m;
4616                                m.mDiffuseColor = RgbColor(0, 1, 0);
4617                                exporter->SetForcedMaterial(m);
4618                                exporter->SetFilled();
4619
4620                                exporter->ExportGeometry(objects);
4621                        }
4622
4623                        delete exporter;
4624                }
4625                cout << "finished" << endl;
4626        }
4627
4628        if (mShowVisualization)
4629        {
4630                // use pvs size for color coding
4631                mColorCode = 1;
4632                Exporter *exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
4633
4634                cout << "exporting view cells after merge (pvs size) ... ";     
4635
4636                if (exporter)
4637                {
4638                        exporter->SetFilled();
4639
4640                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
4641
4642                        if (mExportGeometry)
4643                        {
4644                                Material m;
4645                                m.mDiffuseColor = RgbColor(0, 1, 0);
4646                                exporter->SetForcedMaterial(m);
4647                                exporter->SetFilled();
4648
4649                                exporter->ExportGeometry(objects);
4650                        }
4651
4652                        delete exporter;
4653                }
4654                cout << "finished" << endl;
4655        }
4656
4657        mColorCode = savedColorCode;
4658}
4659
4660
4661void VspBspViewCellsManager::RefineViewCells(const VssRayContainer &rays,
4662                                                                                         const ObjectContainer &objects)
4663{
4664        mRenderer->RenderScene();
4665
4666        SimulationStatistics ss;
4667        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
4668    Debug << "render time before refine\n\n" << ss << endl;
4669
4670        const long startTime = GetTime();
4671        cout << "Refining the merged view cells ... ";
4672
4673        // refining the merged view cells
4674        const int refined = mViewCellsTree->RefineViewCells(rays, objects);
4675
4676        //-- stats and visualizations
4677        cout << "finished" << endl;
4678        cout << "refined " << refined << " view cells in "
4679                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
4680
4681        Debug << "Postprocessing: refined " << refined << " view cells in "
4682                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
4683}
4684
4685
4686int VspBspViewCellsManager::PostProcess(const ObjectContainer &objects,
4687                                                                                const VssRayContainer &rays)
4688{
4689        if (!ViewCellsConstructed())
4690        {
4691                Debug << "postprocess error: no view cells constructed" << endl;
4692                return 0;
4693        }
4694
4695        // view cells already finished before post processing step
4696        // (i.e. because they were loaded)
4697        if (mViewCellsFinished)
4698        {
4699                FinalizeViewCells(true);
4700                EvaluateViewCellsStats();
4701
4702                return 0;
4703        }
4704
4705        // check if new view cells turned invalid
4706        int minPvs, maxPvs;
4707
4708        if (0)
4709        {
4710                minPvs = mMinPvsSize;
4711                maxPvs = mMaxPvsSize;
4712        }
4713        else
4714        {
4715                // problem matt: why did I start here from zero?
4716                minPvs = 0;
4717                maxPvs = mMaxPvsSize;
4718        }
4719
4720        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4721        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
4722       
4723        SetValidity(minPvs, maxPvs);
4724
4725        // update valid view space according to valid view cells
4726        if (0) mVspBspTree->ValidateTree();
4727
4728        // area has to be recomputed
4729        mTotalAreaValid = false;
4730        VssRayContainer postProcessRays;
4731        GetRaySets(rays, mPostProcessSamples, postProcessRays);
4732
4733        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
4734
4735        //////////
4736        //-- merge neighbouring view cells
4737        MergeViewCells(postProcessRays, objects);
4738       
4739        // refines the merged view cells
4740        if (0) RefineViewCells(postProcessRays, objects);
4741
4742
4743        ///////////
4744        //-- render simulation after merge + refine
4745
4746        cout << "\nview cells partition render time before compress" << endl << endl;;
4747        dynamic_cast<RenderSimulator *>(mRenderer)->RenderScene();
4748        SimulationStatistics ss;
4749        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
4750        cout << ss << endl;
4751       
4752        if (0) CompressViewCells();
4753       
4754        // collapse sibling leaves that share the same view cell
4755        if (0) mVspBspTree->CollapseTree();
4756
4757        // recompute view cell list and statistics
4758        ResetViewCells();
4759
4760        // compute final meshes and volume / area
4761        if (1) FinalizeViewCells(true);
4762
4763        return 0;
4764}
4765
4766
4767int VspBspViewCellsManager::GetType() const
4768{
4769        return VSP_BSP;
4770}
4771
4772
4773ViewCell *VspBspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
4774{
4775        // terminate recursion
4776        if (root->IsLeaf())
4777        {
4778                BspLeaf *leaf = dynamic_cast<BspLeaf *>(root);
4779                leaf->GetViewCell()->SetMergeCost(0.0f);
4780                return leaf->GetViewCell();
4781        }
4782       
4783       
4784        BspInterior *interior = dynamic_cast<BspInterior *>(root);
4785        ViewCellInterior *viewCellInterior = new ViewCellInterior();
4786               
4787        // evaluate merge cost for priority traversal
4788        float mergeCost = 1.0f / (float)root->mTimeStamp;
4789        viewCellInterior->SetMergeCost(mergeCost);
4790
4791        float volume = 0;
4792       
4793        BspNode *front = interior->GetFront();
4794        BspNode *back = interior->GetBack();
4795
4796
4797        ObjectPvs frontPvs, backPvs;
4798
4799        //-- recursivly compute child hierarchies
4800        ViewCell *backVc = ConstructSpatialMergeTree(back);
4801        ViewCell *frontVc = ConstructSpatialMergeTree(front);
4802
4803
4804        viewCellInterior->SetupChildLink(backVc);
4805        viewCellInterior->SetupChildLink(frontVc);
4806
4807        volume += backVc->GetVolume();
4808        volume += frontVc->GetVolume();
4809
4810        viewCellInterior->SetVolume(volume);
4811
4812        return viewCellInterior;
4813}
4814
4815
4816bool VspBspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
4817{
4818        if (!ViewCellsConstructed())
4819                return ViewCellsManager::GetViewPoint(viewPoint);
4820
4821        // TODO: set reasonable limit
4822        const int limit = 20;
4823
4824        for (int i = 0; i < limit; ++ i)
4825        {
4826                viewPoint = mViewSpaceBox.GetRandomPoint();
4827                if (mVspBspTree->ViewPointValid(viewPoint))
4828                {
4829                        return true;
4830                }
4831        }
4832
4833        Debug << "failed to find valid view point, taking " << viewPoint << endl;
4834        return false;
4835}
4836
4837
4838bool VspBspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
4839{
4840        // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
4841        // validy update in preprocessor for all managers)
4842        return ViewCellsManager::ViewPointValid(viewPoint);
4843
4844        //      return mViewSpaceBox.IsInside(viewPoint) &&
4845        //                 mVspBspTree->ViewPointValid(viewPoint);
4846}
4847
4848
4849void VspBspViewCellsManager::Visualize(const ObjectContainer &objects,
4850                                                                           const VssRayContainer &sampleRays)
4851{
4852        if (!ViewCellsConstructed())
4853                return;
4854
4855        VssRayContainer visRays;
4856        GetRaySets(sampleRays, mVisualizationSamples, visRays);
4857       
4858        if (1)
4859        {       
4860                //////////////////
4861                //-- export final view cell partition
4862
4863                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
4864               
4865                if (exporter)
4866                {
4867                        cout << "exporting view cells after post process ... ";
4868                        if (0)
4869                        {       // export view space box
4870                                exporter->SetWireframe();
4871                                exporter->ExportBox(mViewSpaceBox);
4872                                exporter->SetFilled();
4873                        }
4874
4875                        Material m;
4876                        m.mDiffuseColor.r = 0.0f;
4877                        m.mDiffuseColor.g = 0.5f;
4878                        m.mDiffuseColor.b = 0.5f;
4879
4880            exporter->SetForcedMaterial(m);
4881
4882                        if (1 && mExportGeometry)
4883                        {
4884                                exporter->ExportGeometry(objects);
4885                        }
4886
4887                        if (0 && mExportRays)
4888                        {
4889                                exporter->ExportRays(visRays, RgbColor(1, 0, 0));
4890                        }
4891                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
4892
4893                        delete exporter;
4894                        cout << "finished" << endl;
4895                }
4896        }
4897
4898        ////////////////
4899        //-- visualization of the BSP splits
4900
4901        bool exportSplits = false;
4902        Environment::GetSingleton()->GetBoolValue("VspBspTree.Visualization.exportSplits", exportSplits);
4903
4904        if (exportSplits)
4905        {
4906                cout << "exporting splits ... ";
4907                ExportSplits(objects, visRays);
4908                cout << "finished" << endl;
4909        }
4910
4911        ////////
4912        //-- export single view cells
4913       
4914        int leafOut;
4915        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
4916        const int raysOut = 100;
4917       
4918        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
4919}
4920
4921
4922void VspBspViewCellsManager::ExportSplits(const ObjectContainer &objects,
4923                                                                                  const VssRayContainer &rays)
4924{
4925        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
4926
4927        if (exporter)
4928        {
4929                Material m;
4930                m.mDiffuseColor = RgbColor(1, 0, 0);
4931                exporter->SetForcedMaterial(m);
4932                exporter->SetWireframe();
4933
4934                exporter->ExportBspSplits(*mVspBspTree, true);
4935
4936                // take forced material, else big scenes cannot be viewed
4937                m.mDiffuseColor = RgbColor(0, 1, 0);
4938                exporter->SetForcedMaterial(m);
4939                exporter->SetFilled();
4940
4941                exporter->ResetForcedMaterial();
4942
4943                // export rays
4944                if (mExportRays)
4945                {
4946                        exporter->ExportRays(rays, RgbColor(1, 1, 0));
4947                }
4948
4949                if (mExportGeometry)
4950                {
4951                        exporter->ExportGeometry(objects);
4952                }
4953                delete exporter;
4954        }
4955}
4956
4957
4958void VspBspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4959                                                                                                   const int maxViewCells,
4960                                                                                                   const bool sortViewCells,
4961                                                                                                   const bool exportPvs,
4962                                                                                                   const bool exportRays,
4963                                                                                                   const int maxRays,
4964                                                                                                   const string prefix,
4965                                                                                                   VssRayContainer *visRays)
4966{       
4967        if (sortViewCells)
4968        {
4969                // sort view cells to visualize the largest view cells
4970                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
4971        }
4972
4973        //////////
4974        //-- some view cells for output
4975
4976        ViewCell::NewMail();
4977        const int limit = min(maxViewCells, (int)mViewCells.size());
4978       
4979        for (int i = 0; i < limit; ++ i)
4980        {
4981                cout << "creating output for view cell " << i << " ... ";
4982
4983                ViewCell *vc = sortViewCells ? // largest view cell pvs first?
4984                        mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 0.5f)] : mViewCells[i];
4985
4986                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
4987                        continue;
4988
4989                vc->Mail();
4990
4991                ObjectPvs pvs;
4992                mViewCellsTree->GetPvs(vc, pvs);
4993
4994                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
4995                Exporter *exporter = Exporter::GetExporter(s);
4996               
4997                const float pvsCost = mViewCellsTree->GetPvsCost(vc);
4998                cout << "view cell " << vc->GetId() << ": pvs cost=" << pvsCost << endl;
4999
5000                if (exportRays)
5001                {
5002                        ////////////
5003                        //-- export rays piercing this view cell
5004
5005                        // take rays stored with the view cells during subdivision
5006                        VssRayContainer vcRays;
5007            VssRayContainer collectRays;
5008
5009                        // collect initial view cells
5010                        ViewCellContainer leaves;
5011                        mViewCellsTree->CollectLeaves(vc, leaves);
5012
5013                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
5014                for (vit = leaves.begin(); vit != vit_end; ++ vit)
5015                        {       
5016                                BspLeaf *vcLeaf = dynamic_cast<BspViewCell *>(*vit)->mLeaves[0];
5017                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
5018
5019                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
5020                                {
5021                                        collectRays.push_back(*rit);
5022                                }
5023                        }
5024
5025                        const int raysOut = min((int)collectRays.size(), maxRays);
5026               
5027                        // prepare some rays for output
5028                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
5029                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
5030                        {
5031                                const float p = RandomValue(0.0f, (float)collectRays.size());
5032                       
5033                                if (p < raysOut)
5034                                {
5035                                        vcRays.push_back(*rit);
5036                                }
5037                        }
5038
5039                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
5040                }
5041               
5042                ////////////////
5043                //-- export view cell geometry
5044
5045                exporter->SetWireframe();
5046
5047                Material m;//= RandomMaterial();
5048                m.mDiffuseColor = RgbColor(0, 1, 0);
5049                exporter->SetForcedMaterial(m);
5050
5051                ExportViewCellGeometry(exporter, vc, NULL, NULL);
5052                exporter->SetFilled();
5053
5054                if (exportPvs)
5055                {
5056                        Intersectable::NewMail();
5057
5058                        ObjectPvsIterator pit = pvs.GetIterator();
5059
5060                        cout << endl;
5061
5062                        // output PVS of view cell
5063                        while (pit.HasMoreEntries())
5064                        {
5065                                ObjectPvsEntry entry = pit.Next();             
5066                                Intersectable *intersect = entry.mObject;
5067                               
5068                                if (!intersect->Mailed())
5069                                {
5070                                        intersect->Mail();
5071
5072                                        m = RandomMaterial();
5073                                        exporter->SetForcedMaterial(m);
5074                                        exporter->ExportIntersectable(intersect);
5075                                }
5076                        }
5077                        cout << endl;
5078                }
5079               
5080                DEL_PTR(exporter);
5081                cout << "finished" << endl;
5082        }
5083}
5084
5085
5086void VspBspViewCellsManager::TestFilter(const ObjectContainer &objects)
5087{
5088        Exporter *exporter = Exporter::GetExporter("filter.x3d");
5089
5090        Vector3 bsize = mViewSpaceBox.Size();
5091        const Vector3 viewPoint(mViewSpaceBox.Center());
5092        float w = Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
5093        const Vector3 width = Vector3(w);
5094       
5095        PrVs testPrVs;
5096       
5097        if (exporter)
5098        {
5099                ViewCellContainer viewCells;
5100       
5101        const AxisAlignedBox3 tbox = GetFilterBBox(viewPoint, mFilterWidth);
5102
5103                GetPrVS(viewPoint, testPrVs, GetFilterWidth());
5104
5105                exporter->SetWireframe();
5106
5107                exporter->SetForcedMaterial(RgbColor(1,1,1));
5108                exporter->ExportBox(tbox);
5109               
5110                exporter->SetFilled();
5111
5112                exporter->SetForcedMaterial(RgbColor(0,1,0));
5113                ExportViewCellGeometry(exporter, GetViewCell(viewPoint), NULL, NULL);
5114
5115                //exporter->ResetForcedMaterial();
5116                exporter->SetForcedMaterial(RgbColor(0,0,1));
5117                ExportViewCellGeometry(exporter, testPrVs.mViewCell, NULL, NULL);
5118
5119        exporter->SetForcedMaterial(RgbColor(1,0,0));
5120                exporter->ExportGeometry(objects);
5121
5122                delete exporter;
5123        }
5124}
5125
5126
5127int VspBspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
5128                                                                                                        ViewCellContainer &viewCells) const
5129{
5130        return mVspBspTree->ComputeBoxIntersections(box, viewCells);
5131}
5132
5133
5134int VspBspViewCellsManager::CastLineSegment(const Vector3 &origin,
5135                                                                                        const Vector3 &termination,
5136                                                                                        ViewCellContainer &viewcells)
5137{
5138        return mVspBspTree->CastLineSegment(origin, termination, viewcells);
5139}
5140
5141
5142bool VspBspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
5143                                                                                                   const Vector3 &termination,
5144                                                                                                   ViewCell *viewCell)
5145{
5146        return false;
5147}
5148
5149
5150void VspBspViewCellsManager::VisualizeWithFromPointQueries()
5151{
5152        int numSamples;
5153       
5154        Environment::GetSingleton()->GetIntValue("RenderSampler.samples", numSamples);
5155        cout << "samples" << numSamples << endl;
5156
5157        vector<RenderCostSample> samples;
5158 
5159        if (!mPreprocessor->GetRenderer())
5160                return;
5161
5162        //start the view point queries
5163        long startTime = GetTime();
5164        cout << "starting sampling of render cost ... ";
5165       
5166        mPreprocessor->GetRenderer()->SampleRenderCost(numSamples, samples, true);
5167
5168        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
5169
5170
5171        // for each sample:
5172        //    find view cells associated with the samples
5173        //    store the sample pvs with the pvs associated with the view cell
5174        //
5175        // for each view cell:
5176        //    compute difference point sampled pvs - view cell pvs
5177        //    export geometry with color coded pvs difference
5178       
5179    std::map<ViewCell *, ObjectPvs> sampleMap;
5180
5181        vector<RenderCostSample>::const_iterator rit, rit_end = samples.end();
5182
5183        for (rit = samples.begin(); rit != rit_end; ++ rit)
5184        {
5185                RenderCostSample sample = *rit;
5186       
5187                ViewCell *vc = GetViewCell(sample.mPosition);
5188
5189                std::map<ViewCell *, ObjectPvs>::iterator it = sampleMap.find(vc);
5190
5191                if (it == sampleMap.end())
5192                {
5193                        sampleMap[vc] = sample.mPvs;
5194                }
5195                else
5196                {
5197                        (*it).second.MergeInPlace(sample.mPvs);
5198                }
5199        }
5200
5201        // visualize the view cells
5202        std::map<ViewCell *, ObjectPvs>::const_iterator vit, vit_end = sampleMap.end();
5203
5204        Material m;//= RandomMaterial();
5205
5206        for (vit = sampleMap.begin(); vit != vit_end; ++ vit)
5207        {
5208                ViewCell *vc = (*vit).first;
5209               
5210                const int pvsVc = mViewCellsTree->GetPvsEntries(vc);
5211                const int pvsPtSamples = (*vit).second.GetSize();
5212
5213        m.mDiffuseColor.r = (float) (pvsVc - pvsPtSamples);
5214                m.mDiffuseColor.b = 1.0f;
5215                //exporter->SetForcedMaterial(m);
5216                //ExportViewCellGeometry(exporter, vc, mClipPlaneForViz);
5217
5218                /*      // counting the pvss
5219                for (rit = samples.begin(); rit != rit_end; ++ rit)
5220                {
5221                        RenderCostSample sample = *rit;
5222                        ViewCell *vc = GetViewCell(sample.mPosition);
5223
5224                        AxisAlignedBox3 box(sample.mPosition - Vector3(1, 1, 1), sample.mPosition + Vector3(1, 1, 1));
5225                        Mesh *hMesh = CreateMeshFromBox(box);
5226
5227                        DEL_PTR(hMesh);
5228                }
5229                */
5230        }
5231}
5232
5233
5234void VspBspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
5235                                                                                                        ViewCell *vc,
5236                                                                                                        const AxisAlignedBox3 *sceneBox,
5237                                                                                                        const AxisAlignedPlane *clipPlane
5238                                                                                                        ) const
5239{
5240        if (clipPlane)
5241        {
5242                const Plane3 plane = clipPlane->GetPlane();
5243
5244                ViewCellContainer leaves;
5245                mViewCellsTree->CollectLeaves(vc, leaves);
5246                ViewCellContainer::const_iterator it, it_end = leaves.end();
5247
5248                for (it = leaves.begin(); it != it_end; ++ it)
5249                {
5250                        BspNodeGeometry geom;
5251                        BspNodeGeometry front;
5252                        BspNodeGeometry back;
5253
5254                        mVspBspTree->ConstructGeometry(*it, geom);
5255
5256                        const float eps = 0.0001f;
5257                        const int cf = geom.Side(plane, eps);
5258
5259                        if (cf == -1)
5260                        {
5261                                exporter->ExportPolygons(geom.GetPolys());
5262                        }
5263                        else if (cf == 0)
5264                        {
5265                                geom.SplitGeometry(front,
5266                                                                   back,
5267                                                                   plane,
5268                                                                   mViewSpaceBox,
5269                                                                   eps);
5270
5271                                if (back.Valid())
5272                                {
5273                                        exporter->ExportPolygons(back.GetPolys());
5274                                }                       
5275                        }
5276                }
5277        }
5278        else
5279        {
5280                // export mesh if available
5281                // TODO: some bug here?
5282                if (1 && vc->GetMesh())
5283                {
5284                        exporter->ExportMesh(vc->GetMesh());
5285                }
5286                else
5287                {
5288                        BspNodeGeometry geom;
5289                        mVspBspTree->ConstructGeometry(vc, geom);
5290                        exporter->ExportPolygons(geom.GetPolys());
5291                }
5292        }
5293}
5294
5295
5296int VspBspViewCellsManager::GetMaxTreeDiff(ViewCell *vc) const
5297{
5298        ViewCellContainer leaves;
5299        mViewCellsTree->CollectLeaves(vc, leaves);
5300
5301        int maxDist = 0;
5302       
5303        // compute max height difference
5304        for (int i = 0; i < (int)leaves.size(); ++ i)
5305        {
5306                for (int j = 0; j < (int)leaves.size(); ++ j)
5307                {
5308                        BspLeaf *leaf = dynamic_cast<BspViewCell *>(leaves[i])->mLeaves[0];
5309
5310                        if (i != j)
5311                        {
5312                                BspLeaf *leaf2 =dynamic_cast<BspViewCell *>(leaves[j])->mLeaves[0];
5313                                const int dist = mVspBspTree->TreeDistance(leaf, leaf2);
5314                               
5315                                if (dist > maxDist)
5316                                        maxDist = dist;
5317                        }
5318                }
5319        }
5320
5321        return maxDist;
5322}
5323
5324
5325ViewCell *VspBspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
5326{
5327        if (!ViewCellsConstructed())
5328                return NULL;
5329
5330        if (!mViewSpaceBox.IsInside(point))
5331          return NULL;
5332
5333        return mVspBspTree->GetViewCell(point, active);
5334}
5335
5336
5337void VspBspViewCellsManager::CreateMesh(ViewCell *vc)
5338{
5339        BspNodeGeometry geom;
5340        mVspBspTree->ConstructGeometry(vc, geom);
5341       
5342        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
5343        IncludeNodeGeomInMesh(geom, *mesh);
5344
5345        vc->SetMesh(mesh);
5346}
5347
5348
5349int VspBspViewCellsManager::CastBeam(Beam &beam)
5350{
5351        return mVspBspTree->CastBeam(beam);
5352}
5353
5354
5355void VspBspViewCellsManager::Finalize(ViewCell *viewCell,
5356                                                                          const bool createMesh)
5357{
5358        float area = 0;
5359        float volume = 0;
5360
5361        ViewCellContainer leaves;
5362        mViewCellsTree->CollectLeaves(viewCell, leaves);
5363
5364        ViewCellContainer::const_iterator it, it_end = leaves.end();
5365
5366    for (it = leaves.begin(); it != it_end; ++ it)
5367        {
5368                BspNodeGeometry geom;
5369                mVspBspTree->ConstructGeometry(*it, geom);
5370
5371                const float lVol = geom.GetVolume();
5372                const float lArea = geom.GetArea();
5373
5374                area += lArea;
5375                volume += lVol;
5376
5377                if (createMesh)
5378                        CreateMesh(*it);
5379        }
5380
5381        viewCell->SetVolume(volume);
5382        viewCell->SetArea(area);
5383}
5384
5385
5386void VspBspViewCellsManager::TestSubdivision()
5387{
5388        ViewCellContainer leaves;
5389        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
5390
5391        ViewCellContainer::const_iterator it, it_end = leaves.end();
5392
5393        const float vol = mViewSpaceBox.GetVolume();
5394        float subdivVol = 0;
5395        float newVol = 0;
5396
5397        for (it = leaves.begin(); it != it_end; ++ it)
5398        {
5399                BspNodeGeometry geom;
5400                mVspBspTree->ConstructGeometry(*it, geom);
5401
5402                const float lVol = geom.GetVolume();
5403               
5404                newVol += lVol;
5405                subdivVol += (*it)->GetVolume();
5406               
5407                float thres = 0.9f;
5408                if ((lVol < ((*it)->GetVolume() * thres)) || (lVol * thres > ((*it)->GetVolume())))
5409                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
5410        }
5411       
5412        Debug << "exact volume: " << vol << endl;
5413        Debug << "subdivision volume: " << subdivVol << endl;
5414        Debug << "new volume: " << newVol << endl;
5415}
5416
5417
5418void VspBspViewCellsManager::PrepareLoadedViewCells()
5419{
5420        // TODO: do I still need this here?
5421        if (0)
5422                mVspBspTree->RepairViewCellsLeafLists();
5423}
5424
5425
5426
5427/************************************************************************/
5428/*                 VspOspViewCellsManager implementation                */
5429/************************************************************************/
5430
5431
5432VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree,
5433                                                                                           const string &hierarchyType)
5434: ViewCellsManager(vcTree)
5435{
5436        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5437
5438        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5439
5440        Debug << "compressing objects: " << mCompressObjects << endl;
5441        cout << "compressing objects: " << mCompressObjects << endl;
5442
5443        mHierarchyManager = CreateHierarchyManager(hierarchyType);
5444        mHierarchyManager->SetViewCellsManager(this);
5445        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5446}
5447
5448
5449VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm)
5450: ViewCellsManager(vcTree), mHierarchyManager(hm)
5451{
5452        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5453        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5454
5455        Debug << "compressing objects: " << mCompressObjects << endl;
5456        cout << "compressing objects: " << mCompressObjects << endl;
5457
5458        mHierarchyManager->SetViewCellsManager(this);
5459        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5460}
5461
5462
5463Intersectable *
5464VspOspViewCellsManager::GetIntersectable(const VssRay &ray, const bool isTermination) const
5465{
5466        if (mUseKdPvs)
5467        {
5468                return ViewCellsManager::GetIntersectable(ray, isTermination);
5469        }
5470        else
5471        {
5472                return mHierarchyManager->GetIntersectable(ray, isTermination);
5473        }
5474}
5475
5476
5477HierarchyManager *VspOspViewCellsManager::CreateHierarchyManager(const string &hierarchyType)
5478{
5479        HierarchyManager *hierarchyManager;
5480
5481        if (strcmp(hierarchyType.c_str(), "osp") == 0)
5482        {
5483                Debug << "hierarchy manager: osp" << endl;
5484                hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
5485        }
5486        else if (strcmp(hierarchyType.c_str(), "bvh") == 0)
5487        {
5488                Debug << "hierarchy manager: bvh" << endl;
5489                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
5490        }
5491        else // only view space partition
5492        {
5493                Debug << "hierarchy manager: obj" << endl;
5494                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
5495        }
5496
5497        return hierarchyManager;
5498}
5499
5500
5501VspOspViewCellsManager::~VspOspViewCellsManager()
5502{
5503        DEL_PTR(mHierarchyManager);
5504}
5505
5506
5507float VspOspViewCellsManager::GetProbability(ViewCell *viewCell)
5508{
5509        return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
5510}
5511
5512
5513void VspOspViewCellsManager::CollectViewCells()
5514{
5515        // view cells tree constructed
5516        if (!ViewCellsTreeConstructed())
5517        {
5518                mHierarchyManager->GetVspTree()->CollectViewCells(mViewCells, false);
5519        }
5520        else
5521        {       // we can use the view cells tree hierarchy to get the right set
5522                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
5523        }
5524}
5525
5526
5527bool VspOspViewCellsManager::ViewCellsConstructed() const
5528{
5529        return mHierarchyManager->GetVspTree()->GetRoot() != NULL;
5530}
5531
5532
5533ViewCell *VspOspViewCellsManager::GenerateViewCell(Mesh *mesh) const
5534{
5535        return new VspViewCell(mesh);
5536}
5537
5538
5539int VspOspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
5540                                                                                                 const VssRayContainer &rays)
5541{
5542        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
5543
5544        // skip rest if view cells were already constructed
5545        if (ViewCellsConstructed())
5546                return 0;
5547
5548        int sampleContributions = 0;
5549        VssRayContainer sampleRays;
5550
5551        int limit = min (mInitialSamples, (int)rays.size());
5552
5553        VssRayContainer constructionRays;
5554        VssRayContainer savedRays;
5555
5556        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
5557                  << ", actual rays: " << (int)rays.size() << endl;
5558
5559        GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
5560
5561        Debug << "initial rays used for construction: " << (int)constructionRays.size() << endl;
5562        Debug << "saved rays: " << (int)savedRays.size() << endl;
5563
5564        mHierarchyManager->Construct(constructionRays, objects, &mViewSpaceBox);
5565
5566#if TEST_EVALUATION
5567        VssRayContainer::const_iterator tit, tit_end = constructionRays.end();
5568        for (tit = constructionRays.begin(); tit != tit_end; ++ tit)
5569        {
5570                storedRays.push_back(new VssRay(*(*tit)));
5571        }
5572#endif
5573
5574        /////////////////////////
5575        //-- print satistics for subdivision and view cells
5576
5577        Debug << endl << endl << *mHierarchyManager << endl;
5578
5579        ResetViewCells();
5580        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
5581
5582        //////////////
5583        //-- recast rest of rays
5584       
5585        const long startTime = GetTime();
5586        cout << "Computing remaining ray contributions ... ";
5587
5588        if (SAMPLE_AFTER_SUBDIVISION)
5589                ComputeSampleContributions(savedRays, true, false);
5590
5591        Debug << "finished computing remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
5592                  << " secs" << endl;
5593
5594        if (0)
5595        {       
5596                // real meshes are constructed at this stage
5597                cout << "finalizing view cells ... ";
5598        FinalizeViewCells(true);
5599                cout << "finished" << endl;
5600        }
5601
5602        return sampleContributions;
5603}
5604
5605
5606int VspOspViewCellsManager::PostProcess(const ObjectContainer &objects,
5607                                                                                const VssRayContainer &rays)
5608{
5609        if (!ViewCellsConstructed())
5610        {
5611                Debug << "post process error: no view cells constructed" << endl;
5612                return 0;
5613        }
5614
5615        // if view cells were already constructed before post processing step
5616        // (e.g., because they were loaded), we are finished
5617        if (mViewCellsFinished)
5618        {
5619                FinalizeViewCells(true);
5620                EvaluateViewCellsStats();
5621
5622                return 0;
5623        }
5624
5625        // check if new view cells turned invalid
5626        int minPvs, maxPvs;
5627
5628        if (0)
5629        {
5630                minPvs = mMinPvsSize;
5631                maxPvs = mMaxPvsSize;
5632        }
5633        else
5634        {
5635                // problem matt: why did I start here from zero?
5636                minPvs = 0;
5637                maxPvs = mMaxPvsSize;
5638        }
5639
5640        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5641        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5642       
5643        SetValidity(minPvs, maxPvs);
5644
5645       
5646        // area is not up to date, has to be recomputed
5647        mTotalAreaValid = false;
5648        VssRayContainer postProcessRays;
5649        GetRaySets(rays, mPostProcessSamples, postProcessRays);
5650
5651        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
5652
5653
5654        // compute tree by merging the nodes of the spatial hierarchy
5655        ViewCell *root = ConstructSpatialMergeTree(mHierarchyManager->GetVspTree()->GetRoot());
5656        mViewCellsTree->SetRoot(root);
5657
5658        //////////////////////////
5659        //-- update pvs up to the root of the hierarchy
5660
5661        ObjectPvs pvs;
5662        UpdatePvsForEvaluation(root, pvs);
5663
5664
5665        //////////////////////
5666        //-- render simulation after merge + refine
5667
5668        cout << "\nview cells partition render time before compress" << endl << endl;
5669        dynamic_cast<RenderSimulator *>(mRenderer)->RenderScene();
5670        SimulationStatistics ss;
5671        dynamic_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
5672        cout << ss << endl;
5673       
5674
5675        mHierarchyManager->CreateUniqueObjectIds();
5676
5677        ///////////
5678        //-- compression
5679
5680        if (0) CompressViewCells();
5681
5682        /////////////
5683        //-- some tasks still to do on the view cells:
5684        //-- Compute meshes from view cell geometry, evaluate volume and / or area
5685
5686        if (1) FinalizeViewCells(true);
5687
5688        return 0;
5689}
5690
5691
5692int VspOspViewCellsManager::GetType() const
5693{
5694        return VSP_OSP;
5695}
5696
5697
5698ViewCell *VspOspViewCellsManager::ConstructSpatialMergeTree(VspNode *root)
5699{
5700        // terminate recursion
5701        if (root->IsLeaf())
5702        {
5703                VspLeaf *leaf = dynamic_cast<VspLeaf *>(root);
5704                leaf->GetViewCell()->SetMergeCost(0.0f);
5705                return leaf->GetViewCell();
5706        }
5707       
5708        VspInterior *interior = dynamic_cast<VspInterior *>(root);
5709        ViewCellInterior *viewCellInterior = new ViewCellInterior();
5710               
5711        // evaluate merge cost for priority traversal
5712        const float mergeCost = -(float)root->mTimeStamp;
5713        viewCellInterior->SetMergeCost(mergeCost);
5714
5715        float volume = 0;
5716       
5717        VspNode *front = interior->GetFront();
5718        VspNode *back = interior->GetBack();
5719
5720        ObjectPvs frontPvs, backPvs;
5721
5722        /////////
5723        //-- recursivly compute child hierarchies
5724
5725        ViewCell *backVc = ConstructSpatialMergeTree(back);
5726        ViewCell *frontVc = ConstructSpatialMergeTree(front);
5727
5728        viewCellInterior->SetupChildLink(backVc);
5729        viewCellInterior->SetupChildLink(frontVc);
5730
5731        volume += backVc->GetVolume();
5732        volume += frontVc->GetVolume();
5733
5734        viewCellInterior->SetVolume(volume);
5735
5736        return viewCellInterior;
5737}
5738
5739
5740bool VspOspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
5741{
5742        if (!ViewCellsConstructed())
5743                return ViewCellsManager::GetViewPoint(viewPoint);
5744
5745        // TODO: set reasonable limit
5746        const int limit = 20;
5747
5748        for (int i = 0; i < limit; ++ i)
5749        {
5750                viewPoint = mViewSpaceBox.GetRandomPoint();
5751
5752                if (mHierarchyManager->GetVspTree()->ViewPointValid(viewPoint))
5753                {
5754                        return true;
5755                }
5756        }
5757
5758        Debug << "failed to find valid view point, taking " << viewPoint << endl;
5759        return false;
5760}
5761
5762
5763void VspOspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
5764                                                                                                        ViewCell *vc,
5765                                                                                                        const AxisAlignedBox3 *sceneBox,
5766                                                                                                        const AxisAlignedPlane *clipPlane
5767                                                                                                        ) const
5768{
5769        ViewCellContainer leaves;
5770        mViewCellsTree->CollectLeaves(vc, leaves);
5771        ViewCellContainer::const_iterator it, it_end = leaves.end();
5772
5773        Plane3 plane;
5774        if (clipPlane)
5775        {
5776                // arbitrary plane definition
5777                plane = clipPlane->GetPlane();
5778        }
5779
5780        for (it = leaves.begin(); it != it_end; ++ it)
5781        {
5782                VspViewCell *vspVc = dynamic_cast<VspViewCell *>(*it);
5783                VspLeaf *l = vspVc->mLeaves[0];
5784
5785                const AxisAlignedBox3 box =
5786                        mHierarchyManager->GetVspTree()->GetBoundingBox(vspVc->mLeaves[0]);
5787               
5788                if (sceneBox && !Overlap(*sceneBox, box))
5789                        continue;
5790
5791                if (clipPlane)
5792                {
5793                        if (box.Side(plane) == -1)
5794                        {
5795                                exporter->ExportBox(box);
5796                        }
5797                        else if (box.Side(plane) == 0)
5798                        {
5799                                // intersection
5800                                AxisAlignedBox3 fbox, bbox;
5801                                box.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
5802                                exporter->ExportBox(bbox);
5803                        }
5804                }
5805                else
5806                {
5807                        exporter->ExportBox(box);
5808                }
5809        }
5810}
5811
5812
5813bool VspOspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
5814{
5815  // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
5816  // validy update in preprocessor for all managers)
5817  return ViewCellsManager::ViewPointValid(viewPoint);
5818
5819  //    return mViewSpaceBox.IsInside(viewPoint) &&
5820  //               mVspTree->ViewPointValid(viewPoint);
5821}
5822
5823
5824float VspOspViewCellsManager::UpdateObjectCosts()
5825{
5826        float maxRenderCost = 0;
5827
5828        cout << "updating object pvs cost ... ";
5829        const long startTime = GetTime();
5830
5831        ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
5832
5833        Intersectable::NewMail();
5834
5835        const float invViewSpaceVol = 1.0f / GetViewSpaceBox().GetVolume();
5836
5837        for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
5838        {
5839                ViewCell *vc = *vit;
5840
5841                ObjectPvsIterator pit = vc->GetPvs().GetIterator();
5842
5843                // output PVS of view cell
5844                while (pit.HasMoreEntries())
5845                {               
5846                        ObjectPvsEntry entry = pit.Next();
5847                               
5848                        BvhNode *node = dynamic_cast<BvhNode *>(entry.mObject);
5849                       
5850                        // hack!!
5851                        if (!node->IsLeaf())
5852                        {
5853                                cout << "error, can only do leaves" << endl;
5854                                return 0;
5855                        }
5856       
5857                        if (!node->Mailed())
5858                        {
5859                                node->Mail();
5860                                node->mRenderCost = 0;
5861                        }
5862
5863                        const float rc = (float)((BvhLeaf *)node)->mObjects.size();
5864
5865                        node->mRenderCost += rc * vc->GetVolume() * invViewSpaceVol;
5866
5867                        if (node->mRenderCost > maxRenderCost)
5868                                maxRenderCost = node->mRenderCost;
5869                }
5870        }
5871
5872        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
5873
5874        return maxRenderCost;
5875}
5876
5877
5878void VspOspViewCellsManager::Visualize(const ObjectContainer &objects,
5879                                                                           const VssRayContainer &sampleRays)
5880{
5881        if (!ViewCellsConstructed())
5882                return;
5883
5884        VssRayContainer visRays;
5885        GetRaySets(sampleRays, mVisualizationSamples, visRays);
5886
5887        ////////////
5888        //-- export final view cells
5889
5890        Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
5891
5892        //Vector3 scale(0.9f, 0.9f, 0.9f);
5893        Vector3 scale(1.0f, 1.0f, 1.0f);
5894
5895        if (exporter)
5896        {
5897                if (CLAMP_TO_BOX)
5898                {       
5899                        exporter->mClampToBox = true;   
5900                }
5901
5902                EvaluateViewCellsStats();
5903
5904                const long starttime = GetTime();
5905                cout << "exporting final view cells (after initial construction + post process) ... " << endl;
5906
5907                // matt: hack for clamping scene
5908                AxisAlignedBox3 bbox = mViewSpaceBox;
5909                bbox.Scale(scale);
5910
5911                if (1 && mExportRays)
5912                {       
5913                        exporter->ExportRays(visRays, RgbColor(0, 1, 0));
5914                }
5915
5916                // hack color code (show pvs size)
5917                const int savedColorCode = mColorCode;
5918
5919                const float maxRenderCost = UpdateObjectCosts();
5920                cout << "maxRenderCost: " << maxRenderCost << endl;
5921                mColorCode = 0; // 0 = random, 1 = export pvs
5922
5923                if (0)
5924                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects,
5925                                                                                                          CLAMP_TO_BOX ? &bbox : NULL, maxRenderCost, false);
5926               
5927
5928                //ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, mColorCode, GetClipPlane());
5929                ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
5930
5931                delete exporter;
5932
5933                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
5934                mColorCode = savedColorCode;
5935        }
5936
5937        exporter = Exporter::GetExporter("final_object_partition.wrl");
5938
5939        if (exporter)
5940        {
5941                if (CLAMP_TO_BOX)
5942                {       
5943                        exporter->mClampToBox = true;   
5944                }
5945
5946                EvaluateViewCellsStats();
5947
5948                const long starttime = GetTime();
5949                cout << "exporting final objects (after initial construction + post process) ... ";
5950
5951                // matt: hack for clamping scene
5952                AxisAlignedBox3 bbox = mViewSpaceBox;
5953                bbox.Scale(scale);
5954
5955                // hack color code (show pvs size)
5956                const int savedColorCode = mColorCode;
5957
5958                mColorCode = 1; // 0 = random, 1 = export pvs
5959                const float maxRenderCost = -1;
5960
5961                if (0)
5962                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects,
5963                                                                                                          CLAMP_TO_BOX ? &bbox : NULL, maxRenderCost, false);
5964               
5965
5966                //ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, mColorCode, GetClipPlane());
5967                ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
5968
5969                delete exporter;
5970
5971                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
5972                mColorCode = savedColorCode;
5973        }
5974
5975        // visualization of the merged view cells
5976    if (0)
5977        {       
5978                ExportMergedViewCells(objects);
5979        }
5980
5981        // export some view cells
5982        int leafOut;
5983        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
5984
5985        const bool sortViewCells = false;
5986        const bool exportPvs = true;
5987        const bool exportRays = true;
5988        const int raysOut = 100;
5989
5990        ExportSingleViewCells(objects,
5991                                                  leafOut,
5992                                                  sortViewCells,
5993                                                  exportPvs,
5994                                                  exportRays,
5995                                                  raysOut,
5996                                                  "");
5997}
5998
5999
6000void VspOspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
6001                                                                                                   const int maxViewCells,
6002                                                                                                   const bool sortViewCells,
6003                                                                                                   const bool exportPvs,
6004                                                                                                   const bool exportRays,
6005                                                                                                   const int maxRays,
6006                                                                                                   const string prefix,
6007                                                                                                   VssRayContainer *visRays)
6008{
6009        if (sortViewCells)
6010        {
6011                // sort view cells to visualize the view cells with highest render cost
6012                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
6013        }
6014
6015        ViewCell::NewMail();
6016        const int limit = min(maxViewCells, (int)mViewCells.size());
6017       
6018        cout << "\nExporting " << limit << " single view cells: " << endl;
6019       
6020        for (int i = 0; i < limit; ++ i)
6021        {
6022                cout << "creating output for view cell " << i << " ... ";
6023               
6024                // largest view cell pvs first of random view cell
6025                ViewCell *vc = sortViewCells ?
6026                        mViewCells[i] : mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
6027               
6028                if (vc->Mailed()) // view cell already processed
6029                        continue;
6030
6031                vc->Mail();
6032
6033                ObjectPvs pvs;
6034                mViewCellsTree->GetPvs(vc, pvs);
6035
6036                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
6037                Exporter *exporter = Exporter::GetExporter(s);
6038               
6039                cout << "view cell " << vc->GetId() << ": pvs cost=" << mViewCellsTree->GetPvsCost(vc) << endl;
6040
6041                if (exportPvs)
6042                {
6043                        Material m;
6044
6045                        Intersectable::NewMail();
6046                       
6047                        ObjectPvsIterator pit = pvs.GetIterator();
6048
6049                        // output PVS of view cell
6050                        while (pit.HasMoreEntries())
6051                        {               
6052                                ObjectPvsEntry entry = pit.Next();
6053                               
6054                                Intersectable *intersect = entry.mObject;
6055
6056                                if (!intersect->Mailed())
6057                                {
6058                                        m = RandomMaterial();
6059                                        exporter->SetForcedMaterial(m);
6060
6061                                        exporter->ExportIntersectable(intersect);
6062                                        intersect->Mail();
6063                                }
6064                        }
6065                }
6066
6067                if (exportRays)
6068                {
6069                        ////////////
6070                        //-- export the sample rays
6071
6072                        // output rays stored with the view cells during subdivision
6073                        VssRayContainer vcRays;
6074                        VssRayContainer collectRays;
6075
6076                        // collect intial view cells
6077                        ViewCellContainer leaves;
6078                        mViewCellsTree->CollectLeaves(vc, leaves);
6079
6080                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
6081
6082                        for (vit = leaves.begin(); vit != vit_end; ++ vit)
6083                        {
6084                                VspLeaf *vcLeaf = dynamic_cast<VspViewCell *>(*vit)->mLeaves[0];
6085                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
6086
6087                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
6088                                {
6089                                        collectRays.push_back(*rit);
6090                                }
6091                        }
6092
6093                        const int raysOut = min((int)collectRays.size(), maxRays);
6094
6095                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
6096
6097                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
6098                        {
6099                                const float p = RandomValue(0.0f, (float)collectRays.size());
6100
6101                                if (p < raysOut)
6102                                        vcRays.push_back(*rit);
6103                        }
6104
6105                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
6106                }
6107               
6108       
6109                /////////////////
6110                //-- export view cell geometry
6111
6112                exporter->SetWireframe();
6113
6114                Material m;
6115                m.mDiffuseColor = RgbColor(0, 1, 0);
6116                exporter->SetForcedMaterial(m);
6117
6118                ExportViewCellGeometry(exporter, vc, NULL, NULL);
6119                exporter->SetFilled();
6120
6121                DEL_PTR(exporter);
6122                cout << "finished" << endl;
6123        }
6124
6125        cout << endl;
6126}
6127
6128
6129int VspOspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
6130                                                                                                        ViewCellContainer &viewCells) const
6131{
6132        return mHierarchyManager->GetVspTree()->ComputeBoxIntersections(box, viewCells);
6133}
6134
6135
6136int VspOspViewCellsManager::CastLineSegment(const Vector3 &origin,
6137                                                                                        const Vector3 &termination,
6138                                                                                        ViewCellContainer &viewcells)
6139{
6140        return mHierarchyManager->
6141                GetVspTree()->CastLineSegment(origin, termination, viewcells);
6142}
6143
6144
6145bool VspOspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
6146                                                                                                   const Vector3 &termination,
6147                                                                                                   ViewCell *viewCell)
6148{
6149        return mHierarchyManager->
6150                GetVspTree()->LineSegmentIntersects(origin, termination, viewCell);
6151}
6152
6153
6154bool VspOspViewCellsManager::ExportViewCells(const string filename,
6155                                                                                         const bool exportPvs,
6156                                                                                         const ObjectContainer &objects)
6157{
6158        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
6159                return false;
6160
6161        const long starttime = GetTime();
6162        cout << "exporting view cells to xml ... ";
6163       
6164        OUT_STREAM stream(filename.c_str());
6165
6166        // for output we need unique ids for each view cell
6167        CreateUniqueViewCellIds();
6168
6169        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
6170        stream << "<VisibilitySolution>" << endl;
6171
6172        // §§ tmp matt: for storage cost
6173        if (0 && exportPvs)
6174        {
6175        ///////////////
6176                //-- export bounding boxes
6177                //-- The bounding boxes are used to identify
6178                //-- the objects in the rendering engine
6179                mHierarchyManager->ExportBoundingBoxes(stream, objects);
6180        }
6181
6182        //////////////////////////
6183        //-- export the view cells and the pvs
6184
6185        const int numViewCells = mCurrentViewCellsStats.viewCells;
6186
6187        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
6188        mViewCellsTree->Export(stream, exportPvs);
6189        stream << "</ViewCells>" << endl;
6190
6191        //////////////////////
6192        //-- export the view space hierarchy
6193       
6194        stream << "<ViewSpaceHierarchy type=\"vsp\""
6195                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
6196                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
6197
6198        mHierarchyManager->GetVspTree()->Export(stream);
6199        stream << "</ViewSpaceHierarchy>" << endl;
6200
6201        ////////////////////// 
6202        //-- export the object space partition
6203       
6204        mHierarchyManager->ExportObjectSpaceHierarchy(stream);
6205       
6206        stream << "</VisibilitySolution>" << endl;
6207        stream.close();
6208       
6209        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
6210        return true;
6211}
6212
6213
6214
6215ViewCell *VspOspViewCellsManager::GetViewCell(const Vector3 &point,
6216                                                                                          const bool active) const
6217{
6218        if (!ViewCellsConstructed())
6219                return NULL;
6220
6221        if (!mViewSpaceBox.IsInside(point))
6222                return NULL;
6223
6224        return mHierarchyManager->GetVspTree()->GetViewCell(point, active);
6225}
6226
6227
6228void VspOspViewCellsManager::CreateMesh(ViewCell *vc)
6229{
6230        // matt: TODO
6231        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
6232
6233        ViewCellContainer leaves;
6234        mViewCellsTree->CollectLeaves(vc, leaves);
6235
6236        ViewCellContainer::const_iterator it, it_end = leaves.end();
6237
6238    for (it = leaves.begin(); it != it_end; ++ it)
6239        {
6240                VspLeaf *leaf = dynamic_cast<VspViewCell *>(*it)->mLeaves[0];
6241                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6242        IncludeBoxInMesh(box, *mesh);
6243        }
6244
6245        vc->SetMesh(mesh);
6246}
6247
6248
6249int VspOspViewCellsManager::CastBeam(Beam &beam)
6250{
6251        // matt: TODO
6252        return 0;
6253}
6254
6255
6256void VspOspViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
6257{
6258        float area = 0;
6259        float volume = 0;
6260
6261        ViewCellContainer leaves;
6262        mViewCellsTree->CollectLeaves(viewCell, leaves);
6263
6264        ViewCellContainer::const_iterator it, it_end = leaves.end();
6265
6266    for (it = leaves.begin(); it != it_end; ++ it)
6267        {
6268                VspLeaf *leaf = dynamic_cast<VspViewCell *>(*it)->mLeaves[0];
6269               
6270                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6271
6272                const float lVol = box.GetVolume();
6273                const float lArea = box.SurfaceArea();
6274
6275                area += lArea;
6276                volume += lVol;
6277
6278        CreateMesh(*it);
6279        }
6280
6281        viewCell->SetVolume(volume);
6282        viewCell->SetArea(area);
6283}
6284
6285
6286void VspOspViewCellsManager::PrepareLoadedViewCells()
6287{
6288        // TODO
6289}
6290
6291
6292static void PrintCompressionStats(HierarchyManager *hm, const int pvsEntries)
6293{
6294        float mem = (float)pvsEntries * ObjectPvs::GetEntrySize();
6295               
6296        float fullmem = mem +
6297                        (hm->GetVspTree()->GetStatistics().Leaves() * 16 +
6298                         hm->mBvHierarchy->GetStatistics().Leaves() * 16) / float(1024 * 1024);
6299
6300        cout << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6301        Debug << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6302}
6303
6304
6305void VspOspViewCellsManager::CompressViewCells()
6306{
6307        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
6308                return;
6309
6310        ////////////
6311        //-- compression
6312
6313        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6314
6315        cout << "before compression: " << endl;
6316        Debug << "before compression: " << endl;
6317       
6318        PrintCompressionStats(mHierarchyManager, pvsEntries);
6319
6320        if (mCompressObjects)
6321        {
6322                cout << "compressing in the objects: " << endl;
6323                Debug << "compressing in the objects: " << endl;
6324
6325                pvsEntries = mHierarchyManager->CompressObjectSpace();
6326        }
6327        else
6328        {
6329                cout << "compressing in the view space: " << endl;
6330                Debug << "compressing in the view space: " << endl;
6331
6332                mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
6333                pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6334        }
6335
6336        PrintCompressionStats(mHierarchyManager, pvsEntries);
6337}
6338
6339
6340ViewCellsManager *VspOspViewCellsManager::LoadViewCells(const string &filename,
6341                                                                                                                ObjectContainer *objects,
6342                                                                                                                const bool finalizeViewCells,
6343                                                                                                                BoundingBoxConverter *bconverter)
6344                                                                                                 
6345{
6346        ViewCellsManager *vm =
6347                ViewCellsManager::LoadViewCells(filename, objects, finalizeViewCells, bconverter);
6348#if 0
6349        // insert scene objects in tree
6350        mOspTree->InsertObjects(mOspTree->GetRoot(), *objects);
6351#endif
6352        return vm;
6353}
6354
6355
6356void
6357VspOspViewCellsManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
6358{
6359  mHierarchyManager->CollectObjects(box, objects);
6360}
6361
6362
6363#if 1
6364
6365void VspOspViewCellsManager::EvalViewCellPartition()
6366{
6367        int samplesPerPass;
6368        int numSamples;
6369        int castSamples = 0;
6370        int oldSamples = 0;
6371        int samplesForStats;
6372        char statsPrefix[100];
6373        char suffix[100];
6374        int splitsStepSize;
6375
6376        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
6377        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
6378        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
6379        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
6380        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.stepSize", splitsStepSize);
6381       
6382        bool useHisto;
6383        int histoMem;
6384
6385        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6386        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoMem", histoMem);
6387
6388        Debug << "step size: " << splitsStepSize << endl;
6389        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
6390        Debug << "view cell evaluation samples: " << numSamples << endl;
6391        Debug << "view cell stats prefix: " << statsPrefix << endl;
6392
6393    cout << "reseting pvs ... ";
6394               
6395        // reset pvs and start over from zero
6396        mViewCellsTree->ResetPvs();
6397       
6398        cout << "finished" << endl;
6399    cout << "Evaluating view cell partition ... " << endl;
6400
6401        vector<int> evalStrats;
6402
6403        // mix of sampling strategies
6404        if (0)
6405        {
6406                evalStrats.push_back(SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION);
6407        }
6408        else
6409        {
6410                /*evalStrats.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
6411                evalStrats.push_back(SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION);
6412                evalStrats.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
6413                */
6414                evalStrats.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
6415        }
6416                       
6417    Debug << "casting eval strategies: ";
6418        for (int i = 0; i < (int)evalStrats.size(); ++ i)
6419                Debug << evalStrats[i] << " ";
6420        Debug << endl;
6421
6422        cout << "casting eval strategies: ";
6423        for (int i = 0; i < (int)evalStrats.size(); ++ i)
6424                cout << evalStrats[i] << " ";
6425        cout << endl;
6426
6427        int pass = 0;
6428
6429        while (castSamples < numSamples)
6430        {               
6431                ///////////////
6432                //-- we have to use uniform sampling strategy for construction rays
6433
6434                VssRayContainer evaluationSamples;
6435                const int samplingType = mEvaluationSamplingType;
6436
6437                long startTime = GetTime();
6438
6439                cout << "casting " << samplesPerPass << " samples ... ";
6440                Debug << "casting " << samplesPerPass << " samples ... ";
6441       
6442                if (1)
6443                {
6444                        CastPassSamples(samplesPerPass, evalStrats, evaluationSamples);
6445                }
6446                else
6447                {
6448                        // use mixed distributions
6449                        CastPassSamples2(samplesPerPass, evaluationSamples);
6450                }
6451
6452                castSamples += samplesPerPass;
6453
6454                Real timeDiff = TimeDiff(startTime, GetTime());
6455               
6456                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6457                cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
6458               
6459                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6460                Debug << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
6461
6462                startTime = GetTime();
6463
6464                ComputeSampleContributions(evaluationSamples, true, false);
6465
6466                timeDiff = TimeDiff(startTime, GetTime());
6467                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6468                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6469
6470                if ((castSamples >= samplesForStats + oldSamples) ||
6471                        (castSamples >= numSamples))
6472                {
6473                        oldSamples += samplesForStats;
6474
6475                        ///////////
6476                        //-- output stats
6477
6478                        sprintf(suffix, "-%09d-eval.log", castSamples);
6479                        const string filename = string(statsPrefix) + string(suffix);
6480
6481                        startTime = GetTime();
6482                       
6483                        cout << "compute new statistics ... " << endl;
6484
6485                        ofstream ofstr(filename.c_str());
6486                        mHierarchyManager->EvaluateSubdivision2(ofstr, splitsStepSize, false, useHisto, histoMem, pass);
6487
6488                        timeDiff = TimeDiff(startTime, GetTime());
6489                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6490                        cout << "*************************************" << endl;
6491
6492                        Debug << "statistics computed in " << timeDiff * 1e-3 << " secs" << endl;
6493
6494#if 0
6495                        //////////////
6496                        // filtered stats
6497
6498                        sprintf(suffix, "-%09d-eval-filter.log", castSamples);
6499                        const string filename2 = string(statsPrefix) + string(suffix);
6500
6501                        startTime = GetTime();
6502                       
6503                        cout << "compute new statistics for filtered pvs ... " << endl;
6504
6505                        ofstream ofstr2(filename2.c_str());
6506                        mHierarchyManager->EvaluateSubdivision2(ofstr2, splitsStepSize, true);
6507
6508                        timeDiff = TimeDiff(startTime, GetTime());
6509                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6510                        cout << "*************************************" << endl;
6511                        Debug << "filtered statistics computed in " << timeDiff * 1e-3 << " secs" << endl;
6512#endif
6513
6514                        // only for debugging purpose
6515                        if (0)
6516                        {
6517                                ViewCellContainer viewCells;
6518                                mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), viewCells);
6519
6520                                ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
6521                                int pvsSize = 0;
6522
6523                                for (vit = viewCells.begin(); vit != vit_end; ++ vit)
6524                                {
6525                                        pvsSize += (*vit)->GetPvs().GetSize();
6526                                }
6527
6528                                cout << "debug entries: " << pvsSize << ", memcost: "
6529                                         << (float)pvsSize * ObjectPvs::GetEntrySize() << endl;
6530                        }
6531                        ++ pass;
6532                }
6533
6534                disposeRays(evaluationSamples, NULL);
6535        }
6536
6537        ////////////
6538        //-- histogram
6539#if 1
6540        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
6541        int histoStepSize;
6542
6543        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6544        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
6545
6546        if (useHisto)
6547        {
6548                // evaluate view cells in a histogram           
6549                char str[64];
6550
6551                // hack: just show final view cells
6552                int pass = (int)mViewCells.size();
6553                //for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
6554                if (1)
6555                {
6556                        string filename;
6557
6558                        cout << "computing histogram for " << pass << " view cells" << endl;
6559
6560                        //////////////////////////////////////////
6561            //-- evaluate histogram for pvs size
6562
6563                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
6564
6565                        sprintf(str, "-%09d-histo-pvs2.log", pass);
6566                        filename = string(statsPrefix) + string(str);
6567
6568                        EvalViewCellHistogramForPvsSize(filename, pass);
6569                }
6570        }
6571#endif
6572}
6573
6574#endif
6575
6576
6577
6578}
Note: See TracBrowser for help on using the repository browser.