source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/Bvh.h @ 2786

Revision 2786, 14.5 KB checked in by mattausch, 16 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 bounds of this node
463            (the box of the node or the tigher bounds of some subnodes).
464        */
465        void RenderBounds(BvhNode *node, RenderState *state, bool useTightBounds);
466        /** Renders bounding boxes of the collection of nodes.
467                @returns #rendered boxes
468        */
469        int RenderBounds(const BvhNodeContainer &nodes, RenderState *state, bool useTightBounds);
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        ////////
520        //-- functions influencing tighter bounds
521
522
523        /** Sets maximal depth for taking the bounding boxes to test the
524                visibility of a node.
525                Deeper => the bounds adapt more to the geometry.
526        */
527        void SetMaxDepthForTestingChildren(int maxDepth);
528
529        void SetAreaRatioThresholdForTestingChildren(float ratio);
530
531        /** Returns stats.
532        */
533        const BvhStats &GetBvhStats() const { return mBvhStats; }
534        /** Returns number of 'virtual' nodes in the hierarchy, i.e.
535                the number of nodes actually used for traversal.
536        */
537        int GetNumVirtualNodes() const  { return mNumVirtualNodes; }
538
539
540protected:
541
542        ////////////////////
543
544        /** protected constructor: do nothing.
545        */
546        Bvh();
547        /** Protected constructor taking scene geometry into account
548        */
549        const Bvh(const SceneEntityContainer &entities);
550        /** Called by the constructor. Initializes important members.
551        */
552        void Init();
553
554        /////////////
555
556        void ComputeBvhStats();
557        void PrintBvhStats() const;
558
559
560        //////////
561        //-- Helper methods for bounding box rendering in immediate and vbo mode.
562       
563        void PrepareVertices();
564
565        int PrepareBoundsWithDrawArrays(const BvhNodeContainer &nodes);
566        void RenderBoundsWithDrawArrays(int numNodes, RenderState *state);
567
568        /** Create the indices that each node needs to use vbo rendering.
569        */
570        void CreateIndices();
571        /** Create the list of nodes whose bounding boxes are tested instead of the
572                bounding box of the node itself.
573        */
574        bool CreateNodeRenderList(BvhNode *node);
575        /** Recursivly updates indices so we can
576                render also interior nodes without traversing hierarchy
577        */
578        void UpdateInteriors(BvhNode *node);
579        /** Recomputes the boundaries of the nodes.
580            This function is always called if some boundary options are changed.
581        */
582        void RecomputeBounds();
583        /** Does some postprocessing on the nodes.
584        */
585        void PostProcess();
586        /** Helper method that updates the number of leaves in the subtree under
587                this node.
588        */
589        void UpdateNumLeaves(BvhNode *node) const;
590        /** Frustum tests the ith plane.
591        */
592        inline bool TestPlane(BvhNode *node, int i, bool &bIntersect);
593        /** Renders a bounding box in immediate mode.
594        */
595        void RenderBoundingBoxImmediate(const AxisAlignedBox3 &box);
596
597
598
599        ////////////////////////
600
601        /// the root of the hierarchy
602        BvhNode *mRoot;
603        /// pointers to the geometry associated with this node
604        SceneEntity **mGeometry;
605        /// #of entities
606        size_t mGeometrySize;
607
608
609        ////////////////
610
611        /// the current camera
612        Camera *mCamera;
613        /// a vertex array used if working with indexed arrays (without vbo)
614        Vector3 *mVertices;
615        /// indices used for draw array rendering
616        unsigned int *mIndices;
617
618        /** maximal depth from which children are fetched for
619                testing instead of the current node
620        */
621        int mMaxDepthForTestingChildren;
622
623        float mAreaRatioThreshold;
624
625
626        BvhStats mBvhStats;
627
628        BvhNodeContainer mTestNodes;
629       
630        unsigned int *mTestIndices;
631        /// a pointer to the end of the indices array
632        int mCurrentIndicesPtr;
633
634        int mNumNodes;
635
636        /// the bounding box
637        AxisAlignedBox3 mBox;
638
639        int mNumVirtualNodes;
640
641        //////////////
642
643        unsigned int mVboId;
644};
645
646}
647
648#endif // __BVH_H
Note: See TracBrowser for help on using the repository browser.