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

Revision 648, 77.1 KB checked in by mattausch, 18 years ago (diff)

removed problems with bsp due to polygons equal to scene box faces. removing
this polyogns in a preprocessing step. also using this for vsp bsp tree, because it
is generally a good thing.

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