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

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