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

Revision 840, 80.7 KB checked in by mattausch, 18 years ago (diff)

implementing bounding box hack

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