source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp @ 1291

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