source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp @ 264

Revision 264, 24.2 KB checked in by mattausch, 19 years ago (diff)

debugged bsp stuff

Line 
1#include "Plane3.h"
2#include "ViewCellBsp.h"
3#include "Mesh.h"
4#include "common.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "Polygon3.h"
8#include "Ray.h"
9#include "AxisAlignedBox3.h"
10#include <stack>
11#include <time.h>
12#include <iomanip>
13#include "Exporter.h"
14
15#define INITIAL_COST 999999// unreachable high initial cost for heuristic evaluation
16
17int BspTree::sTermMaxPolygons = 10;
18int BspTree::sTermMaxDepth = 20;
19int BspTree::sSplitPlaneStrategy = NEXT_POLYGON;
20int BspTree::sMaxCandidates = 10;
21int BspTree::sConstructionMethod = VIEW_CELLS;
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a balanced tree.
25*/
26int BspTree::sLeastSplitsTable[4] = {0, 0, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for a minimum number splits in the tree.
29*/
30int BspTree::sBalancedTreeTable[4] = {-1, 1, 0, 0};
31
32int counter = 0;
33/****************************************************************/
34/*                  class BspNode implementation                */
35/****************************************************************/
36
37BspNode::BspNode(): mParent(NULL), mPolygons(NULL)
38{
39}
40
41BspNode::BspNode(BspInterior *parent): mParent(parent), mPolygons(NULL)
42{}
43
44BspNode::~BspNode()
45{
46        if (mPolygons)
47        {
48                CLEAR_CONTAINER(*mPolygons);
49                DEL_PTR(mPolygons);
50        }
51}
52bool BspNode::IsRoot() const
53{
54        return mParent == NULL;
55}
56
57BspInterior *BspNode::GetParent()
58{
59        return mParent;
60}
61
62void BspNode::SetParent(BspInterior *parent)
63{
64        mParent = parent;
65}
66
67PolygonContainer *BspNode::GetPolygons()
68{
69        if (!mPolygons)
70                mPolygons = new PolygonContainer();
71
72        return mPolygons;
73}
74
75void BspNode::ProcessPolygons(PolygonContainer *polys, bool storePolys)
76{
77        if (storePolys)
78        {
79                while (!polys->empty())
80                {
81                        GetPolygons()->push_back(polys->back());
82                        polys->pop_back();
83                }
84        }
85        else CLEAR_CONTAINER(*polys);
86
87        delete polys;
88}
89
90
91/****************************************************************/
92/*              class BspInterior implementation                */
93/****************************************************************/
94
95
96BspInterior::BspInterior(const Plane3 &plane):
97mPlane(plane), mFront(NULL), mBack(NULL)
98{}
99
100bool BspInterior::IsLeaf() const
101{
102        return false;
103}
104
105BspNode *BspInterior::GetBack()
106{
107        return mBack;
108}
109
110BspNode *BspInterior::GetFront()
111{
112        return mFront;
113}
114
115Plane3 *BspInterior::GetPlane()
116{
117        return &mPlane;
118}
119
120void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
121{
122        if (mBack == oldChild)
123                mBack = newChild;
124        else
125                mFront = newChild;
126}
127
128void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
129{
130    mBack = b;
131    mFront = f;
132}
133
134void BspInterior::ProcessPolygon(Polygon3 *poly, const bool storePolys)
135{
136        if (storePolys)
137                GetPolygons()->push_back(poly);
138        else
139                delete poly;
140}
141
142bool BspInterior::SplitPolygons(PolygonContainer *polys,
143                                                                PolygonContainer *frontPolys,
144                                                                PolygonContainer *backPolys,
145                                                                int &splits, bool storePolys)
146{
147#ifdef _Debug
148        Debug << "Splitting polygons of node " << this << " with plane " << mPlane << endl;
149#endif
150        bool inside = false;
151
152        while (!polys->empty())
153        {
154                Polygon3 *poly = polys->back();
155                polys->pop_back();
156
157                // test if split is neccessary
158                int result = poly->ClassifyPlane(mPlane);
159
160                Polygon3 *front_piece = NULL;
161                Polygon3 *back_piece = NULL;
162               
163                switch (result)
164                {
165                        case Polygon3::COINCIDENT:
166
167                                if (!inside)
168                                        // same surface normal
169                                        inside = (DotProd(mPlane.mNormal, poly->GetSupportingPlane().mNormal) > 0);
170                                       
171                                //Debug << "coincident" << endl;
172                                // discard polygons or saves them in node
173                                ProcessPolygon(poly, storePolys);
174                                break;
175                        case Polygon3::FRONT_SIDE:
176                                //Debug << "front" << endl;
177                                frontPolys->push_back(poly);
178                                break;
179                        case Polygon3::BACK_SIDE:
180                                inside = true;
181                                //Debug << "back" << endl;
182                                backPolys->push_back(poly);
183                                break;
184                        case Polygon3::SPLIT:
185                                inside = true;
186                                //Debug << "split" << endl;
187
188                                front_piece = new Polygon3();
189                                back_piece = new Polygon3();
190
191                                //-- split polygon
192                                poly->Split(&mPlane, front_piece, back_piece, splits);
193
194                                frontPolys->push_back(front_piece);
195                                backPolys->push_back(back_piece);
196
197#ifdef _DEBUG
198                                Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
199#endif
200                                // save or discard polygons
201                                ProcessPolygon(poly, storePolys);
202                               
203                                break;
204                        default:
205                Debug << "SHOULD NEVER COME HERE\n";
206                                break;
207                }
208        }
209
210        // contains nothing
211        delete polys;
212
213        return inside;
214}
215
216/****************************************************************/
217/*                  class BspLeaf implementation                */
218/****************************************************************/
219BspLeaf::BspLeaf(): mViewCell(NULL)
220{
221}
222
223BspLeaf::BspLeaf(ViewCell *viewCell): mViewCell(viewCell)
224{
225}
226
227BspLeaf::BspLeaf(BspInterior *parent): BspNode(parent), mViewCell(NULL)
228{}
229
230BspLeaf::BspLeaf(BspInterior *parent, ViewCell *viewCell):
231BspNode(parent), mViewCell(viewCell)
232{
233}
234ViewCell *BspLeaf::GetViewCell()
235{
236        return mViewCell;
237}
238
239void BspLeaf::SetViewCell(ViewCell *viewCell)
240{
241        mViewCell = viewCell;
242}
243
244bool BspLeaf::IsLeaf() const
245{
246        return true;
247}
248
249/****************************************************************/
250/*                  class BspTree implementation                */
251/****************************************************************/
252
253BspTree::BspTree():
254mTermMaxPolygons(0),
255mTermMaxDepth(0),
256mRoot(NULL),
257mIsIncremential(false),
258mStorePolys(false)
259{
260        Randomize(); // initialise random generator for heuristics
261}
262 
263const BspTreeStatistics &BspTree::GetStatistics() const
264{
265        return mStat;
266}
267
268void BspTreeStatistics::Print(ostream &app) const
269{
270        app << "===== BspTree statistics ===============\n";
271
272        app << setprecision(4);
273
274        app << "#N_RAYS Number of rays )\n"
275                << rays << endl;
276        app << "#N_DOMAINS  ( Number of query domains )\n"
277                << queryDomains <<endl;
278
279        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
280
281        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
282
283        app << "#N_SPLITS ( Number of splits)\n" << splits << "\n";
284
285        app << "#N_RAYREFS ( Number of rayRefs )\n" <<
286        rayRefs << "\n";
287
288        app << "#N_RAYRAYREFS  ( Number of rayRefs / ray )\n" <<
289        rayRefs/(double)rays << "\n";
290
291        app << "#N_LEAFRAYREFS  ( Number of rayRefs / leaf )\n" <<
292        rayRefs/(double)Leaves() << "\n";
293
294        app << "#N_MAXOBJECTREFS  ( Max number of rayRefs / leaf )\n" <<
295        maxObjectRefs << "\n";
296
297        app << "#N_NONEMPTYRAYREFS  ( Number of rayRefs in nonEmpty leaves / non empty leaf )\n" <<
298        rayRefsNonZeroQuery/(double)(Leaves() - zeroQueryNodes) << "\n";
299
300        app << "#N_LEAFDOMAINREFS  ( Number of query domain Refs / leaf )\n" <<
301        objectRefs/(double)Leaves() << "\n";
302
303        app << "#N_PEMPTYLEAVES  ( Percentage of leaves with zero query domains )\n"<<
304        zeroQueryNodes*100/(double)Leaves() << endl;
305
306        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maxdepth )\n"<<
307        maxDepthNodes * 100 / (double)Leaves() << endl;
308
309        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth <<endl;
310
311        app << "#N_ADDED_RAYREFS  (Number of dynamically added ray references )\n"<<
312        addedRayRefs<<endl;
313
314        app << "#N_REMOVED_RAYREFS  (Number of dynamically removed ray references )\n"<<
315        removedRayRefs<<endl;
316
317        //  app << setprecision(4);
318
319        //  app << "#N_CTIME  ( Construction time [s] )\n"
320        //      << Time() << " \n";
321
322        app << "===== END OF BspTree statistics ==========\n";
323}
324
325BspTree::~BspTree()
326{
327        std::stack<BspNode *> tStack;
328
329        tStack.push(mRoot);
330
331        while (!tStack.empty())
332        {
333                BspNode *node = tStack.top();
334
335            tStack.pop();
336       
337                if (!node->IsLeaf())
338                {
339                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
340
341                        // push the children on the stack (there are always two children)
342                        tStack.push(interior->GetBack());
343                        tStack.push(interior->GetFront());
344                }
345
346                DEL_PTR(node);
347        }
348}
349
350
351void BspTree::InsertViewCell(ViewCell *viewCell)
352{       
353        std::stack<BspTraversalData> tStack;
354       
355        PolygonContainer *polys = new PolygonContainer();
356
357        // extract polygons that guide the split process
358        AddMesh2Polygons(viewCell->GetMesh(), *polys);
359        mBox.Include(viewCell->GetBox()); // add to BSP aabb
360
361         // traverse tree or create new one
362        BspNode *firstNode = mRoot ? mRoot : new BspLeaf();
363
364        tStack.push(BspTraversalData(firstNode, polys, 0, true));
365
366        while (!tStack.empty())
367        {
368                // filter polygons donw the tree
369                BspTraversalData tData = tStack.top();
370            tStack.pop();
371                       
372                if (!tData.mNode->IsLeaf())
373                {
374                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
375
376                        //-- filter view cell polygons down the tree until a leaf is reached
377                        if ((int)tData.mPolygons->size() > 0)
378                        {
379                                PolygonContainer *frontPolys = new PolygonContainer();
380                                PolygonContainer *backPolys = new PolygonContainer();
381
382                                int splits = 0;
383               
384                                // split viecell polygons with respect to split plane
385                                bool inside = interior->SplitPolygons(tData.mPolygons, frontPolys, backPolys, splits, mStorePolys);
386                                //Debug << "Reached level " << tData.mDepth << " bk: " << backPolys->size() << " frnt: " << frontPolys->size() << endl;
387                                mStat.splits += splits;
388
389                                // push the children on the stack
390                                tStack.push(BspTraversalData(interior->GetFront(), frontPolys, tData.mDepth + 1, false));
391                                tStack.push(BspTraversalData(interior->GetBack(), backPolys, tData.mDepth + 1, inside));
392                       
393                        }
394                        else // stop traversal
395                        {
396                                DEL_PTR(tData.mPolygons);
397                        }
398                }
399                else // reached leaf => subdivide current viewcell
400                {
401                        BspNode *root = Subdivide(tStack, tData, viewCell);             
402
403            // tree empty => new root
404                        if (!mRoot)
405                                mRoot = root;
406                }
407        }
408        Debug << "ended traversal" << endl; Debug.flush();
409}
410
411void BspTree::InitTree(int maxPolygons, int maxDepth)
412{
413        mTermMaxPolygons = maxPolygons;
414        mTermMaxDepth = maxDepth;
415        mStat.nodes = 1;
416       
417        mBox.Initialize();      // initialise bsp tree bounding box
418}
419
420
421
422void BspTree::AddMesh2Polygons(Mesh *mesh, PolygonContainer &polys)
423{
424        FaceContainer::const_iterator fi;
425       
426        // copy the face data to polygons
427        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
428        {
429                Polygon3 *poly = new Polygon3((*fi), mesh);
430                polys.push_back(poly);
431        }
432}
433
434void BspTree::Copy2PolygonSoup(const ViewCellContainer &viewCells, PolygonContainer &polys, int maxObjects)
435{
436        int limit = (maxObjects > 0) ? Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
437 
438        for (int i = 0; i < limit; ++i)
439        {
440                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
441                {
442                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
443                        AddMesh2Polygons(viewCells[i]->GetMesh(), polys);
444                }
445        }
446}
447
448void BspTree::Copy2PolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects)
449{
450        int limit = (maxObjects > 0) ? Min((int)objects.size(), maxObjects) : (int)objects.size();
451 
452        for (int i = 0; i < limit; ++i)
453        {
454                Intersectable *object = objects[i];//*it;
455                Mesh *mesh = NULL;
456
457                switch (object->Type()) // extract the meshes
458                {
459                case Intersectable::MESH_INSTANCE:
460                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
461                        break;
462                case Intersectable::VIEWCELL:
463                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
464                        break;
465                        // TODO: handle transformed mesh instances
466                default:
467                        break;
468                }
469               
470        if (mesh) // copy the mesh data to polygons
471                {
472                        mBox.Include(object->GetBox()); // add to BSP tree aabb
473                        AddMesh2Polygons(mesh, polys);
474                }
475        }
476
477        Debug << "Number of polygons: " << (int)polys.size() << ", BSP root box: " << mBox << endl;
478}
479
480void BspTree::Construct(const ViewCellContainer &viewCells)
481{
482        //-- Construct tree using the given viewcells
483       
484        /* for this type of construction we filter all viewcells down the
485         * tree. If there is no polygon left, the last split plane
486         * decides inside or outside of the viewcell.
487    */
488        InitTree(sTermMaxPolygons, sTermMaxDepth);
489
490    bool savedStorePolys = mStorePolys;
491
492        // tree is completely constructed once before
493        // view cells are inserted one after another =>
494        // global tree optimization possible
495        if (!mIsIncremential)
496        {
497                // copy view cell meshes into one big polygon soup
498                PolygonContainer *polys = new PolygonContainer();
499                Copy2PolygonSoup(viewCells, *polys, sMaxCandidates);
500
501                // polygons are stored only during view cell insertion
502                mStorePolys = false;
503
504                // construct tree from viewcell polygons
505                Construct(polys);
506                //Export("bsp.x3d");
507        }
508       
509        //-- insert all viewcells
510        ViewCellContainer::const_iterator it;
511
512        mStorePolys = savedStorePolys;
513
514        counter = 0;
515
516        Debug << "\n**** Started view cells insertion ****\n\n";
517        for (it = viewCells.begin(); it != viewCells.end(); ++ it)
518        {
519                Debug << "*** Inserting view cell " << counter << " ***" << endl;
520                InsertViewCell(*it);
521                counter ++;
522        }
523        Debug << "**** finished view cells insertion ****" << endl; Debug.flush();
524}
525
526
527void BspTree::Construct(const ObjectContainer &objects, ViewCellContainer *viewCells)
528{
529        // take termination criteria from globals
530        InitTree(sTermMaxPolygons, sTermMaxDepth);
531       
532        PolygonContainer *polys = new PolygonContainer();
533       
534        // copy mesh instance polygons into one big polygon soup
535        Copy2PolygonSoup(objects, *polys, sMaxCandidates);
536
537        // construct tree from polygon soup
538        Construct(polys);
539
540        // TODO: generate view cells
541}
542
543void BspTree::Construct(const RayContainer &rays, ViewCellContainer *viewCells)
544{
545        // TODO
546}
547
548void BspTree::Construct(PolygonContainer *polys)
549{
550        std::stack<BspTraversalData> tStack;
551       
552        BspTraversalData tData(new BspLeaf(), polys, 0, true);
553
554        tStack.push(tData);
555
556        Debug << "**** Contructing tree using objects ****\n";
557        while (!tStack.empty())
558        {
559                tData = tStack.top();
560            tStack.pop();
561       
562                // subdivide leaf node
563                BspNode *root = Subdivide(tStack, tData);
564
565                // empty tree => new root corresponding to unbounded space
566                if (!mRoot)
567                        mRoot = root;
568        }
569
570        Debug << "**** tree construction finished ****\n";
571}
572
573
574BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData,
575                                                        ViewCell *viewCell)
576{
577        //-- terminate traversal 
578        if (((tData.mPolygons->size() <= mTermMaxPolygons) || (tData.mDepth >= mTermMaxDepth))
579                // if there is another view cell associated with this leaf => subdivide further
580                && !(viewCell && tData.mIsInside && dynamic_cast<BspLeaf *>(tData.mNode)->GetViewCell()))
581        {
582#ifdef _DEBUG
583        Debug << "terminate subdivision, size " << (int)tData.mPolygons->size() << ", depth " << tData.mDepth << endl;
584#endif
585
586                EvaluateLeafStats(tData);
587
588            // add view cell if inside object)
589                if (viewCell && tData.mIsInside)
590                        // || (tData.mGeometry->size() > 0) // or if there is still geometry left
591                {
592                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
593
594#ifdef _DEBUG
595                        if (leaf->GetViewCell())
596                                Debug << "ERROR: leaf already has view cell" << endl;
597
598                        Debug << "**** Inserted view cell ****" << endl;
599#endif
600                        leaf->SetViewCell(viewCell);
601                }
602
603                // add or delete remaining polygons
604                tData.mNode->ProcessPolygons(tData.mPolygons, mStorePolys);
605
606                return tData.mNode;
607        }
608
609        //-- create new subdivided node
610        PolygonContainer *backPolys = new PolygonContainer();
611        PolygonContainer *frontPolys = new PolygonContainer();
612
613        bool inside = false;
614
615        BspInterior *interior = SubdivideNode(dynamic_cast<BspLeaf *>(tData.mNode),
616                                                                                  tData.mPolygons,
617                                                                                  frontPolys,
618                                                                                  backPolys, inside);
619
620        // push the children on the stack (there are always two children)
621        tStack.push(BspTraversalData(interior->GetBack(), backPolys, tData.mDepth + 1, inside));
622        tStack.push(BspTraversalData(interior->GetFront(), frontPolys, tData.mDepth + 1, false));
623
624        return interior;
625}
626
627
628BspInterior *BspTree::SubdivideNode(BspLeaf *leaf,
629                                                                        PolygonContainer *polys,
630                                                                        PolygonContainer *frontPolys,
631                                                                        PolygonContainer *backPolys, bool &inside)
632{
633        mStat.nodes += 2;
634
635        // add the new nodes to the tree + select subdivision plane
636        BspInterior *interior = new BspInterior(SelectPlane(polys));
637
638#ifdef _DEBUG
639        Debug << interior << endl;
640#endif
641
642        // split polygon according to current plane
643        int splits = 0;
644               
645        inside = interior->SplitPolygons(polys, frontPolys, backPolys, splits, mStorePolys);
646       
647        mStat.splits += splits;
648
649        BspInterior *parent = leaf->GetParent();
650
651        // replace a link from node's parent
652        if (parent)
653        {
654                parent->ReplaceChildLink(leaf, interior);
655                interior->SetParent(parent);
656        }
657
658        // and setup child links
659        interior->SetupChildLinks(new BspLeaf(interior, leaf->mViewCell), new BspLeaf(interior));
660       
661        delete leaf; // leaf not member of tree anymore
662
663        return interior;
664}
665
666Plane3 BspTree::SelectPlane(PolygonContainer *polys)  const
667{
668        if (polys->size() == 0)
669        {
670                Debug << "Warning: No split candidate available\n";
671                return Plane3();
672        }
673
674        // simple strategy: just take next polygon
675        if (sSplitPlaneStrategy == NEXT_POLYGON)
676        {
677                return polys->front()->GetSupportingPlane();
678        }
679       
680        // use heuristics to find appropriate plane
681        return SelectPlaneHeuristics(polys, sMaxCandidates);
682}
683
684Plane3 BspTree::SelectPlaneHeuristics(PolygonContainer *polygons, int maxTests) const
685{
686        int lowestCost = INITIAL_COST;
687        Plane3 *bestPlane = NULL;
688       
689        int limit = Min((int)polygons->size(), maxTests);
690
691        for (int i = 0; i < limit; ++i)
692        {
693                int candidateIdx = Random((int)polygons->size());
694                Plane3 candidatePlane = (*polygons)[candidateIdx]->GetSupportingPlane();
695               
696                // evaluate current candidate
697                int candidateCost = EvalSplitPlane(polygons, candidatePlane);
698                       
699                if (candidateCost < lowestCost)
700                {
701                        bestPlane = &candidatePlane;
702                        lowestCost = candidateCost;
703                        //Debug << "new plane cost " << lowestCost << endl;
704                }
705        }
706               
707        return *bestPlane;
708}
709
710int BspTree::EvalSplitPlane(PolygonContainer *polygons, const Plane3 &candidatePlane) const
711{
712        PolygonContainer::const_iterator it;
713
714        int sum = 0, sum2 = 0;
715
716        for (it = polygons->begin(); it < polygons->end(); ++ it)
717        {
718                int classification = (*it)->ClassifyPlane(candidatePlane);
719               
720                if ((sSplitPlaneStrategy == COMBINED) || (sSplitPlaneStrategy == BALANCED_TREE))
721                {
722                        sum += sBalancedTreeTable[classification];
723                }
724               
725                if ((sSplitPlaneStrategy == COMBINED) ||(sSplitPlaneStrategy == LEAST_SPLITS))
726                {
727                        sum2 += sLeastSplitsTable[classification];
728                }
729        }
730
731        // return linear combination of both sums
732        return abs(sum) + abs(sum2);
733}
734
735void BspTree::ParseEnvironment()
736{
737        environment->GetIntValue("BspTree.Termination.maxDepth", sTermMaxDepth);
738        environment->GetIntValue("BspTree.Termination.maxPolygons", sTermMaxPolygons);
739        environment->GetIntValue("BspTree.maxCandidates", sMaxCandidates);
740
741        //-- extract strategy to choose the next split plane
742        char splitPlaneStrategyStr[60];
743
744        environment->GetStringValue("BspTree.splitPlaneStrategy", splitPlaneStrategyStr);
745       
746        sSplitPlaneStrategy = BspTree::NEXT_POLYGON;
747       
748        if (strcmp(splitPlaneStrategyStr, "nextPolygon") == 0)
749                sSplitPlaneStrategy = BspTree::NEXT_POLYGON;
750        else if (strcmp(splitPlaneStrategyStr, "leastSplits") == 0)
751                sSplitPlaneStrategy = BspTree::LEAST_SPLITS;
752        else if (strcmp(splitPlaneStrategyStr, "balancedTree") == 0)
753                sSplitPlaneStrategy = BspTree::BALANCED_TREE;
754        else
755        {
756                cerr << "Wrong BSP split plane strategy " << splitPlaneStrategyStr << endl;
757                exit(1);
758    }
759
760        //-- parse BSP tree construction method
761        char constructionMethodStr[64];
762       
763        environment->GetStringValue("BspTree.constructionMethod", constructionMethodStr);
764
765        sConstructionMethod = BspTree::VIEW_CELLS;
766       
767        if (strcmp(constructionMethodStr, "viewCells") == 0)
768                sConstructionMethod = BspTree::VIEW_CELLS;
769        else if (strcmp(constructionMethodStr, "sceneGeometry") == 0)
770                sConstructionMethod = BspTree::SCENE_GEOMETRY;
771        else if (strcmp(constructionMethodStr, "rays") == 0)
772                sConstructionMethod = BspTree::RAYS;
773        else
774        {
775                cerr << "Wrong bsp construction method " << constructionMethodStr << endl;
776                exit(1);
777    }
778
779}
780
781void BspTree::CollectLeaves(vector<BspLeaf *> &leaves)
782{
783        stack<BspNode *> nodeStack;
784        nodeStack.push(mRoot);
785 
786        while (!nodeStack.empty())
787        {
788                BspNode *node = nodeStack.top();
789   
790                nodeStack.pop();
791   
792                if (node->IsLeaf())
793                {
794                        BspLeaf *leaf = (BspLeaf *)node;
795                       
796                        leaves.push_back(leaf);
797                } else
798                {
799                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
800                        nodeStack.push(interior->GetBack());
801                        nodeStack.push(interior->GetFront());
802                }
803        }
804}
805
806int BspTree::CollectLeafPvs()
807{
808        int totalPvsSize = 0;
809 
810        stack<BspNode *> nodeStack;
811 
812        nodeStack.push(mRoot);
813 
814        while (!nodeStack.empty())
815        {
816                BspNode *node = nodeStack.top();
817               
818                nodeStack.pop();
819               
820                if (node->IsLeaf())
821                {
822                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
823
824                        ViewCell *viewcell = leaf->GetViewCell();
825                       
826                        if (!viewcell->Mailed())
827                        {
828                                viewcell->Mail(); // what does mail mean?
829                                       
830                                // add this node to pvs of all nodes it can see
831                                BspPvsMap::iterator ni;
832         
833        /*                      for (ni = object->mBspPvs.mEntries.begin(); ni != object->mKdPvs.mEntries.end(); ni++)
834                                {
835                                        BspNode *node = (*ni).first;
836           
837                                        // $$ JB TEMPORARY solution -> should add object PVS or explictly computed
838                                        // BSP tree PVS
839                                if (leaf->mBspPvs.AddNodeSample(node))
840                                                totalPvsSize++;
841                                }*/
842                        }
843                } else
844                {
845                        // traverse tree
846                        BspInterior *interior = (BspInterior *)node;
847     
848                        nodeStack.push(interior->GetFront());
849                        nodeStack.push(interior->GetBack());
850                }
851        }
852
853        return totalPvsSize;
854}
855
856AxisAlignedBox3 BspTree::GetBoundingBox() const
857{
858        return mBox;
859}
860
861BspNode *BspTree::GetRoot() const
862{
863        return mRoot;
864}
865
866bool BspTree::StorePolys() const
867{
868        return mStorePolys;
869}
870
871void BspTree::EvaluateLeafStats(const BspTraversalData &data)
872{
873        // the node became a leaf -> evaluate stats for leafs
874        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
875
876        if (data.mDepth >= mTermMaxDepth)
877        {
878                ++ mStat.maxDepthNodes;
879        }
880
881        // store maximal depth
882        if (data.mDepth > mStat.maxDepth)
883                mStat.maxDepth = data.mDepth;
884
885#ifdef _DEBUG
886        Debug << "BSP Traversal data. Depth: " << data.mDepth << " (max: " << mTermMaxDepth<< "), #polygons: " <<
887          data.mPolygons->size() << " (max: " << mTermMaxPolygons << ")" << endl;
888#endif
889}
890
891int BspTree::CastRay(Ray &ray)
892{
893        int hits = 0;
894 
895        stack<BspRayTraversalData> tStack;
896 
897        float maxt = 1e6;
898        float mint = 0;
899
900        Intersectable::NewMail();
901
902        // test with tree bounding box
903        if (!mBox.GetMinMaxT(ray, &mint, &maxt))
904                return 0;
905
906        if (mint < 0)
907                mint = 0;
908 
909        maxt += Limits::Threshold;
910 
911        Vector3 entp = ray.Extrap(mint);
912        Vector3 extp = ray.Extrap(maxt);
913 
914        BspNode *node = mRoot;
915        BspNode *farChild;
916       
917        while (1)
918        {
919                if (!node->IsLeaf())
920                {
921                        BspInterior *in = (BspInterior *) node;
922                       
923                        Plane3 *splitPlane = in->GetPlane();
924
925                        float t = 0;
926                        bool coplanar = false;
927               
928                        int entSide = splitPlane->Side(entp);
929                        int extSide = splitPlane->Side(extp);
930
931                        Vector3 intersection;
932
933                        if (entSide < 0)
934                        {
935                                node = in->GetBack();
936
937                                if(extSide <= 0)
938                                        continue;
939                                       
940                                farChild = in->GetFront(); // plane splits ray
941
942                        } else if (entSide > 0)
943                        {
944                                node = in->GetFront();
945
946                                if (extSide >= 0)
947                                        continue;
948
949                                farChild = in->GetBack();        // plane splits ray                   
950                        }
951                        else // ray and plane are coincident // WHAT TO DO IN THIS CASE ?
952                        {
953                                node = in->GetFront();
954                                continue;
955                        }
956
957                        //-- split
958
959                        // push data for far child
960                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
961
962                        // find intersection with plane between ray origin and exit point
963                        extp = splitPlane->FindIntersection(ray.GetLoc(), extp, &maxt);
964
965                } else // compute intersections with objects in leaf
966                {
967                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
968                        //ray.leaves.push_back(leaf);
969      // TODO
970                        /*ObjectContainer::const_iterator mi;
971                        for (mi = leaf->mObjects.begin(); mi != leaf->mObjects.end(); ++mi)
972                        {
973                                Intersectable *object = *mi;
974                                if (!object->Mailed())
975                                {
976                                        object->Mail();
977                                        //ray.meshes.push_back(mesh);
978                                        hits += object->CastRay(ray);
979                                }
980                        }*/
981
982                        if (hits && ray.GetType() == Ray::LOCAL_RAY)
983                                if (ray.intersections[0].mT <= maxt)
984                                        break;
985     
986                        // get the next node from the stack
987                        if (tStack.empty())
988                                break;
989     
990                        entp = extp;
991                        mint = maxt;
992                        BspRayTraversalData &s  = tStack.top();
993
994                        node = s.mNode;
995                        extp = s.mExitPoint;
996                        maxt = s.mMaxT;
997
998                        tStack.pop();
999                }
1000        }
1001
1002        return hits;
1003}
1004
1005bool BspTree::Export(const string filename)
1006{
1007        Exporter *exporter = Exporter::GetExporter(filename);
1008
1009        if (exporter)
1010        {
1011                exporter->ExportBspTree(*this);
1012                delete exporter;
1013
1014                return true;
1015        }       
1016
1017        return false;
1018}
1019//} // GtpVisibilityPreprocessor
Note: See TracBrowser for help on using the repository browser.