source: GTP/trunk/Lib/Vis/Preprocessing/src/VspTree.cpp @ 1764

Revision 1764, 79.2 KB checked in by mattausch, 18 years ago (diff)

removed error in sample registration

Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "ViewCell.h"
6#include "Plane3.h"
7#include "VspTree.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 "KdTree.h"
19#include "IntersectableWrapper.h"
20#include "HierarchyManager.h"
21#include "BvHierarchy.h"
22#include "OspTree.h"
23
24
25
26namespace GtpVisibilityPreprocessor {
27
28
29#define USE_FIXEDPOINT_T 0
30
31/////////////
32//-- static members
33
34VspTree *VspTree::VspSubdivisionCandidate::sVspTree = NULL;
35int VspNode::sMailId = 1;
36
37// variable for debugging volume contribution for heuristics
38static float debugVol;
39
40
41// pvs penalty can be different from pvs size
42inline static float EvalPvsPenalty(const int pvs,
43                                                                   const int lower,
44                                                                   const int upper)
45{
46        // clamp to minmax values
47        if (pvs < lower)
48        {
49                return (float)lower;
50        }
51        else if (pvs > upper)
52        {
53                return (float)upper;
54        }
55        return (float)pvs;
56}
57
58#if WORK_WITH_VIEWCELLS
59static bool ViewCellHasMultipleReferences(Intersectable *obj,
60                                                                                  ViewCell *vc,
61                                                                                  bool checkOnlyMailed)
62{
63        MailablePvsData *vdata = obj->mViewCellPvs.Find(vc);
64
65        if (vdata)
66        {
67                // more than one view cell sees this object inside different kd cells
68                if (!checkOnlyMailed || !vdata->Mailed())
69                {
70                        if (checkOnlyMailed)
71                                vdata->Mail();
72                        //Debug << "sumpdf: " << vdata->mSumPdf << endl;
73                        if (vdata->mSumPdf > 1.5f)
74                                return true;
75                }
76        }
77       
78        return false;
79}
80
81
82void VspTree::RemoveParentViewCellReferences(ViewCell *parent) const
83{
84        KdLeaf::NewMail();
85
86        // remove the parents from the object pvss
87        ObjectPvsEntries::const_iterator oit, oit_end = parent->GetPvs().mEntries.end();
88
89        for (oit = parent->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
90        {
91                Intersectable *object = (*oit).first;
92                // HACK: make sure that the view cell is removed from the pvs
93                const float high_contri = 9999999;
94
95                // remove reference count of view cells
96                object->mViewCellPvs.RemoveSample(parent, high_contri);
97        }
98}
99
100
101void VspTree::AddViewCellReferences(ViewCell *vc) const
102{
103        KdLeaf::NewMail();
104
105        // Add front view cell to the object pvsss
106        ObjectPvsEntries::const_iterator oit, oit_end = vc->GetPvs().mEntries.end();
107
108        for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
109        {
110                Intersectable *object = (*oit).first;
111
112                // increase reference count of view cells
113                object->mViewCellPvs.AddSample(vc, 1);
114        }
115}
116
117#endif
118
119void VspTreeStatistics::Print(ostream &app) const
120{
121        app << "=========== VspTree statistics ===============\n";
122
123        app << setprecision(4);
124
125        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
126
127        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
128
129        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
130
131        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
132
133        app << "#N_SPLITS ( Number of splits in axes x y z)\n";
134
135        for (int i = 0; i < 3; ++ i)
136                app << splits[i] << " ";
137
138        app << endl;
139
140        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
141                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
142
143        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
144                << minPvsNodes * 100 / (double)Leaves() << endl;
145
146        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
147                << minRaysNodes * 100 / (double)Leaves() << endl;
148
149        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
150                << maxCostNodes * 100 / (double)Leaves() << endl;
151
152        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
153                << minProbabilityNodes * 100 / (double)Leaves() << endl;
154
155        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
156                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
157
158        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
159
160        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
161
162        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
163
164        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
165
166        app << "#AVGRAYS (number of rays / leaf)\n" << AvgRays() << endl;
167       
168        app << "#N_GLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
169
170        app << "========== END OF VspTree statistics ==========\n";
171}
172
173
174
175/******************************************************************/
176/*                  class VspNode implementation                  */
177/******************************************************************/
178
179
180VspNode::VspNode():
181mParent(NULL),
182mTreeValid(true),
183mTimeStamp(0)
184//,mRenderCostDecr(0)
185//,mMemoryIncr(0)
186//,mPvsEntriesIncr(0)
187{}
188
189
190VspNode::VspNode(VspInterior *parent):
191mParent(parent),
192mTreeValid(true),
193//,mMemoryIncr(0)
194//,mRenderCostDecr(0)
195//,mPvsEntriesIncr(0)
196mTimeStamp(0)
197{}
198
199
200bool VspNode::IsRoot() const
201{
202        return mParent == NULL;
203}
204
205
206VspInterior *VspNode::GetParent()
207{
208        return mParent;
209}
210
211
212void VspNode::SetParent(VspInterior *parent)
213{
214        mParent = parent;
215}
216
217
218bool VspNode::IsSibling(VspNode *n) const
219{
220        return  ((this != n) && mParent &&
221                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
222}
223
224
225int VspNode::GetDepth() const
226{
227        int depth = 0;
228        VspNode *p = mParent;
229       
230        while (p)
231        {
232                p = p->mParent;
233                ++ depth;
234        }
235
236        return depth;
237}
238
239
240bool VspNode::TreeValid() const
241{
242        return mTreeValid;
243}
244
245
246void VspNode::SetTreeValid(const bool v)
247{
248        mTreeValid = v;
249}
250
251
252
253/****************************************************************/
254/*              class VspInterior implementation                */
255/****************************************************************/
256
257
258VspInterior::VspInterior(const AxisAlignedPlane &plane):
259mPlane(plane), mFront(NULL), mBack(NULL)
260{}
261
262
263VspInterior::~VspInterior()
264{
265        DEL_PTR(mFront);
266        DEL_PTR(mBack);
267}
268
269
270bool VspInterior::IsLeaf() const
271{
272        return false;
273}
274
275
276VspNode *VspInterior::GetBack()
277{
278        return mBack;
279}
280
281
282VspNode *VspInterior::GetFront()
283{
284        return mFront;
285}
286
287
288AxisAlignedPlane VspInterior::GetPlane() const
289{
290        return mPlane;
291}
292
293
294float VspInterior::GetPosition() const
295{
296        return mPlane.mPosition;
297}
298
299
300int VspInterior::GetAxis() const
301{
302        return mPlane.mAxis;
303}
304
305
306void VspInterior::ReplaceChildLink(VspNode *oldChild, VspNode *newChild)
307{
308        if (mBack == oldChild)
309                mBack = newChild;
310        else
311                mFront = newChild;
312}
313
314
315void VspInterior::SetupChildLinks(VspNode *front, VspNode *back)
316{
317    mBack = back;
318    mFront = front;
319}
320
321
322AxisAlignedBox3 VspInterior::GetBoundingBox() const
323{
324        return mBoundingBox;
325}
326
327
328void VspInterior::SetBoundingBox(const AxisAlignedBox3 &box)
329{
330        mBoundingBox = box;
331}
332
333
334int VspInterior::Type() const
335{
336        return Interior;
337}
338
339
340
341/****************************************************************/
342/*                  class VspLeaf implementation                */
343/****************************************************************/
344
345
346VspLeaf::VspLeaf():
347mViewCell(NULL), mSubdivisionCandidate(NULL)
348//, mPvs(NULL)
349{
350}
351
352
353VspLeaf::~VspLeaf()
354{
355        VssRayContainer::const_iterator vit, vit_end = mVssRays.end();
356        for (vit = mVssRays.begin(); vit != vit_end; ++ vit)
357        {
358                VssRay *ray = *vit;
359                ray->Unref();
360
361                if (!ray->IsActive())
362                        delete ray;
363        }
364        //CLEAR_CONTAINER(mVssRays);
365}
366
367
368int VspLeaf::Type() const
369{
370        return Leaf;
371}
372
373
374VspLeaf::VspLeaf(ViewCellLeaf *viewCell):
375mViewCell(viewCell)
376{
377}
378
379
380VspLeaf::VspLeaf(VspInterior *parent):
381VspNode(parent), mViewCell(NULL)
382//, mPvs(NULL)
383{}
384
385
386VspLeaf::VspLeaf(VspInterior *parent, ViewCellLeaf *viewCell):
387VspNode(parent), mViewCell(viewCell)
388//, mPvs(NULL)
389{
390}
391
392
393ViewCellLeaf *VspLeaf::GetViewCell() const
394{
395        return mViewCell;
396}
397
398
399void VspLeaf::SetViewCell(ViewCellLeaf *viewCell)
400{
401        mViewCell = viewCell;
402}
403
404
405bool VspLeaf::IsLeaf() const
406{
407        return true;
408}
409
410
411
412/*************************************************************************/
413/*                       class VspTree implementation                    */
414/*************************************************************************/
415
416
417VspTree::VspTree():
418mRoot(NULL),
419mOutOfBoundsCell(NULL),
420mStoreRays(false),
421mTimeStamp(1),
422mHierarchyManager(NULL)
423{
424        mLocalSubdivisionCandidates = new vector<SortableEntry>;
425
426        bool randomize = false;
427        Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize);
428        if (randomize)
429                Randomize(); // initialise random generator for heuristics
430
431        char subdivisionStatsLog[100];
432        Environment::GetSingleton()->GetStringValue("VspTree.subdivisionStats", subdivisionStatsLog);
433        mSubdivisionStats.open(subdivisionStatsLog);
434
435        /////////////
436        //-- termination criteria for autopartition
437
438        Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxDepth", mTermMaxDepth);
439        Environment::GetSingleton()->GetIntValue("VspTree.Termination.minPvs", mTermMinPvs);
440        Environment::GetSingleton()->GetIntValue("VspTree.Termination.minRays", mTermMinRays);
441        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minProbability", mTermMinProbability);
442        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxRayContribution", mTermMaxRayContribution);
443       
444        Environment::GetSingleton()->GetIntValue("VspTree.Termination.missTolerance", mTermMissTolerance);
445        Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxViewCells", mMaxViewCells);
446        // max cost ratio for early tree termination
447        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxCostRatio", mTermMaxCostRatio);
448
449        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
450        Environment::GetSingleton()->GetIntValue("VspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
451
452        Environment::GetSingleton()->GetFloatValue("VspTree.maxStaticMemory", mMaxMemory);
453
454
455        //////////////
456        //-- factors for bsp tree split plane heuristics
457
458        Environment::GetSingleton()->GetFloatValue("VspTree.Termination.ct_div_ci", mCtDivCi);
459        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.epsilon", mEpsilon);
460        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.minBand", mMinBand);
461        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.maxBand", mMaxBand);
462        Environment::GetSingleton()->GetIntValue("VspTree.maxTests", mMaxTests);
463
464        Environment::GetSingleton()->GetFloatValue("VspTree.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
465       
466        // if only the driving axis is used for axis aligned split
467        Environment::GetSingleton()->GetBoolValue("VspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
468        Environment::GetSingleton()->GetBoolValue("VspTree.useCostHeuristics", mUseCostHeuristics);
469        Environment::GetSingleton()->GetBoolValue("VspTree.simulateOctree", mCirculatingAxis);
470
471        //mMemoryConst = (float)(sizeof(VspLeaf) + sizeof(VspViewCell));
472        //mMemoryConst = 50;//(float)(sizeof(VspViewCell));
473
474        //mMemoryConst = (float)(sizeof(VspLeaf) + sizeof(ObjectPvs));
475        mMemoryConst = 16;//(float)sizeof(ObjectPvs);
476        cout << "vsp memcost: " << mMemoryConst << endl;
477
478        //////////////
479        //-- debug output
480
481        Debug << "******* VSP options ******** " << endl;
482
483    Debug << "max depth: " << mTermMaxDepth << endl;
484        Debug << "min PVS: " << mTermMinPvs << endl;
485        Debug << "min probabiliy: " << mTermMinProbability << endl;
486        Debug << "min rays: " << mTermMinRays << endl;
487        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
488        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
489        Debug << "miss tolerance: " << mTermMissTolerance << endl;
490        Debug << "max view cells: " << mMaxViewCells << endl;
491        Debug << "randomize: " << randomize << endl;
492
493        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
494        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
495        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
496        Debug << "max memory: " << mMaxMemory << endl;
497        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
498        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
499        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
500
501        Debug << "circulating axis: " << mCirculatingAxis << endl;
502        Debug << "minband: " << mMinBand << endl;
503        Debug << "maxband: " << mMaxBand << endl;
504
505        Debug << "vsp mem const: " << mMemoryConst << endl;
506
507        cout << "use cost heuristics: " << mUseCostHeuristics << endl;
508
509        Debug << endl;
510}
511
512
513VspViewCell *VspTree::GetOutOfBoundsCell()
514{
515        return mOutOfBoundsCell;
516}
517
518
519VspViewCell *VspTree::GetOrCreateOutOfBoundsCell()
520{
521        if (!mOutOfBoundsCell)
522        {
523                mOutOfBoundsCell = new VspViewCell();
524                mOutOfBoundsCell->SetId(-1);
525                mOutOfBoundsCell->SetValid(false);
526        }
527
528        return mOutOfBoundsCell;
529}
530
531
532const VspTreeStatistics &VspTree::GetStatistics() const
533{
534        return mVspStats;
535}
536
537
538VspTree::~VspTree()
539{
540        DEL_PTR(mRoot);
541        DEL_PTR(mLocalSubdivisionCandidates);
542}
543
544
545void VspTree::ComputeBoundingBox(const VssRayContainer &rays,
546                                                                 AxisAlignedBox3 *forcedBoundingBox)
547{       
548        if (forcedBoundingBox)
549        {
550                mBoundingBox = *forcedBoundingBox;
551                return;
552        }
553       
554        //////////////////////////////////////////////
555        // bounding box of view space includes all visibility events
556        mBoundingBox.Initialize();
557        VssRayContainer::const_iterator rit, rit_end = rays.end();
558
559        for (rit = rays.begin(); rit != rit_end; ++ rit)
560        {
561                VssRay *ray = *rit;
562
563                mBoundingBox.Include(ray->GetTermination());
564                mBoundingBox.Include(ray->GetOrigin());
565        }
566}
567
568
569void VspTree::AddSubdivisionStats(const int viewCells,
570                                                                  const float renderCostDecr,
571                                                                  const float totalRenderCost,
572                                                                  const float avgRenderCost)
573{
574        mSubdivisionStats
575                        << "#ViewCells\n" << viewCells << endl
576                        << "#RenderCostDecrease\n" << renderCostDecr << endl
577                        << "#TotalRenderCost\n" << totalRenderCost << endl
578                        << "#AvgRenderCost\n" << avgRenderCost << endl;
579}
580
581
582// $$matt temporary: number of rayrefs + pvs should be in there, but
583// commented out for testing
584float VspTree::GetMemUsage() const
585{
586        return (float)
587                 (sizeof(VspTree)
588                  + mVspStats.Leaves() * sizeof(VspLeaf)
589                  + mVspStats.Leaves() * sizeof(VspViewCell)
590                  + mVspStats.Interior() * sizeof(VspInterior)
591                  //+ mVspStats.pvs * sizeof(PvsData)
592                  //+ mVspStats.rayRefs * sizeof(RayInfo)
593                  ) / (1024.0f * 1024.0f);
594}
595
596
597inline bool VspTree::LocalTerminationCriteriaMet(const VspTraversalData &data) const
598{
599        const bool localTerminationCriteriaMet = (0
600                || ((int)data.mRays->size() <= mTermMinRays)
601                || (data.mPvs <= mTermMinPvs)
602                || (data.mProbability <= mTermMinProbability)
603                //|| (data.GetAvgRayContribution() > mTermMaxRayContribution)
604                || (data.mDepth >= mTermMaxDepth)
605                );
606
607#if GTP_DEBUG
608        if (localTerminationCriteriaMet)
609        {
610                Debug << "local termination criteria met:" << endl;
611                Debug << "rays: " << (int)data.mRays->size() << "  " << mTermMinRays << endl;
612                Debug << "pvs: " << data.mPvs << " " << mTermMinPvs << endl;
613                Debug << "p: " <<  data.mProbability << " " << mTermMinProbability << endl;
614                Debug << "avg contri: " << data.GetAvgRayContribution() << " " << mTermMaxRayContribution << endl;
615                Debug << "depth " << data.mDepth << " " << mTermMaxDepth << endl;
616        }
617#endif
618        return localTerminationCriteriaMet;             
619}
620
621
622inline bool VspTree::GlobalTerminationCriteriaMet(const VspTraversalData &data) const
623{
624        // note: to track for global cost misses does not really
625        // make sense because cost termination  happens in the hierarchy mananger
626
627        const bool terminationCriteriaMet = (0
628                // || mOutOfMemory
629                || (mVspStats.Leaves() >= mMaxViewCells)
630                // || (mVspStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
631                );
632
633#if GTP_DEBUG
634        if (terminationCriteriaMet)
635        {
636                Debug << "vsp global termination criteria met:" << endl;
637                Debug << "cost misses: " << mVspStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
638                Debug << "leaves: " << mVspStats.Leaves() << " " <<  mMaxViewCells << endl;
639        }
640#endif
641
642        return terminationCriteriaMet;
643}
644
645
646void VspTree::CreateViewCell(VspTraversalData &tData, const bool updatePvs)
647{
648        ///////////////
649        //-- create new view cell
650
651        VspLeaf *leaf = tData.mNode;
652
653        VspViewCell *viewCell = new VspViewCell();
654    leaf->SetViewCell(viewCell);
655       
656        int conSamp = 0;
657        float sampCon = 0.0f;
658
659        if (updatePvs)
660        {
661                // update pvs of view cell
662                AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp);
663
664                // update scalar pvs size value
665                ObjectPvs &pvs = viewCell->GetPvs();
666                mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.EvalPvsCost(), pvs.GetSize());
667
668                mVspStats.contributingSamples += conSamp;
669                mVspStats.sampleContributions += (int)sampCon;
670        }
671
672        if (mStoreRays)
673        {
674                ///////////
675                //-- store sampling rays
676
677        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
678
679                for (it = tData.mRays->begin(); it != it_end; ++ it)
680                {
681                        (*it).mRay->Ref();                     
682                        // note: should rather store rays with view cell
683                        leaf->mVssRays.push_back((*it).mRay);
684                }
685        }
686               
687        // set view cell values
688        viewCell->mLeaves.push_back(leaf);
689
690        viewCell->SetVolume(tData.mProbability);
691    leaf->mProbability = tData.mProbability;
692}
693
694
695void VspTree::EvalSubdivisionStats(const SubdivisionCandidate &sc)
696{
697        const float costDecr = sc.GetRenderCostDecrease();
698       
699        AddSubdivisionStats(mVspStats.Leaves(),
700                                                costDecr,
701                                                mTotalCost,
702                                                (float)mTotalPvsSize / (float)mVspStats.Leaves());
703}
704
705
706VspNode *VspTree::Subdivide(SplitQueue &tQueue,
707                                                        SubdivisionCandidate *splitCandidate,
708                                                        const bool globalCriteriaMet)
709{
710        // todo remove dynamic cast
711        VspSubdivisionCandidate *sc =
712                dynamic_cast<VspSubdivisionCandidate *>(splitCandidate);
713
714        VspTraversalData &tData = sc->mParentData;
715        VspNode *newNode = tData.mNode;
716
717        if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet)
718        {       
719                ///////////
720                //-- continue subdivision
721
722                VspTraversalData tFrontData;
723                VspTraversalData tBackData;
724               
725                // create new interior node and two leaf node
726                const AxisAlignedPlane splitPlane = sc->mSplitPlane;
727                const int maxCostMisses = sc->GetMaxCostMisses();
728
729                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData);
730       
731                // how often was max cost ratio missed in this branch?
732                tFrontData.mMaxCostMisses = maxCostMisses;
733                tBackData.mMaxCostMisses = maxCostMisses;
734                       
735                mTotalCost -= sc->GetRenderCostDecrease();
736                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
737                mPvsEntries += sc->GetPvsEntriesIncr();
738
739                // subdivision statistics
740                if (1) EvalSubdivisionStats(*sc);
741               
742                /////////////
743                //-- evaluate new split candidates for global greedy cost heuristics
744
745                VspSubdivisionCandidate *frontCandidate = new VspSubdivisionCandidate(tFrontData);
746                VspSubdivisionCandidate *backCandidate = new VspSubdivisionCandidate(tBackData);
747
748                EvalSubdivisionCandidate(*frontCandidate);
749                EvalSubdivisionCandidate(*backCandidate);
750
751                // cross reference
752                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
753                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
754
755                tQueue.Push(frontCandidate);
756                tQueue.Push(backCandidate);
757
758                // note: leaf is not destroyed because it is needed to collect
759                // dirty candidates in hierarchy manager
760        }
761
762        if (newNode->IsLeaf()) // subdivision terminated
763        {
764                VspLeaf *leaf = dynamic_cast<VspLeaf *>(newNode);
765               
766#if 0
767        /////////////
768                //-- store pvs optained from rays
769
770                // view cell is created during subdivision
771                ViewCell *viewCell = leaf->GetViewCell();
772
773                int conSamp = 0;
774                float sampCon = 0.0f;
775
776                AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp);
777
778                // update scalar pvs size value
779                ObjectPvs &pvs = viewCell->GetPvs();
780                mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.EvalPvsCost(), pvs.GetSize());
781
782                mVspStats.contributingSamples += conSamp;
783                mVspStats.sampleContributions += (int)sampCon;
784#endif
785                if (mStoreRays)
786                {
787                        //////////
788                        //-- store rays piercing this view cell
789                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
790                        for (it = tData.mRays->begin(); it != it_end; ++ it)
791                        {
792                                (*it).mRay->Ref();                     
793                                leaf->mVssRays.push_back((*it).mRay);
794                                //leaf->mVssRays.push_back(new VssRay(*(*it).mRay));
795                        }
796                }
797
798                // finally evaluate statistics for this leaf
799                EvaluateLeafStats(tData);
800                // detach subdivision candidate: this leaf is no candidate for
801                // splitting anymore
802                tData.mNode->SetSubdivisionCandidate(NULL);
803                // detach node so it won't get deleted
804                tData.mNode = NULL;
805        }
806
807        return newNode;
808}
809
810
811void VspTree::EvalSubdivisionCandidate(VspSubdivisionCandidate &splitCandidate,
812                                                                           bool computeSplitPlane)
813{
814        if (computeSplitPlane)
815        {
816                float frontProb;
817                float backProb;
818
819                // compute locally best split plane
820                const float ratio = SelectSplitPlane(splitCandidate.mParentData,
821                                                                                         splitCandidate.mSplitPlane,
822                                                                                         frontProb,
823                                                                                         backProb);
824       
825                const bool maxCostRatioViolated = mTermMaxCostRatio < ratio;
826
827                const int maxCostMisses = splitCandidate.mParentData.mMaxCostMisses;
828                // max cost threshold violated?
829                splitCandidate.SetMaxCostMisses(maxCostRatioViolated  ? maxCostMisses + 1: maxCostMisses);
830        }
831       
832        VspLeaf *leaf = dynamic_cast<VspLeaf *>(splitCandidate.mParentData.mNode);
833       
834        // compute global decrease in render cost
835        float oldRenderCost;
836        const float renderCostDecr = EvalRenderCostDecrease(splitCandidate.mSplitPlane,
837                                                                                                                splitCandidate.mParentData,
838                                                                                                                oldRenderCost);
839
840        splitCandidate.SetRenderCostDecrease(renderCostDecr);
841
842        // the increase in pvs entries num induced by this split
843        const int pvsEntriesIncr = EvalPvsEntriesIncr(splitCandidate);
844        splitCandidate.SetPvsEntriesIncr(pvsEntriesIncr);
845
846        // take render cost of node into account
847        // otherwise danger of being stuck in a local minimum!
848        const float factor = mRenderCostDecreaseWeight;
849
850        float priority;
851
852        if (1)
853        {
854                priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
855                if (mHierarchyManager->mConsiderMemory)
856                {
857                        priority /= ((float)splitCandidate.GetPvsEntriesIncr() + mMemoryConst);
858                }
859        }
860        else
861        {
862                if (!mHierarchyManager->mConsiderMemory)
863                {
864                        priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
865                }
866                else
867                {
868                        const float ratio =
869                                renderCostDecr / ((float)splitCandidate.GetPvsEntriesIncr() + mMemoryConst);
870
871                        priority = factor * ratio + (1.0f - factor) * oldRenderCost;
872                }
873        }
874
875        splitCandidate.SetPriority(priority);
876}
877
878
879int VspTree::EvalPvsEntriesIncr(VspSubdivisionCandidate &splitCandidate) const
880{
881        float oldPvsSize = 0;
882        float fPvsSize = 0;
883        float bPvsSize = 0;
884       
885        const AxisAlignedPlane candidatePlane = splitCandidate.mSplitPlane;
886       
887        Intersectable::NewMail(3);
888        KdLeaf::NewMail(3);
889        BvhLeaf::NewMail(3);
890
891        RayInfoContainer::const_iterator rit, rit_end = splitCandidate.mParentData.mRays->end();
892
893    // this is the main ray classification loop!
894        for(rit = splitCandidate.mParentData.mRays->begin(); rit != rit_end; ++ rit)
895        {
896                VssRay *ray = (*rit).mRay;
897                RayInfo rayInf = *rit;
898               
899                float t;
900                // classify ray
901                const int cf =  rayInf.ComputeRayIntersection(candidatePlane.mAxis,
902                                                                                                          candidatePlane.mPosition, t);
903
904                UpdatePvsEntriesContribution(*ray, true, cf, fPvsSize, bPvsSize, oldPvsSize);
905#if COUNT_ORIGIN_OBJECTS
906                UpdatePvsEntriesContribution(*ray, false, cf, fPvsSize, bPvsSize, oldPvsSize);
907#endif
908        }
909
910        return (int)(fPvsSize + bPvsSize - oldPvsSize);
911}
912
913
914VspInterior *VspTree::SubdivideNode(const AxisAlignedPlane &splitPlane,
915                                                                        VspTraversalData &tData,
916                                                                        VspTraversalData &frontData,
917                                                                        VspTraversalData &backData)
918{
919        VspLeaf *leaf = dynamic_cast<VspLeaf *>(tData.mNode);
920       
921        ///////////////
922        //-- new traversal values
923
924        frontData.mDepth = tData.mDepth + 1;
925        backData.mDepth = tData.mDepth + 1;
926
927        frontData.mRays = new RayInfoContainer();
928        backData.mRays = new RayInfoContainer();
929
930        //-- subdivide rays
931        SplitRays(splitPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
932
933        //-- compute pvs
934        frontData.mPvs = EvalPvsSize(*frontData.mRays);
935        backData.mPvs = EvalPvsSize(*backData.mRays);
936               
937        //-- split front and back node geometry and compute area
938        tData.mBoundingBox.Split(splitPlane.mAxis,
939                                                         splitPlane.mPosition,
940                                                         frontData.mBoundingBox,
941                                                         backData.mBoundingBox);
942
943        frontData.mProbability = frontData.mBoundingBox.GetVolume();
944        backData.mProbability = tData.mProbability - frontData.mProbability;
945
946
947        ////////
948        //-- update some stats
949       
950        if (tData.mDepth > mVspStats.maxDepth)
951        {       
952                mVspStats.maxDepth = tData.mDepth;
953        }
954
955        // two more leaves per split
956        mVspStats.nodes += 2;
957        // and a new split
958        ++ mVspStats.splits[splitPlane.mAxis];
959
960
961        ////////////////
962        //-- create front and back and subdivide further
963
964        VspInterior *interior = new VspInterior(splitPlane);
965        VspInterior *parent = leaf->GetParent();
966
967        // replace a link from node's parent
968        if (parent)
969        {
970                parent->ReplaceChildLink(leaf, interior);
971                interior->SetParent(parent);
972#if WORK_WITH_VIEWCELLS
973                // remove "parent" view cell from pvs of all objects (traverse trough rays)
974                RemoveParentViewCellReferences(tData.mNode->GetViewCell());
975#endif
976        }
977        else // new root
978        {
979                mRoot = interior;
980        }
981
982        VspLeaf *frontLeaf = new VspLeaf(interior);
983        VspLeaf *backLeaf = new VspLeaf(interior);
984
985        // and setup child links
986        interior->SetupChildLinks(frontLeaf, backLeaf);
987       
988        // add bounding box
989        interior->SetBoundingBox(tData.mBoundingBox);
990
991        // set front and back leaf
992        frontData.mNode = frontLeaf;
993        backData.mNode = backLeaf;
994
995        // create front and back view cell for the new leaves
996        CreateViewCell(frontData, false);
997        CreateViewCell(backData, false);
998
999        // set the time stamp so the order of traversal can be reconstructed
1000        interior->mTimeStamp = mHierarchyManager->mTimeStamp ++;
1001
1002#if WORK_WITH_VIEWCELL_PVS
1003        // create front and back view cell
1004        // add front and back view cell to
1005        // "potentially visible view cells"
1006        // of the objects in front and back pvs
1007
1008        AddViewCellReferences(frontLeaf->GetViewCell());
1009        AddViewCellReferences(backLeaf->GetViewCell());
1010#endif
1011
1012        return interior;
1013}
1014
1015
1016void VspTree::AddSamplesToPvs(VspLeaf *leaf,
1017                                                          const RayInfoContainer &rays,
1018                                                          float &sampleContributions,
1019                                                          int &contributingSamples)
1020{
1021        sampleContributions = 0;
1022        contributingSamples = 0;
1023 
1024        RayInfoContainer::const_iterator it, it_end = rays.end();
1025 
1026        ViewCellLeaf *vc = leaf->GetViewCell();
1027
1028        // add contributions from samples to the pvs
1029        for (it = rays.begin(); it != it_end; ++ it)
1030        {
1031                float sc = 0.0f;
1032                VssRay *ray = (*it).mRay;
1033
1034                bool madeContrib = false;
1035                float contribution = 1;
1036
1037                Intersectable *entry =
1038                        mHierarchyManager->GetIntersectable(ray->mTerminationObject, true);
1039
1040                if (entry)
1041                {
1042                        madeContrib =
1043                                vc->GetPvs().AddSample(entry, ray->mPdf);
1044
1045                        sc += contribution;
1046                }
1047#if COUNT_ORIGIN_OBJECTS
1048                entry = mHierarchyManager->GetIntersectable(ray->mOriginObject, true);
1049
1050                if (entry)
1051                {
1052                        madeContrib =
1053                                vc->GetPvs().AddSample(entry, ray->mPdf);
1054
1055                        sc += contribution;
1056                }
1057#endif
1058                if (madeContrib)
1059                {
1060                        ++ contributingSamples;
1061                }
1062
1063                // store rays for visualization
1064                if (0) leaf->mVssRays.push_back(new VssRay(*ray));
1065        }
1066}
1067
1068
1069void VspTree::SortSubdivisionCandidates(const RayInfoContainer &rays,
1070                                                                  const int axis,
1071                                                                  float minBand,
1072                                                                  float maxBand)
1073{
1074        mLocalSubdivisionCandidates->clear();
1075
1076        const int requestedSize = 2 * (int)(rays.size());
1077
1078        // creates a sorted split candidates array
1079        if (mLocalSubdivisionCandidates->capacity() > 500000 &&
1080                requestedSize < (int)(mLocalSubdivisionCandidates->capacity() / 10) )
1081        {
1082        delete mLocalSubdivisionCandidates;
1083                mLocalSubdivisionCandidates = new vector<SortableEntry>;
1084        }
1085
1086        mLocalSubdivisionCandidates->reserve(requestedSize);
1087
1088        float pos;
1089        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1090
1091        const bool delayMinEvent = false;
1092
1093        ////////////
1094        //-- insert all queries
1095        for (rit = rays.begin(); rit != rit_end; ++ rit)
1096        {
1097                const bool positive = (*rit).mRay->HasPosDir(axis);
1098               
1099                // origin point
1100                pos = (*rit).ExtrapOrigin(axis);
1101                const int oType = positive ? SortableEntry::ERayMin : SortableEntry::ERayMax;
1102
1103                if (delayMinEvent && oType == SortableEntry::ERayMin)
1104                        pos += mEpsilon; // could be useful feature for walls
1105
1106                mLocalSubdivisionCandidates->push_back(SortableEntry(oType, pos, (*rit).mRay));
1107
1108                // termination point
1109                pos = (*rit).ExtrapTermination(axis);
1110                const int tType = positive ? SortableEntry::ERayMax : SortableEntry::ERayMin;
1111
1112                if (delayMinEvent && tType == SortableEntry::ERayMin)
1113                        pos += mEpsilon; // could be useful feature for walls
1114
1115                mLocalSubdivisionCandidates->push_back(SortableEntry(tType, pos, (*rit).mRay));
1116        }
1117
1118        stable_sort(mLocalSubdivisionCandidates->begin(), mLocalSubdivisionCandidates->end());
1119}
1120
1121
1122int VspTree::PrepareHeuristics(KdLeaf *leaf)
1123{       
1124        int pvsSize = 0;
1125       
1126        if (!leaf->Mailed())
1127        {
1128                leaf->Mail();
1129                leaf->mCounter = 1;
1130                // add objects without the objects which are in several kd leaves
1131                pvsSize += (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
1132        }
1133        else
1134        {
1135                ++ leaf->mCounter;
1136        }
1137
1138        //-- the objects belonging to several leaves must be handled seperately
1139        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1140
1141        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1142        {
1143                Intersectable *object = *oit;
1144                                               
1145                if (!object->Mailed())
1146                {
1147                        object->Mail();
1148                        object->mCounter = 1;
1149
1150                        ++ pvsSize;
1151                }
1152                else
1153                {
1154                        ++ object->mCounter;
1155                }
1156        }
1157       
1158        return pvsSize;
1159}
1160
1161
1162int VspTree::PrepareHeuristics(const RayInfoContainer &rays)
1163{       
1164        Intersectable::NewMail();
1165        KdNode::NewMail();
1166        BvhLeaf::NewMail();
1167
1168        int pvsSize = 0;
1169
1170        RayInfoContainer::const_iterator ri, ri_end = rays.end();
1171
1172    // set all kd nodes / objects as belonging to the front pvs
1173        for (ri = rays.begin(); ri != ri_end; ++ ri)
1174        {
1175                VssRay *ray = (*ri).mRay;
1176               
1177                pvsSize += PrepareHeuristics(*ray, true);
1178#if COUNT_ORIGIN_OBJECTS
1179                pvsSize += PrepareHeuristics(*ray, false);
1180#endif
1181        }
1182
1183        return pvsSize;
1184}
1185
1186
1187int VspTree::EvalMaxEventContribution(KdLeaf *leaf) const
1188{
1189        int pvs = 0;
1190
1191        // leaf falls out of right pvs
1192        if (-- leaf->mCounter == 0)
1193        {
1194                pvs -= ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size());
1195        }
1196
1197        //-- separately handle objects which are in several kd leaves
1198
1199        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1200
1201        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1202        {
1203                Intersectable *object = *oit;
1204
1205                if (-- object->mCounter == 0)
1206                {
1207                        ++ pvs;
1208                }
1209        }
1210
1211        return pvs;
1212}
1213
1214
1215int VspTree::EvalMinEventContribution(KdLeaf *leaf) const
1216{
1217        if (leaf->Mailed())
1218                return 0;
1219       
1220        leaf->Mail();
1221
1222        // add objects without those which are part of several kd leaves
1223        int pvs = ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size());
1224
1225        // separately handle objects which are part of several kd leaves
1226        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1227
1228        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1229        {
1230                Intersectable *object = *oit;
1231
1232                // object not previously in pvs
1233                if (!object->Mailed())
1234                {
1235                        object->Mail();
1236                        ++ pvs;
1237                }
1238        }       
1239
1240        return pvs;
1241}
1242
1243
1244void VspTree::EvalHeuristics(const SortableEntry &ci,
1245                                                         int &pvsLeft,
1246                                                         int &pvsRight) const
1247{
1248        VssRay *ray = ci.ray;
1249
1250        // eval changes in pvs causes by min event
1251        if (ci.type == SortableEntry::ERayMin)
1252        {
1253#if COUNT_ORIGIN_OBJECTS
1254                pvsLeft += EvalMinEventContribution(*ray, true);
1255#else
1256                pvsLeft += EvalMinEventContribution(*ray, false);
1257#endif
1258        }
1259        else // eval changes in pvs causes by max event
1260        {
1261#if COUNT_ORIGIN_OBJECTS
1262                pvsRight -= EvalMaxEventContribution(*ray, true);
1263#else
1264                pvsRight -= EvalMaxEventContribution(*ray, false);
1265#endif
1266        }
1267}
1268
1269
1270float VspTree::EvalLocalCostHeuristics(const VspTraversalData &tData,
1271                                                                           const AxisAlignedBox3 &box,
1272                                                                           const int axis,
1273                                                                           float &position)
1274{
1275        // get subset of rays
1276        RayInfoContainer randomRays;
1277        randomRays.reserve(mMaxTests);
1278
1279        RayInfoContainer *usedRays;
1280
1281        if (mMaxTests < (int)tData.mRays->size())
1282        {
1283                GetRayInfoSets(*tData.mRays, mMaxTests, randomRays);
1284                usedRays = &randomRays;
1285        }
1286        else
1287        {
1288                usedRays = tData.mRays;
1289        }
1290
1291        const float minBox = box.Min(axis);
1292        const float maxBox = box.Max(axis);
1293
1294        const float sizeBox = maxBox - minBox;
1295
1296        const float minBand = minBox + mMinBand * sizeBox;
1297        const float maxBand = minBox + mMaxBand * sizeBox;
1298
1299        SortSubdivisionCandidates(*usedRays, axis, minBand, maxBand);
1300
1301        // prepare the sweep
1302        // note: returns pvs size => no need t give pvs size as function parameter
1303        const int pvsSize = PrepareHeuristics(*usedRays);
1304
1305        // go through the lists, count the number of objects left and right
1306        // and evaluate the following cost funcion:
1307        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1308
1309        int pvsl = 0;
1310        int pvsr = pvsSize;
1311
1312        int pvsBack = pvsl;
1313        int pvsFront = pvsr;
1314
1315        float sum = (float)pvsSize * sizeBox;
1316        float minSum = 1e20f;
1317
1318        // if no good split can be found, take mid split
1319        position = minBox + 0.5f * sizeBox;
1320       
1321        // the relative cost ratio
1322        float ratio = 99999999.0f;
1323        bool splitPlaneFound = false;
1324
1325        Intersectable::NewMail();
1326        KdLeaf::NewMail();
1327        BvhLeaf::NewMail();
1328
1329        //-- traverse through visibility events
1330        vector<SortableEntry>::const_iterator ci, ci_end = mLocalSubdivisionCandidates->end();
1331
1332#ifdef GTPGTP_DEBUG
1333        const float volRatio = tData.mBoundingBox.GetVolume() / (sizeBox * mBoundingBox.GetVolume());
1334        const int leaves = mVspStats.Leaves();
1335        const bool printStats = ((axis == 0) && (leaves > 0) && (leaves < 90));
1336       
1337        ofstream sumStats;
1338        ofstream pvslStats;
1339        ofstream pvsrStats;
1340
1341        if (printStats)
1342        {
1343                char str[64];
1344               
1345                sprintf(str, "tmp/vsp_heur_sum-%04d.log", leaves);
1346                sumStats.open(str);
1347                sprintf(str, "tmp/vsp_heur_pvsl-%04d.log", leaves);
1348                pvslStats.open(str);
1349                sprintf(str, "tmp/vsp_heur_pvsr-%04d.log", leaves);
1350                pvsrStats.open(str);
1351        }
1352
1353#endif
1354        for (ci = mLocalSubdivisionCandidates->begin(); ci != ci_end; ++ ci)
1355        {
1356                // compute changes to front and back pvs
1357                EvalHeuristics(*ci, pvsl, pvsr);
1358
1359                // Note: sufficient to compare size of bounding boxes of front and back side?
1360                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
1361                {
1362                        float currentPos;
1363                       
1364                        // HACK: current positition is BETWEEN visibility events
1365                        if (0 && ((ci + 1) != ci_end))
1366                                currentPos = ((*ci).value + (*(ci + 1)).value) * 0.5f;
1367                        else
1368                                currentPos = (*ci).value;                       
1369
1370                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
1371                       
1372#ifdef GTPGTP_DEBUG
1373                        if (printStats)
1374                        {
1375                                sumStats
1376                                        << "#Position\n" << currentPos << endl
1377                                        << "#Sum\n" << sum * volRatio << endl
1378                                        << "#Pvs\n" << pvsl + pvsr << endl;
1379
1380                                pvslStats
1381                                        << "#Position\n" << currentPos << endl
1382                                        << "#Pvsl\n" << pvsl << endl;
1383
1384                                pvsrStats
1385                                        << "#Position\n" << currentPos << endl
1386                                        << "#Pvsr\n" << pvsr << endl;
1387                        }
1388#endif
1389
1390                        if (sum < minSum)
1391                        {
1392                                splitPlaneFound = true;
1393
1394                                minSum = sum;
1395                                position = currentPos;
1396                               
1397                                pvsBack = pvsl;
1398                                pvsFront = pvsr;
1399                        }
1400                }
1401        }
1402       
1403        /////////       
1404        //-- compute cost
1405
1406        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1407        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1408
1409        const float pOverall = sizeBox;
1410        const float pBack = position - minBox;
1411        const float pFront = maxBox - position;
1412
1413        const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit);
1414    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1415        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1416       
1417        const float oldRenderCost = penaltyOld * pOverall + Limits::Small;
1418        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1419
1420        if (splitPlaneFound)
1421        {
1422                ratio = newRenderCost / oldRenderCost;
1423        }
1424       
1425#ifdef GTPGTP_DEBUG
1426        Debug << "\n§§§§ eval local cost §§§§" << endl
1427                  << "back pvs: " << penaltyBack << " front pvs: " << penaltyFront << " total pvs: " << penaltyOld << endl
1428                  << "back p: " << pBack * volRatio << " front p " << pFront * volRatio << " p: " << pOverall * volRatio << endl
1429                  << "old rc: " << oldRenderCost * volRatio << " new rc: " << newRenderCost * volRatio << endl
1430                  << "render cost decrease: " << oldRenderCost * volRatio - newRenderCost * volRatio << endl;
1431#endif
1432        return ratio;
1433}
1434
1435
1436float VspTree::SelectSplitPlane(const VspTraversalData &tData,
1437                                                                AxisAlignedPlane &plane,
1438                                                                float &pFront,
1439                                                                float &pBack)
1440{
1441        float nPosition[3];
1442        float nCostRatio[3];
1443        float nProbFront[3];
1444        float nProbBack[3];
1445
1446        // create bounding box of node geometry
1447        AxisAlignedBox3 box = tData.mBoundingBox;
1448               
1449        int sAxis = 0;
1450        int bestAxis = -1;
1451
1452        // do we use some kind of specialised "fixed" axis?
1453    const bool useSpecialAxis =
1454                mOnlyDrivingAxis || mCirculatingAxis;
1455       
1456        if (mCirculatingAxis)
1457        {
1458                int parentAxis = 0;
1459                VspNode *parent = tData.mNode->GetParent();
1460
1461                if (parent)
1462                        parentAxis = dynamic_cast<VspInterior *>(parent)->GetAxis();
1463
1464                sAxis = (parentAxis + 1) % 3;
1465        }
1466        else if (mOnlyDrivingAxis)
1467        {
1468                sAxis = box.Size().DrivingAxis();
1469        }
1470       
1471        for (int axis = 0; axis < 3; ++ axis)
1472        {
1473                if (!useSpecialAxis || (axis == sAxis))
1474                {
1475                        if (mUseCostHeuristics)
1476                        {
1477                                //-- place split plane using heuristics
1478                                nCostRatio[axis] =
1479                                        EvalLocalCostHeuristics(tData,
1480                                                                                        box,
1481                                                                                        axis,
1482                                                                                        nPosition[axis]);                       
1483                        }
1484                        else
1485                        {
1486                                //-- split plane position is spatial median                             
1487                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1488                                nCostRatio[axis] = EvalLocalSplitCost(tData,
1489                                                                                                          box,
1490                                                                                                          axis,
1491                                                                                                          nPosition[axis],
1492                                                                                                          nProbFront[axis],
1493                                                                                                          nProbBack[axis]);
1494                        }
1495                                               
1496                        if (bestAxis == -1)
1497                        {
1498                                bestAxis = axis;
1499                        }
1500                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
1501                        {
1502                                bestAxis = axis;
1503                        }
1504                }
1505        }
1506
1507        ////////////////////////////////
1508        //-- assign values of best split
1509
1510        plane.mAxis = bestAxis;
1511        // best split plane position
1512        plane.mPosition = nPosition[bestAxis];
1513
1514        pFront = nProbFront[bestAxis];
1515        pBack = nProbBack[bestAxis];
1516
1517        return nCostRatio[bestAxis];
1518}
1519
1520
1521float VspTree::EvalRenderCostDecrease(const AxisAlignedPlane &candidatePlane,
1522                                                                          const VspTraversalData &data,
1523                                                                          float &normalizedOldRenderCost) const
1524{
1525        float pvsFront = 0;
1526        float pvsBack = 0;
1527        float totalPvs = 0;
1528
1529        const float viewSpaceVol = mBoundingBox.GetVolume();
1530
1531        //////////////////////////////////////////////
1532        // mark objects in the front / back / both using mailboxing
1533        // then count pvs sizes
1534
1535        Intersectable::NewMail(3);
1536        KdLeaf::NewMail(3);
1537        BvhLeaf::NewMail(3);
1538
1539        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1540
1541        for (rit = data.mRays->begin(); rit != rit_end; ++ rit)
1542        {
1543                RayInfo rayInf = *rit;
1544
1545                float t;
1546               
1547                // classify ray
1548                const int cf = rayInf.ComputeRayIntersection(candidatePlane.mAxis,
1549                                                                                                         candidatePlane.mPosition,
1550                                                                                                         t);
1551
1552                VssRay *ray = rayInf.mRay;
1553
1554                // evaluate contribution of ray endpoint to front
1555                // and back pvs with respect to the classification
1556                UpdateContributionsToPvs(*ray, true, cf, pvsFront, pvsBack, totalPvs);
1557#if COUNT_ORIGIN_OBJECTS
1558                UpdateContributionsToPvs(*ray, false, cf, pvsFront, pvsBack, totalPvs);
1559#endif
1560        }
1561   
1562        AxisAlignedBox3 frontBox;
1563        AxisAlignedBox3 backBox;
1564
1565        data.mBoundingBox.Split(candidatePlane.mAxis, candidatePlane.mPosition, frontBox, backBox);
1566
1567        // probability that view point lies in back / front node
1568        float pOverall = data.mProbability;
1569        float pFront = pFront = frontBox.GetVolume();
1570        float pBack = pOverall - pFront;
1571
1572
1573        ////////////////////////////////////
1574        //-- evaluate render cost heuristics
1575
1576        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1577        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1578
1579        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
1580    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
1581        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
1582                       
1583        const float oldRenderCost = pOverall * penaltyOld;
1584        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1585
1586        // we also return the old render cost
1587        normalizedOldRenderCost = oldRenderCost / viewSpaceVol;
1588
1589        // the render cost decrase for this split
1590        const float renderCostDecrease = (oldRenderCost - newRenderCost) / viewSpaceVol;
1591
1592#ifdef GTPGTP_DEBUG
1593        Debug << "\nvsp render cost decrease" << endl
1594                  << "back pvs: " << pvsBack << " front pvs " << pvsFront << " total pvs: " << totalPvs << endl
1595                  << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << " p: " << pOverall / viewSpaceVol << endl
1596                  << "old rc: " << normalizedOldRenderCost << " new rc: " << newRenderCost / viewSpaceVol << endl
1597                  << "render cost decrease: " << renderCostDecrease << endl;
1598#endif
1599
1600        return renderCostDecrease;
1601}
1602
1603
1604
1605float VspTree::EvalLocalSplitCost(const VspTraversalData &data,
1606                                                                  const AxisAlignedBox3 &box,
1607                                                                  const int axis,
1608                                                                  const float &position,
1609                                                                  float &pFront,
1610                                                                  float &pBack) const
1611{
1612        float pvsTotal = 0;
1613        float pvsFront = 0;
1614        float pvsBack = 0;
1615       
1616        // create unique ids for pvs heuristics
1617        Intersectable::NewMail(3);
1618        BvhLeaf::NewMail(3);
1619        KdLeaf::NewMail(3);
1620
1621        const int pvsSize = data.mPvs;
1622        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1623
1624        // this is the main ray classification loop!
1625        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
1626        {
1627                VssRay *ray = (*rit).mRay;
1628
1629                // determine the side of this ray with respect to the plane
1630                float t;
1631                const int side = (*rit).ComputeRayIntersection(axis, position, t);
1632       
1633                UpdateContributionsToPvs(*ray, true, side, pvsFront, pvsBack, pvsTotal);
1634                UpdateContributionsToPvs(*ray, false, side, pvsFront, pvsBack, pvsTotal);
1635        }
1636
1637        //////////////
1638        //-- evaluate cost heuristics
1639        float pOverall = data.mProbability;
1640
1641        // we use spatial mid split => simplified computation
1642        pBack = pFront = pOverall * 0.5f;
1643       
1644        const float newCost = pvsBack * pBack + pvsFront * pFront;
1645        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
1646       
1647#ifdef GTPGTP_DEBUG
1648        Debug << "axis: " << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
1649        Debug << "p: " << pFront << " " << pBack << " " << pOverall << endl;
1650#endif
1651
1652        return  (mCtDivCi + newCost) / oldCost;
1653}
1654
1655
1656void VspTree::UpdateContributionsToPvs(Intersectable *obj,
1657                                                                           const int cf,
1658                                                                           float &frontPvs,
1659                                                                           float &backPvs,
1660                                                                           float &totalPvs) const
1661{
1662        if (!obj) return;
1663
1664        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
1665
1666        // object in no pvs => new
1667        if (!obj->Mailed() && !obj->Mailed(1) && !obj->Mailed(2))
1668        {
1669                totalPvs += renderCost;
1670        }
1671
1672        // QUESTION matt: is it safe to assume that
1673        // the object belongs to no pvs in this case?
1674        //if (cf == Ray::COINCIDENT) return;
1675        if (cf >= 0) // front pvs
1676        {
1677                if (!obj->Mailed() && !obj->Mailed(2))
1678                {
1679                        frontPvs += renderCost;
1680               
1681                        // already in back pvs => in both pvss
1682                        if (obj->Mailed(1))
1683                                obj->Mail(2);
1684                        else
1685                                obj->Mail();
1686                }
1687        }
1688
1689        if (cf <= 0) // back pvs
1690        {
1691                if (!obj->Mailed(1) && !obj->Mailed(2))
1692                {
1693                        backPvs += renderCost;
1694               
1695                        // already in front pvs => in both pvss
1696                        if (obj->Mailed())
1697                                obj->Mail(2);
1698                        else
1699                                obj->Mail(1);
1700                }
1701        }
1702}
1703
1704
1705void VspTree::UpdateContributionsToPvs(BvhLeaf *leaf,
1706                                                                           const int cf,
1707                                                                           float &frontPvs,
1708                                                                           float &backPvs,
1709                                                                           float &totalPvs,
1710                                                                           const bool countEntries) const
1711{
1712        if (!leaf) return;
1713
1714        const float renderCost = countEntries ? 1 :
1715                mHierarchyManager->mBvHierarchy->EvalAbsCost(leaf->mObjects);
1716       
1717        // leaf in no pvs => new
1718        if (!leaf->Mailed() && !leaf->Mailed(1) && !leaf->Mailed(2))
1719        {
1720                totalPvs += renderCost;
1721        }
1722
1723        if (cf >= 0) // front pvs
1724        {
1725                if (!leaf->Mailed() && !leaf->Mailed(2))
1726                {
1727                        frontPvs += renderCost;
1728       
1729                        // already in back pvs => in both pvss
1730                        if (leaf->Mailed(1))
1731                                leaf->Mail(2);
1732                        else
1733                                leaf->Mail();
1734                }
1735        }
1736
1737        if (cf <= 0) // back pvs
1738        {
1739                if (!leaf->Mailed(1) && !leaf->Mailed(2))
1740                {
1741                        backPvs += renderCost;
1742               
1743                        // already in front pvs => in both pvss
1744                        if (leaf->Mailed())
1745                        {
1746                                leaf->Mail(2);
1747                        }
1748                        else
1749                                leaf->Mail(1);
1750                }
1751        }
1752}
1753
1754
1755void VspTree::UpdateContributionsToPvs(KdLeaf *leaf,
1756                                                                           const int cf,
1757                                                                           float &frontPvs,
1758                                                                           float &backPvs,
1759                                                                           float &totalPvs) const
1760{
1761        if (!leaf) return;
1762
1763        // the objects which are referenced in this and only this leaf
1764        const int contri = (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
1765       
1766        // newly found leaf
1767        if (!leaf->Mailed() && !leaf->Mailed(1) && !leaf->Mailed(2))
1768        {
1769                totalPvs += contri;
1770        }
1771
1772        // recursivly update contributions of yet unclassified objects
1773        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
1774
1775        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
1776        {       
1777                UpdateContributionsToPvs(*oit, cf, frontPvs, backPvs, totalPvs);
1778    }   
1779       
1780        if (cf >= 0) // front pvs
1781        {
1782                if (!leaf->Mailed() && !leaf->Mailed(2))
1783                {
1784                        frontPvs += contri;
1785               
1786                        // already in back pvs => in both pvss
1787                        if (leaf->Mailed(1))
1788                                leaf->Mail(2);
1789                        else
1790                                leaf->Mail();
1791                }
1792        }
1793
1794        if (cf <= 0) // back pvs
1795        {
1796                if (!leaf->Mailed(1) && !leaf->Mailed(2))
1797                {
1798                        backPvs += contri;
1799               
1800                        // already in front pvs => in both pvss
1801                        if (leaf->Mailed())
1802                                leaf->Mail(2);
1803                        else
1804                                leaf->Mail(1);
1805                }
1806        }
1807}
1808
1809
1810void VspTree::CollectLeaves(vector<VspLeaf *> &leaves,
1811                                                        const bool onlyUnmailed,
1812                                                        const int maxPvsSize) const
1813{
1814        stack<VspNode *> nodeStack;
1815        nodeStack.push(mRoot);
1816
1817        while (!nodeStack.empty())
1818        {
1819                VspNode *node = nodeStack.top();
1820                nodeStack.pop();
1821               
1822                if (node->IsLeaf())
1823                {
1824                        // test if this leaf is in valid view space
1825                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
1826
1827                        if (leaf->TreeValid() &&
1828                                (!onlyUnmailed || !leaf->Mailed()) &&
1829                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().EvalPvsCost() <= maxPvsSize)))
1830                        {
1831                                leaves.push_back(leaf);
1832                        }
1833                }
1834                else
1835                {
1836                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
1837
1838                        nodeStack.push(interior->GetBack());
1839                        nodeStack.push(interior->GetFront());
1840                }
1841        }
1842}
1843
1844
1845AxisAlignedBox3 VspTree::GetBoundingBox() const
1846{
1847        return mBoundingBox;
1848}
1849
1850
1851VspNode *VspTree::GetRoot() const
1852{
1853        return mRoot;
1854}
1855
1856
1857void VspTree::EvaluateLeafStats(const VspTraversalData &data)
1858{
1859        // the node became a leaf -> evaluate stats for leafs
1860        VspLeaf *leaf = dynamic_cast<VspLeaf *>(data.mNode);
1861
1862
1863        if (data.mPvs > mVspStats.maxPvs)
1864        {
1865                mVspStats.maxPvs = data.mPvs;
1866        }
1867
1868        mVspStats.pvs += data.mPvs;
1869
1870        if (data.mDepth < mVspStats.minDepth)
1871        {
1872                mVspStats.minDepth = data.mDepth;
1873        }
1874       
1875        if (data.mDepth >= mTermMaxDepth)
1876        {
1877        ++ mVspStats.maxDepthNodes;
1878                //Debug << "new max depth: " << mVspStats.maxDepthNodes << endl;
1879        }
1880
1881        // accumulate rays to compute rays /  leaf
1882        mVspStats.rayRefs += (int)data.mRays->size();
1883
1884        if (data.mPvs < mTermMinPvs)
1885                ++ mVspStats.minPvsNodes;
1886
1887        if ((int)data.mRays->size() < mTermMinRays)
1888                ++ mVspStats.minRaysNodes;
1889
1890        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1891                ++ mVspStats.maxRayContribNodes;
1892
1893        if (data.mProbability <= mTermMinProbability)
1894                ++ mVspStats.minProbabilityNodes;
1895       
1896        // accumulate depth to compute average depth
1897        mVspStats.accumDepth += data.mDepth;
1898
1899        ++ mCreatedViewCells;
1900
1901#ifdef GTPGTP_DEBUG
1902        Debug << "BSP stats: "
1903                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1904                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1905                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1906                  << "#pvs: " << leaf->GetViewCell()->GetPvs().EvalPvsCost() << "), "
1907                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1908#endif
1909}
1910
1911
1912void VspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
1913{
1914        ViewCell::NewMail();
1915        CollectViewCells(mRoot, onlyValid, viewCells, true);
1916}
1917
1918
1919void VspTree::CollapseViewCells()
1920{
1921// TODO matt
1922#if HAS_TO_BE_REDONE
1923        stack<VspNode *> nodeStack;
1924
1925        if (!mRoot)
1926                return;
1927
1928        nodeStack.push(mRoot);
1929       
1930        while (!nodeStack.empty())
1931        {
1932                VspNode *node = nodeStack.top();
1933                nodeStack.pop();
1934               
1935                if (node->IsLeaf())
1936        {
1937                        BspViewCell *viewCell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
1938
1939                        if (!viewCell->GetValid())
1940                        {
1941                                BspViewCell *viewCell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
1942       
1943                                ViewCellContainer leaves;
1944                                mViewCellsTree->CollectLeaves(viewCell, leaves);
1945
1946                                ViewCellContainer::const_iterator it, it_end = leaves.end();
1947
1948                                for (it = leaves.begin(); it != it_end; ++ it)
1949                                {
1950                                        VspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
1951                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
1952                                        ++ mVspStats.invalidLeaves;
1953                                }
1954
1955                                // add to unbounded view cell
1956                                ViewCell *outOfBounds = GetOrCreateOutOfBoundsCell();
1957                                outOfBounds->GetPvs().AddPvs(viewCell->GetPvs());
1958                                DEL_PTR(viewCell);
1959                        }
1960                }
1961                else
1962                {
1963                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
1964               
1965                        nodeStack.push(interior->GetFront());
1966                        nodeStack.push(interior->GetBack());
1967                }
1968        }
1969
1970        Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl;
1971#endif
1972}
1973
1974
1975void VspTree::CollectRays(VssRayContainer &rays)
1976{
1977        vector<VspLeaf *> leaves;
1978        CollectLeaves(leaves);
1979
1980        vector<VspLeaf *>::const_iterator lit, lit_end = leaves.end();
1981
1982        for (lit = leaves.begin(); lit != lit_end; ++ lit)
1983        {
1984                VspLeaf *leaf = *lit;
1985                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
1986
1987                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
1988                        rays.push_back(*rit);
1989        }
1990}
1991
1992
1993void VspTree::SetViewCellsManager(ViewCellsManager *vcm)
1994{
1995        mViewCellsManager = vcm;
1996}
1997
1998
1999void VspTree::ValidateTree()
2000{
2001        if (!mRoot)
2002                return;
2003
2004        mVspStats.invalidLeaves = 0;
2005        stack<VspNode *> nodeStack;
2006
2007        nodeStack.push(mRoot);
2008
2009        while (!nodeStack.empty())
2010        {
2011                VspNode *node = nodeStack.top();
2012                nodeStack.pop();
2013               
2014                if (node->IsLeaf())
2015                {
2016                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2017
2018                        if (!leaf->GetViewCell()->GetValid())
2019                                ++ mVspStats.invalidLeaves;
2020
2021                        // validity flags don't match => repair
2022                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2023                        {
2024                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2025                                PropagateUpValidity(leaf);
2026                        }
2027                }
2028                else
2029                {
2030                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2031               
2032                        nodeStack.push(interior->GetFront());
2033                        nodeStack.push(interior->GetBack());
2034                }
2035        }
2036
2037        Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl;
2038}
2039
2040
2041
2042void VspTree::CollectViewCells(VspNode *root,
2043                                                                  bool onlyValid,
2044                                                                  ViewCellContainer &viewCells,
2045                                                                  bool onlyUnmailed) const
2046{
2047        if (!root)
2048                return;
2049
2050        stack<VspNode *> nodeStack;
2051        nodeStack.push(root);
2052       
2053        while (!nodeStack.empty())
2054        {
2055                VspNode *node = nodeStack.top();
2056                nodeStack.pop();
2057               
2058                if (node->IsLeaf())
2059                {
2060                        if (!onlyValid || node->TreeValid())
2061                        {
2062                                ViewCellLeaf *leafVc = dynamic_cast<VspLeaf *>(node)->GetViewCell();
2063
2064                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2065                                               
2066                                if (!onlyUnmailed || !viewCell->Mailed())
2067                                {
2068                                        viewCell->Mail();
2069                                        viewCells.push_back(viewCell);
2070                                }
2071                        }
2072                }
2073                else
2074                {
2075                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2076               
2077                        nodeStack.push(interior->GetFront());
2078                        nodeStack.push(interior->GetBack());
2079                }
2080        }
2081}
2082
2083
2084int VspTree::FindNeighbors(VspLeaf *n,
2085                                                   vector<VspLeaf *> &neighbors,
2086                                                   const bool onlyUnmailed) const
2087{
2088        stack<VspNode *> nodeStack;
2089        nodeStack.push(mRoot);
2090
2091        const AxisAlignedBox3 box = GetBoundingBox(n);
2092
2093        while (!nodeStack.empty())
2094        {
2095                VspNode *node = nodeStack.top();
2096                nodeStack.pop();
2097
2098                if (node->IsLeaf())
2099                {
2100                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2101
2102                        if (leaf != n && (!onlyUnmailed || !leaf->Mailed()))
2103                                neighbors.push_back(leaf);
2104                }
2105                else
2106                {
2107                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2108                       
2109                        if (interior->GetPosition() > box.Max(interior->GetAxis()))
2110                                nodeStack.push(interior->GetBack());
2111                        else
2112                        {
2113                                if (interior->GetPosition() < box.Min(interior->GetAxis()))
2114                                        nodeStack.push(interior->GetFront());
2115                                else
2116                                {
2117                                        // random decision
2118                                        nodeStack.push(interior->GetBack());
2119                                        nodeStack.push(interior->GetFront());
2120                                }
2121                        }
2122                }
2123        }
2124
2125        return (int)neighbors.size();
2126}
2127
2128
2129// Find random neighbor which was not mailed
2130VspLeaf *VspTree::GetRandomLeaf(const Plane3 &plane)
2131{
2132        stack<VspNode *> nodeStack;
2133        nodeStack.push(mRoot);
2134 
2135        int mask = rand();
2136 
2137        while (!nodeStack.empty())
2138        {
2139                VspNode *node = nodeStack.top();
2140               
2141                nodeStack.pop();
2142               
2143                if (node->IsLeaf())
2144                {
2145                        return dynamic_cast<VspLeaf *>(node);
2146                }
2147                else
2148                {
2149                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2150                        VspNode *next;
2151                       
2152                        if (GetBoundingBox(interior->GetBack()).Side(plane) < 0)
2153                        {
2154                                next = interior->GetFront();
2155                        }
2156            else
2157                        {
2158                                if (GetBoundingBox(interior->GetFront()).Side(plane) < 0)
2159                                {
2160                                        next = interior->GetBack();
2161                                }
2162                                else
2163                                {
2164                                        // random decision
2165                                        if (mask & 1)
2166                                                next = interior->GetBack();
2167                                        else
2168                                                next = interior->GetFront();
2169                                        mask = mask >> 1;
2170                                }
2171                        }
2172                       
2173                        nodeStack.push(next);
2174                }
2175        }
2176 
2177        return NULL;
2178}
2179
2180
2181VspLeaf *VspTree::GetRandomLeaf(const bool onlyUnmailed)
2182{
2183        stack<VspNode *> nodeStack;
2184
2185        nodeStack.push(mRoot);
2186
2187        int mask = rand();
2188
2189        while (!nodeStack.empty())
2190        {
2191                VspNode *node = nodeStack.top();
2192                nodeStack.pop();
2193
2194                if (node->IsLeaf())
2195                {
2196                        if ( (!onlyUnmailed || !node->Mailed()) )
2197                                return dynamic_cast<VspLeaf *>(node);
2198                }
2199                else
2200                {
2201                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2202
2203                        // random decision
2204                        if (mask & 1)
2205                                nodeStack.push(interior->GetBack());
2206                        else
2207                                nodeStack.push(interior->GetFront());
2208
2209                        mask = mask >> 1;
2210                }
2211        }
2212
2213        return NULL;
2214}
2215
2216
2217int VspTree::EvalPvsSize(const RayInfoContainer &rays) const
2218{
2219        int pvsSize = 0;
2220       
2221        Intersectable::NewMail();
2222        KdNode::NewMail();
2223        BvhLeaf::NewMail();
2224
2225        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2226
2227        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2228        {
2229                VssRay *ray = (*rit).mRay;
2230#if COUNT_ORIGIN_OBJECTS
2231                pvsSize += EvalContributionToPvs(*ray, true);
2232#else
2233                pvsSize += EvalContributionToPvs(*ray, false);
2234#endif
2235        }
2236       
2237        return pvsSize;
2238}
2239
2240
2241int VspTree::EvalPvsEntriesContribution(const VssRay &ray,
2242                                                                                const bool isTermination) const
2243
2244{
2245                Intersectable *obj;
2246                Vector3 pt;
2247                KdNode *node;
2248
2249                ray.GetSampleData(isTermination, pt, &obj, &node);
2250                if (!obj) return 0;
2251
2252                switch(mHierarchyManager->GetObjectSpaceSubdivisionType())
2253                {
2254                case HierarchyManager::NO_OBJ_SUBDIV:
2255                {
2256                        if (!obj->Mailed())
2257                        {
2258                                obj->Mail();
2259                                return 1;
2260                        }
2261                       
2262                        return 0;
2263                }
2264
2265                case HierarchyManager::KD_BASED_OBJ_SUBDIV:
2266                {
2267                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
2268                        if (!leaf->Mailed())
2269                        {
2270                                leaf->Mail();
2271                                return 1;
2272                        }
2273                       
2274                        return 0;
2275                }
2276        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
2277                {
2278                        BvhLeaf *bvhleaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
2279
2280                        if (!bvhleaf->Mailed())
2281                        {
2282                                bvhleaf->Mail();
2283                                return 1;
2284                        }
2285                       
2286                        return 0;
2287                }
2288        default:
2289                break;
2290        }
2291
2292        return 0;
2293}
2294
2295
2296int VspTree::EvalPvsEntriesSize(const RayInfoContainer &rays) const
2297{
2298        int pvsSize = 0;
2299
2300        Intersectable::NewMail();
2301        KdNode::NewMail();
2302        BvhLeaf::NewMail();
2303
2304        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2305
2306        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2307        {
2308                VssRay *ray = (*rit).mRay;
2309#if COUNT_ORIGIN_OBJECTS
2310                pvsSize += EvalPvsEntriesContribution(*ray, true);
2311#else
2312                pvsSize += EvalPvsEntriesContribution(*ray, false);
2313#endif
2314        }
2315
2316        return pvsSize;
2317}
2318
2319
2320float VspTree::GetEpsilon() const
2321{
2322        return mEpsilon;
2323}
2324
2325
2326int VspTree::CastLineSegment(const Vector3 &origin,
2327                                                         const Vector3 &termination,
2328                             ViewCellContainer &viewcells,
2329                                                         const bool useMailboxing)
2330{
2331        int hits = 0;
2332
2333        float mint = 0.0f, maxt = 1.0f;
2334        const Vector3 dir = termination - origin;
2335
2336        stack<LineTraversalData> tStack;
2337
2338        Vector3 entp = origin;
2339        Vector3 extp = termination;
2340
2341        VspNode *node = mRoot;
2342        VspNode *farChild;
2343
2344        float position;
2345        int axis;
2346
2347        while (1)
2348        {
2349                if (!node->IsLeaf())
2350                {
2351                        VspInterior *in = dynamic_cast<VspInterior *>(node);
2352                        position = in->GetPosition();
2353                        axis = in->GetAxis();
2354
2355                        if (entp[axis] <= position)
2356                        {
2357                                if (extp[axis] <= position)
2358                                {
2359                                        node = in->GetBack();
2360                                        // cases N1,N2,N3,P5,Z2,Z3
2361                                        continue;
2362                                } else
2363                                {
2364                                        // case N4
2365                                        node = in->GetBack();
2366                                        farChild = in->GetFront();
2367                                }
2368                        }
2369                        else
2370                        {
2371                                if (position <= extp[axis])
2372                                {
2373                                        node = in->GetFront();
2374                                        // cases P1,P2,P3,N5,Z1
2375                                        continue;
2376                                }
2377                                else
2378                                {
2379                                        node = in->GetFront();
2380                                        farChild = in->GetBack();
2381                                        // case P4
2382                                }
2383                        }
2384
2385                        // $$ modification 3.5.2004 - hints from Kamil Ghais
2386                        // case N4 or P4
2387                        const float tdist = (position - origin[axis]) / dir[axis];
2388                        tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO
2389
2390                        extp = origin + dir * tdist;
2391                        maxt = tdist;
2392                }
2393                else
2394                {
2395                        // compute intersection with all objects in this leaf
2396                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2397                        ViewCell *viewCell;
2398                        if (0)
2399                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2400                        else
2401                                viewCell = leaf->GetViewCell();
2402
2403                        // don't have to mail if each view cell belongs to exactly one leaf
2404                        if (!useMailboxing || !viewCell->Mailed())
2405                        {
2406                                if (useMailboxing)
2407                                        viewCell->Mail();
2408
2409                                viewcells.push_back(viewCell);
2410                                ++ hits;
2411                        }
2412
2413                        // get the next node from the stack
2414                        if (tStack.empty())
2415                                break;
2416
2417                        entp = extp;
2418                        mint = maxt;
2419                       
2420                        LineTraversalData &s  = tStack.top();
2421                        node = s.mNode;
2422                        extp = s.mExitPoint;
2423                        maxt = s.mMaxT;
2424
2425                        tStack.pop();
2426                }
2427        }
2428
2429        return hits;
2430}
2431
2432
2433int VspTree::CastRay(Ray &ray)
2434{
2435        int hits = 0;
2436
2437        stack<LineTraversalData> tStack;
2438        const Vector3 dir = ray.GetDir();
2439
2440        float maxt, mint;
2441
2442        if (!mBoundingBox.GetRaySegment(ray, mint, maxt))
2443                return 0;
2444
2445        Intersectable::NewMail();
2446        ViewCell::NewMail();
2447
2448        Vector3 entp = ray.Extrap(mint);
2449        Vector3 extp = ray.Extrap(maxt);
2450
2451        const Vector3 origin = entp;
2452
2453        VspNode *node = mRoot;
2454        VspNode *farChild = NULL;
2455
2456        float position;
2457        int axis;
2458
2459        while (1)
2460        {
2461                if (!node->IsLeaf())
2462                {
2463                        VspInterior *in = dynamic_cast<VspInterior *>(node);
2464                        position = in->GetPosition();
2465                        axis = in->GetAxis();
2466
2467                        if (entp[axis] <= position)
2468                        {
2469                                if (extp[axis] <= position)
2470                                {
2471                                        node = in->GetBack();
2472                                        // cases N1,N2,N3,P5,Z2,Z3
2473                                        continue;
2474                                }
2475                                else
2476                                {
2477                                        // case N4
2478                                        node = in->GetBack();
2479                                        farChild = in->GetFront();
2480                                }
2481                        }
2482                        else
2483                        {
2484                                if (position <= extp[axis])
2485                                {
2486                                        node = in->GetFront();
2487                                        // cases P1,P2,P3,N5,Z1
2488                                        continue;
2489                                }
2490                                else
2491                                {
2492                                        node = in->GetFront();
2493                                        farChild = in->GetBack();
2494                                        // case P4
2495                                }
2496                        }
2497
2498                        // $$ modification 3.5.2004 - hints from Kamil Ghais
2499                        // case N4 or P4
2500                        const float tdist = (position - origin[axis]) / dir[axis];
2501                        tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO
2502                        extp = origin + dir * tdist;
2503                        maxt = tdist;
2504                }
2505                else
2506                {
2507                        // compute intersection with all objects in this leaf
2508                        VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2509                        ViewCell *vc = leaf->GetViewCell();
2510
2511                        if (!vc->Mailed())
2512                        {
2513                                vc->Mail();
2514                                // todo: add view cells to ray
2515                                ++ hits;
2516                        }
2517
2518                        // get the next node from the stack
2519                        if (tStack.empty())
2520                                break;
2521
2522                        entp = extp;
2523                        mint = maxt;
2524                       
2525                        LineTraversalData &s  = tStack.top();
2526                        node = s.mNode;
2527                        extp = s.mExitPoint;
2528                        maxt = s.mMaxT;
2529                        tStack.pop();
2530                }
2531        }
2532
2533        return hits;
2534}
2535
2536
2537ViewCell *VspTree::GetViewCell(const Vector3 &point, const bool active)
2538{
2539        if (mRoot == NULL)
2540                return NULL;
2541
2542        stack<VspNode *> nodeStack;
2543        nodeStack.push(mRoot);
2544 
2545        ViewCellLeaf *viewcell = NULL;
2546 
2547        while (!nodeStack.empty()) 
2548        {
2549                VspNode *node = nodeStack.top();
2550                nodeStack.pop();
2551       
2552                if (node->IsLeaf())
2553                {
2554                        /*const AxisAlignedBox3 box = GetBoundingBox(dynamic_cast<VspLeaf *>(node));
2555                        if (!box.IsInside(point))
2556                                cerr << "error, point " << point << " should be in view cell " << box << endl;
2557                        */     
2558                        viewcell = dynamic_cast<VspLeaf *>(node)->GetViewCell();
2559                        break;
2560                }
2561                else   
2562                {       
2563                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2564     
2565                        // random decision
2566                        if (interior->GetPosition() - point[interior->GetAxis()] < 0)
2567                        {
2568                                nodeStack.push(interior->GetFront());
2569                        }
2570                        else
2571                        {
2572                                nodeStack.push(interior->GetBack());
2573                        }
2574                }
2575        }
2576 
2577        if (active)
2578        {
2579                return mViewCellsTree->GetActiveViewCell(viewcell);
2580        }
2581        else
2582        {
2583                return viewcell;
2584        }
2585}
2586
2587
2588bool VspTree::ViewPointValid(const Vector3 &viewPoint) const
2589{
2590        VspNode *node = mRoot;
2591
2592        while (1)
2593        {
2594                // early exit
2595                if (node->TreeValid())
2596                        return true;
2597
2598                if (node->IsLeaf())
2599                        return false;
2600                       
2601                VspInterior *in = dynamic_cast<VspInterior *>(node);
2602                                       
2603                if (in->GetPosition() - viewPoint[in->GetAxis()] <= 0)
2604                {
2605                        node = in->GetBack();
2606                }
2607                else
2608                {
2609                        node = in->GetFront();
2610                }
2611        }
2612
2613        // should never come here
2614        return false;
2615}
2616
2617
2618void VspTree::PropagateUpValidity(VspNode *node)
2619{
2620        const bool isValid = node->TreeValid();
2621
2622        // propagative up invalid flag until only invalid nodes exist over this node
2623        if (!isValid)
2624        {
2625                while (!node->IsRoot() && node->GetParent()->TreeValid())
2626                {
2627                        node = node->GetParent();
2628                        node->SetTreeValid(false);
2629                }
2630        }
2631        else
2632        {
2633                // propagative up valid flag until one of the subtrees is invalid
2634                while (!node->IsRoot() && !node->TreeValid())
2635                {
2636            node = node->GetParent();
2637                        VspInterior *interior = dynamic_cast<VspInterior *>(node);
2638                       
2639                        // the parent is valid iff both leaves are valid
2640                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
2641                                                           interior->GetFront()->TreeValid());
2642                }
2643        }
2644}
2645
2646
2647bool VspTree::Export(OUT_STREAM &stream)
2648{
2649        ExportNode(mRoot, stream);
2650
2651        return true;
2652}
2653
2654
2655void VspTree::ExportNode(VspNode *node, OUT_STREAM &stream)
2656{
2657        if (node->IsLeaf())
2658        {
2659                VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2660                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2661
2662                int id = -1;
2663                if (viewCell != mOutOfBoundsCell)
2664                        id = viewCell->GetId();
2665
2666                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
2667        }
2668        else
2669        {       
2670                VspInterior *interior = dynamic_cast<VspInterior *>(node);
2671       
2672                AxisAlignedPlane plane = interior->GetPlane();
2673                stream << "<Interior plane=\"" << plane.mPosition << " "
2674                           << plane.mAxis << "\">" << endl;
2675
2676                ExportNode(interior->GetBack(), stream);
2677                ExportNode(interior->GetFront(), stream);
2678
2679                stream << "</Interior>" << endl;
2680        }
2681}
2682
2683
2684int VspTree::SplitRays(const AxisAlignedPlane &plane,
2685                                           RayInfoContainer &rays,
2686                                           RayInfoContainer &frontRays,
2687                                           RayInfoContainer &backRays) const
2688{
2689        int splits = 0;
2690
2691        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2692
2693        for (rit = rays.begin(); rit != rit_end; ++ rit)
2694        {
2695                RayInfo bRay = *rit;
2696               
2697                VssRay *ray = bRay.mRay;
2698                float t;
2699
2700                // get classification and receive new t
2701                // test if start point behind or in front of plane
2702                const int side = bRay.ComputeRayIntersection(plane.mAxis, plane.mPosition, t);
2703                       
2704                if (side == 0)
2705                {
2706                        ++ splits;
2707
2708                        if (ray->HasPosDir(plane.mAxis))
2709                        {
2710                                backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2711                                frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2712                        }
2713                        else
2714                        {
2715                                frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2716                                backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2717                        }
2718                }
2719                else if (side == 1)
2720                {
2721                        frontRays.push_back(bRay);
2722                }
2723                else
2724                {
2725                        backRays.push_back(bRay);
2726                }
2727        }
2728
2729        return splits;
2730}
2731
2732
2733AxisAlignedBox3 VspTree::GetBoundingBox(VspNode *node) const
2734{
2735        if (!node->GetParent())
2736                return mBoundingBox;
2737
2738        if (!node->IsLeaf())
2739        {
2740                return (dynamic_cast<VspInterior *>(node))->GetBoundingBox();           
2741        }
2742
2743        VspInterior *parent = dynamic_cast<VspInterior *>(node->GetParent());
2744
2745        AxisAlignedBox3 box(parent->GetBoundingBox());
2746
2747        if (parent->GetFront() == node)
2748                box.SetMin(parent->GetAxis(), parent->GetPosition());
2749    else
2750                box.SetMax(parent->GetAxis(), parent->GetPosition());
2751
2752        return box;
2753}
2754
2755
2756int VspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2757                                                                         ViewCellContainer &viewCells) const
2758{
2759        stack<VspNode *> nodeStack;
2760 
2761        ViewCell::NewMail();
2762
2763        nodeStack.push(mRoot);
2764       
2765        while (!nodeStack.empty())
2766        {
2767                VspNode *node = nodeStack.top();
2768                nodeStack.pop();
2769
2770                const AxisAlignedBox3 bbox = GetBoundingBox(node);
2771
2772                if (Overlap(bbox, box)) {
2773                  if (node->IsLeaf())
2774                        {
2775                          VspLeaf *leaf = dynamic_cast<VspLeaf *>(node);
2776                         
2777                          if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2778                                {
2779                                  leaf->GetViewCell()->Mail();
2780                                  viewCells.push_back(leaf->GetViewCell());
2781                                }
2782                        }
2783                  else
2784                        {
2785                          VspInterior *interior = dynamic_cast<VspInterior *>(node);
2786                         
2787                          VspNode *first = interior->GetFront();
2788                          VspNode *second = interior->GetBack();
2789                         
2790                          nodeStack.push(first);
2791                          nodeStack.push(second);
2792                        }
2793                }
2794                // default: cull
2795        }
2796
2797        return (int)viewCells.size();
2798}
2799
2800
2801void VspTree::PreprocessRays(const VssRayContainer &sampleRays,
2802                                                         RayInfoContainer &rays)
2803{
2804        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
2805
2806        long startTime = GetTime();
2807
2808        cout << "storing rays ... ";
2809
2810        Intersectable::NewMail();
2811
2812        //-- store rays and objects
2813        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
2814        {
2815                VssRay *ray = *rit;
2816                float minT, maxT;
2817                static Ray hray;
2818
2819                hray.Init(*ray);
2820               
2821                // TODO: not very efficient to implictly cast between rays types
2822                if (GetBoundingBox().GetRaySegment(hray, minT, maxT))
2823                {
2824                        float len = ray->Length();
2825
2826                        if (!len)
2827                                len = Limits::Small;
2828
2829                        rays.push_back(RayInfo(ray, minT / len, maxT / len));
2830                }
2831        }
2832
2833        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
2834}
2835
2836
2837void VspTree::GetViewCells(const VssRay &ray, ViewCellContainer &viewCells)
2838{
2839        static Ray hray;
2840        hray.Init(ray);
2841       
2842        float tmin = 0, tmax = 1.0;
2843
2844        if (!mBoundingBox.GetRaySegment(hray, tmin, tmax) || (tmin > tmax))
2845                return;
2846
2847        const Vector3 origin = hray.Extrap(tmin);
2848        const Vector3 termination = hray.Extrap(tmax);
2849
2850        // view cells were not precomputed
2851        // don't mail because we need mailboxing for something else
2852        CastLineSegment(origin, termination, viewCells, false);
2853}
2854
2855
2856void VspTree::Initialise(const VssRayContainer &rays,
2857                                                 AxisAlignedBox3 *forcedBoundingBox)
2858{
2859        ComputeBoundingBox(rays, forcedBoundingBox);
2860
2861        VspLeaf *leaf = new VspLeaf();
2862        mRoot = leaf;
2863
2864        VspViewCell *viewCell = new VspViewCell();
2865    leaf->SetViewCell(viewCell);
2866
2867        // set view cell values
2868        viewCell->mLeaves.push_back(leaf);
2869        viewCell->SetVolume(mBoundingBox.GetVolume());
2870
2871        leaf->mProbability = mBoundingBox.GetVolume();
2872}
2873
2874
2875SubdivisionCandidate *VspTree::PrepareConstruction(const VssRayContainer &sampleRays,
2876                                                                                                   RayInfoContainer &rays)
2877{       
2878        mVspStats.Reset();
2879        mVspStats.Start();
2880        mVspStats.nodes = 1;
2881
2882        // store pointer to this tree
2883        VspSubdivisionCandidate::sVspTree = this;
2884       
2885        // initialise termination criteria
2886        mTermMinProbability *= mBoundingBox.GetVolume();
2887       
2888        // get clipped rays
2889        PreprocessRays(sampleRays, rays);
2890
2891        /// collect pvs from rays
2892        const int pvsSize = EvalPvsSize(rays);
2893       
2894        // root and bounding box were already constructed
2895        VspLeaf *leaf = dynamic_cast<VspLeaf *>(mRoot);
2896
2897        //////////
2898        //-- prepare view space partition
2899
2900        const float prop = mBoundingBox.GetVolume();
2901       
2902        // first vsp traversal data
2903        VspTraversalData vData(leaf, 0, &rays, pvsSize, prop, mBoundingBox);
2904
2905
2906#if WORK_WITH_VIEWCELL_PVS
2907        // add first view cell to all the objects view cell pvs
2908        ObjectPvsEntries::const_iterator oit,
2909                oit_end = leaf->GetViewCell()->GetPvs().mEntries.end();
2910
2911        for (oit = leaf->GetViewCell()->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
2912        {
2913                Intersectable *obj = (*oit).first;
2914                obj->mViewCellPvs.AddSample(leaf->GetViewCell(), 1);
2915        }
2916#endif
2917
2918        //////////////
2919        //-- create the first split candidate
2920
2921        VspSubdivisionCandidate *splitCandidate = new VspSubdivisionCandidate(vData);
2922    EvalSubdivisionCandidate(*splitCandidate);
2923        leaf->SetSubdivisionCandidate(splitCandidate);
2924
2925        mTotalCost = (float)pvsSize;
2926        mPvsEntries = EvalPvsEntriesSize(rays);
2927
2928        EvalSubdivisionStats(*splitCandidate);
2929
2930        return splitCandidate;
2931}
2932
2933
2934void VspTree::CollectDirtyCandidate(const VssRay &ray,
2935                                                                        const bool isTermination,
2936                                                                        vector<SubdivisionCandidate *> &dirtyList,
2937                                                                        const bool onlyUnmailed) const
2938{
2939
2940        Intersectable *obj;
2941        Vector3 pt;
2942        KdNode *node;
2943
2944        ray.GetSampleData(isTermination, pt, &obj, &node);
2945       
2946        if (!obj) return;
2947       
2948        SubdivisionCandidate *candidate = NULL;
2949               
2950        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
2951        {
2952        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
2953                {
2954                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
2955
2956                        if (!leaf->Mailed())
2957                        {
2958                                leaf->Mail();
2959                                candidate = leaf->mSubdivisionCandidate;
2960                        }
2961                        break;
2962                }
2963        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
2964                {
2965                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
2966
2967                        if (!leaf->Mailed())
2968                        {
2969                                leaf->Mail();
2970                                candidate = leaf->GetSubdivisionCandidate();
2971                        }
2972                        break;
2973                }
2974        default:
2975                cerr << "not implemented yet" << endl;
2976                candidate = NULL;
2977                break;
2978        }
2979
2980        // is this leaf still a split candidate?
2981        if (candidate && (!onlyUnmailed || !candidate->Mailed()))
2982        {
2983                candidate->Mail();
2984                candidate->SetDirty(true);
2985                dirtyList.push_back(candidate);
2986        }
2987}
2988
2989
2990void VspTree::CollectDirtyCandidates(VspSubdivisionCandidate *sc,
2991                                                                         vector<SubdivisionCandidate *> &dirtyList,
2992                                                                         const bool onlyUnmailed)
2993{
2994        VspTraversalData &tData = sc->mParentData;
2995        VspLeaf *node = tData.mNode;
2996       
2997        KdLeaf::NewMail();
2998        BvhLeaf::NewMail();
2999       
3000        RayInfoContainer::const_iterator rit, rit_end = tData.mRays->end();
3001
3002        // add all kd nodes seen by the rays
3003        for (rit = tData.mRays->begin(); rit != rit_end; ++ rit)
3004        {
3005                VssRay *ray = (*rit).mRay;
3006               
3007                CollectDirtyCandidate(*ray, true, dirtyList, onlyUnmailed);
3008        CollectDirtyCandidate(*ray, false, dirtyList, onlyUnmailed);
3009        }
3010}
3011
3012
3013int VspTree::EvalMaxEventContribution(const VssRay &ray,
3014                                                                          const bool isTermination) const
3015{
3016        Intersectable *obj;
3017        Vector3 pt;
3018        KdNode *node;
3019
3020        ray.GetSampleData(isTermination, pt, &obj, &node);
3021
3022        if (!obj)
3023                return 0;
3024
3025        int pvs = 0;
3026
3027        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3028        {
3029        case HierarchyManager::NO_OBJ_SUBDIV:
3030                {
3031                        if (-- obj->mCounter == 0)
3032                                ++ pvs;
3033                        break;
3034                }
3035        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3036                {
3037                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3038
3039                        // add contributions of the kd nodes
3040                        pvs += EvalMaxEventContribution(leaf);
3041                        break;
3042                }
3043        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3044                {
3045                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3046
3047                        if (-- leaf->mCounter == 0)
3048                                pvs += (int)leaf->mObjects.size();
3049                        break;
3050                }
3051        default:
3052                break;
3053        }
3054
3055        return pvs;
3056}
3057
3058
3059int VspTree::PrepareHeuristics(const VssRay &ray, const bool isTermination)
3060{
3061        int pvsSize = 0;
3062       
3063        Intersectable *obj;
3064        Vector3 pt;
3065        KdNode *node;
3066
3067        ray.GetSampleData(isTermination, pt, &obj, &node);
3068
3069        if (!obj)
3070                return 0;
3071
3072        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3073        {
3074        case HierarchyManager::NO_OBJ_SUBDIV:
3075                {
3076                        if (!obj->Mailed())
3077                        {
3078                                obj->Mail();
3079                                obj->mCounter = 0;
3080                                ++ pvsSize;
3081                        }
3082
3083                        ++ obj->mCounter;       
3084                        break;
3085                }
3086        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3087                {
3088                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3089                        pvsSize += PrepareHeuristics(leaf);     
3090                        break;
3091                }
3092        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3093                {
3094                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3095
3096                        if (!leaf->Mailed())
3097                        {
3098                                leaf->Mail();
3099                                leaf->mCounter = 0;
3100                                pvsSize += (int)leaf->mObjects.size();
3101                        }
3102
3103                        ++ leaf->mCounter;     
3104                        break;
3105                }
3106        default:
3107                break;
3108        }
3109
3110        return pvsSize;
3111}
3112
3113
3114int VspTree::EvalMinEventContribution(const VssRay &ray,
3115                                                                          const bool isTermination) const
3116{
3117        Intersectable *obj;
3118        Vector3 pt;
3119        KdNode *node;
3120
3121        ray.GetSampleData(isTermination, pt, &obj, &node);
3122
3123        if (!obj) return 0;
3124
3125        int pvs = 0;
3126
3127        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3128        {
3129        case HierarchyManager::NO_OBJ_SUBDIV:
3130                {
3131                        if (!obj->Mailed())
3132                        {
3133                                obj->Mail();
3134                                ++ pvs;
3135                        }
3136                        break;
3137                }
3138        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3139                {
3140                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3141                        // add contributions of the kd nodes
3142                        pvs += EvalMinEventContribution(leaf);                         
3143                        break;
3144                }
3145        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3146                {
3147                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3148                        if (!leaf->Mailed())
3149                        {
3150                                leaf->Mail();
3151                                pvs += (int)leaf->mObjects.size();
3152                        }
3153                        break;
3154                }
3155        default:
3156                break;
3157        }
3158
3159        return pvs;
3160}
3161
3162
3163void VspTree::UpdateContributionsToPvs(const VssRay &ray,
3164                                                                           const bool isTermination,
3165                                                                           const int cf,
3166                                                                           float &frontPvs,
3167                                                                           float &backPvs,
3168                                                                           float &totalPvs) const
3169{
3170        Intersectable *obj;
3171        Vector3 pt;
3172        KdNode *node;
3173
3174        ray.GetSampleData(isTermination, pt, &obj, &node);
3175
3176        if (!obj) return;
3177
3178        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3179        {
3180                case HierarchyManager::NO_OBJ_SUBDIV:
3181                {
3182                        // find front and back pvs for origing and termination object
3183                        UpdateContributionsToPvs(obj, cf, frontPvs, backPvs, totalPvs);
3184                        break;
3185                }
3186                case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3187                {
3188                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3189                        UpdateContributionsToPvs(leaf, cf, frontPvs, backPvs, totalPvs);
3190                        break;
3191                }
3192                case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3193                {
3194                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3195                        UpdateContributionsToPvs(leaf, cf, frontPvs, backPvs, totalPvs);
3196                        break;
3197                }
3198        }
3199}
3200
3201
3202void VspTree::UpdatePvsEntriesContribution(const VssRay &ray,
3203                                                                                   const bool isTermination,
3204                                                                                   const int cf,
3205                                                                                   float &pvsFront,
3206                                                                                   float &pvsBack,
3207                                                                                   float &totalPvs) const
3208{
3209        Intersectable *obj;
3210        Vector3 pt;
3211        KdNode *node;
3212
3213        ray.GetSampleData(isTermination, pt, &obj, &node);
3214        if (!obj) return;
3215
3216        switch (mHierarchyManager->GetObjectSpaceSubdivisionType())
3217        {
3218        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3219                // TODO
3220                break;
3221        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3222                {
3223                        BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3224                        UpdateContributionsToPvs(leaf, cf, pvsFront, pvsBack, totalPvs, true);
3225                        break;
3226                }
3227        default:
3228                UpdateContributionsToPvs(obj, cf, pvsFront, pvsBack, totalPvs);
3229                break;
3230        }
3231}
3232
3233
3234int VspTree::EvalContributionToPvs(const VssRay &ray, const bool isTermination) const
3235{       
3236        Intersectable *obj;
3237        Vector3 pt;
3238        KdNode *node;
3239
3240        ray.GetSampleData(isTermination, pt, &obj, &node);
3241
3242        if (!obj) return 0;
3243
3244        int pvs = 0;
3245
3246        switch(mHierarchyManager->GetObjectSpaceSubdivisionType())
3247        {
3248        case HierarchyManager::NO_OBJ_SUBDIV:
3249                {
3250                        if (!obj->Mailed())
3251                        {
3252                                obj->Mail();
3253                                ++ pvs;
3254                        }
3255                        break;
3256                }
3257        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
3258                {
3259                        KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node);
3260                        pvs += EvalContributionToPvs(leaf);
3261                        break;
3262                }
3263        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
3264                {
3265                        BvhLeaf *bvhleaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj);
3266
3267                        if (!bvhleaf->Mailed())
3268                        {
3269                                bvhleaf->Mail();
3270                                pvs += (int)bvhleaf->mObjects.size();
3271                        }
3272                        break;
3273                }
3274        default:
3275                break;
3276        }
3277
3278        return pvs;
3279}
3280
3281
3282int VspTree::EvalContributionToPvs(KdLeaf *leaf) const
3283{
3284        if (leaf->Mailed()) // leaf already mailed
3285                return 0;
3286       
3287        leaf->Mail();
3288
3289        // this is the pvs which is uniquely part of this kd leaf
3290        int pvs = (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size());
3291
3292        ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end();
3293
3294        for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit)
3295        {
3296                Intersectable *obj = *oit;
3297                if (!obj->Mailed())
3298                {
3299                        obj->Mail();
3300                        ++ pvs;
3301                }
3302        }
3303
3304        return pvs;
3305}
3306
3307
3308VspNode *VspTree::SubdivideAndCopy(SplitQueue &tQueue,
3309                                                                   SubdivisionCandidate *splitCandidate)
3310{
3311        // todo remove dynamic cast
3312        VspSubdivisionCandidate *sc = dynamic_cast<VspSubdivisionCandidate *>(splitCandidate);
3313
3314        VspTraversalData &tData = sc->mParentData;
3315        VspNode *newNode = tData.mNode;
3316        VspNode *oldNode = (VspNode *)splitCandidate->mEvaluationHack;
3317
3318        if (!oldNode->IsLeaf())
3319        {       
3320                ///////////
3321                //-- continue subdivision
3322
3323                VspTraversalData tFrontData;
3324                VspTraversalData tBackData;
3325               
3326                VspInterior *oldInterior = dynamic_cast<VspInterior *>(oldNode);
3327
3328                // create new interior node and two leaf node
3329                const AxisAlignedPlane splitPlane = oldInterior->GetPlane();
3330       
3331                sc->mSplitPlane = splitPlane;
3332       
3333                // evaluate the changes in render cost and pvs entries
3334                EvalSubdivisionCandidate(*sc, false);
3335
3336                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData);
3337       
3338                //oldNode->mRenderCostDecr += sc->GetRenderCostDecrease();
3339                //oldNode->mPvsEntriesIncr += sc->GetPvsEntriesIncr();
3340
3341                //oldNode->mRenderCostDecr = sc->GetRenderCostDecrease();
3342                //oldNode->mPvsEntriesIncr = sc->GetPvsEntriesIncr();
3343
3344                /////////////
3345                //-- evaluate new split candidates for global greedy cost heuristics
3346
3347                VspSubdivisionCandidate *frontCandidate = new VspSubdivisionCandidate(tFrontData);
3348                VspSubdivisionCandidate *backCandidate = new VspSubdivisionCandidate(tBackData);
3349
3350                frontCandidate->SetPriority((float)-oldInterior->GetFront()->mTimeStamp);
3351                backCandidate->SetPriority((float)-oldInterior->GetBack()->mTimeStamp);
3352
3353                frontCandidate->mEvaluationHack = oldInterior->GetFront();
3354                backCandidate->mEvaluationHack = oldInterior->GetBack();
3355
3356                // cross reference
3357                tFrontData.mNode->SetSubdivisionCandidate(frontCandidate);
3358                tBackData.mNode->SetSubdivisionCandidate(backCandidate);
3359
3360                tQueue.Push(frontCandidate);
3361                tQueue.Push(backCandidate);
3362
3363                // note: leaf is not destroyed because it is needed to collect
3364                // dirty candidates in hierarchy manager
3365        }
3366
3367        if (newNode->IsLeaf()) // subdivision terminated
3368        {
3369                // detach subdivision candidate: this leaf is no candidate for splitting anymore
3370                tData.mNode->SetSubdivisionCandidate(NULL);
3371                // detach node so it won't get deleted
3372                tData.mNode = NULL;
3373        }
3374
3375        return newNode;
3376}
3377
3378}
Note: See TracBrowser for help on using the repository browser.