source: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.cpp @ 1904

Revision 1904, 65.1 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "ViewCell.h"
6#include "Plane3.h"
7#include "HierarchyManager.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 "VspTree.h"
21#include "OspTree.h"
22#include "BvHierarchy.h"
23#include "ViewCell.h"
24
25
26namespace GtpVisibilityPreprocessor {
27
28
29#define USE_FIXEDPOINT_T 0
30
31#define STUPID_METHOD 0
32
33
34
35/*******************************************************************/
36/*              class HierarchyManager implementation              */
37/*******************************************************************/
38
39
40HierarchyManager::HierarchyManager(const int objectSpaceSubdivisionType):
41mObjectSpaceSubdivisionType(objectSpaceSubdivisionType),
42mOspTree(NULL),
43mBvHierarchy(NULL)
44{
45        switch(mObjectSpaceSubdivisionType)
46        {
47        case KD_BASED_OBJ_SUBDIV:
48                mOspTree = new OspTree();
49                mOspTree->mVspTree = mVspTree;
50                mOspTree->mHierarchyManager = this;
51                break;
52        case BV_BASED_OBJ_SUBDIV:
53        mBvHierarchy = new BvHierarchy();
54                mBvHierarchy->mHierarchyManager = this;
55                break;
56        default:
57                break;
58        }
59
60        // hierarchy manager links view space partition and object space partition
61        mVspTree = new VspTree();
62        mVspTree->mHierarchyManager = this;
63       
64        mViewSpaceSubdivisionType = KD_BASED_VIEWSPACE_SUBDIV;
65        ParseEnvironment();
66}
67
68
69HierarchyManager::HierarchyManager(KdTree *kdTree):
70mObjectSpaceSubdivisionType(KD_BASED_OBJ_SUBDIV),
71mBvHierarchy(NULL)
72{
73        mOspTree = new OspTree(*kdTree);
74        mOspTree->mVspTree = mVspTree;
75
76        mVspTree = new VspTree();
77        mVspTree->mHierarchyManager = this;
78
79        mViewSpaceSubdivisionType = KD_BASED_VIEWSPACE_SUBDIV;
80        ParseEnvironment();
81}
82
83
84void HierarchySubdivisionStats::Print(ostream &app) const
85{
86        app << "#Pass\n" << 0 << endl
87                << "#Splits\n" << mNumSplits << endl
88                << "#TotalRenderCost\n" << mTotalRenderCost << endl
89                << "#TotalEntriesInPvs\n" << mEntriesInPvs << endl
90                << "#Memory\n" << mMemoryCost << endl
91                << "#StepsView\n" << mViewSpaceSplits << endl
92                << "#StepsObject\n" << mObjectSpaceSplits << endl
93                << "#VspOspRatio\n" << VspOspRatio() << endl
94                << "#FullMem\n" << mFullMemory << endl
95                << "#RenderCostDecrease\n" << mRenderCostDecrease << endl
96                << "#Priority\n" << mPriority << endl
97                << "#FpsPerMb\n" << FpsPerMb() << endl
98                << endl;
99}
100
101
102void HierarchyManager::ParseEnvironment()
103{
104        Environment::GetSingleton()->GetFloatValue(
105                "Hierarchy.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
106        Environment::GetSingleton()->GetIntValue(
107                "Hierarchy.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
108
109        Environment::GetSingleton()->GetBoolValue(
110                "Hierarchy.Construction.startWithObjectSpace", mStartWithObjectSpace);
111
112        Environment::GetSingleton()->GetIntValue(
113                "Hierarchy.Termination.maxLeaves", mTermMaxLeaves);
114
115        Environment::GetSingleton()->GetIntValue(
116                "Hierarchy.Construction.type", mConstructionType);
117
118        Environment::GetSingleton()->GetIntValue(
119                "Hierarchy.Construction.minDepthForOsp", mMinDepthForObjectSpaceSubdivion);
120
121        Environment::GetSingleton()->GetIntValue(
122                "Hierarchy.Construction.minDepthForVsp", mMinDepthForViewSpaceSubdivion);
123       
124        Environment::GetSingleton()->GetBoolValue(
125                "Hierarchy.Construction.repairQueue", mRepairQueue);
126
127        Environment::GetSingleton()->GetBoolValue(
128                "Hierarchy.Construction.useMultiLevel", mUseMultiLevelConstruction);
129
130        Environment::GetSingleton()->GetIntValue(
131                "Hierarchy.Construction.levels", mNumMultiLevels);
132
133        Environment::GetSingleton()->GetIntValue(
134                "Hierarchy.Construction.minStepsOfSameType", mMinStepsOfSameType);
135       
136        Environment::GetSingleton()->GetIntValue(
137                "Hierarchy.Construction.maxStepsOfSameType", mMaxStepsOfSameType);
138
139        char subdivisionStatsLog[100];
140        Environment::GetSingleton()->GetStringValue("Hierarchy.subdivisionStats", subdivisionStatsLog);
141        mSubdivisionStats.open(subdivisionStatsLog);
142
143        Environment::GetSingleton()->GetBoolValue(
144                "Hierarchy.Construction.recomputeSplitPlaneOnRepair", mRecomputeSplitPlaneOnRepair);
145
146        Environment::GetSingleton()->GetBoolValue(
147                "Hierarchy.Construction.considerMemory", mConsiderMemory);
148
149        Environment::GetSingleton()->GetFloatValue(
150                "Hierarchy.Termination.maxMemory", mTermMaxMemory);
151
152        Environment::GetSingleton()->GetIntValue(
153                "Hierarchy.Construction.maxRepairs", mMaxRepairs);
154
155        Environment::GetSingleton()->GetFloatValue(
156                "Hierarchy.Construction.maxAvgRayContri", mMaxAvgRayContri);
157
158        // for comparing it with byte - value
159        mTermMaxMemory *= (1024.0f * 1024.0f);
160
161        Debug << "******** Hierarchy Manager Options ***********" << endl;
162        Debug << "max leaves: " << mTermMaxLeaves << endl;
163        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
164        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
165        Debug << "min depth for object space subdivision: " << mMinDepthForObjectSpaceSubdivion << endl;
166        Debug << "repair queue: " << mRepairQueue << endl;
167        Debug << "number of multilevels: " << mNumMultiLevels << endl;
168        Debug << "recompute split plane on repair: " << mRecomputeSplitPlaneOnRepair << endl;
169        Debug << "minimal number of steps from same type: " << mMinStepsOfSameType << endl;
170        Debug << "maximal allowed memory: " << mTermMaxMemory << endl;
171        Debug << "consider memory: " << mConsiderMemory << endl;
172        Debug << "min steps of same kind: " << mMinStepsOfSameType << endl;
173        Debug << "max steps of same kind: " << mMaxStepsOfSameType << endl;
174        Debug << "max repairs: " << mMaxRepairs << endl;
175        Debug << "max avg ray contribution: " << mMaxAvgRayContri << endl;
176
177
178        switch (mConstructionType)
179        {
180        case 0:
181                Debug << "construction type: sequential" << endl;
182                break;
183        case 1:
184                Debug << "construction type: interleaved" << endl;
185                break;
186        case 2:
187                Debug << "construction type: gradient" << endl;
188                break;
189        case 3:
190                Debug << "construction type: multilevel" << endl;
191                break;
192        default:
193                Debug << "construction type " << mConstructionType << " unknown" << endl;
194                break;
195        }
196
197        //Debug << "min render cost " << mMinRenderCostDecrease << endl;
198        Debug << endl;
199}
200
201
202HierarchyManager::~HierarchyManager()
203{
204        DEL_PTR(mOspTree);
205        DEL_PTR(mVspTree);
206        DEL_PTR(mBvHierarchy);
207}
208
209
210int HierarchyManager::GetObjectSpaceSubdivisionType() const
211{
212        return mObjectSpaceSubdivisionType;
213}
214
215
216int HierarchyManager::GetViewSpaceSubdivisionType() const
217{
218        return mViewSpaceSubdivisionType;
219}
220
221
222void HierarchyManager::SetViewCellsManager(ViewCellsManager *vcm)
223{
224        mVspTree->SetViewCellsManager(vcm);
225
226        if (mOspTree)
227        {
228                mOspTree->SetViewCellsManager(vcm);
229        }
230        else if (mBvHierarchy)
231        {
232                mBvHierarchy->SetViewCellsManager(vcm);
233        }
234}
235
236
237void HierarchyManager::SetViewCellsTree(ViewCellsTree *vcTree)
238{
239        mVspTree->SetViewCellsTree(vcTree);
240}
241
242
243VspTree *HierarchyManager::GetVspTree()
244{
245        return mVspTree;
246}
247
248/*
249AxisAlignedBox3 HierarchyManager::GetViewSpaceBox() const
250{
251        return mVspTree->mBoundingBox;
252}*/
253
254
255AxisAlignedBox3 HierarchyManager::GetObjectSpaceBox() const
256{
257        switch (mObjectSpaceSubdivisionType)
258        {
259        case KD_BASED_OBJ_SUBDIV:
260                return mOspTree->mBoundingBox;
261        case BV_BASED_OBJ_SUBDIV:
262                return mBvHierarchy->mBoundingBox;
263        default:
264                // hack: empty box
265                return AxisAlignedBox3();
266        }
267}
268
269
270SubdivisionCandidate *HierarchyManager::NextSubdivisionCandidate(SplitQueue &splitQueue)
271{
272        SubdivisionCandidate *splitCandidate = splitQueue.Top();
273        splitQueue.Pop();
274
275        // split was not reevaluated before => do it now
276        if (splitCandidate->IsDirty())
277                splitCandidate->EvalCandidate();
278
279        return splitCandidate;
280}
281
282
283float HierarchyManager::EvalFullMem() const
284{
285        // question: should I also add the mem usage of the hierarchies?
286        const float objectSpaceMem = 16;//GetObjectSpaceMemUsage();
287        const float viewSpaceMem = 16;//mVspTree->GetMemUsage();
288        // HACK: the same value is used for view and object space
289        return mHierarchyStats.mMemory + mHierarchyStats.Leaves() * objectSpaceMem;
290}
291
292
293void HierarchyManager::EvalSubdivisionStats()
294{
295       
296        HierarchySubdivisionStats stats;
297
298        stats.mNumSplits = mHierarchyStats.Leaves();
299        stats.mTotalRenderCost = mHierarchyStats.mTotalCost;
300        stats.mEntriesInPvs = mHierarchyStats.mPvsEntries;
301        stats.mMemoryCost = mHierarchyStats.mMemory  / float(1024 * 1024);
302        stats.mFullMemory = EvalFullMem() / float(1024 * 1024);
303        stats.mViewSpaceSplits = mVspTree->mVspStats.Leaves();
304        stats.mObjectSpaceSplits = GetObjectSpaceSubdivisionLeaves();
305        stats.mRenderCostDecrease = mHierarchyStats.mRenderCostDecrease;
306        stats.mPriority = mPriority;
307
308        stats.Print(mSubdivisionStats);
309}
310
311
312void HierarchyManager::AddSubdivisionStats(const int splits,
313                                                                                   const float renderCostDecr,
314                                                                                   const float totalRenderCost,
315                                                                                   const int pvsEntries,
316                                                                                   const float memory,
317                                                                                   const float renderCostPerStorage,
318                                                                                   const float vspOspRatio)
319{
320        mSubdivisionStats
321                        << "#Splits\n" << splits << endl
322                        << "#RenderCostDecrease\n" << renderCostDecr << endl
323                        << "#TotalEntriesInPvs\n" << pvsEntries << endl
324                        << "#TotalRenderCost\n" << totalRenderCost << endl
325                        << "#Memory\n" << memory << endl
326                        << "#FpsPerMb\n" << renderCostPerStorage << endl
327                        << "#VspOspRatio\n" << vspOspRatio << endl
328                        << endl;
329}
330
331
332bool HierarchyManager::GlobalTerminationCriteriaMet(SubdivisionCandidate *candidate) const
333{
334        const bool terminationCriteriaMet =
335                (0
336                || (mHierarchyStats.Leaves() >= mTermMaxLeaves)
337                //|| (mHierarchyStats.mMemory >= mTermMaxMemory)
338                || (EvalFullMem() >= mTermMaxMemory)
339                || candidate->GlobalTerminationCriteriaMet()
340                //|| (mHierarchyStats.mRenderCostDecrease < mMinRenderCostDecrease)
341                //|| (mHierarchyStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
342                );
343
344#if GTP_DEBUG
345        if (terminationCriteriaMet)
346        {
347                Debug << "hierarchy global termination criteria met:" << endl;
348                Debug << "leaves: " << mHierarchyStats.Leaves() << " " << mTermMaxLeaves << endl;
349                Debug << "cost misses: " << mHierarchyStats.mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl;
350                Debug << "memory: " << mHierarchyStats.mMemory << " " << mTermMaxMemory << endl;
351                Debug << "full memory: " << EvalFullMem() << " " << mTermMaxMemory << endl;
352        }
353#endif
354
355        return terminationCriteriaMet;
356}
357
358
359void HierarchyManager::Construct(const VssRayContainer &sampleRays,
360                                                                 const ObjectContainer &objects,
361                                                                 AxisAlignedBox3 *forcedViewSpace)
362{
363        mTimeStamp = 1;
364
365        switch (mConstructionType)
366        {
367        case MULTILEVEL:
368                ConstructMultiLevel(sampleRays, objects, forcedViewSpace);
369                break;
370        case INTERLEAVED:
371        case SEQUENTIAL:
372                ConstructInterleaved(sampleRays, objects, forcedViewSpace);
373                break;
374        case GRADIENT:
375                ConstructInterleavedWithGradient(sampleRays, objects, forcedViewSpace);
376                break;
377        default:
378                break;
379        }
380
381        // hack: should be different parameter name
382        if (mUseMultiLevelConstruction)
383        {
384                cout << "starting optimizing multilevel ... " << endl;
385                // try to optimize on the above hierarchy
386                OptimizeMultiLevel(sampleRays, objects, forcedViewSpace);
387               
388                cout << "finished" << endl;
389        }
390}
391
392
393void HierarchyManager::ConstructInterleavedWithGradient(const VssRayContainer &sampleRays,
394                                                                                                                const ObjectContainer &objects,
395                                                                                                                AxisAlignedBox3 *forcedViewSpace)
396{
397        mHierarchyStats.Reset();
398        mHierarchyStats.Start();
399       
400        mHierarchyStats.mNodes = 2;
401
402        // create first nodes
403        mVspTree->Initialise(sampleRays, forcedViewSpace);
404        InitialiseObjectSpaceSubdivision(objects);
405
406        // hack: assume that object space can be seen from view space
407        mHierarchyStats.mTotalCost = mInitialRenderCost = (float)objects.size();
408        // only one entry for start
409        mHierarchyStats.mPvsEntries = 1;
410        mHierarchyStats.mMemory = (float)ObjectPvs::GetEntrySizeByte();
411
412        EvalSubdivisionStats();
413        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
414
415        const long startTime = GetTime();
416        cout << "Constructing view space / object space tree ... \n";
417       
418        SplitQueue objectSpaceQueue;
419        SplitQueue viewSpaceQueue;
420
421        int vspSteps = 0, ospSteps = 0;
422
423        // use sah for evaluating osp tree construction
424        // in the first iteration of the subdivision
425        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
426        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
427        mSavedObjectSpaceSubdivisionType = mObjectSpaceSubdivisionType;
428
429        // number of initial splits
430        const int minSteps = mMinStepsOfSameType;
431        const int maxSteps = mMaxStepsOfSameType;
432
433        PrepareObjectSpaceSubdivision(objectSpaceQueue, sampleRays, objects);
434       
435        /////////////////////////
436        // calulcate initial object space splits
437       
438        SubdivisionCandidateContainer dirtyList;
439
440        // subdivide object space first
441        // for first round, use sah splits. Once view space partition
442        // has started, use render cost heuristics instead
443        ospSteps = RunConstruction(objectSpaceQueue,
444                                                           dirtyList,
445                                                           NULL,
446                                                           minSteps,
447                                                           maxSteps);
448
449        cout << "\n" << ospSteps << " object space partition steps taken" << endl;
450
451        // create view space
452        PrepareViewSpaceSubdivision(viewSpaceQueue, sampleRays, objects);
453
454        dirtyList.clear();
455
456        // view space subdivision started
457        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
458
459        if (1)
460        {
461                // rather also start with 100 view space splits to avoid initial bias.
462                vspSteps = RunConstruction(viewSpaceQueue, dirtyList, NULL, minSteps, maxSteps);
463                cout << "\n" << vspSteps << " view space partition steps taken" << endl;
464               
465                /// Repair split queue
466                cout << "repairing queue ... " << endl;
467                RepairQueue(dirtyList, objectSpaceQueue, true);
468                cout << "repaired " << (int)dirtyList.size() << " candidates" << endl;
469
470                dirtyList.clear();
471        }
472        else
473        {
474                // the priorities were calculated for driving sah.
475                // => recalculate "real" priorities taking visibility into
476                // account so we can compare to view space splits
477                ResetQueue(objectSpaceQueue, false);
478        }
479
480        // This method subdivides view space / object space
481        // in order to converge to some optimal cost for this partition
482        // start with object space partiton
483        // then optimizate view space partition for the current osp
484        // and vice versa until iteration depth is reached.
485
486        bool lastSplitWasOsp = true;
487
488        while (!(viewSpaceQueue.Empty() && objectSpaceQueue.Empty()))
489        {
490                // decide upon next split type
491                const float vspPriority =
492                        viewSpaceQueue.Top() ? viewSpaceQueue.Top()->GetPriority() : -1e20f;
493                const float ospPriority =
494                        objectSpaceQueue.Top() ? objectSpaceQueue.Top()->GetPriority() : -1e20f;
495               
496                cout << "new decicion, vsp: " << vspPriority << ", osp: " << ospPriority << endl;
497
498                // should view or object space be subdivided further?
499                if (ospPriority >= vspPriority)
500                //if (!lastSplitWasOsp)
501                {
502                        lastSplitWasOsp = true;
503                        cout << "osp" << endl;
504                       
505                        // dirtied view space candidates
506                        SubdivisionCandidateContainer dirtyVspList;
507
508                        // subdivide object space first for first round,
509                        // use sah splits. Once view space partition
510                        // has started, use render cost heuristics instead
511                        const int ospSteps = RunConstruction(objectSpaceQueue,
512                                                                                                 dirtyVspList,
513                                                                                                 viewSpaceQueue.Top(),
514                                                                                                 minSteps,
515                                                                                                 maxSteps);
516
517                        cout << "\n" << ospSteps << " object space partition steps taken" << endl;
518                        Debug << "\n" << ospSteps << " object space partition steps taken" << endl;
519
520                        /// Repair split queue, i.e., affected view space candidates
521                        cout << "repairing queue ... " << endl;
522                        const int repaired = RepairQueue(dirtyVspList, viewSpaceQueue, true);
523           
524                        cout << "\nrepaired " << repaired << " candidates from "
525                                 << (int)dirtyVspList.size() << " dirtied candidates" << endl;
526                }
527                else
528                {
529                        lastSplitWasOsp = false;
530                        cout << "vsp" << endl;
531                       
532                        /////////////////
533                        // subdivide view space with respect to the objects
534
535                        // dirtied object space candidates
536                        SubdivisionCandidateContainer dirtyOspList;
537
538                        // process view space candidates
539                        const int vspSteps = RunConstruction(viewSpaceQueue,
540                                                                                                 dirtyOspList,
541                                                                                                 objectSpaceQueue.Top(),
542                                                                                                 minSteps,
543                                                                                                 maxSteps);
544
545                        cout << "\n" << vspSteps << " view space partition steps taken" << endl;
546                        Debug << "\n" << vspSteps << " view space partition steps taken" << endl;
547
548                        // view space subdivision constructed
549                        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
550
551                        /// Repair split queue
552                        cout << "repairing queue ... " << endl;
553                        const int repaired = RepairQueue(dirtyOspList, objectSpaceQueue, true);
554
555                        cout << "\nrepaired " << repaired << " candidates from "
556                                 << (int)dirtyOspList.size() << " dirtied candidates" << endl;
557                }
558        }
559
560        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
561
562        mHierarchyStats.Stop();
563        mVspTree->mVspStats.Stop();
564
565        FinishObjectSpaceSubdivision(objects, !mUseMultiLevelConstruction);
566}
567
568
569void HierarchyManager::ConstructInterleaved(const VssRayContainer &sampleRays,
570                                                                                        const ObjectContainer &objects,
571                                                                                        AxisAlignedBox3 *forcedViewSpace)
572{
573        mHierarchyStats.Reset();
574        mHierarchyStats.Start();
575
576        // two nodes for view space and object space
577        mHierarchyStats.mNodes = 2;
578        mHierarchyStats.mPvsEntries = 1;
579        mHierarchyStats.mMemory = (float)ObjectPvs::GetEntrySizeByte();
580        mHierarchyStats.mTotalCost = (float)objects.size();
581
582        mHierarchyStats.mRenderCostDecrease = 0;
583
584        EvalSubdivisionStats();
585        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
586
587        const long startTime = GetTime();
588        cout << "Constructing view space / object space tree ... \n";
589       
590        // create only roots
591        mVspTree->Initialise(sampleRays, forcedViewSpace);
592        InitialiseObjectSpaceSubdivision(objects);
593
594        // use objects for evaluating vsp tree construction in the
595        // first levels of the subdivision
596        mSavedObjectSpaceSubdivisionType = mObjectSpaceSubdivisionType;
597        mObjectSpaceSubdivisionType = NO_OBJ_SUBDIV;
598
599        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
600        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
601
602        // start view space subdivison immediately?
603        if (StartViewSpaceSubdivision())
604        {
605                // prepare vsp tree for traversal
606        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
607                PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
608        }
609       
610        // start object space subdivision immediately?
611        if (StartObjectSpaceSubdivision())
612        {
613                mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
614                PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
615        }
616       
617        // begin subdivision
618        RunConstruction(mRepairQueue, sampleRays, objects, forcedViewSpace);
619       
620        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
621
622        mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
623        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
624
625        mHierarchyStats.Stop();
626        mVspTree->mVspStats.Stop();
627       
628        FinishObjectSpaceSubdivision(objects, !mUseMultiLevelConstruction);
629}
630
631
632void HierarchyManager::PrepareViewSpaceSubdivision(SplitQueue &tQueue,
633                                                                                                   const VssRayContainer &sampleRays,
634                                                                                                   const ObjectContainer &objects)
635{
636        cout << "\npreparing view space hierarchy construction ... " << endl;
637
638        // hack: reset global cost misses
639        mHierarchyStats.mGlobalCostMisses = 0;
640
641        RayInfoContainer *viewSpaceRays = new RayInfoContainer();
642        mVspTree->PrepareConstruction(tQueue, sampleRays, *viewSpaceRays);
643
644        /////////
645        //-- new stats
646
647        mHierarchyStats.mTotalCost = mVspTree->mTotalCost;
648        cout << "\nreseting cost for vsp, new total cost: " << mHierarchyStats.mTotalCost << endl;
649}
650
651
652float HierarchyManager::GetObjectSpaceMemUsage() const
653{
654        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
655        {
656                // TODO;
657        }
658        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
659        {
660                return mBvHierarchy->GetMemUsage();
661        }
662
663        return -1;
664}
665
666
667void HierarchyManager::InitialiseObjectSpaceSubdivision(const ObjectContainer &objects)
668{
669        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
670        {
671                // TODO;
672        }
673        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
674        {
675                mBvHierarchy->Initialise(objects);
676        }
677}
678
679
680void HierarchyManager::PrepareObjectSpaceSubdivision(SplitQueue &tQueue,
681                                                                                                         const VssRayContainer &sampleRays,
682                                                                                                         const ObjectContainer &objects)
683{
684        // hack: reset global cost misses
685        mHierarchyStats.mGlobalCostMisses = 0;
686
687        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
688        {
689                return PrepareOspTree(tQueue, sampleRays, objects);
690        }
691        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
692        {
693                return PrepareBvHierarchy(tQueue, sampleRays, objects);
694        }
695}
696
697
698void HierarchyManager::PrepareBvHierarchy(SplitQueue &tQueue,
699                                                                                  const VssRayContainer &sampleRays,
700                                                                                  const ObjectContainer &objects)
701{
702        const long startTime = GetTime();
703
704        cout << "preparing bv hierarchy construction ... " << endl;
705       
706        // compute first candidate
707        mBvHierarchy->PrepareConstruction(tQueue, sampleRays, objects);
708
709        mHierarchyStats.mTotalCost = mBvHierarchy->mTotalCost;
710        Debug << "\nreseting cost, new total cost: " << mHierarchyStats.mTotalCost << endl;
711
712        cout << "finished bv hierarchy preparation in "
713                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
714}
715
716
717void HierarchyManager::PrepareOspTree(SplitQueue &tQueue,
718                                                                          const VssRayContainer &sampleRays,
719                                                                          const ObjectContainer &objects)
720{
721        cout << "starting osp tree construction ... " << endl;
722
723        RayInfoContainer *objectSpaceRays = new RayInfoContainer();
724
725        // start with one big kd cell - all objects can be seen from everywhere
726        // note: only true for view space = object space
727
728        // compute first candidate
729        mOspTree->PrepareConstruction(tQueue, sampleRays, objects, *objectSpaceRays);
730
731        mHierarchyStats.mTotalCost = mOspTree->mTotalCost;
732        Debug << "\nreseting cost for osp, new total cost: " << mHierarchyStats.mTotalCost << endl;
733}
734
735
736bool HierarchyManager::ApplySubdivisionCandidate(SubdivisionCandidate *sc,
737                                                                                                 SplitQueue &splitQueue,
738                                                                                                 const bool repairQueue)
739{
740        const bool terminationCriteriaMet = GlobalTerminationCriteriaMet(sc);
741        const bool success = sc->Apply(splitQueue, terminationCriteriaMet);
742
743        if (sc->IsDirty())
744                cerr << "Error: Should never come here!" << endl;
745
746        if (!success) // split was not taken
747        {
748                cout << "x";
749                return false;
750        }
751
752        //cout << "priority: " << sc->GetPriority() << " rc decr: " << sc->GetRenderCostDecrease() << " | ";
753        ///////////////
754        //-- split was successful => update stats and queue
755
756    // cost ratio of cost decrease / totalCost
757        const float costRatio = sc->GetRenderCostDecrease() / mHierarchyStats.mTotalCost;
758        //cout << "ratio: " << costRatio << " min ratio: " << mTermMinGlobalCostRatio << endl;
759       
760        if (costRatio < mTermMinGlobalCostRatio)
761        {
762                ++ mHierarchyStats.mGlobalCostMisses;
763        }
764       
765        cout << sc->Type() << " ";
766               
767        /////////////
768        // update stats
769
770        mHierarchyStats.mNodes += 2;
771        mHierarchyStats.mTotalCost -= sc->GetRenderCostDecrease();
772
773        const int pvsEntriesIncr = sc->GetPvsEntriesIncr();
774        mHierarchyStats.mPvsEntries += pvsEntriesIncr;
775        //cout << "pvs entries: " << pvsEntriesIncr << " " << mHierarchyStats.pvsEntries << endl;
776
777        // memory size in byte
778        float mem = (float)ObjectPvs::GetEntrySizeByte() * pvsEntriesIncr;
779
780        // high avg ray contri, the result is influenced by undersampling
781        // => decrease priority
782        if (USE_AVGRAYCONTRI && (sc->GetAvgRayContribution() > mMaxAvgRayContri))
783        {
784                const float factor = 1.0f + sc->GetAvgRayContribution() - mMaxAvgRayContri;
785                cout << "h " << factor << endl;
786
787                mem *= factor;
788        }
789       
790        mHierarchyStats.mMemory += mem;
791        mHierarchyStats.mRenderCostDecrease = sc->GetRenderCostDecrease();
792       
793        mPriority = sc->GetPriority();
794
795        //////////
796        // show current memory
797
798        static float memoryCount = 0;
799
800        if (mHierarchyStats.mMemory > memoryCount)
801        {
802                memoryCount += 100000;
803                cout << "\nstorage cost: " << mHierarchyStats.mMemory / float(1024 * 1024)
804                         << " MB, steps: " << mHierarchyStats.Leaves() << endl;
805        }
806
807        // output stats
808        EvalSubdivisionStats();
809               
810        if (repairQueue)
811        {
812                // reevaluate candidates affected by the split for view space splits,
813                // this would be object space splits and other way round
814                vector<SubdivisionCandidate *> dirtyList;
815                sc->CollectDirtyCandidates(dirtyList, false);
816
817                RepairQueue(dirtyList, splitQueue, mRecomputeSplitPlaneOnRepair);
818        }
819
820        return true;
821}
822
823
824int HierarchyManager::GetObjectSpaceSubdivisionDepth() const
825{
826        int maxDepth = 0;
827
828        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
829        {
830                maxDepth = mOspTree->mOspStats.maxDepth;
831        }
832        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
833        {
834                maxDepth = mBvHierarchy->mBvhStats.maxDepth;
835        }
836
837        return maxDepth;
838}
839
840
841int HierarchyManager::GetObjectSpaceSubdivisionLeaves() const
842{
843        int maxLeaves= 0;
844
845        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
846        {
847                maxLeaves = mOspTree->mOspStats.Leaves();
848        }
849        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
850        {
851                maxLeaves = mBvHierarchy->mBvhStats.Leaves();
852        }
853
854        return maxLeaves;
855}
856
857
858int HierarchyManager::GetObjectSpaceSubdivisionNodes() const
859{
860        int maxLeaves = 0;
861
862        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
863        {
864                maxLeaves = mOspTree->mOspStats.nodes;
865        }
866        else if (mObjectSpaceSubdivisionType == BV_BASED_OBJ_SUBDIV)
867        {
868                maxLeaves = mBvHierarchy->mBvhStats.nodes;
869        }
870
871        return maxLeaves;
872}
873
874bool HierarchyManager::StartObjectSpaceSubdivision() const
875{
876        // view space construction already started
877        if (ObjectSpaceSubdivisionConstructed())
878                return false;
879
880        // start immediately with object space subdivision?
881        if (mStartWithObjectSpace)
882                return true;
883
884        // is the queue empty again?
885        if (ViewSpaceSubdivisionConstructed() && mTQueue.Empty())
886                return true;
887
888        // has the depth for subdivision been reached?
889        return
890                ((mConstructionType == INTERLEAVED) &&
891                 (mMinStepsOfSameType <= mVspTree->mVspStats.nodes));
892}
893
894
895bool HierarchyManager::StartViewSpaceSubdivision() const
896{
897        // view space construction already started
898        if (ViewSpaceSubdivisionConstructed())
899                return false;
900
901        // start immediately with view space subdivision?
902        if (!mStartWithObjectSpace)
903                return true;
904
905        // is the queue empty again?
906        if (ObjectSpaceSubdivisionConstructed() && mTQueue.Empty())
907                return true;
908
909        // has the depth for subdivision been reached?
910        return
911                ((mConstructionType == INTERLEAVED) &&
912                 (mMinStepsOfSameType <= GetObjectSpaceSubdivisionLeaves()));
913}
914
915
916void HierarchyManager::RunConstruction(const bool repairQueue,
917                                                                           const VssRayContainer &sampleRays,
918                                                                           const ObjectContainer &objects,
919                                                                           AxisAlignedBox3 *forcedViewSpace)
920{
921        while (!FinishedConstruction())
922        {
923                SubdivisionCandidate *sc = NextSubdivisionCandidate(mTQueue);   
924       
925                ///////////////////
926                //-- subdivide leaf node
927
928                ApplySubdivisionCandidate(sc, mTQueue, repairQueue);
929                               
930                // we use objects for evaluating vsp tree construction until
931                // a certain depth once a certain depth existiert ...
932                if (StartObjectSpaceSubdivision())
933                {
934                        mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
935
936                        cout << "\nstarting object space subdivision after "
937                                 << mVspTree->mVspStats.nodes << " (" << mMinStepsOfSameType << ") steps, mem="
938                                 << mHierarchyStats.mMemory / float(1024 * 1024) << " MB" << endl;
939
940                        PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
941                       
942                        cout << "reseting queue ... ";
943                        ResetQueue(mTQueue, mRecomputeSplitPlaneOnRepair);
944                        cout << "finished" << endl;
945                }
946
947                if (StartViewSpaceSubdivision())
948                {
949                        mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
950
951                        cout << "\nstarting view space subdivision at "
952                                 << GetObjectSpaceSubdivisionLeaves() << " ("
953                                 << mMinStepsOfSameType << ") , mem="
954                                 << mHierarchyStats.mMemory / float(1024 * 1024) << " MB" << endl;
955
956                        PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
957
958                        cout << "reseting queue ... ";
959                        ResetQueue(mTQueue, mRecomputeSplitPlaneOnRepair);
960                        cout << "finished" << endl;
961                }
962
963                DEL_PTR(sc);
964        }
965}
966
967
968void HierarchyManager::RunConstruction(const bool repairQueue)
969{
970        // main loop
971        while (!FinishedConstruction())
972        {
973                SubdivisionCandidate *sc = NextSubdivisionCandidate(mTQueue);   
974               
975                ////////
976                //-- subdivide leaf node of either type
977
978        ApplySubdivisionCandidate(sc, mTQueue, repairQueue);
979               
980                DEL_PTR(sc);
981        }
982}
983
984
985int HierarchyManager::RunConstruction(SplitQueue &splitQueue,
986                                                                          SubdivisionCandidateContainer &dirtyCandidates,
987                                                                          SubdivisionCandidate *oldCandidate,
988                                                                          const int minSteps,
989                                                                          const int maxSteps)
990{
991        if (minSteps >= maxSteps)
992                cout << "error!! " << minSteps << " equal or larger maxSteps" << endl;
993
994        int steps = 0;
995        SubdivisionCandidate::NewMail();
996
997        // main loop
998        while (!splitQueue.Empty())
999        {
1000                const float priority = splitQueue.Top()->GetPriority();
1001                const float threshold = oldCandidate ? oldCandidate->GetPriority() : 1e20f;
1002
1003                // minimum slope reached
1004                if ((steps >= maxSteps) || ((priority < threshold) && !(steps < minSteps)))
1005                {
1006                        cout << "\nbreaking on " << priority << " smaller than " << threshold << endl;
1007                        break;
1008                }
1009               
1010                ////////
1011                //-- subdivide leaf node of either type
1012
1013                SubdivisionCandidate *sc = NextSubdivisionCandidate(splitQueue);
1014                       
1015                const bool repairQueue = false;
1016                const bool success = ApplySubdivisionCandidate(sc, splitQueue, repairQueue);
1017
1018                if (success)
1019                {
1020                        sc->CollectDirtyCandidates(dirtyCandidates, true);
1021                        ++ steps;
1022                }
1023
1024                DEL_PTR(sc);
1025        }
1026
1027        return steps;
1028}
1029
1030
1031void HierarchyManager::ResetObjectSpaceSubdivision(SplitQueue &tQueue,
1032                                                                                                   const VssRayContainer &sampleRays,
1033                                                                                                   const ObjectContainer &objects)
1034{       
1035        SubdivisionCandidate *firstCandidate;
1036
1037        // object space partition constructed => reconstruct
1038        switch (mObjectSpaceSubdivisionType)
1039        {
1040        case BV_BASED_OBJ_SUBDIV:
1041                {
1042                        cout << "\nreseting bv hierarchy" << endl;
1043                        Debug << "old bv hierarchy:\n " << mBvHierarchy->mBvhStats << endl;
1044                               
1045                        // rather use this: remove previous nodes and add the two new ones
1046                        //mHierarchyStats.mNodes -= mBvHierarchy->mBvhStats.nodes + 1;
1047                        mHierarchyStats.mNodes = mVspTree->mVspStats.nodes;
1048                       
1049                        // create root
1050                        mBvHierarchy->Initialise(objects);
1051       
1052                        mBvHierarchy->Reset(tQueue, sampleRays, objects);
1053
1054                        mHierarchyStats.mTotalCost = mBvHierarchy->mTotalCost;
1055                       
1056                        //mHierarchyStats.mPvsEntries -= mBvHierarchy->mPvsEntries + 1;
1057                        mHierarchyStats.mPvsEntries = mBvHierarchy->CountViewCells(objects);
1058
1059                        mHierarchyStats.mMemory =
1060                                (float)mHierarchyStats.mPvsEntries * ObjectPvs::GetEntrySizeByte();
1061
1062                        mHierarchyStats.mRenderCostDecrease = 0;
1063
1064                        // evaluate stats before first subdivision
1065                        EvalSubdivisionStats();
1066                        cout << "finished bv hierarchy preparation" << endl;
1067                }
1068                break;
1069
1070        case KD_BASED_OBJ_SUBDIV:
1071                // TODO
1072        default:
1073                break;
1074        }
1075}
1076
1077
1078void HierarchyManager::ResetViewSpaceSubdivision(SplitQueue &tQueue,
1079                                                                                                 const VssRayContainer &sampleRays,
1080                                                                                                 const ObjectContainer &objects,
1081                                                                                                 AxisAlignedBox3 *forcedViewSpace)
1082{
1083        ViewCellsManager *vm = mVspTree->mViewCellsManager;
1084
1085        // HACK: rather not destroy vsp tree
1086        DEL_PTR(mVspTree);
1087        mVspTree = new VspTree();
1088
1089        mVspTree->mHierarchyManager = this;
1090        mVspTree->mViewCellsManager = vm;
1091
1092        mVspTree->Initialise(sampleRays, forcedViewSpace);
1093       
1094        //////////
1095        //-- reset stats
1096    mHierarchyStats.mNodes = GetObjectSpaceSubdivisionNodes();
1097                //-mVspTree->mVspStats.nodes + 1;
1098       
1099        PrepareViewSpaceSubdivision(mTQueue, sampleRays, objects);
1100       
1101        mHierarchyStats.mPvsEntries = mVspTree->mPvsEntries;
1102        mHierarchyStats.mRenderCostDecrease = 0;
1103
1104        mHierarchyStats.mMemory =
1105                (float)mHierarchyStats.mPvsEntries * ObjectPvs::GetEntrySizeByte();
1106
1107        // evaluate new stats before first subdivsiion
1108        EvalSubdivisionStats();
1109}
1110
1111
1112void HierarchyManager::ConstructMultiLevel(const VssRayContainer &sampleRays,                                                                                   
1113                                                                                   const ObjectContainer &objects,
1114                                                                                   AxisAlignedBox3 *forcedViewSpace)
1115{
1116        mHierarchyStats.Reset();
1117        mHierarchyStats.Start();
1118        mHierarchyStats.mNodes = 2;
1119       
1120        mHierarchyStats.mTotalCost = (float)objects.size();
1121        Debug << "setting total cost to " << mHierarchyStats.mTotalCost << endl;
1122
1123        const long startTime = GetTime();
1124        cout << "Constructing view space / object space tree ... \n";
1125       
1126        // initialise view / object space
1127        mVspTree->Initialise(sampleRays, forcedViewSpace);
1128        InitialiseObjectSpaceSubdivision(objects);
1129
1130        // use sah for evaluating osp tree construction
1131        // in the first iteration of the subdivision
1132
1133        mSavedViewSpaceSubdivisionType = mViewSpaceSubdivisionType;
1134        mViewSpaceSubdivisionType = NO_VIEWSPACE_SUBDIV;
1135
1136        PrepareObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1137
1138        //////////////////////////
1139
1140
1141        const int limit = mNumMultiLevels;
1142        int i = 0;
1143
1144        // This method subdivides view space / object space
1145        // in order to converge to some optimal cost for this partition
1146        // start with object space partiton
1147        // then optimizate view space partition for the current osp
1148        // and vice versa until iteration depth is reached.
1149        while (1)
1150        {
1151                char subdivisionStatsLog[100];
1152                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", i);
1153                mSubdivisionStats.open(subdivisionStatsLog);
1154
1155                // subdivide object space first
1156                ResetObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1157
1158                // process object space candidates
1159                RunConstruction(false);
1160
1161                // object space subdivision constructed
1162                mObjectSpaceSubdivisionType = mSavedObjectSpaceSubdivisionType;
1163
1164                cout << "iteration " << i << " of " << limit << " finished" << endl;
1165                mSubdivisionStats.close();
1166
1167                if ((i ++) >= limit)
1168                        break;
1169
1170                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", i);
1171                mSubdivisionStats.open(subdivisionStatsLog);
1172
1173
1174                /////////////////
1175                // subdivide view space with respect to the objects
1176
1177                ResetViewSpaceSubdivision(mTQueue, sampleRays, objects, forcedViewSpace);
1178               
1179                // view space subdivision constructed
1180                mViewSpaceSubdivisionType = mSavedViewSpaceSubdivisionType;
1181               
1182                // process view space candidates
1183                RunConstruction(false);
1184
1185                cout << "iteration " << i << " of " << limit << " finished" << endl;
1186                mSubdivisionStats.close();
1187
1188                if ((i ++) >= limit)
1189                        break;
1190        }
1191       
1192        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
1193
1194        mHierarchyStats.Stop();
1195        mVspTree->mVspStats.Stop();
1196        FinishObjectSpaceSubdivision(objects);
1197}
1198
1199
1200void HierarchyManager::OptimizeMultiLevel(const VssRayContainer &sampleRays,                                                                                     
1201                                                                                  const ObjectContainer &objects,
1202                                                                                  AxisAlignedBox3 *forcedViewSpace)
1203{
1204        const long startTime = GetTime();
1205        const int limit = mNumMultiLevels;
1206
1207        // open up new subdivision
1208        mSubdivisionStats.close();
1209
1210        int steps = 0;
1211
1212        int maxViewSpaceLeaves = mVspTree->mVspStats.Leaves();
1213        int maxObjectSpaceLeaves;
1214       
1215        // set the number of leaves 'evaluated' from the previous methods
1216        // we go for the same numbers, but we try to optimize both subdivisions
1217        switch (mObjectSpaceSubdivisionType)
1218        {
1219        case BV_BASED_OBJ_SUBDIV:
1220                maxObjectSpaceLeaves = mBvHierarchy->mBvhStats.Leaves();
1221                break;
1222        case KD_BASED_OBJ_SUBDIV:
1223                maxObjectSpaceLeaves = mOspTree->mOspStats.Leaves();
1224        default:
1225                maxObjectSpaceLeaves = 0;
1226                break;
1227        }
1228
1229        // This method subdivides view space / object space
1230        // in order to converge to some optimal cost for this partition
1231        // start with object space partiton
1232        // then optimizate view space partition for the current osp
1233        // and vice versa until iteration depth is reached.
1234        while (1)
1235        {
1236                char subdivisionStatsLog[100];
1237                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", steps);
1238                mSubdivisionStats.open(subdivisionStatsLog);
1239
1240                // subdivide object space first
1241                ResetObjectSpaceSubdivision(mTQueue, sampleRays, objects);
1242       
1243                // set the number of leaves 'evaluated' from the previous methods
1244                // we go for the same numbers, but we try to optimize both subdivisions
1245                mBvHierarchy->mTermMaxLeaves = maxObjectSpaceLeaves;
1246
1247                // process object space candidates
1248                RunConstruction(false);
1249
1250                cout << "iteration " << steps << " of " << limit << " finished" << endl;
1251                mSubdivisionStats.close();
1252
1253                if ((++ steps) >= limit)
1254                        break;
1255
1256                sprintf(subdivisionStatsLog, "tests/i3d/subdivision-%04d.log", steps);
1257                mSubdivisionStats.open(subdivisionStatsLog);
1258
1259                /////////////////
1260                // subdivide view space with respect to the objects
1261
1262                ResetViewSpaceSubdivision(mTQueue, sampleRays, objects, forcedViewSpace);
1263
1264                mVspTree->mMaxViewCells = maxViewSpaceLeaves;
1265
1266                // process view space candidates
1267                RunConstruction(false);
1268
1269                cout << "iteration " << steps << " of " << limit << " finished" << endl;
1270                mSubdivisionStats.close();
1271
1272                if ((++ steps) >= limit)
1273                        break;
1274        }
1275       
1276        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
1277
1278        mHierarchyStats.Stop();
1279        mVspTree->mVspStats.Stop();
1280        FinishObjectSpaceSubdivision(objects);
1281}
1282
1283
1284
1285bool HierarchyManager::FinishedConstruction() const
1286{
1287        return mTQueue.Empty();
1288}
1289
1290
1291bool HierarchyManager::ObjectSpaceSubdivisionConstructed() const
1292{
1293        /*switch (mObjectSpaceSubdivisionType)
1294        {
1295        case KD_BASED_OBJ_SUBDIV:
1296                return mOspTree && mOspTree->GetRoot();
1297        case BV_BASED_OBJ_SUBDIV:
1298                return mBvHierarchy && mBvHierarchy->GetRoot();
1299        default:
1300                return false;
1301        }*/
1302        return mObjectSpaceSubdivisionType != NO_OBJ_SUBDIV;
1303}
1304
1305
1306bool HierarchyManager::ViewSpaceSubdivisionConstructed() const
1307{
1308        return mViewSpaceSubdivisionType != NO_VIEWSPACE_SUBDIV;
1309        //return mVspTree && mVspTree->GetRoot();
1310}
1311
1312
1313void HierarchyManager::CollectDirtyCandidates(const SubdivisionCandidateContainer &chosenCandidates,
1314                                                                                          SubdivisionCandidateContainer &dirtyList)
1315{
1316        SubdivisionCandidateContainer::const_iterator sit, sit_end = chosenCandidates.end();
1317        SubdivisionCandidate::NewMail();
1318
1319        for (sit = chosenCandidates.begin(); sit != sit_end; ++ sit)
1320        {
1321                (*sit)->CollectDirtyCandidates(dirtyList, true);
1322        }
1323}
1324
1325
1326int HierarchyManager::RepairQueue(const SubdivisionCandidateContainer &dirtyList,
1327                                                                  SplitQueue &splitQueue,
1328                                                                  const bool recomputeSplitPlaneOnRepair)
1329{
1330        // for each update of the view space partition:
1331        // the candidates from object space partition which
1332        // have been afected by the view space split (the kd split candidates
1333        // which saw the view cell which was split) must be reevaluated
1334        // (maybe not locally, just reinsert them into the queue)
1335        //
1336        // vice versa for the view cells
1337        // for each update of the object space partition
1338        // reevaluate split candidate for view cells which saw the split kd cell
1339        //
1340        // the priority queue update can be solved by implementing a binary heap
1341        // (explicit data structure, binary tree)
1342        // *) inserting and removal is efficient
1343        // *) search is not efficient => store queue position with each
1344        // split candidate
1345
1346        int repaired = 0;
1347
1348        // collect list of "dirty" candidates
1349        const long startTime = GetTime();
1350        if (0) cout << "repairing " << (int)dirtyList.size() << " candidates ... ";
1351
1352        const float prop = (float)mMaxRepairs / (float)dirtyList.size();
1353
1354        ///////////////////////////
1355        //-- reevaluate the dirty list
1356
1357        SubdivisionCandidateContainer::const_iterator sit, sit_end = dirtyList.end();
1358       
1359        for (sit = dirtyList.begin(); sit != sit_end; ++ sit)
1360        {
1361                // only repair a certain number of candidates
1362                if ((mMaxRepairs < (int)dirtyList.size()) && (Random(1.0f) >= prop))
1363                        continue;
1364
1365                SubdivisionCandidate* sc = *sit;
1366                const float rcd = sc->GetRenderCostDecrease();
1367               
1368                // erase from queue
1369                splitQueue.Erase(sc);
1370                // reevaluate candidate
1371                sc->EvalCandidate(recomputeSplitPlaneOnRepair);
1372                 // reinsert
1373                splitQueue.Push(sc);
1374               
1375                ++ repaired;
1376                cout << ".";
1377
1378#ifdef GTP_DEBUG
1379                Debug << "candidate " << sc << " reevaluated\n"
1380                          << "render cost decrease diff " <<  rcd - sc->GetRenderCostDecrease()
1381                          << " old: " << rcd << " new " << sc->GetRenderCostDecrease() << endl;
1382#endif 
1383        }
1384
1385        const long endTime = GetTime();
1386        const Real timeDiff = TimeDiff(startTime, endTime);
1387
1388        mHierarchyStats.mRepairTime += timeDiff;
1389
1390        return repaired;
1391}
1392
1393
1394void HierarchyManager::ResetQueue(SplitQueue &splitQueue, const bool recomputeSplitPlane)
1395{
1396        SubdivisionCandidateContainer mCandidateBuffer;
1397
1398        // remove from queue
1399        while (!splitQueue.Empty())
1400        {
1401                SubdivisionCandidate *candidate = NextSubdivisionCandidate(splitQueue);
1402               
1403                // reevaluate local split plane and priority
1404                candidate->EvalCandidate(recomputeSplitPlane);
1405                cout << ".";
1406                mCandidateBuffer.push_back(candidate);
1407        }
1408
1409        // put back into queue
1410        SubdivisionCandidateContainer::const_iterator sit, sit_end = mCandidateBuffer.end();
1411    for (sit = mCandidateBuffer.begin(); sit != sit_end; ++ sit)
1412        {
1413                splitQueue.Push(*sit);
1414        }
1415}
1416
1417
1418void HierarchyManager::ExportObjectSpaceHierarchy(OUT_STREAM &stream)
1419{
1420        // the type of the view cells hierarchy
1421        switch (mObjectSpaceSubdivisionType)
1422        {
1423        case KD_BASED_OBJ_SUBDIV:
1424                stream << "<ObjectSpaceHierarchy type=\"osp\">" << endl;
1425                mOspTree->Export(stream);
1426                stream << endl << "</ObjectSpaceHierarchy>" << endl;
1427                break;         
1428        case BV_BASED_OBJ_SUBDIV:
1429                stream << "<ObjectSpaceHierarchy type=\"bvh\">" << endl;
1430                mBvHierarchy->Export(stream);
1431                stream << endl << "</ObjectSpaceHierarchy>" << endl;
1432                break;
1433        }
1434}
1435
1436
1437void HierarchyManager::PrintHierarchyStatistics(ostream &stream) const
1438{
1439        stream << mHierarchyStats << endl;
1440        stream << "\nview space:" << endl << endl;
1441        stream << mVspTree->GetStatistics() << endl;
1442        stream << "\nobject space:" << endl << endl;
1443
1444        switch (mObjectSpaceSubdivisionType)
1445        {
1446        case KD_BASED_OBJ_SUBDIV:
1447                {
1448                        stream << mOspTree->GetStatistics() << endl;
1449                        break;
1450                }
1451        case BV_BASED_OBJ_SUBDIV:
1452                {
1453                        stream << mBvHierarchy->GetStatistics() << endl;
1454                        break;
1455                }
1456        default:
1457                break;
1458        }
1459}
1460
1461
1462void HierarchyManager::ExportObjectSpaceHierarchy(Exporter *exporter,
1463                                                                                                  const ObjectContainer &objects,
1464                                                                                                  AxisAlignedBox3 *bbox,
1465                                                                                                  const bool exportBounds) const
1466{
1467        switch (mObjectSpaceSubdivisionType)
1468        {
1469        case KD_BASED_OBJ_SUBDIV:
1470                {
1471                        ExportOspTree(exporter, objects);
1472                        break;
1473                }
1474        case BV_BASED_OBJ_SUBDIV:
1475                {
1476                        exporter->ExportBvHierarchy(*mBvHierarchy, 0, bbox, exportBounds);
1477                        break;
1478                }
1479        default:
1480                break;
1481        }
1482}
1483
1484
1485void HierarchyManager::ExportOspTree(Exporter *exporter,
1486                                                                         const ObjectContainer &objects) const
1487{
1488        if (0) exporter->ExportGeometry(objects);
1489                       
1490        exporter->SetWireframe();
1491        exporter->ExportOspTree(*mOspTree, 0);
1492}
1493
1494
1495Intersectable *HierarchyManager::GetIntersectable(Intersectable *obj,
1496                                                                                                  const Vector3 &point) const
1497{
1498
1499        if (!obj)
1500                return NULL;
1501
1502        switch (mObjectSpaceSubdivisionType)
1503        {
1504        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
1505                {
1506                        KdLeaf *leaf = mOspTree->GetLeaf(point, NULL);
1507                        return mOspTree->GetOrCreateKdIntersectable(leaf);
1508                }
1509        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
1510                {
1511                        BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
1512                        return leaf;
1513                }
1514        default:
1515                return obj;
1516        }
1517}
1518
1519Intersectable *HierarchyManager::GetIntersectable(const VssRay &ray,
1520                                                                                                  const bool isTermination) const
1521{
1522        Intersectable *obj = NULL;
1523        Vector3 pt;
1524        KdNode *node;
1525
1526        ray.GetSampleData(isTermination, pt, &obj, &node);
1527
1528        if (!obj)
1529                return NULL;
1530
1531        switch (mObjectSpaceSubdivisionType)
1532        {
1533        case HierarchyManager::KD_BASED_OBJ_SUBDIV:
1534                {
1535                        KdLeaf *leaf = mOspTree->GetLeaf(pt, node);
1536                        return mOspTree->GetOrCreateKdIntersectable(leaf);
1537                }
1538        case HierarchyManager::BV_BASED_OBJ_SUBDIV:
1539                {
1540                        BvhLeaf *leaf = mBvHierarchy->GetLeaf(obj);
1541                        return leaf;
1542                }
1543        default:
1544                break;
1545        }
1546
1547        return obj;
1548}
1549
1550
1551void HierarchyStatistics::Print(ostream &app) const
1552{
1553        app << "=========== Hierarchy statistics ===============\n";
1554
1555        app << setprecision(4);
1556
1557        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
1558       
1559        app << "#N_RTIME  ( Repair time [s] )\n" << mRepairTime * 1e-3f << " \n";
1560
1561        app << "#N_NODES ( Number of nodes )\n" << mNodes << "\n";
1562
1563        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
1564
1565        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
1566
1567        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << mMaxDepth << endl;
1568
1569        app << "#N_GLOBALCOSTMISSES ( Global cost misses )\n" << mGlobalCostMisses << endl;
1570       
1571        app << "========== END OF Hierarchy statistics ==========\n";
1572}
1573
1574
1575static void RemoveRayRefs(const ObjectContainer &objects)
1576{
1577        ObjectContainer::const_iterator oit, oit_end = objects.end();
1578        for (oit = objects.begin(); oit != oit_end; ++ oit)
1579        {
1580                (*oit)->DelRayRefs();
1581        }
1582}
1583
1584
1585void HierarchyManager::FinishObjectSpaceSubdivision(const ObjectContainer &objects,
1586                                                                                                        const bool removeRayRefs) const
1587{
1588        switch (mObjectSpaceSubdivisionType)
1589        {
1590        case KD_BASED_OBJ_SUBDIV:
1591                {
1592                        mOspTree->mOspStats.Stop();
1593                        break;
1594                }
1595        case BV_BASED_OBJ_SUBDIV:
1596                {
1597                        mBvHierarchy->mBvhStats.Stop();
1598                        if (removeRayRefs)
1599                                RemoveRayRefs(objects);
1600                        break;
1601                }
1602        default:
1603                break;
1604        }
1605}
1606
1607
1608void HierarchyManager::ExportBoundingBoxes(OUT_STREAM &stream, const ObjectContainer &objects)
1609{
1610        stream << "<BoundingBoxes>" << endl;
1611           
1612        if (mObjectSpaceSubdivisionType == KD_BASED_OBJ_SUBDIV)
1613        {
1614                KdIntersectableMap::const_iterator kit, kit_end = mOspTree->mKdIntersectables.end();
1615
1616                int id = 0;
1617                for (kit = mOspTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
1618                {
1619                        Intersectable *obj = (*kit).second;
1620                        const AxisAlignedBox3 box = obj->GetBox();
1621               
1622                        obj->SetId(id);
1623
1624                        stream << "<BoundingBox" << " id=\"" << id << "\""
1625                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1626                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1627                }
1628        }
1629        else
1630        {
1631                ObjectContainer::const_iterator oit, oit_end = objects.end();
1632
1633                for (oit = objects.begin(); oit != oit_end; ++ oit)
1634                {
1635                        const AxisAlignedBox3 box = (*oit)->GetBox();
1636               
1637                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
1638                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1639                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1640                }
1641        }
1642               
1643        stream << "</BoundingBoxes>" << endl;
1644}
1645
1646
1647class HierarchyNodeWrapper;
1648
1649
1650template <typename T> class myless
1651{
1652public:
1653        bool operator() (T v1, T v2) const
1654        {
1655                return (v1->GetMergeCost() < v2->GetMergeCost());
1656        }
1657};
1658
1659
1660typedef priority_queue<HierarchyNodeWrapper *, vector<HierarchyNodeWrapper *>,
1661                                           myless<vector<HierarchyNodeWrapper *>::value_type> > HierarchyNodeQueue;
1662
1663class HierarchyNodeWrapper
1664{
1665public:
1666        enum {VSP_NODE, BVH_NODE, VIEW_CELL};
1667
1668        virtual float GetMergeCost() const = 0;
1669        virtual int Type() const  = 0;
1670        virtual bool IsLeaf() const = 0;
1671
1672        virtual void PushChildren(HierarchyNodeQueue &tQueue) = 0;
1673};
1674
1675
1676class VspNodeWrapper: public HierarchyNodeWrapper
1677{
1678public:
1679        VspNodeWrapper(VspNode *node): mNode(node) {}
1680
1681        int Type() const { return VSP_NODE; }
1682
1683        float GetMergeCost() const { return (float) -mNode->mTimeStamp; };
1684
1685        bool IsLeaf() const { return mNode->IsLeaf(); }
1686
1687        void PushChildren(HierarchyNodeQueue &tQueue)
1688        {
1689                if (!mNode->IsLeaf())
1690                {
1691                        VspInterior *interior = dynamic_cast<VspInterior *>(mNode);
1692
1693                        tQueue.push(new VspNodeWrapper(interior->GetFront()));
1694                        tQueue.push(new VspNodeWrapper(interior->GetBack()));
1695                }
1696        }
1697
1698        VspNode *mNode;
1699};
1700
1701
1702class BvhNodeWrapper: public HierarchyNodeWrapper
1703{
1704public:
1705        BvhNodeWrapper(BvhNode *node): mNode(node) {}
1706       
1707        int Type()  const { return BVH_NODE; }
1708
1709        float GetMergeCost() const { return (float)-mNode->GetTimeStamp(); };
1710
1711        bool IsLeaf() const { return mNode->IsLeaf(); }
1712
1713        void PushChildren(HierarchyNodeQueue &tQueue)
1714        {
1715                if (!mNode->IsLeaf())
1716                {
1717                        BvhInterior *interior = dynamic_cast<BvhInterior *>(mNode);
1718
1719                        tQueue.push(new BvhNodeWrapper(interior->GetFront()));
1720                        tQueue.push(new BvhNodeWrapper(interior->GetBack()));
1721                }
1722        }
1723
1724        BvhNode *mNode;
1725};
1726
1727
1728class ViewCellWrapper: public HierarchyNodeWrapper
1729{
1730public:
1731
1732        ViewCellWrapper(ViewCell *vc): mViewCell(vc) {}
1733       
1734        int Type()  const { return VIEW_CELL; }
1735
1736        float GetMergeCost() const { return mViewCell->GetMergeCost(); };
1737
1738        bool IsLeaf() const { return mViewCell->IsLeaf(); }
1739
1740        void PushChildren(HierarchyNodeQueue &tQueue)
1741        {
1742                if (!mViewCell->IsLeaf())
1743                {
1744                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(mViewCell);
1745
1746                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1747
1748                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1749                        {
1750                                tQueue.push(new ViewCellWrapper(*it));
1751                        }
1752                }
1753        }
1754
1755        ViewCell *mViewCell;
1756};
1757
1758
1759void HierarchyManager::CollectBestSet(const int maxSplits,
1760                                                                          const float maxMemoryCost,
1761                                                                          ViewCellContainer &viewCells,
1762                                                                          vector<BvhNode *> &bvhNodes)
1763{
1764        HierarchyNodeQueue tqueue;
1765        //tqueue.push(new VspNodeWrapper(mVspTree->GetRoot()));
1766        tqueue.push(new ViewCellWrapper(mVspTree->mViewCellsTree->GetRoot()));
1767        tqueue.push(new BvhNodeWrapper(mBvHierarchy->GetRoot()));
1768       
1769        float memCost = 0;
1770
1771        while (!tqueue.empty())
1772        {
1773                HierarchyNodeWrapper *nodeWrapper = tqueue.top();
1774                tqueue.pop();
1775                //cout << "priority: " << nodeWrapper->GetMergeCost() << endl;
1776                // save the view cells if it is a leaf or if enough view cells have already been traversed
1777                // because of the priority queue, this will be the optimal set of v
1778                if (nodeWrapper->IsLeaf() ||
1779                        ((viewCells.size() + bvhNodes.size() + tqueue.size() + 1) >= maxSplits) ||
1780                        (memCost > maxMemoryCost)
1781                        )
1782                {
1783                        if (nodeWrapper->Type() == HierarchyNodeWrapper::VIEW_CELL)
1784                        {
1785                                //cout << "1";
1786                                ViewCellWrapper *viewCellWrapper = dynamic_cast<ViewCellWrapper *>(nodeWrapper);
1787                                viewCells.push_back(viewCellWrapper->mViewCell);
1788                        }
1789                        else
1790                        {
1791                                //cout << "0";
1792                                BvhNodeWrapper *bvhNodeWrapper = dynamic_cast<BvhNodeWrapper *>(nodeWrapper);
1793                                bvhNodes.push_back(bvhNodeWrapper->mNode);
1794                        }
1795                }
1796                else
1797                {       
1798                        nodeWrapper->PushChildren(tqueue);
1799                }
1800
1801                delete nodeWrapper;
1802        }
1803}
1804
1805
1806void HierarchyManager::ComputePvs(const ObjectPvs &pvs,
1807                                                                  float &rc,
1808                                                                  int &pvsEntries)
1809{
1810        BvhNode::NewMail();
1811
1812        ObjectPvsIterator pit = pvs.GetIterator();
1813
1814        while (pit.HasMoreEntries())
1815        {
1816                const ObjectPvsEntry &entry = pit.Next();
1817
1818                if (entry.mObject->Type() != Intersectable::BVH_INTERSECTABLE)
1819                        cout << "error " << entry.mObject->Type() << endl;
1820
1821                BvhNode *intersect = dynamic_cast<BvhNode *>(entry.mObject);
1822                BvhNode *activeNode;
1823
1824                // hack for choosing which node to account for
1825                if (intersect->IsLeaf())
1826                {
1827                        activeNode =
1828                                dynamic_cast<BvhLeaf *>(intersect)->GetActiveNode();
1829                }
1830                else
1831                {
1832                        activeNode = intersect;
1833                }
1834
1835                if (!activeNode->Mailed())
1836                {
1837                        activeNode->Mail();
1838
1839#if STUPID_METHOD
1840
1841                        ObjectContainer objects;
1842            activeNode->CollectObjects(objects);
1843                        rc += mBvHierarchy->EvalAbsCost(objects);
1844#else
1845                        rc += mBvHierarchy->GetRenderCostIncrementially(activeNode);
1846#endif
1847                        ++ pvsEntries;
1848                }
1849        }
1850}
1851
1852
1853void HierarchyManager::GetPvsEfficiently(ViewCell *viewCell, ObjectPvs &pvs) const
1854{
1855        ////////////////
1856        //-- pvs is not stored with the interiors => reconstruct
1857       
1858        // add pvs from leaves
1859        stack<ViewCell *> tstack;
1860        tstack.push(viewCell);
1861
1862        Intersectable::NewMail();
1863
1864        while (!tstack.empty())
1865        {
1866                ViewCell *vc = tstack.top();
1867                tstack.pop();
1868       
1869                // add newly found pvs to merged pvs: break here even for interior
1870                if (!vc->GetPvs().Empty())
1871                {
1872                        ObjectPvsIterator pit = vc->GetPvs().GetIterator();
1873
1874                        while (pit.HasMoreEntries())
1875                        {               
1876                                const ObjectPvsEntry &entry = pit.Next();
1877
1878                                Intersectable *object = entry.mObject;
1879                                if (!object->Mailed())
1880                                {
1881                                        object->Mail();
1882                                        pvs.AddSampleDirty(object, 1.0f);
1883                                }
1884                        }
1885                }
1886                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
1887                {
1888                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1889                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1890
1891                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1892                        {
1893                                tstack.push(*it);
1894                        }               
1895                }
1896        }
1897}
1898
1899
1900// TODO matt: implement this function for different storing methods
1901void HierarchyManager::GetPvsIncrementially(ViewCell *vc, ObjectPvs &pvs) const
1902{
1903        ////////////////
1904        //-- pvs is not stored with the interiors => reconstruct
1905       
1906        // add pvs from leaves
1907        stack<ViewCell *> tstack;
1908        tstack.push(vc);
1909
1910        while (!tstack.empty())
1911        {
1912                vc = tstack.top();
1913                tstack.pop();
1914       
1915                // add newly found pvs to merged pvs: break here even for interior
1916                if (!vc->GetPvs().Empty())
1917                {
1918                        //if (vc->IsLeaf()) cout << " l " << pvs.GetSize();
1919                        //else cout << " i " << pvs.GetSize();
1920                        pvs.MergeInPlace(vc->GetPvs());
1921                }
1922                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
1923                {
1924                        //cout <<" t";
1925                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1926                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1927
1928                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1929                        {
1930                                tstack.push(*it);
1931                        }               
1932                }
1933                else cout <<"k";
1934        }
1935}
1936
1937
1938// TODO matt: implement this function for different storing methods
1939void HierarchyManager::PullUpPvsIncrementally(ViewCell *viewCell) const
1940{
1941        ////////////////
1942        //-- pvs is not stored with the interiors => reconstruct
1943       
1944        // early exit: pvs is already pulled up to this view cell
1945        if (!viewCell->GetPvs().Empty())
1946                return;
1947
1948        // add pvs from leaves
1949        stack<ViewCell *> tstack;
1950        tstack.push(viewCell);
1951
1952        ViewCell *vc = viewCell;
1953
1954        while (!tstack.empty())
1955        {
1956                vc = tstack.top();
1957                tstack.pop();
1958       
1959                // add newly found pvs to merged pvs: break here even for interior
1960                if (!vc->GetPvs().Empty())
1961                {
1962                        viewCell->GetPvs().MergeInPlace(vc->GetPvs());
1963                }
1964                else if (!vc->IsLeaf()) // interior cells: go down to leaf level
1965                {
1966                        //cout <<" t";
1967                        ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1968                        ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1969
1970                        for (it = interior->mChildren.begin(); it != it_end; ++ it)
1971                        {
1972                                tstack.push(*it);
1973                        }               
1974                }
1975        }
1976}
1977
1978
1979
1980// TODO matt: implement this function for different storing methods
1981void HierarchyManager::GetPvsRecursive(ViewCell *vc, ObjectPvs &pvs) const
1982{
1983        ////////////////
1984        //-- pvs is not stored with the interiors => reconstruct
1985        if (vc->IsLeaf() || !vc->GetPvs().Empty())
1986        {
1987                pvs = vc->GetPvs();
1988        }
1989        else
1990        {
1991                ViewCellInterior *interior = dynamic_cast<ViewCellInterior *>(vc);
1992#if 0
1993                ViewCellContainer::const_iterator it, it_end = interior->mChildren.end();
1994                const int childPvsSize = (int)interior->mChildren.size();
1995                vector<ObjectPvs> childPvs;
1996                childPvs.resize((int)interior->mChildren.size());
1997
1998                int i = 0;
1999                for (it = interior->mChildren.begin(); it != it_end; ++ it, ++ i)
2000                {
2001                        GetPvsRecursive(*it, childPvs[i]);
2002                        pvs.MergeInPlace(childPvs[i]);
2003                }
2004#else
2005
2006                ObjectPvs leftPvs, rightPvs;
2007
2008                GetPvsRecursive(interior->mChildren[0], leftPvs);
2009                GetPvsRecursive(interior->mChildren[1], rightPvs);
2010
2011                ObjectPvs::Merge(pvs, leftPvs, rightPvs);
2012#endif
2013        }
2014}
2015
2016
2017int HierarchyManager::ExtractStatistics(const int maxSplits,
2018                                                                                const float maxMemoryCost,
2019                                                                                float &renderCost,
2020                                                                                float &memory,
2021                                                                                int &pvsEntries,
2022                                                                                int &viewSpaceSplits,
2023                                                                                int &objectSpaceSplits,
2024                                                                                const bool useFilter)
2025{
2026        ViewCellContainer viewCells;
2027        vector<BvhNode *> bvhNodes;
2028
2029        // collect best set of view cells for this #splits
2030    CollectBestSet(maxSplits, maxMemoryCost, viewCells, bvhNodes);
2031        vector<BvhNode *>::const_iterator bit, bit_end = bvhNodes.end();
2032       
2033        // set new nodes to be active
2034        for (bit = bvhNodes.begin(); bit != bit_end; ++ bit)
2035        {
2036                mBvHierarchy->SetActive(*bit);
2037        }
2038
2039        ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
2040
2041        pvsEntries = 0;
2042        renderCost = 0.0f;
2043
2044        ViewCell::NewMail();
2045
2046        //cout << "\nviewcells: " << viewCells.size() << endl;
2047        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
2048        {
2049                ViewCell *vc = *vit;
2050                float rc = 0;
2051       
2052#if STUPID_METHOD       
2053                ObjectPvs pvs;
2054                GetPvsIncrementially(vc, pvs);
2055                vc->SetPvs(pvs);
2056               
2057#else
2058       
2059                ObjectPvs pvs;
2060                               
2061                if (vc->GetPvs().Empty())
2062                {
2063                        // warning: uses mailing, pvs not sorted!!
2064                        GetPvsEfficiently(vc, pvs);
2065                        //GetPvsRecursive(vc, pvs);
2066                        vc->SetPvs(pvs);
2067                        //cout << "q";
2068                }
2069                //else cout << "t";
2070#endif
2071
2072                vc->Mail();
2073
2074                if (useFilter)
2075                {
2076                        const long startT = GetTime();
2077                        ObjectPvs filteredPvs;
2078                        mVspTree->mViewCellsManager->ApplyFilter2(vc, false, 1.0f, filteredPvs);
2079                        const long endT = GetTime();
2080
2081                        //cout << "filter computed in " << TimeDiff(startT, endT) * 1e-3f << " secs" << endl;
2082                        ComputePvs(filteredPvs, rc, pvsEntries);
2083                }
2084                else
2085                {
2086                        ComputePvs(vc->GetPvs(), rc, pvsEntries);
2087                }
2088
2089                rc *= vc->GetVolume();
2090                renderCost += rc;
2091        }
2092
2093        renderCost /= mVspTree->mViewCellsManager->GetViewSpaceBox().GetVolume();
2094        memory = pvsEntries * ObjectPvs::GetEntrySize();
2095
2096        viewSpaceSplits = (int)viewCells.size();
2097        objectSpaceSplits = (int)bvhNodes.size();
2098        //cout << "viewCells: " << (int)viewCells.size() << " nodes: " << (int)bvhNodes.size() << " rc: " << renderCost << " entries: " << pvsEntries << endl;
2099
2100        // delete old "base" view cells if they are not leaves
2101        ViewCellContainer::const_iterator oit, oit_end = mOldViewCells.end();
2102
2103        for (oit = mOldViewCells.begin(); oit != oit_end; ++ oit)
2104        {
2105                if (!(*oit)->Mailed() && !(*oit)->IsLeaf())
2106                {
2107                        (*oit)->GetPvs().Clear();
2108                }
2109        }
2110
2111        // store current level
2112        mOldViewCells = viewCells;
2113
2114        return (int)(viewCells.size() + bvhNodes.size());
2115}
2116
2117
2118void HierarchyManager::ExportStats(ofstream &stats,
2119                                                                   SplitQueue &tQueue,
2120                                                                   const ObjectContainer &objects)
2121{
2122        HierarchySubdivisionStats subStats;
2123        subStats.Reset();
2124
2125        /////////////
2126        //-- initial situation
2127
2128        subStats.mNumSplits = 0;
2129        subStats.mTotalRenderCost = (float)objects.size();
2130        subStats.mEntriesInPvs = 1;
2131        subStats.mMemoryCost = (float)ObjectPvs::GetEntrySize();
2132        subStats.mFullMemory = subStats.mMemoryCost;
2133        subStats.mViewSpaceSplits = 0;
2134        subStats.mObjectSpaceSplits = 0;
2135        subStats.mRenderCostDecrease = 0;
2136        subStats.Print(stats);
2137
2138        cout << "exporting vsposp stats ... " << endl;
2139
2140        //-- go through tree in the order of render cost decrease
2141        //-- which is the same order as the view cells were merged
2142        //-- or the reverse order of subdivision for subdivision-only
2143        //-- view cell hierarchies.
2144
2145        while (!tQueue.Empty())
2146        {
2147                SubdivisionCandidate *nextCandidate = NextSubdivisionCandidate(tQueue);
2148                bool isLeaf;
2149                int timeStamp;
2150                float rcDecr;
2151                int entriesIncr;
2152
2153                if (nextCandidate->Type() == SubdivisionCandidate::VIEW_SPACE)
2154                {
2155                        timeStamp = (int)-nextCandidate->GetPriority();
2156
2157                        VspNode *newNode = mVspTree->SubdivideAndCopy(tQueue, nextCandidate);
2158                        VspNode *oldNode = (VspNode *)nextCandidate->mEvaluationHack;
2159
2160                        isLeaf = newNode->IsLeaf();
2161                        //subStats.mRenderCostDecrease = oldNode->mRenderCostDecr;
2162                        //entriesIncr = oldNode->mPvsEntriesIncr;
2163                }
2164                else
2165                {
2166                        timeStamp = (int)-nextCandidate->GetPriority();
2167
2168                        BvhNode *newNode = mBvHierarchy->SubdivideAndCopy(tQueue, nextCandidate);
2169                        BvhNode *oldNode = (BvhNode *)nextCandidate->mEvaluationHack;
2170
2171                        isLeaf = newNode->IsLeaf();
2172                        //subStats.mRenderCostDecrease = oldNode->mRenderCostDecr;
2173                        //entriesIncr = oldNode->mPvsEntriesIncr;
2174                }               
2175
2176                if (!isLeaf)
2177                {
2178                        subStats.mTotalRenderCost -= subStats.mRenderCostDecrease;
2179                        //subStats.mEntriesInPvs += entriesIncr;
2180
2181                        if (nextCandidate->Type() == SubdivisionCandidate::VIEW_SPACE)
2182                        {
2183                                ++ subStats.mViewSpaceSplits;
2184                                cout << "v";
2185                                //cout << "vsp t: " << timeStamp << " rc: " << rcDecr << " pvs: " << entriesIncr << endl;
2186                        }
2187                        else
2188                        {
2189                                ++ subStats.mObjectSpaceSplits;
2190                                cout << "o";
2191                                //"osp t: " << timeStamp << " rc: " << rcDecr << " pvs: " << entriesIncr << endl;
2192                        }
2193
2194                        ++ subStats.mNumSplits;
2195
2196                        if ((subStats.mNumSplits % 500) == 499)
2197                                cout << subStats.mNumSplits << " steps taken" << endl;
2198
2199                        subStats.mMemoryCost = (float)subStats.mEntriesInPvs * (float)ObjectPvs::GetEntrySize();
2200                        subStats.mFullMemory = subStats.mMemoryCost;
2201
2202                        subStats.Print(stats);
2203
2204                }
2205
2206                DEL_PTR(nextCandidate);
2207        }
2208
2209        stats.close();
2210}
2211
2212
2213void HierarchyManager::EvaluateSubdivision(const VssRayContainer &sampleRays,
2214                                                                                   const ObjectContainer &objects,
2215                                                                                   const string &filename)
2216{
2217#if 0
2218        VspTree *oldVspTree = mVspTree;
2219        ViewCellsManager *vm = mVspTree->mViewCellsManager;
2220        BvHierarchy *oldHierarchy = mBvHierarchy;
2221
2222        mBvHierarchy = new BvHierarchy();
2223        mBvHierarchy->mHierarchyManager = this;
2224        mBvHierarchy->mViewCellsManager = vm;
2225
2226        mVspTree = new VspTree();
2227        mVspTree->mHierarchyManager = this;
2228        mVspTree->mViewCellsManager = vm;
2229
2230        // create first nodes
2231        mVspTree->Initialise(sampleRays, &oldVspTree->mBoundingBox);
2232        InitialiseObjectSpaceSubdivision(objects);
2233
2234        const long startTime = GetTime();
2235        cout << "Constructing evaluation hierarchies ... \n";
2236       
2237        ofstream stats;
2238        stats.open(filename.c_str());
2239        SplitQueue tQueue;
2240
2241        BvhNode *oldBvhRoot = oldHierarchy->GetRoot();
2242        VspNode *oldVspRoot = oldVspTree->GetRoot();
2243
2244        RayInfoContainer *viewSpaceRays = new RayInfoContainer();
2245       
2246        SubdivisionCandidate *firstVsp = mVspTree->PrepareConstruction(sampleRays, *viewSpaceRays);
2247        tQueue.Push(firstVsp);
2248
2249        mBvHierarchy->PrepareConstruction(tQueue, sampleRays, objects);
2250
2251    firstVsp->mEvaluationHack = oldVspRoot;
2252        firstBvh->mEvaluationHack = oldBvhRoot;
2253
2254        firstVsp->SetPriority((float)-oldVspRoot->mTimeStamp);
2255        firstBvh->SetPriority((float)-oldBvhRoot->GetTimeStamp());
2256       
2257        ExportStats(stats, tQueue, objects);
2258
2259        cout << "\nfinished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
2260        RemoveRayRefs(objects);
2261
2262        // view cells needed only for evaluation
2263        ViewCellContainer viewCells;
2264        mVspTree->CollectViewCells(viewCells, false);
2265       
2266        // helper trees can be destroyed
2267        DEL_PTR(mVspTree);
2268        DEL_PTR(mBvHierarchy);
2269
2270        CLEAR_CONTAINER(viewCells);
2271
2272        // reset hierarchies
2273        mVspTree = oldVspTree;
2274        mBvHierarchy = oldHierarchy;
2275
2276        // reinstall old bv refs
2277        vector<BvhLeaf *> leaves;
2278        mBvHierarchy->CollectLeaves(mBvHierarchy->GetRoot(), leaves);
2279        vector<BvhLeaf *>::const_iterator bit, bit_end = leaves.end();
2280
2281        for (bit = leaves.begin(); bit != bit_end; ++ bit)
2282        {
2283                mBvHierarchy->AssociateObjectsWithLeaf(*bit);
2284        }
2285#endif
2286}
2287
2288
2289void HierarchyManager::EvaluateSubdivision2(ofstream &splitsStats,
2290                                                                                        const int splitsStepSize,
2291                                                                                        const bool useFilter)
2292{
2293        vector<HierarchySubdivisionStats> subStatsContainer;
2294
2295        int splits = (1 + (mHierarchyStats.Leaves() - 1) / splitsStepSize) * splitsStepSize;
2296        cout << "splits: " << splits << endl;
2297
2298        while (1)
2299        {
2300                HierarchySubdivisionStats subStats;
2301                subStats.mNumSplits = ExtractStatistics(splits,
2302                                                                                                99999.0,
2303                                                                                                subStats.mTotalRenderCost,
2304                                                                                                subStats.mMemoryCost,
2305                                                                                                subStats.mEntriesInPvs,
2306                                                                                                subStats.mViewSpaceSplits,
2307                                                                                                subStats.mObjectSpaceSplits,
2308                                                                                                useFilter);
2309
2310               
2311                const float objectSpaceHierarchyMem = float(
2312                                                                                          subStats.mObjectSpaceSplits * mBvHierarchy->mMemoryConst//sizeof(ObjectContainer)
2313                                                                                          //+ (subStats.mObjectSpaceSplits - 1) * sizeof(BvhInterior)
2314                                                                                          //+sizeof(BvHierarchy)
2315                                                                                          ) / float(1024 * 1024);
2316
2317                       
2318                const float viewSpaceHierarchyMem = float(
2319                                                                                        subStats.mViewSpaceSplits * mVspTree->mMemoryConst//sizeof(ObjectPvs)
2320                                                                                        //+ (subStats.mViewSpaceSplits - 1) * sizeof(VspInterior)
2321                                                                                        + sizeof(ObjectPvs)
2322                                                                                        //+ sizeof(VspTree)
2323                                                                                        )  / float(1024 * 1024);
2324
2325                subStats.mFullMemory = subStats.mMemoryCost + objectSpaceHierarchyMem + viewSpaceHierarchyMem;
2326               
2327                subStatsContainer.push_back(subStats);
2328               
2329                if (splits == 0)
2330                {
2331                        break;
2332                }
2333                splits -= splitsStepSize;
2334
2335                cout << "splits: " << subStats.mNumSplits << " ";
2336        }
2337
2338        vector<HierarchySubdivisionStats>::const_reverse_iterator hit, hit_end = subStatsContainer.rend();
2339
2340        for (hit = subStatsContainer.rbegin(); hit != hit_end; ++ hit)
2341        {
2342                (*hit).Print(splitsStats);
2343        }
2344
2345        // delete old "base" view cells: only pvss in the leaves are allowed
2346        ViewCellContainer::const_iterator oit, oit_end = mOldViewCells.end();
2347        for (oit = mOldViewCells.begin(); oit != oit_end; ++ oit)
2348        {
2349                if (!(*oit)->IsLeaf())
2350                {
2351                        (*oit)->GetPvs().Clear();
2352                }
2353        }
2354
2355        mOldViewCells.clear();
2356
2357        // reset active nodes
2358        vector<BvhLeaf *> bvhLeaves;
2359
2360        mBvHierarchy->CollectLeaves(mBvHierarchy->GetRoot(), bvhLeaves);
2361
2362        vector<BvhLeaf *>::const_iterator bit, bit_end = bvhLeaves.end();
2363
2364        for (bit = bvhLeaves.begin(); bit != bit_end; ++ bit)
2365        {
2366                (*bit)->SetActiveNode(*bit);
2367        }
2368
2369        cout << endl;
2370}
2371
2372
2373void HierarchyManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
2374{
2375        mBvHierarchy->CollectObjects(box, objects);
2376}
2377
2378
2379int HierarchyManager::CompressObjectSpace()
2380{
2381        //mBvHierarchy->Compress();
2382        return mVspTree->CompressObjects();
2383}
2384
2385
2386void HierarchyManager::CreateUniqueObjectIds()
2387{
2388        mBvHierarchy->CreateUniqueObjectIds();
2389}
2390
2391
2392}
Note: See TracBrowser for help on using the repository browser.