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

Revision 647, 78.0 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include "Plane3.h"
2#include "ViewCellBsp.h"
3#include "Mesh.h"
4#include "common.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "Polygon3.h"
8#include "Ray.h"
9#include "AxisAlignedBox3.h"
10#include "Triangle3.h"
11#include "Tetrahedron3.h"
12#include "ViewCellsManager.h"
13#include "Exporter.h"
14#include "Plane3.h"
15#include <stack>
16
17
18
19//-- static members
20
21int BspNode::sMailId = 1;
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number splits in the tree.
25*/
26const float BspTree::sLeastPolySplitsTable[] = {0, 0, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for a balanced tree.
29*/
30const float BspTree::sBalancedPolysTable[] = {1, -1, 0, 0};
31
32/** Evaluates split plane classification with respect to the plane's
33        contribution for a minimum number of ray splits.
34*/
35const float BspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
36/** Evaluates split plane classification with respect to the plane's
37        contribution for balanced rays.
38*/
39const float BspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
40
41int BspTree::sFrontId = 0;
42int BspTree::sBackId = 0;
43int BspTree::sFrontAndBackId = 0;
44
45
46/****************************************************************/
47/*                  class BspNode implementation                */
48/****************************************************************/
49
50
51BspNode::BspNode():
52mParent(NULL), mTreeValid(true), mTimeStamp(0)
53{}
54
55BspNode::BspNode(BspInterior *parent):
56mParent(parent), mTreeValid(true)
57{}
58
59
60bool BspNode::IsRoot() const
61{
62        return mParent == NULL;
63}
64
65
66BspInterior *BspNode::GetParent()
67{
68        return mParent;
69}
70
71
72void BspNode::SetParent(BspInterior *parent)
73{
74        mParent = parent;
75}
76
77
78bool BspNode::IsSibling(BspNode *n) const
79{
80        return  ((this != n) && mParent &&
81                         (mParent->GetFront() == n) || (mParent->GetBack() == n));
82}
83
84
85int BspNode::GetDepth() const
86{
87        int depth = 0;
88        BspNode *p = mParent;
89       
90        while (p)
91        {
92                p = p->mParent;
93                ++ depth;
94        }
95
96        return depth;
97}
98
99
100bool BspNode::TreeValid() const
101{
102        return mTreeValid;
103}
104
105
106void BspNode::SetTreeValid(const bool v)
107{
108        mTreeValid = v;
109}
110
111
112/****************************************************************/
113/*              class BspInterior implementation                */
114/****************************************************************/
115
116
117BspInterior::BspInterior(const Plane3 &plane):
118mPlane(plane), mFront(NULL), mBack(NULL)
119{}
120
121BspInterior::~BspInterior()
122{
123        DEL_PTR(mFront);
124        DEL_PTR(mBack);
125}
126
127bool BspInterior::IsLeaf() const
128{
129        return false;
130}
131
132BspNode *BspInterior::GetBack()
133{
134        return mBack;
135}
136
137BspNode *BspInterior::GetFront()
138{
139        return mFront;
140}
141
142Plane3 BspInterior::GetPlane() const
143{
144        return mPlane;
145}
146
147void BspInterior::ReplaceChildLink(BspNode *oldChild, BspNode *newChild)
148{
149        if (mBack == oldChild)
150                mBack = newChild;
151        else
152                mFront = newChild;
153}
154
155void BspInterior::SetupChildLinks(BspNode *b, BspNode *f)
156{
157    mBack = b;
158    mFront = f;
159}
160
161/****************************************************************/
162/*                  class BspLeaf implementation                */
163/****************************************************************/
164
165
166BspLeaf::BspLeaf(): mViewCell(NULL), mPvs(NULL)
167{
168}
169
170
171BspLeaf::~BspLeaf()
172{
173        DEL_PTR(mPvs);
174}
175
176
177BspLeaf::BspLeaf(ViewCell *viewCell):
178mViewCell(viewCell)
179{
180}
181
182
183BspLeaf::BspLeaf(BspInterior *parent):
184BspNode(parent), mViewCell(NULL), mPvs(NULL)
185{}
186
187
188
189BspLeaf::BspLeaf(BspInterior *parent, ViewCell *viewCell):
190BspNode(parent), mViewCell(viewCell), mPvs(NULL)
191{
192}
193
194ViewCell *BspLeaf::GetViewCell() const
195{
196        return mViewCell;
197}
198
199void BspLeaf::SetViewCell(ViewCell *viewCell)
200{
201        mViewCell = viewCell;
202}
203
204
205bool BspLeaf::IsLeaf() const
206{
207        return true;
208}
209
210
211/*********************************************************************/
212/*                       class BspTree implementation                */
213/*********************************************************************/
214
215BspTree::BspTree(): 
216mRoot(NULL),
217mUseAreaForPvs(false),
218mGenerateViewCells(true),
219mTimeStamp(0)
220{
221        Randomize(); // initialise random generator for heuristics
222
223        mOutOfBoundsCell = GetOrCreateOutOfBoundsCell();
224
225        //-- termination criteria for autopartition
226        environment->GetIntValue("BspTree.Termination.maxDepth", mTermMaxDepth);
227        environment->GetIntValue("BspTree.Termination.minPvs", mTermMinPvs);
228        environment->GetIntValue("BspTree.Termination.minPolygons", mTermMinPolys);
229        environment->GetIntValue("BspTree.Termination.minRays", mTermMinRays);
230        environment->GetFloatValue("BspTree.Termination.minProbability", mTermMinProbability); 
231        environment->GetFloatValue("BspTree.Termination.maxRayContribution", mTermMaxRayContribution);
232        environment->GetFloatValue("BspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
233
234        //-- factors for bsp tree split plane heuristics
235        environment->GetFloatValue("BspTree.Factor.verticalSplits", mVerticalSplitsFactor);
236        environment->GetFloatValue("BspTree.Factor.largestPolyArea", mLargestPolyAreaFactor);
237        environment->GetFloatValue("BspTree.Factor.blockedRays", mBlockedRaysFactor);
238        environment->GetFloatValue("BspTree.Factor.leastRaySplits", mLeastRaySplitsFactor);
239        environment->GetFloatValue("BspTree.Factor.balancedRays", mBalancedRaysFactor);
240        environment->GetFloatValue("BspTree.Factor.pvs", mPvsFactor);
241        environment->GetFloatValue("BspTree.Factor.leastSplits" , mLeastSplitsFactor);
242        environment->GetFloatValue("BspTree.Factor.balancedPolys", mBalancedPolysFactor);
243        environment->GetFloatValue("BspTree.Factor.balancedViewCells", mBalancedViewCellsFactor);
244        environment->GetFloatValue("BspTree.Termination.ct_div_ci", mCtDivCi);
245
246        //-- termination criteria for axis aligned split
247        environment->GetFloatValue("BspTree.Termination.AxisAligned.ct_div_ci", mAxisAlignedCtDivCi);
248        environment->GetFloatValue("BspTree.Termination.maxCostRatio", mMaxCostRatio);
249        environment->GetIntValue("BspTree.Termination.AxisAligned.minPolys",
250                                                         mTermMinPolysForAxisAligned);
251        environment->GetIntValue("BspTree.Termination.AxisAligned.minRays",
252                                                         mTermMinRaysForAxisAligned);
253        environment->GetIntValue("BspTree.Termination.AxisAligned.minObjects",
254                                                         mTermMinObjectsForAxisAligned);
255        //-- partition criteria
256        environment->GetIntValue("BspTree.maxPolyCandidates", mMaxPolyCandidates);
257        environment->GetIntValue("BspTree.maxRayCandidates", mMaxRayCandidates);
258        environment->GetIntValue("BspTree.splitPlaneStrategy", mSplitPlaneStrategy);
259        environment->GetFloatValue("BspTree.AxisAligned.splitBorder", mSplitBorder);
260        environment->GetIntValue("BspTree.maxTests", mMaxTests);
261        environment->GetIntValue("BspTree.Termination.maxViewCells", mMaxViewCells);
262
263        environment->GetFloatValue("BspTree.Construction.epsilon", mEpsilon);
264
265        mSubdivisionStats.open("subdivisionStats.log");
266
267    Debug << "BSP max depth: " << mTermMaxDepth << endl;
268        Debug << "BSP min PVS: " << mTermMinPvs << endl;
269        Debug << "BSP min probability: " << mTermMinProbability << endl;
270        Debug << "BSP max polys: " << mTermMinPolys << endl;
271        Debug << "BSP max rays: " << mTermMinRays << endl;
272        Debug << "BSP max polygon candidates: " << mMaxPolyCandidates << endl;
273        Debug << "BSP max plane candidates: " << mMaxRayCandidates << endl;
274
275        Debug << "Split plane strategy: ";
276        if (mSplitPlaneStrategy & RANDOM_POLYGON)
277                Debug << "random polygon ";
278        if (mSplitPlaneStrategy & AXIS_ALIGNED)
279                Debug << "axis aligned ";
280        if (mSplitPlaneStrategy & LEAST_SPLITS)     
281                Debug << "least splits ";
282        if (mSplitPlaneStrategy & BALANCED_POLYS)
283                Debug << "balanced polygons ";
284        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
285                Debug << "balanced view cells ";
286        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
287                Debug << "largest polygon area ";
288        if (mSplitPlaneStrategy & VERTICAL_AXIS)
289                Debug << "vertical axis ";
290        if (mSplitPlaneStrategy & BLOCKED_RAYS)
291                Debug << "blocked rays ";
292        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
293                Debug << "least ray splits ";
294        if (mSplitPlaneStrategy & BALANCED_RAYS)
295                Debug << "balanced rays ";
296        if (mSplitPlaneStrategy & PVS)
297                Debug << "pvs";
298
299        Debug << endl;
300}
301
302
303const BspTreeStatistics &BspTree::GetStatistics() const
304{
305        return mStat;
306}
307
308
309int BspTree::SplitPolygons(const Plane3 &plane,
310                                                   PolygonContainer &polys,
311                                                   PolygonContainer &frontPolys,
312                                                   PolygonContainer &backPolys,
313                                                   PolygonContainer &coincident) const
314{
315        int splits = 0;
316
317#ifdef _Debug
318        Debug << "splitting polygons of node " << this << " with plane " << mPlane << endl;
319#endif
320        PolygonContainer::const_iterator it, it_end = polys.end();
321
322        for (it = polys.begin(); it != polys.end(); ++ it)     
323        {
324                Polygon3 *poly = *it;
325       
326                //-- classify polygon
327                const int cf = poly->ClassifyPlane(plane, mEpsilon);
328
329                switch (cf)
330                {
331                        case Polygon3::COINCIDENT:
332                                coincident.push_back(poly);
333                                Debug << "!!!Coincident: " << poly->GetSupportingPlane() << endl;
334                                break;                 
335                        case Polygon3::FRONT_SIDE:     
336                                frontPolys.push_back(poly);
337                                Debug << "!!!front: " << poly->GetSupportingPlane() << endl;
338                                break;
339                        case Polygon3::BACK_SIDE:
340                                Debug << "!!!back: " << poly->GetSupportingPlane() << endl;
341                                backPolys.push_back(poly);
342                                break;
343                        case Polygon3::SPLIT:
344                                {
345                                        Polygon3 *front_piece = new Polygon3(poly->mParent);
346                                        Polygon3 *back_piece = new Polygon3(poly->mParent);
347
348                                        //-- split polygon into front and back part
349                                        poly->Split(plane,
350                                                                *front_piece,
351                                                                *back_piece,
352                                                                mEpsilon);
353                                       
354                                        ++ splits; // increase number of splits
355
356                                        //-- inherit rays from parent polygon for blocked ray criterium
357                                        poly->InheritRays(*front_piece, *back_piece);
358                               
359                                        // check if polygons still valid
360                                        if (front_piece->Valid(mEpsilon))
361                                                frontPolys.push_back(front_piece);
362                                        else
363                                                DEL_PTR(front_piece);
364                               
365                                        if (back_piece->Valid(mEpsilon))
366                                                backPolys.push_back(back_piece);
367                                        else                           
368                                                DEL_PTR(back_piece);
369                               
370#ifdef _DEBUG
371                                        Debug << "split " << *poly << endl << *front_piece << endl << *back_piece << endl;
372#endif
373                                        DEL_PTR(poly);
374                                }
375                                break;
376                        default:
377                Debug << "SHOULD NEVER COME HERE\n";
378                                break;
379                }
380        }
381
382        return splits;
383}
384
385
386void BspTreeStatistics::Print(ostream &app) const
387{
388        app << "===== BspTree statistics ===============\n";
389
390        app << setprecision(4);
391
392        app << "#N_CTIME  ( Construction time [s] )\n" << Time() << " \n";
393
394        app << "#N_NODES ( Number of nodes )\n" << nodes << "\n";
395
396        app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n";
397
398        app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n";
399
400        app << "#N_POLYSPLITS ( Number of polygon splits )\n" << polySplits << "\n";
401
402        app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits[0] + splits[1] + splits[2] << endl;
403
404        app << "#N_SPLITS ( Number of splits in axes x y z\n";
405
406        for (int i = 0; i < 3; ++ i)
407                app << splits[i] << " ";
408        app << endl;
409
410        app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n"
411                <<      maxDepthNodes * 100 / (double)Leaves() << endl;
412
413        app << "#N_PMINPVSLEAVES  ( Percentage of leaves with mininimal PVS )\n"
414                << minPvsNodes * 100 / (double)Leaves() << endl;
415
416        app << "#N_PMINRAYSLEAVES  ( Percentage of leaves with minimal number of rays)\n"
417                << minRaysNodes * 100 / (double)Leaves() << endl;
418
419        app << "#N_MAXCOSTNODES  ( Percentage of leaves with terminated because of max cost ratio )\n"
420                << maxCostNodes * 100 / (double)Leaves() << endl;
421
422        app << "#N_PMINPROBABILITYLEAVES  ( Percentage of leaves with mininum probability )\n"
423                << minProbabilityNodes * 100 / (double)Leaves() << endl;
424
425        app << "#N_PMAXRAYCONTRIBLEAVES  ( Percentage of leaves with maximal ray contribution )\n"
426                <<      maxRayContribNodes * 100 / (double)Leaves() << endl;
427
428        app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl;
429
430        app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl;
431
432        app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl;
433
434        app << "#N_INPUTPOLYGONS (number of input polygons )\n" << polys << endl;
435
436        app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl;
437
438        app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl;
439        //app << "#N_PVS: " << pvs << endl;
440
441        app << "#N_ROUTPUT_INPUT_POLYGONS ( ratio polygons after subdivision / input polygons )\n" <<
442                 (polys + polySplits) / (double)polys << endl;
443       
444        app << "===== END OF BspTree statistics ==========\n";
445}
446
447
448BspTree::~BspTree()
449{
450        DEL_PTR(mRoot);
451
452        // TODO must be deleted if used!!
453        //if (mGenerateViewCells) DEL_PTR(mOutOfBoundsCell);
454}
455
456BspViewCell *BspTree::GetOutOfBoundsCell()
457{
458        return mOutOfBoundsCell;
459}
460
461
462BspNode *BspTree::GetRoot() const
463{
464        return mRoot;
465}
466
467BspViewCell *BspTree::GetOrCreateOutOfBoundsCell()
468{
469        if (!mOutOfBoundsCell)
470        {
471                mOutOfBoundsCell = new BspViewCell();
472                mOutOfBoundsCell->SetId(-1);
473                mOutOfBoundsCell->SetValid(false);
474        }
475
476        return mOutOfBoundsCell;
477}
478
479
480void BspTree::InsertViewCell(ViewCell *viewCell)
481{
482        PolygonContainer *polys = new PolygonContainer();
483
484        // don't generate new view cell, insert this one
485        mGenerateViewCells = false;
486        // extract polygons that guide the split process
487        mStat.polys += AddMeshToPolygons(viewCell->GetMesh(), *polys, viewCell);
488        mBox.Include(viewCell->GetBox()); // add to BSP aabb
489
490        InsertPolygons(polys);
491}
492
493
494void BspTree::InsertPolygons(PolygonContainer *polys)
495{       
496        BspTraversalStack tStack;
497
498        // traverse existing tree or create new tree
499    if (!mRoot)
500                mRoot = new BspLeaf();
501
502        tStack.push(BspTraversalData(mRoot,
503                                                                 polys,
504                                                                 0,
505                                                                 mOutOfBoundsCell,
506                                                                 new BoundedRayContainer(),
507                                                                 0,
508                                                                 mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
509                                                                 new BspNodeGeometry()));
510
511        while (!tStack.empty())
512        {
513                // filter polygons donw the tree
514                BspTraversalData tData = tStack.top();
515            tStack.pop();
516                       
517                if (!tData.mNode->IsLeaf())
518                {
519                        BspInterior *interior = dynamic_cast<BspInterior *>(tData.mNode);
520
521                        //-- filter view cell polygons down the tree until a leaf is reached
522                        if (!tData.mPolygons->empty())
523                        {
524                                PolygonContainer *frontPolys = new PolygonContainer();
525                                PolygonContainer *backPolys = new PolygonContainer();
526                                PolygonContainer coincident;
527
528                                int splits = 0;
529               
530                                // split viewcell polygons with respect to split plane
531                                splits += SplitPolygons(interior->GetPlane(),
532                                                                                *tData.mPolygons,
533                                                                                *frontPolys,
534                                                                                *backPolys,
535                                                                                coincident);
536                               
537                                // extract view cells associated with the split polygons
538                                ViewCell *frontViewCell = GetOrCreateOutOfBoundsCell();
539                                ViewCell *backViewCell = GetOrCreateOutOfBoundsCell();
540                       
541                                BspTraversalData frontData(interior->GetFront(),
542                                                                                   frontPolys,
543                                                                                   tData.mDepth + 1,
544                                                                                   mOutOfBoundsCell,   
545                                                                                   tData.mRays,
546                                                                                   tData.mPvs,
547                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
548                                                                                   new BspNodeGeometry());
549
550                                BspTraversalData backData(interior->GetBack(),
551                                                                                  backPolys,
552                                                                                  tData.mDepth + 1,
553                                                                                  mOutOfBoundsCell,     
554                                                                                  tData.mRays,
555                                                                                  tData.mPvs,
556                                                                                   mUseAreaForPvs ? mBox.SurfaceArea() : mBox.GetVolume(),
557                                                                                  new BspNodeGeometry());
558
559                                if (!mGenerateViewCells)
560                                {
561                                        ExtractViewCells(frontData,
562                                                                         backData,
563                                                                         coincident,
564                                                                         interior->mPlane);
565                                }
566
567                                // don't need coincident polygons anymore
568                                CLEAR_CONTAINER(coincident);
569
570                                mStat.polySplits += splits;
571
572                                // push the children on the stack
573                                tStack.push(frontData);
574                                tStack.push(backData);
575                        }
576
577                        // cleanup
578                        DEL_PTR(tData.mPolygons);
579                        DEL_PTR(tData.mRays);
580                }
581                else
582                {
583                        // reached leaf => subdivide current viewcell
584                        BspNode *subRoot = Subdivide(tStack, tData);
585                }
586        }
587}
588
589int BspTree::AddMeshToPolygons(Mesh *mesh,
590                                                           PolygonContainer &polys,
591                                                           MeshInstance *parent)
592{
593        FaceContainer::const_iterator fi;
594       
595        // copy the face data to polygons
596        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
597        {
598                Polygon3 *poly = new Polygon3((*fi), mesh);
599               
600                if (poly->Valid(mEpsilon))
601                {
602                        poly->mParent = parent; // set parent intersectable
603                        polys.push_back(poly);
604                }
605                else
606                        DEL_PTR(poly);
607        }
608        return (int)mesh->mFaces.size();
609}
610
611
612int BspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
613                                                          PolygonContainer &polys,
614                                                          int maxObjects)
615{
616        int limit = (maxObjects > 0) ?
617                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
618 
619        int polysSize = 0;
620
621        for (int i = 0; i < limit; ++ i)
622        {
623                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
624                {
625                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
626                        polysSize += AddMeshToPolygons(viewCells[i]->GetMesh(), polys, viewCells[i]);
627                }
628        }
629
630        return polysSize;
631}
632
633
634int BspTree::AddToPolygonSoup(const ObjectContainer &objects,
635                                                          PolygonContainer &polys,
636                                                          int maxObjects,
637                                                          bool addToBbox)
638{
639        int limit = (maxObjects > 0) ?
640                Min((int)objects.size(), maxObjects) : (int)objects.size();
641 
642        for (int i = 0; i < limit; ++i)
643        {
644                Intersectable *object = objects[i];//*it;
645                Mesh *mesh = NULL;
646
647                switch (object->Type()) // extract the meshes
648                {
649                case Intersectable::MESH_INSTANCE:
650                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
651                        break;
652                case Intersectable::VIEW_CELL:
653                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
654                        break;
655                        // TODO: handle transformed mesh instances
656                default:
657                        Debug << "intersectable type not supported" << endl;
658                        break;
659                }
660               
661        if (mesh) // copy the mesh data to polygons
662                {
663                        if (addToBbox)
664                        {
665                                mBox.Include(object->GetBox()); // add to BSP tree aabb
666                        }
667               
668                        AddMeshToPolygons(mesh, polys, mOutOfBoundsCell);
669                }
670        }
671
672        return (int)polys.size();
673}
674
675
676void BspTree::Construct(const ViewCellContainer &viewCells)
677{
678        mStat.nodes = 1;
679        mBox.Initialize();      // initialise bsp tree bounding box
680
681        // copy view cell meshes into one big polygon soup
682        PolygonContainer *polys = new PolygonContainer();
683        mStat.polys = AddToPolygonSoup(viewCells, *polys);
684
685        // view cells are given
686        mGenerateViewCells = false;
687        // construct tree from the view cell polygons
688        Construct(polys, new BoundedRayContainer());
689}
690
691
692void BspTree::Construct(const ObjectContainer &objects)
693{
694        mStat.nodes = 1;
695        mBox.Initialize();      // initialise bsp tree bounding box
696       
697        PolygonContainer *polys = new PolygonContainer();
698
699        mGenerateViewCells = true;
700        // copy mesh instance polygons into one big polygon soup
701        mStat.polys = AddToPolygonSoup(objects, *polys);
702
703        // construct tree from polygon soup
704        Construct(polys, new BoundedRayContainer());
705}
706
707
708void BspTree::PreprocessPolygons(PolygonContainer &polys)
709{
710        // preprocess: throw out polygons coincident to the view space box (not needed)
711        PolygonContainer boxPolys;
712        mBox.ExtractPolygons(boxPolys);
713        vector<Plane3> boxPlanes;
714        PolygonContainer::const_iterator pit, pit_end = polys->end();
715
716        for (pit = polys->begin(); pit != pit_end; ++ pit)
717        {
718               
719        }
720}
721
722void BspTree::Construct(const RayContainer &sampleRays,
723                                                AxisAlignedBox3 *forcedBoundingBox)
724{
725    mStat.nodes = 1;
726        mBox.Initialize();      // initialise BSP tree bounding box
727       
728        if (forcedBoundingBox)
729                mBox = *forcedBoundingBox;
730
731        PolygonContainer *polys = new PolygonContainer();
732        BoundedRayContainer *rays = new BoundedRayContainer();
733
734        RayContainer::const_iterator rit, rit_end = sampleRays.end();
735
736        // generate view cells
737        mGenerateViewCells = true;
738
739        long startTime = GetTime();
740
741        Debug << "**** Extracting polygons from rays ****\n";
742
743        std::map<Face *, Polygon3 *> facePolyMap;
744
745        //-- extract polygons intersected by the rays
746        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
747        {
748                Ray *ray = *rit;
749       
750                // get ray-face intersection. Store polygon representing the rays together
751                // with rays intersecting the face.
752                if (!ray->intersections.empty())
753                {
754                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->intersections[0].mObject);
755                        Face *face = obj->GetMesh()->mFaces[ray->intersections[0].mFace];
756
757                        std::map<Face *, Polygon3 *>::iterator it = facePolyMap.find(face);
758
759                        if (it != facePolyMap.end())
760                        {
761                                //store rays if needed for heuristics
762                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
763                                        (*it).second->mPiercingRays.push_back(ray);
764                        }
765                        else
766                        {       //store rays if needed for heuristics
767                                Polygon3 *poly = new Polygon3(face, obj->GetMesh());
768                                poly->mParent = obj;
769                                polys->push_back(poly);
770
771                                if (mSplitPlaneStrategy & BLOCKED_RAYS)
772                                        poly->mPiercingRays.push_back(ray);
773
774                                facePolyMap[face] = poly;
775                        }
776                }
777        }
778       
779        facePolyMap.clear();
780
781        // compute bounding box
782        if (!forcedBoundingBox)
783                Polygon3::IncludeInBox(*polys, mBox);
784
785        //-- store rays
786        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
787        {
788                Ray *ray = *rit;
789        ray->SetId(-1); // reset id
790
791                float minT, maxT;
792                if (mBox.GetRaySegment(*ray, minT, maxT))
793                        rays->push_back(new BoundedRay(ray, minT, maxT));
794        }
795
796        PreprocessPolygons();
797
798        mStat.polys = (int)polys->size();
799
800        Debug << "**** Finished polygon extraction ****" << endl;
801        Debug << (int)polys->size() << " polys extracted from " << (int)sampleRays.size() << " rays" << endl;
802        Debug << "extraction time: " << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
803
804        Construct(polys, rays);
805}
806
807
808void BspTree::Construct(const ObjectContainer &objects,
809                                                const RayContainer &sampleRays,
810                                                AxisAlignedBox3 *forcedBoundingBox)
811{
812    mStat.nodes = 1;
813        mBox.Initialize();      // initialise BSP tree bounding box
814       
815        if (forcedBoundingBox)
816                mBox = *forcedBoundingBox;
817
818        BoundedRayContainer *rays = new BoundedRayContainer();
819        PolygonContainer *polys = new PolygonContainer();
820       
821        mGenerateViewCells = true;
822
823        // copy mesh instance polygons into one big polygon soup
824        mStat.polys = AddToPolygonSoup(objects, *polys, 0, !forcedBoundingBox);
825
826
827        RayContainer::const_iterator rit, rit_end = sampleRays.end();
828
829        //-- store rays
830        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
831        {
832                Ray *ray = *rit;
833        ray->SetId(-1); // reset id
834
835                float minT, maxT;
836                if (mBox.GetRaySegment(*ray, minT, maxT))
837                        rays->push_back(new BoundedRay(ray, minT, maxT));
838        }
839
840        Debug << "tree has " << (int)polys->size() << " polys, " << (int)sampleRays.size() << " rays" << endl;
841        Construct(polys, rays);
842}
843
844
845void BspTree::Construct(PolygonContainer *polys, BoundedRayContainer *rays)
846{
847        BspTraversalStack tStack;
848
849        mRoot = new BspLeaf();
850
851        // constrruct root node geometry
852        BspNodeGeometry *geom = new BspNodeGeometry();
853        ConstructGeometry(mRoot, *geom);
854
855        BspTraversalData tData(mRoot,
856                                                   polys,
857                                                   0,
858                                                   GetOrCreateOutOfBoundsCell(),
859                                                   rays,
860                                                   ComputePvsSize(*rays),
861                                                   mUseAreaForPvs ? geom->GetArea() : geom->GetVolume(),
862                                                   geom);
863
864        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
865        mTotalPvsSize = tData.mPvs;
866       
867        mSubdivisionStats
868                        << "#ViewCells\n1\n" <<  endl
869                        << "#RenderCostDecrease\n0\n" << endl
870                        << "#TotalRenderCost\n" << mTotalCost << endl
871                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
872
873        tStack.push(tData);
874
875        // used for intermediate time measurements and progress
876        long interTime = GetTime();     
877        int nleaves = 500;
878
879        mStat.Start();
880        cout << "Contructing bsp tree ...\n";
881        long startTime = GetTime();
882        while (!tStack.empty())
883        {
884                tData = tStack.top();
885
886            tStack.pop();
887
888                // subdivide leaf node
889                BspNode *r = Subdivide(tStack, tData);
890
891                if (r == mRoot)
892            Debug << "BSP tree construction time spent at root: "
893                                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl;
894
895                if (mStat.Leaves() >= nleaves)
896                {
897                        nleaves += 500;
898                       
899                        cout << "leaves=" << mStat.Leaves() << endl;
900                        Debug << "needed "
901                                  << TimeDiff(interTime, GetTime())*1e-3
902                                  << " secs to create 500 leaves" << endl;
903                        interTime = GetTime();
904                }
905        }
906
907        cout << "finished\n";
908
909        mStat.Stop();
910}
911
912
913bool BspTree::TerminationCriteriaMet(const BspTraversalData &data) const
914{
915        return
916                (((int)data.mPolygons->size() <= mTermMinPolys) ||
917                 ((int)data.mRays->size() <= mTermMinRays) ||
918                 (data.mPvs <= mTermMinPvs) ||
919                 (data.mProbability <= mTermMinProbability) ||
920                 (data.mDepth >= mTermMaxDepth) ||
921                 (mStat.Leaves() >= mMaxViewCells) ||
922                 (data.GetAvgRayContribution() > mTermMaxRayContribution));
923}
924
925
926BspNode *BspTree::Subdivide(BspTraversalStack &tStack, BspTraversalData &tData)
927{
928        //-- terminate traversal 
929        if (TerminationCriteriaMet(tData))             
930        {
931                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
932       
933                BspViewCell *viewCell;
934
935                // generate new view cell for each leaf
936                if (mGenerateViewCells)
937                        viewCell = new BspViewCell();
938                else
939                        // add view cell to leaf
940                        viewCell = dynamic_cast<BspViewCell *>(tData.mViewCell);
941               
942                leaf->SetViewCell(viewCell);
943                viewCell->mLeaf = leaf;
944
945                if (mUseAreaForPvs)
946                        viewCell->SetArea(tData.mProbability);
947                else
948                        viewCell->SetVolume(tData.mProbability);
949               
950                //-- add pvs
951                if (viewCell != mOutOfBoundsCell)
952                {
953                        int conSamp = 0, sampCon = 0;
954                        AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
955                       
956                        mStat.contributingSamples += conSamp;
957                        mStat.sampleContributions += sampCon;
958                }
959
960                EvaluateLeafStats(tData);
961               
962                //-- clean up
963               
964                // discard polygons
965                CLEAR_CONTAINER(*tData.mPolygons);
966                // discard rays
967                CLEAR_CONTAINER(*tData.mRays);
968
969                DEL_PTR(tData.mPolygons);
970                DEL_PTR(tData.mRays);
971                DEL_PTR(tData.mGeometry);
972
973                return leaf;
974        }
975
976        //-- continue subdivision
977        PolygonContainer coincident;
978       
979        BspTraversalData tFrontData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
980                                                                new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
981        BspTraversalData tBackData(NULL, new PolygonContainer(), tData.mDepth + 1, mOutOfBoundsCell,
982                                                           new BoundedRayContainer(), 0, 0, new BspNodeGeometry());
983
984
985        // create new interior node and two leaf nodes
986        BspInterior *interior =
987                SubdivideNode(tData, tFrontData, tBackData, coincident);
988
989
990        if (1)
991        {
992                int pvsData = tData.mPvs;
993                float cData = (float)pvsData * tData.mProbability;
994
995                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
996                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
997               
998                Debug << "front pvs: " << tFrontData.mPvs << " p: " << tFrontData.mProbability << endl;
999                Debug << "back pvs: " << tBackData.mPvs << " p: " << tBackData.mProbability << endl;
1000                Debug << "pvs: " << pvsData << " p: " << tData.mProbability << endl;
1001
1002                Debug << "data: " << cData << " front: " << cFront << " back: " << cBack << endl;
1003                Debug << "cost ratio: " << (cFront + cBack) / cData << endl;
1004
1005                if (((cFront + cBack) / cData > 1) || (tFrontData.mProbability == 0) || (tBackData.mProbability == 0))
1006                {
1007                        Debug << "ERROR!!" << endl;
1008
1009                        vector<Plane3> halfSpaces;
1010                        ExtractHalfSpaces(interior, halfSpaces);
1011       
1012                        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1013                                Debug << halfSpaces[i] << endl;
1014
1015                        Debug << "geom:\n" << *tData.mGeometry << endl;
1016                        Debug << "fgeom:\n" << *tFrontData.mGeometry << endl;
1017                        Debug << "bgeom:\n" << *tBackData.mGeometry << endl;
1018                }
1019
1020                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
1021
1022               
1023                mTotalCost += costDecr;
1024                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - pvsData;
1025
1026                mSubdivisionStats
1027                        << "#ViewCells\n" << mStat.Leaves() << endl
1028                        << "#RenderCostDecrease\n" << -costDecr << endl
1029                        << "#TotalRenderCost\n" << mTotalCost << endl
1030                        << "#AvgRenderCost\n" << mTotalPvsSize / mStat.Leaves() << endl;
1031        }
1032
1033        // extract view cells from coincident polygons according to plane normal
1034    // only if front or back polygons are empty
1035        if (!mGenerateViewCells)
1036        {
1037                ExtractViewCells(tFrontData,
1038                                                 tBackData,
1039                                                 coincident,
1040                                                 interior->mPlane);                     
1041        }
1042
1043        // don't need coincident polygons anymory
1044        CLEAR_CONTAINER(coincident);
1045
1046        // push the children on the stack
1047        tStack.push(tFrontData);
1048        tStack.push(tBackData);
1049
1050        // cleanup
1051        DEL_PTR(tData.mNode);
1052
1053        DEL_PTR(tData.mPolygons);
1054        DEL_PTR(tData.mRays);
1055        DEL_PTR(tData.mGeometry);               
1056       
1057        return interior;
1058}
1059
1060
1061void BspTree::ExtractViewCells(BspTraversalData &frontData,
1062                                                           BspTraversalData &backData,
1063                                                           const PolygonContainer &coincident,
1064                                                           const Plane3 &splitPlane) const
1065{
1066        // if not empty, tree is further subdivided => don't have to find view cell
1067        bool foundFront = !frontData.mPolygons->empty();
1068        bool foundBack = !frontData.mPolygons->empty();
1069
1070        PolygonContainer::const_iterator it =
1071                coincident.begin(), it_end = coincident.end();
1072
1073        //-- find first view cells in front and back leafs
1074        for (; !(foundFront && foundBack) && (it != it_end); ++ it)
1075        {
1076                if (DotProd((*it)->GetNormal(), splitPlane.mNormal) > 0)
1077                {
1078                        backData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1079                        foundBack = true;
1080                }
1081                else
1082                {
1083                        frontData.mViewCell = dynamic_cast<ViewCell *>((*it)->mParent);
1084                        foundFront = true;
1085                }
1086        }
1087}
1088
1089
1090BspInterior *BspTree::SubdivideNode(BspTraversalData &tData,
1091                                                                        BspTraversalData &frontData,
1092                                                                        BspTraversalData &backData,
1093                                                                        PolygonContainer &coincident)
1094{
1095        mStat.nodes += 2;
1096       
1097        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1098
1099       
1100       
1101        // select subdivision plane
1102        BspInterior *interior =
1103                new BspInterior(SelectPlane(leaf, tData));
1104       
1105       
1106//#ifdef _DEBUG
1107        Debug << interior << endl;
1108        Debug << interior->GetPlane() << endl;
1109//#endif
1110       
1111
1112        // subdivide rays into front and back rays
1113        SplitRays(interior->mPlane, *tData.mRays, *frontData.mRays, *backData.mRays);
1114       
1115       
1116
1117        // subdivide polygons with plane
1118        mStat.polySplits += SplitPolygons(interior->GetPlane(),
1119                                                                          *tData.mPolygons,
1120                                                                          *frontData.mPolygons,
1121                                                                          *backData.mPolygons,
1122                                                                          coincident);
1123
1124       
1125
1126    // compute pvs
1127        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1128        backData.mPvs = ComputePvsSize(*backData.mRays);
1129
1130        // split geometry and compute area
1131        if (1)
1132        {
1133                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1134                                                                           *backData.mGeometry,
1135                                                                           interior->mPlane,
1136                                                                           mBox,
1137                                                                           //0.000000000001);
1138                                                                           mEpsilon);
1139       
1140               
1141                if (mUseAreaForPvs)
1142                {
1143                        frontData.mProbability = frontData.mGeometry->GetArea();
1144                        backData.mProbability = backData.mGeometry->GetArea();
1145                }
1146                else
1147                {
1148                        frontData.mProbability = frontData.mGeometry->GetVolume();
1149                        backData.mProbability = tData.mProbability - frontData.mProbability;
1150
1151                        Debug << "************" << endl;
1152                        Debug << "plane: " << interior->mPlane << endl;
1153                        Debug << "box: " << mBox << endl;
1154                        Debug << "all: " << tData.mProbability << " f: " << frontData.mProbability << " b: " << backData.mProbability << endl;
1155                        Debug << "real back: " << backData.mGeometry->GetVolume() << endl;
1156                        Debug << "data geom: " << tData.mGeometry->mPolys.size() << " f: " << frontData.mGeometry->mPolys.size() << " b: " << backData.mGeometry->mPolys.size() << endl;
1157                }
1158        }
1159
1160        //-- create front and back leaf
1161
1162        BspInterior *parent = leaf->GetParent();
1163
1164        // replace a link from node's parent
1165        if (!leaf->IsRoot())
1166        {
1167                parent->ReplaceChildLink(leaf, interior);
1168                interior->SetParent(parent);
1169        }
1170        else // new root
1171        {
1172                mRoot = interior;
1173        }
1174
1175        // and setup child links
1176        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1177       
1178        frontData.mNode = interior->GetFront();
1179        backData.mNode = interior->GetBack();
1180       
1181        frontData.mNode->mTimeStamp = mTimeStamp;
1182        backData.mNode->mTimeStamp = mTimeStamp ++;
1183
1184        //DEL_PTR(leaf);
1185        return interior;
1186}
1187
1188
1189void BspTree::SortSplitCandidates(const PolygonContainer &polys,
1190                                                                  const int axis,
1191                                                                  vector<SortableEntry> &splitCandidates) const
1192{
1193        splitCandidates.clear();
1194
1195        int requestedSize = 2 * (int)polys.size();
1196        // creates a sorted split candidates array 
1197        splitCandidates.reserve(requestedSize);
1198
1199        PolygonContainer::const_iterator it, it_end = polys.end();
1200
1201        AxisAlignedBox3 box;
1202
1203        // insert all queries
1204        for(it = polys.begin(); it != it_end; ++ it)
1205        {
1206                box.Initialize();
1207                box.Include(*(*it));
1208               
1209                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
1210                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
1211        }
1212
1213        stable_sort(splitCandidates.begin(), splitCandidates.end());
1214}
1215
1216
1217float BspTree::BestCostRatio(const PolygonContainer &polys,
1218                                                         const AxisAlignedBox3 &box,
1219                                                         const int axis,
1220                                                         float &position,
1221                                                         int &objectsBack,
1222                                                         int &objectsFront) const
1223{
1224        vector<SortableEntry> splitCandidates;
1225
1226        SortSplitCandidates(polys, axis, splitCandidates);
1227       
1228        // go through the lists, count the number of objects left and right
1229        // and evaluate the following cost funcion:
1230        // C = ct_div_ci  + (ol + or)/queries
1231       
1232        int objectsLeft = 0, objectsRight = (int)polys.size();
1233       
1234        float minBox = box.Min(axis);
1235        float maxBox = box.Max(axis);
1236        float boxArea = box.SurfaceArea();
1237 
1238        float minBand = minBox + mSplitBorder * (maxBox - minBox);
1239        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
1240       
1241        float minSum = 1e20f;
1242        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
1243
1244        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
1245        {
1246                switch ((*ci).type)
1247                {
1248                        case SortableEntry::POLY_MIN:
1249                                ++ objectsLeft;
1250                                break;
1251                        case SortableEntry::POLY_MAX:
1252                            -- objectsRight;
1253                                break;
1254                        default:
1255                                break;
1256                }
1257               
1258                if ((*ci).value > minBand && (*ci).value < maxBand)
1259                {
1260                        AxisAlignedBox3 lbox = box;
1261                        AxisAlignedBox3 rbox = box;
1262                        lbox.SetMax(axis, (*ci).value);
1263                        rbox.SetMin(axis, (*ci).value);
1264
1265                        const float sum = objectsLeft * lbox.SurfaceArea() +
1266                                                          objectsRight * rbox.SurfaceArea();
1267     
1268                        if (sum < minSum)
1269                        {
1270                                minSum = sum;
1271                                position = (*ci).value;
1272
1273                                objectsBack = objectsLeft;
1274                                objectsFront = objectsRight;
1275                        }
1276                }
1277        }
1278 
1279        const float oldCost = (float)polys.size();
1280        const float newCost = mAxisAlignedCtDivCi + minSum / boxArea;
1281        const float ratio = newCost / oldCost;
1282
1283
1284#if 0
1285  Debug << "====================" << endl;
1286  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
1287      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
1288#endif
1289  return ratio;
1290}
1291
1292bool BspTree::SelectAxisAlignedPlane(Plane3 &plane,
1293                                                                         const PolygonContainer &polys) const
1294{
1295        AxisAlignedBox3 box;
1296        box.Initialize();
1297       
1298        // create bounding box of region
1299        Polygon3::IncludeInBox(polys, box);
1300       
1301        int objectsBack = 0, objectsFront = 0;
1302        int axis = 0;
1303        float costRatio = MAX_FLOAT;
1304        Vector3 position;
1305
1306        //-- area subdivision
1307        for (int i = 0; i < 3; ++ i)
1308        {
1309                float p = 0;
1310                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
1311               
1312                if (r < costRatio)
1313                {
1314                        costRatio = r;
1315                        axis = i;
1316                        position = p;
1317                }
1318        }
1319       
1320        if (costRatio >= mMaxCostRatio)
1321                return false;
1322
1323        Vector3 norm(0,0,0); norm[axis] = 1.0f;
1324        plane = Plane3(norm, position);
1325
1326        return true;
1327}
1328
1329
1330Plane3 BspTree::SelectPlane(BspLeaf *leaf, BspTraversalData &data)
1331{
1332        if ((!mMaxPolyCandidates || data.mPolygons->empty()) &&
1333                (!mMaxRayCandidates || data.mRays->empty()))
1334        {
1335                Debug << "Warning: No autopartition polygon candidate available\n";
1336       
1337                // return axis aligned split
1338                AxisAlignedBox3 box;
1339                box.Initialize();
1340       
1341                // create bounding box of region
1342                Polygon3::IncludeInBox(*data.mPolygons, box);
1343
1344                const int axis = box.Size().DrivingAxis();
1345                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1346
1347                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1348                return Plane3(norm, position);
1349        }
1350       
1351        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
1352                ((int)data.mPolygons->size() > mTermMinPolysForAxisAligned) &&
1353                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1354                ((mTermMinObjectsForAxisAligned < 0) ||
1355                 (Polygon3::ParentObjectsSize(*data.mPolygons) > mTermMinObjectsForAxisAligned)))
1356        {
1357                Plane3 plane;
1358                if (SelectAxisAlignedPlane(plane, *data.mPolygons))
1359                        return plane;
1360        }
1361
1362        // simplest strategy: just take next polygon
1363        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1364        {
1365        if (!data.mPolygons->empty())
1366                {
1367                        Polygon3 *nextPoly =
1368                                (*data.mPolygons)[(int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1))];
1369                        return nextPoly->GetSupportingPlane();
1370                }
1371                else
1372                {
1373                        const int candidateIdx = (int)RandomValue(0, (Real)((int)data.mRays->size() - 1));
1374                        BoundedRay *bRay = (*data.mRays)[candidateIdx];
1375
1376                        Ray *ray = bRay->mRay;
1377                                               
1378                        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1379                        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1380
1381                        const Vector3 pt = (maxPt + minPt) * 0.5;
1382
1383                        const Vector3 normal = ray->GetDir();
1384                       
1385                        return Plane3(normal, pt);
1386                }
1387
1388                return Plane3();
1389        }
1390
1391        // use heuristics to find appropriate plane
1392        return SelectPlaneHeuristics(leaf, data);
1393}
1394
1395
1396Plane3 BspTree::ChooseCandidatePlane(const BoundedRayContainer &rays) const
1397{       
1398        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1399        BoundedRay *bRay = rays[candidateIdx];
1400        Ray *ray = bRay->mRay;
1401
1402        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1403        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1404
1405        const Vector3 pt = (maxPt + minPt) * 0.5;
1406
1407        const Vector3 normal = ray->GetDir();
1408                       
1409        return Plane3(normal, pt);
1410}
1411
1412Plane3 BspTree::ChooseCandidatePlane2(const BoundedRayContainer &rays) const
1413{       
1414        Vector3 pt[3];
1415        int idx[3];
1416        int cmaxT = 0;
1417        int cminT = 0;
1418        bool chooseMin = false;
1419
1420        for (int j = 0; j < 3; j ++)
1421        {
1422                idx[j] = (int)RandomValue(0, Real((int)rays.size() * 2 - 1));
1423                               
1424                if (idx[j] >= (int)rays.size())
1425                {
1426                        idx[j] -= (int)rays.size();             
1427                        chooseMin = (cminT < 2);
1428                }
1429                else
1430                        chooseMin = (cmaxT < 2);
1431
1432                BoundedRay *bRay = rays[idx[j]];
1433                pt[j] = chooseMin ? bRay->mRay->Extrap(bRay->mMinT) :
1434                                                        bRay->mRay->Extrap(bRay->mMaxT);
1435        }       
1436                       
1437        return Plane3(pt[0], pt[1], pt[2]);
1438}
1439
1440Plane3 BspTree::ChooseCandidatePlane3(const BoundedRayContainer &rays) const
1441{       
1442        Vector3 pt[3];
1443       
1444        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1445        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1446
1447        // check if rays different
1448        if (idx1 == idx2)
1449                idx2 = (idx2 + 1) % (int)rays.size();
1450
1451        const BoundedRay *ray1 = rays[idx1];
1452        const BoundedRay *ray2 = rays[idx2];
1453
1454        // normal vector of the plane parallel to both lines
1455        const Vector3 norm =
1456                Normalize(CrossProd(ray1->mRay->GetDir(), ray2->mRay->GetDir()));
1457
1458        const Vector3 orig1 = ray1->mRay->Extrap(ray1->mMinT);
1459        const Vector3 orig2 = ray2->mRay->Extrap(ray2->mMinT);
1460
1461        // vector from line 1 to line 2
1462        const Vector3 vd = orig1 - orig2;
1463       
1464        // project vector on normal to get distance
1465        const float dist = DotProd(vd, norm);
1466
1467        // point on plane lies halfway between the two planes
1468        const Vector3 planePt = orig1 + norm * dist * 0.5;
1469
1470        return Plane3(norm, planePt);
1471}
1472
1473
1474Plane3 BspTree::SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data)
1475{
1476        float lowestCost = MAX_FLOAT;
1477        Plane3 bestPlane;
1478        // intermediate plane
1479        Plane3 plane;
1480
1481        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1482        int maxIdx = (int)data.mPolygons->size();
1483       
1484        for (int i = 0; i < limit; ++ i)
1485        {
1486                // assure that no index is taken twice
1487                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1488                               
1489                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1490
1491                // swap candidate to the end to avoid testing same plane
1492                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1493                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1494
1495                // evaluate current candidate
1496                const float candidateCost =
1497                        SplitPlaneCost(poly->GetSupportingPlane(), data);
1498
1499                Debug << "supporting plane: " << poly->GetSupportingPlane() << endl;
1500
1501                if (candidateCost < lowestCost)
1502                {
1503                        bestPlane = poly->GetSupportingPlane();
1504                        lowestCost = candidateCost;
1505                }
1506        }
1507       
1508        //-- choose candidate planes extracted from rays
1509        for (int i = 0; i < mMaxRayCandidates; ++ i)
1510        {
1511                plane = ChooseCandidatePlane3(*data.mRays);
1512                const float candidateCost = SplitPlaneCost(plane, data);
1513
1514                if (candidateCost < lowestCost)
1515                {
1516                        bestPlane = plane;     
1517                        lowestCost = candidateCost;
1518                }
1519        }
1520
1521#ifdef _DEBUG
1522        Debug << "plane lowest cost: " << lowestCost << endl;
1523#endif
1524        Debug << "choosen plane: " << bestPlane << endl;
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.