source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCell.cpp @ 586

Revision 586, 39.0 KB checked in by mattausch, 18 years ago (diff)

changed shuffling (but does not work yet...)

Line 
1#include "ViewCell.h"
2#include "Mesh.h"
3#include "Intersectable.h"
4#include "MeshKdTree.h"
5#include "Triangle3.h"
6#include "common.h"
7#include "Environment.h"
8#include "ViewCellsManager.h"
9#include "Exporter.h"
10
11#include <time.h>
12#include <iomanip>
13#include <stack>
14
15
16
17template <typename T> class myless
18{
19public:
20       
21        //bool operator() (HierarchyNode *v1, HierarchyNode *v2) const
22        bool operator() (T v1, T v2) const
23        {
24                return (v1->GetTimeStamp() < v2->GetTimeStamp());
25        }
26};
27
28
29typedef priority_queue<ViewCell *, vector<ViewCell *>, myless<vector<ViewCell *>::value_type> > TraversalQueue;
30
31int ViewCell::sMailId = 21843194198;
32int ViewCell::sReservedMailboxes = 1;
33
34//int upperPvsLimit = 120;
35//int lowerPvsLimit = 5;
36
37float MergeCandidate::sRenderCostWeight = 0;
38
39
40// pvs penalty can be different from pvs size
41inline float EvalPvsPenalty(const int pvs,
42                                                        const int lower,
43                                                        const int upper)
44{
45        // clamp to minmax values
46        if (pvs < lower)
47                return (float)lower;
48        if (pvs > upper)
49                return (float)upper;
50
51        return (float)pvs;
52}
53
54
55
56
57inline int CountDiffPvs(ViewCell *vc)
58{
59        int count = 0;
60
61        ObjectPvsMap::const_iterator it, it_end = vc->GetPvs().mEntries.end();
62        for (it = vc->GetPvs().mEntries.begin(); it != it_end; ++ it)
63        {
64                if (!(*it).first->Mailed())
65                {
66                        (*it).first->Mail();
67                        ++ count;
68                }
69        }
70
71        return count;
72}
73
74
75int ComputeMergedPvsSize(const ObjectPvs &pvs1, const ObjectPvs &pvs2)
76{
77        int pvs = pvs1.GetSize();
78
79        // compute new pvs size
80        ObjectPvsMap::const_iterator it, it_end =  pvs1.mEntries.end();
81
82        Intersectable::NewMail();
83
84        for (it = pvs1.mEntries.begin(); it != it_end; ++ it)
85        {
86                (*it).first->Mail();
87        }
88
89        it_end = pvs2.mEntries.end();
90
91        for (it = pvs2.mEntries.begin(); it != it_end; ++ it)
92        {
93                Intersectable *obj = (*it).first;
94                if (!obj->Mailed())
95                        ++ pvs;
96        }
97
98        return pvs;
99}
100
101
102ViewCell::ViewCell():
103MeshInstance(NULL),
104mPiercingRays(0),
105mArea(-1),
106mVolume(-1),
107mValid(true),
108mParent(NULL),
109mTimeStamp(0)
110{
111}
112
113ViewCell::ViewCell(Mesh *mesh):
114MeshInstance(mesh),
115mPiercingRays(0),
116mArea(-1),
117mVolume(-1),
118mValid(true),
119mParent(NULL),
120mTimeStamp(0)
121{
122}
123
124
125const ObjectPvs &ViewCell::GetPvs() const
126{
127        return mPvs;
128}
129
130ObjectPvs &ViewCell::GetPvs()
131{
132        return mPvs;
133}
134
135
136int ViewCell::Type() const
137{
138        return VIEW_CELL;
139}
140
141
142float ViewCell::GetVolume() const
143{
144        return mVolume;
145}
146
147
148void ViewCell::SetVolume(float volume)
149{
150        mVolume = volume;
151}
152
153
154void ViewCell::SetMesh(Mesh *mesh)
155{
156        mMesh = mesh;
157}
158
159
160void ViewCell::UpdateViewCellsStats(ViewCellsStatistics &vcStat)
161{
162        ++ vcStat.viewCells;
163               
164        const int pvsSize = mPvs.GetSize();
165
166        vcStat.pvs += pvsSize;
167
168        if (pvsSize == 0)
169                ++ vcStat.emptyPvs;
170
171        if (pvsSize > vcStat.maxPvs)
172                vcStat.maxPvs = pvsSize;
173
174        if (pvsSize < vcStat.minPvs)
175                vcStat.minPvs = pvsSize;
176
177        if (!mValid)
178                ++ vcStat.invalid;
179}
180
181
182float ViewCell::GetArea() const
183{
184        return mArea;
185}
186
187
188void ViewCell::SetArea(float area)
189{
190        mArea = area;
191}
192
193
194void ViewCell::SetValid(const bool valid)
195{
196        mValid = valid;
197}
198
199
200bool ViewCell::GetValid() const
201{
202        return mValid;
203}
204
205
206/*bool ViewCell::IsLeaf() const
207{
208        return true;
209}*/
210
211
212void ViewCell::SetParent(ViewCellInterior *parent)
213{
214        mParent = parent;
215}
216
217
218bool ViewCell::IsRoot() const
219{
220        return !mParent;
221}
222
223
224ViewCellInterior *ViewCell::GetParent() const
225{
226        return mParent;
227}
228
229
230void ViewCell::SetTimeStamp(const int timeStamp)
231{
232        mTimeStamp = timeStamp;
233}
234
235
236int ViewCell::GetTimeStamp() const
237{
238        return mTimeStamp;
239}
240
241
242
243/************************************************************************/
244/*                class ViewCellInterior implementation                 */
245/************************************************************************/
246
247
248ViewCellInterior::ViewCellInterior()
249{
250}
251
252
253ViewCellInterior::~ViewCellInterior()
254{
255        ViewCellContainer::const_iterator it, it_end = mChildren.end();
256
257        for (it = mChildren.begin(); it != it_end; ++ it)
258                delete (*it);
259}
260
261
262ViewCellInterior::ViewCellInterior(Mesh *mesh):
263ViewCell(mesh)
264{
265}
266
267
268bool ViewCellInterior::IsLeaf() const
269{
270        return false;
271}
272
273
274void ViewCellInterior::SetupChildLink(ViewCell *l)
275{
276    mChildren.push_back(l);
277    l->mParent = this;
278}
279
280
281void ViewCellInterior::RemoveChildLink(ViewCell *l)
282{
283        // erase leaf from old view cell
284        ViewCellContainer::iterator it = mChildren.begin();
285
286        for (; (*it) != l; ++ it);
287        if (it == mChildren.end())
288                Debug << "error" << endl;
289        else
290                mChildren.erase(it);
291}
292
293/************************************************************************/
294/*                class ViewCellsStatistics implementation              */
295/************************************************************************/
296
297
298
299
300void ViewCellsStatistics::Print(ostream &app) const
301{
302        app << "=========== View Cells Statistics ===============\n";
303
304        app << setprecision(4);
305
306        //app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
307
308        app << "#N_OVERALLPVS ( objects in PVS )\n" << pvs << endl;
309
310        app << "#N_PMAXPVS ( largest PVS )\n" << maxPvs << endl;
311
312        app << "#N_PMINPVS ( smallest PVS )\n" << minPvs << endl;
313
314        app << "#N_PAVGPVS ( average PVS )\n" << AvgPvs() << endl;
315
316        app << "#N_PEMPTYPVS ( view cells with empty PVS )\n" << emptyPvs << endl;
317
318        app << "#N_VIEWCELLS ( number of view cells)\n" << viewCells << endl;
319
320        app << "#N_AVGLEAVES (average number of leaves per view cell )\n" << AvgLeaves() << endl;
321
322        app << "#N_MAXLEAVES ( maximal number of leaves per view cell )\n" << maxLeaves << endl;
323       
324        app << "#N_INVALID ( number of invalid view cells )\n" << invalid << endl;
325
326        app << "========== End of View Cells Statistics ==========\n";
327}
328
329
330/*************************************************************************/
331/*                    class ViewCellsTree implementation                 */
332/*************************************************************************/
333
334
335ViewCellsTree::ViewCellsTree(ViewCellsManager *vcm):
336mRoot(NULL),
337mUseAreaForPvs(false),
338mViewCellsManager(vcm),
339mIsCompressed(false)
340{
341        environment->GetBoolValue("ViewCells.Visualization.exportMergedViewCells", mExportMergedViewCells);
342        environment->GetFloatValue("ViewCells.maxStaticMemory", mMaxMemory);
343
344        //-- merge options
345        environment->GetFloatValue("ViewCells.PostProcess.renderCostWeight", mRenderCostWeight);
346        environment->GetIntValue("ViewCells.PostProcess.minViewCells", mMergeMinViewCells);
347        environment->GetFloatValue("ViewCells.PostProcess.maxCostRatio", mMergeMaxCostRatio);
348        environment->GetBoolValue("ViewCells.PostProcess.refine", mRefineViewCells);   
349
350
351        Debug << "========= view cell tree options ================\n";
352        Debug << "minimum view cells: " << mMergeMinViewCells << endl;
353        Debug << "max cost ratio: " << mMergeMaxCostRatio << endl;
354        Debug << "max memory: " << mMaxMemory << endl;
355        Debug << "refining view cells: " << mRefineViewCells << endl;
356
357        MergeCandidate::sRenderCostWeight = mRenderCostWeight;
358
359        mStats.open("mergeStats.log");
360}
361
362
363// return memory usage in MB
364float ViewCellsTree::GetMemUsage() const
365{
366        return 0;
367                /*(sizeof(ViewCellsTree) +
368                 mBspStats.Leaves() * sizeof(BspLeaf) +
369                 mBspStats.Interior() * sizeof(BspInterior) +
370                 mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);*/
371}
372
373
374int ViewCellsTree::GetSize(ViewCell *vc) const
375{
376        int vcSize = 0;
377
378        stack<ViewCell *> tstack;
379
380        tstack.push(vc);
381
382        while (!tstack.empty())
383        {
384                ViewCell *vc = tstack.top();
385                tstack.pop();
386
387                if (vc->IsLeaf())
388                {
389                        ++ vcSize;
390                }
391                else
392                {
393                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
394                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
395                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
396                                tstack.push(*it);
397                       
398                }
399        }
400
401        return vcSize;
402}
403
404
405void ViewCellsTree::CollectLeaves(ViewCell *vc, ViewCellContainer &leaves) const
406{
407        stack<ViewCell *> tstack;
408
409        tstack.push(vc);
410
411        while (!tstack.empty())
412        {
413                ViewCell *vc = tstack.top();
414                tstack.pop();
415
416                if (vc->IsLeaf())
417                {
418                        leaves.push_back(vc);
419                }
420                else
421                {
422                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
423                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
424                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
425                                tstack.push(*it);
426                       
427                }
428        }
429}
430
431
432ViewCellsTree::~ViewCellsTree()
433{
434        DEL_PTR(mRoot);
435}
436
437
438int ViewCellsTree::ConstructMergeTree(const VssRayContainer &rays,
439                                                                          const ObjectContainer &objects)
440{
441        mNumActiveViewCells = (int)mViewCellsManager->GetViewCells().size();
442
443        float variance = 0;
444        int totalPvs = 0;
445        float totalCost = 0;
446
447        //-- compute statistics values of initial view cells
448        mViewCellsManager->EvaluateRenderStatistics(totalCost,
449                                                                                                mExpectedCost,
450                                                                                                mDeviation,
451                                                                                                variance,
452                                                                                                totalPvs,
453                                                                                                mAvgRenderCost);
454
455
456        //-- fill merge queue
457        vector<MergeCandidate> candidates;
458
459        mViewCellsManager->CollectMergeCandidates(rays, candidates);
460        while(!candidates.empty())
461        {
462                MergeCandidate mc = candidates.back();
463                candidates.pop_back();
464                EvalMergeCost(mc);
465                mMergeQueue.push(mc);
466        }
467
468        Debug << "************************* merge ***********************************" << endl; 
469        Debug << "deviation: " << mDeviation << endl;
470        Debug << "avg render cost: " << mAvgRenderCost << endl;
471        Debug << "expected cost: " <<mExpectedCost << endl;
472
473
474        ViewCellsManager::PvsStatistics pvsStats;
475        mViewCellsManager->GetPvsStatistics(pvsStats);
476
477        static float expectedValue = pvsStats.avgPvs;
478       
479        // the current view cells are kept in this container
480        // we start with the current view cells from the
481        // view cell manager. They will change with
482        // subsequent merges
483        ViewCellContainer &activeViewCells = mViewCellsManager->GetViewCells();
484
485
486        ViewCell::NewMail();
487
488        MergeStatistics mergeStats;
489        mergeStats.Start();
490       
491        long startTime = GetTime();
492
493        mergeStats.collectTime = TimeDiff(startTime, GetTime());
494        mergeStats.candidates = (int)mMergeQueue.size();
495        startTime = GetTime();
496
497        // frequency stats are updated
498        const int statsOut = 100;
499
500        // passes are needed for statistics, because we don't want to record
501        // every merge
502        int pass = 0;
503        int mergedPerPass = 0;
504        float realExpectedCost = mExpectedCost;
505        float realAvgRenderCost = mAvgRenderCost;
506        int realNumActiveViewCells = mNumActiveViewCells;
507       
508        // maximal ratio of old expected render cost to expected render
509        // when the the render queue has to be reset.
510        float avgCostMaxDeviation;
511        int maxMergesPerPass;
512        int numMergedViewCells = 0;
513
514        environment->GetIntValue("ViewCells.PostProcess.maxMergesPerPass", maxMergesPerPass);
515        environment->GetFloatValue("ViewCells.PostProcess.avgCostMaxDeviation", avgCostMaxDeviation);
516
517        cout << "actual merge starts now ... " << endl;
518       
519
520        //-- use priority queue to merge leaf pairs
521
522        while (!mMergeQueue.empty())// && (realNumActiveViewCells > mMergeMinViewCells))
523        {
524                //-- reset merge queue if the ratio of current expected cost / real expected cost
525                //   too small or after a given number of merges
526                if ((mergedPerPass > maxMergesPerPass) ||
527                        (avgCostMaxDeviation > mAvgRenderCost / realAvgRenderCost))
528                {
529                        Debug << "************ reset queue *****************\n"
530                                  << "ratios: " << avgCostMaxDeviation
531                                  << " real avg render cost " << realAvgRenderCost << " average render cost " << mAvgRenderCost
532                                  << " merged per pass : " << mergedPerPass << " of maximal " << maxMergesPerPass << endl;
533
534                        Debug << "Values before reset: " 
535                                  << " erc: " << mExpectedCost
536                                  << " avgrc: " << mAvgRenderCost
537                                  << " dev: " << mDeviation << endl;
538       
539                        // adjust render cost
540                        ++ pass;
541
542                        mergedPerPass = 0;
543                        mExpectedCost = realExpectedCost;
544                        mAvgRenderCost = realAvgRenderCost;
545                        mNumActiveViewCells = realNumActiveViewCells;
546                       
547                        const int numMergedViewCells = UpdateActiveViewCells(activeViewCells);
548               
549                        // refines the view cells
550                        // then priorities are recomputed
551                        // and the candidates are put back into merge queue
552                        if (mRefineViewCells)
553                                RefineViewCells(rays, objects);
554                        else
555                                ResetMergeQueue();
556
557                       
558                        Debug << "Values after reset: " 
559                                  << " erc: " << mExpectedCost
560                                  << " avg: " << mAvgRenderCost
561                                  << " dev: " << mDeviation << endl;
562
563                        if (mExportMergedViewCells)
564                        {
565                                ExportMergedViewCells(activeViewCells, objects, numMergedViewCells);
566                        }
567                }
568
569#ifdef _DEBUG
570                Debug << "abs mergecost: " << mMergeQueue.top().GetMergeCost() <<
571                          << " rel mergecost: " << mMergeQueue.top().GetRenderCost() / mExpectedCost <<
572                          << " max ratio: " << mMergeMaxCostRatio << endl
573                          << " expected value: " << realExpectedCost << endl;
574#endif
575
576       
577                MergeCandidate mc = mMergeQueue.top();
578                mMergeQueue.pop();
579       
580                // both view cells equal
581                // NOTE: do I really still need this? probably cannot happen!!
582                if (mc.mLeftViewCell == mc.mRightViewCell)
583                        continue;
584
585                if (mc.IsValid())
586                {
587                        ViewCell::NewMail();
588                                               
589                        -- realNumActiveViewCells;
590                        ++ mergeStats.merged;
591                        ++ mergedPerPass;
592
593
594                        //-- update statistical values
595
596                        // total render cost and deviation has changed
597                        // real expected cost will be larger than expected cost used for the
598                        // cost heuristics, but cannot recompute costs on each increase of the
599                        // expected cost
600
601                        totalCost += mc.GetRenderCost();
602                        mDeviation += mc.GetDeviationIncr();
603                                               
604                        realExpectedCost = totalCost / (float)realNumActiveViewCells;
605                       
606                        const float currentMergeCost = mc.GetMergeCost();
607
608                        // merge the view cells of leaf1 and leaf2
609                        int pvsDiff;
610                        ViewCellInterior *mergedVc =
611                                MergeViewCells(mc.mLeftViewCell, mc.mRightViewCell, pvsDiff);
612
613                        totalPvs += pvsDiff;
614
615                        // set timestamp
616                        mergedVc->SetTimeStamp(mergeStats.merged);
617
618                        realAvgRenderCost = (float)totalPvs / (float)realNumActiveViewCells;
619#if VC_HISTORY
620                        if (mc.mLeftViewCell->IsSibling(mc.mRightViewCell))
621                                ++ mergeStats.siblings;
622#endif
623                        if (((mergeStats.merged % statsOut) == 0) ||
624                                (realNumActiveViewCells == mMergeMinViewCells))
625                        {
626                                cout << "merged " << mergeStats.merged << " view cells" << endl;
627
628                                mStats
629                                        << "#Pass\n" << pass << endl
630                                        << "#Merged\n" << mergeStats.merged << endl
631                                        << "#Viewcells\n" << realNumActiveViewCells << endl
632                                        << "#CurrentCost\n" << currentMergeCost << endl
633                                        << "#RelativeCost\n" << currentMergeCost / mOverallCost << endl
634                                        << "#CurrentPvs\n" << mc.GetLeftViewCell()->GetPvs().GetSize() << endl
635                                        << "#MergedSiblings\n" << mergeStats.siblings << endl
636                                        << "#AvgTreeDist\n" << mergeStats.AvgTreeDist() << endl
637                                        << "#UsedExpectedCost\n" << mExpectedCost << endl
638                                        << "#RealExpectedCost\n" << realExpectedCost << endl
639                                        << "#RealAvgRenderCost\n" << realAvgRenderCost << endl
640                                        << "#AvgRenderCost\n" << mAvgRenderCost << endl
641                                        << "#expectedCostRatio\n" << mExpectedCost / realExpectedCost << endl
642                                        << "#Deviation\n" << mDeviation / (float)realNumActiveViewCells << endl
643                                        << "#TotalDeviation\n" << mDeviation<< endl;
644                        }
645                }
646                else
647                {
648                        // merge candidate not valid, because one of the leaves was already
649                        // merged with another one => validate and reinsert into queue
650                        if (ValidateMergeCandidate(mc))
651                        {
652                                EvalMergeCost(mc);
653                                mMergeQueue.push(mc);
654                        }
655                }
656        }
657
658        // adjust stats and reset queue one final time
659        mExpectedCost = realExpectedCost;
660        mAvgRenderCost = realAvgRenderCost;
661        mNumActiveViewCells = realNumActiveViewCells;
662
663        UpdateActiveViewCells(activeViewCells);
664
665        // refine view cells and reset costs
666        if (mRefineViewCells)
667                RefineViewCells(rays, objects);
668        else
669                ResetMergeQueue();
670
671        // create a root node if the merge was not done till root level,
672        // else take the single node as new root
673        if ((int)activeViewCells.size() > 1)
674        {
675                Debug << "creating root of view cell hierarchy for " << (int)activeViewCells.size() << " view cells" << endl;
676                /*for (int i = 0;  i < activeViewCells.size(); ++ i){
677                        Debug << "parent " << activeViewCells[i]->GetParent() << endl;
678                        Debug << "viewcell " << activeViewCells[i] << endl;*/
679                }
680                ViewCellInterior *root = mViewCellsManager->MergeViewCells(activeViewCells);
681
682                root->SetTimeStamp(mergeStats.merged + 1);
683                mRoot = root;
684        }
685        else if ((int)activeViewCells.size() == 1)
686        {
687                Debug << "setting root of the merge history" << endl;
688                mRoot = activeViewCells[0];
689        }
690
691        // TODO delete because makes no sense here
692        mergeStats.expectedRenderCost = realExpectedCost;
693        mergeStats.deviation = mDeviation;
694
695        // we want to optimize this heuristics
696        mergeStats.heuristics =
697                mDeviation * (1.0f - mRenderCostWeight) +
698                mExpectedCost * mRenderCostWeight;
699
700        mergeStats.mergeTime = TimeDiff(startTime, GetTime());
701        mergeStats.Stop();
702
703        Debug << mergeStats << endl << endl;
704
705
706        //TODO: should return sample contributions?
707        return mergeStats.merged;
708}
709
710
711ViewCell *ViewCellsTree::GetRoot() const
712{
713        return mRoot;
714}
715
716
717void ViewCellsTree::ResetMergeQueue()
718{
719        cout << "reset merge queue ... ";
720       
721        vector<MergeCandidate> buf;
722        buf.reserve(mMergeQueue.size());
723                       
724       
725        // store merge candidates in intermediate buffer
726        while (!mMergeQueue.empty())
727        {
728                MergeCandidate mc = mMergeQueue.top();
729                mMergeQueue.pop();
730               
731                // recalculate cost
732                if (ValidateMergeCandidate(mc))
733                {
734                        EvalMergeCost(mc);
735                        buf.push_back(mc);                             
736                }
737        }
738
739        vector<MergeCandidate>::const_iterator bit, bit_end = buf.end();
740
741        // reinsert back into queue
742        for (bit = buf.begin(); bit != bit_end; ++ bit)
743        {     
744                mMergeQueue.push(*bit);
745        }
746
747        cout << "finished" << endl;
748}
749
750
751int ViewCellsTree::UpdateActiveViewCells(ViewCellContainer &viewCells)
752{
753        int numMergedViewCells = 0;
754
755        Debug << "updating active vc: " << (int)viewCells.size() << endl;
756        // find all already merged view cells and remove them from view cells
757               
758        // sort out all view cells which are not active anymore, i.e., they
759        // were already part of a merge
760        int i = 0;
761
762        ViewCell::NewMail();
763
764        while (1)
765        {
766                // remove all merged view cells from end of the vector
767                while (!viewCells.empty() && (viewCells.back()->GetParent()))
768                {
769                        viewCells.pop_back();
770                }
771
772                // all merged view cells have been found
773                if (i >= viewCells.size())
774                        break;
775
776                // already merged view cell, put it to end of vector
777                if (viewCells[i]->GetParent())
778                        swap(viewCells[i], viewCells.back());
779               
780                viewCells[i ++]->Mail();
781        }
782
783
784        // add new view cells to container only if they don't have been
785        // merged in the mean time
786        ViewCellContainer::const_iterator ait, ait_end = mMergedViewCells.end();
787        for (ait = mMergedViewCells.begin(); ait != ait_end; ++ ait)
788        {
789                ViewCell *vc = mMergedViewCells.back();
790                if (!vc->GetParent() && !vc->Mailed())
791                {
792                        vc->Mail();
793                        viewCells.push_back(vc);
794                        ++ numMergedViewCells;
795                }
796        }
797
798        mMergedViewCells.clear();
799
800        // update standard deviation
801        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
802       
803        mDeviation = 0;
804
805        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
806        {
807                int lower = mViewCellsManager->GetMinPvsSize();
808                int upper = mViewCellsManager->GetMaxPvsSize();
809                float penalty = EvalPvsPenalty((*vit)->GetPvs().GetSize(), lower, upper);
810               
811                mDeviation += fabs(mAvgRenderCost - penalty);
812        }
813
814        mDeviation /= (float)viewCells.size();
815       
816        return numMergedViewCells;
817}
818
819
820void ViewCellsTree::ExportMergedViewCells(ViewCellContainer &viewCells,
821                                                                                  const ObjectContainer &objects,
822                                                                                  const int numMergedViewCells)
823{
824       
825
826        char s[64];
827
828        sprintf(s, "merged_viewcells%07d.x3d", (int)viewCells.size());
829        Exporter *exporter = Exporter::GetExporter(s);
830
831        if (exporter)
832        {
833                cout << "exporting " << (int)viewCells.size() << " merged view cells ... ";
834                exporter->ExportGeometry(objects);
835                //Debug << "vc size " << (int)viewCells.size() << " merge queue size: " << (int)mMergeQueue.size() << endl;
836                ViewCellContainer::const_iterator it, it_end = viewCells.end();
837
838                int i = 0;
839                for (it = viewCells.begin(); it != it_end; ++ it)
840                {
841                        Material m;
842                        // assign special material to new view cells
843                        // new view cells are on the back of container
844                        if (i ++ >= (viewCells.size() - numMergedViewCells))
845                        {
846                                //m = RandomMaterial();
847                                m.mDiffuseColor.r = RandomValue(0.5f, 1.0f);
848                                m.mDiffuseColor.g = RandomValue(0.5f, 1.0f);
849                                m.mDiffuseColor.b = RandomValue(0.5f, 1.0f);
850                        }
851                        else
852                        {
853                                float col = RandomValue(0.1f, 0.4f);
854                                m.mDiffuseColor.r = col;
855                                m.mDiffuseColor.g = col;
856                                m.mDiffuseColor.b = col;
857                        }
858
859                        exporter->SetForcedMaterial(m);
860                        mViewCellsManager->ExportViewCellGeometry(exporter, *it);
861                }
862                delete exporter;
863                cout << "finished" << endl;
864        }
865}
866
867
868// TODO: should be done in view cells manager
869ViewCellInterior *ViewCellsTree::MergeViewCells(ViewCell *l,
870                                                                                                ViewCell *r,
871                                                                                                int &pvsDiff) //const
872{
873        ViewCellInterior *vc = mViewCellsManager->MergeViewCells(l, r);
874
875        // if merge was unsuccessful
876        if (!vc) return NULL;
877
878        // set new size of view cell
879        if (mUseAreaForPvs)
880                vc->SetArea(l->GetArea() + l->GetArea());
881        else
882                vc->SetVolume(r->GetVolume() + r->GetVolume());
883       
884        // important so other merge candidates sharing this view cell
885        // are notified that the merge cost must be updated!!
886        vc->Mail();
887
888        const int pvs1 = l->GetPvs().GetSize();
889        const int pvs2 = r->GetPvs().GetSize();
890
891
892        // new view cells are stored in this vector
893        mMergedViewCells.push_back(vc);
894
895        pvsDiff = vc->GetPvs().GetSize() - pvs1 - pvs2;
896
897        return vc;
898}
899
900
901
902int ViewCellsTree::RefineViewCells(const VssRayContainer &rays,
903                                                                   const ObjectContainer &objects)
904{
905        Debug << "refining " << (int)mMergeQueue.size() << " candidates " << endl;
906
907        // intermediate buffer for shuffled view cells
908        vector<MergeCandidate> buf;
909        buf.reserve(mMergeQueue.size());
910                       
911        // Use priority queue of remaining leaf pairs
912        // The candidates either share the same view cells or
913        // are border leaves which share a boundary.
914        // We test if they can be shuffled, i.e.,
915        // either one leaf is made part of one view cell or the other
916        // leaf is made part of the other view cell. It is tested if the
917        // remaining view cells are "better" than the old ones.
918       
919        const int numPasses = 3;
920        int pass = 0;
921        int passShuffled = 0;
922        int shuffled = 0;
923        int shuffledViewCells = 0;
924
925        ViewCell::NewMail();
926       
927        while (!mMergeQueue.empty())
928        {
929                MergeCandidate mc = mMergeQueue.top();
930                mMergeQueue.pop();
931
932                // both view cells equal or already shuffled
933                if ((mc.GetLeftViewCell() == mc.GetRightViewCell()) ||
934                        mc.GetLeftViewCell()->IsLeaf() || mc.GetRightViewCell()->IsLeaf())
935                {                       
936                        continue;
937                }
938
939                // candidate for shuffling
940                const bool wasShuffled = ShuffleLeaves(mc);
941               
942                // shuffled or put into other queue for further refine
943                if (wasShuffled)
944                {
945                        ++ passShuffled;
946
947                        if (!mc.GetLeftViewCell()->Mailed())
948                        {
949                                mc.GetLeftViewCell()->Mail();
950                                ++ shuffledViewCells;
951                        }
952                        if (!mc.GetRightViewCell()->Mailed())
953                        {
954                                mc.GetRightViewCell()->Mail();
955                                ++ shuffledViewCells;
956                        }
957                }
958
959                // put back into intermediate vector
960                buf.push_back(mc);
961        }
962
963
964        //-- in the end, the candidates must be in the mergequeue again
965        //   with the correct cost
966
967        cout << "reset merge queue ... ";
968       
969       
970        vector<MergeCandidate>::const_iterator bit, bit_end = buf.end();
971       
972        for (bit = buf.begin(); bit != bit_end; ++ bit)
973        {   
974                MergeCandidate mc = *bit;
975                // recalculate cost
976                if (ValidateMergeCandidate(mc))
977                {
978                        EvalMergeCost(mc);
979                        mMergeQueue.push(mc);   
980                }
981        }
982
983        cout << "finished" << endl;
984
985        return shuffledViewCells;
986}
987
988
989
990
991inline int AddedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
992{
993        return pvs1.AddPvs(pvs2);
994}
995
996
997// recomputes pvs size minus pvs of leaf l
998#if 0
999inline int SubtractedPvsSize(BspViewCell *vc, BspLeaf *l, const ObjectPvs &pvs2)
1000{
1001        ObjectPvs pvs;
1002        vector<BspLeaf *>::const_iterator it, it_end = vc->mLeaves.end();
1003        for (it = vc->mLeaves.begin(); it != vc->mLeaves.end(); ++ it)
1004                if (*it != l)
1005                        pvs.AddPvs(*(*it)->mPvs);
1006        return pvs.GetSize();
1007}
1008#endif
1009
1010
1011// computes pvs1 minus pvs2
1012inline int SubtractedPvsSize(ObjectPvs pvs1, const ObjectPvs &pvs2)
1013{
1014        return pvs1.SubtractPvs(pvs2);
1015}
1016
1017
1018float ViewCellsTree::EvalShuffleCost(ViewCell *leaf,
1019                                                                         ViewCellInterior *vc1,
1020                                                                         ViewCellInterior *vc2) const
1021{
1022        //const int pvs1 = SubtractedPvsSize(vc1, leaf, *leaf->mPvs);
1023        const int pvs1 = SubtractedPvsSize(vc1->GetPvs(), leaf->GetPvs());
1024        const int pvs2 = AddedPvsSize(vc2->GetPvs(), leaf->GetPvs());
1025
1026        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1027        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1028
1029        const float pvsPenalty1 =
1030                EvalPvsPenalty(pvs1, lowerPvsLimit, upperPvsLimit);
1031
1032        const float pvsPenalty2 =
1033                EvalPvsPenalty(pvs2, lowerPvsLimit, upperPvsLimit);
1034
1035
1036        // don't shuffle leaves with pvs > max
1037        if (0 && (pvs1 + pvs2 > mViewCellsManager->GetMaxPvsSize()))
1038        {
1039                return 1e20f;
1040        }
1041
1042        float p1, p2;
1043
1044    if (mUseAreaForPvs)
1045        {
1046                p1 = vc1->GetArea() - leaf->GetArea();
1047                p2 = vc2->GetArea() + leaf->GetArea();
1048        }
1049        else
1050        {
1051                p1 = vc1->GetVolume() - leaf->GetVolume();
1052                p2 = vc2->GetVolume() + leaf->GetVolume();
1053        }
1054
1055        const float renderCost1 = pvsPenalty1 * p1;
1056        const float renderCost2 = pvsPenalty2 * p2;
1057
1058        float dev1, dev2;
1059
1060        if (1)
1061        {
1062                dev1 = fabs(mAvgRenderCost - pvsPenalty1);
1063                dev2 = fabs(mAvgRenderCost - pvsPenalty2);
1064        }
1065        else
1066        {
1067                dev1 = fabs(mExpectedCost - renderCost1);
1068                dev2 = fabs(mExpectedCost - renderCost2);
1069        }
1070       
1071        return mRenderCostWeight * (renderCost1 + renderCost2) +
1072                  (1.0f - mRenderCostWeight) * (dev1 + dev2) / (float)mNumActiveViewCells;
1073}
1074
1075
1076void ViewCellsTree::ShuffleLeaf(ViewCell *leaf,
1077                                                                ViewCellInterior *vc1,
1078                                                                ViewCellInterior *vc2) const
1079{
1080        // compute new pvs and area
1081        // TODO change
1082        vc1->GetPvs().SubtractPvs(leaf->GetPvs());
1083        vc2->GetPvs().AddPvs(leaf->GetPvs());
1084       
1085        if (mUseAreaForPvs)
1086        {
1087                vc1->SetArea(vc1->GetArea() - leaf->GetArea());
1088                vc2->SetArea(vc2->GetArea() + leaf->GetArea());
1089        }
1090        else
1091        {
1092                vc1->SetVolume(vc1->GetVolume() - leaf->GetVolume());
1093                vc2->SetVolume(vc2->GetVolume() + leaf->GetVolume());
1094        }
1095
1096       
1097        ViewCellInterior *p = dynamic_cast<ViewCellInterior *>(leaf->GetParent());
1098
1099        p->RemoveChildLink(leaf);
1100        vc2->SetupChildLink(leaf);
1101}
1102
1103
1104bool ViewCellsTree::ShuffleLeaves(MergeCandidate &mc) const
1105{
1106        float cost1, cost2;
1107
1108        ViewCellInterior *vc1 = dynamic_cast<ViewCellInterior *>(mc.GetLeftViewCell());
1109        ViewCellInterior *vc2 = dynamic_cast<ViewCellInterior *>(mc.GetRightViewCell());
1110
1111        ViewCell *leaf1 = mc.GetInitialLeftViewCell();
1112        ViewCell *leaf2 = mc.GetInitialRightViewCell();
1113
1114        //-- first test if shuffling would decrease cost
1115        cost1 = GetCostHeuristics(vc1);
1116        cost2 = GetCostHeuristics(vc2);
1117
1118        const float oldCost = cost1 + cost2;
1119       
1120        float shuffledCost1 = Limits::Infinity;
1121        float shuffledCost2 = Limits::Infinity;
1122
1123        if (leaf1)
1124                shuffledCost1 = EvalShuffleCost(leaf1, vc1, vc2);       
1125        if (leaf2)
1126                shuffledCost2 = EvalShuffleCost(leaf2, vc2, vc1);
1127
1128        // if cost of shuffle is less than old cost => shuffle
1129        if ((oldCost <= shuffledCost1) && (oldCost <= shuffledCost2))
1130                return false;
1131       
1132        if (shuffledCost1 < shuffledCost2)
1133        {
1134                if (leaf1)
1135                        ShuffleLeaf(leaf1, vc1, vc2);
1136                mc.mInitialLeftViewCell = NULL;
1137        }
1138        else
1139        {
1140                if (leaf2)
1141                        ShuffleLeaf(leaf2, vc2, vc1);
1142                mc.mInitialRightViewCell = NULL;
1143        }
1144
1145        return true;
1146}
1147
1148
1149float ViewCellsTree::GetVariance(ViewCell *vc) const
1150{
1151        const int upper = mViewCellsManager->GetMaxPvsSize();
1152        const int lower = mViewCellsManager->GetMinPvsSize();
1153
1154        if (1)
1155        {
1156                const float penalty = EvalPvsPenalty(vc->GetPvs().GetSize(), lower, upper);
1157                return (mAvgRenderCost - penalty) * (mAvgRenderCost - penalty) / (float)mNumActiveViewCells;
1158        }
1159
1160    const float leafCost = GetRenderCost(vc);
1161        return (mExpectedCost - leafCost) * (mExpectedCost - leafCost);
1162}
1163
1164
1165float ViewCellsTree::GetDeviation(ViewCell *vc) const
1166{
1167        const int upper = mViewCellsManager->GetMaxPvsSize();
1168        const int lower = mViewCellsManager->GetMinPvsSize();
1169
1170        if (1)
1171        {
1172                const float penalty = EvalPvsPenalty(vc->GetPvs().GetSize(), lower, upper);
1173                return fabs(mAvgRenderCost - penalty) / (float)mNumActiveViewCells;
1174        }
1175
1176    const float renderCost = GetRenderCost(vc);
1177        return fabs(mExpectedCost - renderCost);
1178}
1179
1180
1181
1182float ViewCellsTree::GetRenderCost(ViewCell *vc) const
1183{
1184        if (mUseAreaForPvs)
1185                return vc->GetPvs().GetSize() * vc->GetArea();
1186
1187        return vc->GetPvs().GetSize() * vc->GetVolume();
1188}
1189
1190
1191float ViewCellsTree::GetCostHeuristics(ViewCell *vc) const
1192{
1193        return GetRenderCost(vc) * mRenderCostWeight +
1194                   GetDeviation(vc) * (1.0f - mRenderCostWeight);
1195}
1196
1197
1198bool ViewCellsTree::ValidateMergeCandidate(MergeCandidate &mc) const
1199{
1200        while (mc.mLeftViewCell->mParent)
1201        {
1202                mc.mLeftViewCell = mc.mLeftViewCell->mParent;
1203        }
1204
1205        while (mc.mRightViewCell->mParent)
1206        {
1207                mc.mRightViewCell = mc.mRightViewCell->mParent;
1208        }
1209
1210        return mc.mLeftViewCell != mc.mRightViewCell;
1211}
1212
1213
1214void ViewCellsTree::EvalMergeCost(MergeCandidate &mc) const
1215{
1216        //-- compute pvs difference
1217        const int newPvs =
1218                ComputeMergedPvsSize(mc.mLeftViewCell->GetPvs(),
1219                                                         mc.mRightViewCell->GetPvs());
1220                       
1221        const float newPenalty =
1222                EvalPvsPenalty(newPvs,
1223                                           mViewCellsManager->GetMinPvsSize(),
1224                                           mViewCellsManager->GetMaxPvsSize());
1225
1226        ViewCell *vc1 = mc.mLeftViewCell;
1227        ViewCell *vc2 = mc.mRightViewCell;
1228
1229        //-- compute ratio of old cost
1230        //   (i.e., added size of left and right view cell times pvs size)
1231        //   to new rendering cost (i.e, size of merged view cell times pvs size)
1232        const float oldCost = GetRenderCost(vc1) + GetRenderCost(vc2);
1233
1234    const float newCost = mUseAreaForPvs ?
1235                (float)newPenalty * (vc1->GetArea() + vc2->GetArea()) :
1236                (float)newPenalty * (vc1->GetVolume() + vc2->GetVolume());
1237
1238
1239        // strong penalty if pvs size too large
1240        if (0 && (newPvs > mViewCellsManager->GetMaxPvsSize()))
1241        {
1242                mc.mRenderCost = 1e20f;
1243        }
1244        else
1245        {
1246                mc.mRenderCost = (newCost - oldCost) /
1247                        mViewCellsManager->GetViewSpaceBox().GetVolume();
1248        }       
1249       
1250
1251        //-- merge cost also takes deviation into account
1252        float newDev, oldDev;
1253
1254        if (1)
1255                newDev = fabs(mAvgRenderCost - newPenalty) / (float)mNumActiveViewCells;
1256        else
1257                newDev = fabs(mExpectedCost - newCost) / (float)mNumActiveViewCells;
1258       
1259        oldDev = GetDeviation(vc1) + GetDeviation(vc2);
1260
1261        // compute deviation increase
1262        mc.mDeviationIncr = newDev - oldDev;
1263       
1264        //Debug << "render cost: " << mc.mRenderCost * mRenderCostWeight << endl;
1265        //Debug << "standard deviation: " << mc.mDeviationIncr * mRenderCostWeight << endl;
1266}
1267
1268void ViewCellsTree::CompressViewCellsPvs()
1269{
1270        if (!mIsCompressed)
1271        {
1272                mIsCompressed = true;
1273                CompressViewCellsPvs(mRoot);
1274        }
1275}
1276
1277void ViewCellsTree::CompressViewCellsPvs(ViewCell *root)
1278{
1279        if (!root->IsLeaf())
1280        {
1281                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(root);
1282
1283        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1284               
1285                // compress child sets first
1286                for (it = interior->mChildren.begin(); it != it_end; ++ it)
1287                {
1288                        CompressViewCellsPvs(*it);
1289                }
1290
1291                // compress root node
1292                PropagateUpVisibility(interior);
1293        }
1294}
1295
1296
1297void ViewCellsTree::CollectBestViewCellSet(ViewCellContainer &viewCells,
1298                                                                                   const int numViewCells)
1299{
1300        TraversalQueue tqueue;
1301        tqueue.push(mRoot);
1302       
1303        while (!tqueue.empty())
1304        {
1305                ViewCell *vc = tqueue.top();
1306               
1307                // save the view cells if it is a leaf or if enough view cells have already been traversed
1308                // because of the priority queue, this will be the optimal set of v
1309                if (vc->IsLeaf() || ((viewCells.size() + tqueue.size()) >= numViewCells))
1310                {
1311                        viewCells.push_back(vc);
1312                }
1313                else
1314                {       
1315                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1316
1317                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1318
1319                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1320                        {
1321                                tqueue.push(*it);
1322                        }
1323                }
1324
1325                tqueue.pop();
1326        }
1327}
1328       
1329
1330void ViewCellsTree::PropagateUpVisibility(ViewCellInterior *interior)
1331{
1332        Intersectable::NewMail((int)interior->mChildren.size());
1333
1334        ViewCellContainer::const_iterator cit, cit_end = interior->mChildren.end();
1335
1336        ObjectPvsMap::const_iterator oit;
1337
1338        // mail all objects in the leaf sets
1339        // we are interested in the objects which are present in all leaves
1340        // => count how often an object is part of a child set
1341        for (cit = interior->mChildren.begin(); cit != cit_end; ++ cit)
1342        {
1343                ViewCell *vc = *cit;
1344
1345                ObjectPvsMap::const_iterator oit_end = vc->GetPvs().mEntries.end();
1346
1347                for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
1348                {
1349                        Intersectable *obj = (*oit).first;
1350                        if ((cit == interior->mChildren.begin()) && !obj->Mailed())
1351                                obj->Mail();
1352                       
1353                        int incm = obj->IncMail();
1354                }
1355        }
1356
1357        interior->GetPvs().mEntries.clear();
1358       
1359       
1360        // only the objects which are present in all leaf pvs
1361        // should remain in the parent pvs
1362        // these are the objects which have been mailed in all children
1363        for (cit = interior->mChildren.begin(); cit != cit_end; ++ cit)
1364        {
1365                ViewCell *vc = *cit;
1366
1367                ObjectPvsMap::const_iterator oit_end = vc->GetPvs().mEntries.end();
1368
1369                for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
1370                {               
1371                        if ((*oit).first->Mailed((int)interior->mChildren.size()))
1372                        {       
1373                                interior->GetPvs().AddSample((*oit).first, (*oit).second.mSumPdf);
1374                        }
1375                }
1376        }
1377
1378
1379
1380        // delete all the objects from the leaf sets which were moved to parent pvs
1381        ObjectPvsMap::const_iterator oit_end = interior->GetPvs().mEntries.end();
1382
1383        for (oit = interior->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
1384        {
1385                for (cit = interior->mChildren.begin(); cit != cit_end; ++ cit)
1386                {
1387                        if (!(*cit)->GetPvs().RemoveSample((*oit).first, Limits::Infinity))
1388                                Debug << "should not come here!" << endl;
1389                }
1390        }
1391
1392        int dummy = interior->GetPvs().GetSize();
1393
1394        for (cit = interior->mChildren.begin(); cit != cit_end; ++ cit)
1395        {
1396                dummy += (*cit)->GetPvs().GetSize();
1397        }
1398
1399}
1400
1401
1402
1403void ViewCellsTree::GetPvs(ViewCell *vc, ObjectPvs &pvs) const
1404{
1405        Intersectable::NewMail();
1406
1407        if (!mIsCompressed)
1408                pvs = vc->GetPvs();
1409
1410        int pvsSize = 0;
1411        ViewCell *root = vc;
1412       
1413        // also add pvs from this view cell to root
1414        while (root->GetParent())
1415        {
1416                root = root->GetParent();
1417                pvs.AddPvs(root->GetPvs());
1418        }
1419
1420        stack<ViewCell *> tstack;
1421        tstack.push(vc);
1422
1423        while (!tstack.empty())
1424        {
1425                vc = tstack.top();
1426                tstack.pop();
1427
1428                pvs.AddPvs(vc->GetPvs());
1429
1430                if (!vc->IsLeaf())
1431                {
1432                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1433
1434                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1435
1436                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1437                        {
1438                                tstack.push(*it);
1439                        }               
1440                }
1441        }
1442}
1443
1444
1445int ViewCellsTree::GetPvsSize(ViewCell *vc) const
1446{
1447        Intersectable::NewMail();
1448
1449        if (!mIsCompressed)
1450                return vc->GetPvs().GetSize();
1451
1452        int pvsSize = 0;
1453        ViewCell *root = vc;
1454       
1455        // also add pvs from this view cell to root
1456        while (root->GetParent())
1457        {
1458                root = root->GetParent();
1459                pvsSize += CountDiffPvs(root);
1460        }
1461
1462        stack<ViewCell *> tstack;
1463        tstack.push(vc);
1464
1465        Debug << "current size: " << pvsSize << endl;
1466
1467        while (!tstack.empty())
1468        {
1469                vc = tstack.top();
1470                tstack.pop();
1471
1472                pvsSize += CountDiffPvs(vc);
1473
1474                if (!vc->IsLeaf())
1475                {
1476                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1477
1478                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1479
1480                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1481                        {
1482                                tstack.push(*it);
1483                        }               
1484                }
1485        }
1486
1487        return pvsSize; 
1488
1489}
1490
1491
1492float ViewCellsTree::GetMemoryCost(ViewCell *vc) const
1493{
1494        const float entrySize =
1495                sizeof(PvsData<Intersectable *>) + sizeof(Intersectable *);
1496
1497        return (float)GetNumPvsEntries(vc) * entrySize;
1498}
1499
1500
1501int ViewCellsTree::GetNumPvsEntries(ViewCell *vc) const
1502{
1503        int pvsSize = vc->GetPvs().GetSize();
1504
1505        if (!vc->IsLeaf())
1506        {
1507                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1508
1509                ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1510
1511                for (it = interior->mChildren.begin(); it != it_end; ++ it)
1512                {
1513                        pvsSize += GetNumPvsEntries(*it);
1514                }
1515        }
1516
1517        return pvsSize;         
1518}
1519
1520
1521bool ViewCellsTree::IsCompressed() const
1522{
1523        return mIsCompressed;
1524}
1525
1526
1527/**************************************************************************/
1528/*                     MergeCandidate implementation                      */
1529/**************************************************************************/
1530
1531
1532MergeCandidate::MergeCandidate(ViewCell *l, ViewCell *r):
1533mRenderCost(0),
1534mDeviationIncr(0),
1535mLeftViewCell(l),
1536mRightViewCell(r),
1537mInitialLeftViewCell(l),
1538mInitialRightViewCell(r)
1539{
1540        //EvalMergeCost();
1541}
1542
1543
1544void MergeCandidate::SetRightViewCell(ViewCell *v)
1545{
1546        mRightViewCell = v;
1547}
1548
1549
1550void MergeCandidate::SetLeftViewCell(ViewCell *v)
1551{
1552        mLeftViewCell = v;
1553}
1554
1555
1556ViewCell *MergeCandidate::GetRightViewCell() const
1557{
1558        return mRightViewCell;
1559}
1560
1561
1562ViewCell *MergeCandidate::GetLeftViewCell() const
1563{
1564        return mLeftViewCell;
1565}
1566
1567
1568ViewCell *MergeCandidate::GetInitialRightViewCell() const
1569{
1570        return mInitialRightViewCell;
1571}
1572
1573
1574ViewCell *MergeCandidate::GetInitialLeftViewCell() const
1575{
1576        return mInitialLeftViewCell;
1577}
1578
1579
1580bool MergeCandidate::IsValid() const
1581{
1582        return !(mLeftViewCell->mParent || mRightViewCell->mParent);
1583}
1584
1585
1586float MergeCandidate::GetRenderCost() const
1587{
1588        return mRenderCost;
1589}
1590
1591
1592float MergeCandidate::GetDeviationIncr() const
1593{
1594        return mDeviationIncr;
1595}
1596
1597
1598float MergeCandidate::GetMergeCost() const
1599{
1600        return mRenderCost * sRenderCostWeight +
1601                   mDeviationIncr * (1.0f - sRenderCostWeight);
1602}
1603
1604
1605/************************************************************************/
1606/*                    MergeStatistics implementation                    */
1607/************************************************************************/
1608
1609
1610void MergeStatistics::Print(ostream &app) const
1611{
1612        app << "===== Merge statistics ===============\n";
1613
1614        app << setprecision(4);
1615
1616        app << "#N_CTIME ( Overall time [s] )\n" << Time() << " \n";
1617
1618        app << "#N_CCTIME ( Collect candidates time [s] )\n" << collectTime * 1e-3f << " \n";
1619
1620        app << "#N_MTIME ( Merge time [s] )\n" << mergeTime * 1e-3f << " \n";
1621
1622        app << "#N_NODES ( Number of nodes before merge )\n" << nodes << "\n";
1623
1624        app << "#N_CANDIDATES ( Number of merge candidates )\n" << candidates << "\n";
1625
1626        app << "#N_MERGEDSIBLINGS ( Number of merged siblings )\n" << siblings << "\n";
1627
1628        app << "#OVERALLCOST ( overall merge cost )\n" << overallCost << "\n";
1629
1630        app << "#N_MERGEDNODES ( Number of merged nodes )\n" << merged << "\n";
1631
1632        app << "#MAX_TREEDIST ( Maximal distance in tree of merged leaves )\n" << maxTreeDist << "\n";
1633
1634        app << "#AVG_TREEDIST ( Average distance in tree of merged leaves )\n" << AvgTreeDist() << "\n";
1635
1636        app << "#EXPECTEDCOST ( expected render cost )\n" << expectedRenderCost << "\n";
1637
1638        app << "#DEVIATION ( deviation )\n" << deviation << "\n";
1639
1640        app << "#HEURISTICS ( heuristics )\n" << heuristics << "\n";
1641       
1642
1643        app << "===== END OF BspTree statistics ==========\n";
1644}
Note: See TracBrowser for help on using the repository browser.