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

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