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

Revision 495, 67.1 KB checked in by mattausch, 19 years ago (diff)

fixed bug in tree collapse

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