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

Revision 1877, 72.0 KB checked in by bittner, 18 years ago (diff)

sampling updates

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