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

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