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

Revision 684, 78.0 KB checked in by mattausch, 18 years ago (diff)

found bug when creating geometry

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                float probability = tData.mProbability;
984
985                if (mUseAreaForPvs)
986                        viewCell->SetArea(probability);
987                else
988                        viewCell->SetVolume(probability);
989
990                //-- add pvs
991                if (viewCell != mOutOfBoundsCell)
992                {
993                        int conSamp = 0, sampCon = 0;
994                        AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
995                       
996                        mStat.contributingSamples += conSamp;
997                        mStat.sampleContributions += sampCon;
998                }
999
1000                EvaluateLeafStats(tData);
1001               
1002                //-- clean up
1003               
1004                // discard polygons
1005                CLEAR_CONTAINER(*tData.mPolygons);
1006                // discard rays
1007                CLEAR_CONTAINER(*tData.mRays);
1008
1009                DEL_PTR(tData.mPolygons);
1010                DEL_PTR(tData.mRays);
1011                DEL_PTR(tData.mGeometry);
1012
1013                return leaf;
1014        }
1015
1016        //-- continue subdivision
1017        PolygonContainer coincident;
1018       
1019        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1020                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1021        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1022                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1023
1024
1025        // create new interior node and two leaf nodes
1026        BspInterior *interior =
1027                SubdivideNode(tData, tFrontData, tBackData, coincident);
1028
1029
1030        if (1)
1031        {
1032                int pvsData = tData.mPvs;
1033
1034                float cData = (float)pvsData * tData.mProbability;
1035                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
1036                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
1037
1038                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
1039               
1040                mTotalCost += costDecr;
1041                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - pvsData;
1042
1043                mSubdivisionStats
1044                        << "#ViewCells\n" << mStat.Leaves() << endl
1045                        << "#RenderCostDecrease\n" << -costDecr << endl
1046                        << "#TotalRenderCost\n" << mTotalCost << endl
1047                        << "#AvgRenderCost\n" << mTotalPvsSize / mStat.Leaves() << endl;
1048        }
1049
1050        // extract view cells from coincident polygons according to plane normal
1051    // only if front or back polygons are empty
1052        if (!mGenerateViewCells)
1053        {
1054                ExtractViewCells(tFrontData,
1055                                                 tBackData,
1056                                                 coincident,
1057                                                 interior->mPlane);                     
1058        }
1059
1060        // don't need coincident polygons anymory
1061        CLEAR_CONTAINER(coincident);
1062
1063        // push the children on the stack
1064        tStack.push(tFrontData);
1065        tStack.push(tBackData);
1066
1067        // cleanup
1068        DEL_PTR(tData.mNode);
1069
1070        DEL_PTR(tData.mPolygons);
1071        DEL_PTR(tData.mRays);
1072        DEL_PTR(tData.mGeometry);               
1073       
1074        return interior;
1075}
1076
1077
1078void BspTree::ExtractViewCells(BspTraversalData &frontData,
1079                                                           BspTraversalData &backData,
1080                                                           const PolygonContainer &coincident,
1081                                                           const Plane3 &splitPlane) const
1082{
1083        // if not empty, tree is further subdivided => don't have to find view cell
1084        bool foundFront = !frontData.mPolygons->empty();
1085        bool foundBack = !frontData.mPolygons->empty();
1086
1087        PolygonContainer::const_iterator it =
1088                coincident.begin(), it_end = coincident.end();
1089
1090        //-- find first view cells in front and back leafs
1091        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
1092        {
1093                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
1094                {
1095                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1096                        foundBack = true;
1097                }
1098                else
1099                {
1100                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1101                        foundFront = true;
1102                }
1103        }
1104}
1105
1106
1107BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
1108                                                                        BspTraversalData &frontData,
1109                                                                        BspTraversalData &backData,
1110                                                                        PolygonContainer &coincident)
1111{
1112        mStat.nodes += 2;
1113       
1114        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1115
1116       
1117       
1118        // select subdivision plane
1119        BspInterior *interior =
1120                new BspInterior(SelectPlane(leaf, tData));
1121       
1122       
1123#ifdef _DEBUG
1124        Debug << interior << endl;
1125#endif
1126       
1127
1128        // subdivide rays into front and back rays
1129        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
1130       
1131       
1132
1133        // subdivide polygons with plane
1134        mStat.polySplits += SplitPolygons(interior->GetPlane(),
1135                                                                          *tData.mPolygons,
1136                                                                          *frontData.mPolygons,
1137                                                                          *backData.mPolygons,
1138                                                                          coincident);
1139
1140       
1141
1142    // compute pvs
1143        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1144        backData.mPvs = ComputePvsSize(*backData.mRays);
1145
1146        // split geometry and compute area
1147        if (1)
1148        {
1149                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1150                                                                           *backData.mGeometry,
1151                                                                           interior->mPlane,
1152                                                                           mBox,
1153                                                                           //0.000000000001);
1154                                                                           mEpsilon);
1155       
1156               
1157                if (mUseAreaForPvs)
1158                {
1159                        frontData.mProbability = frontData.mGeometry->GetArea();
1160                        backData.mProbability = backData.mGeometry->GetArea();
1161                }
1162                else
1163                {
1164                        frontData.mProbability = frontData.mGeometry->GetVolume();
1165                        backData.mProbability = tData.mProbability - frontData.mProbability;
1166                }
1167        }
1168
1169        //-- create front and back leaf
1170
1171        BspInterior *parent = leaf->GetParent();
1172
1173        // replace a link from node's parent
1174        if (!leaf->IsRoot())
1175        {
1176                parent->ReplaceChildLink(leaf, interior);
1177                interior->SetParent(parent);
1178        }
1179        else // new root
1180        {
1181                mRoot = interior;
1182        }
1183
1184        // and setup child links
1185        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1186       
1187        frontData.mNode = interior->GetFront();
1188        backData.mNode = interior->GetBack();
1189       
1190        interior->mTimeStamp = mTimeStamp ++;
1191       
1192        //DEL_PTR(leaf);
1193        return interior;
1194}
1195
1196
1197void BspTree::SortSplitCandidates(const PolygonContainer &polys,
1198                                                                  const int axis,
1199                                                                  vector<SortableEntry> &splitCandidates) const
1200{
1201        splitCandidates.clear();
1202
1203        int requestedSize = 2 * (int)polys.size();
1204        // creates a sorted split candidates array 
1205        splitCandidates.reserve(requestedSize);
1206
1207        PolygonContainer::const_iterator it, it_end = polys.end();
1208
1209        AxisAlignedBox3 box;
1210
1211        // insert all queries
1212        for(it = polys.begin(); it != it_end; ++ it)
1213        {
1214                box.Initialize();
1215                box.Include(*(*it));
1216               
1217                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
1218                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
1219        }
1220
1221        stable_sort(splitCandidates.begin(), splitCandidates.end());
1222}
1223
1224
1225float BspTree::BestCostRatio(const PolygonContainer &polys,
1226                                                         const AxisAlignedBox3 &box,
1227                                                         const int axis,
1228                                                         float &position,
1229                                                         int &objectsBack,
1230                                                         int &objectsFront) const
1231{
1232        vector<SortableEntry> splitCandidates;
1233
1234        SortSplitCandidates(polys, axis, splitCandidates);
1235       
1236        // go through the lists, count the number of objects left and right
1237        // and evaluate the following cost funcion:
1238        // C = ct_div_ci  + (ol + or)/queries
1239       
1240        int objectsLeft = 0, objectsRight = (int)polys.size();
1241       
1242        float minBox = box.Min(axis);
1243        float maxBox = box.Max(axis);
1244        float boxArea = box.SurfaceArea();
1245 
1246        float minBand = minBox + mSplitBorder * (maxBox - minBox);
1247        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
1248       
1249        float minSum = 1e20f;
1250        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
1251
1252        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
1253        {
1254                switch ((*ci).type)
1255                {
1256                        case SortableEntry::POLY_MIN:
1257                                ++ objectsLeft;
1258                                break;
1259                        case SortableEntry::POLY_MAX:
1260                            -- objectsRight;
1261                                break;
1262                        default:
1263                                break;
1264                }
1265               
1266                if ((*ci).value > minBand && (*ci).value < maxBand)
1267                {
1268                        AxisAlignedBox3 lbox = box;
1269                        AxisAlignedBox3 rbox = box;
1270                        lbox.SetMax(axis, (*ci).value);
1271                        rbox.SetMin(axis, (*ci).value);
1272
1273                        const float sum = objectsLeft * lbox.SurfaceArea() +
1274                                                          objectsRight * rbox.SurfaceArea();
1275     
1276                        if (sum < minSum)
1277                        {
1278                                minSum = sum;
1279                                position = (*ci).value;
1280
1281                                objectsBack = objectsLeft;
1282                                objectsFront = objectsRight;
1283                        }
1284                }
1285        }
1286 
1287        const float oldCost = (float)polys.size();
1288        const float newCost = mAxisAlignedCtDivCi + minSum / boxArea;
1289        const float ratio = newCost / oldCost;
1290
1291
1292#if 0
1293  Debug << "====================" << endl;
1294  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
1295      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
1296#endif
1297  return ratio;
1298}
1299
1300bool BspTree::SelectAxisAlignedPlane(Plane3 &plane,
1301                                                                         const PolygonContainer &polys) const
1302{
1303        AxisAlignedBox3 box;
1304        box.Initialize();
1305       
1306        // create bounding box of region
1307        Polygon3::IncludeInBox(polys, box);
1308       
1309        int objectsBack = 0, objectsFront = 0;
1310        int axis = 0;
1311        float costRatio = MAX_FLOAT;
1312        Vector3 position;
1313
1314        //-- area subdivision
1315        for (int i = 0; i < 3; ++ i)
1316        {
1317                float p = 0;
1318                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
1319               
1320                if (r < costRatio)
1321                {
1322                        costRatio = r;
1323                        axis = i;
1324                        position = p;
1325                }
1326        }
1327       
1328        if (costRatio >= mMaxCostRatio)
1329                return false;
1330
1331        Vector3 norm(0,0,0); norm[axis] = 1.0f;
1332        plane = Plane3(norm, position);
1333
1334        return true;
1335}
1336
1337
1338Plane3 BspTree::SelectPlane(BspLeaf *leaf, BspTraversalData &data)
1339{
1340        if ((!mMaxPolyCandidates || data.mPolygons->empty()) &&
1341                (!mMaxRayCandidates || data.mRays->empty()))
1342        {
1343                Debug << "Warning: No autopartition polygon candidate available\n";
1344       
1345                // return axis aligned split
1346                AxisAlignedBox3 box;
1347                box.Initialize();
1348       
1349                // create bounding box of region
1350                Polygon3::IncludeInBox(*data.mPolygons, box);
1351
1352                const int axis = box.Size().DrivingAxis();
1353                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1354
1355                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1356                return Plane3(norm, position);
1357        }
1358       
1359        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
1360                ((int)data.mPolygons->size() > mTermMinPolysForAxisAligned) &&
1361                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1362                ((mTermMinObjectsForAxisAligned < 0) ||
1363                 (Polygon3::ParentObjectsSize(*data.mPolygons) > mTermMinObjectsForAxisAligned)))
1364        {
1365                Plane3 plane;
1366                if (SelectAxisAlignedPlane(plane, *data.mPolygons))
1367                        return plane;
1368        }
1369
1370        // simplest strategy: just take next polygon
1371        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1372        {
1373        if (!data.mPolygons->empty())
1374                {
1375                        Polygon3 *nextPoly =
1376                                (*data.mPolygons)[(int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1))];
1377                        return nextPoly->GetSupportingPlane();
1378                }
1379                else
1380                {
1381                        const int candidateIdx = (int)RandomValue(0, (Real)((int)data.mRays->size() - 1));
1382                        BoundedRay *bRay = (*data.mRays)[candidateIdx];
1383
1384                        Ray *ray = bRay->mRay;
1385                                               
1386                        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1387                        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1388
1389                        const Vector3 pt = (maxPt + minPt) * 0.5;
1390
1391                        const Vector3 normal = ray->GetDir();
1392                       
1393                        return Plane3(normal, pt);
1394                }
1395
1396                return Plane3();
1397        }
1398
1399        // use heuristics to find appropriate plane
1400        return SelectPlaneHeuristics(leaf, data);
1401}
1402
1403
1404Plane3 BspTree::ChooseCandidatePlane(const BoundedRayContainer &rays) const
1405{       
1406        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1407        BoundedRay *bRay = rays[candidateIdx];
1408        Ray *ray = bRay->mRay;
1409
1410        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1411        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1412
1413        const Vector3 pt = (maxPt + minPt) * 0.5;
1414
1415        const Vector3 normal = ray->GetDir();
1416                       
1417        return Plane3(normal, pt);
1418}
1419
1420Plane3 BspTree::ChooseCandidatePlane2(const BoundedRayContainer &rays) const
1421{       
1422        Vector3 pt[3];
1423        int idx[3];
1424        int cmaxT = 0;
1425        int cminT = 0;
1426        bool chooseMin = false;
1427
1428        for (int j = 0; j < 3; j ++)
1429        {
1430                idx[j] = (int)RandomValue(0, Real((int)rays.size() * 2 - 1));
1431                               
1432                if (idx[j] >= (int)rays.size())
1433                {
1434                        idx[j] -= (int)rays.size();             
1435                        chooseMin = (cminT < 2);
1436                }
1437                else
1438                        chooseMin = (cmaxT < 2);
1439
1440                BoundedRay *bRay = rays[idx[j]];
1441                pt[j] = chooseMin ? bRay->mRay->Extrap(bRay->mMinT) :
1442                                                        bRay->mRay->Extrap(bRay->mMaxT);
1443        }       
1444                       
1445        return Plane3(pt[0], pt[1], pt[2]);
1446}
1447
1448Plane3 BspTree::ChooseCandidatePlane3(const BoundedRayContainer &rays) const
1449{       
1450        Vector3 pt[3];
1451       
1452        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1453        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1454
1455        // check if rays different
1456        if (idx1 == idx2)
1457                idx2 = (idx2 + 1) % (int)rays.size();
1458
1459        const BoundedRay *ray1 = rays[idx1];
1460        const BoundedRay *ray2 = rays[idx2];
1461
1462        // normal vector of the plane parallel to both lines
1463        const Vector3 norm =
1464                Normalize(CrossProd(ray1->mRay->GetDir(), ray2->mRay->GetDir()));
1465
1466        const Vector3 orig1 = ray1->mRay->Extrap(ray1->mMinT);
1467        const Vector3 orig2 = ray2->mRay->Extrap(ray2->mMinT);
1468
1469        // vector from line 1 to line 2
1470        const Vector3 vd = orig1 - orig2;
1471       
1472        // project vector on normal to get distance
1473        const float dist = DotProd(vd, norm);
1474
1475        // point on plane lies halfway between the two planes
1476        const Vector3 planePt = orig1 + norm * dist * 0.5;
1477
1478        return Plane3(norm, planePt);
1479}
1480
1481
1482Plane3 BspTree::SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data)
1483{
1484        float lowestCost = MAX_FLOAT;
1485        Plane3 bestPlane;
1486        // intermediate plane
1487        Plane3 plane;
1488
1489        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1490        int maxIdx = (int)data.mPolygons->size();
1491       
1492        for (int i = 0; i < limit; ++ i)
1493        {
1494                // assure that no index is taken twice
1495                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1496                               
1497                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1498
1499                // swap candidate to the end to avoid testing same plane
1500                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1501                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1502
1503                // evaluate current candidate
1504                const float candidateCost =
1505                        SplitPlaneCost(poly->GetSupportingPlane(), data);
1506
1507                if (candidateCost < lowestCost)
1508                {
1509                        bestPlane = poly->GetSupportingPlane();
1510                        lowestCost = candidateCost;
1511                }
1512        }
1513       
1514        //-- choose candidate planes extracted from rays
1515        for (int i = 0; i < mMaxRayCandidates; ++ i)
1516        {
1517                plane = ChooseCandidatePlane3(*data.mRays);
1518                const float candidateCost = SplitPlaneCost(plane, data);
1519
1520                if (candidateCost < lowestCost)
1521                {
1522                        bestPlane = plane;     
1523                        lowestCost = candidateCost;
1524                }
1525        }
1526
1527#ifdef _DEBUG
1528        Debug << "plane lowest cost: " << lowestCost << endl;
1529#endif
1530       
1531        return bestPlane;
1532}
1533
1534
1535float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1536                                                          const PolygonContainer &polys) const
1537{
1538        float val = 0;
1539
1540        float sumBalancedPolys = 0;
1541        float sumSplits = 0;
1542        float sumPolyArea = 0;
1543        float sumBalancedViewCells = 0;
1544        float sumBlockedRays = 0;
1545        float totalBlockedRays = 0;
1546        //float totalArea = 0;
1547        int totalViewCells = 0;
1548
1549        // need three unique ids for each type of view cell
1550        // for balanced view cells criterium
1551        ViewCell::NewMail();
1552        const int backId = ViewCell::sMailId;
1553        ViewCell::NewMail();
1554        const int frontId = ViewCell::sMailId;
1555        ViewCell::NewMail();
1556        const int frontAndBackId = ViewCell::sMailId;
1557
1558        bool useRand;
1559        int limit;
1560
1561        // choose test polyongs randomly if over threshold
1562        if ((int)polys.size() > mMaxTests)
1563        {
1564                useRand = true;
1565                limit = mMaxTests;
1566        }
1567        else
1568        {
1569                useRand = false;
1570                limit = (int)polys.size();
1571        }
1572
1573        for (int i = 0; i < limit; ++ i)
1574        {
1575                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1576
1577                Polygon3 *poly = polys[testIdx];
1578
1579        const int classification =
1580                        poly->ClassifyPlane(candidatePlane, mEpsilon);
1581
1582                if (mSplitPlaneStrategy & BALANCED_POLYS)
1583                        sumBalancedPolys += sBalancedPolysTable[classification];
1584               
1585                if (mSplitPlaneStrategy & LEAST_SPLITS)
1586                        sumSplits += sLeastPolySplitsTable[classification];
1587
1588                if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1589                {
1590                        if (classification == Polygon3::COINCIDENT)
1591                                sumPolyArea += poly->GetArea();
1592                        //totalArea += area;
1593                }
1594               
1595                if (mSplitPlaneStrategy & BLOCKED_RAYS)
1596                {
1597                        const float blockedRays = (float)poly->mPiercingRays.size();
1598               
1599                        if (classification == Polygon3::COINCIDENT)
1600                                sumBlockedRays += blockedRays;
1601                       
1602                        totalBlockedRays += blockedRays;
1603                }
1604
1605                // assign view cells to back or front according to classificaion
1606                if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1607                {
1608                        MeshInstance *viewCell = poly->mParent;
1609               
1610                        // assure that we only count a view cell
1611                        // once for the front and once for the back side of the plane
1612                        if (classification == Polygon3::FRONT_SIDE)
1613                        {
1614                                if ((viewCell->mMailbox != frontId) &&
1615                                        (viewCell->mMailbox != frontAndBackId))
1616                                {
1617                                        sumBalancedViewCells += 1.0;
1618
1619                                        if (viewCell->mMailbox != backId)
1620                                                viewCell->mMailbox = frontId;
1621                                        else
1622                                                viewCell->mMailbox = frontAndBackId;
1623                                       
1624                                        ++ totalViewCells;
1625                                }
1626                        }
1627                        else if (classification == Polygon3::BACK_SIDE)
1628                        {
1629                                if ((viewCell->mMailbox != backId) &&
1630                                    (viewCell->mMailbox != frontAndBackId))
1631                                {
1632                                        sumBalancedViewCells -= 1.0;
1633
1634                                        if (viewCell->mMailbox != frontId)
1635                                                viewCell->mMailbox = backId;
1636                                        else
1637                                                viewCell->mMailbox = frontAndBackId;
1638
1639                                        ++ totalViewCells;
1640                                }
1641                        }
1642                }
1643        }
1644
1645        const float polysSize = (float)polys.size() + Limits::Small;
1646
1647        // all values should be approx. between 0 and 1 so they can be combined
1648        // and scaled with the factors according to their importance
1649        if (mSplitPlaneStrategy & BALANCED_POLYS)
1650                val += mBalancedPolysFactor * fabs(sumBalancedPolys) / polysSize;
1651       
1652        if (mSplitPlaneStrategy & LEAST_SPLITS) 
1653                val += mLeastSplitsFactor * sumSplits / polysSize;
1654
1655        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1656                // HACK: polys.size should be total area so scaling is between 0 and 1
1657                val += mLargestPolyAreaFactor * (float)polys.size() / sumPolyArea;
1658
1659        if (mSplitPlaneStrategy & BLOCKED_RAYS)
1660                if (totalBlockedRays != 0)
1661                        val += mBlockedRaysFactor * (totalBlockedRays - sumBlockedRays) / totalBlockedRays;
1662
1663        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1664                val += mBalancedViewCellsFactor * fabs(sumBalancedViewCells) /
1665                        ((float)totalViewCells + Limits::Small);
1666       
1667        return val;
1668}
1669
1670
1671inline void BspTree::GenerateUniqueIdsForPvs()
1672{
1673        ViewCell::NewMail(); sBackId = ViewCell::sMailId;
1674        ViewCell::NewMail(); sFrontId = ViewCell::sMailId;
1675        ViewCell::NewMail(); sFrontAndBackId = ViewCell::sMailId;
1676}
1677
1678
1679float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1680                                                          const BoundedRayContainer &rays,
1681                                                          const int pvs,
1682                                                          const float probability,
1683                                                          const BspNodeGeometry &cell) const
1684{
1685        float val = 0;
1686
1687        float sumBalancedRays = 0;
1688        float sumRaySplits = 0;
1689
1690        int frontPvs = 0;
1691        int backPvs = 0;
1692
1693        // probability that view point lies in child
1694        float pOverall = 0;
1695        float pFront = 0;
1696        float pBack = 0;
1697
1698        const bool pvsUseLen = false;
1699
1700        if (mSplitPlaneStrategy & PVS)
1701        {
1702                // create unique ids for pvs heuristics
1703                GenerateUniqueIdsForPvs();
1704
1705                // construct child geometry with regard to the candidate split plane
1706                BspNodeGeometry frontCell;
1707                BspNodeGeometry backCell;
1708
1709                cell.SplitGeometry(frontCell,
1710                                                   backCell,
1711                                                   candidatePlane,
1712                                                   mBox,
1713                                                   mEpsilon);
1714
1715                if (mUseAreaForPvs)
1716                {
1717                        pFront = frontCell.GetArea();
1718                        pBack = backCell.GetArea();
1719                }
1720                else
1721                {
1722                        pFront = frontCell.GetVolume();
1723                        pBack = pOverall - pFront;
1724                }
1725               
1726
1727                pOverall = probability;
1728        }
1729                       
1730        bool useRand;
1731        int limit;
1732
1733        // choose test polyongs randomly if over threshold
1734        if ((int)rays.size() > mMaxTests)
1735        {
1736                useRand = true;
1737                limit = mMaxTests;
1738        }
1739        else
1740        {
1741                useRand = false;
1742                limit = (int)rays.size();
1743        }
1744
1745        for (int i = 0; i < limit; ++ i)
1746        {
1747                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1748       
1749                BoundedRay *bRay = rays[testIdx];
1750
1751                Ray *ray = bRay->mRay;
1752                const float minT = bRay->mMinT;
1753                const float maxT = bRay->mMaxT;
1754
1755                Vector3 entP, extP;
1756
1757                const int cf =
1758                        ray->ClassifyPlane(candidatePlane, minT, maxT, entP, extP);
1759
1760                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1761                {
1762                        sumBalancedRays += sBalancedRaysTable[cf];
1763                }
1764               
1765                if (mSplitPlaneStrategy & BALANCED_RAYS)
1766                {
1767                        sumRaySplits += sLeastRaySplitsTable[cf];
1768                }
1769
1770                if (mSplitPlaneStrategy & PVS)
1771                {
1772                        // in case the ray intersects an object
1773                        // assure that we only count the object
1774                        // once for the front and once for the back side of the plane
1775                       
1776                        // add the termination object
1777                        if (!ray->intersections.empty())
1778                                AddObjToPvs(ray->intersections[0].mObject, cf, frontPvs, backPvs);
1779                       
1780                        // add the source object
1781                        AddObjToPvs(ray->sourceObject.mObject, cf, frontPvs, backPvs);
1782                }
1783        }
1784
1785        const float raysSize = (float)rays.size() + Limits::Small;
1786
1787        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1788                val += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1789
1790        if (mSplitPlaneStrategy & BALANCED_RAYS)
1791                val += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
1792
1793        const float denom = pOverall * (float)pvs * 2.0f + Limits::Small;
1794
1795        if (mSplitPlaneStrategy & PVS)
1796        {
1797                val += mPvsFactor * (frontPvs * pFront + (backPvs * pBack)) / denom;
1798
1799                // give penalty to unbalanced split
1800                if (0)
1801                if (((pFront * 0.2 + Limits::Small) > pBack) ||
1802                        (pFront < (pBack * 0.2 + Limits::Small)))
1803                        val += 0.5;
1804        }
1805
1806       
1807#ifdef _DEBUG
1808        Debug << "totalpvs: " << pvs << " ptotal: " << pOverall
1809                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1810                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1811#endif
1812       
1813        return val;
1814}
1815
1816void BspTree::AddObjToPvs(Intersectable *obj,
1817                                                  const int cf,
1818                                                  int &frontPvs,
1819                                                  int &backPvs) const
1820{
1821        if (!obj)
1822                return;
1823        // TODO: does this really belong to no pvs?
1824        //if (cf == Ray::COINCIDENT) return;
1825
1826        // object belongs to both PVS
1827        const bool bothSides = (cf == Ray::FRONT_BACK) ||
1828                                                   (cf == Ray::BACK_FRONT) ||
1829                                                   (cf == Ray::COINCIDENT);
1830
1831        if ((cf == Ray::FRONT) || bothSides)
1832        {
1833                if ((obj->mMailbox != sFrontId) &&
1834                        (obj->mMailbox != sFrontAndBackId))
1835                {
1836                        ++ frontPvs;
1837
1838                        if (obj->mMailbox == sBackId)
1839                                obj->mMailbox = sFrontAndBackId;       
1840                        else
1841                                obj->mMailbox = sFrontId;                                                               
1842                }
1843        }
1844       
1845        if ((cf == Ray::BACK) || bothSides)
1846        {
1847                if ((obj->mMailbox != sBackId) &&
1848                        (obj->mMailbox != sFrontAndBackId))
1849                {
1850                        ++ backPvs;
1851
1852                        if (obj->mMailbox == sFrontId)
1853                                obj->mMailbox = sFrontAndBackId;
1854                        else
1855                                obj->mMailbox = sBackId;                               
1856                }
1857        }
1858}
1859
1860
1861float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1862                                                          BspTraversalData &data) const
1863{
1864        float val = 0;
1865
1866        if (mSplitPlaneStrategy & VERTICAL_AXIS)
1867        {
1868                Vector3 tinyAxis(0,0,0); tinyAxis[mBox.Size().TinyAxis()] = 1.0f;
1869                // we put a penalty on the dot product between the "tiny" vertical axis
1870                // and the split plane axis
1871                val += mVerticalSplitsFactor *
1872                           fabs(DotProd(candidatePlane.mNormal, tinyAxis));
1873        }
1874
1875        // the following criteria loop over all polygons to find the cost value
1876        if ((mSplitPlaneStrategy & BALANCED_POLYS)      ||
1877                (mSplitPlaneStrategy & LEAST_SPLITS)        ||
1878                (mSplitPlaneStrategy & LARGEST_POLY_AREA)   ||
1879                (mSplitPlaneStrategy & BALANCED_VIEW_CELLS) ||
1880                (mSplitPlaneStrategy & BLOCKED_RAYS))
1881        {
1882                val += SplitPlaneCost(candidatePlane, *data.mPolygons);
1883        }
1884
1885        // the following criteria loop over all rays to find the cost value
1886        if ((mSplitPlaneStrategy & BALANCED_RAYS)      ||
1887                (mSplitPlaneStrategy & LEAST_RAY_SPLITS)   ||
1888                (mSplitPlaneStrategy & PVS))
1889        {
1890                val += SplitPlaneCost(candidatePlane, *data.mRays, data.mPvs,
1891                                                          data.mProbability, *data.mGeometry);
1892        }
1893
1894        // return linear combination of the sums
1895        return val;
1896}
1897
1898void BspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1899{
1900        stack<BspNode *> nodeStack;
1901        nodeStack.push(mRoot);
1902 
1903        while (!nodeStack.empty())
1904        {
1905                BspNode *node = nodeStack.top();
1906   
1907                nodeStack.pop();
1908   
1909                if (node->IsLeaf())
1910                {
1911                        BspLeaf *leaf = (BspLeaf *)node;               
1912                        leaves.push_back(leaf);
1913                }
1914                else
1915                {
1916                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1917
1918                        nodeStack.push(interior->GetBack());
1919                        nodeStack.push(interior->GetFront());
1920                }
1921        }
1922}
1923
1924
1925AxisAlignedBox3 BspTree::GetBoundingBox() const
1926{
1927        return mBox;
1928}
1929
1930
1931void BspTree::EvaluateLeafStats(const BspTraversalData &data)
1932{
1933        // the node became a leaf -> evaluate stats for leafs
1934        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1935
1936        // store maximal and minimal depth
1937        if (data.mDepth > mStat.maxDepth)
1938                mStat.maxDepth = data.mDepth;
1939
1940        if (data.mDepth < mStat.minDepth)
1941                mStat.minDepth = data.mDepth;
1942
1943        // accumulate depth to compute average depth
1944        mStat.accumDepth += data.mDepth;
1945        // accumulate rays to compute rays /  leaf
1946        mStat.accumRays += (int)data.mRays->size();
1947
1948        if (data.mDepth >= mTermMaxDepth)
1949                ++ mStat.maxDepthNodes;
1950
1951        if (data.mPvs < mTermMinPvs)
1952                ++ mStat.minPvsNodes;
1953
1954        if ((int)data.mRays->size() < mTermMinRays)
1955                ++ mStat.minRaysNodes;
1956
1957        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1958                ++ mStat.maxRayContribNodes;
1959       
1960        if (data.mProbability <= mTermMinProbability)
1961                ++ mStat.minProbabilityNodes;
1962
1963#ifdef _DEBUG
1964        Debug << "BSP stats: "
1965                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1966                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1967                  << "Probability: " << data.mProbability << " (min: " << mTermMinProbability << "), "
1968                  << "#polygons: " << (int)data.mPolygons->size() << " (max: " << mTermMinPolys << "), "
1969                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1970                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1971                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1972#endif
1973}
1974
1975int
1976BspTree::_CastRay(Ray &ray)
1977{
1978        int hits = 0;
1979 
1980        stack<BspRayTraversalData> tStack;
1981 
1982        float maxt, mint;
1983
1984        if (!mBox.GetRaySegment(ray, mint, maxt))
1985                return 0;
1986
1987        ViewCell::NewMail();
1988
1989        Vector3 entp = ray.Extrap(mint);
1990        Vector3 extp = ray.Extrap(maxt);
1991 
1992        BspNode *node = mRoot;
1993        BspNode *farChild = NULL;
1994       
1995        while (1)
1996        {
1997                if (!node->IsLeaf())
1998                {
1999                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2000                       
2001                        Plane3 splitPlane = in->GetPlane();
2002                        const int entSide = splitPlane.Side(entp);
2003                        const int extSide = splitPlane.Side(extp);
2004
2005                        if (entSide < 0)
2006                        {
2007                                node = in->GetBack();
2008
2009                                if(extSide <= 0) // plane does not split ray => no far child
2010                                        continue;
2011                                       
2012                                farChild = in->GetFront(); // plane splits ray
2013
2014                        } else if (entSide > 0)
2015                        {
2016                                node = in->GetFront();
2017
2018                                if (extSide >= 0) // plane does not split ray => no far child
2019                                        continue;
2020
2021                                farChild = in->GetBack(); // plane splits ray                   
2022                        }
2023                        else // ray and plane are coincident
2024                        {
2025                                // WHAT TO DO IN THIS CASE ?
2026                                //break;
2027                                node = in->GetFront();
2028                                continue;
2029                        }
2030
2031                        // push data for far child
2032                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2033
2034                        // find intersection of ray segment with plane
2035                        float t;
2036                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2037                        maxt *= t;
2038                       
2039                } else // reached leaf => intersection with view cell
2040                {
2041                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2042     
2043                        if (!leaf->mViewCell->Mailed())
2044                        {
2045                                //ray.bspIntersections.push_back(Ray::BspIntersection(maxt, leaf));
2046                                leaf->mViewCell->Mail();
2047                                ++ hits;
2048                        }
2049                       
2050                        //-- fetch the next far child from the stack
2051                        if (tStack.empty())
2052                                break;
2053     
2054                        entp = extp;
2055                        mint = maxt; // NOTE: need this?
2056
2057                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2058                                break;
2059
2060                        BspRayTraversalData &s = tStack.top();
2061
2062                        node = s.mNode;
2063                        extp = s.mExitPoint;
2064                        maxt = s.mMaxT;
2065
2066                        tStack.pop();
2067                }
2068        }
2069
2070        return hits;
2071}
2072
2073
2074int BspTree::CastLineSegment(const Vector3 &origin,
2075                                                         const Vector3 &termination,
2076                                                         vector<ViewCell *> &viewcells)
2077{
2078        int hits = 0;
2079        stack<BspRayTraversalData> tStack;
2080
2081        float mint = 0.0f, maxt = 1.0f;
2082
2083        Intersectable::NewMail();
2084        ViewCell::NewMail();
2085
2086        Vector3 entp = origin;
2087        Vector3 extp = termination;
2088
2089        BspNode *node = mRoot;
2090        BspNode *farChild = NULL;
2091
2092        const float thresh = 1 ? 1e-6f : 0.0f;
2093
2094        while (1)
2095        {
2096                if (!node->IsLeaf()) 
2097                {
2098                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2099               
2100                        Plane3 splitPlane = in->GetPlane();
2101                       
2102                        const int entSide = splitPlane.Side(entp, thresh);
2103                        const int extSide = splitPlane.Side(extp, thresh);
2104
2105                        if (entSide < 0)
2106                        {
2107                                node = in->GetBack();
2108               
2109                                if(extSide <= 0) // plane does not split ray => no far child
2110                                        continue;
2111               
2112                                farChild = in->GetFront(); // plane splits ray
2113               
2114                        }
2115                        else if (entSide > 0)
2116                        {
2117                                node = in->GetFront();
2118                       
2119                                if (extSide >= 0) // plane does not split ray => no far child
2120                                        continue;
2121                       
2122                                farChild = in->GetBack(); // plane splits ray                   
2123                        }
2124                        else // ray and plane are coincident
2125                        {
2126                                // NOTE: what to do if ray is coincident with plane?
2127                                if (extSide < 0)
2128                                        node = in->GetBack();
2129                                else
2130                                        node = in->GetFront();
2131                                                               
2132                                continue; // no far child
2133                        }
2134               
2135                        // push data for far child
2136                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2137               
2138                        // find intersection of ray segment with plane
2139                        float t;
2140                        extp = splitPlane.FindIntersection(origin, extp, &t);
2141                        maxt *= t; 
2142                }
2143                else
2144                {
2145                        // reached leaf => intersection with view cell
2146                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2147               
2148                        if (!leaf->mViewCell->Mailed())
2149                        {
2150                                viewcells.push_back(leaf->mViewCell);
2151                                leaf->mViewCell->Mail();
2152                                hits++;
2153                        }
2154               
2155                        //-- fetch the next far child from the stack
2156                        if (tStack.empty())
2157                                break;
2158           
2159                        entp = extp;
2160                        mint = maxt; // NOTE: need this?
2161               
2162                        BspRayTraversalData &s = tStack.top();
2163               
2164                        node = s.mNode;
2165                        extp = s.mExitPoint;
2166                        maxt = s.mMaxT;
2167               
2168                        tStack.pop();
2169                }
2170        }
2171        return hits;
2172}
2173
2174
2175void BspTree::CollectViewCells(ViewCellContainer &viewCells) const
2176{
2177        stack<BspNode *> nodeStack;
2178        nodeStack.push(mRoot);
2179
2180        ViewCell::NewMail();
2181
2182        while (!nodeStack.empty())
2183        {
2184                BspNode *node = nodeStack.top();
2185                nodeStack.pop();
2186
2187                if (node->IsLeaf())
2188                {
2189                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
2190
2191                        if (!viewCell->Mailed())
2192                        {
2193                                viewCell->Mail();
2194                                viewCells.push_back(viewCell);
2195                        }
2196                }
2197                else
2198                {
2199                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2200
2201                        nodeStack.push(interior->GetFront());
2202                        nodeStack.push(interior->GetBack());
2203                }
2204        }
2205}
2206
2207
2208BspTreeStatistics &BspTree::GetStat()
2209{
2210        return mStat;
2211}
2212
2213
2214float BspTree::AccumulatedRayLength(BoundedRayContainer &rays) const
2215{
2216        float len = 0;
2217
2218        BoundedRayContainer::const_iterator it, it_end = rays.end();
2219
2220        for (it = rays.begin(); it != it_end; ++ it)
2221        {
2222                len += SqrDistance((*it)->mRay->Extrap((*it)->mMinT),
2223                                                   (*it)->mRay->Extrap((*it)->mMaxT));
2224        }
2225
2226        return len;
2227}
2228
2229
2230int BspTree::SplitRays(const Plane3 &plane,
2231                                           BoundedRayContainer &rays,
2232                                           BoundedRayContainer &frontRays,
2233                                           BoundedRayContainer &backRays)
2234{
2235        int splits = 0;
2236       
2237        while (!rays.empty())
2238        {
2239                BoundedRay *bRay = rays.back();
2240                Ray *ray = bRay->mRay;
2241                float minT = bRay->mMinT;
2242                float maxT = bRay->mMaxT;
2243
2244                rays.pop_back();
2245       
2246                Vector3 entP, extP;
2247
2248                const int cf =
2249                        ray->ClassifyPlane(plane, minT, maxT, entP, extP);
2250               
2251                // set id to ray classification
2252                ray->SetId(cf);
2253
2254                switch (cf)
2255                {
2256                case Ray::COINCIDENT: // TODO: should really discard ray?
2257                        frontRays.push_back(bRay);
2258                        //DEL_PTR(bRay);
2259                        break;
2260                case Ray::BACK:
2261                        backRays.push_back(bRay);
2262                        break;
2263                case Ray::FRONT:
2264                        frontRays.push_back(bRay);
2265                        break;
2266                case Ray::FRONT_BACK:
2267                        {
2268                                // find intersection of ray segment with plane
2269                                const float t = plane.FindT(ray->GetLoc(), extP);
2270                               
2271                                const float newT = t * maxT;
2272
2273                                frontRays.push_back(new BoundedRay(ray, minT, newT));
2274                                backRays.push_back(new BoundedRay(ray, newT, maxT));
2275
2276                                DEL_PTR(bRay);
2277                        }
2278                        break;
2279                case Ray::BACK_FRONT:
2280                        {
2281                                // find intersection of ray segment with plane
2282                                const float t = plane.FindT(ray->GetLoc(), extP);
2283                                const float newT = t * bRay->mMaxT;
2284
2285                                backRays.push_back(new BoundedRay(ray, minT, newT));
2286                                frontRays.push_back(new BoundedRay(ray, newT, maxT));
2287
2288                                DEL_PTR(bRay);
2289
2290                                ++ splits;
2291                        }
2292                        break;
2293                default:
2294                        Debug << "Should not come here 4" << endl;
2295                        break;
2296                }
2297        }
2298
2299        return splits;
2300}
2301
2302void BspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2303{
2304        BspNode *lastNode;
2305
2306        do
2307        {
2308                lastNode = n;
2309
2310                // want to get planes defining geometry of this node => don't take
2311                // split plane of node itself
2312                n = n->GetParent();
2313               
2314                if (n)
2315                {
2316                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2317                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2318
2319            if (interior->GetBack() != lastNode)
2320                                halfSpace.ReverseOrientation();
2321
2322                        halfSpaces.push_back(halfSpace);
2323                }
2324        }
2325        while (n);
2326}
2327
2328
2329
2330void BspTree::ConstructGeometry(ViewCell *vc,
2331                                                                BspNodeGeometry &vcGeom) const
2332{
2333        ViewCellContainer leaves;
2334        mViewCellsTree->CollectLeaves(vc, leaves);
2335
2336        ViewCellContainer::const_iterator it, it_end = leaves.end();
2337
2338        for (it = leaves.begin(); it != it_end; ++ it)
2339        {
2340                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2341                ConstructGeometry(l, vcGeom);
2342        }
2343}
2344
2345
2346void BspTree::ConstructGeometry(BspNode *n,
2347                                                                BspNodeGeometry &geom) const
2348{
2349        vector<Plane3> halfSpaces;
2350        ExtractHalfSpaces(n, halfSpaces);
2351
2352        PolygonContainer candidatePolys;
2353        vector<Plane3> candidatePlanes;
2354
2355        // bounded planes are added to the polygons
2356        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2357        {
2358                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2359
2360                if (p->Valid(mEpsilon))
2361                {
2362                        candidatePolys.push_back(p);
2363                        candidatePlanes.push_back(halfSpaces[i]);
2364                }
2365        }
2366
2367        // add faces of bounding box (also could be faces of the cell)
2368        for (int i = 0; i < 6; ++ i)
2369        {
2370                VertexContainer vertices;
2371
2372                for (int j = 0; j < 4; ++ j)
2373                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2374
2375                Polygon3 *poly = new Polygon3(vertices);
2376
2377                candidatePolys.push_back(poly);
2378                candidatePlanes.push_back(poly->GetSupportingPlane());
2379        }
2380
2381        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2382        {
2383                // polygon is split by all other planes
2384                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[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 =
2393                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2394                                                                                                 mEpsilon);
2395
2396                        switch (cf)
2397                        {
2398                                case Polygon3::SPLIT:
2399                                        frontPoly = new Polygon3();
2400                                        backPoly = new Polygon3();
2401
2402                                        candidatePolys[i]->Split(halfSpaces[j],
2403                                                                                         *frontPoly,
2404                                                                                         *backPoly,
2405                                                                                         mEpsilon);
2406
2407                                        DEL_PTR(candidatePolys[i]);
2408
2409                                        if (frontPoly->Valid(mEpsilon))
2410                                                candidatePolys[i] = frontPoly;
2411                                        else
2412                                                DEL_PTR(frontPoly);
2413
2414                                        DEL_PTR(backPoly);
2415                                        break;
2416                                // polygon outside of halfspace
2417                                case Polygon3::FRONT_SIDE:
2418                                        DEL_PTR(candidatePolys[i]);
2419                                        break;
2420                                // just take polygon as it is
2421                                case Polygon3::BACK_SIDE:
2422                                case Polygon3::COINCIDENT:
2423                                default:
2424                                        break;
2425                        }
2426                }
2427
2428                if (candidatePolys[i])
2429                {
2430                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2431                        //      geom.mPolys.push_back(candidates[i]);
2432                }
2433        }
2434}
2435
2436
2437void BspTree::SetViewCellsManager(ViewCellsManager *vcm)
2438{
2439        mViewCellsManager = vcm;
2440}
2441
2442
2443typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2444
2445
2446int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *>
2447                                                   &neighbors,
2448                                                   const bool onlyUnmailed) const
2449{
2450        stack<bspNodePair> nodeStack;
2451       
2452        BspNodeGeometry nodeGeom;
2453        ConstructGeometry(n, nodeGeom);
2454       
2455        // split planes from the root to this node
2456        // needed to verify that we found neighbor leaf
2457        // TODO: really needed?
2458        vector<Plane3> halfSpaces;
2459        ExtractHalfSpaces(n, halfSpaces);
2460
2461
2462        BspNodeGeometry *rgeom = new BspNodeGeometry();
2463        ConstructGeometry(mRoot, *rgeom);
2464
2465        nodeStack.push(bspNodePair(mRoot, rgeom));
2466
2467        while (!nodeStack.empty())
2468        {
2469                BspNode *node = nodeStack.top().first;
2470                BspNodeGeometry *geom = nodeStack.top().second;
2471       
2472                nodeStack.pop();
2473
2474                if (node->IsLeaf())
2475                {
2476                        // test if this leaf is in valid view space
2477                        if (node->TreeValid() &&
2478                                (node != n) &&
2479                                (!onlyUnmailed || !node->Mailed()))
2480                        {
2481                                bool isAdjacent = true;
2482
2483                                if (1)
2484                                {
2485                                        // test all planes of current node if still adjacent
2486                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2487                                        {
2488                                                const int cf =
2489                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2490                                                                                                        halfSpaces[i],
2491                                                                                                        mEpsilon);
2492
2493                                                if (cf == Polygon3::FRONT_SIDE)
2494                                                {
2495                                                        isAdjacent = false;
2496                                                }
2497                                        }
2498                                }
2499                                else
2500                                {
2501                                        // TODO: why is this wrong??
2502                                        // test all planes of current node if still adjacent
2503                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2504                                        {
2505                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2506
2507                                                const int cf =
2508                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2509                                                                                                        poly->GetSupportingPlane(),
2510                                                                                                        mEpsilon);
2511
2512                                                if (cf == Polygon3::FRONT_SIDE)
2513                                                {
2514                                                        isAdjacent = false;
2515                                                }
2516                                        }
2517                                }
2518                                // neighbor was found
2519                                if (isAdjacent)
2520                                {       
2521                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2522                                }
2523                        }
2524                }
2525                else
2526                {
2527                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2528
2529                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2530                                                                                                   interior->GetPlane(),
2531                                                                                                   mEpsilon);
2532                       
2533                        BspNode *front = interior->GetFront();
2534                        BspNode *back = interior->GetBack();
2535           
2536                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2537                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2538
2539                        geom->SplitGeometry(*fGeom,
2540                                                                *bGeom,
2541                                                                interior->GetPlane(),
2542                                                                mBox,
2543                                                                //0.0000001f);
2544                                                                mEpsilon);
2545               
2546                        if (cf == Polygon3::BACK_SIDE)
2547                        {
2548                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2549                                DEL_PTR(fGeom);
2550                        }
2551                        else
2552                        {
2553                                if (cf == Polygon3::FRONT_SIDE)
2554                                {
2555                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2556                                        DEL_PTR(bGeom);
2557                                }
2558                                else
2559                                {       // random decision
2560                                        nodeStack.push(bspNodePair(front, fGeom));
2561                                        nodeStack.push(bspNodePair(back, bGeom));
2562                                }
2563                        }
2564                }
2565       
2566                DEL_PTR(geom);
2567        }
2568
2569        return (int)neighbors.size();
2570}
2571
2572
2573BspLeaf *BspTree::GetRandomLeaf(const bool onlyUnmailed)
2574{
2575        stack<BspNode *> nodeStack;
2576       
2577        nodeStack.push(mRoot);
2578
2579        int mask = rand();
2580       
2581        while (!nodeStack.empty())
2582        {
2583                BspNode *node = nodeStack.top();
2584                nodeStack.pop();
2585               
2586                if (node->IsLeaf())
2587                {
2588                        if ( (!onlyUnmailed || !node->Mailed()) )
2589                                return dynamic_cast<BspLeaf *>(node);
2590                }
2591                else
2592                {
2593                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2594
2595                        // random decision
2596                        if (mask & 1)
2597                                nodeStack.push(interior->GetBack());
2598                        else
2599                                nodeStack.push(interior->GetFront());
2600
2601                        mask = mask >> 1;
2602                }
2603        }
2604       
2605        return NULL;
2606}
2607
2608
2609void BspTree::AddToPvs(BspLeaf *leaf,
2610                                           const BoundedRayContainer &rays,
2611                                           int &sampleContributions,
2612                                           int &contributingSamples)
2613{
2614        sampleContributions = 0;
2615        contributingSamples = 0;
2616
2617    BoundedRayContainer::const_iterator it, it_end = rays.end();
2618
2619        ViewCell *vc = leaf->GetViewCell();
2620
2621        // add contributions from samples to the PVS
2622        for (it = rays.begin(); it != it_end; ++ it)
2623        {
2624                int contribution = 0;
2625                Ray *ray = (*it)->mRay;
2626                float relContribution;
2627                if (!ray->intersections.empty())
2628                  contribution += vc->GetPvs().AddSample(ray->intersections[0].mObject,
2629                                                                                                 1.0f,
2630                                                                                                 relContribution);
2631               
2632                if (ray->sourceObject.mObject)
2633                        contribution += vc->GetPvs().AddSample(ray->sourceObject.mObject,
2634                                                                                                   1.0f,
2635                                                                                                   relContribution);
2636               
2637                if (contribution)
2638                {
2639                        sampleContributions += contribution;
2640                        ++ contributingSamples;
2641                }
2642
2643                //if (ray->mFlags & Ray::STORE_BSP_INTERSECTIONS)
2644                //      ray->bspIntersections.push_back(Ray::BspIntersection((*it)->mMinT, this));
2645        }
2646}
2647
2648
2649int BspTree::ComputePvsSize(const BoundedRayContainer &rays) const
2650{
2651        int pvsSize = 0;
2652
2653        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
2654
2655        Intersectable::NewMail();
2656
2657        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2658        {
2659                Ray *ray = (*rit)->mRay;
2660               
2661                if (!ray->intersections.empty())
2662                {
2663                        if (!ray->intersections[0].mObject->Mailed())
2664                        {
2665                                ray->intersections[0].mObject->Mail();
2666                                ++ pvsSize;
2667                        }
2668                }
2669                if (ray->sourceObject.mObject)
2670                {
2671                        if (!ray->sourceObject.mObject->Mailed())
2672                        {
2673                                ray->sourceObject.mObject->Mail();
2674                                ++ pvsSize;
2675                        }
2676                }
2677        }
2678
2679        return pvsSize;
2680}
2681
2682
2683float BspTree::GetEpsilon() const
2684{
2685        return mEpsilon;
2686}
2687
2688
2689int BspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
2690                                                                        vector<MergeCandidate> &candidates)
2691{
2692        BspLeaf::NewMail();
2693       
2694        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2695
2696        int numCandidates = 0;
2697
2698        // find merge candidates and push them into queue
2699        for (it = leaves.begin(); it != it_end; ++ it)
2700        {
2701                BspLeaf *leaf = *it;
2702               
2703                // the same leaves must not be part of two merge candidates
2704                leaf->Mail();
2705                vector<BspLeaf *> neighbors;
2706                FindNeighbors(leaf, neighbors, true);
2707
2708                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2709
2710                // TODO: test if at least one ray goes from one leaf to the other
2711                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2712                {
2713                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
2714                        {
2715                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
2716                                candidates.push_back(mc);
2717
2718                                ++ numCandidates;
2719                                if ((numCandidates % 1000) == 0)
2720                                {
2721                                        cout << "collected " << numCandidates << " merge candidates" << endl;
2722                                }
2723                        }
2724                }
2725        }
2726
2727        Debug << "merge queue: " << (int)candidates.size() << endl;
2728        Debug << "leaves in queue: " << numCandidates << endl;
2729       
2730
2731        return (int)leaves.size();
2732}
2733
2734
2735int BspTree::CollectMergeCandidates(const VssRayContainer &rays,
2736                                                                        vector<MergeCandidate> &candidates)
2737{
2738        ViewCell::NewMail();
2739        long startTime = GetTime();
2740       
2741        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2742        ViewCellContainer::const_iterator iit;
2743
2744        int numLeaves = 0;
2745       
2746        BspLeaf::NewMail();
2747
2748        for (int i = 0; i < (int)rays.size(); ++ i)
2749        { 
2750                VssRay *ray = rays[i];
2751       
2752                // traverse leaves stored in the rays and compare and
2753                // merge consecutive leaves (i.e., the neighbors in the tree)
2754                if (ray->mViewCells.size() < 2)
2755                        continue;
2756
2757                iit = ray->mViewCells.begin();
2758                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
2759                BspLeaf *leaf = bspVc->mLeaf;
2760               
2761                // traverse intersections
2762                // consecutive leaves are neighbors => add them to queue
2763                for (; iit != ray->mViewCells.end(); ++ iit)
2764                {
2765                        // next pair
2766                        BspLeaf *prevLeaf = leaf;
2767                        bspVc = dynamic_cast<BspViewCell *>(*iit);
2768            leaf = bspVc->mLeaf;
2769
2770                        // view space not valid or same view cell
2771                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
2772                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
2773                                continue;
2774
2775                vector<BspLeaf *> &neighbors = neighborMap[leaf];
2776                       
2777                        bool found = false;
2778
2779                        // both leaves inserted in queue already =>
2780                        // look if double pair already exists
2781                        if (leaf->Mailed() && prevLeaf->Mailed())
2782                        {
2783                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2784                               
2785                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2786                                        if (*it == prevLeaf)
2787                                                found = true; // already in queue
2788                        }
2789               
2790                        if (!found)
2791                        {
2792                                // this pair is not in map yet
2793                                // => insert into the neighbor map and the queue
2794                                neighbors.push_back(prevLeaf);
2795                                neighborMap[prevLeaf].push_back(leaf);
2796
2797                                leaf->Mail();
2798                                prevLeaf->Mail();
2799               
2800                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
2801                               
2802                                candidates.push_back(mc);
2803
2804                                if (((int)candidates.size() % 1000) == 0)
2805                                {
2806                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
2807                                }
2808                        }
2809        }
2810        }
2811
2812        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2813        Debug << "merge queue: " << (int)candidates.size() << endl;
2814        Debug << "leaves in queue: " << numLeaves << endl;
2815
2816
2817        //-- collect the leaves which haven't been found by ray casting
2818#if 0
2819        cout << "finding additional merge candidates using geometry" << endl;
2820        vector<BspLeaf *> leaves;
2821        CollectLeaves(leaves, true);
2822        Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
2823        CollectMergeCandidates(leaves, candidates);
2824#endif
2825
2826        return numLeaves;
2827}
2828
2829
2830
2831
2832/***************************************************************/
2833/*              BspNodeGeometry Implementation                 */
2834/***************************************************************/
2835
2836
2837BspNodeGeometry::BspNodeGeometry(const BspNodeGeometry &rhs)
2838{
2839        mPolys.reserve(rhs.mPolys.size());
2840       
2841        PolygonContainer::const_iterator it, it_end = rhs.mPolys.end();
2842
2843        int i = 0;
2844
2845        for (it = rhs.mPolys.begin(); it != it_end; ++ it)
2846        {
2847                Polygon3 *poly = *it;
2848                Add(new Polygon3(*poly), rhs.mPlanes[i ++]);
2849        }
2850}
2851
2852
2853BspNodeGeometry::~BspNodeGeometry()
2854{
2855        CLEAR_CONTAINER(mPolys);
2856}
2857
2858
2859int BspNodeGeometry::Size() const
2860{
2861        return (int)mPolys.size();
2862}
2863
2864
2865const PolygonContainer &BspNodeGeometry::GetPolys()
2866{
2867        return mPolys;
2868}
2869
2870
2871void BspNodeGeometry::Add(Polygon3 *p, const Plane3 &plane)
2872{
2873    mPolys.push_back(p);
2874        mPlanes.push_back(plane);
2875}
2876
2877
2878float BspNodeGeometry::GetArea() const
2879{
2880        return Polygon3::GetArea(mPolys);
2881}
2882
2883
2884float BspNodeGeometry::GetVolume() const
2885{
2886        //-- compute volume using tetrahedralization of the geometry
2887        //   and adding the volume of the single tetrahedrons
2888        float volume = 0;
2889        const float f = 1.0f / 6.0f;
2890
2891        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2892
2893        // note: can take arbitrary point, e.g., the origin. However,
2894        // we rather take the center of mass to prevents precision errors
2895        const Vector3 center = CenterOfMass();
2896
2897        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2898        {
2899                Polygon3 *poly = *pit;
2900                const Vector3 v0 = poly->mVertices[0] - center;
2901
2902                for (int i = 1; i < (int)poly->mVertices.size() - 1; ++ i)
2903                {
2904                        const Vector3 v1 = poly->mVertices[i] - center;
2905                        const Vector3 v2 = poly->mVertices[i + 1] - center;
2906
2907                        // more robust version using abs and the center of mass
2908                        volume += fabs (f * (DotProd(v0, CrossProd(v1, v2))));
2909                }
2910        }
2911
2912        return volume;
2913}
2914
2915
2916Vector3 BspNodeGeometry::CenterOfMass() const
2917{
2918        int n = 0;
2919
2920        Vector3 center(0,0,0);
2921
2922        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2923
2924        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2925        {
2926                Polygon3 *poly = *pit;
2927               
2928                VertexContainer::const_iterator vit, vit_end = poly->mVertices.end();
2929
2930                for(vit = poly->mVertices.begin(); vit != vit_end; ++ vit)
2931                {
2932                        center += *vit;
2933                        ++ n;
2934                }
2935        }
2936
2937        //Debug << "center: " << center << " new " << center / (float)n << endl;
2938
2939        return center / (float)n;
2940}
2941
2942
2943bool BspNodeGeometry::Valid() const
2944{
2945        if (mPolys.size() < 4)
2946                return false;
2947       
2948        return true;
2949}
2950
2951
2952void BspNodeGeometry::AddToMesh(Mesh &mesh)
2953{
2954        PolygonContainer::const_iterator it, it_end = mPolys.end();
2955       
2956        for (it = mPolys.begin(); it != mPolys.end(); ++ it)
2957        {
2958                (*it)->AddToMesh(mesh);
2959        }
2960}
2961
2962
2963bool BspNodeGeometry::SplitGeometry(BspNodeGeometry &front,
2964                                                                        BspNodeGeometry &back,
2965                                                                        const Plane3 &splitPlane,
2966                                                                        const AxisAlignedBox3 &box,
2967                                                                        const float epsilon) const
2968{       
2969        // get cross section of new polygon
2970        Polygon3 *planePoly = box.CrossSection(splitPlane);
2971        //Vector3 ndummy = planePoly->GetSupportingPlane().mNormal;
2972        // split polygon with all other polygons
2973        planePoly = SplitPolygon(planePoly, epsilon);
2974
2975        bool splitsGeom = (planePoly != NULL);
2976
2977        //-- new polygon splits all other polygons
2978        for (int i = 0; i < (int)mPolys.size()/* && planePoly*/; ++ i)
2979        {
2980                /// don't use epsilon here to get exact split planes
2981                const int cf =
2982                        mPolys[i]->ClassifyPlane(splitPlane, epsilon);
2983                       
2984                switch (cf)
2985                {
2986                        case Polygon3::SPLIT:
2987                                {
2988                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
2989
2990                                        Polygon3 *frontPoly = new Polygon3();
2991                                        Polygon3 *backPoly = new Polygon3();
2992                               
2993                                        poly->Split(splitPlane,
2994                                                                *frontPoly,
2995                                                                *backPoly,
2996                                                                epsilon);
2997
2998                                        DEL_PTR(poly);
2999
3000                                        if (frontPoly->Valid(epsilon))
3001                                        {
3002                                                front.Add(frontPoly, mPlanes[i]);
3003                                        }
3004                                        else
3005                                        {
3006                                                //Debug << "no f! " << endl;
3007                                                DEL_PTR(frontPoly);
3008                                        }
3009
3010                                        if (backPoly->Valid(epsilon))
3011                                        {
3012                                                back.Add(backPoly, mPlanes[i]);
3013                                        }
3014                                        else
3015                                        {
3016                                                //Debug << "no b! " << endl;
3017                                                DEL_PTR(backPoly);
3018                                        }
3019                                }
3020                               
3021                                break;
3022                        case Polygon3::BACK_SIDE:
3023                                back.Add(new Polygon3(mPolys[i]->mVertices), mPlanes[i]);
3024                                break;
3025                        case Polygon3::FRONT_SIDE:
3026                                front.Add(new Polygon3(mPolys[i]->mVertices), mPlanes[i]);
3027                                break;
3028                        // only put into back container (split should have no effect ...)
3029                        case Polygon3::COINCIDENT:
3030                                //Debug << "error should not come here" << endl;
3031                                splitsGeom = false;
3032
3033                                if (DotProd(mPlanes[i].mNormal, splitPlane.mNormal > 0))
3034                                        back.Add(new Polygon3(mPolys[i]->mVertices), mPlanes[i]);
3035                                else
3036                    front.Add(new Polygon3(mPolys[i]->mVertices), mPlanes[i]);
3037                                break;
3038                        default:
3039                                break;
3040                }
3041        }
3042
3043        //-- finally add the new polygon to the child node geometries
3044        if (planePoly)
3045        {
3046        // add polygon with reverse orientation to front cell
3047                Plane3 reversePlane(splitPlane);
3048                reversePlane.ReverseOrientation();
3049
3050                // add polygon with normal pointing into positive half space to back cell
3051                back.Add(planePoly, splitPlane);
3052                //back.mPolys.push_back(planePoly);
3053
3054                Polygon3 *reversePoly = planePoly->CreateReversePolygon();
3055                front.Add(reversePoly, reversePlane);
3056                //Debug << "poly normal : " << reversePoly->GetSupportingPlane().mNormal << " split plane normal " << reversePlane.mNormal << endl;
3057        }
3058       
3059
3060        return splitsGeom;
3061}
3062
3063
3064Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
3065                                                                                const float epsilon) const
3066{
3067        if (!planePoly->Valid(epsilon))
3068        {
3069                //Debug << "not valid!!" << endl;
3070                DEL_PTR(planePoly);
3071        }
3072        // polygon is split by all other planes
3073        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
3074        {
3075                //Plane3 plane = mPolys[i]->GetSupportingPlane();
3076                Plane3 plane = mPlanes[i];
3077
3078                /// don't use epsilon here to get exact split planes
3079                const int cf =
3080                        planePoly->ClassifyPlane(plane, epsilon);
3081                       
3082                // split new polygon with all previous planes
3083                switch (cf)
3084                {
3085                        case Polygon3::SPLIT:
3086                                {
3087                                        Polygon3 *frontPoly = new Polygon3();
3088                                        Polygon3 *backPoly = new Polygon3();
3089
3090                                        planePoly->Split(plane,
3091                                                                         *frontPoly,
3092                                                                         *backPoly,
3093                                                                         epsilon);
3094                                       
3095                                        // don't need anymore
3096                                        DEL_PTR(planePoly);
3097                                        DEL_PTR(frontPoly);
3098
3099                                        // back polygon is belonging to geometry
3100                                        if (backPoly->Valid(epsilon))
3101                                                planePoly = backPoly;
3102                                        else
3103                                                DEL_PTR(backPoly);
3104                                }
3105                                break;
3106                        case Polygon3::FRONT_SIDE:
3107                                DEL_PTR(planePoly);
3108                break;
3109                        // polygon is taken as it is
3110                        case Polygon3::BACK_SIDE:
3111                        case Polygon3::COINCIDENT:
3112                        default:
3113                                break;
3114                }
3115        }
3116
3117        return planePoly;
3118}
3119
3120
3121ViewCell *BspTree::GetViewCell(const Vector3 &point)
3122{
3123  if (mRoot == NULL)
3124        return NULL;
3125 
3126
3127  stack<BspNode *> nodeStack;
3128  nodeStack.push(mRoot);
3129 
3130  ViewCell *viewcell = NULL;
3131 
3132  while (!nodeStack.empty())  {
3133        BspNode *node = nodeStack.top();
3134        nodeStack.pop();
3135       
3136        if (node->IsLeaf()) {
3137          viewcell = dynamic_cast<BspLeaf *>(node)->mViewCell;
3138          break;
3139        } else {
3140         
3141          BspInterior *interior = dynamic_cast<BspInterior *>(node);
3142               
3143          // random decision
3144          if (interior->GetPlane().Side(point) < 0)
3145                nodeStack.push(interior->GetBack());
3146          else
3147                nodeStack.push(interior->GetFront());
3148        }
3149  }
3150 
3151  return viewcell;
3152}
3153
3154
3155void BspNodeGeometry::IncludeInBox(AxisAlignedBox3 &box)
3156{
3157        Polygon3::IncludeInBox(mPolys, box);
3158}
3159
3160
3161bool BspTree::Export(ofstream &stream)
3162{
3163        ExportNode(mRoot, stream);
3164
3165        return true;
3166}
3167
3168
3169void BspTree::ExportNode(BspNode *node, ofstream &stream)
3170{
3171        if (node->IsLeaf())
3172        {
3173                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3174                       
3175                int id = -1;
3176                if (leaf->GetViewCell() != mOutOfBoundsCell)
3177                        id = leaf->GetViewCell()->GetId();
3178
3179                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3180        }
3181        else
3182        {
3183                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3184       
3185                Plane3 plane = interior->GetPlane();
3186                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3187                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3188                           << plane.mD << "\">" << endl;
3189
3190                ExportNode(interior->GetBack(), stream);
3191                ExportNode(interior->GetFront(), stream);
3192
3193                stream << "</Interior>" << endl;
3194        }
3195}
Note: See TracBrowser for help on using the repository browser.