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

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