source: GTP/trunk/App/Demos/Vis/CHC_revisited/Bvh.h @ 2776

Revision 2776, 14.4 KB checked in by mattausch, 17 years ago (diff)
Line 
1// This file has been written by Jiri Bittner, October 2006
2
3#ifndef __BVH_H
4#define __BVH_H
5
6#include "common.h"
7#include "Vector3.h"
8#include "AxisAlignedBox3.h"
9//#include "SceneEntity.h"
10
11
12namespace CHCDemoEngine
13{
14
15////////
16//-- Forward declarations
17
18class SceneEntity;
19class Camera;
20class RenderState;
21
22
23/** A node in the bv hierarchy.
24*/
25class BvhNode
26{
27        friend class Bvh;
28        friend class BvhLoader;
29        friend class mygreaterdistance;
30
31public:
32
33        /** visibility related options
34        */
35        struct VisibilityInfo
36        {
37                VisibilityInfo() { Reset(); }           
38                /** Reset the visibility info.
39                */
40                void Reset();
41
42                /// if the node is visible
43                bool mIsVisible;
44                /// frame id until this node is assumed to stay visible
45                int mAssumedVisibleFrameId;
46                /// the frame when this node was last touched during traversal
47                int mLastVisitedFrame;
48                /// #times this node was invisible (only valid if the node actually is invisible)
49                int mTimesInvisible;
50                /// if the node is view frustum culled
51                bool mIsFrustumCulled;
52                /// if the node is newly processed with no prior history available
53                bool mIsNew;
54        };
55
56        /** Constructor taking the parent node.
57        */
58        BvhNode(BvhNode *parent);
59        /** Returns true if this node is a leaf.
60        */
61        //virtual bool IsPseudoLeaf() = 0;
62        /** Virtual destructor doing nothing.
63        */
64        virtual ~BvhNode();
65        /** Returns unique id for this node.
66        */
67        //inline int GetId() {return mId;}
68        /** Depth of this node in the tree.
69        */
70        inline int GetDepth() const {return mDepth;}
71        /** Returns parent of this bvh node, NULL if it is root.
72        */
73        inline BvhNode *GetParent() {return mParent;}
74        /** Number of leaves in the subtree induced by this node.
75        */
76        inline int GetNumLeaves() const {return mNumLeaves;}
77        /** Reset the status of this node.
78        */
79        virtual void ResetVisibility();
80
81        virtual bool IsLeaf() const = 0;
82
83        bool IsVirtualLeaf() const { return mIsVirtualLeaf; }
84
85
86        ////////////////
87        //-- visibility culling related functions
88
89        inline int GetLastVisitedFrame() const;
90
91        inline void SetLastVisitedFrame(int lastVisited);
92        /** If this node is considered visible.
93        */
94        inline bool IsVisible() const;
95        /** Set visibility flag of the node.
96        */
97        inline void SetVisible(bool visible);
98        /** The frame id until this node is assumed visible
99        */
100        inline void SetAssumedVisibleFrameId(int t);
101        /** See set.
102        */
103        inline int GetAssumedVisibleFrameId() const;
104        /** Increases the #times this node was
105                successfully tested invisible.
106        */
107        inline void IncTimesTestedInvisible();
108       
109        inline int GetTimesTestedInvisible() const;
110        inline void SetTimesTestedInvisible(int t);
111       
112        inline int GetTurnedVisibleFrame() const;
113        inline void SetTurnedVisibleFrame(int turnedVisibleFrame);
114
115        inline int GetLastTestedFrame();
116        inline void SetLastTestedFrame(int lastTested);
117       
118        inline bool IsViewFrustumCulled() const;
119        inline void SetViewFrustumCulled(bool frustumCulled);
120
121        inline bool IsNew() const;
122        inline void SetIsNew(bool isNew);
123
124
125        /** Returns the bounding box of this node.
126        */
127        inline const AxisAlignedBox3 &GetBox() { return mBox; }
128        /** Return index of this node.
129        */
130        inline int GetId() const { return mId; }
131        /** See get
132        */
133        inline void SetId(int id) { mId = id; }
134
135
136        //////////
137        //-- rendering
138       
139        /** Returns the frame in which this node was last rendered.
140        */
141        inline int GetLastRenderedFrame() const;
142        /** See get.
143        */
144        inline void SetLastRenderedFrame(int lastRenderedFrame);
145        /** Does this node contain renderable geometry?
146        */
147        inline bool Empty() const;
148        /** Counts #geometry stored in the subtree.
149        */
150        inline int CountPrimitives() const;
151
152
153protected:
154
155        /////////////
156       
157        /// some flags
158        int mFlags;
159        /// the depth of this node
160        unsigned char mDepth;
161        /// the split axis
162        char mAxis;
163        /// the parent node
164        BvhNode *mParent;
165        /// stores the visibility related info
166        VisibilityInfo mVisibility;
167
168        /////////
169        // used for view frustum culling
170
171        int mPlaneMask;
172        int mPreferredPlane;
173
174
175        ////////////
176        //-- rendering related options
177       
178        /// when the node was last rendered
179        int mLastRenderedFrame;
180        /// #leaves under this node
181        int mNumLeaves;
182       
183        // Indices to first and last triangle in the triangle array
184        // assumes the triangle are placed in continuous chunk of memory
185        // however this need not be a global array!
186       
187        /// the index of the first triangle
188        int mFirst;
189        /// the index of the last triangle
190        int mLast;
191
192        /// these nodes can be tested instead of the current node
193        int mTestNodesIdx;
194       
195        int mNumTestNodes;
196
197        int mIndicesPtr;
198
199        /// Area of this node
200        float mArea;
201        /// distance to the camera
202        float mDistance;
203        /// the index of this node
204        unsigned int mId;
205        /// indices used for draw array rendering
206        unsigned int *mIndices;
207        /// the bounding box
208        AxisAlignedBox3 mBox;
209        /// if this node is a virtual leaf
210        bool mIsVirtualLeaf;
211        /** This marks the maximal depth where a virtual leaf can be defined.
212            From this point on it makes no sense to traverse down further, as all
213                nodes below contain the same geometry, so no further refinement of visibility
214                can be archieved. All nodes below this point can merely used to define the
215                tighter bounds.
216        */
217        bool mIsMaxDepthForVirtualLeaf;
218};
219
220
221/////////////////
222//-- public inline functions
223
224int BvhNode::GetLastVisitedFrame() const
225{
226        return mVisibility.mLastVisitedFrame;
227}
228
229
230void BvhNode::SetLastVisitedFrame(const int lastVisited)
231{
232        mVisibility.mLastVisitedFrame = lastVisited;
233}
234
235
236bool BvhNode::IsVisible() const
237{
238        return mVisibility.mIsVisible;
239}
240
241
242void BvhNode::SetVisible(bool visible)
243{
244        mVisibility.mIsVisible = visible;
245}
246
247
248void BvhNode::IncTimesTestedInvisible()
249{
250        ++ mVisibility.mTimesInvisible;
251}
252
253
254int BvhNode::GetTimesTestedInvisible() const
255{
256        return mVisibility.mTimesInvisible;
257}
258
259
260void BvhNode::SetTimesTestedInvisible(int t)
261{
262        mVisibility.mTimesInvisible = t;
263}
264
265
266bool BvhNode::IsViewFrustumCulled() const
267{
268        return mVisibility.mIsFrustumCulled;
269}
270
271
272void BvhNode::SetViewFrustumCulled(const bool frustumCulled)
273{
274        mVisibility.mIsFrustumCulled = frustumCulled;
275}
276
277
278bool BvhNode::IsNew() const
279{
280        return mVisibility.mIsNew;
281}
282
283
284void BvhNode::SetIsNew(const bool isNew)
285{
286        mVisibility.mIsNew = isNew;
287}
288
289
290int BvhNode::GetLastRenderedFrame() const
291{
292        return mLastRenderedFrame;
293}
294       
295
296void BvhNode::SetLastRenderedFrame(int lastRenderedFrame)
297{
298        mLastRenderedFrame = lastRenderedFrame;
299}
300       
301       
302bool BvhNode::Empty() const
303{
304        return mFirst == -1;
305}
306
307
308int BvhNode::CountPrimitives() const
309{
310        return mLast - mFirst + 1;
311}
312
313
314void BvhNode::SetAssumedVisibleFrameId(int t)
315{
316        mVisibility.mAssumedVisibleFrameId = t;
317}
318
319
320int BvhNode::GetAssumedVisibleFrameId() const
321{
322        return mVisibility.mAssumedVisibleFrameId;
323}
324
325
326/** Internal node of the bv hierarchy.
327*/
328class BvhInterior: public BvhNode
329{
330        friend class Bvh;
331        friend class BvhLoader;
332
333public:
334
335        BvhInterior(BvhNode *parent): mBack(NULL), mFront(NULL), BvhNode(parent)
336        {}
337        virtual bool IsLeaf() const { return false; }
338        /** Back child.
339        */
340        inline BvhNode *GetBack() { return mBack; }
341        /** Front child.
342        */
343        inline BvhNode *GetFront() { return mFront; }
344        /** recursivly delete tree.
345        */
346        virtual ~BvhInterior() { if (mBack) delete mBack; if (mFront) delete mFront;}
347
348
349protected:
350
351        BvhNode *mBack;
352        BvhNode *mFront;
353};
354
355
356class BvhLeaf: public BvhNode
357{
358        friend class Bvh;
359        friend class BvhLoader;
360
361public:
362
363        BvhLeaf(BvhNode *parent): BvhNode(parent)
364        {}
365
366        ~BvhLeaf();
367
368        virtual bool IsLeaf() const { return true; }
369};
370
371
372/**     This class implements the compare operator for the priority queue.
373        a lower distance has a higher value in the queue
374*/
375class mygreaterdistance
376{
377public:
378        bool operator() (BvhNode *v1, BvhNode *v2) const
379    {
380                return (v1->mDistance > v2->mDistance);
381    }
382};
383
384typedef std::priority_queue<BvhNode *, std::vector<BvhNode *>, mygreaterdistance> TraversalQueue;
385
386
387/** Class representing a bounding volume hierarchy.
388*/
389class Bvh
390{
391        friend class BvhLoader;
392
393        /** Bvh properties
394        */
395        struct BvhStats
396        {
397                BvhStats():
398                mInteriorSA(0),
399                mLeafSA(0),
400                mInteriorVol(0),
401                mLeafVol(0),
402                mTriangles(0),
403                mTriangleRatio(0),
404                mGeometryRatio(0),
405                mMaxGeometry(0),
406                mMaxTriangles(0)
407                {}
408               
409                float mInteriorSA;
410                float mLeafSA;
411                float mInteriorVol;
412                float mLeafVol;
413               
414                int mTriangles;
415
416                float mTriangleRatio;
417                float mGeometryRatio;
418
419                int mMaxGeometry;
420                int mMaxTriangles;
421        };
422
423public:
424
425        /** Destructor.
426        */
427        ~Bvh();
428        /** Returns number of bvh nodes.
429        */
430        inline int GetNumNodes() const { return mNumNodes; }
431        /** Returns number of bvh leaves.
432        */
433        inline int GetNumLeaves() const { return mNumNodes / 2 + 1;}
434        /** Returns root node of the bvh.
435        */
436        BvhNode *GetRoot() { return mRoot; }
437        /** Sets the scene camera
438        */
439        void SetCamera(Camera * camera) { mCamera = camera; }
440
441        ///////////////
442        //-- functions collecting nodes based on some criteria
443
444        void CollectNodes(BvhNode *node, BvhNodeContainer &nodes, int depth);
445        void CollectNodes(BvhNode *node, BvhNodeContainer &nodes);
446        void CollectLeaves(BvhNode *node, BvhLeafContainer &leaves);
447        /** Collect only the virtual leaves.
448        */
449        void CollectVirtualLeaves(BvhNode *node, BvhNodeContainer &leaves);
450
451
452        //////////////////////
453
454        /** Returns geometry by reference (faster).
455        */
456        SceneEntity **GetGeometry(BvhNode *node, int &size);
457
458
459        /////////////
460        //-- Rendering related options
461
462        /** Renders the bounding box of this node (Or the tigher bounding boxes of some subnodes).
463        */
464        void RenderBoundingBox(BvhNode *node, RenderState *state);
465        /** Renders bounding boxes of the collection of nodes.
466                @returns #rendered boxes
467        */
468        int RenderBoundingBoxes(const BvhNodeContainer &nodes, RenderState *state);
469
470        /** Returns the bounding box of this bvh.
471        */
472        inline const AxisAlignedBox3 &GetBox() { return mBox; }
473
474
475        //////////////
476        //-- Traversal related options
477
478        /** Pulls up visible classification.
479        */
480        void MakeParentsVisible(BvhNode *node);
481        /** Does the view frustum culling for this node with respect to the previous culls
482                @returns: 0 if completely outside, 1 if completely inside, -1 if intersecting (partly inside),
483        */
484        int     IsWithinViewFrustum(BvhNode *node);
485        /** Sets frame dependent values
486        */
487        void InitFrame();
488        /** This gives the orthogonal distance from the viewpoint to the nearest bounding box vertex
489                note that negative values can appear because culling is done only afterwards
490        */
491        void CalcDistance(BvhNode *node) const;
492        /** Returns the stored distance.
493        */
494        float GetDistance(BvhNode *node) const  { return node->mDistance; }
495        /** Pulls up the last visited classification in the bvh.
496        */
497        void PullUpLastVisited(BvhNode *node, int frameId) const;
498        /** Resets the node classifications in the tree.
499        */
500        void ResetNodeClassifications();
501        /** Helper function that renders the bounding boxes of the leaves as
502                wireframes for visualization purpose.
503        */
504        //void RenderBoundingBoxesForViz(int mode);
505        /** Count triangles the node contains.
506        */
507        int CountTriangles(BvhNode *node) const;
508        /** Returns area of the the node.
509        */
510        float GetArea(BvhNode *node) const;
511        /** Compute unique ids for the nodes.
512        */
513        void ComputeIds();
514        /** Assign virtual leaves based on specified number of triangles per leaf.
515        */
516        void SetVirtualLeaves(int numTriangles);
517
518        ////////
519        //-- functions influencing tighter bounds
520
521
522        /** Sets maximal depth for taking the bounding boxes to test the
523                visibility of a node.
524                Deeper => the bounds adapt more to the geometry.
525        */
526        void SetMaxDepthForTestingChildren(int maxDepth);
527
528        void SetAreaRatioThresholdForTestingChildren(float ratio);
529
530        /** Returns stats.
531        */
532        const BvhStats &GetBvhStats() const { return mBvhStats; }
533        /** Returns number of 'virtual' nodes in the hierarchy, i.e.
534                the number of nodes actually used for traversal.
535        */
536        int GetNumVirtualNodes() const  { return mNumVirtualNodes; }
537
538
539protected:
540
541        ////////////////////
542
543        /** protected constructor: do nothing.
544        */
545        Bvh();
546        /** Protected constructor taking scene geometry into account
547        */
548        const Bvh(const SceneEntityContainer &entities);
549        /** Called by the constructor. Initializes important members.
550        */
551        void Init();
552
553        /////////////
554
555        void ComputeBvhStats();
556        void PrintBvhStats() const;
557
558
559        //////////
560        //-- Helper methods for bounding box rendering in immediate and vbo mode.
561       
562        void PrepareVertices();
563
564        int PrepareBoundingBoxesWithDrawArrays(const BvhNodeContainer &nodes);
565        void RenderBoundingBoxesWithDrawArrays(int numNodes, RenderState *state);
566
567        /** Create the indices that each node needs to use vbo rendering.
568        */
569        void CreateIndices();
570        /** Create the list of nodes whose bounding boxes are tested instead of the
571                bounding box of the node itself.
572        */
573        bool CreateNodeRenderList(BvhNode *node);
574        /** Recursivly updates indices so we can
575                render also interior nodes without traversing hierarchy
576        */
577        void UpdateInteriors(BvhNode *node);
578        /** Recomputes the boundaries of the nodes.
579            This function is always called if some boundary options are changed.
580        */
581        void RecomputeBounds();
582        /** Does some postprocessing on the nodes.
583        */
584        void PostProcess();
585        /** Helper method that updates the number of leaves in the subtree under
586                this node.
587        */
588        void UpdateNumLeaves(BvhNode *node) const;
589        /** Frustum tests the ith plane.
590        */
591        inline bool TestPlane(BvhNode *node, int i, bool &bIntersect);
592
593        void RenderBoundingBoxImmediate(const AxisAlignedBox3 &box);
594
595
596
597        ////////////////////////
598
599        /// the root of the hierarchy
600        BvhNode *mRoot;
601        /// pointers to the geometry associated with this node
602        SceneEntity **mGeometry;
603        /// #of entities
604        size_t mGeometrySize;
605
606
607        ////////////////
608
609        /// the current camera
610        Camera *mCamera;
611        /// a vertex array used if working with indexed arrays (without vbo)
612        Vector3 *mVertices;
613        /// indices used for draw array rendering
614        unsigned int *mIndices;
615
616        /** maximal depth from which children are fetched for
617                testing instead of the current node
618        */
619        int mMaxDepthForTestingChildren;
620
621        float mAreaRatioThreshold;
622
623
624        BvhStats mBvhStats;
625
626        BvhNodeContainer mTestNodes;
627       
628        unsigned int *mTestIndices;
629        /// a pointer to the end of the indices array
630        int mCurrentIndicesPtr;
631
632        int mNumNodes;
633
634        /// the bounding box
635        AxisAlignedBox3 mBox;
636
637        int mNumVirtualNodes;
638
639        //////////////
640
641        unsigned int mVboId;
642};
643
644}
645
646#endif // __BVH_H
Note: See TracBrowser for help on using the repository browser.