source: GTP/trunk/Lib/Vis/Preprocessing/src/BvHierarchy.cpp @ 1744

Revision 1744, 66.0 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "BvHierarchy.h"
6#include "ViewCell.h"
7#include "Plane3.h"
8#include "Mesh.h"
9#include "common.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellsManager.h"
17#include "Beam.h"
18#include "VspTree.h"
19#include "HierarchyManager.h"
20
21
22namespace GtpVisibilityPreprocessor {
23
24
25#define PROBABILIY_IS_BV_VOLUME 1
26#define USE_FIXEDPOINT_T 0
27#define USE_VOLUMES_FOR_HEURISTICS 1
28
29int BvhNode::sMailId = 10000; //2147483647;
30int BvhNode::sReservedMailboxes = 1;
31
32BvHierarchy *BvHierarchy::BvhSubdivisionCandidate::sBvHierarchy = NULL;
33
34
35/// sorting operator
36inline static bool ilt(Intersectable *obj1, Intersectable *obj2)
37{
38        return obj1->mId < obj2->mId;
39}
40
41
42/***************************************************************/
43/*              class BvhNode implementation                   */
44/***************************************************************/
45
46BvhNode::BvhNode():
47mParent(NULL),
48mMailbox(0),
49//mRenderCostDecr(0),
50//mMemoryIncr(0),
51//mPvsEntriesIncr(0),
52mTimeStamp(0)
53{
54       
55}
56
57BvhNode::BvhNode(const AxisAlignedBox3 &bbox):
58mParent(NULL),
59mBoundingBox(bbox),
60mMailbox(0),
61//mMemoryIncr(0),
62//mRenderCostDecr(0),
63//mPvsEntriesIncr(0),
64mTimeStamp(0)
65{
66}
67
68
69BvhNode::BvhNode(const AxisAlignedBox3 &bbox, BvhInterior *parent):
70mBoundingBox(bbox),
71mParent(parent),
72mMailbox(0),
73//mMemoryIncr(0),
74//mRenderCostDecr(0),
75//mPvsEntriesIncr(0),
76mTimeStamp(0)
77{
78}
79
80
81bool BvhNode::IsRoot() const
82{
83        return mParent == NULL;
84}
85
86
87BvhInterior *BvhNode::GetParent()
88{
89        return mParent;
90}
91
92
93void BvhNode::SetParent(BvhInterior *parent)
94{
95        mParent = parent;
96}
97
98
99
100/******************************************************************/
101/*              class BvhInterior implementation                  */
102/******************************************************************/
103
104
105BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox):
106BvhNode(bbox),
107mSubdivisionCandidate(NULL)
108{
109        mActiveNode = this;
110}
111
112
113BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox, BvhInterior *parent):
114BvhNode(bbox, parent)
115{
116        mActiveNode = this;
117}
118
119
120BvhLeaf::BvhLeaf(const AxisAlignedBox3 &bbox,
121                                 BvhInterior *parent,
122                                 const int numObjects):
123BvhNode(bbox, parent)
124{
125        mObjects.reserve(numObjects);
126        mActiveNode = this;
127}
128
129
130bool BvhLeaf::IsLeaf() const
131{
132        return true;
133}
134
135
136BvhLeaf::~BvhLeaf()
137{
138}
139
140
141void BvhLeaf::CollectObjects(ObjectContainer &objects)
142{
143        ObjectContainer::const_iterator oit, oit_end = mObjects.end();
144        for (oit = mObjects.begin(); oit != oit_end; ++ oit)
145        {
146                objects.push_back(*oit);
147        }
148}
149
150/******************************************************************/
151/*              class BvhInterior implementation                  */
152/******************************************************************/
153
154
155BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox):
156BvhNode(bbox), mFront(NULL), mBack(NULL)
157{
158}
159
160
161BvhInterior::BvhInterior(const AxisAlignedBox3 &bbox, BvhInterior *parent):
162BvhNode(bbox, parent), mFront(NULL), mBack(NULL)
163{
164}
165
166
167void BvhInterior::ReplaceChildLink(BvhNode *oldChild, BvhNode *newChild)
168{
169        if (mBack == oldChild)
170                mBack = newChild;
171        else
172                mFront = newChild;
173}
174
175
176bool BvhInterior::IsLeaf() const
177{
178        return false;
179}
180
181
182BvhInterior::~BvhInterior()
183{
184        DEL_PTR(mFront);
185        DEL_PTR(mBack);
186}
187
188
189void BvhInterior::SetupChildLinks(BvhNode *front, BvhNode *back)
190{
191    mBack = back;
192    mFront = front;
193}
194
195
196void BvhInterior::CollectObjects(ObjectContainer &objects)
197{
198        mFront->CollectObjects(objects);
199        mBack->CollectObjects(objects);
200}
201
202
203/*******************************************************************/
204/*                  class BvHierarchy implementation               */
205/*******************************************************************/
206
207
208BvHierarchy::BvHierarchy():
209mRoot(NULL),
210mTimeStamp(1)
211{
212        ReadEnvironment();
213        mSubdivisionCandidates = new SortableEntryContainer;
214        for (int i = 0; i < 3; ++ i)
215                mSortedObjects[i] = NULL;
216}
217
218
219BvHierarchy::~BvHierarchy()
220{
221        // delete bvh intersectables
222        BvhIntersectableMap::iterator it, it_end = mBvhIntersectables.end();
223
224        for (it = mBvhIntersectables.begin(); it != mBvhIntersectables.end(); ++ it)
225        {
226                DEL_PTR((*it).second);
227        }
228
229        // delete the local subdivision candidates
230        DEL_PTR(mSubdivisionCandidates);
231
232        // delete the presorted objects
233        for (int i = 0; i < 3; ++ i)
234        {
235                DEL_PTR(mSortedObjects[i]);
236        }
237       
238        // delete the tree
239        DEL_PTR(mRoot);
240}
241
242
243void BvHierarchy::ReadEnvironment()
244{
245        bool randomize = false;
246        Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize);
247         
248        // initialise random generator for heuristics
249        if (randomize)
250                Randomize();
251
252        //////////////////////////////
253        //-- termination criteria for autopartition
254
255        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxDepth", mTermMaxDepth);
256        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.maxLeaves", mTermMaxLeaves);
257        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.minObjects", mTermMinObjects);
258        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.minRays", mTermMinRays);
259        Environment::GetSingleton()->GetFloatValue(
260                "BvHierarchy.Termination.minProbability", mTermMinProbability);
261    Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.missTolerance", mTermMissTolerance);
262
263
264        //////////////////////////////
265        //-- max cost ratio for early tree termination
266
267        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.maxCostRatio", mTermMaxCostRatio);
268        Environment::GetSingleton()->GetFloatValue("BvHierarchy.Termination.minGlobalCostRatio",
269                mTermMinGlobalCostRatio);
270        Environment::GetSingleton()->GetIntValue("BvHierarchy.Termination.globalCostMissTolerance",
271                mTermGlobalCostMissTolerance);
272
273
274        //////////////////////////////
275        //-- factors for subdivision heuristics
276
277        // if only the driving axis is used for splits
278        Environment::GetSingleton()->GetBoolValue("BvHierarchy.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
279        Environment::GetSingleton()->GetFloatValue("BvHierarchy.maxStaticMemory", mMaxMemory);
280        Environment::GetSingleton()->GetBoolValue("BvHierarchy.useCostHeuristics", mUseCostHeuristics);
281        Environment::GetSingleton()->GetBoolValue("BvHierarchy.useSah", mUseSah);
282
283    char subdivisionStatsLog[100];
284        Environment::GetSingleton()->GetStringValue("BvHierarchy.subdivisionStats", subdivisionStatsLog);
285        mSubdivisionStats.open(subdivisionStatsLog);
286
287        Environment::GetSingleton()->GetFloatValue(
288                "BvHierarchy.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
289        Environment::GetSingleton()->GetBoolValue(
290                "BvHierarchy.Construction.useGlobalSorting", mUseGlobalSorting);
291        Environment::GetSingleton()->GetIntValue("BvHierarchy.minRaysForVisibility", mMinRaysForVisibility);
292        Environment::GetSingleton()->GetIntValue("BvHierarchy.maxTests", mMaxTests);
293
294        //mMemoryConst = (float)(sizeof(VspLeaf) + sizeof(VspViewCell));
295        //mMemoryConst = (float)sizeof(BvhLeaf);
296        mMemoryConst = (float)sizeof(ObjectContainer);
297
298        /*cout << "bvh memcost: " << mMemoryConst << endl;
299        cout << "triangle: " << sizeof(TriangleIntersectable) << endl;
300        cout << "triangle: " << sizeof(Intersectable) << endl;
301        cout << "triangle: " << sizeof(ObjectContainer) << endl;
302        cout << "triangle: " << sizeof(float) << endl;
303        cout << "triangle: " << sizeof(int) << endl;
304*/
305    mUseBboxAreaForSah = true;
306
307        /////////////
308        //-- debug output
309
310        Debug << "******* Bvh hierarchy options ******** " << endl;
311    Debug << "max depth: " << mTermMaxDepth << endl;
312        Debug << "min probabiliy: " << mTermMinProbability<< endl;
313        Debug << "min objects: " << mTermMinObjects << endl;
314        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
315        Debug << "miss tolerance: " << mTermMissTolerance << endl;
316        Debug << "max leaves: " << mTermMaxLeaves << endl;
317        Debug << "randomize: " << randomize << endl;
318        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
319        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
320        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
321        Debug << "max memory: " << mMaxMemory << endl;
322        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
323        Debug << "use surface area heuristics: " << mUseSah << endl;
324        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
325        Debug << "split borders: " << mSplitBorder << endl;
326        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
327        Debug << "use global sort: " << mUseGlobalSorting << endl;
328        Debug << "minimal rays for visibility: " << mMinRaysForVisibility << endl;
329        Debug << "bvh mem const: " << mMemoryConst << endl;
330cout << "here10 " << mRenderCostDecreaseWeight << endl;
331        Debug << endl;
332}
333
334
335void BvHierarchy::AssociateObjectsWithLeaf(BvhLeaf *leaf)
336{
337        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
338
339        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
340        {
341                (*oit)->mBvhLeaf = leaf;
342        }
343}
344
345
346static int CountRays(const ObjectContainer &objects)
347{
348        int nRays = 0;
349
350        ObjectContainer::const_iterator oit, oit_end = objects.end();
351
352        for (oit = objects.begin(); oit != oit_end; ++ oit)
353        {
354                nRays += (int)(*oit)->GetOrCreateRays()->size();
355        }
356
357        return nRays;
358}
359                                                                       
360
361BvhInterior *BvHierarchy::SubdivideNode(const BvhSubdivisionCandidate &sc,
362                                                                                BvhTraversalData &frontData,
363                                                                                BvhTraversalData &backData)
364{
365        const BvhTraversalData &tData = sc.mParentData;
366        BvhLeaf *leaf = tData.mNode;
367        AxisAlignedBox3 parentBox = leaf->GetBoundingBox();
368
369        // update stats: we have two new leaves
370        mBvhStats.nodes += 2;
371
372        if (tData.mDepth > mBvhStats.maxDepth)
373        {
374                mBvhStats.maxDepth = tData.mDepth;
375        }
376
377        // add the new nodes to the tree
378        BvhInterior *node = new BvhInterior(parentBox, leaf->GetParent());
379       
380
381        //////////////////
382        //-- create front and back leaf
383
384        AxisAlignedBox3 fbox = EvalBoundingBox(sc.mFrontObjects, &parentBox);
385        AxisAlignedBox3 bbox = EvalBoundingBox(sc.mBackObjects, &parentBox);
386
387        BvhLeaf *back = new BvhLeaf(bbox, node, (int)sc.mBackObjects.size());
388        BvhLeaf *front = new BvhLeaf(fbox, node, (int)sc.mFrontObjects.size());
389
390        BvhInterior *parent = leaf->GetParent();
391
392        // replace a link from node's parent
393        if (parent)
394        {
395                parent->ReplaceChildLink(leaf, node);
396                node->SetParent(parent);
397        }
398        else // no parent => this node is the root
399        {
400                mRoot = node;
401        }
402
403        // and setup child links
404        node->SetupChildLinks(front, back);
405
406        ++ mBvhStats.splits;
407
408
409        ////////////////////////////////////////
410        //-- fill  front and back traversal data with the new values
411
412        frontData.mDepth = backData.mDepth = tData.mDepth + 1;
413
414        frontData.mNode = front;
415        backData.mNode = back;
416
417        back->mObjects = sc.mBackObjects;
418        front->mObjects = sc.mFrontObjects;
419
420        // if the number of rays is too low, no assumptions can be made
421        // (=> switch to surface area heuristics?)
422        frontData.mNumRays = CountRays(sc.mFrontObjects);
423        backData.mNumRays = CountRays(sc.mBackObjects);
424
425        AssociateObjectsWithLeaf(back);
426        AssociateObjectsWithLeaf(front);
427   
428#if PROBABILIY_IS_BV_VOLUME
429        // volume of bvh (= probability that this bvh can be seen)
430        frontData.mProbability = fbox.GetVolume();
431        backData.mProbability = bbox.GetVolume();
432#else
433        // compute probability of this node being visible,
434        // i.e., volume of the view cells that can see this node
435        frontData.mProbability = EvalViewCellsVolume(sc.mFrontObjects);
436        backData.mProbability = EvalViewCellsVolume(sc.mBackObjects);
437#endif
438
439    // how often was max cost ratio missed in this branch?
440        frontData.mMaxCostMisses = sc.GetMaxCostMisses();
441        backData.mMaxCostMisses = sc.GetMaxCostMisses();
442       
443        // set the time stamp so the order of traversal can be reconstructed
444        node->mTimeStamp = mHierarchyManager->mTimeStamp ++;
445               
446        // assign the objects in sorted order
447        if (mUseGlobalSorting)
448        {
449                AssignSortedObjects(sc, frontData, backData);
450        }
451       
452        // return the new interior node
453        return node;
454}
455
456
457BvhNode *BvHierarchy::Subdivide(SplitQueue &tQueue,
458                                                                SubdivisionCandidate *splitCandidate,
459                                                                const bool globalCriteriaMet)
460{
461        BvhSubdivisionCandidate *sc = dynamic_cast<BvhSubdivisionCandidate *>(splitCandidate);
462        BvhTraversalData &tData = sc->mParentData;
463
464        BvhNode *currentNode = tData.mNode;
465
466        if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
467        {       
468                //////////////
469                //-- continue subdivision
470
471                BvhTraversalData tFrontData;
472                BvhTraversalData tBackData;
473                       
474                // create new interior node and two leaf node
475                currentNode = SubdivideNode(*sc, tFrontData, tBackData);
476       
477                // decrease the weighted average cost of the subdivisoin
478                mTotalCost -= sc->GetRenderCostDecrease();
479                mPvsEntries += sc->GetPvsEntriesIncr();
480
481                // subdivision statistics
482                if (1) PrintSubdivisionStats(*sc);
483
484
485                ///////////////////////////
486                //-- push the new split candidates on the queue
487               
488                BvhSubdivisionCandidate *frontCandidate = new BvhSubdivisionCandidate(tFrontData);
489                BvhSubdivisionCandidate *backCandidate = new BvhSubdivisionCandidate(tBackData);
490
491                EvalSubdivisionCandidate(*frontCandidate);
492                EvalSubdivisionCandidate(*backCandidate);
493       
494                // cross reference
495                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
496                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
497
498                //cout << "f: " << frontCandidate->GetPriority() << " b: " << backCandidate->GetPriority() << endl;
499                tQueue.Push(frontCandidate);
500                tQueue.Push(backCandidate);
501        }
502
503        /////////////////////////////////
504        //-- node is a leaf => terminate traversal
505
506        if (currentNode->IsLeaf())
507        {
508                /////////////////////
509                //-- store additional info
510                EvaluateLeafStats(tData);
511       
512                // this leaf is no candidate for splitting anymore
513                // => detach subdivision candidate
514                tData.mNode->SetSubdivisionCandidate(NULL);
515                // detach node so we don't delete it with the traversal data
516                tData.mNode = NULL;
517        }
518       
519        return currentNode;
520}
521
522
523void BvHierarchy::EvalSubdivisionCandidate(BvhSubdivisionCandidate &splitCandidate,
524                                                                                   bool computeSplitPlane)
525{
526        if (computeSplitPlane)
527        {
528                const bool sufficientSamples =
529                        splitCandidate.mParentData.mNumRays > mMinRaysForVisibility;
530
531                const bool useVisibiliyBasedHeuristics =
532                        !mUseSah &&
533                        (mHierarchyManager->GetViewSpaceSubdivisionType() ==
534                        HierarchyManager::KD_BASED_VIEWSPACE_SUBDIV) &&
535                        sufficientSamples;
536
537                // compute best object partition
538                const float ratio =     SelectObjectPartition(splitCandidate.mParentData,
539                                                                                                  splitCandidate.mFrontObjects,
540                                                                                                  splitCandidate.mBackObjects,
541                                                                                                  useVisibiliyBasedHeuristics);
542       
543                // cost ratio violated?
544                const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
545                const int previousMisses = splitCandidate.mParentData.mMaxCostMisses;
546
547                splitCandidate.SetMaxCostMisses(maxCostRatioViolated ? previousMisses + 1 : previousMisses);
548
549        }
550
551        BvhLeaf *leaf = splitCandidate.mParentData.mNode;
552
553        const float oldProp = EvalViewCellsVolume(leaf->mObjects);
554        const float oldRenderCost = EvalRenderCost(leaf->mObjects);
555               
556        // compute global decrease in render cost
557        const float newRenderCost = EvalRenderCost(splitCandidate.mFrontObjects) +
558                                                                EvalRenderCost(splitCandidate.mBackObjects);
559
560        const float renderCostDecr = oldRenderCost - newRenderCost;
561       
562        splitCandidate.SetRenderCostDecrease(renderCostDecr);
563
564        // increase in pvs entries
565        const int pvsEntriesIncr = EvalPvsEntriesIncr(splitCandidate);
566        splitCandidate.SetPvsEntriesIncr(pvsEntriesIncr);
567
568#ifdef GTP_DEBUG
569        Debug << "old render cost: " << oldRenderCost << endl;
570        Debug << "new render cost: " << newRenderCost << endl;
571        Debug << "render cost decrease: " << renderCostDecr << endl;
572#endif
573
574        float priority;
575
576        // surface area heuristics is used when there is no view space subdivision available.
577        // In order to have some prioritized traversal, use this formula instead
578        if (mHierarchyManager->GetViewSpaceSubdivisionType() ==
579                HierarchyManager::NO_VIEWSPACE_SUBDIV)
580        {
581                priority = EvalSahCost(leaf);
582        }
583        else
584        {
585                // take render cost of node into account
586                // otherwise danger of being stuck in a local minimum!
587                const float factor = mRenderCostDecreaseWeight;
588
589                if (1)
590                {
591                        priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
592                        if (mHierarchyManager->mConsiderMemory)
593                        {
594                                priority /= ((float)splitCandidate.GetPvsEntriesIncr() + mMemoryConst);
595                        }
596                }
597                else
598                {
599                        if (!mHierarchyManager->mConsiderMemory)
600                        {
601                                priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
602                        }
603                        else
604                        {
605                                const float ratio =
606                                        renderCostDecr / ((float)splitCandidate.GetPvsEntriesIncr() + mMemoryConst);
607
608                                priority = factor * ratio + (1.0f - factor) * oldRenderCost;
609                        }
610                }
611        }
612
613        //splitCandidate.SetOldCost(oldRenderCost);
614        // compute global decrease in render cost
615        splitCandidate.SetPriority(priority);
616}
617
618
619int BvHierarchy::EvalPvsEntriesIncr(BvhSubdivisionCandidate &splitCandidate) const
620{
621        const int oldPvsSize = CountViewCells(splitCandidate.mParentData.mNode->mObjects);
622       
623        const int fPvsSize = CountViewCells(splitCandidate.mFrontObjects);
624        const int bPvsSize = CountViewCells(splitCandidate.mBackObjects);
625
626        return fPvsSize + bPvsSize - oldPvsSize;
627}
628
629
630inline bool BvHierarchy::LocalTerminationCriteriaMet(const BvhTraversalData &data) const
631{
632        const bool terminationCriteriaMet =
633                        (0
634                        || ((int)data.mNode->mObjects.size() <= 1)//mTermMinObjects)
635                        //|| (data.mProbability <= mTermMinProbability)
636                        //|| (data.mNumRays <= mTermMinRays)
637                 );
638
639#ifdef _DEBUG
640        if (terminationCriteriaMet)
641        {
642                cout << "bvh local termination criteria met:" << endl;
643                cout << "objects: " << data.mNode->mObjects.size() << " " << mTermMinObjects << endl;
644        }
645#endif
646        return terminationCriteriaMet;
647}
648
649
650inline bool BvHierarchy::GlobalTerminationCriteriaMet(const BvhTraversalData &data) const
651{
652        // note: tracking for global cost termination
653        // does not make much sense for interleaved vsp / osp partition
654        // as it is the responsibility of the hierarchy manager
655
656        const bool terminationCriteriaMet =
657                (0
658                || (mBvhStats.Leaves() >= mTermMaxLeaves)
659                //|| (mBvhStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
660                //|| mOutOfMemory
661                );
662
663#ifdef GTP_DEBUG
664        if (terminationCriteriaMet)
665        {
666                Debug << "bvh global termination criteria met:" << endl;
667                Debug << "cost misses: " << mBvhStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
668                Debug << "leaves: " << mBvhStats.Leaves() << " " << mTermMaxLeaves << endl;
669        }
670#endif
671        return terminationCriteriaMet;
672}
673
674
675void BvHierarchy::EvaluateLeafStats(const BvhTraversalData &data)
676{
677        // the node became a leaf -> evaluate stats for leafs
678        BvhLeaf *leaf = data.mNode;
679       
680        ++ mCreatedLeaves;
681
682       
683        if (data.mProbability <= mTermMinProbability)
684        {
685                ++ mBvhStats.minProbabilityNodes;
686        }
687
688        ////////////////////////////////////////////
689        // depth related stuff
690
691        if (data.mDepth < mBvhStats.minDepth)
692        {
693                mBvhStats.minDepth = data.mDepth;
694        }
695
696        if (data.mDepth >= mTermMaxDepth)
697        {
698        ++ mBvhStats.maxDepthNodes;
699        }
700
701        // accumulate depth to compute average depth
702        mBvhStats.accumDepth += data.mDepth;
703
704
705        ////////////////////////////////////////////
706        // objects related stuff
707
708        // note: the sum should alwaysbe total number of objects for bvh
709        mBvhStats.objectRefs += (int)leaf->mObjects.size();
710
711        if ((int)leaf->mObjects.size() <= mTermMinObjects)
712        {
713             ++ mBvhStats.minObjectsNodes;
714        }
715
716        if (leaf->mObjects.empty())
717        {
718                ++ mBvhStats.emptyNodes;
719        }
720
721        if ((int)leaf->mObjects.size() > mBvhStats.maxObjectRefs)
722        {
723                mBvhStats.maxObjectRefs = (int)leaf->mObjects.size();
724        }
725
726        if ((int)leaf->mObjects.size() < mBvhStats.minObjectRefs)
727        {
728                mBvhStats.minObjectRefs = (int)leaf->mObjects.size();
729        }
730
731        ////////////////////////////////////////////
732        // ray related stuff
733
734        // note: this number should always accumulate to the total number of rays
735        mBvhStats.rayRefs += data.mNumRays;
736       
737        if (data.mNumRays <= mTermMinRays)
738        {
739             ++ mBvhStats.minRaysNodes;
740        }
741
742        if (data.mNumRays > mBvhStats.maxRayRefs)
743        {
744                mBvhStats.maxRayRefs = data.mNumRays;
745        }
746
747        if (data.mNumRays < mBvhStats.minRayRefs)
748        {
749                mBvhStats.minRayRefs = data.mNumRays;
750        }
751
752#ifdef _DEBUG
753        cout << "depth: " << data.mDepth << " objects: " << (int)leaf->mObjects.size()
754                 << " rays: " << data.mNumRays << " rays / objects "
755                 << (float)data.mNumRays / (float)leaf->mObjects.size() << endl;
756#endif
757}
758
759
760#if 0
761
762/// compute object boundaries using spatial mid split
763float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
764                                                                                        const int axis,
765                                                                                        ObjectContainer &objectsFront,
766                                                                                        ObjectContainer &objectsBack)
767{
768        const float maxBox = tData.mBoundingBox.Max(axis);
769        const float minBox = tData.mBoundingBox.Min(axis);
770
771        float midPoint = (maxBox + minBox) * 0.5f;
772
773        ObjectContainer::const_iterator oit, oit_end = tData.mNode->mObjects.end();
774       
775        for (oit = tData.mNode->mObjects.begin(); oit != oit_end; ++ oit)
776        {
777                Intersectable *obj = *oit;
778                const AxisAlignedBox3 box = obj->GetBox();
779
780                const float objMid = (box.Max(axis) + box.Min(axis)) * 0.5f;
781
782                // object mailed => belongs to back objects
783                if (objMid < midPoint)
784                {
785                        objectsBack.push_back(obj);
786                }
787                else
788                {
789                        objectsFront.push_back(obj);
790                }
791        }
792
793        const float oldRenderCost = EvalRenderCost(tData.mNode->mObjects);
794        const float newRenderCost = EvalRenderCost(objectsFront) * EvalRenderCost(objectsBack);
795
796        const float ratio = newRenderCost / oldRenderCost;
797        return ratio;
798}
799
800#else
801
802/// compute object partition by getting balanced objects on the left and right side
803float BvHierarchy::EvalLocalObjectPartition(const BvhTraversalData &tData,
804                                                                                        const int axis,
805                                                                                        ObjectContainer &objectsFront,
806                                                                                        ObjectContainer &objectsBack)
807{
808        PrepareLocalSubdivisionCandidates(tData, axis);
809       
810        SortableEntryContainer::const_iterator cit, cit_end = mSubdivisionCandidates->end();
811
812        int i = 0;
813        const int border = (int)tData.mNode->mObjects.size() / 2;
814
815    for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ i)
816        {
817                Intersectable *obj = (*cit).mObject;
818
819                // object mailed => belongs to back objects
820                if (i < border)
821                {
822                        objectsBack.push_back(obj);
823                }
824                else
825                {
826                        objectsFront.push_back(obj);
827                }
828        }
829
830#if 1
831        const float cost = (tData.mNode->GetBoundingBox().Size().DrivingAxis() == axis) ? -1.0f : 0.0f;
832#else
833        const float oldRenderCost = EvalRenderCost(tData.mNode->mObjects);
834        const float newRenderCost = EvalRenderCost(objectsFront) * EvalRenderCost(objectsBack);
835
836        const float cost = newRenderCost / oldRenderCost;
837#endif
838
839        return cost;
840}
841#endif
842
843#if 1
844
845float BvHierarchy::EvalSah(const BvhTraversalData &tData,
846                                                   const int axis,
847                                                   ObjectContainer &objectsFront,
848                                                   ObjectContainer &objectsBack)
849{
850        // go through the lists, count the number of objects left and right
851        // and evaluate the following cost funcion:
852        // C = ct_div_ci  + (ol + or) / queries
853        PrepareLocalSubdivisionCandidates(tData, axis);
854
855        const float totalRenderCost = EvalAbsCost(tData.mNode->mObjects);
856        float objectsLeft = 0, objectsRight = totalRenderCost;
857 
858        const AxisAlignedBox3 nodeBbox = tData.mNode->GetBoundingBox();
859        const float boxArea = nodeBbox.SurfaceArea();
860
861        float minSum = 1e20f;
862 
863        float minBorder = nodeBbox.Max(axis);
864        float maxBorder = nodeBbox.Min(axis);
865
866        float areaLeft = 0, areaRight = 0;
867
868        SortableEntryContainer::const_iterator currentPos =
869                mSubdivisionCandidates->begin();
870       
871        vector<float> bordersRight;
872
873        // we keep track of both borders of the bounding boxes =>
874        // store the events in descending order
875
876        bordersRight.resize(mSubdivisionCandidates->size());
877
878        SortableEntryContainer::reverse_iterator rcit =
879                mSubdivisionCandidates->rbegin(), rcit_end =
880                mSubdivisionCandidates->rend();
881
882        vector<float>::reverse_iterator rbit = bordersRight.rbegin();
883
884        for (; rcit != rcit_end; ++ rcit, ++ rbit)
885        {
886                Intersectable *obj = (*rcit).mObject;
887                const AxisAlignedBox3 obox = obj->GetBox();
888
889                if (obox.Min(axis) < minBorder)
890                {
891                        minBorder = obox.Min(axis);
892                }
893
894                (*rbit) = minBorder;
895        }
896
897        // temporary surface areas
898        float al = 0;
899        float ar = boxArea;
900
901        vector<float>::const_iterator bit = bordersRight.begin();
902        SortableEntryContainer::const_iterator cit, cit_end = mSubdivisionCandidates->end();
903
904        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ bit)
905        {
906                Intersectable *obj = (*cit).mObject;
907
908                const float renderCost = mViewCellsManager->EvalRenderCost(obj);
909               
910                objectsLeft += renderCost;
911                objectsRight -= renderCost;
912
913                const AxisAlignedBox3 obox = obj->GetBox();
914
915                // the borders of the bounding boxes have changed
916                if (obox.Max(axis) > maxBorder)
917                {
918                        maxBorder = obox.Max(axis);
919                }
920
921                minBorder = (*bit);
922
923                AxisAlignedBox3 lbox = nodeBbox;
924                AxisAlignedBox3 rbox = nodeBbox;
925
926                lbox.SetMax(axis, maxBorder);
927                rbox.SetMin(axis, minBorder);
928
929                al = lbox.SurfaceArea();
930                ar = rbox.SurfaceArea();
931
932                const bool noValidSplit = ((objectsLeft <= Limits::Small) || (objectsRight <= Limits::Small));
933                const float sum =  noValidSplit ? 1e25 : objectsLeft * al + objectsRight * ar;
934     
935                /*cout << "pos=" << (*cit).mPos << "\t q=(" << objectsLeft << "," << objectsRight <<")\t r=("
936                         << lbox.SurfaceArea() << "," << rbox.SurfaceArea() << ")" << endl;
937                cout << "minborder: " << minBorder << " maxborder: " << maxBorder << endl;
938            cout << "cost= " << sum << endl;*/
939       
940                if (sum < minSum)
941                {       
942                        minSum = sum;
943                        areaLeft = al;
944                        areaRight = ar;
945
946                        // objects belong to left side now
947                        for (; currentPos != (cit + 1); ++ currentPos);
948                }
949        }
950
951        ////////////
952        //-- assign object to front and back volume
953
954        // belongs to back bv
955        for (cit = mSubdivisionCandidates->begin(); cit != currentPos; ++ cit)
956                objectsBack.push_back((*cit).mObject);
957       
958        // belongs to front bv
959        for (cit = currentPos; cit != cit_end; ++ cit)
960                objectsFront.push_back((*cit).mObject);
961
962        float newCost = minSum / boxArea;
963        float ratio = newCost / totalRenderCost;
964 
965#ifdef GTP_DEBUG
966        cout << "\n\nobjects=(" << (int)objectsBack.size() << "," << (int)objectsFront.size() << " of "
967                 << (int)tData.mNode->mObjects.size() << ")\t area=("
968                 << areaLeft << ", " << areaRight << ", " << boxArea << ")" << endl
969                 << "cost= " << newCost << " oldCost=" << totalRenderCost / boxArea << endl;
970#endif
971
972        return ratio;
973}
974
975#else
976
977float BvHierarchy::EvalSah(const BvhTraversalData &tData,
978                                                   const int axis,
979                                                   ObjectContainer &objectsFront,
980                                                   ObjectContainer &objectsBack)
981{
982        // go through the lists, count the number of objects left and right
983        // and evaluate the following cost funcion:
984        // C = ct_div_ci  + (ol + or) / queries
985        PrepareLocalSubdivisionCandidates(tData, axis);
986
987        const float totalRenderCost = EvalAbsCost(tData.mNode->mObjects);
988        float objectsLeft = 0, objectsRight = totalRenderCost;
989 
990        const AxisAlignedBox3 nodeBbox = tData.mNode->GetBoundingBox();
991
992        const float minBox = nodeBbox.Min(axis);
993        const float maxBox = nodeBbox.Max(axis);
994        const float boxArea = nodeBbox.SurfaceArea();
995
996        float minSum = 1e20f;
997 
998        Vector3 minBorder = nodeBbox.Max();
999        Vector3 maxBorder = nodeBbox.Min();
1000
1001        float areaLeft = 0, areaRight = 0;
1002
1003        SortableEntryContainer::const_iterator currentPos =
1004                mSubdivisionCandidates->begin();
1005       
1006        vector<Vector3> bordersRight;
1007
1008        // we keep track of both borders of the bounding boxes =>
1009        // store the events in descending order
1010        bordersRight.resize(mSubdivisionCandidates->size());
1011
1012        SortableEntryContainer::reverse_iterator rcit =
1013                mSubdivisionCandidates->rbegin(), rcit_end =
1014                mSubdivisionCandidates->rend();
1015
1016        vector<Vector3>::reverse_iterator rbit = bordersRight.rbegin();
1017
1018        for (; rcit != rcit_end; ++ rcit, ++ rbit)
1019        {
1020                Intersectable *obj = (*rcit).mObject;
1021                const AxisAlignedBox3 obox = obj->GetBox();
1022
1023                for (int i = 0; i < 3; ++ i)
1024                {
1025                        if (obox.Min(i) < minBorder[i])
1026                        {
1027                                minBorder[i] = obox.Min(i);
1028                        }
1029                }
1030
1031                (*rbit) = minBorder;
1032        }
1033
1034        // temporary surface areas
1035        float al = 0;
1036        float ar = boxArea;
1037
1038        vector<Vector3>::const_iterator bit = bordersRight.begin();
1039        SortableEntryContainer::const_iterator cit, cit_end =
1040                mSubdivisionCandidates->end();
1041
1042        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit, ++ bit)
1043        {
1044                Intersectable *obj = (*cit).mObject;
1045
1046                const float renderCost = mViewCellsManager->EvalRenderCost(obj);
1047               
1048                objectsLeft += renderCost;
1049                objectsRight -= renderCost;
1050
1051                const AxisAlignedBox3 obox = obj->GetBox();
1052
1053                AxisAlignedBox3 lbox = nodeBbox;
1054                AxisAlignedBox3 rbox = nodeBbox;
1055       
1056                // the borders of the left bounding box have changed
1057                for (int i = 0; i < 3; ++ i)
1058                {
1059                        if (obox.Max(i) > maxBorder[i])
1060                        {
1061                                maxBorder[i] = obox.Max(i);
1062                        }
1063                }
1064
1065                minBorder = (*bit);
1066
1067                lbox.SetMax(maxBorder);
1068                rbox.SetMin(minBorder);
1069
1070                al = lbox.SurfaceArea();
1071                ar = rbox.SurfaceArea();
1072       
1073                const bool noValidSplit = ((objectsLeft <= Limits::Small) || (objectsRight <= Limits::Small));
1074                const float sum =  noValidSplit ? 1e25 : objectsLeft * al + objectsRight * ar;
1075     
1076                /*cout << "pos=" << (*cit).mPos << "\t q=(" << objectsLeft << "," << objectsRight <<")\t r=("
1077                         << lbox.SurfaceArea() << "," << rbox.SurfaceArea() << ")" << endl;
1078                cout << "minborder: " << minBorder << " maxborder: " << maxBorder << endl;
1079            cout << "cost= " << sum << endl;*/
1080       
1081                if (sum < minSum)
1082                {       
1083                        minSum = sum;
1084                        areaLeft = al;
1085                        areaRight = ar;
1086
1087                        // objects belong to left side now
1088                        for (; currentPos != (cit + 1); ++ currentPos);
1089                }
1090        }
1091
1092        /////////////
1093        //-- assign object to front and back volume
1094
1095        // belongs to back bv
1096        for (cit = mSubdivisionCandidates->begin(); cit != currentPos; ++ cit)
1097                objectsBack.push_back((*cit).mObject);
1098       
1099        // belongs to front bv
1100        for (cit = currentPos; cit != cit_end; ++ cit)
1101                objectsFront.push_back((*cit).mObject);
1102
1103        float newCost = minSum / boxArea;
1104        float ratio = newCost / totalRenderCost;
1105 
1106#ifdef GTP_DEBUG
1107        cout << "\n\nobjects=(" << (int)objectsBack.size() << "," << (int)objectsFront.size() << " of "
1108                 << (int)tData.mNode->mObjects.size() << ")\t area=("
1109                 << areaLeft << ", " << areaRight << ", " << boxArea << ")" << endl
1110                 << "cost= " << newCost << " oldCost=" << totalRenderCost / boxArea << endl;
1111#endif
1112
1113        return ratio;
1114}
1115
1116#endif
1117
1118static bool PrepareOutput(const int axis,
1119                                                  const int leaves,
1120                                                  ofstream &sumStats,
1121                                                  ofstream &vollStats,
1122                                                  ofstream &volrStats)
1123{
1124        if ((axis == 0) && (leaves > 0) && (leaves < 90))
1125        {
1126                char str[64];   
1127                sprintf(str, "tmp/bvh_heur_sum-%04d.log", leaves);
1128                sumStats.open(str);
1129                sprintf(str, "tmp/bvh_heur_voll-%04d.log", leaves);
1130                vollStats.open(str);
1131                sprintf(str, "tmp/bvh_heur_volr-%04d.log", leaves);
1132                volrStats.open(str);
1133        }
1134
1135        return sumStats.is_open() && vollStats.is_open() && volrStats.is_open();
1136}
1137
1138
1139static void PrintHeuristics(const float objectsRight,
1140                                                        const float sum,
1141                                                        const float volLeft,
1142                                                        const float volRight,
1143                                                        const float viewSpaceVol,
1144                                                        ofstream &sumStats,
1145                                                        ofstream &vollStats,
1146                                                        ofstream &volrStats)
1147{
1148        sumStats
1149                << "#Position\n" << objectsRight << endl
1150                << "#Sum\n" << sum / viewSpaceVol << endl
1151                << "#Vol\n" << (volLeft +  volRight) / viewSpaceVol << endl;
1152
1153        vollStats
1154                << "#Position\n" << objectsRight << endl
1155                << "#Vol\n" << volLeft / viewSpaceVol << endl;
1156
1157        volrStats
1158                << "#Position\n" << objectsRight << endl
1159                << "#Vol\n" << volRight / viewSpaceVol << endl;
1160}
1161
1162
1163float BvHierarchy::EvalLocalCostHeuristics(const BvhTraversalData &tData,
1164                                                                                   const int axis,
1165                                                                                   ObjectContainer &objectsFront,
1166                                                                                   ObjectContainer &objectsBack)
1167{
1168        ///////////////////////////////////////////////////////
1169        //-- go through the lists, count the number of objects left
1170        //-- and right and evaluate the cost funcion
1171
1172        // prepare the heuristics by setting mailboxes and counters.
1173        const float totalVol = PrepareHeuristics(tData, axis);
1174       
1175        // local helper variables
1176        float volLeft = 0;
1177        float volRight = totalVol;
1178       
1179        const float nTotalObjects = EvalAbsCost(tData.mNode->mObjects);
1180        float nObjectsLeft = 0;
1181        float nObjectsRight = nTotalObjects;
1182
1183        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
1184
1185        SortableEntryContainer::const_iterator backObjectsStart =
1186                mSubdivisionCandidates->begin();
1187
1188        /////////////////////////////////
1189        //-- the parameters for the current optimum
1190
1191        float volBack = volLeft;
1192        float volFront = volRight;
1193        float newRenderCost = nTotalObjects * totalVol;
1194
1195#ifdef GTP_DEBUG
1196        ofstream sumStats;
1197        ofstream vollStats;
1198        ofstream volrStats;
1199
1200        const bool printStats =
1201                PrepareOutput(axis, mBvhStats.Leaves(), sumStats, vollStats, volrStats);
1202#endif
1203
1204        ///////////////////////
1205        //-- the sweep heuristics
1206        //-- traverse through events and find best split plane
1207
1208        SortableEntryContainer::const_iterator cit,
1209                cit_end = cit_end = mSubdivisionCandidates->end();
1210
1211        for (cit = mSubdivisionCandidates->begin(); cit != cit_end; ++ cit)
1212        {
1213                Intersectable *object = (*cit).mObject;
1214       
1215                // evaluate change in l and r volume
1216                // voll = view cells that see only left node (i.e., left pvs)
1217                // volr = view cells that see only right node (i.e., right pvs)
1218                EvalHeuristicsContribution(object, volLeft, volRight);
1219
1220                const float rc = mViewCellsManager->EvalRenderCost(object);
1221
1222                nObjectsLeft += rc;
1223                nObjectsRight -= rc;
1224               
1225                const bool noValidSplit = ((nObjectsLeft <= Limits::Small) || (nObjectsRight <= Limits::Small));
1226
1227                // the heuristics
1228            const float sum = noValidSplit ?
1229                        1e25 : volLeft * (float)nObjectsLeft + volRight * (float)nObjectsRight;
1230
1231#ifdef GTP_DEBUG
1232                if (printStats)
1233                {
1234                        PrintHeuristics(nObjectsRight, sum, volLeft, volRight, viewSpaceVol,
1235                                                        sumStats, vollStats, volrStats);
1236                }
1237#endif
1238
1239                if (sum < newRenderCost)
1240                {
1241                        newRenderCost = sum;
1242
1243                        volBack = volLeft;
1244                        volFront = volRight;
1245
1246                        // objects belongs to left side now
1247                        for (; backObjectsStart != (cit + 1); ++ backObjectsStart);
1248                }
1249        }
1250
1251        ////////////////////////////////////////////
1252        //-- assign object to front and back volume
1253
1254        // belongs to back bv
1255        for (cit = mSubdivisionCandidates->begin(); cit != backObjectsStart; ++ cit)
1256        {
1257                objectsBack.push_back((*cit).mObject);
1258        }
1259        // belongs to front bv
1260        for (cit = backObjectsStart; cit != cit_end; ++ cit)
1261        {
1262                objectsFront.push_back((*cit).mObject);
1263        }
1264
1265        // render cost of the old parent
1266        const float oldRenderCost = (float)nTotalObjects * totalVol + Limits::Small;
1267        // the relative cost ratio
1268        const float ratio = newRenderCost / oldRenderCost;
1269
1270#ifdef GTP_DEBUG
1271        Debug << "\n§§§§ bvh eval const decrease §§§§" << endl
1272                  << "back pvs: " << (int)objectsBack.size() << " front pvs: "
1273                  << (int)objectsFront.size() << " total pvs: " << nTotalObjects << endl
1274                  << "back p: " << volBack / viewSpaceVol << " front p "
1275                  << volFront / viewSpaceVol << " p: " << totalVol / viewSpaceVol << endl
1276                  << "old rc: " << oldRenderCost / viewSpaceVol << " new rc: "
1277                  << newRenderCost / viewSpaceVol << endl
1278                  << "render cost decrease: "
1279                  << oldRenderCost / viewSpaceVol - newRenderCost / viewSpaceVol << endl;
1280#endif
1281
1282        return ratio;
1283}
1284
1285
1286void BvHierarchy::PrepareLocalSubdivisionCandidates(const BvhTraversalData &tData,
1287                                                                                                        const int axis)                                                                                 
1288{
1289        //-- insert object queries
1290        ObjectContainer *objects = mUseGlobalSorting ?
1291                tData.mSortedObjects[axis] : &tData.mNode->mObjects;
1292
1293        CreateLocalSubdivisionCandidates(*objects, &mSubdivisionCandidates, !mUseGlobalSorting, axis);
1294}
1295
1296
1297void BvHierarchy::CreateLocalSubdivisionCandidates(const ObjectContainer &objects,
1298                                                                                                  SortableEntryContainer **subdivisionCandidates,
1299                                                                                                  const bool sort,
1300                                                                                                  const int axis)
1301{
1302        (*subdivisionCandidates)->clear();
1303
1304        // compute requested size and look if subdivision candidate has to be recomputed
1305        const int requestedSize = (int)objects.size() * 2;
1306       
1307        // creates a sorted split candidates array
1308        if ((*subdivisionCandidates)->capacity() > 500000 &&
1309                requestedSize < (int)((*subdivisionCandidates)->capacity() / 10) )
1310        {
1311        delete (*subdivisionCandidates);
1312                (*subdivisionCandidates) = new SortableEntryContainer;
1313        }
1314
1315        (*subdivisionCandidates)->reserve(requestedSize);
1316
1317        ObjectContainer::const_iterator oit, oit_end = objects.end();
1318
1319        for (oit = objects.begin(); oit < oit_end; ++ oit)
1320        {
1321                Intersectable *object = *oit;
1322                const AxisAlignedBox3 &box = object->GetBox();
1323                const float midPt = (box.Min(axis) + box.Max(axis)) * 0.5f;
1324
1325                (*subdivisionCandidates)->push_back(SortableEntry(object, midPt));
1326        }
1327
1328        if (sort)
1329        {       // no presorted candidate list
1330                stable_sort((*subdivisionCandidates)->begin(), (*subdivisionCandidates)->end());
1331        }
1332}
1333
1334
1335const BvhStatistics &BvHierarchy::GetStatistics() const
1336{
1337        return mBvhStats;
1338}
1339
1340
1341float BvHierarchy::PrepareHeuristics(const BvhTraversalData &tData,
1342                                                                         const int axis)
1343{       
1344        BvhLeaf *leaf = tData.mNode;
1345        float vol = 0;
1346
1347    // sort so we can use a sweep from right to left
1348        PrepareLocalSubdivisionCandidates(tData, axis);
1349       
1350        VssRayContainer rays;
1351        // maximal 2 objects share the same ray
1352        rays.reserve(tData.mNumRays * 2);
1353        CollectRays(tData.mNode->mObjects, rays);
1354
1355        const float prop = (float)mMaxTests / ((float)tData.mNumRays + Limits::Small);
1356
1357        VssRay::NewMail();
1358
1359        //cout << "here7 " << tData.mNumRays << " " << rays.size() << endl;
1360        //cout << "here5 prop: " << prop << " " << mMaxTests << " " << tData.mNumRays << endl;
1361        // only use a subset of the rays
1362        VssRayContainer::const_iterator rit, rit_end = rays.end();
1363
1364        int nRays = 0;
1365
1366        for (rit = rays.begin(); rit != rit_end; ++ rit)
1367        {
1368                if ((mMaxTests >= (int)rays.size()) || (Random(1.0f) < prop))
1369                {
1370                        (*rit)->Mail();
1371                        ++ nRays;
1372                }
1373        }
1374       
1375        //cout << "here99 " << nRays << " obj " << tData.mNode->mObjects.size() << endl;
1376        // collect and mark the view cells as belonging to front pvs
1377        ViewCellContainer viewCells;
1378        CollectViewCells(tData.mNode->mObjects, viewCells, true, true);
1379       
1380        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1381        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1382        {
1383#if USE_VOLUMES_FOR_HEURISTICS
1384                const float volIncr = (*vit)->GetVolume();
1385#else
1386                const float volIncr = 1.0f;
1387#endif
1388                vol += volIncr;
1389        }
1390
1391        // we will mail view cells switching to the back side
1392        ViewCell::NewMail();
1393       
1394        return vol;
1395}
1396
1397///////////////////////////////////////////////////////////
1398
1399
1400void BvHierarchy::EvalHeuristicsContribution(Intersectable *obj,
1401                                                                                         float &volLeft,
1402                                                                                         float &volRight)
1403{
1404        // collect all view cells associated with this objects
1405        // (also multiple times, if they are pierced by several rays)
1406        ViewCellContainer viewCells;
1407        const bool useMailboxing = false;
1408
1409        CollectViewCells(obj, viewCells, useMailboxing, true, true);
1410
1411        // classify view cells and compute volume contri accordingly
1412        // possible view cell classifications:
1413        // view cell mailed => view cell can be seen from left child node
1414        // view cell counter > 0 view cell can be seen from right child node
1415        // combined: view cell volume belongs to both nodes
1416        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1417       
1418        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1419        {
1420                // view cells can also be seen from left child node
1421                ViewCell *viewCell = *vit;
1422#if USE_VOLUMES_FOR_HEURISTICS
1423                const float vol = viewCell->GetVolume();
1424#else
1425                const float vol = 1.0f;
1426#endif
1427                if (!viewCell->Mailed())
1428                {
1429                        viewCell->Mail();
1430                        // we now see view cell from both nodes
1431                        // => add volume to left node
1432                        volLeft += vol;
1433                }
1434
1435                // last reference into the right node
1436                if (-- viewCell->mCounter == 0)
1437                {       
1438                        // view cell was previously seen from both nodes  =>
1439                        // remove volume from right node
1440                        volRight -= vol;
1441                }
1442        }
1443}
1444
1445
1446void BvHierarchy::SetViewCellsManager(ViewCellsManager *vcm)
1447{
1448        mViewCellsManager = vcm;
1449}
1450
1451
1452AxisAlignedBox3 BvHierarchy::GetBoundingBox() const
1453{
1454        return mBoundingBox;
1455}
1456
1457
1458float BvHierarchy::SelectObjectPartition(const BvhTraversalData &tData,
1459                                                                                 ObjectContainer &frontObjects,
1460                                                                                 ObjectContainer &backObjects,
1461                                                                                 bool useVisibilityBasedHeuristics)
1462{
1463        ObjectContainer nFrontObjects[3];
1464        ObjectContainer nBackObjects[3];
1465        float nCostRatio[3];
1466
1467        int sAxis = 0;
1468        int bestAxis = -1;
1469
1470        if (mOnlyDrivingAxis)
1471        {
1472                const AxisAlignedBox3 box = tData.mNode->GetBoundingBox();
1473                sAxis = box.Size().DrivingAxis();
1474        }
1475       
1476        ////////////////////////////////////
1477        //-- evaluate split cost for all three axis
1478       
1479        for (int axis = 0; axis < 3; ++ axis)
1480        {
1481                if (!mOnlyDrivingAxis || (axis == sAxis))
1482                {
1483                        if (mUseCostHeuristics)
1484                        {
1485                                //////////////////////////////////
1486                //-- split objects using heuristics
1487                               
1488                                if (useVisibilityBasedHeuristics)
1489                                {
1490                                        ///////////
1491                                        //-- heuristics using objects weighted by view cells volume
1492                                        nCostRatio[axis] =
1493                                                EvalLocalCostHeuristics(tData,
1494                                                                                                axis,
1495                                                                                                nFrontObjects[axis],
1496                                                                                                nBackObjects[axis]);
1497                                }
1498                                else
1499                                {       
1500                                        //////////////////
1501                                        //-- view cells not constructed yet     => use surface area heuristic                   
1502                                        nCostRatio[axis] = EvalSah(tData,
1503                                                                                           axis,
1504                                                                                           nFrontObjects[axis],
1505                                                                                           nBackObjects[axis]);
1506                                }
1507                        }
1508                        else
1509                        {
1510                                //-- split objects using some simple criteria
1511                                nCostRatio[axis] =
1512                                        EvalLocalObjectPartition(tData, axis, nFrontObjects[axis], nBackObjects[axis]);
1513                        }
1514
1515                        if ((bestAxis == -1) || (nCostRatio[axis] < nCostRatio[bestAxis]))
1516                        {
1517                                bestAxis = axis;
1518                        }
1519                }
1520        }
1521
1522    ////////////////
1523        //-- assign values
1524
1525        frontObjects = nFrontObjects[bestAxis];
1526        backObjects = nBackObjects[bestAxis];
1527
1528        //cout << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl;
1529        return nCostRatio[bestAxis];
1530}
1531
1532
1533int BvHierarchy::AssociateObjectsWithRays(const VssRayContainer &rays) const
1534{
1535        int nRays = 0;
1536        VssRayContainer::const_iterator rit, rit_end = rays.end();
1537
1538        VssRay::NewMail();
1539
1540    for (rit = rays.begin(); rit != rays.end(); ++ rit)
1541        {
1542                VssRay *ray = (*rit);
1543
1544                if (ray->mTerminationObject)
1545                {
1546                        ray->mTerminationObject->GetOrCreateRays()->push_back(ray);
1547                        if (!ray->Mailed())
1548                        {
1549                                ray->Mail();
1550                                ++ nRays;
1551                        }
1552                }
1553#if COUNT_ORIGIN_OBJECTS
1554                if (ray->mOriginObject)
1555                {
1556                        ray->mOriginObject->GetOrCreateRays()->push_back(ray);
1557
1558                        if (!ray->Mailed())
1559                        {
1560                                ray->Mail();
1561                                ++ nRays;
1562                        }
1563                }
1564#endif
1565        }
1566
1567        return nRays;
1568}
1569
1570
1571void BvHierarchy::PrintSubdivisionStats(const SubdivisionCandidate &sc)
1572{
1573        const float costDecr = sc.GetRenderCostDecrease();     
1574
1575        mSubdivisionStats
1576                        << "#Leaves\n" << mBvhStats.Leaves() << endl
1577                        << "#RenderCostDecrease\n" << costDecr << endl
1578                        << "#TotalRenderCost\n" << mTotalCost << endl
1579                        << "#EntriesInPvs\n" << mPvsEntries << endl;
1580}
1581
1582
1583void BvHierarchy::CollectRays(const ObjectContainer &objects,
1584                                                          VssRayContainer &rays) const
1585{
1586        VssRay::NewMail();
1587        ObjectContainer::const_iterator oit, oit_end = objects.end();
1588
1589        // evaluate reverse pvs and view cell volume on left and right cell
1590        // note: should I take all leaf objects or rather the objects hit by rays?
1591        for (oit = objects.begin(); oit != oit_end; ++ oit)
1592        {
1593                Intersectable *obj = *oit;
1594                VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1595
1596                for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1597                {
1598                        VssRay *ray = (*rit);
1599
1600                        if (!ray->Mailed())
1601                        {
1602                                ray->Mail();
1603                                rays.push_back(ray);
1604                        }
1605                }
1606        }
1607}
1608
1609
1610float BvHierarchy::EvalAbsCost(const ObjectContainer &objects)// const
1611{
1612#if USE_BETTER_RENDERCOST_EST
1613        ObjectContainer::const_iterator oit, oit_end = objects.end();
1614
1615        for (oit = objects.begin(); oit != oit_end; ++ oit)
1616        {
1617                objRenderCost += ViewCellsManager::GetRendercost(*oit);
1618        }
1619#else
1620        return (float)objects.size();
1621#endif
1622}
1623
1624
1625float BvHierarchy::EvalSahCost(BvhLeaf *leaf)
1626{
1627        ////////////////
1628        //-- surface area heuristics
1629        if (leaf->mObjects.empty())
1630                return 0.0f;
1631
1632        const AxisAlignedBox3 box = GetBoundingBox(leaf);
1633        const float area = box.SurfaceArea();
1634        const float viewSpaceArea = mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1635
1636        return EvalAbsCost(leaf->mObjects) * area / viewSpaceArea;
1637}
1638
1639
1640float BvHierarchy::EvalRenderCost(const ObjectContainer &objects) const
1641{       
1642        ///////////////
1643        //-- render cost heuristics
1644
1645        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
1646
1647        // probability that view point lies in a view cell which sees this node
1648        const float p = EvalViewCellsVolume(objects) / viewSpaceVol;
1649    const float objRenderCost = EvalAbsCost(objects);
1650       
1651        return objRenderCost * p;
1652}
1653
1654
1655AxisAlignedBox3 BvHierarchy::EvalBoundingBox(const ObjectContainer &objects,
1656                                                                                         const AxisAlignedBox3 *parentBox) const
1657{
1658        // if there are no objects in this box, box size is set to parent box size.
1659        // Question: Invalidate box instead?
1660        if (parentBox && objects.empty())
1661                return *parentBox;
1662
1663        AxisAlignedBox3 box;
1664        box.Initialize();
1665
1666        ObjectContainer::const_iterator oit, oit_end = objects.end();
1667
1668        for (oit = objects.begin(); oit != oit_end; ++ oit)
1669        {
1670                Intersectable *obj = *oit;
1671                // grow bounding box to include all objects
1672                box.Include(obj->GetBox());
1673        }
1674
1675        return box;
1676}
1677
1678
1679void BvHierarchy::CollectLeaves(BvhNode *root, vector<BvhLeaf *> &leaves) const
1680{
1681        stack<BvhNode *> nodeStack;
1682        nodeStack.push(root);
1683
1684        while (!nodeStack.empty())
1685        {
1686                BvhNode *node = nodeStack.top();
1687                nodeStack.pop();
1688
1689                if (node->IsLeaf())
1690                {
1691                        BvhLeaf *leaf = (BvhLeaf *)node;
1692                        leaves.push_back(leaf);
1693                }
1694                else
1695                {
1696                        BvhInterior *interior = (BvhInterior *)node;
1697
1698                        nodeStack.push(interior->GetBack());
1699                        nodeStack.push(interior->GetFront());
1700                }
1701        }
1702}
1703
1704
1705AxisAlignedBox3 BvHierarchy::GetBoundingBox(BvhNode *node) const
1706{
1707        return node->GetBoundingBox();
1708}
1709
1710
1711int BvHierarchy::CollectViewCells(const ObjectContainer &objects,
1712                                                                  ViewCellContainer &viewCells,
1713                                                                  const bool setCounter,
1714                                                                  const bool onlyMailedRays) const
1715{
1716        ViewCell::NewMail();
1717        ObjectContainer::const_iterator oit, oit_end = objects.end();
1718
1719        int numRays = 0;
1720        // loop through all object and collect view cell pvs of this node
1721        for (oit = objects.begin(); oit != oit_end; ++ oit)
1722        {
1723                // always use only mailed objects
1724                numRays += CollectViewCells(*oit, viewCells, true, setCounter, onlyMailedRays);
1725        }
1726        //cout << "here4 " << numRays << " boj: " << objects.size() << " " << onlyMailedRays << endl;
1727
1728        return numRays;
1729}
1730
1731
1732int BvHierarchy::CollectViewCells(Intersectable *obj,
1733                                                                  ViewCellContainer &viewCells,
1734                                                                  const bool useMailBoxing,
1735                                                                  const bool setCounter,
1736                                                                  const bool onlyMailedRays) const
1737{
1738        VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1739
1740        int numRays = 0;
1741
1742        for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1743        {
1744                VssRay *ray = (*rit);
1745
1746                if (onlyMailedRays && !ray->Mailed())
1747                        continue;
1748
1749                //ray->Mail();
1750                ++ numRays;
1751
1752                ViewCellContainer tmpViewCells;
1753                mHierarchyManager->mVspTree->GetViewCells(*ray, tmpViewCells);
1754
1755                // matt: probably slow to allocate memory for view cells every time
1756                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1757
1758                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1759                {
1760                        ViewCell *vc = *vit;
1761
1762                        // store view cells
1763                        if (!useMailBoxing || !vc->Mailed())
1764                        {
1765                                if (useMailBoxing)
1766                                {
1767                                        vc->Mail();
1768                                        if (setCounter)
1769                                        {
1770                                                vc->mCounter = 0;
1771                                        }
1772                                }
1773                                viewCells.push_back(vc);
1774                        }
1775                       
1776                        if (setCounter)
1777                        {
1778                                ++ vc->mCounter;
1779                        }
1780                }
1781        }
1782
1783        return numRays;
1784}
1785
1786
1787int BvHierarchy::CountViewCells(Intersectable *obj) const
1788{
1789        int result = 0;
1790       
1791        VssRayContainer::const_iterator rit, rit_end = obj->GetOrCreateRays()->end();
1792
1793        for (rit = obj->GetOrCreateRays()->begin(); rit < rit_end; ++ rit)
1794        {
1795                VssRay *ray = (*rit);
1796                ViewCellContainer tmpViewCells;
1797       
1798                mHierarchyManager->mVspTree->GetViewCells(*ray, tmpViewCells);
1799               
1800                ViewCellContainer::const_iterator vit, vit_end = tmpViewCells.end();
1801                for (vit = tmpViewCells.begin(); vit != vit_end; ++ vit)
1802                {
1803                        ViewCell *vc = *vit;
1804
1805                        // store view cells
1806                        if (!vc->Mailed())
1807                        {
1808                                vc->Mail();
1809                                ++ result;
1810                        }
1811                }
1812        }
1813
1814        return result;
1815}
1816
1817
1818int BvHierarchy::CountViewCells(const ObjectContainer &objects) const
1819{
1820        int nViewCells = 0;
1821        ViewCell::NewMail();
1822        ObjectContainer::const_iterator oit, oit_end = objects.end();
1823
1824        // loop through all object and collect view cell pvs of this node
1825        for (oit = objects.begin(); oit != oit_end; ++ oit)
1826        {
1827                nViewCells += CountViewCells(*oit);
1828        }
1829
1830        return nViewCells;
1831}
1832
1833
1834void BvHierarchy::CollectDirtyCandidates(BvhSubdivisionCandidate *sc,
1835                                                                                 vector<SubdivisionCandidate *> &dirtyList,
1836                                                                                 const bool onlyUnmailed)
1837{
1838        BvhTraversalData &tData = sc->mParentData;
1839        BvhLeaf *node = tData.mNode;
1840       
1841        ViewCellContainer viewCells;
1842        ViewCell::NewMail();
1843        int numRays = CollectViewCells(node->mObjects, viewCells, true, false);
1844
1845        //cout << "here6 " << numRays << endl;
1846        if (0) cout << "collected " << (int)viewCells.size() << " dirty candidates" << endl;
1847       
1848        // split candidates handling
1849        // these view cells  are thrown into dirty list
1850        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
1851
1852        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
1853        {
1854        VspViewCell *vc = dynamic_cast<VspViewCell *>(*vit);
1855                VspLeaf *leaf = vc->mLeaves[0];
1856       
1857                SubdivisionCandidate *candidate = leaf->GetSubdivisionCandidate();
1858               
1859                // is this leaf still a split candidate?
1860                if (candidate && (!onlyUnmailed || !candidate->Mailed()))
1861                {
1862                        candidate->Mail();
1863                        candidate->SetDirty(true);
1864                        dirtyList.push_back(candidate);
1865                }
1866        }
1867}
1868
1869
1870BvhNode *BvHierarchy::GetRoot() const
1871{
1872        return mRoot;
1873}
1874
1875
1876bool BvHierarchy::IsObjectInLeaf(BvhLeaf *leaf, Intersectable *object) const
1877{
1878        ObjectContainer::const_iterator oit =
1879                lower_bound(leaf->mObjects.begin(), leaf->mObjects.end(), object, ilt);
1880                               
1881        // objects sorted by id
1882        if ((oit != leaf->mObjects.end()) && ((*oit)->GetId() == object->GetId()))
1883        {
1884                return true;
1885        }
1886        else
1887        {
1888                return false;
1889        }
1890}
1891
1892
1893BvhLeaf *BvHierarchy::GetLeaf(Intersectable *object, BvhNode *node) const
1894{
1895        // rather use the simple version
1896        if (!object)
1897                return NULL;
1898       
1899        return object->mBvhLeaf;
1900       
1901        ///////////////////////////////////////
1902        // start from root of tree
1903       
1904        if (node == NULL)
1905                node = mRoot;
1906       
1907        vector<BvhLeaf *> leaves;
1908
1909        stack<BvhNode *> nodeStack;
1910        nodeStack.push(node);
1911 
1912        BvhLeaf *leaf = NULL;
1913 
1914        while (!nodeStack.empty()) 
1915        {
1916                BvhNode *node = nodeStack.top();
1917                nodeStack.pop();
1918       
1919                if (node->IsLeaf())
1920                {
1921                        leaf = dynamic_cast<BvhLeaf *>(node);
1922
1923                        if (IsObjectInLeaf(leaf, object))
1924                        {
1925                                return leaf;
1926                        }
1927                }
1928                else   
1929                {       
1930                        // find point
1931                        BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
1932       
1933                        if (interior->GetBack()->GetBoundingBox().Includes(object->GetBox()))
1934                        {
1935                                nodeStack.push(interior->GetBack());
1936                        }
1937                       
1938                        // search both sides as we are using bounding volumes
1939                        if (interior->GetFront()->GetBoundingBox().Includes(object->GetBox()))
1940                        {
1941                                nodeStack.push(interior->GetFront());
1942                        }
1943                }
1944        }
1945 
1946        return leaf;
1947}
1948
1949
1950BvhIntersectable *BvHierarchy::GetOrCreateBvhIntersectable(BvhLeaf *node)
1951{
1952        // search nodes
1953        std::map<BvhLeaf *, BvhIntersectable *>::const_iterator
1954                it = mBvhIntersectables.find(node);
1955
1956        if (it != mBvhIntersectables.end())
1957        {
1958                return (*it).second;
1959        }
1960
1961        // not in map => create new entry
1962        BvhIntersectable *bvhObj = new BvhIntersectable(node);
1963        mBvhIntersectables[node] = bvhObj;
1964
1965        return bvhObj;
1966}
1967
1968
1969bool BvHierarchy::Export(OUT_STREAM &stream)
1970{
1971        ExportNode(mRoot, stream);
1972
1973        return true;
1974}
1975
1976
1977void BvHierarchy::ExportObjects(BvhLeaf *leaf, OUT_STREAM &stream)
1978{
1979        ObjectContainer::const_iterator oit, oit_end = leaf->mObjects.end();
1980        for (oit = leaf->mObjects.begin(); oit != oit_end; ++ oit)
1981        {
1982                stream << (*oit)->GetId() << " ";
1983        }
1984}
1985
1986
1987void BvHierarchy::ExportNode(BvhNode *node, OUT_STREAM &stream)
1988{
1989        if (node->IsLeaf())
1990        {
1991                BvhLeaf *leaf = dynamic_cast<BvhLeaf *>(node);
1992                const AxisAlignedBox3 box = leaf->GetBoundingBox();
1993                stream << "<Leaf"
1994                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1995                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\""
1996                           << " objects=\"";
1997               
1998                //-- export objects
1999                ExportObjects(leaf, stream);
2000               
2001                stream << "\" />" << endl;
2002        }
2003        else
2004        {       
2005                BvhInterior *interior = dynamic_cast<BvhInterior *>(node);
2006                const AxisAlignedBox3 box = interior->GetBoundingBox();
2007
2008                stream << "<Interior"
2009                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
2010                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z
2011                           << "\">" << endl;
2012
2013                ExportNode(interior->GetBack(), stream);
2014                ExportNode(interior->GetFront(), stream);
2015
2016                stream << "</Interior>" << endl;
2017        }
2018}
2019
2020
2021float BvHierarchy::EvalViewCellsVolume(const ObjectContainer &objects) const
2022{
2023        float vol = 0;
2024
2025        ViewCellContainer viewCells;
2026       
2027        // we have to account for all view cells that can
2028        // be seen from the objects
2029        int numRays = CollectViewCells(objects, viewCells, false, false);
2030
2031        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
2032
2033        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
2034        {
2035                vol += (*vit)->GetVolume();
2036        }
2037
2038        return vol;
2039}
2040
2041
2042void BvHierarchy::Initialise(const ObjectContainer &objects)
2043{
2044        AxisAlignedBox3 box = EvalBoundingBox(objects);
2045
2046        ///////
2047        //-- create new root
2048
2049        BvhLeaf *bvhleaf = new BvhLeaf(box, NULL, (int)objects.size());
2050        bvhleaf->mObjects = objects;
2051        mRoot = bvhleaf;
2052
2053        // compute bounding box from objects
2054        mBoundingBox = mRoot->GetBoundingBox();
2055
2056        // associate root with current objects
2057        AssociateObjectsWithLeaf(bvhleaf);
2058}
2059
2060
2061/*
2062Mesh *BvHierarchy::MergeLeafToMesh()
2063{
2064        vector<BvhLeaf *> leaves;
2065        CollectLeaves(leaves);
2066
2067        vector<BvhLeaf *>::const_iterator lit, lit_end = leaves.end();
2068
2069        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2070        {
2071                Mesh *mesh = MergeLeafToMesh(*lit);
2072        }
2073}*/
2074
2075
2076SubdivisionCandidate *BvHierarchy::PrepareConstruction(const VssRayContainer &sampleRays,
2077                                                                                                           const ObjectContainer &objects)
2078{
2079        ///////////////////////////////////////
2080        //-- we assume that we have objects sorted by their id =>
2081        //-- we don't have to sort them here and an binary search
2082        //-- for identifying if a object is in a leaf.
2083       
2084        mBvhStats.Reset();
2085        mBvhStats.Start();
2086        mBvhStats.nodes = 1;
2087               
2088        // store pointer to this tree
2089        BvhSubdivisionCandidate::sBvHierarchy = this;
2090       
2091        // root and bounding box was already constructed
2092        BvhLeaf *bvhLeaf = dynamic_cast<BvhLeaf *>(mRoot);
2093
2094        // multiply termination criterium for comparison,
2095        // so it can be set between zero and one and
2096        // no division is necessary during traversal
2097
2098#if PROBABILIY_IS_BV_VOLUME
2099        mTermMinProbability *= mBoundingBox.GetVolume();
2100        // probability that bounding volume is seen
2101        const float prop = GetBoundingBox().GetVolume();
2102#else
2103        mTermMinProbability *= mVspTree->GetBoundingBox().GetVolume();
2104        // probability that volume is "seen" from the view cells
2105        const float prop = EvalViewCellsVolume(objects);
2106#endif
2107
2108        // only rays intersecting objects in node are interesting
2109        const int nRays = AssociateObjectsWithRays(sampleRays);
2110        //Debug << "using " << nRays << " of " << (int)sampleRays.size() << " rays" << endl;
2111
2112        // create bvh traversal data
2113        BvhTraversalData oData(bvhLeaf, 0, prop, nRays);
2114
2115        // create sorted object lists for the first data
2116        if (mUseGlobalSorting)
2117        {
2118                AssignInitialSortedObjectList(oData);
2119        }
2120       
2121
2122        ///////////////////
2123        //-- add first candidate for object space partition     
2124
2125        BvhSubdivisionCandidate *oSubdivisionCandidate = new BvhSubdivisionCandidate(oData);
2126
2127        // evaluate priority
2128        EvalSubdivisionCandidate(*oSubdivisionCandidate);
2129        bvhLeaf->SetSubdivisionCandidate(oSubdivisionCandidate);
2130
2131        mTotalCost = EvalRenderCost(objects);
2132        mPvsEntries = CountViewCells(objects);
2133
2134        PrintSubdivisionStats(*oSubdivisionCandidate);
2135       
2136        return oSubdivisionCandidate;
2137}
2138
2139
2140void BvHierarchy::AssignInitialSortedObjectList(BvhTraversalData &tData)
2141{
2142        // we sort the objects as a preprocess so they don't have
2143        // to be sorted for each split
2144        for (int i = 0; i < 3; ++ i)
2145        {
2146                // create new objects
2147                if (!mSortedObjects[i])
2148                {
2149                        mSortedObjects[i] = new SortableEntryContainer();
2150                        CreateLocalSubdivisionCandidates(tData.mNode->mObjects, &mSortedObjects[i], true, i);
2151                }
2152
2153                // copy list into traversal data list
2154                tData.mSortedObjects[i] = new ObjectContainer();
2155                tData.mSortedObjects[i]->reserve((int)mSortedObjects[i]->size());
2156
2157                SortableEntryContainer::const_iterator oit, oit_end = mSortedObjects[i]->end();
2158
2159                for (oit = mSortedObjects[i]->begin(); oit != oit_end; ++ oit)
2160                {
2161                        tData.mSortedObjects[i]->push_back((*oit).mObject);
2162                }
2163        }
2164}
2165
2166
2167void BvHierarchy::AssignSortedObjects(const BvhSubdivisionCandidate &sc,
2168                                                                          BvhTraversalData &frontData,
2169                                                                          BvhTraversalData &backData)
2170{
2171        Intersectable::NewMail();
2172
2173        // we sorted the objects as a preprocess so they don't have
2174        // to be sorted for each split
2175        ObjectContainer::const_iterator fit, fit_end = sc.mFrontObjects.end();
2176
2177        for (fit = sc.mFrontObjects.begin(); fit != fit_end; ++ fit)
2178        {
2179                (*fit)->Mail();
2180        }
2181
2182        for (int i = 0; i < 3; ++ i)
2183        {
2184                frontData.mSortedObjects[i] = new ObjectContainer();
2185                backData.mSortedObjects[i] = new ObjectContainer();
2186
2187                frontData.mSortedObjects[i]->reserve((int)sc.mFrontObjects.size());
2188                backData.mSortedObjects[i]->reserve((int)sc.mFrontObjects.size());
2189
2190                ObjectContainer::const_iterator oit, oit_end = sc.mParentData.mSortedObjects[i]->end();
2191
2192                for (oit = sc.mParentData.mSortedObjects[i]->begin(); oit != oit_end; ++ oit)
2193                {
2194                        if ((*oit)->Mailed())
2195                        {
2196                                frontData.mSortedObjects[i]->push_back(*oit);
2197                        }
2198                        else
2199                        {
2200                                backData.mSortedObjects[i]->push_back(*oit);
2201                        }
2202                }
2203        }
2204}
2205
2206
2207SubdivisionCandidate *BvHierarchy::Reset(const VssRayContainer &sampleRays,
2208                                                                                 const ObjectContainer &objects)
2209{
2210        // reset stats
2211        mBvhStats.Reset();
2212        mBvhStats.Start();
2213        mBvhStats.nodes = 1;
2214
2215        // reset root
2216        DEL_PTR(mRoot);
2217       
2218        BvhLeaf *bvhleaf = new BvhLeaf(mBoundingBox, NULL, (int)objects.size());
2219        bvhleaf->mObjects = objects;
2220        mRoot = bvhleaf;
2221       
2222#if PROBABILIY_IS_BV_VOLUME
2223        mTermMinProbability *= mBoundingBox.GetVolume();
2224        // probability that bounding volume is seen
2225        const float prop = GetBoundingBox().GetVolume();
2226#else
2227        mTermMinProbability *= mVspTree->GetBoundingBox().GetVolume();
2228        // probability that volume is "seen" from the view cells
2229        const float prop = EvalViewCellsVolume(objects);
2230#endif
2231
2232        const int nRays = CountRays(objects);
2233        BvhLeaf *bvhLeaf = dynamic_cast<BvhLeaf *>(mRoot);
2234
2235        // create bvh traversal data
2236        BvhTraversalData oData(bvhLeaf, 0, prop, nRays);
2237
2238        AssignInitialSortedObjectList(oData);
2239       
2240
2241        ///////////////////
2242        //-- add first candidate for object space partition     
2243
2244        BvhSubdivisionCandidate *oSubdivisionCandidate =
2245                new BvhSubdivisionCandidate(oData);
2246
2247        EvalSubdivisionCandidate(*oSubdivisionCandidate);
2248        bvhLeaf->SetSubdivisionCandidate(oSubdivisionCandidate);
2249
2250        const float viewSpaceVol = mViewCellsManager->GetViewSpaceBox().GetVolume();
2251        mTotalCost = (float)objects.size() * prop / viewSpaceVol;
2252
2253        PrintSubdivisionStats(*oSubdivisionCandidate);
2254
2255        return oSubdivisionCandidate;
2256}
2257
2258
2259void BvhStatistics::Print(ostream &app) const
2260{
2261        app << "=========== BvHierarchy statistics ===============\n";
2262
2263        app << setprecision(4);
2264
2265        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
2266
2267        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
2268
2269        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
2270
2271        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
2272
2273        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits << endl;
2274
2275        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
2276                << maxCostNodes * 100 / (double)Leaves() << endl;
2277
2278        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
2279                << minProbabilityNodes * 100 / (double)Leaves() << endl;
2280
2281
2282        //////////////////////////////////////////////////
2283       
2284        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
2285                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
2286       
2287        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
2288
2289        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
2290
2291        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
2292
2293       
2294        ////////////////////////////////////////////////////////
2295       
2296        app << "#N_PMINOBJECTSLEAVES  ( Percentage of leaves with mininum objects )\n"
2297                << minObjectsNodes * 100 / (double)Leaves() << endl;
2298
2299        app << "#N_MAXOBJECTREFS  ( Max number of object refs / leaf )\n" << maxObjectRefs << "\n";
2300
2301        app << "#N_MINOBJECTREFS  ( Min number of object refs / leaf )\n" << minObjectRefs << "\n";
2302
2303        app << "#N_EMPTYLEAFS ( Empty leafs )\n" << emptyNodes << "\n";
2304       
2305        app << "#N_PAVGOBJECTSLEAVES  ( average object refs / leaf)\n" << AvgObjectRefs() << endl;
2306
2307
2308        ////////////////////////////////////////////////////////
2309       
2310        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with mininum rays )\n"
2311                << minRaysNodes * 100 / (double)Leaves() << endl;
2312
2313        app << "#N_MAXRAYREFS  ( Max number of ray refs / leaf )\n" << maxRayRefs << "\n";
2314
2315        app << "#N_MINRAYREFS  ( Min number of ray refs / leaf )\n" << minRayRefs << "\n";
2316       
2317        app << "#N_PAVGRAYLEAVES  ( average ray refs / leaf )\n" << AvgRayRefs() << endl;
2318       
2319        app << "#N_PAVGRAYCONTRIBLEAVES  ( Average ray contribution)\n" <<
2320                rayRefs / (double)objectRefs << endl;
2321
2322        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"<<
2323                maxRayContriNodes * 100 / (double)Leaves() << endl;
2324
2325        app << "#N_PGLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
2326
2327        app << "========== END OF BvHierarchy statistics ==========\n";
2328}
2329
2330
2331// TODO: return memory usage in MB
2332float BvHierarchy::GetMemUsage() const
2333{
2334        return (float)(sizeof(BvHierarchy)
2335                                   + mBvhStats.Leaves() * sizeof(BvhLeaf)
2336                                   + mBvhStats.Interior() * sizeof(BvhInterior)
2337                                   ) / float(1024 * 1024);
2338}
2339
2340
2341void BvHierarchy::SetActive(BvhNode *node) const
2342{
2343        vector<BvhLeaf *> leaves;
2344
2345        // sets the pointers to the currently active view cells
2346        CollectLeaves(node, leaves);
2347        vector<BvhLeaf *>::const_iterator lit, lit_end = leaves.end();
2348
2349        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2350        {
2351                (*lit)->SetActiveNode(node);
2352        }
2353}
2354
2355
2356BvhNode *BvHierarchy::SubdivideAndCopy(SplitQueue &tQueue,
2357                                                                           SubdivisionCandidate *splitCandidate)
2358{
2359        BvhSubdivisionCandidate *sc =
2360                dynamic_cast<BvhSubdivisionCandidate *>(splitCandidate);
2361        BvhTraversalData &tData = sc->mParentData;
2362
2363        BvhNode *currentNode = tData.mNode;
2364        BvhNode *oldNode = (BvhNode *)splitCandidate->mEvaluationHack;
2365
2366        if (!oldNode->IsLeaf())
2367        {       
2368                //////////////
2369                //-- continue subdivision
2370
2371                BvhTraversalData tFrontData;
2372                BvhTraversalData tBackData;
2373                       
2374                BvhInterior *oldInterior = dynamic_cast<BvhInterior *>(oldNode);
2375               
2376                sc->mFrontObjects.clear();
2377                sc->mBackObjects.clear();
2378
2379                oldInterior->GetFront()->CollectObjects(sc->mFrontObjects);
2380                oldInterior->GetBack()->CollectObjects(sc->mBackObjects);
2381               
2382                // evaluate the changes in render cost and pvs entries
2383                EvalSubdivisionCandidate(*sc, false);
2384
2385                // create new interior node and two leaf node
2386                currentNode = SubdivideNode(*sc, tFrontData, tBackData);
2387       
2388                //oldNode->mRenderCostDecr += sc->GetRenderCostDecrease();
2389                //oldNode->mPvsEntriesIncr += sc->GetPvsEntriesIncr();
2390               
2391                //oldNode->mRenderCostDecr = sc->GetRenderCostDecrease();
2392                //oldNode->mPvsEntriesIncr = sc->GetPvsEntriesIncr();
2393               
2394                ///////////////////////////
2395                //-- push the new split candidates on the queue
2396               
2397                BvhSubdivisionCandidate *frontCandidate = new BvhSubdivisionCandidate(tFrontData);
2398                BvhSubdivisionCandidate *backCandidate = new BvhSubdivisionCandidate(tBackData);
2399
2400                frontCandidate->SetPriority((float)-oldInterior->GetFront()->mTimeStamp);
2401                backCandidate->SetPriority((float)-oldInterior->GetBack()->mTimeStamp);
2402
2403                frontCandidate->mEvaluationHack = oldInterior->GetFront();
2404                backCandidate->mEvaluationHack = oldInterior->GetBack();
2405
2406                // cross reference
2407                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
2408                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
2409
2410                //cout << "f: " << frontCandidate->GetPriority() << " b: " << backCandidate->GetPriority() << endl;
2411                tQueue.Push(frontCandidate);
2412                tQueue.Push(backCandidate);
2413        }
2414
2415        /////////////////////////////////
2416        //-- node is a leaf => terminate traversal
2417
2418        if (currentNode->IsLeaf())
2419        {
2420                // this leaf is no candidate for splitting anymore
2421                // => detach subdivision candidate
2422                tData.mNode->SetSubdivisionCandidate(NULL);
2423                // detach node so we don't delete it with the traversal data
2424                tData.mNode = NULL;
2425        }
2426       
2427        return currentNode;
2428}
2429
2430
2431void BvHierarchy::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
2432{
2433  stack<BvhNode *> nodeStack;
2434
2435  nodeStack.push(mRoot);
2436
2437  while (!nodeStack.empty())
2438        {
2439          BvhNode *node = nodeStack.top();
2440         
2441          nodeStack.pop();
2442         
2443          if (node->IsLeaf())
2444                {
2445                  BvhLeaf *leaf = (BvhLeaf *)node;
2446                  if (Overlap(box, leaf->GetBoundingBox())) {
2447                        Intersectable *object = GetOrCreateBvhIntersectable(leaf);
2448                        if (!object->Mailed()) {
2449                          object->Mail();
2450                          objects.push_back(object);
2451                        }
2452                  }
2453                }
2454          else
2455                {
2456                  BvhInterior *interior = (BvhInterior *)node;
2457                 
2458                  if (Overlap(box, interior->GetBoundingBox()))
2459                        nodeStack.push(interior->GetFront());
2460                 
2461                  if (Overlap(box, interior->GetBoundingBox()))
2462                        nodeStack.push(interior->GetBack());
2463                }
2464        }
2465}
2466
2467}
Note: See TracBrowser for help on using the repository browser.