source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp @ 675

Revision 675, 77.3 KB checked in by mattausch, 18 years ago (diff)
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 "Triangle3.h"
11#include "Tetrahedron3.h"
12#include "ViewCellsManager.h"
13#include "Exporter.h"
14#include "Plane3.h"
15#include <stack>
16
17
18
19//-- static members
20
21int BspNode::sMailId = 1;
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number splits in the tree.
25*/
26const float BspTree::sLeastPolySplitsTable[] = {0, 0, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for a balanced tree.
29*/
30const float BspTree::sBalancedPolysTable[] = {1, -1, 0, 0};
31
32/** Evaluates split plane classification with respect to the plane's
33        contribution for a minimum number of ray splits.
34*/
35const float BspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
36/** Evaluates split plane classification with respect to the plane's
37        contribution for balanced rays.
38*/
39const float BspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
40
41int BspTree::sFrontId = 0;
42int BspTree::sBackId = 0;
43int BspTree::sFrontAndBackId = 0;
44
45
46/****************************************************************/
47/*                  class BspNode implementation                */
48/****************************************************************/
49
50
51BspNode::BspNode():
52mParent(NULL), mTreeValid(true), mTimeStamp(0)
53{}
54
55
56BspNode::BspNode(BspInterior *parent):
57mParent(parent), mTreeValid(true)
58{}
59
60
61bool BspNode::IsRoot() const
62{
63        return mParent == NULL;
64}
65
66
67BspInterior *BspNode::GetParent()
68{
69        return mParent;
70}
71
72
73void BspNode::SetParent(BspInterior *parent)
74{
75        mParent = parent;
76}
77
78
79bool BspNode::IsSibling(BspNode *n) const
80{
81        return  ((this != n) && mParent &&
82                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
83}
84
85
86int BspNode::GetDepth() const
87{
88        int depth = 0;
89        BspNode *p = mParent;
90       
91        while (p)
92        {
93                p = p->mParent;
94                ++ depth;
95        }
96
97        return depth;
98}
99
100
101bool BspNode::TreeValid() const
102{
103        return mTreeValid;
104}
105
106
107void BspNode::SetTreeValid(const bool v)
108{
109        mTreeValid = v;
110}
111
112
113/****************************************************************/
114/*              class BspInterior implementation                */
115/****************************************************************/
116
117
118BspInterior::BspInterior(const Plane3 &plane):
119mPlane(plane), mFront(NULL), mBack(NULL)
120{}
121
122BspInterior::~BspInterior()
123{
124        DEL_PTR(mFront);
125        DEL_PTR(mBack);
126}
127
128bool BspInterior::IsLeaf() const
129{
130        return false;
131}
132
133BspNode *BspInterior::GetBack()
134{
135        return mBack;
136}
137
138BspNode *BspInterior::GetFront()
139{
140        return mFront;
141}
142
143Plane3 BspInterior::GetPlane() const
144{
145        return mPlane;
146}
147
148void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
149{
150        if (mBack == oldChild)
151                mBack = newChild;
152        else
153                mFront = newChild;
154}
155
156void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
157{
158    mBack = b;
159    mFront = f;
160}
161
162/****************************************************************/
163/*                  class BspLeaf implementation                */
164/****************************************************************/
165
166
167BspLeaf::BspLeaf(): mViewCell(NULL), mPvs(NULL)
168{
169}
170
171
172BspLeaf::~BspLeaf()
173{
174        DEL_PTR(mPvs);
175}
176
177
178BspLeaf::BspLeaf(ViewCell *viewCell):
179mViewCell(viewCell)
180{
181}
182
183
184BspLeaf::BspLeaf(BspInterior *parent):
185BspNode(parent), mViewCell(NULL), mPvs(NULL)
186{}
187
188
189
190BspLeaf::BspLeaf(BspInterior *parent, ViewCell *viewCell):
191BspNode(parent), mViewCell(viewCell), mPvs(NULL)
192{
193}
194
195ViewCell *BspLeaf::GetViewCell() const
196{
197        return mViewCell;
198}
199
200void BspLeaf::SetViewCell(ViewCell *viewCell)
201{
202        mViewCell = viewCell;
203}
204
205
206bool BspLeaf::IsLeaf() const
207{
208        return true;
209}
210
211
212/*********************************************************************/
213/*                       class BspTree implementation                */
214/*********************************************************************/
215
216BspTree::BspTree(): 
217mRoot(NULL),
218mUseAreaForPvs(false),
219mGenerateViewCells(true),
220mTimeStamp(1)
221{
222        Randomize(); // initialise random generator for heuristics
223
224        mOutOfBoundsCell = GetOrCreateOutOfBoundsCell();
225
226        //-- termination criteria for autopartition
227        environment->GetIntValue("BspTree.Termination.maxDepth", mTermMaxDepth);
228        environment->GetIntValue("BspTree.Termination.minPvs", mTermMinPvs);
229        environment->GetIntValue("BspTree.Termination.minPolygons", mTermMinPolys);
230        environment->GetIntValue("BspTree.Termination.minRays", mTermMinRays);
231        environment->GetFloatValue("BspTree.Termination.minProbability", mTermMinProbability); 
232        environment->GetFloatValue("BspTree.Termination.maxRayContribution", mTermMaxRayContribution);
233        environment->GetFloatValue("BspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
234
235        //-- factors for bsp tree split plane heuristics
236        environment->GetFloatValue("BspTree.Factor.verticalSplits", mVerticalSplitsFactor);
237        environment->GetFloatValue("BspTree.Factor.largestPolyArea", mLargestPolyAreaFactor);
238        environment->GetFloatValue("BspTree.Factor.blockedRays", mBlockedRaysFactor);
239        environment->GetFloatValue("BspTree.Factor.leastRaySplits", mLeastRaySplitsFactor);
240        environment->GetFloatValue("BspTree.Factor.balancedRays", mBalancedRaysFactor);
241        environment->GetFloatValue("BspTree.Factor.pvs", mPvsFactor);
242        environment->GetFloatValue("BspTree.Factor.leastSplits" , mLeastSplitsFactor);
243        environment->GetFloatValue("BspTree.Factor.balancedPolys", mBalancedPolysFactor);
244        environment->GetFloatValue("BspTree.Factor.balancedViewCells", mBalancedViewCellsFactor);
245        environment->GetFloatValue("BspTree.Termination.ct_div_ci", mCtDivCi);
246
247        //-- termination criteria for axis aligned split
248        environment->GetFloatValue("BspTree.Termination.AxisAligned.ct_div_ci", mAxisAlignedCtDivCi);
249        environment->GetFloatValue("BspTree.Termination.maxCostRatio", mMaxCostRatio);
250        environment->GetIntValue("BspTree.Termination.AxisAligned.minPolys",
251                                                         mTermMinPolysForAxisAligned);
252        environment->GetIntValue("BspTree.Termination.AxisAligned.minRays",
253                                                         mTermMinRaysForAxisAligned);
254        environment->GetIntValue("BspTree.Termination.AxisAligned.minObjects",
255                                                         mTermMinObjectsForAxisAligned);
256        //-- partition criteria
257        environment->GetIntValue("BspTree.maxPolyCandidates", mMaxPolyCandidates);
258        environment->GetIntValue("BspTree.maxRayCandidates", mMaxRayCandidates);
259        environment->GetIntValue("BspTree.splitPlaneStrategy", mSplitPlaneStrategy);
260        environment->GetFloatValue("BspTree.AxisAligned.splitBorder", mSplitBorder);
261        environment->GetIntValue("BspTree.maxTests", mMaxTests);
262        environment->GetIntValue("BspTree.Termination.maxViewCells", mMaxViewCells);
263
264        environment->GetFloatValue("BspTree.Construction.epsilon", mEpsilon);
265
266        char subdivisionStatsLog[100];
267        environment->GetStringValue("BspTree.subdivisionStats", subdivisionStatsLog);
268        mSubdivisionStats.open(subdivisionStatsLog);
269
270    Debug << "BSP max depth: " << mTermMaxDepth << endl;
271        Debug << "BSP min PVS: " << mTermMinPvs << endl;
272        Debug << "BSP min probability: " << mTermMinProbability << endl;
273        Debug << "BSP max polys: " << mTermMinPolys << endl;
274        Debug << "BSP max rays: " << mTermMinRays << endl;
275        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
276        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
277
278        Debug << "Split plane strategy: ";
279        if (mSplitPlaneStrategy & RANDOM_POLYGON)
280                Debug << "random polygon ";
281        if (mSplitPlaneStrategy & AXIS_ALIGNED)
282                Debug << "axis aligned ";
283        if (mSplitPlaneStrategy & LEAST_SPLITS)     
284                Debug << "least splits ";
285        if (mSplitPlaneStrategy & BALANCED_POLYS)
286                Debug << "balanced polygons ";
287        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
288                Debug << "balanced view cells ";
289        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
290                Debug << "largest polygon area ";
291        if (mSplitPlaneStrategy & VERTICAL_AXIS)
292                Debug << "vertical axis ";
293        if (mSplitPlaneStrategy & BLOCKED_RAYS)
294                Debug << "blocked rays ";
295        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
296                Debug << "least ray splits ";
297        if (mSplitPlaneStrategy & BALANCED_RAYS)
298                Debug << "balanced rays ";
299        if (mSplitPlaneStrategy & PVS)
300                Debug << "pvs";
301
302        Debug << endl;
303}
304
305
306const BspTreeStatistics &BspTree::GetStatistics() const
307{
308        return mStat;
309}
310
311
312int BspTree::SplitPolygons(const Plane3 &plane,
313                                                   PolygonContainer &polys,
314                                                   PolygonContainer &frontPolys,
315                                                   PolygonContainer &backPolys,
316                                                   PolygonContainer &coincident) const
317{
318        int splits = 0;
319
320#ifdef _Debug
321        Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
322#endif
323
324        PolygonContainer::const_iterator it, it_end = polys.end();
325
326        for (it = polys.begin(); it != polys.end(); ++ it)     
327        {
328                Polygon3 *poly = *it;
329       
330                //-- classify polygon
331                const int cf = poly->ClassifyPlane(plane, mEpsilon);
332
333                switch (cf)
334                {
335                        case Polygon3::COINCIDENT:
336                                coincident.push_back(poly);
337                                break;                 
338                        case Polygon3::FRONT_SIDE:     
339                                frontPolys.push_back(poly);
340                                break;
341                        case Polygon3::BACK_SIDE:
342                                backPolys.push_back(poly);
343                                break;
344                        case Polygon3::SPLIT:
345                                {
346                                        Polygon3 *front_piece = new Polygon3(poly->mParent);
347                                        Polygon3 *back_piece = new Polygon3(poly->mParent);
348
349                                        //-- split polygon into front and back part
350                                        poly->Split(plane,
351                                                                *front_piece,
352                                                                *back_piece,
353                                                                mEpsilon);
354                                       
355                                        ++ splits; // increase number of splits
356
357                                        //-- inherit rays from parent polygon for blocked ray criterium
358                                        poly->InheritRays(*front_piece, *back_piece);
359                               
360                                        // check if polygons still valid
361                                        if (front_piece->Valid(mEpsilon))
362                                                frontPolys.push_back(front_piece);
363                                        else
364                                                DEL_PTR(front_piece);
365                               
366                                        if (back_piece->Valid(mEpsilon))
367                                                backPolys.push_back(back_piece);
368                                        else                           
369                                                DEL_PTR(back_piece);
370                               
371#ifdef _DEBUG
372                                        Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
373#endif
374                                        DEL_PTR(poly);
375                                }
376                                break;
377                        default:
378                Debug << "SHOULD NEVER COME HERE\n";
379                                break;
380                }
381        }
382
383        return splits;
384}
385
386
387void BspTreeStatistics::Print(ostream &app) const
388{
389        app << "===== BspTree statistics ===============\n";
390
391        app << setprecision(4);
392
393        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
394
395        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
396
397        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
398
399        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
400
401        app << "#N_POLYSPLITS ( Number of polygon splits )\n" << polySplits << "\n";
402
403        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits[0] + splits[1] + splits[2] << endl;
404
405        app << "#N_SPLITS ( Number of splits in axes x y z)\n";
406
407        for (int i = 0; i < 3; ++ i)
408                app << splits[i] << " ";
409        app << endl;
410
411        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
412                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
413
414        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
415                << minPvsNodes * 100 / (double)Leaves() << endl;
416
417        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
418                << minRaysNodes * 100 / (double)Leaves() << endl;
419
420        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
421                << maxCostNodes * 100 / (double)Leaves() << endl;
422
423        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
424                << minProbabilityNodes * 100 / (double)Leaves() << endl;
425
426        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
427                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
428
429        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
430
431        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
432
433        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
434
435        app << "#N_INPUTPOLYGONS (number of input polygons )\n" << polys << endl;
436
437        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
438
439        app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
440        //app << "#N_PVS: " << pvs << endl;
441
442        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
443                 (polys + polySplits) / (double)polys << endl;
444       
445        app << "===== END OF BspTree statistics ==========\n";
446}
447
448
449BspTree::~BspTree()
450{
451        DEL_PTR(mRoot);
452
453        // TODO must be deleted if used!!
454        //if (mGenerateViewCells) DEL_PTR(mOutOfBoundsCell);
455}
456
457BspViewCell *BspTree::GetOutOfBoundsCell()
458{
459        return mOutOfBoundsCell;
460}
461
462
463BspNode *BspTree::GetRoot() const
464{
465        return mRoot;
466}
467
468BspViewCell *BspTree::GetOrCreateOutOfBoundsCell()
469{
470        if (!mOutOfBoundsCell)
471        {
472                mOutOfBoundsCell = new BspViewCell();
473                mOutOfBoundsCell->SetId(-1);
474                mOutOfBoundsCell->SetValid(false);
475        }
476
477        return mOutOfBoundsCell;
478}
479
480
481void BspTree::InsertViewCell(ViewCell *viewCell)
482{
483        PolygonContainer *polys = new PolygonContainer();
484
485        // don't generate new view cell, insert this one
486        mGenerateViewCells = false;
487        // extract polygons that guide the split process
488        mStat.polys += AddMeshToPolygons(viewCell->GetMesh(), *polys, viewCell);
489        mBox.Include(viewCell->GetBox()); // add to BSP aabb
490
491        InsertPolygons(polys);
492}
493
494
495void BspTree::InsertPolygons(PolygonContainer *polys)
496{       
497        BspTraversalStack tStack;
498
499        // traverse existing tree or create new tree
500    if (!mRoot)
501                mRoot = new BspLeaf();
502
503        tStack.push(BspTraversalData(mRoot,
504                                                                 polys,
505                                                                 0,
506                                                                 mOutOfBoundsCell,
507                                                                 new BoundedRayContainer(),
508                                                                 0,
509                                                                 mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
510                                                                 new BspNodeGeometry()));
511
512        while (!tStack.empty())
513        {
514                // filter polygons donw the tree
515                BspTraversalData tData = tStack.top();
516            tStack.pop();
517                       
518                if (!tData.mNode->IsLeaf())
519                {
520                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
521
522                        //-- filter view cell polygons down the tree until a leaf is reached
523                        if (!tData.mPolygons->empty())
524                        {
525                                PolygonContainer *frontPolys = new PolygonContainer();
526                                PolygonContainer *backPolys = new PolygonContainer();
527                                PolygonContainer coincident;
528
529                                int splits = 0;
530               
531                                // split viewcell polygons with respect to split plane
532                                splits += SplitPolygons(interior->GetPlane(),
533                                                                                *tData.mPolygons,
534                                                                                *frontPolys,
535                                                                                *backPolys,
536                                                                                coincident);
537                               
538                                // extract view cells associated with the split polygons
539                                ViewCell *frontViewCell = GetOrCreateOutOfBoundsCell();
540                                ViewCell *backViewCell = GetOrCreateOutOfBoundsCell();
541                       
542                                BspTraversalData frontData(interior->GetFront(),
543                                                                                   frontPolys,
544                                                                                   tData.mDepth + 1,
545                                                                                   mOutOfBoundsCell,   
546                                                                                   tData.mRays,
547                                                                                   tData.mPvs,
548                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
549                                                                                   new BspNodeGeometry());
550
551                                BspTraversalData backData(interior->GetBack(),
552                                                                                  backPolys,
553                                                                                  tData.mDepth + 1,
554                                                                                  mOutOfBoundsCell,     
555                                                                                  tData.mRays,
556                                                                                  tData.mPvs,
557                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
558                                                                                  new BspNodeGeometry());
559
560                                if (!mGenerateViewCells)
561                                {
562                                        ExtractViewCells(frontData,
563                                                                         backData,
564                                                                         coincident,
565                                                                         interior->mPlane);
566                                }
567
568                                // don't need coincident polygons anymore
569                                CLEAR_CONTAINER(coincident);
570
571                                mStat.polySplits += splits;
572
573                                // push the children on the stack
574                                tStack.push(frontData);
575                                tStack.push(backData);
576                        }
577
578                        // cleanup
579                        DEL_PTR(tData.mPolygons);
580                        DEL_PTR(tData.mRays);
581                }
582                else
583                {
584                        // reached leaf => subdivide current viewcell
585                        BspNode *subRoot = Subdivide(tStack, tData);
586                }
587        }
588}
589
590int BspTree::AddMeshToPolygons(Mesh *mesh,
591                                                           PolygonContainer &polys,
592                                                           MeshInstance *parent)
593{
594        FaceContainer::const_iterator fi;
595       
596        // copy the face data to polygons
597        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
598        {
599                Polygon3 *poly = new Polygon3((*fi), mesh);
600               
601                if (poly->Valid(mEpsilon))
602                {
603                        poly->mParent = parent; // set parent intersectable
604                        polys.push_back(poly);
605                }
606                else
607                        DEL_PTR(poly);
608        }
609        return (int)mesh->mFaces.size();
610}
611
612
613int BspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
614                                                          PolygonContainer &polys,
615                                                          int maxObjects)
616{
617        int limit = (maxObjects > 0) ?
618                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
619 
620        int polysSize = 0;
621
622        for (int i = 0; i < limit; ++ i)
623        {
624                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
625                {
626                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
627                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
628                }
629        }
630
631        return polysSize;
632}
633
634
635int BspTree::AddToPolygonSoup(const ObjectContainer &objects,
636                                                          PolygonContainer &polys,
637                                                          int maxObjects,
638                                                          bool addToBbox)
639{
640        int limit = (maxObjects > 0) ?
641                Min((int)objects.size(), maxObjects) : (int)objects.size();
642 
643        for (int i = 0; i < limit; ++i)
644        {
645                Intersectable *object = objects[i];//*it;
646                Mesh *mesh = NULL;
647
648                switch (object->Type()) // extract the meshes
649                {
650                case Intersectable::MESH_INSTANCE:
651                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
652                        break;
653                case Intersectable::VIEW_CELL:
654                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
655                        break;
656                        // TODO: handle transformed mesh instances
657                default:
658                        Debug << "intersectable type not supported" << endl;
659                        break;
660                }
661               
662        if (mesh) // copy the mesh data to polygons
663                {
664                        if (addToBbox)
665                        {
666                                mBox.Include(object->GetBox()); // add to BSP tree aabb
667                        }
668               
669                        AddMeshToPolygons(mesh, polys, mOutOfBoundsCell);
670                }
671        }
672
673        return (int)polys.size();
674}
675
676
677void BspTree::Construct(const ViewCellContainer &viewCells)
678{
679        mStat.nodes = 1;
680        mBox.Initialize();      // initialise bsp tree bounding box
681
682        // copy view cell meshes into one big polygon soup
683        PolygonContainer *polys = new PolygonContainer();
684        mStat.polys = AddToPolygonSoup(viewCells, *polys);
685
686        // view cells are given
687        mGenerateViewCells = false;
688        // construct tree from the view cell polygons
689        Construct(polys, new BoundedRayContainer());
690}
691
692
693void BspTree::Construct(const ObjectContainer &objects)
694{
695        mStat.nodes = 1;
696        mBox.Initialize();      // initialise bsp tree bounding box
697       
698        PolygonContainer *polys = new PolygonContainer();
699
700        mGenerateViewCells = true;
701        // copy mesh instance polygons into one big polygon soup
702        mStat.polys = AddToPolygonSoup(objects, *polys);
703
704        // construct tree from polygon soup
705        Construct(polys, new BoundedRayContainer());
706}
707
708
709void BspTree::PreprocessPolygons(PolygonContainer &polys)
710{
711        // preprocess: throw out polygons coincident to the view space box (not needed)
712        PolygonContainer boxPolys;
713        mBox.ExtractPolys(boxPolys);
714        vector<Plane3> boxPlanes;
715
716        PolygonContainer::iterator pit, pit_end = boxPolys.end();
717
718        // extract planes of box
719        // TODO: can be done more elegantly than first extracting polygons
720        // and take their planes
721        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
722        {
723                boxPlanes.push_back((*pit)->GetSupportingPlane());
724        }
725
726        pit_end = polys.end();
727
728        for (pit = polys.begin(); pit != pit_end; ++ pit)
729        {
730                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
731               
732                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
733                {
734                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
735
736                        if (cf == Polygon3::COINCIDENT)
737                        {
738                                DEL_PTR(*pit);
739                                //Debug << "coincident!!" << endl;
740                        }
741                }
742        }
743
744        // remove deleted entries
745        for (int i = 0; i < (int)polys.size(); ++ i)
746        {
747                while (!polys[i] && (i < (int)polys.size()))
748                {
749                        swap(polys[i], polys.back());
750                        polys.pop_back();
751                }
752        }
753}
754
755
756
757void BspTree::Construct(const RayContainer &sampleRays,
758                                                AxisAlignedBox3 *forcedBoundingBox)
759{
760    mStat.nodes = 1;
761        mBox.Initialize();      // initialise BSP tree bounding box
762       
763        if (forcedBoundingBox)
764                mBox = *forcedBoundingBox;
765
766        PolygonContainer *polys = new PolygonContainer();
767        BoundedRayContainer *rays = new BoundedRayContainer();
768
769        RayContainer::const_iterator rit, rit_end = sampleRays.end();
770
771        // generate view cells
772        mGenerateViewCells = true;
773
774        long startTime = GetTime();
775
776        Debug << "**** Extracting polygons from rays ****\n";
777
778        std::map<Face *, Polygon3 *> facePolyMap;
779
780        //-- extract polygons intersected by the rays
781        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
782        {
783                Ray *ray = *rit;
784       
785                // get ray-face intersection. Store polygon representing the rays together
786                // with rays intersecting the face.
787                if (!ray->intersections.empty())
788                {
789                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->intersections[0].mObject);
790                        Face *face = obj->GetMesh()->mFaces[ray->intersections[0].mFace];
791
792                        std::map<Face *, Polygon3 *>::iterator it = facePolyMap.find(face);
793
794                        if (it != facePolyMap.end())
795                        {
796                                //store rays if needed for heuristics
797                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
798                                        (*it).second->mPiercingRays.push_back(ray);
799                        }
800                        else
801                        {       //store rays if needed for heuristics
802                                Polygon3 *poly = new Polygon3(face, obj->GetMesh());
803                                poly->mParent = obj;
804                                polys->push_back(poly);
805
806                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
807                                        poly->mPiercingRays.push_back(ray);
808
809                                facePolyMap[face] = poly;
810                        }
811                }
812        }
813       
814        facePolyMap.clear();
815
816        // compute bounding box
817        if (!forcedBoundingBox)
818                Polygon3::IncludeInBox(*polys, mBox);
819
820        //-- store rays
821        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
822        {
823                Ray *ray = *rit;
824        ray->SetId(-1); // reset id
825
826                float minT, maxT;
827                if (mBox.GetRaySegment(*ray, minT, maxT))
828                        rays->push_back(new BoundedRay(ray, minT, maxT));
829        }
830
831        // throw out bad polygons
832        PreprocessPolygons(*polys);
833
834        mStat.polys = (int)polys->size();
835
836        Debug << "**** Finished polygon extraction ****" << endl;
837        Debug << (int)polys->size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
838        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
839
840        Construct(polys, rays);
841}
842
843
844void BspTree::Construct(const ObjectContainer &objects,
845                                                const RayContainer &sampleRays,
846                                                AxisAlignedBox3 *forcedBoundingBox)
847{
848    mStat.nodes = 1;
849        mBox.Initialize();      // initialise BSP tree bounding box
850       
851        if (forcedBoundingBox)
852                mBox = *forcedBoundingBox;
853
854        BoundedRayContainer *rays = new BoundedRayContainer();
855        PolygonContainer *polys = new PolygonContainer();
856       
857        mGenerateViewCells = true;
858
859        // copy mesh instance polygons into one big polygon soup
860        mStat.polys = AddToPolygonSoup(objects, *polys, 0, !forcedBoundingBox);
861
862
863        RayContainer::const_iterator rit, rit_end = sampleRays.end();
864
865        //-- store rays
866        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
867        {
868                Ray *ray = *rit;
869        ray->SetId(-1); // reset id
870
871                float minT, maxT;
872                if (mBox.GetRaySegment(*ray, minT, maxT))
873                        rays->push_back(new BoundedRay(ray, minT, maxT));
874        }
875
876        PreprocessPolygons(*polys);
877        Debug << "tree has " << (int)polys->size() << " polys, " << (int)sampleRays.size() << " rays" << endl;
878        Construct(polys, rays);
879}
880
881
882void BspTree::Construct(PolygonContainer *polys, BoundedRayContainer *rays)
883{
884        BspTraversalStack tStack;
885
886        mRoot = new BspLeaf();
887
888        // constrruct root node geometry
889        BspNodeGeometry *geom = new BspNodeGeometry();
890        ConstructGeometry(mRoot, *geom);
891
892        BspTraversalData tData(mRoot,
893                                                   polys,
894                                                   0,
895                                                   GetOrCreateOutOfBoundsCell(),
896                                                   rays,
897                                                   ComputePvsSize(*rays),
898                                                   mUseAreaForPvs ? geom->GetArea() : geom->GetVolume(),
899                                                   geom);
900
901        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
902        mTotalPvsSize = tData.mPvs;
903       
904        mSubdivisionStats
905                        << "#ViewCells\n1\n" <<  endl
906                        << "#RenderCostDecrease\n0\n" << endl
907                        << "#TotalRenderCost\n" << mTotalCost << endl
908                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
909
910        tStack.push(tData);
911
912        // used for intermediate time measurements and progress
913        long interTime = GetTime();     
914        int nleaves = 500;
915
916        mStat.Start();
917        cout << "Constructing bsp tree ...\n";
918        long startTime = GetTime();
919        while (!tStack.empty())
920        {
921                tData = tStack.top();
922
923            tStack.pop();
924
925                // subdivide leaf node
926                BspNode *r = Subdivide(tStack, tData);
927
928                if (r == mRoot)
929            Debug << "BSP tree construction time spent at root: "
930                                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl;
931
932                if (mStat.Leaves() >= nleaves)
933                {
934                        nleaves += 500;
935                       
936                        cout << "leaves=" << mStat.Leaves() << endl;
937                        Debug << "needed "
938                                  << TimeDiff(interTime, GetTime())*1e-3
939                                  << " secs to create 500 leaves" << endl;
940                        interTime = GetTime();
941                }
942        }
943
944        cout << "finished\n";
945
946        mStat.Stop();
947}
948
949
950bool BspTree::TerminationCriteriaMet(const BspTraversalData &data) const
951{
952        return
953                (((int)data.mPolygons->size() <= mTermMinPolys) ||
954                 ((int)data.mRays->size() <= mTermMinRays) ||
955                 (data.mPvs <= mTermMinPvs) ||
956                 (data.mProbability <= mTermMinProbability) ||
957                 (data.mDepth >= mTermMaxDepth) ||
958                 (mStat.Leaves() >= mMaxViewCells) ||
959                 (data.GetAvgRayContribution() > mTermMaxRayContribution));
960}
961
962
963BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData)
964{
965        //-- terminate traversal 
966        if (TerminationCriteriaMet(tData))             
967        {
968                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
969       
970                BspViewCell *viewCell;
971
972                // generate new view cell for each leaf
973                if (mGenerateViewCells)
974                        viewCell = new BspViewCell();
975                else
976                        // add view cell to leaf
977                        viewCell = dynamic_cast<BspViewCell *>(tData.mViewCell);
978               
979                leaf->SetViewCell(viewCell);
980                viewCell->mLeaf = leaf;
981
982                float probability = max(0.0f, tData.mProbability);
983
984                if (mUseAreaForPvs)
985                        viewCell->SetArea(probability);
986                else
987                        viewCell->SetVolume(probability);
988
989                //-- add pvs
990                if (viewCell != mOutOfBoundsCell)
991                {
992                        int conSamp = 0, sampCon = 0;
993                        AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
994                       
995                        mStat.contributingSamples += conSamp;
996                        mStat.sampleContributions += sampCon;
997                }
998
999                EvaluateLeafStats(tData);
1000               
1001                //-- clean up
1002               
1003                // discard polygons
1004                CLEAR_CONTAINER(*tData.mPolygons);
1005                // discard rays
1006                CLEAR_CONTAINER(*tData.mRays);
1007
1008                DEL_PTR(tData.mPolygons);
1009                DEL_PTR(tData.mRays);
1010                DEL_PTR(tData.mGeometry);
1011
1012                return leaf;
1013        }
1014
1015        //-- continue subdivision
1016        PolygonContainer coincident;
1017       
1018        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1019                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1020        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1021                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1022
1023
1024        // create new interior node and two leaf nodes
1025        BspInterior *interior =
1026                SubdivideNode(tData, tFrontData, tBackData, coincident);
1027
1028
1029        if (1)
1030        {
1031                int pvsData = tData.mPvs;
1032
1033                float cData = (float)pvsData * tData.mProbability;
1034                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
1035                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
1036
1037                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
1038               
1039                mTotalCost += costDecr;
1040                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - pvsData;
1041
1042                mSubdivisionStats
1043                        << "#ViewCells\n" << mStat.Leaves() << endl
1044                        << "#RenderCostDecrease\n" << -costDecr << endl
1045                        << "#TotalRenderCost\n" << mTotalCost << endl
1046                        << "#AvgRenderCost\n" << mTotalPvsSize / mStat.Leaves() << endl;
1047        }
1048
1049        // extract view cells from coincident polygons according to plane normal
1050    // only if front or back polygons are empty
1051        if (!mGenerateViewCells)
1052        {
1053                ExtractViewCells(tFrontData,
1054                                                 tBackData,
1055                                                 coincident,
1056                                                 interior->mPlane);                     
1057        }
1058
1059        // don't need coincident polygons anymory
1060        CLEAR_CONTAINER(coincident);
1061
1062        // push the children on the stack
1063        tStack.push(tFrontData);
1064        tStack.push(tBackData);
1065
1066        // cleanup
1067        DEL_PTR(tData.mNode);
1068
1069        DEL_PTR(tData.mPolygons);
1070        DEL_PTR(tData.mRays);
1071        DEL_PTR(tData.mGeometry);               
1072       
1073        return interior;
1074}
1075
1076
1077void BspTree::ExtractViewCells(BspTraversalData &frontData,
1078                                                           BspTraversalData &backData,
1079                                                           const PolygonContainer &coincident,
1080                                                           const Plane3 &splitPlane) const
1081{
1082        // if not empty, tree is further subdivided => don't have to find view cell
1083        bool foundFront = !frontData.mPolygons->empty();
1084        bool foundBack = !frontData.mPolygons->empty();
1085
1086        PolygonContainer::const_iterator it =
1087                coincident.begin(), it_end = coincident.end();
1088
1089        //-- find first view cells in front and back leafs
1090        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
1091        {
1092                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
1093                {
1094                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1095                        foundBack = true;
1096                }
1097                else
1098                {
1099                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1100                        foundFront = true;
1101                }
1102        }
1103}
1104
1105
1106BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
1107                                                                        BspTraversalData &frontData,
1108                                                                        BspTraversalData &backData,
1109                                                                        PolygonContainer &coincident)
1110{
1111        mStat.nodes += 2;
1112       
1113        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1114
1115       
1116       
1117        // select subdivision plane
1118        BspInterior *interior =
1119                new BspInterior(SelectPlane(leaf, tData));
1120       
1121       
1122#ifdef _DEBUG
1123        Debug << interior << endl;
1124#endif
1125       
1126
1127        // subdivide rays into front and back rays
1128        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
1129       
1130       
1131
1132        // subdivide polygons with plane
1133        mStat.polySplits += SplitPolygons(interior->GetPlane(),
1134                                                                          *tData.mPolygons,
1135                                                                          *frontData.mPolygons,
1136                                                                          *backData.mPolygons,
1137                                                                          coincident);
1138
1139       
1140
1141    // compute pvs
1142        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1143        backData.mPvs = ComputePvsSize(*backData.mRays);
1144
1145        // split geometry and compute area
1146        if (1)
1147        {
1148                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1149                                                                           *backData.mGeometry,
1150                                                                           interior->mPlane,
1151                                                                           mBox,
1152                                                                           //0.000000000001);
1153                                                                           mEpsilon);
1154       
1155               
1156                if (mUseAreaForPvs)
1157                {
1158                        frontData.mProbability = frontData.mGeometry->GetArea();
1159                        backData.mProbability = backData.mGeometry->GetArea();
1160                }
1161                else
1162                {
1163                        frontData.mProbability = frontData.mGeometry->GetVolume();
1164                        backData.mProbability = tData.mProbability - frontData.mProbability;
1165                }
1166        }
1167
1168        //-- create front and back leaf
1169
1170        BspInterior *parent = leaf->GetParent();
1171
1172        // replace a link from node's parent
1173        if (!leaf->IsRoot())
1174        {
1175                parent->ReplaceChildLink(leaf, interior);
1176                interior->SetParent(parent);
1177        }
1178        else // new root
1179        {
1180                mRoot = interior;
1181        }
1182
1183        // and setup child links
1184        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1185       
1186        frontData.mNode = interior->GetFront();
1187        backData.mNode = interior->GetBack();
1188       
1189        interior->mTimeStamp = mTimeStamp ++;
1190       
1191        //DEL_PTR(leaf);
1192        return interior;
1193}
1194
1195
1196void BspTree::SortSplitCandidates(const PolygonContainer &polys,
1197                                                                  const int axis,
1198                                                                  vector<SortableEntry> &splitCandidates) const
1199{
1200        splitCandidates.clear();
1201
1202        int requestedSize = 2 * (int)polys.size();
1203        // creates a sorted split candidates array 
1204        splitCandidates.reserve(requestedSize);
1205
1206        PolygonContainer::const_iterator it, it_end = polys.end();
1207
1208        AxisAlignedBox3 box;
1209
1210        // insert all queries
1211        for(it = polys.begin(); it != it_end; ++ it)
1212        {
1213                box.Initialize();
1214                box.Include(*(*it));
1215               
1216                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
1217                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
1218        }
1219
1220        stable_sort(splitCandidates.begin(), splitCandidates.end());
1221}
1222
1223
1224float BspTree::BestCostRatio(const PolygonContainer &polys,
1225                                                         const AxisAlignedBox3 &box,
1226                                                         const int axis,
1227                                                         float &position,
1228                                                         int &objectsBack,
1229                                                         int &objectsFront) const
1230{
1231        vector<SortableEntry> splitCandidates;
1232
1233        SortSplitCandidates(polys, axis, splitCandidates);
1234       
1235        // go through the lists, count the number of objects left and right
1236        // and evaluate the following cost funcion:
1237        // C = ct_div_ci  + (ol + or)/queries
1238       
1239        int objectsLeft = 0, objectsRight = (int)polys.size();
1240       
1241        float minBox = box.Min(axis);
1242        float maxBox = box.Max(axis);
1243        float boxArea = box.SurfaceArea();
1244 
1245        float minBand = minBox + mSplitBorder * (maxBox - minBox);
1246        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
1247       
1248        float minSum = 1e20f;
1249        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
1250
1251        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
1252        {
1253                switch ((*ci).type)
1254                {
1255                        case SortableEntry::POLY_MIN:
1256                                ++ objectsLeft;
1257                                break;
1258                        case SortableEntry::POLY_MAX:
1259                            -- objectsRight;
1260                                break;
1261                        default:
1262                                break;
1263                }
1264               
1265                if ((*ci).value > minBand && (*ci).value < maxBand)
1266                {
1267                        AxisAlignedBox3 lbox = box;
1268                        AxisAlignedBox3 rbox = box;
1269                        lbox.SetMax(axis, (*ci).value);
1270                        rbox.SetMin(axis, (*ci).value);
1271
1272                        const float sum = objectsLeft * lbox.SurfaceArea() +
1273                                                          objectsRight * rbox.SurfaceArea();
1274     
1275                        if (sum < minSum)
1276                        {
1277                                minSum = sum;
1278                                position = (*ci).value;
1279
1280                                objectsBack = objectsLeft;
1281                                objectsFront = objectsRight;
1282                        }
1283                }
1284        }
1285 
1286        const float oldCost = (float)polys.size();
1287        const float newCost = mAxisAlignedCtDivCi + minSum / boxArea;
1288        const float ratio = newCost / oldCost;
1289
1290
1291#if 0
1292  Debug << "====================" << endl;
1293  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
1294      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
1295#endif
1296  return ratio;
1297}
1298
1299bool BspTree::SelectAxisAlignedPlane(Plane3 &plane,
1300                                                                         const PolygonContainer &polys) const
1301{
1302        AxisAlignedBox3 box;
1303        box.Initialize();
1304       
1305        // create bounding box of region
1306        Polygon3::IncludeInBox(polys, box);
1307       
1308        int objectsBack = 0, objectsFront = 0;
1309        int axis = 0;
1310        float costRatio = MAX_FLOAT;
1311        Vector3 position;
1312
1313        //-- area subdivision
1314        for (int i = 0; i < 3; ++ i)
1315        {
1316                float p = 0;
1317                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
1318               
1319                if (r < costRatio)
1320                {
1321                        costRatio = r;
1322                        axis = i;
1323                        position = p;
1324                }
1325        }
1326       
1327        if (costRatio >= mMaxCostRatio)
1328                return false;
1329
1330        Vector3 norm(0,0,0); norm[axis] = 1.0f;
1331        plane = Plane3(norm, position);
1332
1333        return true;
1334}
1335
1336
1337Plane3 BspTree::SelectPlane(BspLeaf *leaf, BspTraversalData &data)
1338{
1339        if ((!mMaxPolyCandidates || data.mPolygons->empty()) &&
1340                (!mMaxRayCandidates || data.mRays->empty()))
1341        {
1342                Debug << "Warning: No autopartition polygon candidate available\n";
1343       
1344                // return axis aligned split
1345                AxisAlignedBox3 box;
1346                box.Initialize();
1347       
1348                // create bounding box of region
1349                Polygon3::IncludeInBox(*data.mPolygons, box);
1350
1351                const int axis = box.Size().DrivingAxis();
1352                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1353
1354                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1355                return Plane3(norm, position);
1356        }
1357       
1358        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
1359                ((int)data.mPolygons->size() > mTermMinPolysForAxisAligned) &&
1360                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1361                ((mTermMinObjectsForAxisAligned < 0) ||
1362                 (Polygon3::ParentObjectsSize(*data.mPolygons) > mTermMinObjectsForAxisAligned)))
1363        {
1364                Plane3 plane;
1365                if (SelectAxisAlignedPlane(plane, *data.mPolygons))
1366                        return plane;
1367        }
1368
1369        // simplest strategy: just take next polygon
1370        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1371        {
1372        if (!data.mPolygons->empty())
1373                {
1374                        Polygon3 *nextPoly =
1375                                (*data.mPolygons)[(int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1))];
1376                        return nextPoly->GetSupportingPlane();
1377                }
1378                else
1379                {
1380                        const int candidateIdx = (int)RandomValue(0, (Real)((int)data.mRays->size() - 1));
1381                        BoundedRay *bRay = (*data.mRays)[candidateIdx];
1382
1383                        Ray *ray = bRay->mRay;
1384                                               
1385                        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1386                        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1387
1388                        const Vector3 pt = (maxPt + minPt) * 0.5;
1389
1390                        const Vector3 normal = ray->GetDir();
1391                       
1392                        return Plane3(normal, pt);
1393                }
1394
1395                return Plane3();
1396        }
1397
1398        // use heuristics to find appropriate plane
1399        return SelectPlaneHeuristics(leaf, data);
1400}
1401
1402
1403Plane3 BspTree::ChooseCandidatePlane(const BoundedRayContainer &rays) const
1404{       
1405        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1406        BoundedRay *bRay = rays[candidateIdx];
1407        Ray *ray = bRay->mRay;
1408
1409        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1410        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1411
1412        const Vector3 pt = (maxPt + minPt) * 0.5;
1413
1414        const Vector3 normal = ray->GetDir();
1415                       
1416        return Plane3(normal, pt);
1417}
1418
1419Plane3 BspTree::ChooseCandidatePlane2(const BoundedRayContainer &rays) const
1420{       
1421        Vector3 pt[3];
1422        int idx[3];
1423        int cmaxT = 0;
1424        int cminT = 0;
1425        bool chooseMin = false;
1426
1427        for (int j = 0; j < 3; j ++)
1428        {
1429                idx[j] = (int)RandomValue(0, Real((int)rays.size() * 2 - 1));
1430                               
1431                if (idx[j] >= (int)rays.size())
1432                {
1433                        idx[j] -= (int)rays.size();             
1434                        chooseMin = (cminT < 2);
1435                }
1436                else
1437                        chooseMin = (cmaxT < 2);
1438
1439                BoundedRay *bRay = rays[idx[j]];
1440                pt[j] = chooseMin ? bRay->mRay->Extrap(bRay->mMinT) :
1441                                                        bRay->mRay->Extrap(bRay->mMaxT);
1442        }       
1443                       
1444        return Plane3(pt[0], pt[1], pt[2]);
1445}
1446
1447Plane3 BspTree::ChooseCandidatePlane3(const BoundedRayContainer &rays) const
1448{       
1449        Vector3 pt[3];
1450       
1451        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1452        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1453
1454        // check if rays different
1455        if (idx1 == idx2)
1456                idx2 = (idx2 + 1) % (int)rays.size();
1457
1458        const BoundedRay *ray1 = rays[idx1];
1459        const BoundedRay *ray2 = rays[idx2];
1460
1461        // normal vector of the plane parallel to both lines
1462        const Vector3 norm =
1463                Normalize(CrossProd(ray1->mRay->GetDir(), ray2->mRay->GetDir()));
1464
1465        const Vector3 orig1 = ray1->mRay->Extrap(ray1->mMinT);
1466        const Vector3 orig2 = ray2->mRay->Extrap(ray2->mMinT);
1467
1468        // vector from line 1 to line 2
1469        const Vector3 vd = orig1 - orig2;
1470       
1471        // project vector on normal to get distance
1472        const float dist = DotProd(vd, norm);
1473
1474        // point on plane lies halfway between the two planes
1475        const Vector3 planePt = orig1 + norm * dist * 0.5;
1476
1477        return Plane3(norm, planePt);
1478}
1479
1480
1481Plane3 BspTree::SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data)
1482{
1483        float lowestCost = MAX_FLOAT;
1484        Plane3 bestPlane;
1485        // intermediate plane
1486        Plane3 plane;
1487
1488        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1489        int maxIdx = (int)data.mPolygons->size();
1490       
1491        for (int i = 0; i < limit; ++ i)
1492        {
1493                // assure that no index is taken twice
1494                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1495                               
1496                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1497
1498                // swap candidate to the end to avoid testing same plane
1499                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1500                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1501
1502                // evaluate current candidate
1503                const float candidateCost =
1504                        SplitPlaneCost(poly->GetSupportingPlane(), data);
1505
1506                if (candidateCost < lowestCost)
1507                {
1508                        bestPlane = poly->GetSupportingPlane();
1509                        lowestCost = candidateCost;
1510                }
1511        }
1512       
1513        //-- choose candidate planes extracted from rays
1514        for (int i = 0; i < mMaxRayCandidates; ++ i)
1515        {
1516                plane = ChooseCandidatePlane3(*data.mRays);
1517                const float candidateCost = SplitPlaneCost(plane, data);
1518
1519                if (candidateCost < lowestCost)
1520                {
1521                        bestPlane = plane;     
1522                        lowestCost = candidateCost;
1523                }
1524        }
1525
1526#ifdef _DEBUG
1527        Debug << "plane lowest cost: " << lowestCost << endl;
1528#endif
1529       
1530        return bestPlane;
1531}
1532
1533
1534float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1535                                                          const PolygonContainer &polys) const
1536{
1537        float val = 0;
1538
1539        float sumBalancedPolys = 0;
1540        float sumSplits = 0;
1541        float sumPolyArea = 0;
1542        float sumBalancedViewCells = 0;
1543        float sumBlockedRays = 0;
1544        float totalBlockedRays = 0;
1545        //float totalArea = 0;
1546        int totalViewCells = 0;
1547
1548        // need three unique ids for each type of view cell
1549        // for balanced view cells criterium
1550        ViewCell::NewMail();
1551        const int backId = ViewCell::sMailId;
1552        ViewCell::NewMail();
1553        const int frontId = ViewCell::sMailId;
1554        ViewCell::NewMail();
1555        const int frontAndBackId = ViewCell::sMailId;
1556
1557        bool useRand;
1558        int limit;
1559
1560        // choose test polyongs randomly if over threshold
1561        if ((int)polys.size() > mMaxTests)
1562        {
1563                useRand = true;
1564                limit = mMaxTests;
1565        }
1566        else
1567        {
1568                useRand = false;
1569                limit = (int)polys.size();
1570        }
1571
1572        for (int i = 0; i < limit; ++ i)
1573        {
1574                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1575
1576                Polygon3 *poly = polys[testIdx];
1577
1578        const int classification =
1579                        poly->ClassifyPlane(candidatePlane, mEpsilon);
1580
1581                if (mSplitPlaneStrategy & BALANCED_POLYS)
1582                        sumBalancedPolys += sBalancedPolysTable[classification];
1583               
1584                if (mSplitPlaneStrategy & LEAST_SPLITS)
1585                        sumSplits += sLeastPolySplitsTable[classification];
1586
1587                if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1588                {
1589                        if (classification == Polygon3::COINCIDENT)
1590                                sumPolyArea += poly->GetArea();
1591                        //totalArea += area;
1592                }
1593               
1594                if (mSplitPlaneStrategy & BLOCKED_RAYS)
1595                {
1596                        const float blockedRays = (float)poly->mPiercingRays.size();
1597               
1598                        if (classification == Polygon3::COINCIDENT)
1599                                sumBlockedRays += blockedRays;
1600                       
1601                        totalBlockedRays += blockedRays;
1602                }
1603
1604                // assign view cells to back or front according to classificaion
1605                if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1606                {
1607                        MeshInstance *viewCell = poly->mParent;
1608               
1609                        // assure that we only count a view cell
1610                        // once for the front and once for the back side of the plane
1611                        if (classification == Polygon3::FRONT_SIDE)
1612                        {
1613                                if ((viewCell->mMailbox != frontId) &&
1614                                        (viewCell->mMailbox != frontAndBackId))
1615                                {
1616                                        sumBalancedViewCells += 1.0;
1617
1618                                        if (viewCell->mMailbox != backId)
1619                                                viewCell->mMailbox = frontId;
1620                                        else
1621                                                viewCell->mMailbox = frontAndBackId;
1622                                       
1623                                        ++ totalViewCells;
1624                                }
1625                        }
1626                        else if (classification == Polygon3::BACK_SIDE)
1627                        {
1628                                if ((viewCell->mMailbox != backId) &&
1629                                    (viewCell->mMailbox != frontAndBackId))
1630                                {
1631                                        sumBalancedViewCells -= 1.0;
1632
1633                                        if (viewCell->mMailbox != frontId)
1634                                                viewCell->mMailbox = backId;
1635                                        else
1636                                                viewCell->mMailbox = frontAndBackId;
1637
1638                                        ++ totalViewCells;
1639                                }
1640                        }
1641                }
1642        }
1643
1644        const float polysSize = (float)polys.size() + Limits::Small;
1645
1646        // all values should be approx. between 0 and 1 so they can be combined
1647        // and scaled with the factors according to their importance
1648        if (mSplitPlaneStrategy & BALANCED_POLYS)
1649                val += mBalancedPolysFactor * fabs(sumBalancedPolys) / polysSize;
1650       
1651        if (mSplitPlaneStrategy & LEAST_SPLITS) 
1652                val += mLeastSplitsFactor * sumSplits / polysSize;
1653
1654        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1655                // HACK: polys.size should be total area so scaling is between 0 and 1
1656                val += mLargestPolyAreaFactor * (float)polys.size() / sumPolyArea;
1657
1658        if (mSplitPlaneStrategy & BLOCKED_RAYS)
1659                if (totalBlockedRays != 0)
1660                        val += mBlockedRaysFactor * (totalBlockedRays - sumBlockedRays) / totalBlockedRays;
1661
1662        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1663                val += mBalancedViewCellsFactor * fabs(sumBalancedViewCells) /
1664                        ((float)totalViewCells + Limits::Small);
1665       
1666        return val;
1667}
1668
1669
1670inline void BspTree::GenerateUniqueIdsForPvs()
1671{
1672        ViewCell::NewMail(); sBackId = ViewCell::sMailId;
1673        ViewCell::NewMail(); sFrontId = ViewCell::sMailId;
1674        ViewCell::NewMail(); sFrontAndBackId = ViewCell::sMailId;
1675}
1676
1677
1678float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1679                                                          const BoundedRayContainer &rays,
1680                                                          const int pvs,
1681                                                          const float probability,
1682                                                          const BspNodeGeometry &cell) const
1683{
1684        float val = 0;
1685
1686        float sumBalancedRays = 0;
1687        float sumRaySplits = 0;
1688
1689        int frontPvs = 0;
1690        int backPvs = 0;
1691
1692        // probability that view point lies in child
1693        float pOverall = 0;
1694        float pFront = 0;
1695        float pBack = 0;
1696
1697        const bool pvsUseLen = false;
1698
1699        if (mSplitPlaneStrategy & PVS)
1700        {
1701                // create unique ids for pvs heuristics
1702                GenerateUniqueIdsForPvs();
1703
1704                // construct child geometry with regard to the candidate split plane
1705                BspNodeGeometry frontCell;
1706                BspNodeGeometry backCell;
1707
1708                cell.SplitGeometry(frontCell,
1709                                                   backCell,
1710                                                   candidatePlane,
1711                                                   mBox,
1712                                                   mEpsilon);
1713
1714                if (mUseAreaForPvs)
1715                {
1716                        pFront = frontCell.GetArea();
1717                        pBack = backCell.GetArea();
1718                }
1719                else
1720                {
1721                        pFront = frontCell.GetVolume();
1722                        pBack = pOverall - pFront;
1723                }
1724               
1725
1726                pOverall = probability;
1727        }
1728                       
1729        bool useRand;
1730        int limit;
1731
1732        // choose test polyongs randomly if over threshold
1733        if ((int)rays.size() > mMaxTests)
1734        {
1735                useRand = true;
1736                limit = mMaxTests;
1737        }
1738        else
1739        {
1740                useRand = false;
1741                limit = (int)rays.size();
1742        }
1743
1744        for (int i = 0; i < limit; ++ i)
1745        {
1746                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1747       
1748                BoundedRay *bRay = rays[testIdx];
1749
1750                Ray *ray = bRay->mRay;
1751                const float minT = bRay->mMinT;
1752                const float maxT = bRay->mMaxT;
1753
1754                Vector3 entP, extP;
1755
1756                const int cf =
1757                        ray->ClassifyPlane(candidatePlane, minT, maxT, entP, extP);
1758
1759                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1760                {
1761                        sumBalancedRays += sBalancedRaysTable[cf];
1762                }
1763               
1764                if (mSplitPlaneStrategy & BALANCED_RAYS)
1765                {
1766                        sumRaySplits += sLeastRaySplitsTable[cf];
1767                }
1768
1769                if (mSplitPlaneStrategy & PVS)
1770                {
1771                        // in case the ray intersects an object
1772                        // assure that we only count the object
1773                        // once for the front and once for the back side of the plane
1774                       
1775                        // add the termination object
1776                        if (!ray->intersections.empty())
1777                                AddObjToPvs(ray->intersections[0].mObject, cf, frontPvs, backPvs);
1778                       
1779                        // add the source object
1780                        AddObjToPvs(ray->sourceObject.mObject, cf, frontPvs, backPvs);
1781                }
1782        }
1783
1784        const float raysSize = (float)rays.size() + Limits::Small;
1785
1786        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1787                val += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1788
1789        if (mSplitPlaneStrategy & BALANCED_RAYS)
1790                val += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
1791
1792        const float denom = pOverall * (float)pvs * 2.0f + Limits::Small;
1793
1794        if (mSplitPlaneStrategy & PVS)
1795        {
1796                val += mPvsFactor * (frontPvs * pFront + (backPvs * pBack)) / denom;
1797
1798                // give penalty to unbalanced split
1799                if (0)
1800                if (((pFront * 0.2 + Limits::Small) > pBack) ||
1801                        (pFront < (pBack * 0.2 + Limits::Small)))
1802                        val += 0.5;
1803        }
1804
1805       
1806#ifdef _DEBUG
1807        Debug << "totalpvs: " << pvs << " ptotal: " << pOverall
1808                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1809                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1810#endif
1811       
1812        return val;
1813}
1814
1815void BspTree::AddObjToPvs(Intersectable *obj,
1816                                                  const int cf,
1817                                                  int &frontPvs,
1818                                                  int &backPvs) const
1819{
1820        if (!obj)
1821                return;
1822        // TODO: does this really belong to no pvs?
1823        //if (cf == Ray::COINCIDENT) return;
1824
1825        // object belongs to both PVS
1826        const bool bothSides = (cf == Ray::FRONT_BACK) ||
1827                                                   (cf == Ray::BACK_FRONT) ||
1828                                                   (cf == Ray::COINCIDENT);
1829
1830        if ((cf == Ray::FRONT) || bothSides)
1831        {
1832                if ((obj->mMailbox != sFrontId) &&
1833                        (obj->mMailbox != sFrontAndBackId))
1834                {
1835                        ++ frontPvs;
1836
1837                        if (obj->mMailbox == sBackId)
1838                                obj->mMailbox = sFrontAndBackId;       
1839                        else
1840                                obj->mMailbox = sFrontId;                                                               
1841                }
1842        }
1843       
1844        if ((cf == Ray::BACK) || bothSides)
1845        {
1846                if ((obj->mMailbox != sBackId) &&
1847                        (obj->mMailbox != sFrontAndBackId))
1848                {
1849                        ++ backPvs;
1850
1851                        if (obj->mMailbox == sFrontId)
1852                                obj->mMailbox = sFrontAndBackId;
1853                        else
1854                                obj->mMailbox = sBackId;                               
1855                }
1856        }
1857}
1858
1859
1860float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1861                                                          BspTraversalData &data) const
1862{
1863        float val = 0;
1864
1865        if (mSplitPlaneStrategy & VERTICAL_AXIS)
1866        {
1867                Vector3 tinyAxis(0,0,0); tinyAxis[mBox.Size().TinyAxis()] = 1.0f;
1868                // we put a penalty on the dot product between the "tiny" vertical axis
1869                // and the split plane axis
1870                val += mVerticalSplitsFactor *
1871                           fabs(DotProd(candidatePlane.mNormal, tinyAxis));
1872        }
1873
1874        // the following criteria loop over all polygons to find the cost value
1875        if ((mSplitPlaneStrategy & BALANCED_POLYS)      ||
1876                (mSplitPlaneStrategy & LEAST_SPLITS)        ||
1877                (mSplitPlaneStrategy & LARGEST_POLY_AREA)   ||
1878                (mSplitPlaneStrategy & BALANCED_VIEW_CELLS) ||
1879                (mSplitPlaneStrategy & BLOCKED_RAYS))
1880        {
1881                val += SplitPlaneCost(candidatePlane, *data.mPolygons);
1882        }
1883
1884        // the following criteria loop over all rays to find the cost value
1885        if ((mSplitPlaneStrategy & BALANCED_RAYS)      ||
1886                (mSplitPlaneStrategy & LEAST_RAY_SPLITS)   ||
1887                (mSplitPlaneStrategy & PVS))
1888        {
1889                val += SplitPlaneCost(candidatePlane, *data.mRays, data.mPvs,
1890                                                          data.mProbability, *data.mGeometry);
1891        }
1892
1893        // return linear combination of the sums
1894        return val;
1895}
1896
1897void BspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1898{
1899        stack<BspNode *> nodeStack;
1900        nodeStack.push(mRoot);
1901 
1902        while (!nodeStack.empty())
1903        {
1904                BspNode *node = nodeStack.top();
1905   
1906                nodeStack.pop();
1907   
1908                if (node->IsLeaf())
1909                {
1910                        BspLeaf *leaf = (BspLeaf *)node;               
1911                        leaves.push_back(leaf);
1912                }
1913                else
1914                {
1915                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1916
1917                        nodeStack.push(interior->GetBack());
1918                        nodeStack.push(interior->GetFront());
1919                }
1920        }
1921}
1922
1923
1924AxisAlignedBox3 BspTree::GetBoundingBox() const
1925{
1926        return mBox;
1927}
1928
1929
1930void BspTree::EvaluateLeafStats(const BspTraversalData &data)
1931{
1932        // the node became a leaf -> evaluate stats for leafs
1933        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1934
1935        // store maximal and minimal depth
1936        if (data.mDepth > mStat.maxDepth)
1937                mStat.maxDepth = data.mDepth;
1938
1939        if (data.mDepth < mStat.minDepth)
1940                mStat.minDepth = data.mDepth;
1941
1942        // accumulate depth to compute average depth
1943        mStat.accumDepth += data.mDepth;
1944        // accumulate rays to compute rays /  leaf
1945        mStat.accumRays += (int)data.mRays->size();
1946
1947        if (data.mDepth >= mTermMaxDepth)
1948                ++ mStat.maxDepthNodes;
1949
1950        if (data.mPvs < mTermMinPvs)
1951                ++ mStat.minPvsNodes;
1952
1953        if ((int)data.mRays->size() < mTermMinRays)
1954                ++ mStat.minRaysNodes;
1955
1956        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1957                ++ mStat.maxRayContribNodes;
1958       
1959        if (data.mProbability <= mTermMinProbability)
1960                ++ mStat.minProbabilityNodes;
1961
1962#ifdef _DEBUG
1963        Debug << "BSP stats: "
1964                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1965                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1966                  << "Probability: " << data.mProbability << " (min: " << mTermMinProbability << "), "
1967                  << "#polygons: " << (int)data.mPolygons->size() << " (max: " << mTermMinPolys << "), "
1968                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1969                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1970                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1971#endif
1972}
1973
1974int
1975BspTree::_CastRay(Ray &ray)
1976{
1977        int hits = 0;
1978 
1979        stack<BspRayTraversalData> tStack;
1980 
1981        float maxt, mint;
1982
1983        if (!mBox.GetRaySegment(ray, mint, maxt))
1984                return 0;
1985
1986        ViewCell::NewMail();
1987
1988        Vector3 entp = ray.Extrap(mint);
1989        Vector3 extp = ray.Extrap(maxt);
1990 
1991        BspNode *node = mRoot;
1992        BspNode *farChild = NULL;
1993       
1994        while (1)
1995        {
1996                if (!node->IsLeaf())
1997                {
1998                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1999                       
2000                        Plane3 splitPlane = in->GetPlane();
2001                        const int entSide = splitPlane.Side(entp);
2002                        const int extSide = splitPlane.Side(extp);
2003
2004                        if (entSide < 0)
2005                        {
2006                                node = in->GetBack();
2007
2008                                if(extSide <= 0) // plane does not split ray => no far child
2009                                        continue;
2010                                       
2011                                farChild = in->GetFront(); // plane splits ray
2012
2013                        } else if (entSide > 0)
2014                        {
2015                                node = in->GetFront();
2016
2017                                if (extSide >= 0) // plane does not split ray => no far child
2018                                        continue;
2019
2020                                farChild = in->GetBack(); // plane splits ray                   
2021                        }
2022                        else // ray and plane are coincident
2023                        {
2024                                // WHAT TO DO IN THIS CASE ?
2025                                //break;
2026                                node = in->GetFront();
2027                                continue;
2028                        }
2029
2030                        // push data for far child
2031                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2032
2033                        // find intersection of ray segment with plane
2034                        float t;
2035                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2036                        maxt *= t;
2037                       
2038                } else // reached leaf => intersection with view cell
2039                {
2040                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2041     
2042                        if (!leaf->mViewCell->Mailed())
2043                        {
2044                                //ray.bspIntersections.push_back(Ray::BspIntersection(maxt, leaf));
2045                                leaf->mViewCell->Mail();
2046                                ++ hits;
2047                        }
2048                       
2049                        //-- fetch the next far child from the stack
2050                        if (tStack.empty())
2051                                break;
2052     
2053                        entp = extp;
2054                        mint = maxt; // NOTE: need this?
2055
2056                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2057                                break;
2058
2059                        BspRayTraversalData &s = tStack.top();
2060
2061                        node = s.mNode;
2062                        extp = s.mExitPoint;
2063                        maxt = s.mMaxT;
2064
2065                        tStack.pop();
2066                }
2067        }
2068
2069        return hits;
2070}
2071
2072
2073int BspTree::CastLineSegment(const Vector3 &origin,
2074                                                         const Vector3 &termination,
2075                                                         vector<ViewCell *> &viewcells)
2076{
2077        int hits = 0;
2078        stack<BspRayTraversalData> tStack;
2079
2080        float mint = 0.0f, maxt = 1.0f;
2081
2082        Intersectable::NewMail();
2083        ViewCell::NewMail();
2084
2085        Vector3 entp = origin;
2086        Vector3 extp = termination;
2087
2088        BspNode *node = mRoot;
2089        BspNode *farChild = NULL;
2090
2091        const float thresh = 1 ? 1e-6f : 0.0f;
2092
2093        while (1)
2094        {
2095                if (!node->IsLeaf()) 
2096                {
2097                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2098               
2099                        Plane3 splitPlane = in->GetPlane();
2100                       
2101                        const int entSide = splitPlane.Side(entp, thresh);
2102                        const int extSide = splitPlane.Side(extp, thresh);
2103
2104                        if (entSide < 0)
2105                        {
2106                                node = in->GetBack();
2107               
2108                                if(extSide <= 0) // plane does not split ray => no far child
2109                                        continue;
2110               
2111                                farChild = in->GetFront(); // plane splits ray
2112               
2113                        }
2114                        else if (entSide > 0)
2115                        {
2116                                node = in->GetFront();
2117                       
2118                                if (extSide >= 0) // plane does not split ray => no far child
2119                                        continue;
2120                       
2121                                farChild = in->GetBack(); // plane splits ray                   
2122                        }
2123                        else // ray and plane are coincident
2124                        {
2125                                // NOTE: what to do if ray is coincident with plane?
2126                                if (extSide < 0)
2127                                        node = in->GetBack();
2128                                else
2129                                        node = in->GetFront();
2130                                                               
2131                                continue; // no far child
2132                        }
2133               
2134                        // push data for far child
2135                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2136               
2137                        // find intersection of ray segment with plane
2138                        float t;
2139                        extp = splitPlane.FindIntersection(origin, extp, &t);
2140                        maxt *= t; 
2141                }
2142                else
2143                {
2144                        // reached leaf => intersection with view cell
2145                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2146               
2147                        if (!leaf->mViewCell->Mailed())
2148                        {
2149                                viewcells.push_back(leaf->mViewCell);
2150                                leaf->mViewCell->Mail();
2151                                hits++;
2152                        }
2153               
2154                        //-- fetch the next far child from the stack
2155                        if (tStack.empty())
2156                                break;
2157           
2158                        entp = extp;
2159                        mint = maxt; // NOTE: need this?
2160               
2161                        BspRayTraversalData &s = tStack.top();
2162               
2163                        node = s.mNode;
2164                        extp = s.mExitPoint;
2165                        maxt = s.mMaxT;
2166               
2167                        tStack.pop();
2168                }
2169        }
2170        return hits;
2171}
2172
2173
2174void BspTree::CollectViewCells(ViewCellContainer &viewCells) const
2175{
2176        stack<BspNode *> nodeStack;
2177        nodeStack.push(mRoot);
2178
2179        ViewCell::NewMail();
2180
2181        while (!nodeStack.empty())
2182        {
2183                BspNode *node = nodeStack.top();
2184                nodeStack.pop();
2185
2186                if (node->IsLeaf())
2187                {
2188                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
2189
2190                        if (!viewCell->Mailed())
2191                        {
2192                                viewCell->Mail();
2193                                viewCells.push_back(viewCell);
2194                        }
2195                }
2196                else
2197                {
2198                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2199
2200                        nodeStack.push(interior->GetFront());
2201                        nodeStack.push(interior->GetBack());
2202                }
2203        }
2204}
2205
2206
2207BspTreeStatistics &BspTree::GetStat()
2208{
2209        return mStat;
2210}
2211
2212
2213float BspTree::AccumulatedRayLength(BoundedRayContainer &rays) const
2214{
2215        float len = 0;
2216
2217        BoundedRayContainer::const_iterator it, it_end = rays.end();
2218
2219        for (it = rays.begin(); it != it_end; ++ it)
2220        {
2221                len += SqrDistance((*it)->mRay->Extrap((*it)->mMinT),
2222                                                   (*it)->mRay->Extrap((*it)->mMaxT));
2223        }
2224
2225        return len;
2226}
2227
2228
2229int BspTree::SplitRays(const Plane3 &plane,
2230                                           BoundedRayContainer &rays,
2231                                           BoundedRayContainer &frontRays,
2232                                           BoundedRayContainer &backRays)
2233{
2234        int splits = 0;
2235       
2236        while (!rays.empty())
2237        {
2238                BoundedRay *bRay = rays.back();
2239                Ray *ray = bRay->mRay;
2240                float minT = bRay->mMinT;
2241                float maxT = bRay->mMaxT;
2242
2243                rays.pop_back();
2244       
2245                Vector3 entP, extP;
2246
2247                const int cf =
2248                        ray->ClassifyPlane(plane, minT, maxT, entP, extP);
2249               
2250                // set id to ray classification
2251                ray->SetId(cf);
2252
2253                switch (cf)
2254                {
2255                case Ray::COINCIDENT: // TODO: should really discard ray?
2256                        frontRays.push_back(bRay);
2257                        //DEL_PTR(bRay);
2258                        break;
2259                case Ray::BACK:
2260                        backRays.push_back(bRay);
2261                        break;
2262                case Ray::FRONT:
2263                        frontRays.push_back(bRay);
2264                        break;
2265                case Ray::FRONT_BACK:
2266                        {
2267                                // find intersection of ray segment with plane
2268                                const float t = plane.FindT(ray->GetLoc(), extP);
2269                               
2270                                const float newT = t * maxT;
2271
2272                                frontRays.push_back(new BoundedRay(ray, minT, newT));
2273                                backRays.push_back(new BoundedRay(ray, newT, maxT));
2274
2275                                DEL_PTR(bRay);
2276                        }
2277                        break;
2278                case Ray::BACK_FRONT:
2279                        {
2280                                // find intersection of ray segment with plane
2281                                const float t = plane.FindT(ray->GetLoc(), extP);
2282                                const float newT = t * bRay->mMaxT;
2283
2284                                backRays.push_back(new BoundedRay(ray, minT, newT));
2285                                frontRays.push_back(new BoundedRay(ray, newT, maxT));
2286
2287                                DEL_PTR(bRay);
2288
2289                                ++ splits;
2290                        }
2291                        break;
2292                default:
2293                        Debug << "Should not come here 4" << endl;
2294                        break;
2295                }
2296        }
2297
2298        return splits;
2299}
2300
2301void BspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2302{
2303        BspNode *lastNode;
2304        do
2305        {
2306                lastNode = n;
2307
2308                // want to get planes defining geometry of this node => don't take
2309                // split plane of node itself
2310                n = n->GetParent();
2311               
2312                if (n)
2313                {
2314                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2315                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2316
2317            if (interior->GetFront() != lastNode)
2318                                halfSpace.ReverseOrientation();
2319
2320                        halfSpaces.push_back(halfSpace);
2321                }
2322        }
2323        while (n);
2324}
2325
2326
2327
2328void BspTree::ConstructGeometry(ViewCell *vc,
2329                                                                BspNodeGeometry &vcGeom) const
2330{
2331        ViewCellContainer leaves;
2332        mViewCellsTree->CollectLeaves(vc, leaves);
2333
2334        ViewCellContainer::const_iterator it, it_end = leaves.end();
2335
2336        for (it = leaves.begin(); it != it_end; ++ it)
2337        {
2338                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2339                ConstructGeometry(l, vcGeom);
2340        }
2341}
2342
2343
2344void BspTree::SetViewCellsManager(ViewCellsManager *vcm)
2345{
2346        mViewCellsManager = vcm;
2347}
2348
2349
2350void BspTree::ConstructGeometry(BspNode *n, BspNodeGeometry &geom) const
2351{
2352        vector<Plane3> halfSpaces;
2353        ExtractHalfSpaces(n, halfSpaces);
2354
2355        PolygonContainer candidates;
2356
2357        // bounded planes are added to the polygons (reverse polygons
2358        // as they have to be outfacing
2359        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2360        {
2361                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2362               
2363                if (p->Valid(mEpsilon))
2364                {
2365                        candidates.push_back(p->CreateReversePolygon());
2366                        DEL_PTR(p);
2367                }
2368        }
2369
2370        // add faces of bounding box (also could be faces of the cell)
2371        for (int i = 0; i < 6; ++ i)
2372        {
2373                VertexContainer vertices;
2374       
2375                for (int j = 0; j < 4; ++ j)
2376                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2377
2378                candidates.push_back(new Polygon3(vertices));
2379        }
2380
2381        for (int i = 0; i < (int)candidates.size(); ++ i)
2382        {
2383                // polygon is split by all other planes
2384                for (int j = 0; (j < (int)halfSpaces.size()) && candidates[i]; ++ j)
2385                {
2386                        if (i == j) // polygon and plane are coincident
2387                                continue;
2388
2389                        VertexContainer splitPts;
2390                        Polygon3 *frontPoly, *backPoly;
2391
2392                        const int cf = candidates[i]->
2393                                ClassifyPlane(halfSpaces[j], mEpsilon);
2394                       
2395                        switch (cf)
2396                        {
2397                                case Polygon3::SPLIT:
2398                                        frontPoly = new Polygon3();
2399                                        backPoly = new Polygon3();
2400
2401                                        candidates[i]->Split(halfSpaces[j],
2402                                                                                 *frontPoly,
2403                                                                                 *backPoly,
2404                                                                                 mEpsilon);
2405
2406                                        DEL_PTR(candidates[i]);
2407
2408                                        if (frontPoly->Valid(mEpsilon))
2409                                                candidates[i] = frontPoly;
2410                                        else
2411                                                DEL_PTR(frontPoly);
2412
2413                                        DEL_PTR(backPoly);
2414                                        break;
2415                                case Polygon3::BACK_SIDE:
2416                                        DEL_PTR(candidates[i]);
2417                                        break;
2418                                // just take polygon as it is
2419                                case Polygon3::FRONT_SIDE:
2420                                case Polygon3::COINCIDENT:
2421                                default:
2422                                        break;
2423                        }
2424                }
2425               
2426                if (candidates[i])
2427                        geom.mPolys.push_back(candidates[i]);
2428        }
2429}
2430
2431
2432typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2433
2434
2435int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2436                                                   const bool onlyUnmailed) const
2437{
2438        stack<bspNodePair> nodeStack;
2439       
2440        BspNodeGeometry nodeGeom;
2441        ConstructGeometry(n, nodeGeom);
2442       
2443        // split planes from the root to this node
2444        // needed to verify that we found neighbor leaf
2445        // TODO: really needed?
2446        vector<Plane3> halfSpaces;
2447        ExtractHalfSpaces(n, halfSpaces);
2448
2449
2450        BspNodeGeometry *rgeom = new BspNodeGeometry();
2451        ConstructGeometry(mRoot, *rgeom);
2452
2453        nodeStack.push(bspNodePair(mRoot, rgeom));
2454
2455        while (!nodeStack.empty())
2456        {
2457                BspNode *node = nodeStack.top().first;
2458                BspNodeGeometry *geom = nodeStack.top().second;
2459       
2460                nodeStack.pop();
2461
2462                if (node->IsLeaf())
2463                {
2464                        // test if this leaf is in valid view space
2465                        if (node->TreeValid() &&
2466                                (node != n) &&
2467                                (!onlyUnmailed || !node->Mailed()))
2468                        {
2469                                bool isAdjacent = true;
2470
2471                                if (1)
2472                                {
2473                                        // test all planes of current node if still adjacent
2474                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2475                                        {
2476                                                const int cf =
2477                                                        Polygon3::ClassifyPlane(geom->mPolys,
2478                                                                                                        halfSpaces[i],
2479                                                                                                        mEpsilon);
2480
2481                                                if (cf == Polygon3::BACK_SIDE)
2482                                                {
2483                                                        isAdjacent = false;
2484                                                }
2485                                        }
2486                                }
2487                                else
2488                                {
2489                                        // TODO: why is this wrong??
2490                                        // test all planes of current node if still adjacent
2491                                        for (int i = 0; (i < (int)nodeGeom.mPolys.size()) && isAdjacent; ++ i)
2492                                        {
2493                                                Polygon3 *poly = nodeGeom.mPolys[i];
2494
2495                                                const int cf =
2496                                                        Polygon3::ClassifyPlane(geom->mPolys,
2497                                                                                                        poly->GetSupportingPlane(),
2498                                                                                                        mEpsilon);
2499
2500                                                if (cf == Polygon3::BACK_SIDE)
2501                                                {
2502                                                        isAdjacent = false;
2503                                                }
2504                                        }
2505                                }
2506                                // neighbor was found
2507                                if (isAdjacent)
2508                                {       
2509                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2510                                }
2511                        }
2512                }
2513                else
2514                {
2515                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2516
2517                        const int cf = Polygon3::ClassifyPlane(nodeGeom.mPolys,
2518                                                                                                   interior->GetPlane(),
2519                                                                                                   mEpsilon);
2520                       
2521                        BspNode *front = interior->GetFront();
2522                        BspNode *back = interior->GetBack();
2523           
2524                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2525                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2526
2527                        geom->SplitGeometry(*fGeom,
2528                                                                *bGeom,
2529                                                                interior->GetPlane(),
2530                                                                mBox,
2531                                                                mEpsilon);
2532               
2533                        if (cf == Polygon3::FRONT_SIDE)
2534                        {
2535                                nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2536                                DEL_PTR(bGeom);
2537                        }
2538                        else
2539                        {
2540                                if (cf == Polygon3::BACK_SIDE)
2541                                {
2542                                        nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2543                                        DEL_PTR(fGeom);
2544                                }
2545                                else
2546                                {       // random decision
2547                                        nodeStack.push(bspNodePair(front, fGeom));
2548                                        nodeStack.push(bspNodePair(back, bGeom));
2549                                }
2550                        }
2551                }
2552       
2553                DEL_PTR(geom);
2554        }
2555
2556        return (int)neighbors.size();
2557}
2558
2559
2560BspLeaf *BspTree::GetRandomLeaf(const Plane3 &halfspace)
2561{
2562    stack<BspNode *> nodeStack;
2563        nodeStack.push(mRoot);
2564       
2565        int mask = rand();
2566 
2567        while (!nodeStack.empty())
2568        {
2569                BspNode *node = nodeStack.top();
2570                nodeStack.pop();
2571         
2572                if (node->IsLeaf())
2573                {
2574                        return dynamic_cast<BspLeaf *>(node);
2575                }
2576                else
2577                {
2578                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2579                        BspNode *next;
2580       
2581                        BspNodeGeometry geom;
2582                        // todo: not very efficient: constructs full cell everytime
2583                        ConstructGeometry(interior, geom);
2584
2585                        const int cf = Polygon3::ClassifyPlane(geom.mPolys,
2586                                                                                                   halfspace,
2587                                                                                                   mEpsilon);
2588
2589                        if (cf == Polygon3::BACK_SIDE)
2590                                next = interior->GetFront();
2591                        else
2592                                if (cf == Polygon3::FRONT_SIDE)
2593                                        next = interior->GetFront();
2594                        else
2595                        {
2596                                // random decision
2597                                if (mask & 1)
2598                                        next = interior->GetBack();
2599                                else
2600                                        next = interior->GetFront();
2601                                mask = mask >> 1;
2602                        }
2603
2604                        nodeStack.push(next);
2605                }
2606        }
2607       
2608        return NULL;
2609}
2610
2611
2612BspLeaf *BspTree::GetRandomLeaf(const bool onlyUnmailed)
2613{
2614        stack<BspNode *> nodeStack;
2615       
2616        nodeStack.push(mRoot);
2617
2618        int mask = rand();
2619       
2620        while (!nodeStack.empty())
2621        {
2622                BspNode *node = nodeStack.top();
2623                nodeStack.pop();
2624               
2625                if (node->IsLeaf())
2626                {
2627                        if ( (!onlyUnmailed || !node->Mailed()) )
2628                                return dynamic_cast<BspLeaf *>(node);
2629                }
2630                else
2631                {
2632                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2633
2634                        // random decision
2635                        if (mask & 1)
2636                                nodeStack.push(interior->GetBack());
2637                        else
2638                                nodeStack.push(interior->GetFront());
2639
2640                        mask = mask >> 1;
2641                }
2642        }
2643       
2644        return NULL;
2645}
2646
2647
2648void BspTree::AddToPvs(BspLeaf *leaf,
2649                                           const BoundedRayContainer &rays,
2650                                           int &sampleContributions,
2651                                           int &contributingSamples)
2652{
2653        sampleContributions = 0;
2654        contributingSamples = 0;
2655
2656    BoundedRayContainer::const_iterator it, it_end = rays.end();
2657
2658        ViewCell *vc = leaf->GetViewCell();
2659
2660        // add contributions from samples to the PVS
2661        for (it = rays.begin(); it != it_end; ++ it)
2662        {
2663                int contribution = 0;
2664                Ray *ray = (*it)->mRay;
2665                float relContribution;
2666                if (!ray->intersections.empty())
2667                  contribution += vc->GetPvs().AddSample(ray->intersections[0].mObject,
2668                                                                                                 1.0f,
2669                                                                                                 relContribution);
2670               
2671                if (ray->sourceObject.mObject)
2672                        contribution += vc->GetPvs().AddSample(ray->sourceObject.mObject,
2673                                                                                                   1.0f,
2674                                                                                                   relContribution);
2675               
2676                if (contribution)
2677                {
2678                        sampleContributions += contribution;
2679                        ++ contributingSamples;
2680                }
2681
2682                //if (ray->mFlags & Ray::STORE_BSP_INTERSECTIONS)
2683                //      ray->bspIntersections.push_back(Ray::BspIntersection((*it)->mMinT, this));
2684        }
2685}
2686
2687
2688int BspTree::ComputePvsSize(const BoundedRayContainer &rays) const
2689{
2690        int pvsSize = 0;
2691
2692        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
2693
2694        Intersectable::NewMail();
2695
2696        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2697        {
2698                Ray *ray = (*rit)->mRay;
2699               
2700                if (!ray->intersections.empty())
2701                {
2702                        if (!ray->intersections[0].mObject->Mailed())
2703                        {
2704                                ray->intersections[0].mObject->Mail();
2705                                ++ pvsSize;
2706                        }
2707                }
2708                if (ray->sourceObject.mObject)
2709                {
2710                        if (!ray->sourceObject.mObject->Mailed())
2711                        {
2712                                ray->sourceObject.mObject->Mail();
2713                                ++ pvsSize;
2714                        }
2715                }
2716        }
2717
2718        return pvsSize;
2719}
2720
2721
2722float BspTree::GetEpsilon() const
2723{
2724        return mEpsilon;
2725}
2726
2727
2728int BspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
2729                                                                        vector<MergeCandidate> &candidates)
2730{
2731        BspLeaf::NewMail();
2732       
2733        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2734
2735        int numCandidates = 0;
2736
2737        // find merge candidates and push them into queue
2738        for (it = leaves.begin(); it != it_end; ++ it)
2739        {
2740                BspLeaf *leaf = *it;
2741               
2742                // the same leaves must not be part of two merge candidates
2743                leaf->Mail();
2744                vector<BspLeaf *> neighbors;
2745                FindNeighbors(leaf, neighbors, true);
2746
2747                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2748
2749                // TODO: test if at least one ray goes from one leaf to the other
2750                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2751                {
2752                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
2753                        {
2754                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
2755                                candidates.push_back(mc);
2756
2757                                ++ numCandidates;
2758                                if ((numCandidates % 1000) == 0)
2759                                {
2760                                        cout << "collected " << numCandidates << " merge candidates" << endl;
2761                                }
2762                        }
2763                }
2764        }
2765
2766        Debug << "merge queue: " << (int)candidates.size() << endl;
2767        Debug << "leaves in queue: " << numCandidates << endl;
2768       
2769
2770        return (int)leaves.size();
2771}
2772
2773
2774int BspTree::CollectMergeCandidates(const VssRayContainer &rays,
2775                                                                        vector<MergeCandidate> &candidates)
2776{
2777        ViewCell::NewMail();
2778        long startTime = GetTime();
2779       
2780        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2781        ViewCellContainer::const_iterator iit;
2782
2783        int numLeaves = 0;
2784       
2785        BspLeaf::NewMail();
2786
2787        for (int i = 0; i < (int)rays.size(); ++ i)
2788        { 
2789                VssRay *ray = rays[i];
2790       
2791                // traverse leaves stored in the rays and compare and
2792                // merge consecutive leaves (i.e., the neighbors in the tree)
2793                if (ray->mViewCells.size() < 2)
2794                        continue;
2795
2796                iit = ray->mViewCells.begin();
2797                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
2798                BspLeaf *leaf = bspVc->mLeaf;
2799               
2800                // traverse intersections
2801                // consecutive leaves are neighbors => add them to queue
2802                for (; iit != ray->mViewCells.end(); ++ iit)
2803                {
2804                        // next pair
2805                        BspLeaf *prevLeaf = leaf;
2806                        bspVc = dynamic_cast<BspViewCell *>(*iit);
2807            leaf = bspVc->mLeaf;
2808
2809                        // view space not valid or same view cell
2810                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
2811                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
2812                                continue;
2813
2814                vector<BspLeaf *> &neighbors = neighborMap[leaf];
2815                       
2816                        bool found = false;
2817
2818                        // both leaves inserted in queue already =>
2819                        // look if double pair already exists
2820                        if (leaf->Mailed() && prevLeaf->Mailed())
2821                        {
2822                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2823                               
2824                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2825                                        if (*it == prevLeaf)
2826                                                found = true; // already in queue
2827                        }
2828               
2829                        if (!found)
2830                        {
2831                                // this pair is not in map yet
2832                                // => insert into the neighbor map and the queue
2833                                neighbors.push_back(prevLeaf);
2834                                neighborMap[prevLeaf].push_back(leaf);
2835
2836                                leaf->Mail();
2837                                prevLeaf->Mail();
2838               
2839                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
2840                               
2841                                candidates.push_back(mc);
2842
2843                                if (((int)candidates.size() % 1000) == 0)
2844                                {
2845                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
2846                                }
2847                        }
2848        }
2849        }
2850
2851        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2852        Debug << "merge queue: " << (int)candidates.size() << endl;
2853        Debug << "leaves in queue: " << numLeaves << endl;
2854
2855
2856        //-- collect the leaves which haven't been found by ray casting
2857#if 0
2858        cout << "finding additional merge candidates using geometry" << endl;
2859        vector<BspLeaf *> leaves;
2860        CollectLeaves(leaves, true);
2861        Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
2862        CollectMergeCandidates(leaves, candidates);
2863#endif
2864
2865        return numLeaves;
2866}
2867
2868
2869
2870
2871/***************************************************************/
2872/*              BspNodeGeometry Implementation                 */
2873/***************************************************************/
2874
2875
2876BspNodeGeometry::BspNodeGeometry(const BspNodeGeometry &rhs)
2877{
2878        mPolys.reserve(rhs.mPolys.size());
2879       
2880        PolygonContainer::const_iterator it, it_end = rhs.mPolys.end();
2881        for (it = rhs.mPolys.begin(); it != it_end; ++ it)
2882        {
2883                Polygon3 *poly = *it;
2884                mPolys.push_back(new Polygon3(*poly));
2885        }
2886}
2887
2888
2889BspNodeGeometry::~BspNodeGeometry()
2890{
2891        CLEAR_CONTAINER(mPolys);
2892}
2893
2894
2895float BspNodeGeometry::GetArea() const
2896{
2897        return Polygon3::GetArea(mPolys);
2898}
2899
2900
2901float BspNodeGeometry::GetVolume() const
2902{
2903        //-- compute volume using tetrahedralization of the geometry
2904        //   and adding the volume of the single tetrahedrons
2905        float volume = 0;
2906        const float f = 1.0f / 6.0f;
2907
2908        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2909
2910        // note: can take arbitrary point, e.g., the origin. However,
2911        // we rather take the center of mass to prevents precision errors
2912        const Vector3 center = CenterOfMass();
2913
2914        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2915        {
2916                Polygon3 *poly = *pit;
2917                const Vector3 v0 = poly->mVertices[0] - center;
2918
2919                for (int i = 1; i < (int)poly->mVertices.size() - 1; ++ i)
2920                {
2921                        const Vector3 v1 = poly->mVertices[i] - center;
2922                        const Vector3 v2 = poly->mVertices[i + 1] - center;
2923
2924                        volume += f * (DotProd(v0, CrossProd(v1, v2)));
2925                }
2926        }
2927
2928        return volume;
2929}
2930
2931
2932Vector3 BspNodeGeometry::CenterOfMass() const
2933{
2934        int n = 0;
2935
2936        Vector3 center(0,0,0);
2937
2938        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2939
2940        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2941        {
2942                Polygon3 *poly = *pit;
2943               
2944                VertexContainer::const_iterator vit, vit_end = poly->mVertices.end();
2945
2946                for(vit = poly->mVertices.begin(); vit != vit_end; ++ vit)
2947                {
2948                        center += *vit;
2949                        ++ n;
2950                }
2951        }
2952
2953        return center / (float)n;
2954}
2955
2956
2957void BspNodeGeometry::AddToMesh(Mesh &mesh)
2958{
2959        PolygonContainer::const_iterator it, it_end = mPolys.end();
2960       
2961        for (it = mPolys.begin(); it != mPolys.end(); ++ it)
2962        {
2963                (*it)->AddToMesh(mesh);
2964        }
2965}
2966
2967
2968void BspNodeGeometry::SplitGeometry(BspNodeGeometry &front,
2969                                                                        BspNodeGeometry &back,
2970                                                                        const Plane3 &splitPlane,
2971                                                                        const AxisAlignedBox3 &box,
2972                                                                        const float epsilon) const
2973{       
2974        // get cross section of new polygon
2975        Polygon3 *planePoly = box.CrossSection(splitPlane);
2976
2977        // split polygon with all other polygons
2978        planePoly = SplitPolygon(planePoly, epsilon);
2979
2980        //-- new polygon splits all other polygons
2981        for (int i = 0; i < (int)mPolys.size(); ++ i)
2982        {
2983                /// don't use epsilon here to get exact split planes
2984                const int cf =
2985                        mPolys[i]->ClassifyPlane(splitPlane, Limits::Small);
2986                       
2987                switch (cf)
2988                {
2989                        case Polygon3::SPLIT:
2990                                {
2991                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
2992
2993                                        Polygon3 *frontPoly = new Polygon3();
2994                                        Polygon3 *backPoly = new Polygon3();
2995                               
2996                                        poly->Split(splitPlane,
2997                                                                *frontPoly,
2998                                                                *backPoly,
2999                                                                epsilon);
3000
3001                                        DEL_PTR(poly);
3002
3003                                        if (frontPoly->Valid(epsilon))
3004                                                front.mPolys.push_back(frontPoly);
3005                                        else
3006                                                DEL_PTR(frontPoly);
3007
3008                                        if (backPoly->Valid(epsilon))
3009                                                back.mPolys.push_back(backPoly);
3010                                        else
3011                                                DEL_PTR(backPoly);
3012                                }
3013                               
3014                                break;
3015                        case Polygon3::BACK_SIDE:
3016                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));                     
3017                                break;
3018                        case Polygon3::FRONT_SIDE:
3019                                front.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));     
3020                                break;
3021                        case Polygon3::COINCIDENT:
3022                                //front.mPolys.push_back(CreateReversePolygon(mPolys[i]));
3023                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));
3024                                break;
3025                        default:
3026                                break;
3027                }
3028        }
3029
3030        //-- finally add the new polygon to the child node geometries
3031        if (planePoly)
3032        {
3033                // add polygon with normal pointing into positive half space to back cell
3034                back.mPolys.push_back(planePoly);
3035                // add polygon with reverse orientation to front cell
3036                front.mPolys.push_back(planePoly->CreateReversePolygon());
3037        }
3038}
3039
3040
3041Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
3042                                                                                const float epsilon) const
3043{
3044        if (!planePoly->Valid(epsilon))
3045                DEL_PTR(planePoly);
3046
3047        // polygon is split by all other planes
3048        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
3049        {
3050                Plane3 plane = mPolys[i]->GetSupportingPlane();
3051
3052                /// don't use epsilon here to get exact split planes
3053                const int cf =
3054                        planePoly->ClassifyPlane(plane, Limits::Small);
3055                       
3056                // split new polygon with all previous planes
3057                switch (cf)
3058                {
3059                        case Polygon3::SPLIT:
3060                                {
3061                                        Polygon3 *frontPoly = new Polygon3();
3062                                        Polygon3 *backPoly = new Polygon3();
3063
3064                                        planePoly->Split(plane,
3065                                                                         *frontPoly,
3066                                                                         *backPoly,
3067                                                                         epsilon);
3068                                       
3069                                        // don't need anymore
3070                                        DEL_PTR(planePoly);
3071                                        DEL_PTR(frontPoly);
3072
3073                                        // back polygon is belonging to geometry
3074                                        if (backPoly->Valid(epsilon))
3075                                                planePoly = backPoly;
3076                                        else
3077                                                DEL_PTR(backPoly);
3078                                }
3079                                break;
3080                        case Polygon3::FRONT_SIDE:
3081                                DEL_PTR(planePoly);
3082                break;
3083                        // polygon is taken as it is
3084                        case Polygon3::BACK_SIDE:
3085                        case Polygon3::COINCIDENT:
3086                        default:
3087                                break;
3088                }
3089        }
3090
3091        return planePoly;
3092}
3093
3094
3095ViewCell *
3096BspTree::GetViewCell(const Vector3 &point)
3097{
3098  if (mRoot == NULL)
3099        return NULL;
3100 
3101
3102  stack<BspNode *> nodeStack;
3103  nodeStack.push(mRoot);
3104 
3105  ViewCell *viewcell = NULL;
3106 
3107  while (!nodeStack.empty())  {
3108        BspNode *node = nodeStack.top();
3109        nodeStack.pop();
3110       
3111        if (node->IsLeaf()) {
3112          viewcell = dynamic_cast<BspLeaf *>(node)->mViewCell;
3113          break;
3114        } else {
3115         
3116          BspInterior *interior = dynamic_cast<BspInterior *>(node);
3117               
3118          // random decision
3119          if (interior->GetPlane().Side(point) < 0)
3120                nodeStack.push(interior->GetBack());
3121          else
3122                nodeStack.push(interior->GetFront());
3123        }
3124  }
3125 
3126  return viewcell;
3127}
3128
3129
3130void BspNodeGeometry::IncludeInBox(AxisAlignedBox3 &box)
3131{
3132        Polygon3::IncludeInBox(mPolys, box);
3133}
3134
3135
3136bool BspTree::Export(ofstream &stream)
3137{
3138        ExportNode(mRoot, stream);
3139
3140        return true;
3141}
3142
3143
3144void BspTree::ExportNode(BspNode *node, ofstream &stream)
3145{
3146        if (node->IsLeaf())
3147        {
3148                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3149                       
3150                int id = -1;
3151                if (leaf->GetViewCell() != mOutOfBoundsCell)
3152                        id = leaf->GetViewCell()->GetId();
3153
3154                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3155        }
3156        else
3157        {
3158                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3159       
3160                Plane3 plane = interior->GetPlane();
3161                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3162                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3163                           << plane.mD << "\">" << endl;
3164
3165                ExportNode(interior->GetBack(), stream);
3166                ExportNode(interior->GetFront(), stream);
3167
3168                stream << "</Interior>" << endl;
3169        }
3170}
Note: See TracBrowser for help on using the repository browser.