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

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

fixed bug in mergueue to find root of merge and sort out doube view cells

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->mLeaf = 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
1032
1033void BspTree::SortSplitCandidates(const PolygonContainer &polys,
1034                                                                  const int axis,
1035                                                                  vector<SortableEntry> &splitCandidates) const
1036{
1037        splitCandidates.clear();
1038
1039        int requestedSize = 2 * (int)polys.size();
1040        // creates a sorted split candidates array 
1041        splitCandidates.reserve(requestedSize);
1042
1043        PolygonContainer::const_iterator it, it_end = polys.end();
1044
1045        AxisAlignedBox3 box;
1046
1047        // insert all queries
1048        for(it = polys.begin(); it != it_end; ++ it)
1049        {
1050                box.Initialize();
1051                box.Include(*(*it));
1052               
1053                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MIN, box.Min(axis), *it));
1054                splitCandidates.push_back(SortableEntry(SortableEntry::POLY_MAX, box.Max(axis), *it));
1055        }
1056
1057        stable_sort(splitCandidates.begin(), splitCandidates.end());
1058}
1059
1060
1061float BspTree::BestCostRatio(const PolygonContainer &polys,
1062                                                         const AxisAlignedBox3 &box,
1063                                                         const int axis,
1064                                                         float &position,
1065                                                         int &objectsBack,
1066                                                         int &objectsFront) const
1067{
1068        vector<SortableEntry> splitCandidates;
1069
1070        SortSplitCandidates(polys, axis, splitCandidates);
1071       
1072        // go through the lists, count the number of objects left and right
1073        // and evaluate the following cost funcion:
1074        // C = ct_div_ci  + (ol + or)/queries
1075       
1076        int objectsLeft = 0, objectsRight = (int)polys.size();
1077       
1078        float minBox = box.Min(axis);
1079        float maxBox = box.Max(axis);
1080        float boxArea = box.SurfaceArea();
1081 
1082        float minBand = minBox + mSplitBorder * (maxBox - minBox);
1083        float maxBand = minBox + (1.0f - mSplitBorder) * (maxBox - minBox);
1084       
1085        float minSum = 1e20f;
1086        vector<SortableEntry>::const_iterator ci, ci_end = splitCandidates.end();
1087
1088        for(ci = splitCandidates.begin(); ci != ci_end; ++ ci)
1089        {
1090                switch ((*ci).type)
1091                {
1092                        case SortableEntry::POLY_MIN:
1093                                ++ objectsLeft;
1094                                break;
1095                        case SortableEntry::POLY_MAX:
1096                            -- objectsRight;
1097                                break;
1098                        default:
1099                                break;
1100                }
1101               
1102                if ((*ci).value > minBand && (*ci).value < maxBand)
1103                {
1104                        AxisAlignedBox3 lbox = box;
1105                        AxisAlignedBox3 rbox = box;
1106                        lbox.SetMax(axis, (*ci).value);
1107                        rbox.SetMin(axis, (*ci).value);
1108
1109                        const float sum = objectsLeft * lbox.SurfaceArea() +
1110                                                          objectsRight * rbox.SurfaceArea();
1111     
1112                        if (sum < minSum)
1113                        {
1114                                minSum = sum;
1115                                position = (*ci).value;
1116
1117                                objectsBack = objectsLeft;
1118                                objectsFront = objectsRight;
1119                        }
1120                }
1121        }
1122 
1123        const float oldCost = (float)polys.size();
1124        const float newCost = mAxisAlignedCtDivCi + minSum / boxArea;
1125        const float ratio = newCost / oldCost;
1126
1127
1128#if 0
1129  Debug << "====================" << endl;
1130  Debug << "costRatio=" << ratio << " pos=" << position<<" t=" << (position - minBox)/(maxBox - minBox)
1131      << "\t o=(" << objectsBack << "," << objectsFront << ")" << endl;
1132#endif
1133  return ratio;
1134}
1135
1136bool BspTree::SelectAxisAlignedPlane(Plane3 &plane,
1137                                                                         const PolygonContainer &polys) const
1138{
1139        AxisAlignedBox3 box;
1140        box.Initialize();
1141       
1142        // create bounding box of region
1143        Polygon3::IncludeInBox(polys, box);
1144       
1145        int objectsBack = 0, objectsFront = 0;
1146        int axis = 0;
1147        float costRatio = MAX_FLOAT;
1148        Vector3 position;
1149
1150        //-- area subdivision
1151        for (int i = 0; i < 3; ++ i)
1152        {
1153                float p = 0;
1154                float r = BestCostRatio(polys, box, i, p, objectsBack, objectsFront);
1155               
1156                if (r < costRatio)
1157                {
1158                        costRatio = r;
1159                        axis = i;
1160                        position = p;
1161                }
1162        }
1163       
1164        if (costRatio >= mMaxCostRatio)
1165                return false;
1166
1167        Vector3 norm(0,0,0); norm[axis] = 1.0f;
1168        plane = Plane3(norm, position);
1169
1170        return true;
1171}
1172
1173
1174Plane3 BspTree::SelectPlane(BspLeaf *leaf, BspTraversalData &data)
1175{
1176        if (data.mPolygons->empty() && data.mRays->empty())
1177        {
1178                Debug << "Warning: No autopartition polygon candidate available\n";
1179       
1180                // return axis aligned split
1181                AxisAlignedBox3 box;
1182                box.Initialize();
1183       
1184                // create bounding box of region
1185                Polygon3::IncludeInBox(*data.mPolygons, box);
1186
1187                const int axis = box.Size().DrivingAxis();
1188                const Vector3 position = (box.Min()[axis] + box.Max()[axis])*0.5f;
1189
1190                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1191                return Plane3(norm, position);
1192        }
1193       
1194        if ((mSplitPlaneStrategy & AXIS_ALIGNED) &&
1195                ((int)data.mPolygons->size() > mTermMinPolysForAxisAligned) &&
1196                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1197                ((mTermMinObjectsForAxisAligned < 0) ||
1198                  (Polygon3::ParentObjectsSize(*data.mPolygons) > mTermMinObjectsForAxisAligned)))
1199        {
1200                Plane3 plane;
1201                if (SelectAxisAlignedPlane(plane, *data.mPolygons))
1202                        return plane;
1203        }
1204
1205        // simplest strategy: just take next polygon
1206        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1207        {
1208        if (!data.mPolygons->empty())
1209                {
1210                        Polygon3 *nextPoly =
1211                                (*data.mPolygons)[(int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1))];
1212                        return nextPoly->GetSupportingPlane();
1213                }
1214                else
1215                {
1216                        const int candidateIdx = (int)RandomValue(0, (Real)((int)data.mRays->size() - 1));
1217                        BoundedRay *bRay = (*data.mRays)[candidateIdx];
1218
1219                        Ray *ray = bRay->mRay;
1220                                               
1221                        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1222                        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1223
1224                        const Vector3 pt = (maxPt + minPt) * 0.5;
1225
1226                        const Vector3 normal = ray->GetDir();
1227                       
1228                        return Plane3(normal, pt);
1229                }
1230
1231                return Plane3();
1232        }
1233
1234        // use heuristics to find appropriate plane
1235        return SelectPlaneHeuristics(leaf, data);
1236}
1237
1238
1239Plane3 BspTree::ChooseCandidatePlane(const BoundedRayContainer &rays) const
1240{       
1241        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1242        BoundedRay *bRay = rays[candidateIdx];
1243        Ray *ray = bRay->mRay;
1244
1245        const Vector3 minPt = ray->Extrap(bRay->mMinT);
1246        const Vector3 maxPt = ray->Extrap(bRay->mMaxT);
1247
1248        const Vector3 pt = (maxPt + minPt) * 0.5;
1249
1250        const Vector3 normal = ray->GetDir();
1251                       
1252        return Plane3(normal, pt);
1253}
1254
1255Plane3 BspTree::ChooseCandidatePlane2(const BoundedRayContainer &rays) const
1256{       
1257        Vector3 pt[3];
1258        int idx[3];
1259        int cmaxT = 0;
1260        int cminT = 0;
1261        bool chooseMin = false;
1262
1263        for (int j = 0; j < 3; j ++)
1264        {
1265                idx[j] = (int)RandomValue(0, Real((int)rays.size() * 2 - 1));
1266                               
1267                if (idx[j] >= (int)rays.size())
1268                {
1269                        idx[j] -= (int)rays.size();             
1270                        chooseMin = (cminT < 2);
1271                }
1272                else
1273                        chooseMin = (cmaxT < 2);
1274
1275                BoundedRay *bRay = rays[idx[j]];
1276                pt[j] = chooseMin ? bRay->mRay->Extrap(bRay->mMinT) :
1277                                                        bRay->mRay->Extrap(bRay->mMaxT);
1278        }       
1279                       
1280        return Plane3(pt[0], pt[1], pt[2]);
1281}
1282
1283Plane3 BspTree::ChooseCandidatePlane3(const BoundedRayContainer &rays) const
1284{       
1285        Vector3 pt[3];
1286       
1287        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1288        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1289
1290        // check if rays different
1291        if (idx1 == idx2)
1292                idx2 = (idx2 + 1) % (int)rays.size();
1293
1294        const BoundedRay *ray1 = rays[idx1];
1295        const BoundedRay *ray2 = rays[idx2];
1296
1297        // normal vector of the plane parallel to both lines
1298        const Vector3 norm =
1299                Normalize(CrossProd(ray1->mRay->GetDir(), ray2->mRay->GetDir()));
1300
1301        const Vector3 orig1 = ray1->mRay->Extrap(ray1->mMinT);
1302        const Vector3 orig2 = ray2->mRay->Extrap(ray2->mMinT);
1303
1304        // vector from line 1 to line 2
1305        const Vector3 vd = orig1 - orig2;
1306       
1307        // project vector on normal to get distance
1308        const float dist = DotProd(vd, norm);
1309
1310        // point on plane lies halfway between the two planes
1311        const Vector3 planePt = orig1 + norm * dist * 0.5;
1312
1313        return Plane3(norm, planePt);
1314}
1315
1316
1317Plane3 BspTree::SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data)
1318{
1319        float lowestCost = MAX_FLOAT;
1320        Plane3 bestPlane;
1321        // intermediate plane
1322        Plane3 plane;
1323
1324        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1325        int maxIdx = (int)data.mPolygons->size();
1326       
1327        for (int i = 0; i < limit; ++ i)
1328        {
1329                // assure that no index is taken twice
1330                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1331                //Debug << "current Idx: " << maxIdx << " cand idx " << candidateIdx << endl;
1332               
1333                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1334
1335                // swap candidate to the end to avoid testing same plane
1336                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1337       
1338                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1339
1340                // evaluate current candidate
1341                const float candidateCost =
1342                        SplitPlaneCost(poly->GetSupportingPlane(), data);
1343
1344                if (candidateCost < lowestCost)
1345                {
1346                        bestPlane = poly->GetSupportingPlane();
1347                        lowestCost = candidateCost;
1348                }
1349        }
1350       
1351        //-- choose candidate planes extracted from rays
1352        for (int i = 0; i < mMaxRayCandidates; ++ i)
1353        {
1354                plane = ChooseCandidatePlane3(*data.mRays);
1355                const float candidateCost = SplitPlaneCost(plane, data);
1356
1357                if (candidateCost < lowestCost)
1358                {
1359                        bestPlane = plane;     
1360                        lowestCost = candidateCost;
1361                }
1362        }
1363
1364#ifdef _DEBUG
1365        Debug << "plane lowest cost: " << lowestCost << endl;
1366#endif
1367
1368        return bestPlane;
1369}
1370
1371
1372float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1373                                                          const PolygonContainer &polys) const
1374{
1375        float val = 0;
1376
1377        float sumBalancedPolys = 0;
1378        float sumSplits = 0;
1379        float sumPolyArea = 0;
1380        float sumBalancedViewCells = 0;
1381        float sumBlockedRays = 0;
1382        float totalBlockedRays = 0;
1383        //float totalArea = 0;
1384        int totalViewCells = 0;
1385
1386        // need three unique ids for each type of view cell
1387        // for balanced view cells criterium
1388        ViewCell::NewMail();
1389        const int backId = ViewCell::sMailId;
1390        ViewCell::NewMail();
1391        const int frontId = ViewCell::sMailId;
1392        ViewCell::NewMail();
1393        const int frontAndBackId = ViewCell::sMailId;
1394
1395        bool useRand;;
1396        int limit;
1397
1398        // choose test polyongs randomly if over threshold
1399        if ((int)polys.size() > mMaxTests)
1400        {
1401                useRand = true;
1402                limit = mMaxTests;
1403        }
1404        else
1405        {
1406                useRand = false;
1407                limit = (int)polys.size();
1408        }
1409
1410        for (int i = 0; i < limit; ++ i)
1411        {
1412                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1413
1414                Polygon3 *poly = polys[testIdx];
1415
1416        const int classification =
1417                        poly->ClassifyPlane(candidatePlane, mEpsilon);
1418
1419                if (mSplitPlaneStrategy & BALANCED_POLYS)
1420                        sumBalancedPolys += sBalancedPolysTable[classification];
1421               
1422                if (mSplitPlaneStrategy & LEAST_SPLITS)
1423                        sumSplits += sLeastPolySplitsTable[classification];
1424
1425                if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1426                {
1427                        if (classification == Polygon3::COINCIDENT)
1428                                sumPolyArea += poly->GetArea();
1429                        //totalArea += area;
1430                }
1431               
1432                if (mSplitPlaneStrategy & BLOCKED_RAYS)
1433                {
1434                        const float blockedRays = (float)poly->mPiercingRays.size();
1435               
1436                        if (classification == Polygon3::COINCIDENT)
1437                                sumBlockedRays += blockedRays;
1438                       
1439                        totalBlockedRays += blockedRays;
1440                }
1441
1442                // assign view cells to back or front according to classificaion
1443                if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1444                {
1445                        MeshInstance *viewCell = poly->mParent;
1446               
1447                        // assure that we only count a view cell
1448                        // once for the front and once for the back side of the plane
1449                        if (classification == Polygon3::FRONT_SIDE)
1450                        {
1451                                if ((viewCell->mMailbox != frontId) &&
1452                                        (viewCell->mMailbox != frontAndBackId))
1453                                {
1454                                        sumBalancedViewCells += 1.0;
1455
1456                                        if (viewCell->mMailbox != backId)
1457                                                viewCell->mMailbox = frontId;
1458                                        else
1459                                                viewCell->mMailbox = frontAndBackId;
1460                                       
1461                                        ++ totalViewCells;
1462                                }
1463                        }
1464                        else if (classification == Polygon3::BACK_SIDE)
1465                        {
1466                                if ((viewCell->mMailbox != backId) &&
1467                                    (viewCell->mMailbox != frontAndBackId))
1468                                {
1469                                        sumBalancedViewCells -= 1.0;
1470
1471                                        if (viewCell->mMailbox != frontId)
1472                                                viewCell->mMailbox = backId;
1473                                        else
1474                                                viewCell->mMailbox = frontAndBackId;
1475
1476                                        ++ totalViewCells;
1477                                }
1478                        }
1479                }
1480        }
1481
1482        const float polysSize = (float)polys.size() + Limits::Small;
1483
1484        // all values should be approx. between 0 and 1 so they can be combined
1485        // and scaled with the factors according to their importance
1486        if (mSplitPlaneStrategy & BALANCED_POLYS)
1487                val += mBalancedPolysFactor * fabs(sumBalancedPolys) / polysSize;
1488       
1489        if (mSplitPlaneStrategy & LEAST_SPLITS) 
1490                val += mLeastSplitsFactor * sumSplits / polysSize;
1491
1492        if (mSplitPlaneStrategy & LARGEST_POLY_AREA)
1493                // HACK: polys.size should be total area so scaling is between 0 and 1
1494                val += mLargestPolyAreaFactor * (float)polys.size() / sumPolyArea;
1495
1496        if (mSplitPlaneStrategy & BLOCKED_RAYS)
1497                if (totalBlockedRays != 0)
1498                        val += mBlockedRaysFactor * (totalBlockedRays - sumBlockedRays) / totalBlockedRays;
1499
1500        if (mSplitPlaneStrategy & BALANCED_VIEW_CELLS)
1501                val += mBalancedViewCellsFactor * fabs(sumBalancedViewCells) /
1502                        ((float)totalViewCells + Limits::Small);
1503       
1504        return val;
1505}
1506
1507
1508inline void BspTree::GenerateUniqueIdsForPvs()
1509{
1510        Intersectable::NewMail(); sBackId = ViewCell::sMailId;
1511        Intersectable::NewMail(); sFrontId = ViewCell::sMailId;
1512        Intersectable::NewMail(); sFrontAndBackId = ViewCell::sMailId;
1513}
1514
1515
1516float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1517                                                          const BoundedRayContainer &rays,
1518                                                          const int pvs,
1519                                                          const float area,
1520                                                          const BspNodeGeometry &cell) const
1521{
1522        float val = 0;
1523
1524        float sumBalancedRays = 0;
1525        float sumRaySplits = 0;
1526
1527        int frontPvs = 0;
1528        int backPvs = 0;
1529
1530        // probability that view point lies in child
1531        float pOverall = 0;
1532        float pFront = 0;
1533        float pBack = 0;
1534
1535        const bool pvsUseLen = false;
1536
1537        if (mSplitPlaneStrategy & PVS)
1538        {
1539                // create unique ids for pvs heuristics
1540                GenerateUniqueIdsForPvs();
1541
1542                if (mUseAreaForPvs) // use front and back cell areas to approximate volume
1543                {
1544                        // construct child geometry with regard to the candidate split plane
1545                        BspNodeGeometry frontCell;
1546                        BspNodeGeometry backCell;
1547
1548                        cell.SplitGeometry(frontCell,
1549                                                           backCell,
1550                                                           candidatePlane,
1551                                                           mBox,
1552                                                           mEpsilon);
1553               
1554                        pFront = frontCell.GetArea();
1555                        pBack = backCell.GetArea();
1556
1557                        pOverall = area;
1558                }
1559        }
1560                       
1561        bool useRand;
1562        int limit;
1563
1564        // choose test polyongs randomly if over threshold
1565        if ((int)rays.size() > mMaxTests)
1566        {
1567                useRand = true;
1568                limit = mMaxTests;
1569        }
1570        else
1571        {
1572                useRand = false;
1573                limit = (int)rays.size();
1574        }
1575
1576        for (int i = 0; i < limit; ++ i)
1577        {
1578                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
1579       
1580                BoundedRay *bRay = rays[testIdx];
1581
1582                Ray *ray = bRay->mRay;
1583                const float minT = bRay->mMinT;
1584                const float maxT = bRay->mMaxT;
1585
1586                Vector3 entP, extP;
1587
1588                const int cf =
1589                        ray->ClassifyPlane(candidatePlane, minT, maxT, entP, extP);
1590
1591                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1592                {
1593                        sumBalancedRays += sBalancedRaysTable[cf];
1594                }
1595               
1596                if (mSplitPlaneStrategy & BALANCED_RAYS)
1597                {
1598                        sumRaySplits += sLeastRaySplitsTable[cf];
1599                }
1600
1601                if (mSplitPlaneStrategy & PVS)
1602                {
1603                        // in case the ray intersects an object
1604                        // assure that we only count the object
1605                        // once for the front and once for the back side of the plane
1606                       
1607                        // add the termination object
1608                        if (!ray->intersections.empty())
1609                                AddObjToPvs(ray->intersections[0].mObject, cf, frontPvs, backPvs);
1610                       
1611                        // add the source object
1612                        AddObjToPvs(ray->sourceObject.mObject, cf, frontPvs, backPvs);
1613                       
1614                        if (mUseAreaForPvs)
1615                        {
1616                                float len = 1;
1617                       
1618                                if (pvsUseLen)
1619                                        len = SqrDistance(entP, extP);
1620       
1621                                // use length of rays to approximate volume
1622                                if (Ray::BACK && Ray::COINCIDENT)
1623                                        pBack += len;
1624                                if (Ray::FRONT && Ray::COINCIDENT)
1625                                        pFront += len;
1626                                if (Ray::FRONT_BACK || Ray::BACK_FRONT)
1627                                {
1628                                        if (pvsUseLen)
1629                                        {
1630                                                const Vector3 extp = ray->Extrap(maxT);
1631                                                const float t = candidatePlane.FindT(ray->GetLoc(), extp);
1632                               
1633                                                const float newT = t * maxT;
1634                                                const float newLen = SqrDistance(ray->Extrap(newT), extp);
1635
1636                                                if (Ray::FRONT_BACK)
1637                                                {
1638                                                        pFront += len - newLen;
1639                                                        pBack += newLen;
1640                                                }
1641                                                else
1642                                                {
1643                                                        pBack += len - newLen;
1644                                                        pFront += newLen;
1645                                                }
1646                                        }
1647                                        else
1648                                        {
1649                                                ++ pFront;
1650                                                ++ pBack;
1651                                        }
1652                                }
1653                        }
1654                }
1655        }
1656
1657        const float raysSize = (float)rays.size() + Limits::Small;
1658
1659        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1660                val += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1661
1662        if (mSplitPlaneStrategy & BALANCED_RAYS)
1663                val += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
1664
1665        const float denom = pOverall * (float)pvs * 2.0f + Limits::Small;
1666
1667        if (mSplitPlaneStrategy & PVS)
1668        {
1669                val += mPvsFactor * (frontPvs * pFront + (backPvs * pBack)) / denom;
1670
1671                // give penalty to unbalanced split
1672                if (0)
1673                if (((pFront * 0.2 + Limits::Small) > pBack) ||
1674                        (pFront < (pBack * 0.2 + Limits::Small)))
1675                        val += 0.5;
1676        }
1677
1678       
1679#ifdef _DEBUG
1680        Debug << "totalpvs: " << pvs << " ptotal: " << pOverall
1681                  << " frontpvs: " << frontPvs << " pFront: " << pFront
1682                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
1683#endif
1684       
1685        return val;
1686}
1687
1688void BspTree::AddObjToPvs(Intersectable *obj,
1689                                                  const int cf,
1690                                                  int &frontPvs,
1691                                                  int &backPvs) const
1692{
1693        if (!obj)
1694                return;
1695        // TODO: does this really belong to no pvs?
1696        //if (cf == Ray::COINCIDENT) return;
1697
1698        // object belongs to both PVS
1699        const bool bothSides = (cf == Ray::FRONT_BACK) ||
1700                                                   (cf == Ray::BACK_FRONT) ||
1701                                                   (cf == Ray::COINCIDENT);
1702
1703        if ((cf == Ray::FRONT) || bothSides)
1704        {
1705                if ((obj->mMailbox != sFrontId) &&
1706                        (obj->mMailbox != sFrontAndBackId))
1707                {
1708                        ++ frontPvs;
1709
1710                        if (obj->mMailbox == sBackId)
1711                                obj->mMailbox = sFrontAndBackId;       
1712                        else
1713                                obj->mMailbox = sFrontId;                                                               
1714                }
1715        }
1716       
1717        if ((cf == Ray::BACK) || bothSides)
1718        {
1719                if ((obj->mMailbox != sBackId) &&
1720                        (obj->mMailbox != sFrontAndBackId))
1721                {
1722                        ++ backPvs;
1723
1724                        if (obj->mMailbox == sFrontId)
1725                                obj->mMailbox = sFrontAndBackId;
1726                        else
1727                                obj->mMailbox = sBackId;                               
1728                }
1729        }
1730}
1731
1732float BspTree::SplitPlaneCost(const Plane3 &candidatePlane,
1733                                                          BspTraversalData &data) const
1734{
1735        float val = 0;
1736
1737        if (mSplitPlaneStrategy & VERTICAL_AXIS)
1738        {
1739                Vector3 tinyAxis(0,0,0); tinyAxis[mBox.Size().TinyAxis()] = 1.0f;
1740                // we put a penalty on the dot product between the "tiny" vertical axis
1741                // and the split plane axis
1742                val += mVerticalSplitsFactor *
1743                           fabs(DotProd(candidatePlane.mNormal, tinyAxis));
1744        }
1745
1746        // the following criteria loop over all polygons to find the cost value
1747        if ((mSplitPlaneStrategy & BALANCED_POLYS)      ||
1748                (mSplitPlaneStrategy & LEAST_SPLITS)        ||
1749                (mSplitPlaneStrategy & LARGEST_POLY_AREA)   ||
1750                (mSplitPlaneStrategy & BALANCED_VIEW_CELLS) ||
1751                (mSplitPlaneStrategy & BLOCKED_RAYS))
1752        {
1753                val += SplitPlaneCost(candidatePlane, *data.mPolygons);
1754        }
1755
1756        // the following criteria loop over all rays to find the cost value
1757        if ((mSplitPlaneStrategy & BALANCED_RAYS)      ||
1758                (mSplitPlaneStrategy & LEAST_RAY_SPLITS)   ||
1759                (mSplitPlaneStrategy & PVS))
1760        {
1761                val += SplitPlaneCost(candidatePlane, *data.mRays, data.mPvs,
1762                                                          data.mArea, *data.mGeometry);
1763        }
1764
1765        // return linear combination of the sums
1766        return val;
1767}
1768
1769void BspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1770{
1771        stack<BspNode *> nodeStack;
1772        nodeStack.push(mRoot);
1773 
1774        while (!nodeStack.empty())
1775        {
1776                BspNode *node = nodeStack.top();
1777   
1778                nodeStack.pop();
1779   
1780                if (node->IsLeaf())
1781                {
1782                        BspLeaf *leaf = (BspLeaf *)node;               
1783                        leaves.push_back(leaf);
1784                }
1785                else
1786                {
1787                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1788
1789                        nodeStack.push(interior->GetBack());
1790                        nodeStack.push(interior->GetFront());
1791                }
1792        }
1793}
1794
1795
1796AxisAlignedBox3 BspTree::GetBoundingBox() const
1797{
1798        return mBox;
1799}
1800
1801
1802BspNode *BspTree::GetRoot() const
1803{
1804        return mRoot;
1805}
1806
1807void BspTree::EvaluateLeafStats(const BspTraversalData &data)
1808{
1809        // the node became a leaf -> evaluate stats for leafs
1810        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1811
1812        // store maximal and minimal depth
1813        if (data.mDepth > mStat.maxDepth)
1814                mStat.maxDepth = data.mDepth;
1815
1816        if (data.mDepth < mStat.minDepth)
1817                mStat.minDepth = data.mDepth;
1818
1819        // accumulate depth to compute average depth
1820        mStat.accumDepth += data.mDepth;
1821        // accumulate rays to compute rays /  leaf
1822        mStat.accumRays += (int)data.mRays->size();
1823
1824        if (data.mDepth >= mTermMaxDepth)
1825                ++ mStat.maxDepthNodes;
1826
1827        if (data.mPvs < mTermMinPvs)
1828                ++ mStat.minPvsNodes;
1829
1830        if ((int)data.mRays->size() < mTermMinRays)
1831                ++ mStat.minRaysNodes;
1832
1833        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1834                ++ mStat.maxRayContribNodes;
1835       
1836        if (data.mGeometry->GetArea() <= mTermMinArea)
1837                ++ mStat.minProbabilityNodes;
1838
1839#ifdef _DEBUG
1840        Debug << "BSP stats: "
1841                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1842                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1843                  << "Area: " << data.mArea << " (min: " << mTermMinArea << "), "
1844                  << "#polygons: " << (int)data.mPolygons->size() << " (max: " << mTermMinPolys << "), "
1845                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1846                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1847                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1848#endif
1849}
1850
1851int
1852BspTree::_CastRay(Ray &ray)
1853{
1854        int hits = 0;
1855 
1856        stack<BspRayTraversalData> tStack;
1857 
1858        float maxt, mint;
1859
1860        if (!mBox.GetRaySegment(ray, mint, maxt))
1861                return 0;
1862
1863        Intersectable::NewMail();
1864
1865        Vector3 entp = ray.Extrap(mint);
1866        Vector3 extp = ray.Extrap(maxt);
1867 
1868        BspNode *node = mRoot;
1869        BspNode *farChild = NULL;
1870       
1871        while (1)
1872        {
1873                if (!node->IsLeaf())
1874                {
1875                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1876                       
1877                        Plane3 splitPlane = in->GetPlane();
1878                        const int entSide = splitPlane.Side(entp);
1879                        const int extSide = splitPlane.Side(extp);
1880
1881                        if (entSide < 0)
1882                        {
1883                                node = in->GetBack();
1884
1885                                if(extSide <= 0) // plane does not split ray => no far child
1886                                        continue;
1887                                       
1888                                farChild = in->GetFront(); // plane splits ray
1889
1890                        } else if (entSide > 0)
1891                        {
1892                                node = in->GetFront();
1893
1894                                if (extSide >= 0) // plane does not split ray => no far child
1895                                        continue;
1896
1897                                farChild = in->GetBack(); // plane splits ray                   
1898                        }
1899                        else // ray and plane are coincident
1900                        {
1901                                // WHAT TO DO IN THIS CASE ?
1902                                //break;
1903                                node = in->GetFront();
1904                                continue;
1905                        }
1906
1907                        // push data for far child
1908                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
1909
1910                        // find intersection of ray segment with plane
1911                        float t;
1912                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
1913                        maxt *= t;
1914                       
1915                } else // reached leaf => intersection with view cell
1916                {
1917                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1918     
1919                        if (!leaf->mViewCell->Mailed())
1920                        {
1921                          //                            ray.bspIntersections.push_back(Ray::BspIntersection(maxt, leaf));
1922                                leaf->mViewCell->Mail();
1923                                ++ hits;
1924                        }
1925                       
1926                        //-- fetch the next far child from the stack
1927                        if (tStack.empty())
1928                                break;
1929     
1930                        entp = extp;
1931                        mint = maxt; // NOTE: need this?
1932
1933                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1934                                break;
1935
1936                        BspRayTraversalData &s = tStack.top();
1937
1938                        node = s.mNode;
1939                        extp = s.mExitPoint;
1940                        maxt = s.mMaxT;
1941
1942                        tStack.pop();
1943                }
1944        }
1945
1946        return hits;
1947}
1948
1949
1950int BspTree::CastLineSegment(const Vector3 &origin,
1951                                                         const Vector3 &termination,
1952                                                         vector<ViewCell *> &viewcells)
1953{
1954        int hits = 0;
1955        stack<BspRayTraversalData> tStack;
1956
1957        float mint = 0.0f, maxt = 1.0f;
1958
1959        Intersectable::NewMail();
1960
1961        Vector3 entp = origin;
1962        Vector3 extp = termination;
1963
1964        BspNode *node = mRoot;
1965        BspNode *farChild = NULL;
1966
1967        while (1)
1968        {
1969                if (!node->IsLeaf()) 
1970                {
1971                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1972               
1973                        Plane3 splitPlane = in->GetPlane();
1974                       
1975                        const int entSide = splitPlane.Side(entp);
1976                        const int extSide = splitPlane.Side(extp);
1977
1978                        if (entSide < 0)
1979                        {
1980                                node = in->GetBack();
1981               
1982                                if(extSide <= 0) // plane does not split ray => no far child
1983                                        continue;
1984               
1985                                farChild = in->GetFront(); // plane splits ray
1986               
1987                        }
1988                        else if (entSide > 0)
1989                        {
1990                                node = in->GetFront();
1991                       
1992                                if (extSide >= 0) // plane does not split ray => no far child
1993                                        continue;
1994                       
1995                                farChild = in->GetBack(); // plane splits ray                   
1996                        }
1997                        else // ray and plane are coincident
1998                        {
1999                                // WHAT TO DO IN THIS CASE ?
2000                                //break;
2001                                node = in->GetFront();
2002                                continue;
2003                        }
2004               
2005                        // push data for far child
2006                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
2007               
2008                        // find intersection of ray segment with plane
2009                        float t;
2010                        extp = splitPlane.FindIntersection(origin, extp, &t);
2011                        maxt *= t; 
2012                }
2013                else
2014                {
2015                        // reached leaf => intersection with view cell
2016                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2017               
2018                        if (!leaf->mViewCell->Mailed())
2019                        {
2020                                viewcells.push_back(leaf->mViewCell);
2021                                leaf->mViewCell->Mail();
2022                                hits++;
2023                        }
2024               
2025                        //-- fetch the next far child from the stack
2026                        if (tStack.empty())
2027                                break;
2028           
2029                        entp = extp;
2030                        mint = maxt; // NOTE: need this?
2031               
2032                        BspRayTraversalData &s = tStack.top();
2033               
2034                        node = s.mNode;
2035                        extp = s.mExitPoint;
2036                        maxt = s.mMaxT;
2037               
2038                        tStack.pop();
2039                }
2040        }
2041        return hits;
2042}
2043
2044bool BspTree::Export(const string filename)
2045{
2046        Exporter *exporter = Exporter::GetExporter(filename);
2047
2048        if (exporter)
2049        {
2050                exporter->ExportBspTree(*this);
2051                return true;
2052        }       
2053
2054        return false;
2055}
2056
2057void BspTree::CollectViewCells(ViewCellContainer &viewCells) const
2058{
2059        stack<BspNode *> nodeStack;
2060        nodeStack.push(mRoot);
2061
2062        ViewCell::NewMail();
2063
2064        while (!nodeStack.empty())
2065        {
2066                BspNode *node = nodeStack.top();
2067                nodeStack.pop();
2068
2069                if (node->IsLeaf())
2070                {
2071                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->mViewCell;
2072
2073                        if (!viewCell->Mailed())
2074                        {
2075                                viewCell->Mail();
2076                                viewCells.push_back(viewCell);
2077                        }
2078                }
2079                else
2080                {
2081                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2082
2083                        nodeStack.push(interior->GetFront());
2084                        nodeStack.push(interior->GetBack());
2085                }
2086        }
2087}
2088
2089
2090BspTreeStatistics &BspTree::GetStat()
2091{
2092        return mStat;
2093}
2094
2095
2096float BspTree::AccumulatedRayLength(BoundedRayContainer &rays) const
2097{
2098        float len = 0;
2099
2100        BoundedRayContainer::const_iterator it, it_end = rays.end();
2101
2102        for (it = rays.begin(); it != it_end; ++ it)
2103        {
2104                len += SqrDistance((*it)->mRay->Extrap((*it)->mMinT),
2105                                                   (*it)->mRay->Extrap((*it)->mMaxT));
2106        }
2107
2108        return len;
2109}
2110
2111
2112int BspTree::SplitRays(const Plane3 &plane,
2113                                           BoundedRayContainer &rays,
2114                                           BoundedRayContainer &frontRays,
2115                                           BoundedRayContainer &backRays)
2116{
2117        int splits = 0;
2118       
2119        while (!rays.empty())
2120        {
2121                BoundedRay *bRay = rays.back();
2122                Ray *ray = bRay->mRay;
2123                float minT = bRay->mMinT;
2124                float maxT = bRay->mMaxT;
2125
2126                rays.pop_back();
2127       
2128                Vector3 entP, extP;
2129
2130                const int cf =
2131                        ray->ClassifyPlane(plane, minT, maxT, entP, extP);
2132               
2133                // set id to ray classification
2134                ray->SetId(cf);
2135
2136                switch (cf)
2137                {
2138                case Ray::COINCIDENT: // TODO: should really discard ray?
2139                        frontRays.push_back(bRay);
2140                        //DEL_PTR(bRay);
2141                        break;
2142                case Ray::BACK:
2143                        backRays.push_back(bRay);
2144                        break;
2145                case Ray::FRONT:
2146                        frontRays.push_back(bRay);
2147                        break;
2148                case Ray::FRONT_BACK:
2149                        {
2150                                // find intersection of ray segment with plane
2151                                const float t = plane.FindT(ray->GetLoc(), extP);
2152                               
2153                                const float newT = t * maxT;
2154
2155                                frontRays.push_back(new BoundedRay(ray, minT, newT));
2156                                backRays.push_back(new BoundedRay(ray, newT, maxT));
2157
2158                                DEL_PTR(bRay);
2159                        }
2160                        break;
2161                case Ray::BACK_FRONT:
2162                        {
2163                                // find intersection of ray segment with plane
2164                                const float t = plane.FindT(ray->GetLoc(), extP);
2165                                const float newT = t * bRay->mMaxT;
2166
2167                                backRays.push_back(new BoundedRay(ray, minT, newT));
2168                                frontRays.push_back(new BoundedRay(ray, newT, maxT));
2169
2170                                DEL_PTR(bRay);
2171
2172                                ++ splits;
2173                        }
2174                        break;
2175                default:
2176                        Debug << "Should not come here 4" << endl;
2177                        break;
2178                }
2179        }
2180
2181        return splits;
2182}
2183
2184void BspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2185{
2186        BspNode *lastNode;
2187        do
2188        {
2189                lastNode = n;
2190
2191                // want to get planes defining geometry of this node => don't take
2192                // split plane of node itself
2193                n = n->GetParent();
2194               
2195                if (n)
2196                {
2197                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2198                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2199
2200            if (interior->GetFront() != lastNode)
2201                                halfSpace.ReverseOrientation();
2202
2203                        halfSpaces.push_back(halfSpace);
2204                }
2205        }
2206        while (n);
2207}
2208
2209void BspTree::ConstructGeometry(BspViewCell *vc, BspNodeGeometry &geom) const
2210{
2211        // TODO
2212/*      vector<BspLeaf *> leaves = vc->mLeaves;
2213
2214        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2215
2216        for (it = leaves.begin(); it != it_end; ++ it)
2217                ConstructGeometry(*it, geom);*/
2218}
2219
2220
2221void BspTree::ConstructGeometry(BspNode *n, BspNodeGeometry &geom) const
2222{
2223        vector<Plane3> halfSpaces;
2224        ExtractHalfSpaces(n, halfSpaces);
2225
2226        PolygonContainer candidates;
2227
2228        // bounded planes are added to the polygons (reverse polygons
2229        // as they have to be outfacing
2230        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2231        {
2232                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2233               
2234                if (p->Valid(mEpsilon))
2235                {
2236                        candidates.push_back(p->CreateReversePolygon());
2237                        DEL_PTR(p);
2238                }
2239        }
2240
2241        // add faces of bounding box (also could be faces of the cell)
2242        for (int i = 0; i < 6; ++ i)
2243        {
2244                VertexContainer vertices;
2245       
2246                for (int j = 0; j < 4; ++ j)
2247                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2248
2249                candidates.push_back(new Polygon3(vertices));
2250        }
2251
2252        for (int i = 0; i < (int)candidates.size(); ++ i)
2253        {
2254                // polygon is split by all other planes
2255                for (int j = 0; (j < (int)halfSpaces.size()) && candidates[i]; ++ j)
2256                {
2257                        if (i == j) // polygon and plane are coincident
2258                                continue;
2259
2260                        VertexContainer splitPts;
2261                        Polygon3 *frontPoly, *backPoly;
2262
2263                        const int cf = candidates[i]->
2264                                ClassifyPlane(halfSpaces[j], mEpsilon);
2265                       
2266                        switch (cf)
2267                        {
2268                                case Polygon3::SPLIT:
2269                                        frontPoly = new Polygon3();
2270                                        backPoly = new Polygon3();
2271
2272                                        candidates[i]->Split(halfSpaces[j],
2273                                                                                 *frontPoly,
2274                                                                                 *backPoly,
2275                                                                                 mEpsilon);
2276
2277                                        DEL_PTR(candidates[i]);
2278
2279                                        if (frontPoly->Valid(mEpsilon))
2280                                                candidates[i] = frontPoly;
2281                                        else
2282                                                DEL_PTR(frontPoly);
2283
2284                                        DEL_PTR(backPoly);
2285                                        break;
2286                                case Polygon3::BACK_SIDE:
2287                                        DEL_PTR(candidates[i]);
2288                                        break;
2289                                // just take polygon as it is
2290                                case Polygon3::FRONT_SIDE:
2291                                case Polygon3::COINCIDENT:
2292                                default:
2293                                        break;
2294                        }
2295                }
2296               
2297                if (candidates[i])
2298                        geom.mPolys.push_back(candidates[i]);
2299        }
2300}
2301
2302
2303int BspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2304                                                   const bool onlyUnmailed) const
2305{
2306        BspNodeGeometry geom;
2307        ConstructGeometry(n, geom);
2308
2309        stack<BspNode *> nodeStack;
2310        nodeStack.push(mRoot);
2311               
2312        // planes needed to verify that we found neighbor leaf.
2313        vector<Plane3> halfSpaces;
2314        ExtractHalfSpaces(n, halfSpaces);
2315
2316        while (!nodeStack.empty())
2317        {
2318                BspNode *node = nodeStack.top();
2319                nodeStack.pop();
2320
2321                if (node->IsLeaf())
2322                {
2323            if (node != n && (!onlyUnmailed || !node->Mailed()))
2324                        {
2325                                // test all planes of current node if neighbour
2326                                // candidate really is neighbour
2327                                BspNodeGeometry candidateGeom;
2328                                ConstructGeometry(node, candidateGeom);
2329                               
2330                                bool isAdjacent = true;
2331                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2332                                {
2333                                        const int cf =
2334                                                Polygon3::ClassifyPlane(candidateGeom.mPolys,
2335                                                                                                halfSpaces[i],
2336                                                                                                mEpsilon);
2337
2338                                        if (cf == Polygon3::BACK_SIDE)
2339                                                isAdjacent = false;
2340                                }
2341
2342                                if (isAdjacent)
2343                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2344                        }
2345                }
2346                else
2347                {
2348                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2349       
2350                        const int cf = Polygon3::ClassifyPlane(geom.mPolys,
2351                                                                                                   interior->mPlane,
2352                                                                                                   mEpsilon);
2353
2354                        if (cf == Polygon3::FRONT_SIDE)
2355                                nodeStack.push(interior->GetFront());
2356                        else
2357                                if (cf == Polygon3::BACK_SIDE)
2358                                        nodeStack.push(interior->GetBack());
2359                                else
2360                                {
2361                                        // random decision
2362                                        nodeStack.push(interior->GetBack());
2363                                        nodeStack.push(interior->GetFront());
2364                                }
2365                }
2366        }
2367       
2368        return (int)neighbors.size();
2369}
2370
2371
2372BspLeaf *BspTree::GetRandomLeaf(const Plane3 &halfspace)
2373{
2374    stack<BspNode *> nodeStack;
2375        nodeStack.push(mRoot);
2376       
2377        int mask = rand();
2378 
2379        while (!nodeStack.empty())
2380        {
2381                BspNode *node = nodeStack.top();
2382                nodeStack.pop();
2383         
2384                if (node->IsLeaf())
2385                {
2386                        return dynamic_cast<BspLeaf *>(node);
2387                }
2388                else
2389                {
2390                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2391                        BspNode *next;
2392       
2393                        BspNodeGeometry geom;
2394                        // todo: not very efficient: constructs full cell everytime
2395                        ConstructGeometry(interior, geom);
2396
2397                        const int cf = Polygon3::ClassifyPlane(geom.mPolys,
2398                                                                                                   halfspace,
2399                                                                                                   mEpsilon);
2400
2401                        if (cf == Polygon3::BACK_SIDE)
2402                                next = interior->GetFront();
2403                        else
2404                                if (cf == Polygon3::FRONT_SIDE)
2405                                        next = interior->GetFront();
2406                        else
2407                        {
2408                                // random decision
2409                                if (mask & 1)
2410                                        next = interior->GetBack();
2411                                else
2412                                        next = interior->GetFront();
2413                                mask = mask >> 1;
2414                        }
2415
2416                        nodeStack.push(next);
2417                }
2418        }
2419       
2420        return NULL;
2421}
2422
2423BspLeaf *BspTree::GetRandomLeaf(const bool onlyUnmailed)
2424{
2425        stack<BspNode *> nodeStack;
2426       
2427        nodeStack.push(mRoot);
2428
2429        int mask = rand();
2430       
2431        while (!nodeStack.empty())
2432        {
2433                BspNode *node = nodeStack.top();
2434                nodeStack.pop();
2435               
2436                if (node->IsLeaf())
2437                {
2438                        if ( (!onlyUnmailed || !node->Mailed()) )
2439                                return dynamic_cast<BspLeaf *>(node);
2440                }
2441                else
2442                {
2443                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2444
2445                        // random decision
2446                        if (mask & 1)
2447                                nodeStack.push(interior->GetBack());
2448                        else
2449                                nodeStack.push(interior->GetFront());
2450
2451                        mask = mask >> 1;
2452                }
2453        }
2454       
2455        return NULL;
2456}
2457
2458void BspTree::AddToPvs(BspLeaf *leaf,
2459                                           const BoundedRayContainer &rays,
2460                                           int &sampleContributions,
2461                                           int &contributingSamples)
2462{
2463        sampleContributions = 0;
2464        contributingSamples = 0;
2465
2466    BoundedRayContainer::const_iterator it, it_end = rays.end();
2467
2468        ViewCell *vc = leaf->GetViewCell();
2469
2470        // add contributions from samples to the PVS
2471        for (it = rays.begin(); it != it_end; ++ it)
2472        {
2473                int contribution = 0;
2474                Ray *ray = (*it)->mRay;
2475                float relContribution;
2476                if (!ray->intersections.empty())
2477                  contribution += vc->GetPvs().AddSample(ray->intersections[0].mObject,
2478                                                                                                 1.0f,
2479                                                                                                 relContribution);
2480               
2481                if (ray->sourceObject.mObject)
2482                        contribution += vc->GetPvs().AddSample(ray->sourceObject.mObject,
2483                                                                                                   1.0f,
2484                                                                                                   relContribution);
2485               
2486                if (contribution)
2487                {
2488                        sampleContributions += contribution;
2489                        ++ contributingSamples;
2490                }
2491
2492                //if (ray->mFlags & Ray::STORE_BSP_INTERSECTIONS)
2493                //      ray->bspIntersections.push_back(Ray::BspIntersection((*it)->mMinT, this));
2494        }
2495}
2496
2497int BspTree::ComputePvsSize(const BoundedRayContainer &rays) const
2498{
2499        int pvsSize = 0;
2500
2501        BoundedRayContainer::const_iterator rit, rit_end = rays.end();
2502
2503        Intersectable::NewMail();
2504
2505        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2506        {
2507                Ray *ray = (*rit)->mRay;
2508               
2509                if (!ray->intersections.empty())
2510                {
2511                        if (!ray->intersections[0].mObject->Mailed())
2512                        {
2513                                ray->intersections[0].mObject->Mail();
2514                                ++ pvsSize;
2515                        }
2516                }
2517                if (ray->sourceObject.mObject)
2518                {
2519                        if (!ray->sourceObject.mObject->Mailed())
2520                        {
2521                                ray->sourceObject.mObject->Mail();
2522                                ++ pvsSize;
2523                        }
2524                }
2525        }
2526
2527        return pvsSize;
2528}
2529
2530float BspTree::GetEpsilon() const
2531{
2532        return mEpsilon;
2533}
2534
2535
2536/*************************************************************/
2537/*            BspNodeGeometry Implementation                 */
2538/*************************************************************/
2539
2540
2541BspNodeGeometry::BspNodeGeometry(const BspNodeGeometry &rhs)
2542{
2543        mPolys.reserve(rhs.mPolys.size());
2544       
2545        PolygonContainer::const_iterator it, it_end = rhs.mPolys.end();
2546        for (it = rhs.mPolys.begin(); it != it_end; ++ it)
2547        {
2548                Polygon3 *poly = *it;
2549                mPolys.push_back(new Polygon3(*poly));
2550        }
2551}
2552
2553
2554BspNodeGeometry::~BspNodeGeometry()
2555{
2556        CLEAR_CONTAINER(mPolys);
2557}
2558
2559
2560float BspNodeGeometry::GetArea() const
2561{
2562        return Polygon3::GetArea(mPolys);
2563}
2564
2565
2566float BspNodeGeometry::GetVolume() const
2567{
2568        //-- compute volume using tetrahedralization of the geometry
2569        //   and adding the volume of the single tetrahedrons
2570        float volume = 0;
2571        const float f = 1.0f / 6.0f;
2572
2573        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2574
2575        // note: can take arbitrary point, e.g., the origin. However,
2576        // center of mass prevents precision errors
2577        const Vector3 center = CenterOfMass();
2578
2579        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2580        {
2581                Polygon3 *poly = *pit;
2582                const Vector3 v0 = poly->mVertices[0] - center;
2583
2584                for (int i = 1; i < (int)poly->mVertices.size() - 1; ++ i)
2585                {
2586                        const Vector3 v1 = poly->mVertices[i] - center;
2587                        const Vector3 v2 = poly->mVertices[i + 1] - center;
2588
2589                        volume += f * (DotProd(v0, CrossProd(v1, v2)));
2590                }
2591        }
2592
2593        return volume;
2594}
2595
2596
2597Vector3 BspNodeGeometry::CenterOfMass() const
2598{
2599        int n = 0;
2600
2601        Vector3 center(0,0,0);
2602
2603        PolygonContainer::const_iterator pit, pit_end = mPolys.end();
2604
2605        for (pit = mPolys.begin(); pit != pit_end; ++ pit)
2606        {
2607                Polygon3 *poly = *pit;
2608               
2609                VertexContainer::const_iterator vit, vit_end = poly->mVertices.end();
2610
2611                for(vit = poly->mVertices.begin(); vit != vit_end; ++ vit)
2612                {
2613                        center += *vit;
2614                        ++ n;
2615                }
2616        }
2617
2618        return center / (float)n;
2619}
2620
2621
2622void BspNodeGeometry::AddToMesh(Mesh &mesh)
2623{
2624        PolygonContainer::const_iterator it, it_end = mPolys.end();
2625       
2626        for (it = mPolys.begin(); it != mPolys.end(); ++ it)
2627        {
2628                (*it)->AddToMesh(mesh);
2629        }
2630}
2631
2632
2633void BspNodeGeometry::SplitGeometry(BspNodeGeometry &front,
2634                                                                        BspNodeGeometry &back,
2635                                                                        const Plane3 &splitPlane,
2636                                                                        const AxisAlignedBox3 &box,
2637                                                                        const float epsilon) const
2638{       
2639        // get cross section of new polygon
2640        Polygon3 *planePoly = box.CrossSection(splitPlane);
2641
2642        // split polygon with all other polygons
2643        planePoly = SplitPolygon(planePoly, epsilon);
2644
2645        //-- new polygon splits all other polygons
2646        for (int i = 0; i < (int)mPolys.size(); ++ i)
2647        {
2648                /// don't use epsilon here to get exact split planes
2649                const int cf =
2650                        mPolys[i]->ClassifyPlane(splitPlane, Limits::Small);
2651                       
2652                switch (cf)
2653                {
2654                        case Polygon3::SPLIT:
2655                                {
2656                                        Polygon3 *poly = new Polygon3(mPolys[i]->mVertices);
2657
2658                                        Polygon3 *frontPoly = new Polygon3();
2659                                        Polygon3 *backPoly = new Polygon3();
2660                               
2661                                        poly->Split(splitPlane,
2662                                                                *frontPoly,
2663                                                                *backPoly,
2664                                                                epsilon);
2665
2666                                        DEL_PTR(poly);
2667
2668                                        if (frontPoly->Valid(epsilon))
2669                                                front.mPolys.push_back(frontPoly);
2670                                        else
2671                                                DEL_PTR(frontPoly);
2672
2673                                        if (backPoly->Valid(epsilon))
2674                                                back.mPolys.push_back(backPoly);
2675                                        else
2676                                                DEL_PTR(backPoly);
2677                                }
2678                               
2679                                break;
2680                        case Polygon3::BACK_SIDE:
2681                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));                     
2682                                break;
2683                        case Polygon3::FRONT_SIDE:
2684                                front.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));     
2685                                break;
2686                        case Polygon3::COINCIDENT:
2687                                //front.mPolys.push_back(CreateReversePolygon(mPolys[i]));
2688                                back.mPolys.push_back(new Polygon3(mPolys[i]->mVertices));
2689                                break;
2690                        default:
2691                                break;
2692                }
2693        }
2694
2695        //-- finally add the new polygon to the child node geometries
2696        if (planePoly)
2697        {
2698                // add polygon with normal pointing into positive half space to back cell
2699                back.mPolys.push_back(planePoly);
2700                // add polygon with reverse orientation to front cell
2701                front.mPolys.push_back(planePoly->CreateReversePolygon());
2702        }
2703
2704        //Debug << "returning new geometry " << mPolys.size() << " f: " << front.mPolys.size() << " b: " << back.mPolys.size() << endl;
2705        //Debug << "old area " << GetArea() << " f: " << front.GetArea() << " b: " << back.GetArea() << endl;
2706}
2707
2708
2709Polygon3 *BspNodeGeometry::SplitPolygon(Polygon3 *planePoly,
2710                                                                                const float epsilon) const
2711{
2712        if (!planePoly->Valid(epsilon))
2713                DEL_PTR(planePoly);
2714
2715        // polygon is split by all other planes
2716        for (int i = 0; (i < (int)mPolys.size()) && planePoly; ++ i)
2717        {
2718                Plane3 plane = mPolys[i]->GetSupportingPlane();
2719
2720                /// don't use epsilon here to get exact split planes
2721                const int cf =
2722                        planePoly->ClassifyPlane(plane, Limits::Small);
2723                       
2724                // split new polygon with all previous planes
2725                switch (cf)
2726                {
2727                        case Polygon3::SPLIT:
2728                                {
2729                                        Polygon3 *frontPoly = new Polygon3();
2730                                        Polygon3 *backPoly = new Polygon3();
2731
2732                                        planePoly->Split(plane,
2733                                                                         *frontPoly,
2734                                                                         *backPoly,
2735                                                                         epsilon);
2736                                       
2737                                        // don't need anymore
2738                                        DEL_PTR(planePoly);
2739                                        DEL_PTR(frontPoly);
2740
2741                                        // back polygon is belonging to geometry
2742                                        if (backPoly->Valid(epsilon))
2743                                                planePoly = backPoly;
2744                                        else
2745                                                DEL_PTR(backPoly);
2746                                }
2747                                break;
2748                        case Polygon3::FRONT_SIDE:
2749                                DEL_PTR(planePoly);
2750                break;
2751                        // polygon is taken as it is
2752                        case Polygon3::BACK_SIDE:
2753                        case Polygon3::COINCIDENT:
2754                        default:
2755                                break;
2756                }
2757        }
2758
2759        return planePoly;
2760}
2761
2762
2763ViewCell *
2764BspTree::GetViewCell(const Vector3 &point)
2765{
2766  if (mRoot == NULL)
2767        return NULL;
2768 
2769
2770  stack<BspNode *> nodeStack;
2771  nodeStack.push(mRoot);
2772 
2773  ViewCell *viewcell = NULL;
2774 
2775  while (!nodeStack.empty())  {
2776        BspNode *node = nodeStack.top();
2777        nodeStack.pop();
2778       
2779        if (node->IsLeaf()) {
2780          viewcell = dynamic_cast<BspLeaf *>(node)->mViewCell;
2781          break;
2782        } else {
2783         
2784          BspInterior *interior = dynamic_cast<BspInterior *>(node);
2785               
2786          // random decision
2787          if (interior->GetPlane().Side(point) < 0)
2788                nodeStack.push(interior->GetBack());
2789          else
2790                nodeStack.push(interior->GetFront());
2791        }
2792  }
2793 
2794  return viewcell;
2795}
2796
2797void BspNodeGeometry::IncludeInBox(AxisAlignedBox3 &box)
2798{
2799        Polygon3::IncludeInBox(mPolys, box);
2800}
Note: See TracBrowser for help on using the repository browser.