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

Revision 490, 66.3 KB checked in by mattausch, 19 years ago (diff)

added loading and storing rays capability

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