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

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