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

Revision 1627, 14.0 KB checked in by mattausch, 18 years ago (diff)
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;
43
44
45
46/** View space / object space hierarchy statistics.
47*/
48class HierarchyStatistics: public StatisticsBase
49{
50public:
51        /// total number of entries in the pvs
52        int mPvsEntries;
53        /// storage cost
54        int mMemory;
55        /// total number of nodes
56        int mNodes;
57        /// maximal reached depth
58        int mMaxDepth;
59        /// accumulated depth
60        int mAccumDepth;
61        /// time spent for queue repair
62        float mRepairTime;
63
64        // global cost ratio violations
65        int mGlobalCostMisses;
66        /// total cost of subdivision
67        float mTotalCost;
68        /// render cost decrease of subdivision
69        float mRenderCostDecrease;
70
71        // Constructor
72        HierarchyStatistics()
73        {
74                Reset();
75        }
76
77        int Nodes() const {return mNodes;}
78        int Interior() const { return mNodes / 2; }
79        int Leaves() const { return (mNodes / 2) + 1; }
80       
81        // TODO: computation wrong
82        double AvgDepth() const { return mAccumDepth / (double)Leaves();}
83
84        void Reset()
85        {
86                mGlobalCostMisses = 0;
87                mTotalCost = 0;
88                mRenderCostDecrease = 0;
89
90                mNodes = 0;
91                mMaxDepth = 0;
92                mAccumDepth = 0;
93                mRepairTime = 0;
94                mMemory = 0;
95                mPvsEntries = 0;
96        }
97
98        void Print(ostream &app) const;
99
100        friend ostream &operator<<(ostream &s, const HierarchyStatistics &stat)
101        {
102                stat.Print(s);
103                return s;
104        }
105};
106
107
108typedef FlexibleHeap<SubdivisionCandidate *> SplitQueue;
109
110/** This class implements a structure holding two different hierarchies,
111        one for object space partitioning and one for view space partitioning.
112
113        The object space and the view space are subdivided using a cost heuristics.
114        If an object space split or a view space split is chosen is also evaluated
115        based on the heuristics.
116       
117        The view space heuristics is evaluated by weighting and adding the pvss of the back and
118        front node of each specific split. unlike for the standalone method vspbsp tree,
119        the pvs of an object would not be the pvs of single object but that of all objects
120        which are contained in the same leaf of the object subdivision. This could be done
121        by storing the pointer to the object space partition parent, which would allow access to all children.
122        Another possibility is to include traced kd-cells in the ray casing process.
123
124        Accordingly, the object space heuristics is evaluated by storing a pvs of view cells with each object.
125        the contribution to an object to the pvs is the number of view cells it can be seen from.
126
127        @note
128        There is a potential efficiency problem involved in a sense that once a certain type
129        of split is chosen for view space / object space, the candidates for the next split of
130        object space / view space must be reevaluated.
131*/
132class HierarchyManager
133{
134        friend VspTree;
135        friend OspTree;
136        friend BvHierarchy;
137        friend ViewCellsParseHandlers;
138
139public:
140        /** Constructor with the view space partition tree and
141                the object space hierarchy type as argument.
142        */
143        HierarchyManager(const int objectSpaceHierarchyType);
144        /** Hack: OspTree will copy the content from this kd tree.
145                Only view space hierarchy will be constructed.
146        */
147        HierarchyManager(KdTree *kdTree);
148
149        /** Deletes space partition and view space partition.
150        */
151        ~HierarchyManager();
152
153        /** Constructs the view space and object space subdivision from a given set of rays
154                and a set of objects.
155                @param sampleRays the set of sample rays the construction is based on
156                @param objects the set of objects
157        */
158        void Construct(
159                const VssRayContainer &sampleRays,
160                const ObjectContainer &objects,
161                AxisAlignedBox3 *forcedViewSpace);
162
163        enum
164        {
165                NO_OBJ_SUBDIV,
166                KD_BASED_OBJ_SUBDIV,
167                BV_BASED_OBJ_SUBDIV
168        };
169
170        enum
171        {
172                NO_VIEWSPACE_SUBDIV,
173                KD_BASED_VIEWSPACE_SUBDIV
174        };
175
176        /** The type of object space subdivison
177        */
178        int GetObjectSpaceSubdivisionType() const;     
179        /** The type of view space space subdivison
180        */
181        int GetViewSpaceSubdivisionType() const;
182        /** Sets a pointer to the view cells manager.
183        */             
184        void SetViewCellsManager(ViewCellsManager *vcm);
185        /** Sets a pointer to the view cells tree.
186        */
187        void SetViewCellsTree(ViewCellsTree *vcTree);
188        /** Exports the object hierarchy to disc.
189        */
190        void ExportObjectSpaceHierarchy(OUT_STREAM &stream);
191        /** Adds a sample to the pvs of the specified view cell.
192        */
193        bool AddSampleToPvs(
194                Intersectable *obj,
195                const Vector3 &hitPoint,
196                ViewCell *vc,
197                const float pdf,
198                float &contribution) const;
199
200        /** Print out statistics.
201        */
202        void PrintHierarchyStatistics(ostream &stream) const;
203
204        /** Returns the view space partition tree.
205        */
206        VspTree *GetVspTree();
207
208        /** Returns view space bounding box.
209        */
210        //AxisAlignedBox3 GetViewSpaceBox() const;
211
212        /** Returns object space bounding box.
213        */
214        AxisAlignedBox3 GetObjectSpaceBox() const;
215
216        /** Exports object space hierarchy for visualization.
217        */
218        void ExportObjectSpaceHierarchy(Exporter *exporter,
219                                                                        const ObjectContainer &objects,
220                                                                        const AxisAlignedBox3 *bbox,
221                                                                        const bool exportBounds = true) const;
222
223        /** Returns intersectable pierced by this ray.
224        */
225        Intersectable *GetIntersectable(const VssRay &ray, const bool isTermination) const;
226
227        /** Export object space partition bounding boxes.
228        */
229        void ExportBoundingBoxes(OUT_STREAM &stream, const ObjectContainer &objects);
230
231        friend ostream &operator<<(ostream &s, const HierarchyManager &hm)
232        {
233                hm.PrintHierarchyStatistics(s);
234                return s;
235        }
236
237protected:
238
239        /** Returns true if the global termination criteria were met.
240        */
241        bool GlobalTerminationCriteriaMet(SubdivisionCandidate *candidate) const;
242
243        /** Prepare construction of the hierarchies, set parameters, compute
244                first split candidates.
245        */
246        SubdivisionCandidate *PrepareObjectSpaceSubdivision(const VssRayContainer &sampleRays,
247                                                                                                                const ObjectContainer &objects);
248
249
250        //////////////////////////////
251        // the main loop
252        //////////////////////
253
254        /** This is for interleaved construction / sequential construction.
255        */
256        void RunConstruction(const bool repairQueue,
257                                                 const VssRayContainer &sampleRays,
258                                                 const ObjectContainer &objects,
259                                                 AxisAlignedBox3 *forcedViewSpace);
260       
261        /** This is for interleaved construction using some objects
262                and some view space splits.
263        */
264        int RunConstruction(SplitQueue &splitQueue,
265                                                SubdivisionCandidateContainer &chosenCandidates,
266                                                const float minRenderCostDecr,
267                                                const int maxSteps);
268
269        /** Default subdivision method.
270        */
271        void RunConstruction(const bool repairQueue);
272               
273        ////////////////////////////////////////////////
274
275        /** Evaluates the subdivision candidate and executes the split.
276        */
277        bool ApplySubdivisionCandidate(SubdivisionCandidate *sc,
278                                                                   SplitQueue &splitQueue,
279                                                                   const bool repairQueue);
280
281        /** Tests if hierarchy construction is finished.
282        */
283        bool FinishedConstruction() const;
284
285        /** Returns next subdivision candidate from the split queue.
286        */
287        SubdivisionCandidate *NextSubdivisionCandidate(SplitQueue &splitQueue);
288
289        /** Repairs the dirty entries of the subdivision candidate queue. The
290                list of entries is given in the dirty list.
291        */
292        void RepairQueue(const vector<SubdivisionCandidate *> &dirtyList, SplitQueue &splitQueue);
293
294        /** Collect subdivision candidates which were affected by the splits from the
295                chosenCandidates list.
296        */
297        void CollectDirtyCandidates(const SubdivisionCandidateContainer &chosenCandidates,
298                                                                SubdivisionCandidateContainer &dirtyList);
299
300        /** Collect the list of dirty candidates after the current
301                subdivision candidate split.
302        */
303        void CollectDirtyCandidates(SubdivisionCandidate *sc,
304                                                                vector<SubdivisionCandidate *> &dirtyList);
305
306        /** Evaluate subdivision stats for log.
307        */
308        void EvalSubdivisionStats();
309
310        void AddSubdivisionStats(const int splits,
311                                                         const float renderCostDecr,
312                                                         const float totalRenderCost,
313                                                         const int totalPvsEntries,
314                                                         const int memory,
315                                                         const float renderCostPerStorage);
316
317        bool AddSampleToPvs(Intersectable *obj,
318                                                const float pdf,
319                                                float &contribution) const;
320
321        /** Collect affected view space candidates.
322        */
323        void CollectViewSpaceDirtyList(SubdivisionCandidate *sc,
324                                                                   SubdivisionCandidateContainer &dirtyList);
325
326        /** Collect affected object space candidates.
327        */
328        void CollectObjectSpaceDirtyList(SubdivisionCandidate *sc,
329                                                                         SubdivisionCandidateContainer &dirtyList);
330               
331        /** Export object space partition tree.
332        */
333        void ExportOspTree(Exporter *exporter,
334                                           const ObjectContainer &objects) const;
335
336        /** Parse the environment variables.
337        */
338        void ParseEnvironment();
339
340        bool StartObjectSpaceSubdivision() const;
341        bool StartViewSpaceSubdivision() const;
342
343        ////////////////////////////
344        // Helper function for preparation of subdivision
345        ///////
346
347        /** Prepare bv hierarchy for subdivision
348        */
349        SubdivisionCandidate *PrepareBvHierarchy(const VssRayContainer &sampleRays,
350                                                                           const ObjectContainer &objects);
351
352        /** Prepare object space kd tree for subdivision.
353        */
354        SubdivisionCandidate *PrepareOspTree(const VssRayContainer &sampleRays,
355                                                                   const ObjectContainer &objects);
356
357        /** Prepare view space subdivision and add candidate to queue.
358        */
359        SubdivisionCandidate *PrepareViewSpaceSubdivision(const VssRayContainer &sampleRays,
360                                                                                                          const ObjectContainer &objects);
361
362        /** Was object space subdivision already constructed?
363        */
364        bool ObjectSpaceSubdivisionConstructed() const;
365       
366        /** Was view space subdivision already constructed?
367        */
368        bool ViewSpaceSubdivisionConstructed() const;
369
370        /** Reset the split queue, i.e., reevaluate the split candidates.
371        */
372    void ResetQueue();
373
374        /** After the suddivision has ended, do some final tasks.
375        */
376        void FinishObjectSpaceSubdivision(const ObjectContainer &objects) const;
377
378        /** Returns depth of object space subdivision.
379        */
380        int GetObjectSpaceSubdivisionDepth() const;
381
382        /** Construct object space partition interleaved with view space partition.
383                Each time the best object or view space candidate is selected
384                for the next split.
385        */
386        void ConstructInterleaved(const VssRayContainer &sampleRays,
387                                                          const ObjectContainer &objects,
388                                                          AxisAlignedBox3 *forcedViewSpace);
389
390        /** Construct object space partition interleaved with view space partition.
391                The method chooses a number candidates of each type for subdivision.
392                The number is determined by the "gradient", i.e., the render cost decrease.
393                Once this render cost decrease is lower than the render cost decrease
394                for the splits of previous type, the method will stop current subdivision and
395                evaluate if view space or object space would be the beneficial for the
396                next number of split.
397        */
398        void ConstructInterleavedWithGradient(const VssRayContainer &sampleRays,
399                                                                                  const ObjectContainer &objects,
400                                                                                  AxisAlignedBox3 *forcedViewSpace);
401
402        /** Use iteration to construct the object space hierarchy.
403        */
404        void ConstructMultiLevel(const VssRayContainer &sampleRays,
405                                                         const ObjectContainer &objects,
406                                                         AxisAlignedBox3 *forcedViewSpace);
407
408        /** Reset the object space subdivision.
409                E.g., deletes hierarchy and resets stats.
410                so construction can be restarted.
411        */
412        SubdivisionCandidate *ResetObjectSpaceSubdivision(const VssRayContainer &rays,
413                                                                                                          const ObjectContainer &objects);
414
415        SubdivisionCandidate *ResetViewSpaceSubdivision(const VssRayContainer &rays,
416                                                                                                        const ObjectContainer &objects);
417
418
419protected:
420
421        /** construction types
422                sequential: construct first view space, then object space
423                interleaved: construct view space and object space fully interleaved
424                gradient: construct view space / object space until a threshold is reached
425                multilevel: iterate until subdivisions converge to the optimum.
426        */
427        enum {SEQUENTIAL, INTERLEAVED, GRADIENT, MULTILEVEL};
428
429        /// type of hierarchy construction
430        int mConstructionType;
431
432        /// Type of object space partition
433        int mObjectSpaceSubdivisionType;
434        /// Type of view space partition
435    int mViewSpaceSubdivisionType;
436
437        /// the traversal queue
438        SplitQueue mTQueue;
439       
440        ////////////
441        //-- helper variables
442       
443        // the original osp type
444        int mSavedObjectSpaceSubdivisionType;
445        // the original vsp type
446        int mSavedViewSpaceSubdivisionType;
447        /// the current subdivision candidate
448        //SubdivisionCandidate *mCurrentCandidate;
449
450
451        ///////////////////
452        // Hierarchies
453
454        /// view space hierarchy
455        VspTree *mVspTree;
456        /// object space partition kd tree
457        OspTree *mOspTree;
458
459        public:
460        /// bounding volume hierarchy
461        BvHierarchy *mBvHierarchy;
462       
463protected:
464
465
466        //////////
467        //-- global termination criteria
468
469        /// the mininal acceptable cost ratio for a split
470        float mTermMinGlobalCostRatio;
471        /// the threshold for global cost miss tolerance
472        int mTermGlobalCostMissTolerance;
473        /// maximum number of leaves
474        int mTermMaxLeaves;
475
476        ////////////////////
477
478        /// statistics about the hierarchy
479        HierarchyStatistics mHierarchyStats;
480
481        int mMinDepthForObjectSpaceSubdivion;
482        int mMinDepthForViewSpaceSubdivion;
483       
484        //int mMinRenderCostDecrease;
485
486        ofstream mSubdivisionStats;
487
488        /// if the queue should be repaired after a subdivision steps
489        bool mRepairQueue;
490
491        bool mStartWithObjectSpace;
492        /** if multi level construction method should be used
493                where we iterate over both hierarchies until we
494                converge to the optimum.
495        */
496        bool mUseMultiLevelConstruction;
497        /// number of iteration steps for multilevel approach   
498        int mNumMultiLevels;
499};
500
501}
502
503#endif
Note: See TracBrowser for help on using the repository browser.