source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.h @ 262

Revision 262, 11.2 KB checked in by mattausch, 19 years ago (diff)

debugged bsp

Line 
1#ifndef _ViewCellBsp_H__
2#define _ViewCellBsp_H__
3
4#include "Mesh.h"
5#include "Containers.h"
6#include <stack>
7
8class ViewCell;
9class Plane3;
10//class Mesh;
11class BspTree; 
12class BspInterior;
13class Polygon3;
14class AxisAlignedBox3;
15class Ray;
16
17//namespace GtpVisibilityPreprocessor {
18
19/** Container storing a soup of polygons used during BSP tree construction
20*/
21typedef vector<Polygon3 *> PolygonContainer;
22typedef vector<Ray *> RayContainer;
23
24struct BspRayTraversalData
25{
26    BspNode *mNode;
27    Vector3 mExitPoint;
28    float mMaxT;
29   
30    BspRayTraversalData() {}
31
32    BspRayTraversalData(BspNode *n, const Vector3 &p, const float maxt):
33    mNode(n), mExitPoint(p), mMaxT(maxt)
34        {}
35};
36
37class BspTreeStatistics // TODO: should have common superclass with KdTreeStatistics
38{
39public:
40  // total number of nodes
41  int nodes;
42  // number of splits
43  int splits;
44  // totals number of rays
45  int rays;
46  // maximal reached depth
47  int maxDepth;
48  // total number of query domains
49  int queryDomains;
50  // total number of ray references
51  int rayRefs;
52  // refs in non empty leafs
53  int rayRefsNonZeroQuery;
54  // total number of query references
55  int objectRefs;
56  // nodes with zero queries
57  int zeroQueryNodes;
58  // max depth nodes
59  int maxDepthNodes;
60  // max number of rays per node
61  int maxObjectRefs;
62  // number of dynamically added ray refs
63  int addedRayRefs;
64  // number of dynamically removed ray refs
65  int removedRayRefs;
66 
67  // Constructor
68  BspTreeStatistics()
69  {
70          Reset();
71  }
72
73  int Nodes() const {return nodes;}
74  int Interior() const { return nodes/2; }
75  int Leaves() const { return (nodes/2) + 1; }
76
77  void Reset()
78  {
79          nodes = 0;
80          splits = 0;
81          rays = queryDomains = 0;
82          rayRefs = rayRefsNonZeroQuery = objectRefs = 0;
83          zeroQueryNodes = 0;
84      maxDepthNodes = 0;
85      //minCostNodes = 0;
86          maxObjectRefs = 0;
87          addedRayRefs = removedRayRefs = 0;
88  }
89
90  void
91  Print(ostream &app) const;
92
93  friend ostream &operator<<(ostream &s, const BspTreeStatistics &stat) {
94    stat.Print(s);
95    return s;
96  }
97 
98};
99
100/**
101    BspNode abstract class serving for interior and leaf node implementation
102*/
103class BspNode
104{
105        friend BspTree;
106
107public:
108        BspNode();
109        BspNode(BspInterior *parent);
110
111        /** Determines whether this node is a leaf or not
112        @return true if leaf
113        */
114        virtual bool IsLeaf() const = 0;
115
116        /** Determines whether this node is a root
117        @return true if root
118        */
119        virtual bool IsRoot() const;
120
121        /** Returns parent node.
122        */
123        BspInterior *GetParent();
124        /** Sets parent node.
125        */
126        void SetParent(BspInterior *parent);
127
128        PolygonContainer *GetPolygons();
129
130protected:
131
132        /// parent of this node
133        BspInterior *mParent;
134
135        PolygonContainer mPolygons;
136};
137
138/** BSP interior node implementation
139*/
140class BspInterior : public BspNode
141{
142public:
143        /** Standard contructor taking split plane as argument.
144        */
145        BspInterior(Plane3 plane);
146        /** @return false since it is an interior node
147        */
148        bool IsLeaf() const;
149
150        BspNode *GetBack();
151        BspNode *GetFront();
152
153        Plane3 *GetPlane();
154
155        void ReplaceChildLink(BspNode *oldChild, BspNode *newChild);
156        void SetupChildLinks(BspNode *b, BspNode *f);
157
158        /** Splits polygons.
159                @param polys the polygons to be split
160                @param frontPolys returns the polygons in the front of the split plane
161                @param backPolys returns the polygons in the back of the split plane
162                @param splits number of splits
163        */
164        void SplitPolygons(PolygonContainer *polys, PolygonContainer *frontPolys,
165                                           PolygonContainer *backPolys, int &splits, bool storePolys = false);
166
167        friend ostream &operator<<(ostream &s, const BspInterior &A)
168        {
169                return s << A.mPlane;
170        }
171
172
173protected:
174       
175        /// Splitting plane corresponding to this node
176        Plane3 mPlane;
177        /// back node
178        BspNode *mBack;
179        /// front node
180        BspNode *mFront;
181};
182
183/** BSP leaf node implementation.
184*/
185class BspLeaf : public BspNode
186{
187        friend BspTree;
188
189public:
190        BspLeaf(ViewCell *viewCell = NULL);
191
192        /** @return true since it is an interior node
193        */
194        bool IsLeaf() const;
195        /** Returns pointer from view cell.
196        */
197        ViewCell *GetViewCell();
198        /** Sets pointer to view cell.
199        */
200        void SetViewCell(ViewCell *viewCell);
201
202protected:
203
204        /** Helper function used to add remaining polygons to leaf.
205        */
206        void AddPolygons(PolygonContainer *polys);
207
208        /// polygonal representation of this viewcell
209        /// if NULL this note does not correspond to feasible viewcell
210        ViewCell *mViewCell;
211};
212
213
214/** Implementation of the ViewCell BSP tree. */
215class BspTree
216{
217public:
218               
219        /** Additional data which is passed down the BSP tree during traversal.
220        */
221        struct BspTraversalData
222        { 
223                /// the current node
224                BspNode *mNode;
225                /// parent of current node
226                BspInterior *mParent;
227                /// polygonal data for splitting
228                PolygonContainer *mPolygons;
229                /// current depth
230                int mDepth;
231               
232                BspTraversalData() {}
233               
234                BspTraversalData(BspNode *node, BspInterior *parent, PolygonContainer *polys, const int depth):
235                mNode(node), mParent(parent), mPolygons(polys), mDepth(depth) {}
236    };
237
238        typedef std::stack<BspTraversalData> BspTraversalStack;
239
240        /// BSP tree construction type
241        enum {VIEWCELLS, SCENE_GEOMETRY, RAYS};
242
243        /** Default constructor creating an empty tree.
244        */
245        BspTree();
246
247        ~BspTree();
248
249        const BspTreeStatistics &GetStatistics() const;
250 
251        /** Constructs tree using the given list of view cells.
252            A pointer to the appropriate view cell is stored within each leaf.
253                Many leafs can point to the same viewcell.
254        */
255        void Construct(const ViewCellContainer &viewCells);
256
257        /** Constructs tree using the given list of objects.
258            Note that the objects are not taken as view cells, but the view cells are
259                constructed from the subdivision: Each leaf is taken as one viewcell;
260
261                @param objects list of objects
262                @returns list of view cells.
263        */
264        void Construct(const ObjectContainer &objects, ViewCellContainer *viewCells);
265
266        /** Constructs tree using the given number of rays
267            @param objects list of objects
268                @returns list of view cells.
269        */
270        void Construct(const RayContainer &rays, ViewCellContainer *viewCells);
271
272        int CollectLeafPvs();
273
274        void CollectLeaves(vector<BspLeaf *> &leaves);
275
276        /** Returns box which bounds the whole tree.
277        */
278        AxisAlignedBox3 GetBoundingBox()const;
279
280        /** Returns root of BSP tree.
281        */
282        BspNode *GetRoot() const;
283
284        /** If the view cell polygons are stored in the nodes.
285        */
286        bool StorePolys() const;
287
288        /** Exports Bsp tree to file.
289        */
290        bool Export(const string filename);
291
292
293protected:
294       
295        /** Initialises BSP tree.
296                @param maxPolygons the maximal polygon count before termination of
297                subdivision
298                @param maxDepth the maximal depth before termination of
299                subdivision
300        */
301        void InitTree(int maxPolygons, int maxDepth);
302
303        /** Constructs the tree from the given list of polygons.
304        */
305        void Construct(PolygonContainer *polys);
306
307        /** Evaluates plane classification with respect to the plane's
308                contribution for a balanced tree.
309        */
310        static inline int EvalForBalancedTree(const int classficiation);
311        /** Evaluates plane classification with respect to the plane's
312                contribution for a minimum number splits in the tree.
313        */
314        static inline int EvalForLeastSplits(const int classification);
315
316        /** Evaluates the contribution of the candidate split plane.
317        */
318        int EvalSplitPlane(PolygonContainer *polygons, const Plane3 &candidatePlane) const;
319
320        /** Evaluates tree stats in the BSP tree leafs.
321        */
322        void EvaluateLeafStats(const BspTraversalData &data);
323
324        /** Subdivides node with respect to the traversal data.
325            @param tStack current traversal stack
326                @param tData traversal data also holding node to be subdivided
327                @param viewCell the view cell that will be represented with this part of the Bsp tree.
328                @returns new root of the subtree
329        */
330        BspNode *Subdivide(BspTraversalStack &tStack, BspTraversalData &tData, ViewCell *viewCell = NULL);
331
332        /** Selects a splitting plane.
333                @param polygons the polygon data on which the split decition is based
334        */
335        Plane3 SelectPlane(PolygonContainer *polygons) const;
336
337        /** Filters next viewcell down the tree and inserts it into the appropriate leaves
338                (i.e., possibly more than one leaf).
339        */
340        void InsertViewCell(ViewCell *viewCell);
341       
342        /** Subdivide leaf.
343                @param leaf the leaf to be subdivided
344                @param parent the parent node of this leaf
345                @param polys the input polygons
346                @param depth the current tree depth
347                @param frontPolys the polygons of the front child node as a result from splitting
348                @param backPolys the polygons of the back child node as a result from splitting
349        */
350        BspNode *SubdivideNode(BspLeaf *leaf,
351                                                   BspInterior *parent,
352                                                   PolygonContainer *polys,
353                                                   const int depth,
354                                                   PolygonContainer *frontPolys,
355                                                   PolygonContainer *backPolys);
356
357        /** Filters polygons down the tree.
358                @param node the current BSP node
359                @param polys the polygons to be filtered
360                @param frontPolys returns the polygons in front of the split plane
361                @param backPolys returns the polygons in the back of the split plane
362        */
363        void FilterPolygons(BspInterior *node, PolygonContainer *polys,
364                                                PolygonContainer *frontPolys, PolygonContainer *backPolys);
365
366        /** Selects the split plane in order to get a balanced tree.
367                @param polygons container of polygons
368                @param maxTests the maximal number of candidate tests
369        */
370        Plane3 SelectPlaneHeuristics(PolygonContainer *polygons, int maxTests) const;
371
372        /** Extracts the meshes of the objects and copies them into the mesh.
373                Adds object aabb to the aabb of the tree.
374                @param maxPolys the maximal number of objects to be stored as polygons
375        */
376        void Copy2PolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects);
377        /** Extracts the meshes of the view cells and copies them into the mesh.
378                Adds view cell aabb to the aabb of the tree.
379                @param maxPolys the maximal number of objects to be stored as polygons
380        */
381        void Copy2PolygonSoup(const ViewCellContainer &viewCells, PolygonContainer &polys, int maxObjects);
382
383        /** Add this mesh as polygons to polygon container.
384        */
385        void AddMesh2Polygons(Mesh *mesh, PolygonContainer &polys);
386
387        /** A ray is cast possible intersecting the tree.
388                @param the ray that is cast.
389                @returns the number of intersections with objects stored in the tree.
390        */
391        int CastRay(Ray &ray);
392
393        /** Discards or stores polygons in leaf and deletes the container.
394                @param polys the polygons
395                @param leaf the leaf where polygons are stored
396        */
397        bool ProcessPolygons(PolygonContainer *polys, BspLeaf *node);
398
399        /// Pointer to the root of the tree
400        BspNode *mRoot;
401
402        /// Pointer to the root cell of the viewspace
403        // ViewCell *mRootCell;
404               
405        BspTreeStatistics mStat;
406
407        /// local maximal polygons (changes depending on method)
408        int mTermMaxPolygons;
409        int mTermMaxDepth;
410
411        /// Strategies for choosing next split plane.
412        enum {NEXT_POLYGON, LEAST_SPLITS, BALANCED_TREE, COMBINED};
413
414        /// box around the whole view domain
415        AxisAlignedBox3 mBox;
416
417                /// if view cell calculation is incremential
418        bool mIsIncremential;
419
420        /// if polygons should be stored in the tree
421        bool mStorePolys;
422
423public:
424        /// Parses the environment and stores the global BSP tree parameters
425        static void ParseEnvironment();
426
427        /// maximal number of polygons where tree construction is terminated
428        static int sTermMaxPolygons;
429        /// maximal possible depth
430        static int sTermMaxDepth;
431        /// strategy to get the best split plane
432        static int sSplitPlaneStrategy;
433        /// number of candidates evaluated for the next split plane
434        static int sMaxCandidates;
435};
436
437//}; // GtpVisibilityPreprocessor
438
439#endif
Note: See TracBrowser for help on using the repository browser.