source: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp @ 2283

Revision 2283, 98.6 KB checked in by mattausch, 17 years ago (diff)
RevLine 
[478]1#include <stack>
2#include <time.h>
3#include <iomanip>
4
[463]5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
[478]17#include "ViewCellsManager.h"
[532]18#include "Beam.h"
[1603]19#include "IntersectableWrapper.h"
[463]20
[1077]21
22
[863]23namespace GtpVisibilityPreprocessor {
[860]24
[1077]25
[639]26#define USE_FIXEDPOINT_T 0
[1020]27#define COUNT_ORIGIN_OBJECTS 1
[590]28
[2072]29#define STORE_PVS 0
[1580]30
[2066]31
[1580]32//////////////
[463]33//-- static members
[508]34
[482]35int VspBspTree::sFrontId = 0;
[463]36int VspBspTree::sBackId = 0;
37int VspBspTree::sFrontAndBackId = 0;
38
[1020]39
40
[697]41typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
[463]42
[557]43
[579]44// pvs penalty can be different from pvs size
[1765]45inline static float EvalPvsPenalty(const float pvs,
46                                                                   const float lower,
47                                                                   const float upper)
[579]48{
49        // clamp to minmax values
50        if (pvs < lower)
51                return (float)lower;
52        if (pvs > upper)
53                return (float)upper;
[578]54
[579]55        return (float)pvs;
56}
[463]57
[557]58
[579]59
60
[601]61/******************************************************************************/
62/*                       class VspBspTree implementation                      */
63/******************************************************************************/
[579]64
65
[1004]66VspBspTree::VspBspTree():
[463]67mRoot(NULL),
[547]68mUseAreaForPvs(false),
[478]69mCostNormalizer(Limits::Small),
70mViewCellsManager(NULL),
[497]71mOutOfBoundsCell(NULL),
[643]72mStoreRays(false),
[605]73mRenderCostWeight(0.5),
[610]74mUseRandomAxis(false),
[650]75mTimeStamp(1)
[463]76{
[486]77        bool randomize = false;
[1004]78        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.randomize", randomize);
[1011]79        if (randomize) Randomize(); // initialise random generator for heuristics
[463]80
[1557]81        //////////////////
[463]82        //-- termination criteria for autopartition
[1557]83
[1004]84        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
85        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
86        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
87        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
88        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
89        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
[1023]90       
[1004]91        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
92        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
[666]93
[1557]94        ////////////////////////
95        //-- cost ratios for early tree termination
[1004]96        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
97        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
98        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
[610]99
[1557]100        ///////////
[463]101        //-- factors for bsp tree split plane heuristics
[1557]102
[1004]103        Environment::GetSingleton()->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
104        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
[463]105
[1557]106        //////////
107        //-- partition criteria
[482]108
[1004]109        Environment::GetSingleton()->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
110        Environment::GetSingleton()->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
111        Environment::GetSingleton()->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
[463]112
[1004]113        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
114        Environment::GetSingleton()->GetIntValue("VspBspTree.maxTests", mMaxTests);
[463]115
[564]116        // if only the driving axis is used for axis aligned split
[1004]117        Environment::GetSingleton()->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
[580]118       
[1557]119        //////////////////////
[508]120        //-- termination criteria for axis aligned split
[1004]121        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
[665]122                                                                mTermMaxRayContriForAxisAligned);
[1004]123        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
[665]124                                                         mTermMinRaysForAxisAligned);
[487]125
[1004]126        Environment::GetSingleton()->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
[508]127
[1004]128        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
[1020]129        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight);
[1004]130        Environment::GetSingleton()->GetBoolValue("VspBspTree.usePolygonSplitIfAvailable", mUsePolygonSplitIfAvailable);
[547]131
[1004]132        Environment::GetSingleton()->GetBoolValue("VspBspTree.useCostHeuristics", mUseCostHeuristics);
133        Environment::GetSingleton()->GetBoolValue("VspBspTree.useSplitCostQueue", mUseSplitCostQueue);
134        Environment::GetSingleton()->GetBoolValue("VspBspTree.simulateOctree", mCirculatingAxis);
135        Environment::GetSingleton()->GetBoolValue("VspBspTree.useRandomAxis", mUseRandomAxis);
136        Environment::GetSingleton()->GetIntValue("VspBspTree.nodePriorityQueueType", mNodePriorityQueueType);
[580]137
[676]138       
[660]139        char subdivisionStatsLog[100];
[1004]140        Environment::GetSingleton()->GetStringValue("VspBspTree.subdivisionStats", subdivisionStatsLog);
[660]141        mSubdivisionStats.open(subdivisionStatsLog);
[612]142
[1004]143        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.minBand", mMinBand);
144        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.maxBand", mMaxBand);
[1006]145        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.useDrivingAxisForMaxCost", mUseDrivingAxisIfMaxCostViolated);
[801]146
[1557]147        /////////
[478]148        //-- debug output
[580]149
[473]150        Debug << "******* VSP BSP options ******** " << endl;
151    Debug << "max depth: " << mTermMaxDepth << endl;
152        Debug << "min PVS: " << mTermMinPvs << endl;
[547]153        Debug << "min probabiliy: " << mTermMinProbability << endl;
[473]154        Debug << "min rays: " << mTermMinRays << endl;
155        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
156        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
157        Debug << "miss tolerance: " << mTermMissTolerance << endl;
158        Debug << "max view cells: " << mMaxViewCells << endl;
159        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
[486]160        Debug << "randomize: " << randomize << endl;
[582]161
[551]162        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
[580]163        Debug << "render cost weight: " << mRenderCostWeight << endl;
[663]164        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
165        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
166        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
167        Debug << "max memory: " << mMaxMemory << endl;
168        Debug << "use poly split if available: " << mUsePolygonSplitIfAvailable << endl;
169        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
170        Debug << "use split cost queue: " << mUseSplitCostQueue << endl;
171        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
[664]172        Debug << "use random axis: " << mUseRandomAxis << endl;
[735]173        Debug << "priority queue type: " << mNodePriorityQueueType << endl;
[822]174        Debug << "circulating axis: " << mCirculatingAxis << endl;
[801]175        Debug << "minband: " << mMinBand << endl;
176        Debug << "maxband: " << mMaxBand << endl;
[1006]177        Debug << "use driving axis for max cost: " << mUseDrivingAxisIfMaxCostViolated << endl;
[1020]178        Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl;
[663]179
[463]180        Debug << "Split plane strategy: ";
[564]181
[463]182        if (mSplitPlaneStrategy & RANDOM_POLYGON)
[474]183        {
[463]184                Debug << "random polygon ";
[474]185        }
[463]186        if (mSplitPlaneStrategy & AXIS_ALIGNED)
[472]187        {
[463]188                Debug << "axis aligned ";
[472]189        }
[665]190        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
[472]191        {
[474]192                mCostNormalizer += mLeastRaySplitsFactor;
[463]193                Debug << "least ray splits ";
[472]194        }
[463]195        if (mSplitPlaneStrategy & BALANCED_RAYS)
[472]196        {
[474]197                mCostNormalizer += mBalancedRaysFactor;
[463]198                Debug << "balanced rays ";
[472]199        }
[463]200        if (mSplitPlaneStrategy & PVS)
[472]201        {
[474]202                mCostNormalizer += mPvsFactor;
[463]203                Debug << "pvs";
[665]204        }
[482]205
[1557]206        Debug << endl;
[489]207
[1233]208        mLocalSubdivisionCandidates = new vector<SortableEntry>;
[463]209}
[580]210
[1027]211
[508]212BspViewCell *VspBspTree::GetOutOfBoundsCell()
213{
214        return mOutOfBoundsCell;
215}
[463]216
[508]217
[489]218BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
219{
220        if (!mOutOfBoundsCell)
[508]221        {
[489]222                mOutOfBoundsCell = new BspViewCell();
[1557]223                mOutOfBoundsCell->SetId(OUT_OF_BOUNDS_ID);
[547]224                mOutOfBoundsCell->SetValid(false);
[508]225        }
[547]226
[489]227        return mOutOfBoundsCell;
228}
229
230
[482]231const BspTreeStatistics &VspBspTree::GetStatistics() const
[463]232{
[574]233        return mBspStats;
[463]234}
235
236
237VspBspTree::~VspBspTree()
238{
239        DEL_PTR(mRoot);
[1233]240        DEL_PTR(mLocalSubdivisionCandidates);
[463]241}
242
[579]243
[482]244int VspBspTree::AddMeshToPolygons(Mesh *mesh,
[1632]245                                                                  PolygonContainer &polys) const
[463]246{
[1632]247        if (!mesh) return 0;
[1603]248
[463]249        FaceContainer::const_iterator fi;
[482]250
[463]251        // copy the face data to polygons
252        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
253        {
254                Polygon3 *poly = new Polygon3((*fi), mesh);
[482]255
[463]256                if (poly->Valid(mEpsilon))
257                {
258                        polys.push_back(poly);
259                }
260                else
[1558]261                {
[463]262                        DEL_PTR(poly);
[1558]263                }
[463]264        }
[1603]265
[463]266        return (int)mesh->mFaces.size();
267}
268
[580]269
[1632]270void VspBspTree::ExtractPolygons(Intersectable *object, PolygonContainer &polys) const
[463]271{
[1632]272        // extract the polygons from the intersectables
273        switch (object->Type())
[463]274        {
275                case Intersectable::MESH_INSTANCE:
[1632]276                        {
[2017]277                                Mesh *mesh = static_cast<MeshInstance *>(object)->GetMesh();
[1632]278                                AddMeshToPolygons(mesh, polys);
279                        }
[463]280                        break;
281                case Intersectable::VIEW_CELL:
[1632]282                        {
[2017]283                                Mesh *mesh = static_cast<ViewCell *>(object)->GetMesh();
[1632]284                                AddMeshToPolygons(mesh, polys);
285                                break;
286                        }
[1001]287                case Intersectable::TRANSFORMED_MESH_INSTANCE:
288                        {
[1603]289                                TransformedMeshInstance *mi =
[2017]290                                        static_cast<TransformedMeshInstance *>(object);
[1001]291
[1603]292                                Mesh mesh;
293                                mi->GetTransformedMesh(mesh);
[1632]294                                AddMeshToPolygons(&mesh, polys);
[1001]295                        }
[1632]296                        break;
[1603]297                case Intersectable::TRIANGLE_INTERSECTABLE:
298                        {
299                                TriangleIntersectable *intersect =
[2017]300                                        static_cast<TriangleIntersectable *>(object);
[1603]301
302                                Polygon3 *poly = new Polygon3(intersect->GetItem());
303
304                                if (poly->Valid(mEpsilon))     
[1632]305                                {
[1603]306                                        polys.push_back(poly);
[1632]307                                }
[1603]308                                else
[1632]309                                {
[1603]310                                        delete poly;
[1632]311                                }
[1603]312                        }
[1632]313                        break;
[463]314                default:
[1632]315                        Debug << "intersectable type not supported" << endl;
[463]316                        break;
[1632]317        }
318}
[482]319
[1632]320
321int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
322                                                                 PolygonContainer &polys,
323                                                                 int maxObjects)
324{
325        const int limit = (maxObjects > 0) ?
326                Min((int)objects.size(), maxObjects) : (int)objects.size();
327
328        for (int i = 0; i < limit; ++i)
329        {
330                Intersectable *object = objects[i];//*it;
331                ExtractPolygons(object, polys);
332
[2070]333                 // add to BSP tree aabb
334                mBoundingBox.Include(object->GetBox());
[463]335        }
336
337        return (int)polys.size();
338}
339
[580]340
[1027]341void VspBspTree::ComputeBoundingBox(const VssRayContainer &sampleRays,
342                                                                        AxisAlignedBox3 *forcedBoundingBox)
343{
344        if (forcedBoundingBox)
345        {
[1563]346                mBoundingBox = *forcedBoundingBox;
[1027]347        }
348        else // compute vsp tree bounding box
349        {
[1563]350                mBoundingBox.Initialize();
[1027]351
352                VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
353
354                //-- compute bounding box
355        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
356                {
357                        VssRay *ray = *rit;
358
359                        // compute bounding box of view space
[1563]360                        mBoundingBox.Include(ray->GetTermination());
361                        mBoundingBox.Include(ray->GetOrigin());
[1027]362                }
363        }
364}
365
366
[483]367void VspBspTree::Construct(const VssRayContainer &sampleRays,
368                                                   AxisAlignedBox3 *forcedBoundingBox)
[463]369{
[1027]370        // Compute the bounding box from the rays
371        ComputeBoundingBox(sampleRays, forcedBoundingBox);
[484]372       
[463]373        PolygonContainer polys;
374        RayInfoContainer *rays = new RayInfoContainer();
375
[1564]376        ////////////
377        //-- extract polygons from rays if polygon candidate planes are required
378
[1027]379        if (mMaxPolyCandidates)
380        {
381                int numObj = 0;
382                Intersectable::NewMail();
[463]383
[1027]384        cout << "Extracting polygons from rays ... ";
[1580]385                const long startTime = GetTime();
[463]386
[1027]387        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
[542]388
[1027]389                //-- extract polygons intersected by the rays
390                for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
[463]391                {
[1027]392                        VssRay *ray = *rit;
393                        Intersectable *obj = ray->mTerminationObject;
[1002]394
[1632]395                        ++ numObj;
[1027]396
[1632]397                        /////////
398                        //-- compute bounding box
[1603]399
[1632]400                        if (!forcedBoundingBox)
401                        {
402                                mBoundingBox.Include(ray->mTermination);
[1002]403                        }
[1027]404
[1563]405                        if ((mBoundingBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
[1027]406                                ray->mOriginObject &&
407                                !ray->mOriginObject->Mailed())
408                        {               
409                                ray->mOriginObject->Mail();
[1632]410                                ExtractPolygons(ray->mOriginObject, polys);
411                                                               
[1027]412                                ++ numObj;
[1002]413                        }
[1027]414                }
[1002]415
[1027]416                // throw out unnecessary polygons
417                PreprocessPolygons(polys);
418                cout << "finished" << endl;
[463]419
[1027]420                Debug << "\n" << (int)polys.size() << " polys extracted from "
421                  << (int)sampleRays.size() << " rays in "
422                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
[463]423        }
[535]424       
[1027]425        Debug << "maximal pvs (i.e., pvs still considered as valid): "
[653]426                  << mViewCellsManager->GetMaxPvsSize() << endl;
[580]427
[1027]428        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
429
[2070]430        /////////
[463]431        //-- store rays
432        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
433        {
434                VssRay *ray = *rit;
[482]435
[463]436                float minT, maxT;
437
[564]438                static Ray hray;
439                hray.Init(*ray);
[562]440
[483]441                // TODO: not very efficient to implictly cast between rays types
[1563]442                if (mBoundingBox.GetRaySegment(hray, minT, maxT))
[463]443                {
444                        float len = ray->Length();
[482]445
446                        if (!len)
[463]447                                len = Limits::Small;
[482]448
[463]449                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
450                }
451        }
452
[547]453        if (mUseAreaForPvs)
[1563]454                mTermMinProbability *= mBoundingBox.SurfaceArea();
[2072]455        else // normalize volume
[1563]456                mTermMinProbability *= mBoundingBox.GetVolume();
[547]457
[1027]458        mBspStats.nodes = 1;
[574]459        mBspStats.polys = (int)polys.size();
[1449]460        mBspStats.mGlobalCostMisses = 0;
[654]461
[463]462
[655]463        // use split cost priority queue
464        if (mUseSplitCostQueue)
465        {
[654]466                ConstructWithSplitQueue(polys, rays);
[655]467        }
[654]468        else
[655]469        {
[654]470                Construct(polys, rays);
[655]471        }
[463]472
473        // clean up polygons
474        CLEAR_CONTAINER(polys);
475}
476
[508]477
[612]478// TODO: return memory usage in MB
[656]479float VspBspTree::GetMemUsage() const
[508]480{
[656]481        return (float)
482                 (sizeof(VspBspTree) +
483                  mBspStats.Leaves() * sizeof(BspLeaf) +
484                  mCreatedViewCells * sizeof(BspViewCell) +
[1189]485                  mBspStats.pvs * sizeof(PvsData) +
[656]486                  mBspStats.Interior() * sizeof(BspInterior) +
487                  mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
[508]488}
489
490
[463]491void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
492{
[600]493        VspBspTraversalQueue tQueue;
[463]494
[1016]495        /// create new vsp tree
[463]496        mRoot = new BspLeaf();
497
498        // constrruct root node geometry
499        BspNodeGeometry *geom = new BspNodeGeometry();
500        ConstructGeometry(mRoot, *geom);
501
[1016]502        /// we use the overall probability as normalizer
503        /// either the overall area or the volume
[547]504        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
505
[1020]506        /// first traversal data
[482]507        VspBspTraversalData tData(mRoot,
508                                                          new PolygonContainer(polys),
[463]509                                                          0,
[482]510                                                          rays,
511                              ComputePvsSize(*rays),
[547]512                                                          prop,
[463]513                                                          geom);
[663]514
[1302]515        // evaluate the priority of this traversal data
[664]516        EvalPriority(tData);
[663]517
[578]518        // first node is kd node, i.e. an axis aligned box
[710]519        if (1)
[578]520        tData.mIsKdNode = true;
521        else
522                tData.mIsKdNode = false;
[562]523
[600]524        tQueue.push(tData);
[463]525
[609]526
[1563]527        mTotalCost = tData.mPvs * tData.mProbability / mBoundingBox.GetVolume();
[607]528        mTotalPvsSize = tData.mPvs;
529       
[1020]530        // first subdivison statistics
531        AddSubdivisionStats(1, 0, 0, mTotalCost, (float)mTotalPvsSize);
532   
[574]533        mBspStats.Start();
[667]534        cout << "Constructing vsp bsp tree ... \n";
[463]535
[1016]536        const long startTime = GetTime();       
537        // used for intermediate time measurements and progress
538        long interTime = GetTime();
539
[664]540        int nLeaves = 500;
541        int nViewCells = 500;
[587]542
[542]543        mOutOfMemory = false;
[612]544        mCreatedViewCells = 0;
545       
[600]546        while (!tQueue.empty())
[463]547        {
[600]548                tData = tQueue.top();
549            tQueue.pop();               
[463]550
[508]551                if (0 && !mOutOfMemory)
552                {
553                        float mem = GetMemUsage();
[478]554
[508]555                        if (mem > mMaxMemory)
556                        {
557                                mOutOfMemory = true;
558                                Debug << "memory limit reached: " << mem << endl;
559                        }
560                }
561
[587]562                // subdivide leaf node
[1016]563                const BspNode *r = Subdivide(tQueue, tData);
[463]564
565                if (r == mRoot)
[482]566                        Debug << "VSP BSP tree construction time spent at root: "
[542]567                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
568
[654]569                if (mBspStats.Leaves() >= nLeaves)
[542]570                {
[612]571                        nLeaves += 500;
572
[574]573                        cout << "leaves=" << mBspStats.Leaves() << endl;
[542]574                        Debug << "needed "
[587]575                                  << TimeDiff(interTime, GetTime())*1e-3
[612]576                                  << " secs to create 500 view cells" << endl;
[542]577                        interTime = GetTime();
578                }
[612]579
[664]580                if (mCreatedViewCells >= nViewCells)
[612]581                {
582                        nViewCells += 500;
583
584                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
585                }
[463]586        }
587
[542]588        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
[1020]589        cout << "finished in " << TimeDiff(startTime, GetTime())*1e-3 << "secs" << endl;
[463]590
[574]591        mBspStats.Stop();
[463]592}
593
[508]594
[653]595
[654]596void VspBspTree::ConstructWithSplitQueue(const PolygonContainer &polys,
[653]597                                                                                          RayInfoContainer *rays)
598{
599        VspBspSplitQueue tQueue;
600
601        mRoot = new BspLeaf();
602
603        // constrruct root node geometry
604        BspNodeGeometry *geom = new BspNodeGeometry();
605        ConstructGeometry(mRoot, *geom);
606
607        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
608
609        VspBspTraversalData tData(mRoot,
610                                                          new PolygonContainer(polys),
611                                                          0,
612                                                          rays,
613                              ComputePvsSize(*rays),
614                                                          prop,
615                                                          geom);
616
[663]617
[1076]618        // first node is kd node, i.e. an axis aligned box
619        if (1)
620        tData.mIsKdNode = true;
621        else
622                tData.mIsKdNode = false;
623
[660]624        // compute first split candidate
[1233]625        VspBspSubdivisionCandidate splitCandidate;
[1145]626        splitCandidate.mParentData = tData;
[653]627
[1233]628        EvalSubdivisionCandidate(splitCandidate);
[1145]629
[653]630        tQueue.push(splitCandidate);
631
[1563]632        mTotalCost = tData.mPvs * tData.mProbability / mBoundingBox.GetVolume();
[653]633        mTotalPvsSize = tData.mPvs;
634       
[1020]635        // first subdivison statistics
636        AddSubdivisionStats(1, 0, 0, mTotalCost, (float)mTotalPvsSize);
637   
638    mBspStats.Start();
[667]639        cout << "Constructing vsp bsp tree ... \n";
[653]640
641        long startTime = GetTime();     
[666]642        int nLeaves = 500;
643        int nViewCells = 500;
[653]644
645        // used for intermediate time measurements and progress
646        long interTime = GetTime();     
647
648        mOutOfMemory = false;
649
650        mCreatedViewCells = 0;
651       
652        while (!tQueue.empty())
653        {
654                splitCandidate = tQueue.top();
655            tQueue.pop();               
656
[654]657                // cost ratio of cost decrease / totalCost
[1288]658                float costRatio = splitCandidate.mRenderCostDecr / mTotalCost;
[654]659
[655]660                //Debug << "cost ratio: " << costRatio << endl;
[654]661                if (costRatio < mTermMinGlobalCostRatio)
[1449]662                {
663                        ++ mBspStats.mGlobalCostMisses;
664                }
665
[653]666                if (0 && !mOutOfMemory)
667                {
668                        float mem = GetMemUsage();
669                        if (mem > mMaxMemory)
670                        {
671                                mOutOfMemory = true;
672                                Debug << "memory limit reached: " << mem << endl;
673                        }
674                }
675
676                // subdivide leaf node
677                BspNode *r = Subdivide(tQueue, splitCandidate);
678
679                if (r == mRoot)
[1449]680                {
[2069]681                        cout << "VSP BSP tree construction time spent at root: "
682                                 << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
[1449]683                }
[653]684
[654]685                if (mBspStats.Leaves() >= nLeaves)
[653]686                {
687                        nLeaves += 500;
688
689                        cout << "leaves=" << mBspStats.Leaves() << endl;
690                        Debug << "needed "
691                                  << TimeDiff(interTime, GetTime())*1e-3
692                                  << " secs to create 500 view cells" << endl;
693                        interTime = GetTime();
694                }
695
696                if (mCreatedViewCells == nViewCells)
697                {
698                        nViewCells += 500;
699                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
700                }
701        }
702
703        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
704        cout << "finished\n";
705
706        mBspStats.Stop();
707}
708
709
[654]710bool VspBspTree::LocalTerminationCriteriaMet(const VspBspTraversalData &data) const
[463]711{
[482]712        return
[463]713                (((int)data.mRays->size() <= mTermMinRays) ||
[473]714                 (data.mPvs <= mTermMinPvs)   ||
[547]715                 (data.mProbability <= mTermMinProbability) ||
[535]716                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
[463]717                 (data.mDepth >= mTermMaxDepth));
718}
719
[508]720
[1020]721void VspBspTree::AddSubdivisionStats(const int viewCells,
722                                                                         const float renderCostDecr,
723                                                                         const float splitCandidateCost,
724                                                                         const float totalRenderCost,
725                                                                         const float avgRenderCost)
726{
727        mSubdivisionStats
728                        << "#ViewCells\n" << viewCells << endl
729                        << "#RenderCostDecrease\n" << renderCostDecr << endl
[1233]730                        << "#SubdivisionCandidateCost\n" << splitCandidateCost << endl
[1020]731                        << "#TotalRenderCost\n" << totalRenderCost << endl
732                        << "#AvgRenderCost\n" << avgRenderCost << endl;
733}
734
735
[654]736bool VspBspTree::GlobalTerminationCriteriaMet(const VspBspTraversalData &data) const
737{
738        return
[1302]739                (0
740                || mOutOfMemory
[654]741                || (mBspStats.Leaves() >= mMaxViewCells)
[1449]742                || (mBspStats.mGlobalCostMisses >= mTermGlobalCostMissTolerance)
[654]743                 );
744}
745
746
[600]747BspNode *VspBspTree::Subdivide(VspBspTraversalQueue &tQueue,
[463]748                                                           VspBspTraversalData &tData)
749{
[473]750        BspNode *newNode = tData.mNode;
751
[654]752        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
[473]753        {
754                PolygonContainer coincident;
[482]755
[473]756                VspBspTraversalData tFrontData;
757                VspBspTraversalData tBackData;
[612]758
[473]759                // create new interior node and two leaf nodes
760                // or return leaf as it is (if maxCostRatio missed)
[653]761                int splitAxis;
762                bool splitFurther = true;
763                int maxCostMisses = tData.mMaxCostMisses;
764               
765                Plane3 splitPlane;
[2017]766                BspLeaf *leaf = static_cast<BspLeaf *>(tData.mNode);
[726]767               
768                // choose next split plane
[653]769                if (!SelectPlane(splitPlane, leaf, tData, tFrontData, tBackData, splitAxis))
[473]770                {
[653]771                        ++ maxCostMisses;
772
773                        if (maxCostMisses > mTermMissTolerance)
774                        {
775                                // terminate branch because of max cost
776                                ++ mBspStats.maxCostNodes;
777                                splitFurther = false;
778                        }
779                }
780       
[726]781                // if this a valid split => subdivide this node further
[1193]782
783                if (splitFurther)
[653]784                {
785                        newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
786
787                        if (splitAxis < 3)
788                                ++ mBspStats.splits[splitAxis];
789                        else
790                                ++ mBspStats.polySplits;
791
[822]792                        // if it was a kd node (i.e., a box) and the split axis is axis aligned, it is still a kd node
[710]793                        tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
[1076]794                       
[726]795                        tFrontData.mAxis = tBackData.mAxis = splitAxis;
[663]796
[653]797                        // how often was max cost ratio missed in this branch?
798                        tFrontData.mMaxCostMisses = maxCostMisses;
799                        tBackData.mMaxCostMisses = maxCostMisses;
800
[664]801                        EvalPriority(tFrontData);
802                        EvalPriority(tBackData);
[663]803
[726]804                        // evaluate subdivision stats
[600]805                        if (1)
[1145]806                                EvalSubdivisionStats(tData, tFrontData, tBackData);
807                       
[605]808
[473]809                        // push the children on the stack
[600]810                        tQueue.push(tFrontData);
811                        tQueue.push(tBackData);
[473]812
813                        // delete old leaf node
[482]814                        DEL_PTR(tData.mNode);
[473]815                }
816        }
[482]817
[478]818        //-- terminate traversal and create new view cell
[473]819        if (newNode->IsLeaf())
[463]820        {
[2017]821                BspLeaf *leaf = static_cast<BspLeaf *>(newNode);
[1020]822               
[547]823                BspViewCell *viewCell = new BspViewCell();
[463]824                leaf->SetViewCell(viewCell);
[487]825       
[2066]826                if (STORE_PVS)
827                {
828                        //////////
829                        //-- update pvs
[487]830
[2066]831                        int conSamp = 0;
832                        float sampCon = 0.0f;
[752]833
[2066]834                        AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
[487]835
[2066]836                        // update scalar pvs size lookup
837                        ObjectPvs &pvs = viewCell->GetPvs();
838                        mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.EvalPvsCost(), pvs.GetSize());
839               
840                        mBspStats.contributingSamples += conSamp;
841                        mBspStats.sampleContributions += (int)sampCon;
842                }
843
844                //////////
[487]845                //-- store additional info
[2066]846
[478]847                if (mStoreRays)
848                {
849                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
850                        for (it = tData.mRays->begin(); it != it_end; ++ it)
[639]851                        {
852                                (*it).mRay->Ref();                     
[478]853                                leaf->mVssRays.push_back((*it).mRay);
[639]854                        }
[478]855                }
[612]856
[564]857                // should I check here?
[1027]858                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0,
859                        mViewCellsManager->GetMaxPvsSize()))
[547]860                {
861                        viewCell->SetValid(false);
862                        leaf->SetTreeValid(false);
863                        PropagateUpValidity(leaf);
[463]864
[574]865                        ++ mBspStats.invalidLeaves;
[547]866                }
867               
[1551]868                viewCell->mLeaves.push_back(leaf);
[547]869
870                if (mUseAreaForPvs)
871                        viewCell->SetArea(tData.mProbability);
872                else
873                        viewCell->SetVolume(tData.mProbability);
874
875                leaf->mProbability = tData.mProbability;
876
[1020]877                // finally evaluate stats until this leaf
[1027]878                if (0)
879                        EvaluateLeafStats(tData);               
[463]880        }
[482]881
[473]882        //-- cleanup
[478]883        tData.Clear();
[463]884
[472]885        return newNode;
[463]886}
887
[1027]888
889// subdivide node using a split plane queue
[653]890BspNode *VspBspTree::Subdivide(VspBspSplitQueue &tQueue,
[1233]891                                                           VspBspSubdivisionCandidate &splitCandidate)
[653]892{
893        VspBspTraversalData &tData = splitCandidate.mParentData;
894
895        BspNode *newNode = tData.mNode;
896
[654]897        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
[666]898        {       
[653]899                PolygonContainer coincident;
900
901                VspBspTraversalData tFrontData;
902                VspBspTraversalData tBackData;
903
[1586]904                ////////////////////
[653]905                //-- continue subdivision
[726]906               
[653]907                // create new interior node and two leaf node
908                const Plane3 splitPlane = splitCandidate.mSplitPlane;
[654]909                               
[653]910                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
[666]911       
[660]912                const int splitAxis = splitCandidate.mSplitAxis;
913                const int maxCostMisses = splitCandidate.mMaxCostMisses;
914
[654]915                if (splitAxis < 3)
916                        ++ mBspStats.splits[splitAxis];
917                else
918                        ++ mBspStats.polySplits;
[653]919
[710]920                tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
[726]921                tFrontData.mAxis = tBackData.mAxis = splitAxis;
922
[654]923                // how often was max cost ratio missed in this branch?
924                tFrontData.mMaxCostMisses = maxCostMisses;
925                tBackData.mMaxCostMisses = maxCostMisses;
[664]926                       
[1020]927                // statistics
[653]928                if (1)
929                {
[2070]930                        const float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
931                        const float cBack = (float)tBackData.mPvs * tBackData.mProbability;
932                        const float cData = (float)tData.mPvs * tData.mProbability;
[675]933                       
[2070]934                        const float costDecr =
[1563]935                                (cFront + cBack - cData) / mBoundingBox.GetVolume();
[653]936
937                        mTotalCost += costDecr;
938                        mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
939
[1020]940                        AddSubdivisionStats(mBspStats.Leaves(),
941                                                                -costDecr, 
942                                                                splitCandidate.GetPriority(),
943                                                                mTotalCost,
944                                                                (float)mTotalPvsSize / (float)mBspStats.Leaves());
[653]945                }
946
[2070]947                ////////////
[653]948                //-- push the new split candidates on the stack
[2070]949
[1233]950                VspBspSubdivisionCandidate frontCandidate;
[1145]951                frontCandidate.mParentData = tFrontData;
952
[1233]953                VspBspSubdivisionCandidate backCandidate;
[1145]954                backCandidate.mParentData = tBackData;
[653]955
[1233]956                EvalSubdivisionCandidate(frontCandidate);
957                EvalSubdivisionCandidate(backCandidate);
[654]958       
[2071]959                cout << "f cost: " << frontCandidate.mPriority << " " << frontCandidate.mRenderCostDecr << endl;
960                cout << "b cost: " << backCandidate.mPriority << " " << backCandidate.mRenderCostDecr << endl;
[653]961                tQueue.push(frontCandidate);
962                tQueue.push(backCandidate);
[666]963       
[653]964                // delete old leaf node
965                DEL_PTR(tData.mNode);
966        }
967
[654]968
[1551]969        //////////////////
[653]970        //-- terminate traversal and create new view cell
[1632]971
[653]972        if (newNode->IsLeaf())
973        {
[2017]974                BspLeaf *leaf = static_cast<BspLeaf *>(newNode);
[1020]975
[653]976                BspViewCell *viewCell = new BspViewCell();
[710]977        leaf->SetViewCell(viewCell);
[653]978               
[2066]979                if (STORE_PVS)
980                {
981                        /////////
982                        //-- update pvs
[653]983
[2066]984            int conSamp = 0;
985                        float sampCon = 0.0f;
[752]986
[2066]987                        AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
988               
989                        // update scalar pvs size value
990                        ObjectPvs &pvs = viewCell->GetPvs();
991                        mViewCellsManager->UpdateScalarPvsSize(viewCell,
992                                                                                                   pvs.EvalPvsCost(),
993                                                                                                   pvs.GetSize());
994                       
995                        mBspStats.contributingSamples += conSamp;
996                        mBspStats.sampleContributions += (int)sampCon;
997                }
[653]998
[1551]999                viewCell->mLeaves.push_back(leaf);
1000
1001                ///////////
[653]1002                //-- store additional info
[1632]1003
[653]1004                if (mStoreRays)
1005                {
1006                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
1007                        for (it = tData.mRays->begin(); it != it_end; ++ it)
1008                        {
1009                                (*it).mRay->Ref();                     
1010                                leaf->mVssRays.push_back((*it).mRay);
1011                        }
1012                }
[1551]1013       
[653]1014                if (mUseAreaForPvs)
1015                        viewCell->SetArea(tData.mProbability);
1016                else
1017                        viewCell->SetVolume(tData.mProbability);
1018
[675]1019        leaf->mProbability = tData.mProbability;
[653]1020
[2070]1021                // finally evaluate stats for this leaf
1022                if (1)
[1027]1023                        EvaluateLeafStats(tData);               
[653]1024        }
1025
1026        //-- cleanup
1027        tData.Clear();
1028
1029        return newNode;
1030}
1031
1032
[664]1033void VspBspTree::EvalPriority(VspBspTraversalData &tData) const
1034{
[735]1035    switch (mNodePriorityQueueType)
1036        {
1037        case BREATH_FIRST:
[734]1038                tData.mPriority = (float)-tData.mDepth;
[735]1039                break;
1040        case DEPTH_FIRST:
[734]1041                tData.mPriority = (float)tData.mDepth;
[735]1042                break;
1043        default:
[734]1044                tData.mPriority = tData.mPvs * tData.mProbability;
[735]1045                //Debug << "priority: " << tData.mPriority << endl;
1046                break;
1047        }
[664]1048}
1049
1050
[1233]1051void VspBspTree::EvalSubdivisionCandidate(VspBspSubdivisionCandidate &splitCandidate)
[1145]1052{
1053        VspBspTraversalData frontData;
1054        VspBspTraversalData backData;
1055       
[2017]1056        BspLeaf *leaf = static_cast<BspLeaf *>(splitCandidate.mParentData.mNode);
[1145]1057       
1058        // compute locally best split plane
[1288]1059    const bool costRatioViolated =
1060                SelectPlane(splitCandidate.mSplitPlane,
1061                                        leaf,
1062                                        splitCandidate.mParentData,
1063                                        frontData,
1064                                        backData,
1065                                        splitCandidate.mSplitAxis);
[652]1066
[1288]1067        // max cost threshold violated?
1068        splitCandidate.mMaxCostMisses = costRatioViolated ?
1069                splitCandidate.mParentData.mMaxCostMisses :
1070                splitCandidate.mParentData.mMaxCostMisses + 1;
1071
[1145]1072        float oldRenderCost;
1073
1074        // compute global decrease in render cost
1075        const float renderCostDecr = EvalRenderCostDecrease(splitCandidate.mSplitPlane,
1076                                                                                                                splitCandidate.mParentData,
1077                                                                                                                oldRenderCost);
1078
1079        splitCandidate.mRenderCostDecr = renderCostDecr;
1080
1081        // TODO: geometry could be reused
1082        delete frontData.mGeometry;
1083        delete backData.mGeometry;
1084
1085        // set priority for queue
1086#if 0
1087        const float priority = (float)-data.mDepth;
1088#else   
1089
1090        // take render cost of node into account
1091        // otherwise danger of being stuck in a local minimum!!
1092        const float factor = mRenderCostDecreaseWeight;
1093        const float priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost;
1094#endif
1095       
1096        splitCandidate.mPriority = priority;
1097}
1098
1099
1100void VspBspTree::EvalSubdivisionStats(const VspBspTraversalData &tData,
1101                                                                          const VspBspTraversalData &tFrontData,
1102                                                                          const VspBspTraversalData &tBackData)
1103{
1104        const float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
1105        const float cBack = (float)tBackData.mPvs * tBackData.mProbability;
1106        const float cData = (float)tData.mPvs * tData.mProbability;
1107       
1108        const float costDecr =
[1563]1109                (cFront + cBack - cData) / mBoundingBox.GetVolume();
[1145]1110
1111        mTotalCost += costDecr;
1112        mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
1113
1114        AddSubdivisionStats(mBspStats.Leaves(),
1115                                                -costDecr,
1116                                                0,
1117                                                mTotalCost,
1118                                                (float)mTotalPvsSize / (float)mBspStats.Leaves());
1119}
1120
1121
[653]1122BspInterior *VspBspTree::SubdivideNode(const Plane3 &splitPlane,
1123                                                                           VspBspTraversalData &tData,
1124                                                                           VspBspTraversalData &frontData,
1125                                                                           VspBspTraversalData &backData,
1126                                                                           PolygonContainer &coincident)
[463]1127{
[2017]1128        BspLeaf *leaf = static_cast<BspLeaf *>(tData.mNode);
[508]1129       
[473]1130        //-- the front and back traversal data is filled with the new values
1131        frontData.mDepth = tData.mDepth + 1;
[508]1132        frontData.mPolygons = new PolygonContainer();
[473]1133        frontData.mRays = new RayInfoContainer();
[508]1134       
[473]1135        backData.mDepth = tData.mDepth + 1;
[508]1136        backData.mPolygons = new PolygonContainer();
[473]1137        backData.mRays = new RayInfoContainer();
[508]1138       
[653]1139
1140        //-- subdivide rays
[652]1141        SplitRays(splitPlane,
[482]1142                          *tData.mRays,
1143                          *frontData.mRays,
[463]1144                          *backData.mRays);
[482]1145
[463]1146
[472]1147        // compute pvs
[463]1148        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1149        backData.mPvs = ComputePvsSize(*backData.mRays);
1150
[508]1151        // split front and back node geometry and compute area
[547]1152       
1153        // if geometry was not already computed
[602]1154        if (!frontData.mGeometry && !backData.mGeometry)
[463]1155        {
[547]1156                frontData.mGeometry = new BspNodeGeometry();
1157                backData.mGeometry = new BspNodeGeometry();
[482]1158
[547]1159                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1160                                                                           *backData.mGeometry,
[652]1161                                                                           splitPlane,
[1563]1162                                                                           mBoundingBox,
[679]1163                                                                           //0.0f);
1164                                                                           mEpsilon);
[508]1165               
[547]1166                if (mUseAreaForPvs)
1167                {
1168                        frontData.mProbability = frontData.mGeometry->GetArea();
1169                        backData.mProbability = backData.mGeometry->GetArea();
[508]1170                }
[547]1171                else
1172                {
1173                        frontData.mProbability = frontData.mGeometry->GetVolume();
[654]1174                        backData.mProbability = tData.mProbability - frontData.mProbability;
[676]1175
[744]1176                        // should never come here: wrong volume !!!
[676]1177                        if (0)
1178                        {
[744]1179                                if (frontData.mProbability < -0.00001)
1180                                        Debug << "fatal error f: " << frontData.mProbability << endl;
1181                                if (backData.mProbability < -0.00001)
1182                                        Debug << "fatal error b: " << backData.mProbability << endl;
1183
1184                                // clamp because of precision issues
[676]1185                                if (frontData.mProbability < 0) frontData.mProbability = 0;
1186                                if (backData.mProbability < 0) backData.mProbability = 0;
1187                        }
[547]1188                }
[463]1189        }
[663]1190
[547]1191       
[652]1192    // subdivide polygons
1193        SplitPolygons(splitPlane,
1194                                  *tData.mPolygons,
1195                      *frontData.mPolygons,
1196                                  *backData.mPolygons,
1197                                  coincident);
[463]1198
[652]1199
1200
[653]1201        ///////////////////////////////////////
1202        // subdivide further
[652]1203
[711]1204        // store maximal and minimal depth
1205        if (tData.mDepth > mBspStats.maxDepth)
1206        {
1207                Debug << "max depth increases to " << tData.mDepth << " at " << mBspStats.Leaves() << " leaves" << endl;
1208                mBspStats.maxDepth = tData.mDepth;
1209        }
1210
[652]1211        mBspStats.nodes += 2;
1212
[711]1213   
[652]1214        BspInterior *interior = new BspInterior(splitPlane);
1215
[1715]1216#ifdef GTP_DEBUG
[652]1217        Debug << interior << endl;
1218#endif
1219
[711]1220
[463]1221        //-- create front and back leaf
1222
1223        BspInterior *parent = leaf->GetParent();
1224
1225        // replace a link from node's parent
[487]1226        if (parent)
[463]1227        {
1228                parent->ReplaceChildLink(leaf, interior);
1229                interior->SetParent(parent);
1230        }
1231        else // new root
1232        {
1233                mRoot = interior;
1234        }
1235
1236        // and setup child links
1237        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
[482]1238
[463]1239        frontData.mNode = interior->GetFront();
1240        backData.mNode = interior->GetBack();
[473]1241
[650]1242        interior->mTimeStamp = mTimeStamp ++;
[652]1243       
[711]1244
[463]1245        //DEL_PTR(leaf);
1246        return interior;
1247}
1248
[508]1249
[463]1250void VspBspTree::AddToPvs(BspLeaf *leaf,
[482]1251                                                  const RayInfoContainer &rays,
[556]1252                                                  float &sampleContributions,
[463]1253                                                  int &contributingSamples)
1254{
[1002]1255        sampleContributions = 0;
1256        contributingSamples = 0;
[556]1257 
[1002]1258        RayInfoContainer::const_iterator it, it_end = rays.end();
[556]1259 
[1002]1260        ViewCellLeaf *vc = leaf->GetViewCell();
[556]1261 
[1002]1262        // add contributions from samples to the PVS
1263        for (it = rays.begin(); it != it_end; ++ it)
[463]1264        {
[1002]1265                float sc = 0.0f;
1266                VssRay *ray = (*it).mRay;
1267
1268                bool madeContrib = false;
1269                float contribution;
1270
1271                if (ray->mTerminationObject)
1272                {
1273                        if (vc->AddPvsSample(ray->mTerminationObject, ray->mPdf, contribution))
1274                                madeContrib = true;
1275                        sc += contribution;
1276                }
[556]1277         
[1006]1278                // only count termination objects?
[2233]1279#if COUNT_ORIGIN_OBJECTS
1280               
1281                if (ray->mOriginObject)
[1002]1282                {
1283                        if (vc->AddPvsSample(ray->mOriginObject, ray->mPdf, contribution))
1284                                madeContrib = true;
[1020]1285
[1002]1286                        sc += contribution;
1287                }
[2233]1288#endif
[1047]1289                sampleContributions += sc;
1290               
1291                if (madeContrib)
1292                        ++ contributingSamples;
[463]1293        }
1294}
1295
[580]1296
[1233]1297void VspBspTree::SortSubdivisionCandidates(const RayInfoContainer &rays,
[710]1298                                                                         const int axis,
1299                                                                         float minBand,
1300                                                                         float maxBand)
[463]1301{
[1233]1302        mLocalSubdivisionCandidates->clear();
[463]1303
[2070]1304        const int requestedSize = 2 * (int)(rays.size());
1305
[480]1306        // creates a sorted split candidates array
[1233]1307        if (mLocalSubdivisionCandidates->capacity() > 500000 &&
1308                requestedSize < (int)(mLocalSubdivisionCandidates->capacity() / 10) )
[480]1309        {
[1233]1310        delete mLocalSubdivisionCandidates;
1311                mLocalSubdivisionCandidates = new vector<SortableEntry>;
[480]1312        }
[463]1313
[1233]1314        mLocalSubdivisionCandidates->reserve(requestedSize);
[480]1315
[710]1316        if (0)
[1137]1317        {       // float values => don't compare with exact values
[710]1318                minBand += Limits::Small;
1319                maxBand -= Limits::Small;
1320        }
1321
[480]1322        // insert all queries
[612]1323        for (RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
[473]1324        {
[612]1325                const bool positive = (*ri).mRay->HasPosDir(axis);
[1137]1326                float pos = (*ri).ExtrapOrigin(axis);
1327
[710]1328                // clamp to min / max band
1329                if (0) ClipValue(pos, minBand, maxBand);
1330               
[2070]1331                mLocalSubdivisionCandidates->
1332                        push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
[810]1333                                                                        pos, (*ri).mRay));
[480]1334
[710]1335                pos = (*ri).ExtrapTermination(axis);
[1137]1336
[710]1337                // clamp to min / max band
1338                if (0) ClipValue(pos, minBand, maxBand);
1339
[2070]1340                mLocalSubdivisionCandidates->
1341                        push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
[810]1342                                                                        pos, (*ri).mRay));
[473]1343        }
[480]1344
[2124]1345        stable_sort(mLocalSubdivisionCandidates->begin(), mLocalSubdivisionCandidates->end());
[463]1346}
1347
[580]1348
[480]1349float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
1350                                                                                  const AxisAlignedBox3 &box,
1351                                                                                  const int pvsSize,
[710]1352                                                                                  const int axis,
[480]1353                                          float &position)
[463]1354{
[1149]1355        RayInfoContainer usedRays;
[1147]1356
[1727]1357        if (mMaxTests < (int)rays.size())
[1147]1358        {
[1149]1359                GetRayInfoSets(rays, mMaxTests, usedRays);
[1147]1360        }
1361        else
[1149]1362        {
[1147]1363                usedRays = rays;
[1149]1364        }
[1147]1365
[710]1366        const float minBox = box.Min(axis);
1367        const float maxBox = box.Max(axis);
[822]1368
[710]1369        const float sizeBox = maxBox - minBox;
[480]1370
[801]1371        const float minBand = minBox + mMinBand * sizeBox;
1372        const float maxBand = minBox + mMaxBand * sizeBox;
[710]1373
[1233]1374        SortSubdivisionCandidates(usedRays, axis, minBand, maxBand);
[710]1375
[1580]1376        //////////////////
[463]1377        // go through the lists, count the number of objects left and right
1378        // and evaluate the following cost funcion:
[480]1379        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1380
[1789]1381        float pvsl = 0;
1382        float pvsr = (float)pvsSize;
[480]1383
[1789]1384        float pvsBack = pvsl;
1385        float pvsFront = pvsr;
[612]1386
1387        float sum = (float)pvsSize * sizeBox;
[463]1388        float minSum = 1e20f;
[822]1389       
[710]1390        // if no border can be found, take mid split
1391        position = minBox + 0.5f * sizeBox;
[822]1392       
1393        // the relative cost ratio
[1074]1394        float ratio = 99999999.0f;
[822]1395        bool splitPlaneFound = false;
[710]1396
[480]1397        Intersectable::NewMail();
[1147]1398        RayInfoContainer::const_iterator ri, ri_end = usedRays.end();
[612]1399
1400        // set all object as belonging to the front pvs
[1149]1401        for(ri = usedRays.begin(); ri != ri_end; ++ ri)
[463]1402        {
[612]1403                Intersectable *oObject = (*ri).mRay->mOriginObject;
1404                Intersectable *tObject = (*ri).mRay->mTerminationObject;
1405
[2233]1406#if COUNT_ORIGIN_OBJECTS
1407               
1408                if (oObject)
[463]1409                {
[612]1410                        if (!oObject->Mailed())
[482]1411                        {
[612]1412                                oObject->Mail();
1413                                oObject->mCounter = 1;
[482]1414                        }
[612]1415                        else
1416                        {
1417                                ++ oObject->mCounter;
1418                        }
[463]1419                }
[2233]1420#endif
[1020]1421
[612]1422                if (tObject)
1423                {
1424                        if (!tObject->Mailed())
1425                        {
1426                                tObject->Mail();
1427                                tObject->mCounter = 1;
1428                        }
1429                        else
1430                        {
1431                                ++ tObject->mCounter;
1432                        }
1433                }
[480]1434        }
1435
1436        Intersectable::NewMail();
[1233]1437        vector<SortableEntry>::const_iterator ci, ci_end = mLocalSubdivisionCandidates->end();
[612]1438
[1233]1439        for (ci = mLocalSubdivisionCandidates->begin(); ci != ci_end; ++ ci)
[480]1440        {
1441                VssRay *ray;
[612]1442                ray = (*ci).ray;
1443               
1444                Intersectable *oObject = ray->mOriginObject;
1445                Intersectable *tObject = ray->mTerminationObject;
1446               
[480]1447                switch ((*ci).type)
[463]1448                {
[480]1449                        case SortableEntry::ERayMin:
1450                                {
[2233]1451#if COUNT_ORIGIN_OBJECTS
1452                                        if (oObject && !oObject->Mailed())
[480]1453                                        {
[612]1454                                                oObject->Mail();
1455                                                ++ pvsl;
[480]1456                                        }
[2233]1457#endif
[612]1458                                        if (tObject && !tObject->Mailed())
1459                                        {
1460                                                tObject->Mail();
1461                                                ++ pvsl;
1462                                        }
[1020]1463
[480]1464                                        break;
1465                                }
1466                        case SortableEntry::ERayMax:
1467                                {
[2233]1468#if COUNT_ORIGIN_OBJECTS
1469                                        if (oObject)
[612]1470                                        {
1471                                                if (-- oObject->mCounter == 0)
1472                                                        -- pvsr;
1473                                        }
[2233]1474#endif
[612]1475                                        if (tObject)
[480]1476                                        {
[612]1477                                                if (-- tObject->mCounter == 0)
1478                                                        -- pvsr;
[480]1479                                        }
1480
1481                                        break;
1482                                }
1483                }
[822]1484               
1485               
[1020]1486                // Note: we compare size of bounding boxes of front and back side because
1487                // of efficiency reasons (otherwise a new geometry would have to be computed
1488                // in each step and incremential evaluation would be difficult.
1489                // but then errors happen if the geometry is not an axis aligned box
1490                // (i.e., if a geometry aligned split was taken before)
1491                // question: is it sufficient to make this approximation?
[710]1492                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
[480]1493                {
[612]1494                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
[480]1495
[1147]1496                        float currentPos;
1497                       
1498                        // HACK: current positition is BETWEEN visibility events
[1149]1499                        if (0 && ((ci + 1) != ci_end))
1500                        {
[1147]1501                                currentPos = ((*ci).value + (*(ci + 1)).value) * 0.5f;
[1149]1502                        }
[1147]1503                        else
[1149]1504                currentPos = (*ci).value;                       
[1147]1505
[822]1506                        //Debug  << "pos=" << (*ci).value << "\t pvs=(" <<  pvsl << "," << pvsr << ")" << endl;
1507                        //Debug << "cost= " << sum << endl;
[480]1508
1509                        if (sum < minSum)
[463]1510                        {
[822]1511                                splitPlaneFound = true;
1512
[463]1513                                minSum = sum;
[1147]1514                                position = currentPos;
[710]1515                               
[612]1516                                pvsBack = pvsl;
1517                                pvsFront = pvsr;
[463]1518                        }
1519                }
1520        }
[710]1521       
[1767]1522        ///////
1523        //-- compute cost
1524
[1772]1525        const float lowerPvsLimit = (float)mViewCellsManager->GetMinPvsSize();
1526        const float upperPvsLimit = (float)mViewCellsManager->GetMaxPvsSize();
[612]1527
1528        const float pOverall = sizeBox;
1529
1530        const float pBack = position - minBox;
1531        const float pFront = maxBox - position;
1532       
[1789]1533        const float penaltyOld = EvalPvsPenalty((float)pvsSize, lowerPvsLimit, upperPvsLimit);
[612]1534    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1535        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1536       
1537        const float oldRenderCost = penaltyOld * pOverall;
1538        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1539
[822]1540        if (splitPlaneFound)
1541        {
1542                ratio = mPvsFactor * newRenderCost / (oldRenderCost + Limits::Small);
1543        }
1544        //if (axis != 1)
1545        //Debug << "axis=" << axis << " costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
1546         //    <<"\t pb=(" << pvsBack << ")\t pf=(" << pvsFront << ")" << endl;
[612]1547
[480]1548        return ratio;
[463]1549}
1550
[480]1551
[482]1552float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
[491]1553                                                                                 const VspBspTraversalData &tData,
[495]1554                                                                                 int &axis,
[508]1555                                                                                 BspNodeGeometry **frontGeom,
1556                                                                                 BspNodeGeometry **backGeom,
[547]1557                                                                                 float &pFront,
1558                                                                                 float &pBack,
[710]1559                                                                                 const bool isKdNode)
[463]1560{
[508]1561        float nPosition[3];
1562        float nCostRatio[3];
[547]1563        float nProbFront[3];
1564        float nProbBack[3];
[508]1565
1566        BspNodeGeometry *nFrontGeom[3];
1567        BspNodeGeometry *nBackGeom[3];
1568
[822]1569        // set to NULL, so I can find out which gemetry was stored
[612]1570        for (int i = 0; i < 3; ++ i)
1571        {
1572                nFrontGeom[i] = NULL;
1573                nBackGeom[i] = NULL;
1574        }
1575
[545]1576        // create bounding box of node geometry
[463]1577        AxisAlignedBox3 box;
[710]1578               
[562]1579        //TODO: for kd split geometry already is box => only take minmax vertices
[551]1580        if (1)
[1147]1581        {       // get bounding box from geometry
[710]1582                tData.mGeometry->GetBoundingBox(box);
[509]1583        }
1584        else
1585        {
[710]1586                box.Initialize();
[509]1587                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
[480]1588
[509]1589                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
1590                        box.Include((*ri).ExtrapTermination());
1591        }
[663]1592
[1147]1593
[663]1594        int sAxis = 0;
[822]1595        int bestAxis;
1596
[837]1597        // if max cost ratio is exceeded, take split along longest axis instead
1598        const float maxCostRatioForArbitraryAxis = 0.9f;
1599
[1006]1600        if (mUseDrivingAxisIfMaxCostViolated)
[822]1601                bestAxis = box.Size().DrivingAxis();
1602        else
1603                bestAxis = -1;
1604
[978]1605#if 0
1606        // maximum cost ratio for axis to be valid:
[822]1607        // if exceeded, spatial mid split is used instead
[978]1608        const maxCostRatioForHeur = 0.99f;
1609#endif
[822]1610
[978]1611        // if we use some kind of specialised fixed axis
[837]1612    const bool useSpecialAxis =
1613                mOnlyDrivingAxis || mUseRandomAxis || mCirculatingAxis;
[663]1614
[801]1615        if (mUseRandomAxis)
[663]1616                sAxis = Random(3);
[801]1617        else if (mCirculatingAxis)
[726]1618                sAxis = (tData.mAxis + 1) % 3;
[822]1619        else if (mOnlyDrivingAxis)
[801]1620                sAxis = box.Size().DrivingAxis();
1621
[664]1622               
[670]1623        //Debug << "use special axis: " << useSpecialAxis << endl;
1624        //Debug << "axis: " << sAxis << " drivingaxis: " << box.Size().DrivingAxis();
[1076]1625       
[822]1626        for (axis = 0; axis < 3 ; ++ axis)
[480]1627        {
[663]1628                if (!useSpecialAxis || (axis == sAxis))
[463]1629                {
[822]1630                        if (mUseCostHeuristics)
[480]1631                        {
[1106]1632                                //-- place split plane using heuristics
[822]1633                                nCostRatio[axis] =
1634                                        BestCostRatioHeuristics(*tData.mRays,
1635                                                                                    box,
1636                                                                                        tData.mPvs,
1637                                                                                        axis,
1638                                                                                        nPosition[axis]);                       
1639                        }
[1106]1640                        else
[1767]1641                        {       
1642                                //-- split plane position is spatial median
[480]1643                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
[543]1644                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
[1076]1645                               
[547]1646                                // allows faster split because we have axis aligned kd tree boxes
[822]1647                                if (isKdNode)
[542]1648                                {
1649                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1650                                                                                                                                box,
1651                                                                                                                                axis,
[547]1652                                                                                                                                nPosition[axis],
1653                                                                                                                                nProbFront[axis],
1654                                                                                                                                nProbBack[axis]);
[542]1655                                       
[710]1656                                        // create back geometry from box
[1767]1657
[1047]1658                                        // NOTE: the geometry is returned from the function so we
1659                                        // don't have to recompute it when possible
[1767]1660                                        Vector3 pos;
1661                                       
[543]1662                                        pos = box.Max(); pos[axis] = nPosition[axis];
[547]1663                                        AxisAlignedBox3 bBox(box.Min(), pos);
[1767]1664                                       
[710]1665                                        PolygonContainer fPolys;
1666                                        bBox.ExtractPolys(fPolys);
1667
1668                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1669       
[1767]1670                                        ////////////
[822]1671                                        //-- create front geometry from box
[1767]1672
[542]1673                                        pos = box.Min(); pos[axis] = nPosition[axis];
[547]1674                                        AxisAlignedBox3 fBox(pos, box.Max());
[710]1675
1676                                        PolygonContainer bPolys;
1677                                        fBox.ExtractPolys(bPolys);
1678                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
[542]1679                                }
1680                                else
1681                                {
[710]1682                                        nFrontGeom[axis] = new BspNodeGeometry();
1683                                        nBackGeom[axis] = new BspNodeGeometry();
1684
[573]1685                                        nCostRatio[axis] =
1686                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1687                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1688                                                                                   nProbFront[axis], nProbBack[axis]);
[542]1689                                }
[480]1690                        }
[822]1691                                               
[978]1692                       
[1006]1693                        if (mUseDrivingAxisIfMaxCostViolated)
[480]1694                        {
[978]1695                                // we take longest axis split if cost ratio exceeds threshold
1696                                if (nCostRatio[axis] < min(maxCostRatioForArbitraryAxis, nCostRatio[bestAxis]))
[822]1697                                {
1698                                        bestAxis = axis;
1699                                }
[1072]1700                                /*else if (nCostRatio[axis] < nCostRatio[bestAxis])
1701                                {
[978]1702                                        Debug << "taking split along longest axis (" << bestAxis << ") instead of  (" << axis << ")" << endl;
[1072]1703                                }*/
1704
[978]1705                        }
1706                        else
1707                        {
1708                                if (bestAxis == -1)
[822]1709                                {
1710                                        bestAxis = axis;
1711                                }
[978]1712                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
[822]1713                                {
1714                                        bestAxis = axis;
1715                                }
[978]1716                        }
[463]1717                }
1718        }
1719
[1767]1720        //////////
[495]1721        //-- assign values
[1072]1722
[495]1723        axis = bestAxis;
[547]1724        pFront = nProbFront[bestAxis];
1725        pBack = nProbBack[bestAxis];
[495]1726
[508]1727        // assign best split nodes geometry
1728        *frontGeom = nFrontGeom[bestAxis];
1729        *backGeom = nBackGeom[bestAxis];
[542]1730
[508]1731        // and delete other geometry
[612]1732        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1733        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
[495]1734
[508]1735        //-- split plane
1736    Vector3 normal(0,0,0); normal[bestAxis] = 1;
[480]1737        plane = Plane3(normal, nPosition[bestAxis]);
[508]1738
[822]1739        //Debug << "best axis: " << bestAxis << " pos " << nPosition[bestAxis] << endl;
[1072]1740
[480]1741        return nCostRatio[bestAxis];
[463]1742}
1743
[480]1744
[508]1745bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1746                                                         BspLeaf *leaf,
[652]1747                                                         VspBspTraversalData &data,                                                     
[508]1748                                                         VspBspTraversalData &frontData,
[612]1749                                                         VspBspTraversalData &backData,
1750                                                         int &splitAxis)
[491]1751{
[810]1752        // HACK matt: subdivide regularily to certain depth
[1072]1753        if (data.mDepth < 0)    // question matt: why depth < 0 ?
[801]1754        {
[1072]1755                cout << "depth: " << data.mDepth << endl;
1756
[801]1757                // return axis aligned split
1758                AxisAlignedBox3 box;
1759                box.Initialize();
1760       
1761                // create bounding box of region
1762                data.mGeometry->GetBoundingBox(box);
1763       
1764                const int axis = box.Size().DrivingAxis();
1765                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1766
1767                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1768                bestPlane = Plane3(norm, position);
1769                splitAxis = axis;
[1072]1770
[801]1771                return true;
1772        }
1773
[508]1774        // simplest strategy: just take next polygon
1775        if (mSplitPlaneStrategy & RANDOM_POLYGON)
[491]1776        {
[508]1777        if (!data.mPolygons->empty())
1778                {
1779                        const int randIdx =
[2283]1780                                (int)RandomValue(0, (Real)((float)data.mPolygons->size() - 0.5f));
[508]1781                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
[491]1782
[508]1783                        bestPlane = nextPoly->GetSupportingPlane();
1784                        return true;
1785                }
[491]1786        }
1787
[508]1788        //-- use heuristics to find appropriate plane
[491]1789
[508]1790        // intermediate plane
1791        Plane3 plane;
1792        float lowestCost = MAX_FLOAT;
[517]1793       
1794        // decides if the first few splits should be only axisAligned
[508]1795        const bool onlyAxisAligned  =
1796                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1797                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1798                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1799       
1800        const int limit = onlyAxisAligned ? 0 :
1801                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
[491]1802
[508]1803        float candidateCost;
[491]1804
[508]1805        int maxIdx = (int)data.mPolygons->size();
[491]1806
[508]1807        for (int i = 0; i < limit; ++ i)
[491]1808        {
[562]1809                // the already taken candidates are stored behind maxIdx
1810                // => assure that no index is taken twice
[508]1811                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1812                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
[491]1813
[508]1814                // swap candidate to the end to avoid testing same plane
1815                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
[2283]1816       
[508]1817                // evaluate current candidate
1818                BspNodeGeometry fGeom, bGeom;
1819                float fArea, bArea;
1820                plane = poly->GetSupportingPlane();
[573]1821                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
[491]1822               
[508]1823                if (candidateCost < lowestCost)
[491]1824                {
[508]1825                        bestPlane = plane;
1826                        lowestCost = candidateCost;
[491]1827                }
1828        }
1829
[1006]1830
[508]1831        //-- evaluate axis aligned splits
[1006]1832       
[508]1833        int axis;
1834        BspNodeGeometry *fGeom, *bGeom;
[547]1835        float pFront, pBack;
[491]1836
[653]1837        candidateCost = 99999999.0f;
[491]1838
[1006]1839        // as a variant, we take axis aligned split only if there is
1840        // more polygon available to guide the split
[653]1841        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1842        {
1843                candidateCost = SelectAxisAlignedPlane(plane,
1844                                                                                           data,
1845                                                                                           axis,
1846                                                                                           &fGeom,
1847                                                                                           &bGeom,
1848                                                                                           pFront,
1849                                                                                           pBack,
1850                                                                                           data.mIsKdNode);     
1851        }
1852
[612]1853        splitAxis = 3;
[562]1854
[508]1855        if (candidateCost < lowestCost)
1856        {       
1857                bestPlane = plane;
1858                lowestCost = candidateCost;
[612]1859                splitAxis = axis;
[653]1860       
[542]1861                // assign already computed values
1862                // we can do this because we always save the
[562]1863                // computed values from the axis aligned splits         
[653]1864
[612]1865                if (fGeom && bGeom)
1866                {
1867                        frontData.mGeometry = fGeom;
1868                        backData.mGeometry = bGeom;
[547]1869       
[612]1870                        frontData.mProbability = pFront;
1871                        backData.mProbability = pBack;
1872                }
[508]1873        }
1874        else
[463]1875        {
[508]1876                DEL_PTR(fGeom);
1877                DEL_PTR(bGeom);
[463]1878        }
[678]1879   
[1715]1880#ifdef GTP_DEBUG
[508]1881        Debug << "plane lowest cost: " << lowestCost << endl;
[679]1882#endif
[508]1883
[801]1884        // exeeded relative max cost ratio
[508]1885        if (lowestCost > mTermMaxCostRatio)
[611]1886        {
[508]1887                return false;
[611]1888        }
[508]1889
1890        return true;
[463]1891}
1892
[480]1893
[473]1894Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
[482]1895{
[2283]1896        const int candidateIdx = (int)RandomValue(0, (Real)((float)rays.size() - 0.5f));
[482]1897
[473]1898        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1899        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1900
1901        const Vector3 pt = (maxPt + minPt) * 0.5;
1902        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1903
1904        return Plane3(normal, pt);
1905}
1906
[480]1907
[473]1908Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
[482]1909{
[473]1910        Vector3 pt[3];
[482]1911
[473]1912        int idx[3];
1913        int cmaxT = 0;
1914        int cminT = 0;
1915        bool chooseMin = false;
1916
1917        for (int j = 0; j < 3; ++ j)
1918        {
1919                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
[482]1920
[473]1921                if (idx[j] >= (int)rays.size())
1922                {
1923                        idx[j] -= (int)rays.size();
[482]1924
[473]1925                        chooseMin = (cminT < 2);
1926                }
1927                else
1928                        chooseMin = (cmaxT < 2);
1929
1930                RayInfo rayInf = rays[idx[j]];
1931                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
[482]1932        }
[473]1933
1934        return Plane3(pt[0], pt[1], pt[2]);
1935}
1936
[580]1937
[473]1938Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
[482]1939{
[473]1940        Vector3 pt[3];
[482]1941
[473]1942        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1943        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1944
1945        // check if rays different
1946        if (idx1 == idx2)
1947                idx2 = (idx2 + 1) % (int)rays.size();
1948
1949        const RayInfo ray1 = rays[idx1];
1950        const RayInfo ray2 = rays[idx2];
1951
1952        // normal vector of the plane parallel to both lines
1953        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1954
1955        // vector from line 1 to line 2
[479]1956        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
[482]1957
[473]1958        // project vector on normal to get distance
1959        const float dist = DotProd(vd, norm);
1960
1961        // point on plane lies halfway between the two planes
1962        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1963
1964        return Plane3(norm, planePt);
1965}
1966
[495]1967
[463]1968inline void VspBspTree::GenerateUniqueIdsForPvs()
1969{
[580]1970        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1971        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1972        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
[463]1973}
1974
[495]1975
[652]1976float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
[1145]1977                                                                                 const VspBspTraversalData &data,
1978                                                                                 float &normalizedOldRenderCost) const
[652]1979{
[729]1980        float pvsFront = 0;
1981        float pvsBack = 0;
1982        float totalPvs = 0;
[652]1983
1984        // probability that view point lies in back / front node
1985        float pOverall = data.mProbability;
1986        float pFront = 0;
1987        float pBack = 0;
1988
1989
1990        // create unique ids for pvs heuristics
1991        GenerateUniqueIdsForPvs();
1992       
1993        for (int i = 0; i < data.mRays->size(); ++ i)
1994        {
1995                RayInfo rayInf = (*data.mRays)[i];
1996
1997                float t;
1998                VssRay *ray = rayInf.mRay;
1999                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
2000
2001                // find front and back pvs for origing and termination object
2002                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
[1020]2003
[2233]2004#if COUNT_ORIGIN_OBJECTS
2005                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
2006#endif
[652]2007        }
2008
2009
2010        BspNodeGeometry geomFront;
2011        BspNodeGeometry geomBack;
2012
2013        // construct child geometry with regard to the candidate split plane
2014        data.mGeometry->SplitGeometry(geomFront,
2015                                                                  geomBack,
2016                                                                  candidatePlane,
[1563]2017                                                                  mBoundingBox,
[679]2018                                                                  //0.0f);
2019                                                                  mEpsilon);
[652]2020
2021        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
2022        {
2023                pFront = geomFront.GetVolume();
2024                pBack = pOverall - pFront;
[675]2025
[729]2026                // something is wrong with the volume
[1027]2027                if (0 && ((pFront < 0.0) || (pBack < 0.0)))
[676]2028                {
[752]2029                        Debug << "ERROR in volume:\n"
2030                                  << "volume f :" << pFront << " b: " << pBack << " p: " << pOverall
2031                                  << ", real volume f: " << pFront << " b: " << geomBack.GetVolume()
2032                                  << ", #polygons f: " << geomFront.Size() << " b: " << geomBack.Size() << " p: " << data.mGeometry->Size() << endl;
[676]2033                }
[652]2034        }
2035        else
2036        {
2037                pFront = geomFront.GetArea();
2038                pBack = geomBack.GetArea();
2039        }
2040       
2041
2042        // -- pvs rendering heuristics
[1020]2043
2044        // upper and lower bounds
[1772]2045        const float lowerPvsLimit = (float)mViewCellsManager->GetMinPvsSize();
2046        const float upperPvsLimit = (float)mViewCellsManager->GetMaxPvsSize();
[652]2047
[1772]2048        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
2049    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
2050        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
[652]2051                       
2052        const float oldRenderCost = pOverall * penaltyOld;
2053        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
2054
[1563]2055        const float renderCostDecrease = (oldRenderCost - newRenderCost) / mBoundingBox.GetVolume();
[752]2056       
[1006]2057        // take render cost of node into account to avoid being stuck in a local minimum
[1563]2058        normalizedOldRenderCost = oldRenderCost / mBoundingBox.GetVolume();
[1006]2059       
[1145]2060        return renderCostDecrease;
[652]2061}
2062
2063
[573]2064float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
2065                                                                         const VspBspTraversalData &data,
2066                                                                         BspNodeGeometry &geomFront,
2067                                                                         BspNodeGeometry &geomBack,
2068                                                                         float &pFront,
2069                                                                         float &pBack) const
[463]2070{
[729]2071        float totalPvs = 0;
2072        float pvsFront = 0;
2073        float pvsBack = 0;
[652]2074       
[1006]2075        // overall probability is used as normalizer
[463]2076        float pOverall = 0;
[1006]2077
2078        // probability that view point lies in back / front node
[547]2079        pFront = 0;
2080        pBack = 0;
[463]2081
[1020]2082        int numTests; // the number of tests
[508]2083
[1020]2084        // if random samples shold be taken instead of testing all the rays
2085        bool useRand;
[463]2086
2087        if ((int)data.mRays->size() > mMaxTests)
2088        {
2089                useRand = true;
[1020]2090                numTests = mMaxTests;
[463]2091        }
2092        else
2093        {
2094                useRand = false;
[1020]2095                numTests = (int)data.mRays->size();
[463]2096        }
[508]2097       
[1020]2098        // create unique ids for pvs heuristics
2099        GenerateUniqueIdsForPvs();
2100
2101        for (int i = 0; i < numTests; ++ i)
[463]2102        {
[508]2103                const int testIdx = useRand ?
[2283]2104                        (int)RandomValue(0, (Real)((float)data.mRays->size() - 0.5f)) : i;
[463]2105                RayInfo rayInf = (*data.mRays)[testIdx];
2106
2107                float t;
[508]2108                VssRay *ray = rayInf.mRay;
[463]2109                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
2110
[652]2111                // find front and back pvs for origing and termination object
2112                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
[1020]2113
[2233]2114#if COUNT_ORIGIN_OBJECTS
2115                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
2116#endif
[652]2117        }
[508]2118
[652]2119        // construct child geometry with regard to the candidate split plane
[679]2120        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
2121                                                                                                                  geomBack,
2122                                                                                                                  candidatePlane,
[1563]2123                                                                                                                  mBoundingBox,
[679]2124                                                                                                                  //0.0f);
2125                                                                                                                  mEpsilon);
[675]2126
[652]2127        pOverall = data.mProbability;
[463]2128
[2072]2129        if (!mUseAreaForPvs)
[652]2130        {
2131                pFront = geomFront.GetVolume();
2132                pBack = pOverall - pFront;
[675]2133               
[729]2134                // HACK: precision issues possible for unbalanced split => don't take this split!
[685]2135                if (1 &&
[682]2136                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
2137                        !geomFront.Valid() || !geomBack.Valid()))
[676]2138                {
[752]2139                        //Debug << "error f: " << pFront << " b: " << pBack << endl;
[1027]2140
2141                        // high penalty for degenerated / wrong split
[711]2142                        return 99999.9f;
[676]2143                }
[463]2144        }
[652]2145        else
[542]2146        {
[2072]2147                // use front and back cell areas to approximate volume
[652]2148                pFront = geomFront.GetArea();
2149                pBack = geomBack.GetArea();
[542]2150        }
[652]2151       
[1772]2152        ////////
2153        //-- pvs rendering heuristics
[542]2154
[1773]2155        const float lowerPvsLimit = (float)mViewCellsManager->GetMinPvsSize();
2156        const float upperPvsLimit = (float)mViewCellsManager->GetMaxPvsSize();
[580]2157
[652]2158        // only render cost heuristics or combined with standard deviation
[1772]2159        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
2160    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
2161        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
[579]2162                       
[652]2163        const float oldRenderCost = pOverall * penaltyOld;
2164        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
[579]2165
[652]2166        float oldCost, newCost;
[580]2167
[652]2168        // only render cost
2169        if (1)
2170        {
2171                oldCost = oldRenderCost;
2172                newCost = newRenderCost;
2173        }
2174        else // also considering standard deviation
2175        {
2176                // standard deviation is difference of back and front pvs
2177                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
[580]2178
[652]2179                const float newDeviation = 0.5f *
2180                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
[580]2181
[652]2182                const float oldDeviation = penaltyOld;
[580]2183
[652]2184                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
2185                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
2186        }
[580]2187
[1020]2188        const float cost = mPvsFactor * newCost / (oldCost + Limits::Small);
[607]2189               
[463]2190
[1715]2191#ifdef GTP_DEBUG
[474]2192        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
[508]2193                  << " frontpvs: " << pvsFront << " pFront: " << pFront
2194                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
[600]2195        Debug << "cost: " << cost << endl;
[463]2196#endif
[482]2197
[652]2198        return cost;
[463]2199}
2200
[508]2201
[697]2202int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2203                                                                                ViewCellContainer &viewCells) const
2204{
2205        stack<bspNodePair> nodeStack;
2206        BspNodeGeometry *rgeom = new BspNodeGeometry();
2207
2208        ConstructGeometry(mRoot, *rgeom);
2209
2210        nodeStack.push(bspNodePair(mRoot, rgeom));
2211 
2212        ViewCell::NewMail();
2213
2214        while (!nodeStack.empty())
2215        {
2216                BspNode *node = nodeStack.top().first;
2217                BspNodeGeometry *geom = nodeStack.top().second;
2218                nodeStack.pop();
2219
2220                const int side = geom->ComputeIntersection(box);
2221               
2222                switch (side)
2223                {
2224                case -1:
2225                        // node geometry is contained in box
2226                        CollectViewCells(node, true, viewCells, true);
2227                        break;
2228
2229                case 0:
2230                        if (node->IsLeaf())
2231                        {
[2017]2232                                BspLeaf *leaf = static_cast<BspLeaf *>(node);
[697]2233                       
2234                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2235                                {
2236                                        leaf->GetViewCell()->Mail();
2237                                        viewCells.push_back(leaf->GetViewCell());
2238                                }
2239                        }
2240                        else
2241                        {
[2017]2242                                BspInterior *interior = static_cast<BspInterior *>(node);
[697]2243                       
2244                                BspNode *first = interior->GetFront();
2245                                BspNode *second = interior->GetBack();
2246           
2247                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2248                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2249
2250                                geom->SplitGeometry(*firstGeom,
2251                                                                        *secondGeom,
2252                                                                        interior->GetPlane(),
[1563]2253                                                                        mBoundingBox,
[697]2254                                                                        //0.0000001f);
2255                                                                        mEpsilon);
2256
2257                                nodeStack.push(bspNodePair(first, firstGeom));
2258                                nodeStack.push(bspNodePair(second, secondGeom));
2259                        }
2260                       
2261                        break;
2262                default:
2263                        // default: cull
2264                        break;
2265                }
2266               
2267                DEL_PTR(geom);
2268               
2269        }
2270
2271        return (int)viewCells.size();
2272}
2273
2274
[580]2275float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2276                                                                                   const AxisAlignedBox3 &box,
2277                                                                                   const int axis,
2278                                                                                   const float &position,                                                                                 
2279                                                                                   float &pFront,
2280                                                                                   float &pBack) const
2281{
[729]2282        float pvsTotal = 0;
2283        float pvsFront = 0;
2284        float pvsBack = 0;
[580]2285       
2286        // create unique ids for pvs heuristics
2287        GenerateUniqueIdsForPvs();
2288
2289        const int pvsSize = data.mPvs;
[726]2290
[580]2291        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2292
2293        // this is the main ray classification loop!
2294        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2295        {
2296                // determine the side of this ray with respect to the plane
2297                float t;
2298                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2299       
2300                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
[1020]2301
[2233]2302#if COUNT_ORIGIN_OBJECTS
2303                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
2304#endif
[580]2305        }
2306
[1020]2307
[580]2308        //-- pvs heuristics
2309
[1020]2310        float pOverall = data.mProbability;
[580]2311
[1020]2312        // note: we use a simplified computation assuming that we always do a
2313        // spatial mid split   
2314       
[580]2315        if (!mUseAreaForPvs)
[1020]2316        {   
2317                // volume
[580]2318                pBack = pFront = pOverall * 0.5f;
2319#if 0
2320                // box length substitute for probability
2321                const float minBox = box.Min(axis);
2322                const float maxBox = box.Max(axis);
2323
2324                pBack = position - minBox;
2325                pFront = maxBox - position;
2326                pOverall = maxBox - minBox;
2327#endif
2328        }
2329        else //-- area substitute for probability
2330        {
2331                const int axis2 = (axis + 1) % 3;
2332                const int axis3 = (axis + 2) % 3;
2333
2334                const float faceArea =
2335                        (box.Max(axis2) - box.Min(axis2)) *
2336                        (box.Max(axis3) - box.Min(axis3));
2337
2338                pBack = pFront = pOverall * 0.5f + faceArea;
2339        }
2340
[1715]2341#ifdef GTP_DEBUG
[1302]2342        Debug << "axis: " << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2343        Debug << "p: " << pFront << " " << pBack << " " << pOverall << endl;
[580]2344#endif
2345
2346       
2347        const float newCost = pvsBack * pBack + pvsFront * pFront;
2348        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2349
2350        return  (mCtDivCi + newCost) / oldCost;
2351}
2352
2353
[1076]2354inline void VspBspTree::AddObjToPvs(Intersectable *obj,
2355                                                                                 const int cf,
2356                                                                                 float &frontPvs,
2357                                                                                 float &backPvs,
2358                                                                                 float &totalPvs) const
[463]2359{
2360        if (!obj)
2361                return;
[1076]2362#if 0
[744]2363        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
[1076]2364#else
2365        const int renderCost = 1;
2366#endif
[654]2367        // new object
[508]2368        if ((obj->mMailbox != sFrontId) &&
2369                (obj->mMailbox != sBackId) &&
2370                (obj->mMailbox != sFrontAndBackId))
2371        {
[744]2372                totalPvs += renderCost;
[508]2373        }
2374
[463]2375        // TODO: does this really belong to no pvs?
2376        //if (cf == Ray::COINCIDENT) return;
2377
2378        // object belongs to both PVS
2379        if (cf >= 0)
2380        {
[482]2381                if ((obj->mMailbox != sFrontId) &&
[463]2382                        (obj->mMailbox != sFrontAndBackId))
2383                {
[744]2384                        frontPvs += renderCost;
[508]2385               
[463]2386                        if (obj->mMailbox == sBackId)
[482]2387                                obj->mMailbox = sFrontAndBackId;
[463]2388                        else
[482]2389                                obj->mMailbox = sFrontId;
[463]2390                }
2391        }
[482]2392
[463]2393        if (cf <= 0)
2394        {
2395                if ((obj->mMailbox != sBackId) &&
2396                        (obj->mMailbox != sFrontAndBackId))
2397                {
[744]2398                        backPvs += renderCost;
[508]2399               
[463]2400                        if (obj->mMailbox == sFrontId)
[482]2401                                obj->mMailbox = sFrontAndBackId;
[463]2402                        else
[482]2403                                obj->mMailbox = sBackId;
[463]2404                }
2405        }
2406}
2407
[491]2408
[503]2409void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2410                                                           const bool onlyUnmailed,
2411                                                           const int maxPvsSize) const
[463]2412{
2413        stack<BspNode *> nodeStack;
2414        nodeStack.push(mRoot);
[482]2415
2416        while (!nodeStack.empty())
[463]2417        {
2418                BspNode *node = nodeStack.top();
2419                nodeStack.pop();
[489]2420               
[482]2421                if (node->IsLeaf())
[463]2422                {
[490]2423                        // test if this leaf is in valid view space
[2017]2424                        BspLeaf *leaf = static_cast<BspLeaf *>(node);
[503]2425                        if (leaf->TreeValid() &&
[508]2426                                (!onlyUnmailed || !leaf->Mailed()) &&
[1707]2427                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().EvalPvsCost() <= maxPvsSize)))
[490]2428                        {
2429                                leaves.push_back(leaf);
2430                        }
[482]2431                }
2432                else
[463]2433                {
[2017]2434                        BspInterior *interior = static_cast<BspInterior *>(node);
[463]2435
2436                        nodeStack.push(interior->GetBack());
2437                        nodeStack.push(interior->GetFront());
2438                }
2439        }
2440}
2441
[489]2442
[463]2443AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2444{
[1563]2445        return mBoundingBox;
[463]2446}
2447
[489]2448
[463]2449BspNode *VspBspTree::GetRoot() const
2450{
2451        return mRoot;
2452}
2453
[489]2454
[463]2455void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2456{
2457        // the node became a leaf -> evaluate stats for leafs
[2017]2458        BspLeaf *leaf = static_cast<BspLeaf *>(data.mNode);
[463]2459
2460
[574]2461        if (data.mPvs > mBspStats.maxPvs)
[711]2462        {
[574]2463                mBspStats.maxPvs = data.mPvs;
[711]2464        }
2465
[656]2466        mBspStats.pvs += data.mPvs;
2467
[574]2468        if (data.mDepth < mBspStats.minDepth)
[711]2469        {
[574]2470                mBspStats.minDepth = data.mDepth;
[711]2471        }
[656]2472       
[463]2473        if (data.mDepth >= mTermMaxDepth)
[711]2474        {
[744]2475        ++ mBspStats.maxDepthNodes;
2476                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
[711]2477        }
[611]2478
[508]2479        // accumulate rays to compute rays /  leaf
[574]2480        mBspStats.accumRays += (int)data.mRays->size();
[463]2481
[437]2482        if (data.mPvs < mTermMinPvs)
[574]2483                ++ mBspStats.minPvsNodes;
[437]2484
2485        if ((int)data.mRays->size() < mTermMinRays)
[574]2486                ++ mBspStats.minRaysNodes;
[437]2487
2488        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
[574]2489                ++ mBspStats.maxRayContribNodes;
[482]2490
[547]2491        if (data.mProbability <= mTermMinProbability)
[574]2492                ++ mBspStats.minProbabilityNodes;
[508]2493       
[474]2494        // accumulate depth to compute average depth
[574]2495        mBspStats.accumDepth += data.mDepth;
[463]2496
[612]2497        ++ mCreatedViewCells;
[656]2498
[1715]2499#ifdef GTP_DEBUG
[463]2500        Debug << "BSP stats: "
2501                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2502                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
[1027]2503                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
[1707]2504                  << "#pvs: " << leaf->GetViewCell()->GetPvs().EvalPvsCost() << "), "
[463]2505                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2506#endif
2507}
2508
[612]2509
[463]2510int VspBspTree::CastRay(Ray &ray)
2511{
2512        int hits = 0;
[482]2513
[600]2514        stack<BspRayTraversalData> tQueue;
[482]2515
[463]2516        float maxt, mint;
2517
[1563]2518        if (!mBoundingBox.GetRaySegment(ray, mint, maxt))
[463]2519                return 0;
2520
2521        Intersectable::NewMail();
[600]2522        ViewCell::NewMail();
[1012]2523
[463]2524        Vector3 entp = ray.Extrap(mint);
2525        Vector3 extp = ray.Extrap(maxt);
[482]2526
[463]2527        BspNode *node = mRoot;
2528        BspNode *farChild = NULL;
[482]2529
[463]2530        while (1)
2531        {
[482]2532                if (!node->IsLeaf())
[463]2533                {
[2017]2534                        BspInterior *in = static_cast<BspInterior *>(node);
[463]2535
2536                        Plane3 splitPlane = in->GetPlane();
2537                        const int entSide = splitPlane.Side(entp);
2538                        const int extSide = splitPlane.Side(extp);
2539
2540                        if (entSide < 0)
2541                        {
2542                                node = in->GetBack();
2543
2544                                if(extSide <= 0) // plane does not split ray => no far child
2545                                        continue;
[482]2546
[463]2547                                farChild = in->GetFront(); // plane splits ray
2548
2549                        } else if (entSide > 0)
2550                        {
2551                                node = in->GetFront();
2552
2553                                if (extSide >= 0) // plane does not split ray => no far child
2554                                        continue;
2555
[482]2556                                farChild = in->GetBack(); // plane splits ray
[463]2557                        }
2558                        else // ray and plane are coincident
2559                        {
[1012]2560                                // matt: WHAT TO DO IN THIS CASE ?
[463]2561                                //break;
2562                                node = in->GetFront();
2563                                continue;
2564                        }
2565
2566                        // push data for far child
[600]2567                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
[463]2568
2569                        // find intersection of ray segment with plane
2570                        float t;
2571                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2572                        maxt *= t;
[1047]2573                }
2574                else // reached leaf => intersection with view cell
[463]2575                {
[2017]2576                        BspLeaf *leaf = static_cast<BspLeaf *>(node);
[482]2577
[463]2578                        if (!leaf->GetViewCell()->Mailed())
2579                        {
2580                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2581                                leaf->GetViewCell()->Mail();
2582                                ++ hits;
2583                        }
[482]2584
[463]2585                        //-- fetch the next far child from the stack
[600]2586                        if (tQueue.empty())
[463]2587                                break;
[482]2588
[463]2589                        entp = extp;
2590                        mint = maxt; // NOTE: need this?
2591
2592                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2593                                break;
2594
[600]2595                        BspRayTraversalData &s = tQueue.top();
[463]2596
2597                        node = s.mNode;
2598                        extp = s.mExitPoint;
2599                        maxt = s.mMaxT;
2600
[600]2601                        tQueue.pop();
[463]2602                }
2603        }
2604
2605        return hits;
2606}
2607
[532]2608
[1072]2609void VspBspTree::CollectViewCells(ViewCellContainer &viewCells,
2610                                                                  bool onlyValid) const
[463]2611{
[532]2612        ViewCell::NewMail();
[551]2613        CollectViewCells(mRoot, onlyValid, viewCells, true);
[532]2614}
2615
2616
[1545]2617void VspBspTree::CollectViewCells(BspNode *root,
2618                                                                  bool onlyValid,
2619                                                                  ViewCellContainer &viewCells,
2620                                                                  bool onlyUnmailed) const
2621{
2622        stack<BspNode *> nodeStack;
2623
2624        if (!root)
2625                return;
2626
2627        nodeStack.push(root);
2628       
2629        while (!nodeStack.empty())
2630        {
2631                BspNode *node = nodeStack.top();
2632                nodeStack.pop();
2633               
2634                if (node->IsLeaf())
2635                {
2636                        if (!onlyValid || node->TreeValid())
2637                        {
[2017]2638                                ViewCellLeaf *leafVc = static_cast<BspLeaf *>(node)->GetViewCell();
[1545]2639
2640                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2641                                               
2642                                if (!onlyUnmailed || !viewCell->Mailed())
2643                                {
2644                                        viewCell->Mail();
2645                                        viewCells.push_back(viewCell);
2646                                }
2647                        }
2648                }
2649                else
2650                {
[2017]2651                        BspInterior *interior = static_cast<BspInterior *>(node);
[1545]2652               
2653                        nodeStack.push(interior->GetFront());
2654                        nodeStack.push(interior->GetBack());
2655                }
2656        }
2657}
2658
2659
[574]2660void VspBspTree::CollapseViewCells()
[542]2661{
[590]2662// TODO
[728]2663#if HAS_TO_BE_REDONE
[542]2664        stack<BspNode *> nodeStack;
2665
2666        if (!mRoot)
2667                return;
2668
2669        nodeStack.push(mRoot);
2670       
2671        while (!nodeStack.empty())
2672        {
2673                BspNode *node = nodeStack.top();
2674                nodeStack.pop();
2675               
2676                if (node->IsLeaf())
[574]2677        {
[2017]2678                        BspViewCell *viewCell = static_cast<BspLeaf *>(node)->GetViewCell();
[542]2679
[574]2680                        if (!viewCell->GetValid())
[542]2681                        {
[2017]2682                                BspViewCell *viewCell = static_cast<BspLeaf *>(node)->GetViewCell();
[580]2683       
2684                                ViewCellContainer leaves;
[590]2685                                mViewCellsTree->CollectLeaves(viewCell, leaves);
[580]2686
2687                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2688
2689                                for (it = leaves.begin(); it != it_end; ++ it)
[542]2690                                {
[2017]2691                                        BspLeaf *l = static_cast<BspViewCell *>(*it)->mLeaf;
[574]2692                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2693                                        ++ mBspStats.invalidLeaves;
2694                                }
[542]2695
[574]2696                                // add to unbounded view cell
2697                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2698                                DEL_PTR(viewCell);
2699                        }
2700                }
2701                else
2702                {
[2017]2703                        BspInterior *interior = static_cast<BspInterior *>(node);
[574]2704               
2705                        nodeStack.push(interior->GetFront());
2706                        nodeStack.push(interior->GetBack());
2707                }
2708        }
[542]2709
[574]2710        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
[590]2711#endif
[574]2712}
2713
2714
[639]2715void VspBspTree::CollectRays(VssRayContainer &rays)
2716{
2717        vector<BspLeaf *> leaves;
2718
2719        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2720
2721        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2722        {
2723                BspLeaf *leaf = *lit;
2724                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2725
2726                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2727                        rays.push_back(*rit);
2728        }
2729}
2730
2731
[574]2732void VspBspTree::ValidateTree()
2733{
2734        stack<BspNode *> nodeStack;
2735
2736        if (!mRoot)
2737                return;
2738
2739        nodeStack.push(mRoot);
2740       
2741        mBspStats.invalidLeaves = 0;
2742        while (!nodeStack.empty())
2743        {
2744                BspNode *node = nodeStack.top();
2745                nodeStack.pop();
2746               
2747                if (node->IsLeaf())
2748                {
[2017]2749                        BspLeaf *leaf = static_cast<BspLeaf *>(node);
[574]2750
2751                        if (!leaf->GetViewCell()->GetValid())
2752                                ++ mBspStats.invalidLeaves;
2753
2754                        // validity flags don't match => repair
2755                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2756                        {
2757                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2758                                PropagateUpValidity(leaf);
[542]2759                        }
2760                }
2761                else
2762                {
[2017]2763                        BspInterior *interior = static_cast<BspInterior *>(node);
[542]2764               
2765                        nodeStack.push(interior->GetFront());
2766                        nodeStack.push(interior->GetBack());
2767                }
2768        }
[562]2769
[574]2770        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
[542]2771}
2772
[547]2773
[648]2774void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2775{
2776        // preprocess: throw out polygons coincident to the view space box (not needed)
2777        PolygonContainer boxPolys;
[1027]2778       
[1563]2779        mBoundingBox.ExtractPolys(boxPolys);
[648]2780        vector<Plane3> boxPlanes;
2781
2782        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2783
2784        // extract planes of box
2785        // TODO: can be done more elegantly than first extracting polygons
2786        // and take their planes
2787        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2788        {
2789                boxPlanes.push_back((*pit)->GetSupportingPlane());
2790        }
2791
2792        pit_end = polys.end();
2793
2794        for (pit = polys.begin(); pit != pit_end; ++ pit)
2795        {
2796                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2797               
2798                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2799                {
2800                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2801
2802                        if (cf == Polygon3::COINCIDENT)
2803                        {
2804                                DEL_PTR(*pit);
2805                                //Debug << "coincident!!" << endl;
2806                        }
2807                }
2808        }
2809
[1002]2810        // remove deleted entries after swapping them to end of vector
[648]2811        for (int i = 0; i < (int)polys.size(); ++ i)
2812        {
2813                while (!polys[i] && (i < (int)polys.size()))
2814                {
2815                        swap(polys[i], polys.back());
2816                        polys.pop_back();
2817                }
[1027]2818        }
[648]2819}
2820
2821
[463]2822float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2823{
2824        float len = 0;
2825
2826        RayInfoContainer::const_iterator it, it_end = rays.end();
2827
2828        for (it = rays.begin(); it != it_end; ++ it)
2829                len += (*it).SegmentLength();
2830
2831        return len;
2832}
2833
[479]2834
[463]2835int VspBspTree::SplitRays(const Plane3 &plane,
[482]2836                                                  RayInfoContainer &rays,
2837                                                  RayInfoContainer &frontRays,
[639]2838                                                  RayInfoContainer &backRays) const
[463]2839{
2840        int splits = 0;
2841
[574]2842        RayInfoContainer::const_iterator it, it_end = rays.end();
2843
2844        for (it = rays.begin(); it != it_end; ++ it)
[463]2845        {
[574]2846                RayInfo bRay = *it;
2847               
[463]2848                VssRay *ray = bRay.mRay;
[473]2849                float t;
[463]2850
[485]2851                // get classification and receive new t
[463]2852                const int cf = bRay.ComputeRayIntersection(plane, t);
[482]2853
[463]2854                switch (cf)
2855                {
2856                case -1:
2857                        backRays.push_back(bRay);
2858                        break;
2859                case 1:
2860                        frontRays.push_back(bRay);
2861                        break;
[482]2862                case 0:
2863                        {
[485]2864                                //-- split ray
[639]2865                                //   test if start point behind or in front of plane
[485]2866                                const int side = plane.Side(bRay.ExtrapOrigin());
2867
[1011]2868                                ++ splits;
2869
[485]2870                                if (side <= 0)
2871                                {
2872                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2873                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2874                                }
2875                                else
2876                                {
2877                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2878                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2879                                }
[463]2880                        }
2881                        break;
2882                default:
[485]2883                        Debug << "Should not come here" << endl;
[463]2884                        break;
2885                }
2886        }
2887
2888        return splits;
2889}
2890
[479]2891
[463]2892void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2893{
2894        BspNode *lastNode;
2895
2896        do
2897        {
2898                lastNode = n;
2899
2900                // want to get planes defining geometry of this node => don't take
2901                // split plane of node itself
2902                n = n->GetParent();
[482]2903
[463]2904                if (n)
2905                {
[2017]2906                        BspInterior *interior = static_cast<BspInterior *>(n);
2907                        Plane3 halfSpace = static_cast<BspInterior *>(interior)->GetPlane();
[463]2908
[683]2909            if (interior->GetBack() != lastNode)
[463]2910                                halfSpace.ReverseOrientation();
2911
2912                        halfSpaces.push_back(halfSpace);
2913                }
2914        }
2915        while (n);
2916}
2917
[485]2918
[482]2919void VspBspTree::ConstructGeometry(BspNode *n,
[503]2920                                                                   BspNodeGeometry &geom) const
[463]2921{
[437]2922        vector<Plane3> halfSpaces;
2923        ExtractHalfSpaces(n, halfSpaces);
2924
2925        PolygonContainer candidatePolys;
[678]2926        vector<Plane3> candidatePlanes;
[437]2927
[719]2928        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2929
[683]2930        // bounded planes are added to the polygons
[719]2931        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
[437]2932        {
[719]2933                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
[482]2934
[448]2935                if (p->Valid(mEpsilon))
[437]2936                {
[683]2937                        candidatePolys.push_back(p);
[719]2938                        candidatePlanes.push_back(*pit);
[437]2939                }
2940        }
2941
2942        // add faces of bounding box (also could be faces of the cell)
2943        for (int i = 0; i < 6; ++ i)
2944        {
2945                VertexContainer vertices;
[482]2946
[437]2947                for (int j = 0; j < 4; ++ j)
[1563]2948                {
2949                        vertices.push_back(mBoundingBox.GetFace(i).mVertices[j]);
2950                }
[437]2951
[678]2952                Polygon3 *poly = new Polygon3(vertices);
2953
2954                candidatePolys.push_back(poly);
2955                candidatePlanes.push_back(poly->GetSupportingPlane());
[437]2956        }
2957
2958        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2959        {
2960                // polygon is split by all other planes
2961                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2962                {
2963                        if (i == j) // polygon and plane are coincident
2964                                continue;
2965
2966                        VertexContainer splitPts;
2967                        Polygon3 *frontPoly, *backPoly;
2968
[482]2969                        const int cf =
[448]2970                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2971                                                                                                 mEpsilon);
[482]2972
[437]2973                        switch (cf)
2974                        {
2975                                case Polygon3::SPLIT:
2976                                        frontPoly = new Polygon3();
2977                                        backPoly = new Polygon3();
2978
[482]2979                                        candidatePolys[i]->Split(halfSpaces[j],
2980                                                                                         *frontPoly,
[448]2981                                                                                         *backPoly,
2982                                                                                         mEpsilon);
[437]2983
2984                                        DEL_PTR(candidatePolys[i]);
2985
[683]2986                                        if (backPoly->Valid(mEpsilon))
[1563]2987                                        {
[683]2988                                                candidatePolys[i] = backPoly;
[1563]2989                                        }
[437]2990                                        else
[1563]2991                                        {
[683]2992                                                DEL_PTR(backPoly);
[1563]2993                                        }
[437]2994
[683]2995                                        // outside, don't need this
2996                                        DEL_PTR(frontPoly);
[437]2997                                        break;
[1563]2998
[683]2999                                // polygon outside of halfspace
3000                                case Polygon3::FRONT_SIDE:
[437]3001                                        DEL_PTR(candidatePolys[i]);
3002                                        break;
[1563]3003
[437]3004                                // just take polygon as it is
[683]3005                                case Polygon3::BACK_SIDE:
[437]3006                                case Polygon3::COINCIDENT:
3007                                default:
3008                                        break;
3009                        }
3010                }
[482]3011
[437]3012                if (candidatePolys[i])
[678]3013                {
3014                        geom.Add(candidatePolys[i], candidatePlanes[i]);
3015                }
[437]3016        }
[463]3017}
3018
[485]3019
[1563]3020bool VspBspTree::IsOutOfBounds(ViewCell *vc) const
3021{
3022        return vc->GetId() == OUT_OF_BOUNDS_ID;
3023}
3024
3025
3026void VspBspTree::SetViewCellsTree(ViewCellsTree *viewCellsTree)
3027{
3028        mViewCellsTree = viewCellsTree;
3029}
3030
3031
[582]3032void VspBspTree::ConstructGeometry(ViewCell *vc,
[503]3033                                                                   BspNodeGeometry &vcGeom) const
[589]3034{
[1551]3035        // if false, cannot construct geometry for interior leaf
3036        if (!mViewCellsTree)
3037                return;
3038
[580]3039        ViewCellContainer leaves;
[590]3040        mViewCellsTree->CollectLeaves(vc, leaves);
[463]3041
[580]3042        ViewCellContainer::const_iterator it, it_end = leaves.end();
3043
[463]3044        for (it = leaves.begin(); it != it_end; ++ it)
[580]3045        {
[1563]3046                if (IsOutOfBounds(*it))
[1557]3047                        continue;
3048               
[2017]3049                BspViewCell *bspVc = static_cast<BspViewCell *>(*it);
[1551]3050                vector<BspLeaf *>::const_iterator bit, bit_end = bspVc->mLeaves.end();
3051
3052                for (bit = bspVc->mLeaves.begin(); bit != bit_end; ++ bit)
3053                {
3054                        BspLeaf *l = *bit;
3055                        ConstructGeometry(l, vcGeom);
3056                }
[580]3057        }
[463]3058}
3059
[485]3060
[482]3061int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
[562]3062                                                          const bool onlyUnmailed) const
[463]3063{
[551]3064        stack<bspNodePair> nodeStack;
3065       
3066        BspNodeGeometry nodeGeom;
3067        ConstructGeometry(n, nodeGeom);
[801]3068//      const float eps = 0.5f;
[752]3069        const float eps = 0.01f;
[500]3070        // split planes from the root to this node
3071        // needed to verify that we found neighbor leaf
[557]3072        // TODO: really needed?
[463]3073        vector<Plane3> halfSpaces;
3074        ExtractHalfSpaces(n, halfSpaces);
3075
[551]3076
3077        BspNodeGeometry *rgeom = new BspNodeGeometry();
3078        ConstructGeometry(mRoot, *rgeom);
3079
3080        nodeStack.push(bspNodePair(mRoot, rgeom));
3081
[482]3082        while (!nodeStack.empty())
[463]3083        {
[551]3084                BspNode *node = nodeStack.top().first;
3085                BspNodeGeometry *geom = nodeStack.top().second;
[562]3086       
[463]3087                nodeStack.pop();
3088
[557]3089                if (node->IsLeaf())
[562]3090                {
[557]3091                        // test if this leaf is in valid view space
3092                        if (node->TreeValid() &&
3093                                (node != n) &&
3094                                (!onlyUnmailed || !node->Mailed()))
3095                        {
3096                                bool isAdjacent = true;
[551]3097
[570]3098                                if (1)
[557]3099                                {
[562]3100                                        // test all planes of current node if still adjacent
3101                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
3102                                        {
3103                                                const int cf =
[678]3104                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
[562]3105                                                                                                        halfSpaces[i],
[752]3106                                                                                                        eps);
[482]3107
[683]3108                                                if (cf == Polygon3::FRONT_SIDE)
[562]3109                                                {
3110                                                        isAdjacent = false;
3111                                                }
[557]3112                                        }
3113                                }
[562]3114                                else
[557]3115                                {
[562]3116                                        // TODO: why is this wrong??
3117                                        // test all planes of current node if still adjacent
[678]3118                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
[562]3119                                        {
[678]3120                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
[555]3121
[562]3122                                                const int cf =
[678]3123                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
[562]3124                                                                                                        poly->GetSupportingPlane(),
[752]3125                                                                                                        eps);
[557]3126
[683]3127                                                if (cf == Polygon3::FRONT_SIDE)
[562]3128                                                {
3129                                                        isAdjacent = false;
3130                                                }
[557]3131                                        }
[570]3132                                }
[557]3133                                // neighbor was found
3134                                if (isAdjacent)
[562]3135                                {       
[2017]3136                                        neighbors.push_back(static_cast<BspLeaf *>(node));
[562]3137                                }
[463]3138                        }
[562]3139                }
3140                else
3141                {
[2017]3142                        BspInterior *interior = static_cast<BspInterior *>(node);
[482]3143
[678]3144                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
[562]3145                                                                                                   interior->GetPlane(),
[752]3146                                                                                                   eps);
[551]3147                       
[562]3148                        BspNode *front = interior->GetFront();
3149                        BspNode *back = interior->GetBack();
[551]3150           
[562]3151                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3152                        BspNodeGeometry *bGeom = new BspNodeGeometry();
[463]3153
[562]3154                        geom->SplitGeometry(*fGeom,
3155                                                                *bGeom,
3156                                                                interior->GetPlane(),
[1563]3157                                                                mBoundingBox,
[675]3158                                                                //0.0000001f);
[752]3159                                                                eps);
[551]3160               
[683]3161                        if (cf == Polygon3::BACK_SIDE)
[562]3162                        {
[683]3163                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3164                                DEL_PTR(fGeom);
[562]3165                        }
3166                        else
3167                        {
[683]3168                                if (cf == Polygon3::FRONT_SIDE)
[551]3169                                {
[683]3170                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3171                                        DEL_PTR(bGeom);
[551]3172                                }
[482]3173                                else
[562]3174                                {       // random decision
3175                                        nodeStack.push(bspNodePair(front, fGeom));
3176                                        nodeStack.push(bspNodePair(back, bGeom));
[463]3177                                }
[551]3178                        }
[463]3179                }
[562]3180       
[551]3181                DEL_PTR(geom);
[463]3182        }
[482]3183
[463]3184        return (int)neighbors.size();
3185}
3186
[489]3187
[600]3188
[710]3189int VspBspTree::FindApproximateNeighbors(BspNode *n,
3190                                                                                 vector<BspLeaf *> &neighbors,
[600]3191                                                                                 const bool onlyUnmailed) const
3192{
3193        stack<bspNodePair> nodeStack;
3194       
3195        BspNodeGeometry nodeGeom;
3196        ConstructGeometry(n, nodeGeom);
3197       
[752]3198        float eps = 0.01f;
[600]3199        // split planes from the root to this node
3200        // needed to verify that we found neighbor leaf
3201        // TODO: really needed?
3202        vector<Plane3> halfSpaces;
3203        ExtractHalfSpaces(n, halfSpaces);
3204
3205
3206        BspNodeGeometry *rgeom = new BspNodeGeometry();
3207        ConstructGeometry(mRoot, *rgeom);
3208
3209        nodeStack.push(bspNodePair(mRoot, rgeom));
3210
3211        while (!nodeStack.empty())
3212        {
3213                BspNode *node = nodeStack.top().first;
3214                BspNodeGeometry *geom = nodeStack.top().second;
3215       
3216                nodeStack.pop();
3217
3218                if (node->IsLeaf())
3219                {
3220                        // test if this leaf is in valid view space
3221                        if (node->TreeValid() &&
3222                                (node != n) &&
3223                                (!onlyUnmailed || !node->Mailed()))
3224                        {
3225                                bool isAdjacent = true;
3226
3227                                // neighbor was found
3228                                if (isAdjacent)
3229                                {       
[2017]3230                                        neighbors.push_back(static_cast<BspLeaf *>(node));
[600]3231                                }
3232                        }
3233                }
3234                else
3235                {
[2017]3236                        BspInterior *interior = static_cast<BspInterior *>(node);
[600]3237
[678]3238                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
[600]3239                                                                                                   interior->GetPlane(),
[752]3240                                                                                                   eps);
[600]3241                       
3242                        BspNode *front = interior->GetFront();
3243                        BspNode *back = interior->GetBack();
3244           
3245                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3246                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3247
3248                        geom->SplitGeometry(*fGeom,
3249                                                                *bGeom,
3250                                                                interior->GetPlane(),
[1563]3251                                                                mBoundingBox,
[675]3252                                                                //0.0000001f);
[752]3253                                                                eps);
[600]3254               
[683]3255                        if (cf == Polygon3::BACK_SIDE)
[600]3256                        {
[683]3257                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3258                                DEL_PTR(fGeom);
[710]3259                                }
[600]3260                        else
3261                        {
[683]3262                                if (cf == Polygon3::FRONT_SIDE)
[600]3263                                {
[683]3264                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3265                                        DEL_PTR(bGeom);
[600]3266                                }
3267                                else
3268                                {       // random decision
3269                                        nodeStack.push(bspNodePair(front, fGeom));
3270                                        nodeStack.push(bspNodePair(back, bGeom));
3271                                }
3272                        }
3273                }
3274       
3275                DEL_PTR(geom);
3276        }
3277
3278        return (int)neighbors.size();
3279}
3280
3281
3282
[463]3283BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3284{
3285    stack<BspNode *> nodeStack;
3286        nodeStack.push(mRoot);
[482]3287
[463]3288        int mask = rand();
[482]3289
3290        while (!nodeStack.empty())
[463]3291        {
3292                BspNode *node = nodeStack.top();
3293                nodeStack.pop();
[482]3294
3295                if (node->IsLeaf())
[463]3296                {
[2017]3297                        return static_cast<BspLeaf *>(node);
[482]3298                }
3299                else
[463]3300                {
[2017]3301                        BspInterior *interior = static_cast<BspInterior *>(node);
[463]3302                        BspNode *next;
[503]3303                        BspNodeGeometry geom;
[482]3304
[463]3305                        // todo: not very efficient: constructs full cell everytime
[498]3306                        ConstructGeometry(interior, geom);
[463]3307
[503]3308                        const int cf =
[678]3309                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
[463]3310
3311                        if (cf == Polygon3::BACK_SIDE)
3312                                next = interior->GetFront();
3313                        else
3314                                if (cf == Polygon3::FRONT_SIDE)
3315                                        next = interior->GetFront();
[482]3316                        else
[463]3317                        {
3318                                // random decision
3319                                if (mask & 1)
3320                                        next = interior->GetBack();
3321                                else
3322                                        next = interior->GetFront();
3323                                mask = mask >> 1;
3324                        }
3325
3326                        nodeStack.push(next);
3327                }
3328        }
[482]3329
[463]3330        return NULL;
3331}
3332
[694]3333
[463]3334BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3335{
3336        stack<BspNode *> nodeStack;
[482]3337
[463]3338        nodeStack.push(mRoot);
3339
3340        int mask = rand();
[482]3341
3342        while (!nodeStack.empty())
[463]3343        {
3344                BspNode *node = nodeStack.top();
3345                nodeStack.pop();
[482]3346
3347                if (node->IsLeaf())
[463]3348                {
3349                        if ( (!onlyUnmailed || !node->Mailed()) )
[2017]3350                                return static_cast<BspLeaf *>(node);
[463]3351                }
[482]3352                else
[463]3353                {
[2017]3354                        BspInterior *interior = static_cast<BspInterior *>(node);
[463]3355
3356                        // random decision
3357                        if (mask & 1)
3358                                nodeStack.push(interior->GetBack());
3359                        else
3360                                nodeStack.push(interior->GetFront());
3361
3362                        mask = mask >> 1;
3363                }
3364        }
[482]3365
[463]3366        return NULL;
3367}
3368
[694]3369
[463]3370int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3371{
3372        int pvsSize = 0;
3373
3374        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3375
3376        Intersectable::NewMail();
3377
3378        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3379        {
3380                VssRay *ray = (*rit).mRay;
[482]3381
[2233]3382#if COUNT_ORIGIN_OBJECTS
3383                if (ray->mOriginObject)
[463]3384                {
3385                        if (!ray->mOriginObject->Mailed())
3386                        {
3387                                ray->mOriginObject->Mail();
3388                                ++ pvsSize;
3389                        }
3390                }
[2233]3391#endif
[463]3392                if (ray->mTerminationObject)
3393                {
3394                        if (!ray->mTerminationObject->Mailed())
3395                        {
3396                                ray->mTerminationObject->Mail();
3397                                ++ pvsSize;
3398                        }
3399                }
3400        }
3401
3402        return pvsSize;
3403}
3404
[694]3405
[463]3406float VspBspTree::GetEpsilon() const
3407{
3408        return mEpsilon;
3409}
3410
3411
3412int VspBspTree::SplitPolygons(const Plane3 &plane,
[482]3413                                                          PolygonContainer &polys,
3414                                                          PolygonContainer &frontPolys,
3415                                                          PolygonContainer &backPolys,
[463]3416                                                          PolygonContainer &coincident) const
3417{
3418        int splits = 0;
3419
[574]3420        PolygonContainer::const_iterator it, it_end = polys.end();
3421
3422        for (it = polys.begin(); it != polys.end(); ++ it)     
[463]3423        {
[574]3424                Polygon3 *poly = *it;
[463]3425
3426                // classify polygon
3427                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3428
3429                switch (cf)
3430                {
3431                        case Polygon3::COINCIDENT:
3432                                coincident.push_back(poly);
[482]3433                                break;
3434                        case Polygon3::FRONT_SIDE:
[463]3435                                frontPolys.push_back(poly);
3436                                break;
3437                        case Polygon3::BACK_SIDE:
3438                                backPolys.push_back(poly);
3439                                break;
3440                        case Polygon3::SPLIT:
3441                                backPolys.push_back(poly);
3442                                frontPolys.push_back(poly);
3443                                ++ splits;
3444                                break;
3445                        default:
3446                Debug << "SHOULD NEVER COME HERE\n";
3447                                break;
3448                }
3449        }
3450
3451        return splits;
3452}
[466]3453
3454
[469]3455int VspBspTree::CastLineSegment(const Vector3 &origin,
3456                                                                const Vector3 &termination,
[882]3457                                                                ViewCellContainer &viewcells)
[466]3458{
[469]3459        int hits = 0;
[719]3460        stack<BspRayTraversalData> tStack;
[482]3461
[469]3462        float mint = 0.0f, maxt = 1.0f;
[482]3463
[1291]3464        //ViewCell::NewMail();
[482]3465
[469]3466        Vector3 entp = origin;
3467        Vector3 extp = termination;
[482]3468
[469]3469        BspNode *node = mRoot;
3470        BspNode *farChild = NULL;
[482]3471
[485]3472        float t;
[752]3473        const float thresh = 1e-6f; // matt: change this to adjustable value
[2015]3474
[482]3475        while (1)
[469]3476        {
[482]3477                if (!node->IsLeaf())
[469]3478                {
[2017]3479                        BspInterior *in = static_cast<BspInterior *>(node);
[482]3480
[2021]3481                        Plane3 &splitPlane = in->GetPlane();
[485]3482                       
[666]3483                        const int entSide = splitPlane.Side(entp, thresh);
3484                        const int extSide = splitPlane.Side(extp, thresh);
[482]3485
[485]3486                        if (entSide < 0)
[469]3487                        {
[666]3488                                node = in->GetBack();
3489                               
3490                                // plane does not split ray => no far child
3491                                if (extSide <= 0)
3492                                        continue;
3493 
3494                                farChild = in->GetFront(); // plane splits ray
[485]3495                        }
3496                        else if (entSide > 0)
[469]3497                        {
[666]3498                                node = in->GetFront();
[482]3499
[666]3500                                if (extSide >= 0) // plane does not split ray => no far child
3501                                        continue;
[482]3502
3503                                farChild = in->GetBack(); // plane splits ray
[469]3504                        }
[694]3505                        else // one of the ray end points is on the plane
[1020]3506                        {       
3507                                // NOTE: what to do if ray is coincident with plane?
[485]3508                                if (extSide < 0)
3509                                        node = in->GetBack();
[694]3510                                else //if (extSide > 0)
[485]3511                                        node = in->GetFront();
[694]3512                                //else break; // coincident => count no intersections
3513
[485]3514                                continue; // no far child
[469]3515                        }
[482]3516
[469]3517                        // push data for far child
[719]3518                        tStack.push(BspRayTraversalData(farChild, extp));
[482]3519
[469]3520                        // find intersection of ray segment with plane
3521                        extp = splitPlane.FindIntersection(origin, extp, &t);
[485]3522                }
3523                else
[469]3524                {
3525                        // reached leaf => intersection with view cell
[2017]3526                        BspLeaf *leaf = static_cast<BspLeaf *>(node);
[666]3527                        ViewCell *viewCell;
3528                       
[1020]3529                        // question: always contribute to leaf or to currently active view cell?
[2021]3530                        //                      if (0)
3531                        //                              viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3532                        //                      else
3533                        viewCell = leaf->GetViewCell();
[482]3534
[590]3535                        if (!viewCell->Mailed())
[469]3536                        {
[590]3537                                viewcells.push_back(viewCell);
3538                                viewCell->Mail();
[469]3539                                ++ hits;
3540                        }
[482]3541
[469]3542                        //-- fetch the next far child from the stack
[719]3543                        if (tStack.empty())
[469]3544                                break;
[482]3545
[469]3546                        entp = extp;
[485]3547                       
[719]3548                        const BspRayTraversalData &s = tStack.top();
[482]3549
[469]3550                        node = s.mNode;
3551                        extp = s.mExitPoint;
[482]3552
[719]3553                        tStack.pop();
[469]3554                }
[466]3555        }
[487]3556
[469]3557        return hits;
[466]3558}
[478]3559
[576]3560
3561
3562
[485]3563int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
[482]3564{
3565        std::deque<BspNode *> path1;
3566        BspNode *p1 = n1;
[479]3567
[482]3568        // create path from node 1 to root
3569        while (p1)
3570        {
3571                if (p1 == n2) // second node on path
3572                        return (int)path1.size();
3573
3574                path1.push_front(p1);
3575                p1 = p1->GetParent();
3576        }
3577
3578        int depth = n2->GetDepth();
3579        int d = depth;
3580
3581        BspNode *p2 = n2;
3582
3583        // compare with same depth
3584        while (1)
3585        {
3586                if ((d < (int)path1.size()) && (p2 == path1[d]))
3587                        return (depth - d) + ((int)path1.size() - 1 - d);
3588
3589                -- d;
3590                p2 = p2->GetParent();
3591        }
3592
3593        return 0; // never come here
3594}
3595
[580]3596
[501]3597BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
[479]3598{
[590]3599// TODO
[728]3600#if HAS_TO_BE_REDONE
[495]3601        if (node->IsLeaf())
[479]3602                return node;
3603
[2017]3604        BspInterior *interior = static_cast<BspInterior *>(node);
[492]3605
[501]3606        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3607        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
[492]3608
[479]3609        if (front->IsLeaf() && back->IsLeaf())
3610        {
[2017]3611                BspLeaf *frontLeaf = static_cast<BspLeaf *>(front);
3612                BspLeaf *backLeaf = static_cast<BspLeaf *>(back);
[479]3613
3614                //-- collapse tree
3615                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3616                {
3617                        BspViewCell *vc = frontLeaf->GetViewCell();
3618
3619                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
[489]3620                        leaf->SetTreeValid(frontLeaf->TreeValid());
[482]3621
[479]3622                        // replace a link from node's parent
3623                        if (leaf->GetParent())
3624                                leaf->GetParent()->ReplaceChildLink(node, leaf);
[517]3625                        else
3626                                mRoot = leaf;
3627
[501]3628                        ++ collapsed;
[479]3629                        delete interior;
3630
3631                        return leaf;
3632                }
3633        }
[590]3634#endif
[495]3635        return node;
3636}
3637
3638
[501]3639int VspBspTree::CollapseTree()
[495]3640{
[501]3641        int collapsed = 0;
[580]3642        //TODO
[728]3643#if HAS_TO_BE_REDONE
[501]3644        (void)CollapseTree(mRoot, collapsed);
[517]3645
[485]3646        // revalidate leaves
[517]3647        RepairViewCellsLeafLists();
[580]3648#endif
[501]3649        return collapsed;
[479]3650}
3651
3652
[517]3653void VspBspTree::RepairViewCellsLeafLists()
[492]3654{
[590]3655// TODO
[728]3656#if HAS_TO_BE_REDONE
[479]3657        // list not valid anymore => clear
[492]3658        stack<BspNode *> nodeStack;
3659        nodeStack.push(mRoot);
3660
3661        ViewCell::NewMail();
3662
3663        while (!nodeStack.empty())
3664        {
3665                BspNode *node = nodeStack.top();
3666                nodeStack.pop();
3667
3668                if (node->IsLeaf())
3669                {
[2017]3670                        BspLeaf *leaf = static_cast<BspLeaf *>(node);
[492]3671
3672                        BspViewCell *viewCell = leaf->GetViewCell();
[590]3673
[492]3674                        if (!viewCell->Mailed())
3675                        {
3676                                viewCell->mLeaves.clear();
3677                                viewCell->Mail();
3678                        }
[580]3679       
[492]3680                        viewCell->mLeaves.push_back(leaf);
[590]3681
[492]3682                }
3683                else
3684                {
[2017]3685                        BspInterior *interior = static_cast<BspInterior *>(node);
[492]3686
3687                        nodeStack.push(interior->GetFront());
3688                        nodeStack.push(interior->GetBack());
3689                }
[479]3690        }
[590]3691// TODO
3692#endif
[479]3693}
3694
3695
[532]3696int VspBspTree::CastBeam(Beam &beam)
3697{
3698    stack<bspNodePair> nodeStack;
3699        BspNodeGeometry *rgeom = new BspNodeGeometry();
3700        ConstructGeometry(mRoot, *rgeom);
3701
3702        nodeStack.push(bspNodePair(mRoot, rgeom));
3703 
3704        ViewCell::NewMail();
3705
3706        while (!nodeStack.empty())
3707        {
3708                BspNode *node = nodeStack.top().first;
3709                BspNodeGeometry *geom = nodeStack.top().second;
3710                nodeStack.pop();
3711               
3712                AxisAlignedBox3 box;
[697]3713                geom->GetBoundingBox(box);
[532]3714
[535]3715                const int side = beam.ComputeIntersection(box);
[532]3716               
3717                switch (side)
3718                {
3719                case -1:
[547]3720                        CollectViewCells(node, true, beam.mViewCells, true);
[532]3721                        break;
3722                case 0:
[535]3723                       
[532]3724                        if (node->IsLeaf())
3725                        {
[2017]3726                                BspLeaf *leaf = static_cast<BspLeaf *>(node);
[535]3727                       
[532]3728                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
[535]3729                                {
3730                                        leaf->GetViewCell()->Mail();
[532]3731                                        beam.mViewCells.push_back(leaf->GetViewCell());
[535]3732                                }
[532]3733                        }
3734                        else
3735                        {
[2017]3736                                BspInterior *interior = static_cast<BspInterior *>(node);
[535]3737                       
[538]3738                                BspNode *first = interior->GetFront();
3739                                BspNode *second = interior->GetBack();
[535]3740           
3741                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3742                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3743
[538]3744                                geom->SplitGeometry(*firstGeom,
3745                                                                        *secondGeom,
3746                                                                        interior->GetPlane(),
[1563]3747                                                                        mBoundingBox,
[675]3748                                                                        //0.0000001f);
[538]3749                                                                        mEpsilon);
[535]3750
[532]3751                                // decide on the order of the nodes
3752                                if (DotProd(beam.mPlanes[0].mNormal,
3753                                        interior->GetPlane().mNormal) > 0)
3754                                {
3755                                        swap(first, second);
[535]3756                                        swap(firstGeom, secondGeom);
[532]3757                                }
3758
[535]3759                                nodeStack.push(bspNodePair(first, firstGeom));
3760                                nodeStack.push(bspNodePair(second, secondGeom));
[532]3761                        }
[535]3762                       
[532]3763                        break;
[538]3764                default:
[532]3765                        // default: cull
[538]3766                        break;
[532]3767                }
[538]3768               
[532]3769                DEL_PTR(geom);
[535]3770               
[532]3771        }
3772
[538]3773        return (int)beam.mViewCells.size();
[532]3774}
3775
3776
[485]3777void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
[478]3778{
[485]3779        mViewCellsManager = vcm;
3780}
3781
3782
[580]3783int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3784                                                                           vector<MergeCandidate> &candidates)
[485]3785{
[478]3786        BspLeaf::NewMail();
[508]3787       
[478]3788        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3789
[580]3790        int numCandidates = 0;
[509]3791
[478]3792        // find merge candidates and push them into queue
3793        for (it = leaves.begin(); it != it_end; ++ it)
3794        {
3795                BspLeaf *leaf = *it;
[485]3796               
3797                // the same leaves must not be part of two merge candidates
3798                leaf->Mail();
[650]3799               
[485]3800                vector<BspLeaf *> neighbors;
[710]3801               
3802                // appoximate neighbor search has slightl relaxed constraints
[694]3803                if (1)
[650]3804                        FindNeighbors(leaf, neighbors, true);
3805                else
3806                        FindApproximateNeighbors(leaf, neighbors, true);
[710]3807
[485]3808                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3809
3810                // TODO: test if at least one ray goes from one leaf to the other
3811                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
[508]3812                {
3813                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
[509]3814                        {
[580]3815                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
[564]3816
[1006]3817                                if (!leaf->GetViewCell()->GetPvs().Empty() ||
[710]3818                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
[676]3819                    leaf->IsSibling(*nit))
3820                                {
3821                                        candidates.push_back(mc);
3822                                }
3823
[580]3824                                ++ numCandidates;
3825                                if ((numCandidates % 1000) == 0)
[566]3826                                {
[580]3827                                        cout << "collected " << numCandidates << " merge candidates" << endl;
[566]3828                                }
[509]3829                        }
[485]3830                }
3831        }
3832
[580]3833        Debug << "merge queue: " << (int)candidates.size() << endl;
3834        Debug << "leaves in queue: " << numCandidates << endl;
3835       
[508]3836
[485]3837        return (int)leaves.size();
3838}
3839
3840
[580]3841int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3842                                                                           vector<MergeCandidate> &candidates)
[485]3843{
[547]3844        ViewCell::NewMail();
[503]3845        long startTime = GetTime();
[574]3846       
[485]3847        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
[574]3848        ViewCellContainer::const_iterator iit;
[485]3849
[503]3850        int numLeaves = 0;
[485]3851       
3852        BspLeaf::NewMail();
3853
[574]3854        for (int i = 0; i < (int)rays.size(); ++ i)
[485]3855        { 
[574]3856                VssRay *ray = rays[i];
[547]3857       
[485]3858                // traverse leaves stored in the rays and compare and
3859                // merge consecutive leaves (i.e., the neighbors in the tree)
[574]3860                if (ray->mViewCells.size() < 2)
[485]3861                        continue;
[1551]3862
[574]3863                iit = ray->mViewCells.begin();
[2017]3864                BspViewCell *bspVc = static_cast<BspViewCell *>(*(iit ++));
[1551]3865                BspLeaf *leaf = bspVc->mLeaves[0];
[485]3866               
3867                // traverse intersections
[489]3868                // consecutive leaves are neighbors => add them to queue
[574]3869                for (; iit != ray->mViewCells.end(); ++ iit)
[485]3870                {
[489]3871                        // next pair
3872                        BspLeaf *prevLeaf = leaf;
[2017]3873                        bspVc = static_cast<BspViewCell *>(*iit);
[1551]3874            leaf = bspVc->mLeaves[0]; // exactly one leaf
[489]3875
[508]3876                        // view space not valid or same view cell
3877                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3878                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
[489]3879                                continue;
3880
[580]3881                vector<BspLeaf *> &neighbors = neighborMap[leaf];
[485]3882                       
3883                        bool found = false;
[478]3884
[485]3885                        // both leaves inserted in queue already =>
3886                        // look if double pair already exists
3887                        if (leaf->Mailed() && prevLeaf->Mailed())
[478]3888                        {
[485]3889                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3890                               
3891                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3892                                        if (*it == prevLeaf)
3893                                                found = true; // already in queue
3894                        }
[547]3895               
[485]3896                        if (!found)
3897                        {
[564]3898                                // this pair is not in map yet
[485]3899                                // => insert into the neighbor map and the queue
3900                                neighbors.push_back(prevLeaf);
3901                                neighborMap[prevLeaf].push_back(leaf);
[478]3902
[485]3903                                leaf->Mail();
3904                                prevLeaf->Mail();
[547]3905               
[580]3906                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3907                               
3908                                candidates.push_back(mc);
[564]3909
[580]3910                                if (((int)candidates.size() % 1000) == 0)
[564]3911                                {
[580]3912                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
[564]3913                                }
[478]3914                        }
[485]3915        }
3916        }
[564]3917
[485]3918        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
[580]3919        Debug << "merge queue: " << (int)candidates.size() << endl;
[503]3920        Debug << "leaves in queue: " << numLeaves << endl;
[485]3921
[580]3922
[503]3923        //-- collect the leaves which haven't been found by ray casting
[542]3924        if (0)
3925        {
[551]3926                cout << "finding additional merge candidates using geometry" << endl;
[542]3927                vector<BspLeaf *> leaves;
[547]3928                CollectLeaves(leaves, true);
[542]3929                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
[580]3930                CollectMergeCandidates(leaves, candidates);
[542]3931        }
[503]3932
3933        return numLeaves;
[485]3934}
3935
3936
3937
3938
[879]3939ViewCell *VspBspTree::GetViewCell(const Vector3 &point, const bool active)
[492]3940{
[879]3941        if (mRoot == NULL)
3942                return NULL;
3943
3944        stack<BspNode *> nodeStack;
3945        nodeStack.push(mRoot);
[492]3946 
[882]3947        ViewCellLeaf *viewcell = NULL;
[492]3948 
[879]3949        while (!nodeStack.empty()) 
3950        {
3951                BspNode *node = nodeStack.top();
3952                nodeStack.pop();
[492]3953       
[879]3954                if (node->IsLeaf())
3955                {
[2017]3956                        viewcell = static_cast<BspLeaf *>(node)->GetViewCell();
[879]3957                        break;
3958                }
3959                else   
3960                {       
[2017]3961                        BspInterior *interior = static_cast<BspInterior *>(node);
[879]3962       
3963                        // random decision
3964                        if (interior->GetPlane().Side(point) < 0)
3965                                nodeStack.push(interior->GetBack());
3966                        else
3967                                nodeStack.push(interior->GetFront());
3968                }
[492]3969        }
3970 
[879]3971        if (active)
3972                return mViewCellsTree->GetActiveViewCell(viewcell);
3973        else
3974                return viewcell;
[492]3975}
3976
3977
[487]3978bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3979{
3980        BspNode *node = mRoot;
[485]3981
[487]3982        while (1)
3983        {
3984                // early exit
3985                if (node->TreeValid())
3986                        return true;
3987
3988                if (node->IsLeaf())
3989                        return false;
3990                       
[2017]3991                BspInterior *in = static_cast<BspInterior *>(node);
[490]3992                                       
3993                if (in->GetPlane().Side(viewPoint) <= 0)
[487]3994                {
3995                        node = in->GetBack();
3996                }
3997                else
3998                {
3999                        node = in->GetFront();
4000                }
4001        }
4002
4003        // should never come here
4004        return false;
4005}
4006
4007
4008void VspBspTree::PropagateUpValidity(BspNode *node)
4009{
[574]4010        const bool isValid = node->TreeValid();
4011
4012        // propagative up invalid flag until only invalid nodes exist over this node
4013        if (!isValid)
[487]4014        {
[574]4015                while (!node->IsRoot() && node->GetParent()->TreeValid())
4016                {
4017                        node = node->GetParent();
4018                        node->SetTreeValid(false);
4019                }
[487]4020        }
[574]4021        else
4022        {
4023                // propagative up valid flag until one of the subtrees is invalid
4024                while (!node->IsRoot() && !node->TreeValid())
4025                {
4026            node = node->GetParent();
[2017]4027                        BspInterior *interior = static_cast<BspInterior *>(node);
[574]4028                       
4029                        // the parent is valid iff both leaves are valid
4030                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
4031                                                           interior->GetFront()->TreeValid());
4032                }
4033        }
[487]4034}
4035
[1201]4036
4037bool VspBspTree::Export(OUT_STREAM &stream)
[503]4038{
[508]4039        ExportNode(mRoot, stream);
[503]4040        return true;
4041}
4042
[1201]4043
4044void VspBspTree::ExportNode(BspNode *node, OUT_STREAM &stream)
[508]4045{
4046        if (node->IsLeaf())
[503]4047        {
[2017]4048                BspLeaf *leaf = static_cast<BspLeaf *>(node);
[590]4049                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
4050
[508]4051                int id = -1;
[590]4052                if (viewCell != mOutOfBoundsCell)
4053                        id = viewCell->GetId();
[503]4054
[508]4055                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
[503]4056        }
[508]4057        else
[503]4058        {
[2017]4059                BspInterior *interior = static_cast<BspInterior *>(node);
[508]4060       
4061                Plane3 plane = interior->GetPlane();
4062                stream << "<Interior plane=\"" << plane.mNormal.x << " "
4063                           << plane.mNormal.y << " " << plane.mNormal.z << " "
4064                           << plane.mD << "\">" << endl;
[503]4065
[508]4066                ExportNode(interior->GetBack(), stream);
4067                ExportNode(interior->GetFront(), stream);
[503]4068
[508]4069                stream << "</Interior>" << endl;
[503]4070        }
4071}
[860]4072
[1580]4073}
Note: See TracBrowser for help on using the repository browser.