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

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

added spatial hierarchy based merge tree

Line 
1#include "Plane3.h"
2#include "ViewCellBsp.h"
3#include "Mesh.h"
4#include "common.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "Polygon3.h"
8#include "Ray.h"
9#include "AxisAlignedBox3.h"
10#include "Triangle3.h"
11#include "Tetrahedron3.h"
12#include "ViewCellsManager.h"
13#include "Exporter.h"
14#include "Plane3.h"
15#include <stack>
16
17
18
19//-- static members
20
21int BspNode::sMailId = 1;
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number splits in the tree.
25*/
26const float BspTree::sLeastPolySplitsTable[] = {0, 0, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for a balanced tree.
29*/
30const float BspTree::sBalancedPolysTable[] = {1, -1, 0, 0};
31
32/** Evaluates split plane classification with respect to the plane's
33        contribution for a minimum number of ray splits.
34*/
35const float BspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
36/** Evaluates split plane classification with respect to the plane's
37        contribution for balanced rays.
38*/
39const float BspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
40
41int BspTree::sFrontId = 0;
42int BspTree::sBackId = 0;
43int BspTree::sFrontAndBackId = 0;
44
45
46/****************************************************************/
47/*                  class BspNode implementation                */
48/****************************************************************/
49
50
51BspNode::BspNode():
52mParent(NULL), mTreeValid(true), mTimeStamp(0)
53{}
54
55
56BspNode::BspNode(BspInterior *parent):
57mParent(parent), mTreeValid(true)
58{}
59
60
61bool BspNode::IsRoot() const
62{
63        return mParent == NULL;
64}
65
66
67BspInterior *BspNode::GetParent()
68{
69        return mParent;
70}
71
72
73void BspNode::SetParent(BspInterior *parent)
74{
75        mParent = parent;
76}
77
78
79bool BspNode::IsSibling(BspNode *n) const
80{
81        return  ((this != n) && mParent &&
82                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
83}
84
85
86int BspNode::GetDepth() const
87{
88        int depth = 0;
89        BspNode *p = mParent;
90       
91        while (p)
92        {
93                p = p->mParent;
94                ++ depth;
95        }
96
97        return depth;
98}
99
100
101bool BspNode::TreeValid() const
102{
103        return mTreeValid;
104}
105
106
107void BspNode::SetTreeValid(const bool v)
108{
109        mTreeValid = v;
110}
111
112
113/****************************************************************/
114/*              class BspInterior implementation                */
115/****************************************************************/
116
117
118BspInterior::BspInterior(const Plane3 &plane):
119mPlane(plane), mFront(NULL), mBack(NULL)
120{}
121
122BspInterior::~BspInterior()
123{
124        DEL_PTR(mFront);
125        DEL_PTR(mBack);
126}
127
128bool BspInterior::IsLeaf() const
129{
130        return false;
131}
132
133BspNode *BspInterior::GetBack()
134{
135        return mBack;
136}
137
138BspNode *BspInterior::GetFront()
139{
140        return mFront;
141}
142
143Plane3 BspInterior::GetPlane() const
144{
145        return mPlane;
146}
147
148void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
149{
150        if (mBack == oldChild)
151                mBack = newChild;
152        else
153                mFront = newChild;
154}
155
156void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
157{
158    mBack = b;
159    mFront = f;
160}
161
162/****************************************************************/
163/*                  class BspLeaf implementation                */
164/****************************************************************/
165
166
167BspLeaf::BspLeaf(): mViewCell(NULL), mPvs(NULL)
168{
169}
170
171
172BspLeaf::~BspLeaf()
173{
174        DEL_PTR(mPvs);
175}
176
177
178BspLeaf::BspLeaf(ViewCell *viewCell):
179mViewCell(viewCell)
180{
181}
182
183
184BspLeaf::BspLeaf(BspInterior *parent):
185BspNode(parent), mViewCell(NULL), mPvs(NULL)
186{}
187
188
189
190BspLeaf::BspLeaf(BspInterior *parent, ViewCell *viewCell):
191BspNode(parent), mViewCell(viewCell), mPvs(NULL)
192{
193}
194
195ViewCell *BspLeaf::GetViewCell() const
196{
197        return mViewCell;
198}
199
200void BspLeaf::SetViewCell(ViewCell *viewCell)
201{
202        mViewCell = viewCell;
203}
204
205
206bool BspLeaf::IsLeaf() const
207{
208        return true;
209}
210
211
212/*********************************************************************/
213/*                       class BspTree implementation                */
214/*********************************************************************/
215
216BspTree::BspTree(): 
217mRoot(NULL),
218mUseAreaForPvs(false),
219mGenerateViewCells(true),
220mTimeStamp(1)
221{
222        Randomize(); // initialise random generator for heuristics
223
224        mOutOfBoundsCell = GetOrCreateOutOfBoundsCell();
225
226        //-- termination criteria for autopartition
227        environment->GetIntValue("BspTree.Termination.maxDepth", mTermMaxDepth);
228        environment->GetIntValue("BspTree.Termination.minPvs", mTermMinPvs);
229        environment->GetIntValue("BspTree.Termination.minPolygons", mTermMinPolys);
230        environment->GetIntValue("BspTree.Termination.minRays", mTermMinRays);
231        environment->GetFloatValue("BspTree.Termination.minProbability", mTermMinProbability); 
232        environment->GetFloatValue("BspTree.Termination.maxRayContribution", mTermMaxRayContribution);
233        environment->GetFloatValue("BspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
234
235        //-- factors for bsp tree split plane heuristics
236        environment->GetFloatValue("BspTree.Factor.verticalSplits", mVerticalSplitsFactor);
237        environment->GetFloatValue("BspTree.Factor.largestPolyArea", mLargestPolyAreaFactor);
238        environment->GetFloatValue("BspTree.Factor.blockedRays", mBlockedRaysFactor);
239        environment->GetFloatValue("BspTree.Factor.leastRaySplits", mLeastRaySplitsFactor);
240        environment->GetFloatValue("BspTree.Factor.balancedRays", mBalancedRaysFactor);
241        environment->GetFloatValue("BspTree.Factor.pvs", mPvsFactor);
242        environment->GetFloatValue("BspTree.Factor.leastSplits" , mLeastSplitsFactor);
243        environment->GetFloatValue("BspTree.Factor.balancedPolys", mBalancedPolysFactor);
244        environment->GetFloatValue("BspTree.Factor.balancedViewCells", mBalancedViewCellsFactor);
245        environment->GetFloatValue("BspTree.Termination.ct_div_ci", mCtDivCi);
246
247        //-- termination criteria for axis aligned split
248        environment->GetFloatValue("BspTree.Termination.AxisAligned.ct_div_ci", mAxisAlignedCtDivCi);
249        environment->GetFloatValue("BspTree.Termination.maxCostRatio", mMaxCostRatio);
250        environment->GetIntValue("BspTree.Termination.AxisAligned.minPolys",
251                                                         mTermMinPolysForAxisAligned);
252        environment->GetIntValue("BspTree.Termination.AxisAligned.minRays",
253                                                         mTermMinRaysForAxisAligned);
254        environment->GetIntValue("BspTree.Termination.AxisAligned.minObjects",
255                                                         mTermMinObjectsForAxisAligned);
256        //-- partition criteria
257        environment->GetIntValue("BspTree.maxPolyCandidates", mMaxPolyCandidates);
258        environment->GetIntValue("BspTree.maxRayCandidates", mMaxRayCandidates);
259        environment->GetIntValue("BspTree.splitPlaneStrategy", mSplitPlaneStrategy);
260        environment->GetFloatValue("BspTree.AxisAligned.splitBorder", mSplitBorder);
261        environment->GetIntValue("BspTree.maxTests", mMaxTests);
262        environment->GetIntValue("BspTree.Termination.maxViewCells", mMaxViewCells);
263
264        environment->GetFloatValue("BspTree.Construction.epsilon", mEpsilon);
265
266        mSubdivisionStats.open("subdivisionStats.log");
267
268    Debug << "BSP max depth: " << mTermMaxDepth << endl;
269        Debug << "BSP min PVS: " << mTermMinPvs << endl;
270        Debug << "BSP min probability: " << mTermMinProbability << endl;
271        Debug << "BSP max polys: " << mTermMinPolys << endl;
272        Debug << "BSP max rays: " << mTermMinRays << endl;
273        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
274        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
275
276        Debug << "Split plane strategy: ";
277        if (mSplitPlaneStrategy & RANDOM_POLYGON)
278                Debug << "random polygon ";
279        if (mSplitPlaneStrategy & AXIS_ALIGNED)
280                Debug << "axis aligned ";
281        if (mSplitPlaneStrategy & LEAST_SPLITS)     
282                Debug << "least splits ";
283        if (mSplitPlaneStrategy & BALANCED_POLYS)
284                Debug << "balanced polygons ";
285        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
286                Debug << "balanced view cells ";
287        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
288                Debug << "largest polygon area ";
289        if (mSplitPlaneStrategy & VERTICAL_AXIS)
290                Debug << "vertical axis ";
291        if (mSplitPlaneStrategy & BLOCKED_RAYS)
292                Debug << "blocked rays ";
293        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
294                Debug << "least ray splits ";
295        if (mSplitPlaneStrategy & BALANCED_RAYS)
296                Debug << "balanced rays ";
297        if (mSplitPlaneStrategy & PVS)
298                Debug << "pvs";
299
300        Debug << endl;
301}
302
303
304const BspTreeStatistics &BspTree::GetStatistics() const
305{
306        return mStat;
307}
308
309
310int BspTree::SplitPolygons(const Plane3 &plane,
311                                                   PolygonContainer &polys,
312                                                   PolygonContainer &frontPolys,
313                                                   PolygonContainer &backPolys,
314                                                   PolygonContainer &coincident) const
315{
316        int splits = 0;
317
318#ifdef _Debug
319        Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
320#endif
321
322        PolygonContainer::const_iterator it, it_end = polys.end();
323
324        for (it = polys.begin(); it != polys.end(); ++ it)     
325        {
326                Polygon3 *poly = *it;
327       
328                //-- classify polygon
329                const int cf = poly->ClassifyPlane(plane, mEpsilon);
330
331                switch (cf)
332                {
333                        case Polygon3::COINCIDENT:
334                                coincident.push_back(poly);
335                                break;                 
336                        case Polygon3::FRONT_SIDE:     
337                                frontPolys.push_back(poly);
338                                break;
339                        case Polygon3::BACK_SIDE:
340                                backPolys.push_back(poly);
341                                break;
342                        case Polygon3::SPLIT:
343                                {
344                                        Polygon3 *front_piece = new Polygon3(poly->mParent);
345                                        Polygon3 *back_piece = new Polygon3(poly->mParent);
346
347                                        //-- split polygon into front and back part
348                                        poly->Split(plane,
349                                                                *front_piece,
350                                                                *back_piece,
351                                                                mEpsilon);
352                                       
353                                        ++ splits; // increase number of splits
354
355                                        //-- inherit rays from parent polygon for blocked ray criterium
356                                        poly->InheritRays(*front_piece, *back_piece);
357                               
358                                        // check if polygons still valid
359                                        if (front_piece->Valid(mEpsilon))
360                                                frontPolys.push_back(front_piece);
361                                        else
362                                                DEL_PTR(front_piece);
363                               
364                                        if (back_piece->Valid(mEpsilon))
365                                                backPolys.push_back(back_piece);
366                                        else                           
367                                                DEL_PTR(back_piece);
368                               
369#ifdef _DEBUG
370                                        Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
371#endif
372                                        DEL_PTR(poly);
373                                }
374                                break;
375                        default:
376                Debug << "SHOULD NEVER COME HERE\n";
377                                break;
378                }
379        }
380
381        return splits;
382}
383
384
385void BspTreeStatistics::Print(ostream &app) const
386{
387        app << "===== BspTree statistics ===============\n";
388
389        app << setprecision(4);
390
391        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
392
393        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
394
395        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
396
397        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
398
399        app << "#N_POLYSPLITS ( Number of polygon splits )\n" << polySplits << "\n";
400
401        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits[0] + splits[1] + splits[2] << endl;
402
403        app << "#N_SPLITS ( Number of splits in axes x y z\n";
404
405        for (int i = 0; i < 3; ++ i)
406                app << splits[i] << " ";
407        app << endl;
408
409        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
410                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
411
412        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
413                << minPvsNodes * 100 / (double)Leaves() << endl;
414
415        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
416                << minRaysNodes * 100 / (double)Leaves() << endl;
417
418        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
419                << maxCostNodes * 100 / (double)Leaves() << endl;
420
421        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
422                << minProbabilityNodes * 100 / (double)Leaves() << endl;
423
424        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
425                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
426
427        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
428
429        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
430
431        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
432
433        app << "#N_INPUTPOLYGONS (number of input polygons )\n" << polys << endl;
434
435        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
436
437        app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
438        //app << "#N_PVS: " << pvs << endl;
439
440        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
441                 (polys + polySplits) / (double)polys << endl;
442       
443        app << "===== END OF BspTree statistics ==========\n";
444}
445
446
447BspTree::~BspTree()
448{
449        DEL_PTR(mRoot);
450
451        // TODO must be deleted if used!!
452        //if (mGenerateViewCells) DEL_PTR(mOutOfBoundsCell);
453}
454
455BspViewCell *BspTree::GetOutOfBoundsCell()
456{
457        return mOutOfBoundsCell;
458}
459
460
461BspNode *BspTree::GetRoot() const
462{
463        return mRoot;
464}
465
466BspViewCell *BspTree::GetOrCreateOutOfBoundsCell()
467{
468        if (!mOutOfBoundsCell)
469        {
470                mOutOfBoundsCell = new BspViewCell();
471                mOutOfBoundsCell->SetId(-1);
472                mOutOfBoundsCell->SetValid(false);
473        }
474
475        return mOutOfBoundsCell;
476}
477
478
479void BspTree::InsertViewCell(ViewCell *viewCell)
480{
481        PolygonContainer *polys = new PolygonContainer();
482
483        // don't generate new view cell, insert this one
484        mGenerateViewCells = false;
485        // extract polygons that guide the split process
486        mStat.polys += AddMeshToPolygons(viewCell->GetMesh(), *polys, viewCell);
487        mBox.Include(viewCell->GetBox()); // add to BSP aabb
488
489        InsertPolygons(polys);
490}
491
492
493void BspTree::InsertPolygons(PolygonContainer *polys)
494{       
495        BspTraversalStack tStack;
496
497        // traverse existing tree or create new tree
498    if (!mRoot)
499                mRoot = new BspLeaf();
500
501        tStack.push(BspTraversalData(mRoot,
502                                                                 polys,
503                                                                 0,
504                                                                 mOutOfBoundsCell,
505                                                                 new BoundedRayContainer(),
506                                                                 0,
507                                                                 mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
508                                                                 new BspNodeGeometry()));
509
510        while (!tStack.empty())
511        {
512                // filter polygons donw the tree
513                BspTraversalData tData = tStack.top();
514            tStack.pop();
515                       
516                if (!tData.mNode->IsLeaf())
517                {
518                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
519
520                        //-- filter view cell polygons down the tree until a leaf is reached
521                        if (!tData.mPolygons->empty())
522                        {
523                                PolygonContainer *frontPolys = new PolygonContainer();
524                                PolygonContainer *backPolys = new PolygonContainer();
525                                PolygonContainer coincident;
526
527                                int splits = 0;
528               
529                                // split viewcell polygons with respect to split plane
530                                splits += SplitPolygons(interior->GetPlane(),
531                                                                                *tData.mPolygons,
532                                                                                *frontPolys,
533                                                                                *backPolys,
534                                                                                coincident);
535                               
536                                // extract view cells associated with the split polygons
537                                ViewCell *frontViewCell = GetOrCreateOutOfBoundsCell();
538                                ViewCell *backViewCell = GetOrCreateOutOfBoundsCell();
539                       
540                                BspTraversalData frontData(interior->GetFront(),
541                                                                                   frontPolys,
542                                                                                   tData.mDepth + 1,
543                                                                                   mOutOfBoundsCell,   
544                                                                                   tData.mRays,
545                                                                                   tData.mPvs,
546                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
547                                                                                   new BspNodeGeometry());
548
549                                BspTraversalData backData(interior->GetBack(),
550                                                                                  backPolys,
551                                                                                  tData.mDepth + 1,
552                                                                                  mOutOfBoundsCell,     
553                                                                                  tData.mRays,
554                                                                                  tData.mPvs,
555                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
556                                                                                  new BspNodeGeometry());
557
558                                if (!mGenerateViewCells)
559                                {
560                                        ExtractViewCells(frontData,
561                                                                         backData,
562                                                                         coincident,
563                                                                         interior->mPlane);
564                                }
565
566                                // don't need coincident polygons anymore
567                                CLEAR_CONTAINER(coincident);
568
569                                mStat.polySplits += splits;
570
571                                // push the children on the stack
572                                tStack.push(frontData);
573                                tStack.push(backData);
574                        }
575
576                        // cleanup
577                        DEL_PTR(tData.mPolygons);
578                        DEL_PTR(tData.mRays);
579                }
580                else
581                {
582                        // reached leaf => subdivide current viewcell
583                        BspNode *subRoot = Subdivide(tStack, tData);
584                }
585        }
586}
587
588int BspTree::AddMeshToPolygons(Mesh *mesh,
589                                                           PolygonContainer &polys,
590                                                           MeshInstance *parent)
591{
592        FaceContainer::const_iterator fi;
593       
594        // copy the face data to polygons
595        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
596        {
597                Polygon3 *poly = new Polygon3((*fi), mesh);
598               
599                if (poly->Valid(mEpsilon))
600                {
601                        poly->mParent = parent; // set parent intersectable
602                        polys.push_back(poly);
603                }
604                else
605                        DEL_PTR(poly);
606        }
607        return (int)mesh->mFaces.size();
608}
609
610
611int BspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
612                                                          PolygonContainer &polys,
613                                                          int maxObjects)
614{
615        int limit = (maxObjects > 0) ?
616                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
617 
618        int polysSize = 0;
619
620        for (int i = 0; i < limit; ++ i)
621        {
622                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
623                {
624                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
625                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
626                }
627        }
628
629        return polysSize;
630}
631
632
633int BspTree::AddToPolygonSoup(const ObjectContainer &objects,
634                                                          PolygonContainer &polys,
635                                                          int maxObjects,
636                                                          bool addToBbox)
637{
638        int limit = (maxObjects > 0) ?
639                Min((int)objects.size(), maxObjects) : (int)objects.size();
640 
641        for (int i = 0; i < limit; ++i)
642        {
643                Intersectable *object = objects[i];//*it;
644                Mesh *mesh = NULL;
645
646                switch (object->Type()) // extract the meshes
647                {
648                case Intersectable::MESH_INSTANCE:
649                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
650                        break;
651                case Intersectable::VIEW_CELL:
652                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
653                        break;
654                        // TODO: handle transformed mesh instances
655                default:
656                        Debug << "intersectable type not supported" << endl;
657                        break;
658                }
659               
660        if (mesh) // copy the mesh data to polygons
661                {
662                        if (addToBbox)
663                        {
664                                mBox.Include(object->GetBox()); // add to BSP tree aabb
665                        }
666               
667                        AddMeshToPolygons(mesh, polys, mOutOfBoundsCell);
668                }
669        }
670
671        return (int)polys.size();
672}
673
674
675void BspTree::Construct(const ViewCellContainer &viewCells)
676{
677        mStat.nodes = 1;
678        mBox.Initialize();      // initialise bsp tree bounding box
679
680        // copy view cell meshes into one big polygon soup
681        PolygonContainer *polys = new PolygonContainer();
682        mStat.polys = AddToPolygonSoup(viewCells, *polys);
683
684        // view cells are given
685        mGenerateViewCells = false;
686        // construct tree from the view cell polygons
687        Construct(polys, new BoundedRayContainer());
688}
689
690
691void BspTree::Construct(const ObjectContainer &objects)
692{
693        mStat.nodes = 1;
694        mBox.Initialize();      // initialise bsp tree bounding box
695       
696        PolygonContainer *polys = new PolygonContainer();
697
698        mGenerateViewCells = true;
699        // copy mesh instance polygons into one big polygon soup
700        mStat.polys = AddToPolygonSoup(objects, *polys);
701
702        // construct tree from polygon soup
703        Construct(polys, new BoundedRayContainer());
704}
705
706
707void BspTree::PreprocessPolygons(PolygonContainer &polys)
708{
709        // preprocess: throw out polygons coincident to the view space box (not needed)
710        PolygonContainer boxPolys;
711        mBox.ExtractPolys(boxPolys);
712        vector<Plane3> boxPlanes;
713
714        PolygonContainer::iterator pit, pit_end = boxPolys.end();
715
716        // extract planes of box
717        // TODO: can be done more elegantly than first extracting polygons
718        // and take their planes
719        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
720        {
721                boxPlanes.push_back((*pit)->GetSupportingPlane());
722        }
723
724        pit_end = polys.end();
725
726        for (pit = polys.begin(); pit != pit_end; ++ pit)
727        {
728                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
729               
730                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
731                {
732                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
733
734                        if (cf == Polygon3::COINCIDENT)
735                        {
736                                DEL_PTR(*pit);
737                                //Debug << "coincident!!" << endl;
738                        }
739                }
740        }
741
742        // remove deleted entries
743        for (int i = 0; i < (int)polys.size(); ++ i)
744        {
745                while (!polys[i] && (i < (int)polys.size()))
746                {
747                        swap(polys[i], polys.back());
748                        polys.pop_back();
749                }
750        }
751}
752
753
754
755void BspTree::Construct(const RayContainer &sampleRays,
756                                                AxisAlignedBox3 *forcedBoundingBox)
757{
758    mStat.nodes = 1;
759        mBox.Initialize();      // initialise BSP tree bounding box
760       
761        if (forcedBoundingBox)
762                mBox = *forcedBoundingBox;
763
764        PolygonContainer *polys = new PolygonContainer();
765        BoundedRayContainer *rays = new BoundedRayContainer();
766
767        RayContainer::const_iterator rit, rit_end = sampleRays.end();
768
769        // generate view cells
770        mGenerateViewCells = true;
771
772        long startTime = GetTime();
773
774        Debug << "**** Extracting polygons from rays ****\n";
775
776        std::map<Face *, Polygon3 *> facePolyMap;
777
778        //-- extract polygons intersected by the rays
779        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
780        {
781                Ray *ray = *rit;
782       
783                // get ray-face intersection. Store polygon representing the rays together
784                // with rays intersecting the face.
785                if (!ray->intersections.empty())
786                {
787                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->intersections[0].mObject);
788                        Face *face = obj->GetMesh()->mFaces[ray->intersections[0].mFace];
789
790                        std::map<Face *, Polygon3 *>::iterator it = facePolyMap.find(face);
791
792                        if (it != facePolyMap.end())
793                        {
794                                //store rays if needed for heuristics
795                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
796                                        (*it).second->mPiercingRays.push_back(ray);
797                        }
798                        else
799                        {       //store rays if needed for heuristics
800                                Polygon3 *poly = new Polygon3(face, obj->GetMesh());
801                                poly->mParent = obj;
802                                polys->push_back(poly);
803
804                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
805                                        poly->mPiercingRays.push_back(ray);
806
807                                facePolyMap[face] = poly;
808                        }
809                }
810        }
811       
812        facePolyMap.clear();
813
814        // compute bounding box
815        if (!forcedBoundingBox)
816                Polygon3::IncludeInBox(*polys, mBox);
817
818        //-- store rays
819        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
820        {
821                Ray *ray = *rit;
822        ray->SetId(-1); // reset id
823
824                float minT, maxT;
825                if (mBox.GetRaySegment(*ray, minT, maxT))
826                        rays->push_back(new BoundedRay(ray, minT, maxT));
827        }
828
829        // throw out bad polygons
830        PreprocessPolygons(*polys);
831
832        mStat.polys = (int)polys->size();
833
834        Debug << "**** Finished polygon extraction ****" << endl;
835        Debug << (int)polys->size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
836        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
837
838        Construct(polys, rays);
839}
840
841
842void BspTree::Construct(const ObjectContainer &objects,
843                                                const RayContainer &sampleRays,
844                                                AxisAlignedBox3 *forcedBoundingBox)
845{
846    mStat.nodes = 1;
847        mBox.Initialize();      // initialise BSP tree bounding box
848       
849        if (forcedBoundingBox)
850                mBox = *forcedBoundingBox;
851
852        BoundedRayContainer *rays = new BoundedRayContainer();
853        PolygonContainer *polys = new PolygonContainer();
854       
855        mGenerateViewCells = true;
856
857        // copy mesh instance polygons into one big polygon soup
858        mStat.polys = AddToPolygonSoup(objects, *polys, 0, !forcedBoundingBox);
859
860
861        RayContainer::const_iterator rit, rit_end = sampleRays.end();
862
863        //-- store rays
864        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
865        {
866                Ray *ray = *rit;
867        ray->SetId(-1); // reset id
868
869                float minT, maxT;
870                if (mBox.GetRaySegment(*ray, minT, maxT))
871                        rays->push_back(new BoundedRay(ray, minT, maxT));
872        }
873
874        PreprocessPolygons(*polys);
875        Debug << "tree has " << (int)polys->size() << " polys, " << (int)sampleRays.size() << " rays" << endl;
876        Construct(polys, rays);
877}
878
879
880void BspTree::Construct(PolygonContainer *polys, BoundedRayContainer *rays)
881{
882        BspTraversalStack tStack;
883
884        mRoot = new BspLeaf();
885
886        // constrruct root node geometry
887        BspNodeGeometry *geom = new BspNodeGeometry();
888        ConstructGeometry(mRoot, *geom);
889
890        BspTraversalData tData(mRoot,
891                                                   polys,
892                                                   0,
893                                                   GetOrCreateOutOfBoundsCell(),
894                                                   rays,
895                                                   ComputePvsSize(*rays),
896                                                   mUseAreaForPvs ? geom->GetArea() : geom->GetVolume(),
897                                                   geom);
898
899        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
900        mTotalPvsSize = tData.mPvs;
901       
902        mSubdivisionStats
903                        << "#ViewCells\n1\n" <<  endl
904                        << "#RenderCostDecrease\n0\n" << endl
905                        << "#TotalRenderCost\n" << mTotalCost << endl
906                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
907
908        tStack.push(tData);
909
910        // used for intermediate time measurements and progress
911        long interTime = GetTime();     
912        int nleaves = 500;
913
914        mStat.Start();
915        cout << "Contructing bsp tree ...\n";
916        long startTime = GetTime();
917        while (!tStack.empty())
918        {
919                tData = tStack.top();
920
921            tStack.pop();
922
923                // subdivide leaf node
924                BspNode *r = Subdivide(tStack, tData);
925
926                if (r == mRoot)
927            Debug << "BSP tree construction time spent at root: "
928                                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl;
929
930                if (mStat.Leaves() >= nleaves)
931                {
932                        nleaves += 500;
933                       
934                        cout << "leaves=" << mStat.Leaves() << endl;
935                        Debug << "needed "
936                                  << TimeDiff(interTime, GetTime())*1e-3
937                                  << " secs to create 500 leaves" << endl;
938                        interTime = GetTime();
939                }
940        }
941
942        cout << "finished\n";
943
944        mStat.Stop();
945}
946
947
948bool BspTree::TerminationCriteriaMet(const BspTraversalData &data) const
949{
950        return
951                (((int)data.mPolygons->size() <= mTermMinPolys) ||
952                 ((int)data.mRays->size() <= mTermMinRays) ||
953                 (data.mPvs <= mTermMinPvs) ||
954                 (data.mProbability <= mTermMinProbability) ||
955                 (data.mDepth >= mTermMaxDepth) ||
956                 (mStat.Leaves() >= mMaxViewCells) ||
957                 (data.GetAvgRayContribution() > mTermMaxRayContribution));
958}
959
960
961BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData)
962{
963        //-- terminate traversal 
964        if (TerminationCriteriaMet(tData))             
965        {
966                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
967       
968                BspViewCell *viewCell;
969
970                // generate new view cell for each leaf
971                if (mGenerateViewCells)
972                        viewCell = new BspViewCell();
973                else
974                        // add view cell to leaf
975                        viewCell = dynamic_cast<BspViewCell *>(tData.mViewCell);
976               
977                leaf->SetViewCell(viewCell);
978                viewCell->mLeaf = leaf;
979
980                if (mUseAreaForPvs)
981                        viewCell->SetArea(tData.mProbability);
982                else
983                        viewCell->SetVolume(tData.mProbability);
984               
985                //-- add pvs
986                if (viewCell != mOutOfBoundsCell)
987                {
988                        int conSamp = 0, sampCon = 0;
989                        AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
990                       
991                        mStat.contributingSamples += conSamp;
992                        mStat.sampleContributions += sampCon;
993                }
994
995                EvaluateLeafStats(tData);
996               
997                //-- clean up
998               
999                // discard polygons
1000                CLEAR_CONTAINER(*tData.mPolygons);
1001                // discard rays
1002                CLEAR_CONTAINER(*tData.mRays);
1003
1004                DEL_PTR(tData.mPolygons);
1005                DEL_PTR(tData.mRays);
1006                DEL_PTR(tData.mGeometry);
1007
1008                return leaf;
1009        }
1010
1011        //-- continue subdivision
1012        PolygonContainer coincident;
1013       
1014        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1015                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1016        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
1017                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
1018
1019
1020        // create new interior node and two leaf nodes
1021        BspInterior *interior =
1022                SubdivideNode(tData, tFrontData, tBackData, coincident);
1023
1024
1025        if (1)
1026        {
1027                int pvsData = tData.mPvs;
1028
1029                float cData = (float)pvsData * tData.mProbability;
1030                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
1031                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
1032
1033                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
1034               
1035                mTotalCost += costDecr;
1036                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - pvsData;
1037
1038                mSubdivisionStats
1039                        << "#ViewCells\n" << mStat.Leaves() << endl
1040                        << "#RenderCostDecrease\n" << -costDecr << endl
1041                        << "#TotalRenderCost\n" << mTotalCost << endl
1042                        << "#AvgRenderCost\n" << mTotalPvsSize / mStat.Leaves() << endl;
1043        }
1044
1045        // extract view cells from coincident polygons according to plane normal
1046    // only if front or back polygons are empty
1047        if (!mGenerateViewCells)
1048        {
1049                ExtractViewCells(tFrontData,
1050                                                 tBackData,
1051                                                 coincident,
1052                                                 interior->mPlane);                     
1053        }
1054
1055        // don't need coincident polygons anymory
1056        CLEAR_CONTAINER(coincident);
1057
1058        // push the children on the stack
1059        tStack.push(tFrontData);
1060        tStack.push(tBackData);
1061
1062        // cleanup
1063        DEL_PTR(tData.mNode);
1064
1065        DEL_PTR(tData.mPolygons);
1066        DEL_PTR(tData.mRays);
1067        DEL_PTR(tData.mGeometry);               
1068       
1069        return interior;
1070}
1071
1072
1073void BspTree::ExtractViewCells(BspTraversalData &frontData,
1074                                                           BspTraversalData &backData,
1075                                                           const PolygonContainer &coincident,
1076                                                           const Plane3 &splitPlane) const
1077{
1078        // if not empty, tree is further subdivided => don't have to find view cell
1079        bool foundFront = !frontData.mPolygons->empty();
1080        bool foundBack = !frontData.mPolygons->empty();
1081
1082        PolygonContainer::const_iterator it =
1083                coincident.begin(), it_end = coincident.end();
1084
1085        //-- find first view cells in front and back leafs
1086        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
1087        {
1088                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
1089                {
1090                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1091                        foundBack = true;
1092                }
1093                else
1094                {
1095                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1096                        foundFront = true;
1097                }
1098        }
1099}
1100
1101
1102BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
1103                                                                        BspTraversalData &frontData,
1104                                                                        BspTraversalData &backData,
1105                                                                        PolygonContainer &coincident)
1106{
1107        mStat.nodes += 2;
1108       
1109        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1110
1111       
1112       
1113        // select subdivision plane
1114        BspInterior *interior =
1115                new BspInterior(SelectPlane(leaf, tData));
1116       
1117       
1118#ifdef _DEBUG
1119        Debug << interior << endl;
1120#endif
1121       
1122
1123        // subdivide rays into front and back rays
1124        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
1125       
1126       
1127
1128        // subdivide polygons with plane
1129        mStat.polySplits += SplitPolygons(interior->GetPlane(),
1130                                                                          *tData.mPolygons,
1131                                                                          *frontData.mPolygons,
1132                                                                          *backData.mPolygons,
1133                                                                          coincident);
1134
1135       
1136
1137    // compute pvs
1138        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1139        backData.mPvs = ComputePvsSize(*backData.mRays);
1140
1141        // split geometry and compute area
1142        if (1)
1143        {
1144                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1145                                                                           *backData.mGeometry,
1146                                                                           interior->mPlane,
1147                                                                           mBox,
1148                                                                           //0.000000000001);
1149                                                                           mEpsilon);
1150       
1151               
1152                if (mUseAreaForPvs)
1153                {
1154                        frontData.mProbability = frontData.mGeometry->GetArea();
1155                        backData.mProbability = backData.mGeometry->GetArea();
1156                }
1157                else
1158                {
1159                        frontData.mProbability = frontData.mGeometry->GetVolume();
1160                        backData.mProbability = tData.mProbability - frontData.mProbability;
1161                }
1162        }
1163
1164        //-- create front and back leaf
1165
1166        BspInterior *parent = leaf->GetParent();
1167
1168        // replace a link from node's parent
1169        if (!leaf->IsRoot())
1170        {
1171                parent->ReplaceChildLink(leaf, interior);
1172                interior->SetParent(parent);
1173        }
1174        else // new root
1175        {
1176                mRoot = interior;
1177        }
1178
1179        // and setup child links
1180        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1181       
1182        frontData.mNode = interior->GetFront();
1183        backData.mNode = interior->GetBack();
1184       
1185        interior->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.