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

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