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

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