source: GTP/trunk/Lib/Vis/Preprocessing/src/HierarchyManager.h @ 1843

Revision 1843, 17.5 KB checked in by mattausch, 18 years ago (diff)

warning! changed pvs output because of paper hack

Line 
1#ifndef _HierarchyManager_H__
2#define _HierarchyManager_H__
3
4#include <stack>
5
6#include "Mesh.h"
7#include "Containers.h"
8#include "Statistics.h"
9#include "VssRay.h"
10#include "RayInfo.h"
11#include "gzstream.h"
12#include "SubdivisionCandidate.h"
13
14
15
16namespace GtpVisibilityPreprocessor {
17
18class ViewCellLeaf;
19class OspTree;
20class VspTree;
21class Plane3;
22class AxisAlignedBox3;
23class Ray;
24class ViewCellsStatistics;
25class ViewCellsManager;
26class MergeCandidate;
27class Beam;
28class ViewCellsTree;
29class Environment;
30class VspInterior;
31class VspLeaf;
32class VspNode;
33class KdNode;
34class KdInterior;
35class KdLeaf;
36class OspTree;
37class KdIntersectable;
38class KdTree;
39class VspTree;
40class KdTreeStatistics;
41class BvHierarchy;
42class Exporter;
43class ViewCellsParseHandlers;
44
45
46#define COUNT_ORIGIN_OBJECTS 1
47
48/** View space / object space hierarchy statistics.
49*/
50class HierarchyStatistics: public StatisticsBase
51{
52public:
53        /// total number of entries in the pvs
54        int mPvsEntries;
55        /// storage cost in MB
56        float mMemory;
57        /// total number of nodes
58        int mNodes;
59        /// maximal reached depth
60        int mMaxDepth;
61        /// accumulated depth
62        int mAccumDepth;
63        /// time spent for queue repair
64        float mRepairTime;
65
66        // global cost ratio violations
67        int mGlobalCostMisses;
68        /// total cost of subdivision
69        float mTotalCost;
70        /// render cost decrease of subdivision
71        float mRenderCostDecrease;
72
73        // Constructor
74        HierarchyStatistics()
75        {
76                Reset();
77        }
78
79        int Nodes() const {return mNodes;}
80        int Interior() const { return mNodes / 2 - 1; }
81        int Leaves() const { return (mNodes / 2) + 1; }
82       
83        // TODO: computation wrong
84        double AvgDepth() const { return mAccumDepth / (double)Leaves();}
85
86        void Reset()
87        {
88                mGlobalCostMisses = 0;
89                mTotalCost = 0;
90                mRenderCostDecrease = 0;
91
92                mNodes = 0;
93                mMaxDepth = 0;
94                mAccumDepth = 0;
95                mRepairTime = 0;
96                mMemory = 0;
97                mPvsEntries = 0;
98        }
99
100        void Print(ostream &app) const;
101
102        friend ostream &operator<<(ostream &s, const HierarchyStatistics &stat)
103        {
104                stat.Print(s);
105                return s;
106        }
107};
108
109
110class HierarchySubdivisionStats
111{
112public:
113           
114        int mNumSplits;
115               
116        float mRenderCostDecrease;
117
118    float mTotalRenderCost;
119   
120        int mEntriesInPvs;
121   
122        float mMemoryCost;
123       
124        float mFullMemory;
125
126        int mViewSpaceSplits;
127
128        int mObjectSpaceSplits;
129
130        float mPriority;
131
132        float VspOspRatio() const { return (float)mViewSpaceSplits / (float)mObjectSpaceSplits; }
133
134        float FpsPerMb() const { return 1.0f / (mTotalRenderCost * mMemoryCost); }
135
136        HierarchySubdivisionStats() { Reset(); }
137
138        void Reset()
139        {
140                mNumSplits = 0;
141                mRenderCostDecrease = 0;
142                mTotalRenderCost = 0;
143                mEntriesInPvs = 0;
144                mMemoryCost = 0;
145                mFullMemory = 0;
146                mViewSpaceSplits = 0;
147                mObjectSpaceSplits = 0;
148                mPriority = 0;
149        }
150
151
152        void Print(ostream &app) const;
153
154        friend ostream &operator<<(ostream &s, const HierarchySubdivisionStats &stat)
155        {
156                stat.Print(s);
157                return s;
158        }
159};
160
161
162/** This class implements a structure holding two different hierarchies,
163        one for object space partitioning and one for view space partitioning.
164
165        The object space and the view space are subdivided using a cost heuristics.
166        If an object space split or a view space split is chosen is also evaluated
167        based on the heuristics.
168       
169        The view space heuristics is evaluated by weighting and adding the pvss of the back and
170        front node of each specific split. unlike for the standalone method vspbsp tree,
171        the pvs of an object would not be the pvs of single object but that of all objects
172        which are contained in the same leaf of the object subdivision. This could be done
173        by storing the pointer to the object space partition parent, which would allow access to all children.
174        Another possibility is to include traced kd-cells in the ray casing process.
175
176        Accordingly, the object space heuristics is evaluated by storing a pvs of view cells with each object.
177        the contribution to an object to the pvs is the number of view cells it can be seen from.
178
179        @note
180        There is a potential efficiency problem involved in a sense that once a certain type
181        of split is chosen for view space / object space, the candidates for the next split of
182        object space / view space must be reevaluated.
183*/
184class HierarchyManager
185{
186public:
187        /** Constructor with the view space partition tree and
188                the object space hierarchy type as argument.
189        */
190        HierarchyManager(const int objectSpaceHierarchyType);
191        /** Hack: OspTree will copy the content from this kd tree.
192                Only view space hierarchy will be constructed.
193        */
194        HierarchyManager(KdTree *kdTree);
195
196        /** Deletes space partition and view space partition.
197        */
198        ~HierarchyManager();
199
200        /** Constructs the view space and object space subdivision from a given set of rays
201                and a set of objects.
202                @param sampleRays the set of sample rays the construction is based on
203                @param objects the set of objects
204        */
205        void Construct(
206                const VssRayContainer &sampleRays,
207                const ObjectContainer &objects,
208                AxisAlignedBox3 *forcedViewSpace);
209
210        enum
211        {
212                NO_OBJ_SUBDIV,
213                KD_BASED_OBJ_SUBDIV,
214                BV_BASED_OBJ_SUBDIV
215        };
216
217        enum
218        {
219                NO_VIEWSPACE_SUBDIV,
220                KD_BASED_VIEWSPACE_SUBDIV
221        };
222
223        /** The type of object space subdivison
224        */
225        int GetObjectSpaceSubdivisionType() const;     
226        /** The type of view space space subdivison
227        */
228        int GetViewSpaceSubdivisionType() const;
229        /** Sets a pointer to the view cells manager.
230        */             
231        void SetViewCellsManager(ViewCellsManager *vcm);
232        /** Sets a pointer to the view cells tree.
233        */
234        void SetViewCellsTree(ViewCellsTree *vcTree);
235        /** Exports the object hierarchy to disc.
236        */
237        void ExportObjectSpaceHierarchy(OUT_STREAM &stream);
238       
239        /** Print out statistics.
240        */
241        void PrintHierarchyStatistics(ostream &stream) const;
242
243        /** Returns the view space partition tree.
244        */
245        VspTree *GetVspTree();
246
247        /** Returns view space bounding box.
248        */
249        //AxisAlignedBox3 GetViewSpaceBox() const;
250
251        /** Returns object space bounding box.
252        */
253        AxisAlignedBox3 GetObjectSpaceBox() const;
254
255        /** Exports object space hierarchy for visualization.
256        */
257        void ExportObjectSpaceHierarchy(Exporter *exporter,
258                                                                        const ObjectContainer &objects,
259                                                                        AxisAlignedBox3 *bbox,
260                                                                        const bool exportBounds = true) const;
261
262        /** Returns intersectable pierced by this ray.
263        */
264        Intersectable *GetIntersectable(const VssRay &ray, const bool isTermination) const;
265 
266  Intersectable *GetIntersectable(Intersectable *obj,
267                                                                  const Vector3 &point) const;
268 
269        /** Export object space partition bounding boxes.
270        */
271        void ExportBoundingBoxes(OUT_STREAM &stream, const ObjectContainer &objects);
272
273        friend ostream &operator<<(ostream &s, const HierarchyManager &hm)
274        {
275                hm.PrintHierarchyStatistics(s);
276                return s;
277        }
278
279        HierarchyStatistics &GetHierarchyStats() { return mHierarchyStats; };
280
281        inline bool ConsiderMemory() const { return mConsiderMemory; }
282       
283        void EvaluateSubdivision(const VssRayContainer &sampleRays,                                                                                     
284                                                         const ObjectContainer &objects,
285                                                         const string &filename);
286
287        void EvaluateSubdivision2(ofstream &splitsStats,
288                                                          const int splitsStepSize,
289                                                          const bool useFilter);
290
291
292        void CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects);
293
294        void CreateUniqueObjectIds();
295
296
297        float mInitialRenderCost;
298
299
300protected:
301
302        /** Returns true if the global termination criteria were met.
303        */
304        bool GlobalTerminationCriteriaMet(SubdivisionCandidate *candidate) const;
305
306        /** Prepare construction of the hierarchies, set parameters, compute
307                first split candidates.
308        */
309        void PrepareObjectSpaceSubdivision(SplitQueue &tQueue,
310                                                                           const VssRayContainer &sampleRays,
311                                                                           const ObjectContainer &objects);
312
313
314        /** Create bounding box and root.
315        */
316        void InitialiseObjectSpaceSubdivision(const ObjectContainer &objects);
317
318        /** Returns memory usage of object space hierarchy.
319        */
320        float GetObjectSpaceMemUsage() const;
321
322
323        //////////////////////////////
324        // the main loop
325
326        /** This is for interleaved construction / sequential construction.
327        */
328        void RunConstruction(const bool repairQueue,
329                                                 const VssRayContainer &sampleRays,
330                                                 const ObjectContainer &objects,
331                                                 AxisAlignedBox3 *forcedViewSpace);
332       
333        /** This is for interleaved construction using some objects
334                and some view space splits.
335        */
336        int RunConstruction(SplitQueue &splitQueue,
337                                                SubdivisionCandidateContainer &chosenCandidates,
338                                                //const float minRenderCostDecr,
339                                                SubdivisionCandidate *oldCandidate,
340                                                const int minSteps,
341                                                const int maxSteps);
342
343        /** Default subdivision method.
344        */
345        void RunConstruction(const bool repairQueue);
346               
347        ////////////////////////////////////////////////
348
349        /** Evaluates the subdivision candidate and executes the split.
350        */
351        bool ApplySubdivisionCandidate(SubdivisionCandidate *sc,
352                                                                   SplitQueue &splitQueue,
353                                                                   const bool repairQueue);
354
355        /** Tests if hierarchy construction is finished.
356        */
357        bool FinishedConstruction() const;
358
359        /** Returns next subdivision candidate from the split queue.
360        */
361        SubdivisionCandidate *NextSubdivisionCandidate(SplitQueue &splitQueue);
362
363        /** Repairs the dirty entries of the subdivision candidate queue. The
364                list of entries is given in the dirty list.
365
366                @returns number of repaired candidates
367        */
368        int RepairQueue(const SubdivisionCandidateContainer &dirtyList,
369                                        SplitQueue &splitQueue,
370                                        const bool recomputeSplitPlaneOnRepair);
371
372        /** Collect subdivision candidates which were affected by the splits from the
373                chosenCandidates list.
374        */
375        void CollectDirtyCandidates(const SubdivisionCandidateContainer &chosenCandidates,
376                                                                SubdivisionCandidateContainer &dirtyList);
377
378        /** Evaluate subdivision stats for log.
379        */
380        void EvalSubdivisionStats();
381
382        void AddSubdivisionStats(const int splits,
383                                                         const float renderCostDecr,
384                                                         const float totalRenderCost,
385                                                         const int totalPvsEntries,
386                                                         const float memory,
387                                                         const float renderCostPerStorage,
388                                                         const float vspOspRatio);
389
390        /** Collect affected view space candidates.
391        */
392        void CollectViewSpaceDirtyList(SubdivisionCandidate *sc,
393                                                                   SubdivisionCandidateContainer &dirtyList);
394
395        /** Collect affected object space candidates.
396        */
397        void CollectObjectSpaceDirtyList(SubdivisionCandidate *sc,
398                                                                         SubdivisionCandidateContainer &dirtyList);
399               
400        /** Export object space partition tree.
401        */
402        void ExportOspTree(Exporter *exporter,
403                                           const ObjectContainer &objects) const;
404
405        /** Parse the environment variables.
406        */
407        void ParseEnvironment();
408
409        bool StartObjectSpaceSubdivision() const;
410        bool StartViewSpaceSubdivision() const;
411
412
413        ////////////////////////////
414        // Helper function for preparation of subdivision
415
416        /** Prepare bv hierarchy for subdivision
417        */
418        void PrepareBvHierarchy(SplitQueue &tQueue,
419                                                        const VssRayContainer &sampleRays,
420                                                        const ObjectContainer &objects);
421
422        /** Prepare object space kd tree for subdivision.
423        */
424        void PrepareOspTree(SplitQueue &tQueue,
425                                                const VssRayContainer &sampleRays,
426                                                const ObjectContainer &objects);
427
428        /** Prepare view space subdivision and add candidate to queue.
429        */
430        void PrepareViewSpaceSubdivision(SplitQueue &tQueue,
431                                                                         const VssRayContainer &sampleRays,
432                                                                         const ObjectContainer &objects);
433
434        /** Was object space subdivision already constructed?
435        */
436        bool ObjectSpaceSubdivisionConstructed() const;
437       
438        /** Was view space subdivision already constructed?
439        */
440        bool ViewSpaceSubdivisionConstructed() const;
441
442        /** Reset the split queue, i.e., reevaluate the split candidates.
443        */
444    void ResetQueue(SplitQueue &splitQueue, const bool recomputeSplitPlane);
445
446        /** After the suddivision has ended, do some final tasks.
447        */
448        void FinishObjectSpaceSubdivision(const ObjectContainer &objects,
449                                                                          const bool removeRayRefs = true) const;
450
451        /** Returns depth of object space subdivision.
452        */
453        int GetObjectSpaceSubdivisionDepth() const;
454
455        /** Returns number of leaves in object space subdivision.
456        */
457        int GetObjectSpaceSubdivisionLeaves() const;
458        int GetObjectSpaceSubdivisionNodes() const;
459
460        /** Construct object space partition interleaved with view space partition.
461                Each time the best object or view space candidate is selected
462                for the next split.
463        */
464        void ConstructInterleaved(const VssRayContainer &sampleRays,
465                                                          const ObjectContainer &objects,
466                                                          AxisAlignedBox3 *forcedViewSpace);
467
468        /** Construct object space partition interleaved with view space partition.
469                The method chooses a number candidates of each type for subdivision.
470                The number is determined by the "gradient", i.e., the render cost decrease.
471                Once this render cost decrease is lower than the render cost decrease
472                for the splits of previous type, the method will stop current subdivision and
473                evaluate if view space or object space would be the beneficial for the
474                next number of split.
475        */
476        void ConstructInterleavedWithGradient(const VssRayContainer &sampleRays,
477                                                                                  const ObjectContainer &objects,
478                                                                                  AxisAlignedBox3 *forcedViewSpace);
479
480        /** Use iteration to construct the object space hierarchy.
481        */
482        void ConstructMultiLevel(const VssRayContainer &sampleRays,
483                                                         const ObjectContainer &objects,
484                                                         AxisAlignedBox3 *forcedViewSpace);
485
486        /** Based on a given subdivision, we try to optimize using an
487                multiple iteration over view and object space.
488        */
489        void OptimizeMultiLevel(const VssRayContainer &sampleRays,                                                                                       
490                                                        const ObjectContainer &objects,
491                                                        AxisAlignedBox3 *forcedViewSpace);
492
493        /** Reset the object space subdivision.
494                E.g., deletes hierarchy and resets stats.
495                so construction can be restarted.
496        */
497        void ResetObjectSpaceSubdivision(SplitQueue &tQueue,
498                                                                         const VssRayContainer &rays,
499                                                                         const ObjectContainer &objects);
500
501        void ResetViewSpaceSubdivision(SplitQueue &tQueue,
502                                                                   const VssRayContainer &rays,
503                                                                   const ObjectContainer &objects,
504                                                                   AxisAlignedBox3 *forcedViewSpace);
505
506
507        ///////////////////////////
508
509        void ExportStats(ofstream &stats,
510                                         SplitQueue &tQueue,
511                                         const ObjectContainer &objects);
512
513        void CollectBestSet(const int maxSplits,
514                                                const float maxMemoryCost,
515                                                ViewCellContainer &viewCells,
516                                                vector<BvhNode *> &bvhNodes);
517
518        int ExtractStatistics(const int maxSplits,
519                                                  const float maxMemoryCost,
520                                                  float &renderCost,
521                                                  float &memory,
522                                                  int &pvsEntries,
523                                                  int &viewSpaceSplits,
524                                                  int &objectSpaceSplits,
525                                                  const bool useFilter);
526
527        void ComputePvs(const ObjectPvs &pvs, float &rc, int &pvsEntries);
528        void GetPvsIncrementially(ViewCell *vc, ObjectPvs &pvs) const;
529        void PullUpPvsIncrementally(ViewCell *viewCell) const;
530        void GetPvsRecursive(ViewCell *vc, ObjectPvs &pvs) const;
531        void GetPvsEfficiently(ViewCell *vc, ObjectPvs &pvs) const;
532
533        float EvalFullMem() const;
534
535
536
537protected:
538
539        /** construction types
540                sequential: construct first view space, then object space
541                interleaved: construct view space and object space fully interleaved
542                gradient: construct view space / object space until a threshold is reached
543                multilevel: iterate until subdivisions converge to the optimum.
544        */
545        enum {SEQUENTIAL, INTERLEAVED, GRADIENT, MULTILEVEL};
546
547        /// type of hierarchy construction
548        int mConstructionType;
549
550        /// Type of object space partition
551        int mObjectSpaceSubdivisionType;
552        /// Type of view space partition
553    int mViewSpaceSubdivisionType;
554
555        /// the traversal queue
556        SplitQueue mTQueue;
557       
558        ////////////
559        //-- helper variables
560       
561        // the original osp type
562        int mSavedObjectSpaceSubdivisionType;
563        // the original vsp type
564        int mSavedViewSpaceSubdivisionType;
565        /// the current subdivision candidate
566        //SubdivisionCandidate *mCurrentCandidate;
567
568
569        ///////////////////
570        // Hierarchies
571
572        /// view space hierarchy
573        VspTree *mVspTree;
574        /// object space partition kd tree
575        OspTree *mOspTree;
576
577        public:
578        /// bounding volume hierarchy
579        BvHierarchy *mBvHierarchy;
580       
581protected:
582
583
584        //////////
585        //-- global termination criteria
586
587        /// the mininal acceptable cost ratio for a split
588        float mTermMinGlobalCostRatio;
589        /// the threshold for global cost miss tolerance
590        int mTermGlobalCostMissTolerance;
591        /// maximum number of leaves
592        int mTermMaxLeaves;
593        /// Maximal allowed memory consumption.
594        float mTermMaxMemory;
595
596
597        ////////////////////
598
599        /// number of minimal steps of the same type
600        int mMinStepsOfSameType;
601        int mMaxStepsOfSameType;
602
603        /// statistics about the hierarchy
604        HierarchyStatistics mHierarchyStats;
605
606        int mMinDepthForObjectSpaceSubdivion;
607        int mMinDepthForViewSpaceSubdivion;
608       
609        //int mMinRenderCostDecrease;
610
611        ofstream mSubdivisionStats;
612
613        /// if the queue should be repaired after a subdivision steps
614        bool mRepairQueue;
615
616        bool mStartWithObjectSpace;
617        /** if multi level construction method should be used
618                where we iterate over both hierarchies until we
619                converge to the optimum.
620        */
621        bool mUseMultiLevelConstruction;
622
623        /// number of iteration steps for multilevel approach   
624        int mNumMultiLevels;
625
626        /** if split plane should be recomputed for the repair.
627                Otherwise only the priority is recomputed, the
628                split plane itself stays the same
629        */
630        bool mRecomputeSplitPlaneOnRepair;
631
632        /** If memory should be considered during choosing
633                of the next split type during gradient method.
634        */
635        bool mConsiderMemory;
636
637        int mMaxRepairs;
638
639        int mTimeStamp;
640        friend VspTree;
641        friend OspTree;
642        friend BvHierarchy;
643
644        float mPriority;
645
646        friend ViewCellsParseHandlers;
647
648        ViewCellContainer mOldViewCells;
649
650        ObjectPvs mOldPvs;
651};
652
653}
654
655#endif
Note: See TracBrowser for help on using the repository browser.