source: trunk/VUT/GtpVisibilityPreprocessor/src/ViewCellBsp.cpp @ 574

Revision 574, 69.1 KB checked in by mattausch, 18 years ago (diff)

finished function for view cell construction
removed bsp rays from vspbspmanager

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