source: GTP/trunk/Lib/Vis/Preprocessing/src/GvsPreprocessor.cpp @ 2717

Revision 2717, 36.5 KB checked in by mattausch, 16 years ago (diff)
  • Property svn:executable set to *
RevLine 
[1460]1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
[1473]4#include "VssRay.h"
5#include "ViewCellsManager.h"
[1486]6#include "Triangle3.h"
[1489]7#include "IntersectableWrapper.h"
[1500]8#include "Plane3.h"
[1521]9#include "RayCaster.h"
[1522]10#include "Exporter.h"
[1545]11#include "SamplingStrategy.h"
[1990]12#include "BvHierarchy.h"
[2116]13#include "Polygon3.h"
[2643]14#include "IntersectableWrapper.h"
[1460]15
[1473]16
[2643]17
[1460]18namespace GtpVisibilityPreprocessor
19{
20 
[2633]21#define GVS_DEBUG 0
[2669]22#define NOT_ACCOUNTED_OBJECT 0
23#define ACCOUNTED_OBJECT 2
[1934]24
[2705]25
[2669]26static const float MIN_DIST = 0.001f;
27
28static ObjectContainer myobjects;
29
30
31/** Visualization structure for the GVS algorithm.
32*/
[1522]33struct VizStruct
34{
35        Polygon3 *enlargedTriangle;
36        Triangle3 originalTriangle;
37        VssRay *ray;
38};
[1460]39
[2669]40static vector<VizStruct> vizContainer;
[2048]41
[1990]42
[1522]43
[2648]44
[1533]45GvsPreprocessor::GvsPreprocessor():
[1545]46Preprocessor(),
[1996]47mProcessedViewCells(0),
[2625]48mCurrentViewCell(NULL),
[2691]49mCurrentViewPoint(Vector3(0.0f, 0.0f, 0.0f)),
50mOnlyRandomSampling(false)
51//mOnlyRandomSampling(true)
[1460]52{
[1486]53        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
54        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
[2048]55        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
[1996]56        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
[1486]57        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
[1500]58        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
[1990]59        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
[1996]60        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
[1473]61
[2048]62        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
63
[2615]64        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
65
66
[1934]67        char gvsStatsLog[100];
68        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
69        mGvsStatsStream.open(gvsStatsLog);
70
[2677]71        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
72        cout << "number of samples per pass: " << mSamplesPerPass << endl;
[2691]73        cout << "only random sampling: " << mOnlyRandomSampling << endl;
[2677]74
[1486]75        Debug << "Gvs preprocessor options" << endl;
76        Debug << "number of total samples: " << mTotalSamples << endl;
77        Debug << "number of initial samples: " << mInitialSamples << endl;
[1501]78        Debug << "threshold: " << mThreshold << endl;
[1934]79        Debug << "epsilon: " << mEps << endl;
80        Debug << "stats: " << gvsStatsLog << endl;
[1996]81        Debug << "per view cell: " << mPerViewCell << endl;
82        Debug << "max view cells: " << mMaxViewCells << endl;
83        Debug << "min contribution: " << mMinContribution << endl;
[1486]84
[2691]85        mDistribution = new ViewCellBasedDistribution(*this, NULL);
[1934]86
87        mGvsStats.Reset();
[2643]88
[2695]89        // hack: some generic statistical values that can be used
[2648]90        // by an application using the preprocessor
[2691]91        for (int i = 0; i < 2; ++ i)
92                mGenericStats[i] = 0;
[1460]93}
94
[1473]95
[1990]96GvsPreprocessor::~GvsPreprocessor()
97{
[2691]98        delete mDistribution;
[1996]99        ClearRayQueue();
100}
101
102
103void GvsPreprocessor::ClearRayQueue()
104{
[1990]105        // clean ray queue
106        while (!mRayQueue.empty())
107        {
108                // handle next ray
109                VssRay *ray = mRayQueue.top();
110                mRayQueue.pop();
111
[2695]112                // note: deletion of the ray is handled by ray pool
[1990]113        }
114}
115
116
[2625]117ViewCell *GvsPreprocessor::NextViewCell()
[1982]118{
[1996]119        if (mProcessedViewCells == (int)mViewCells.size())
[2625]120                return NULL; // no more view cells
[1982]121
[2625]122        ViewCell *vc = mViewCells[mProcessedViewCells];
[1982]123
[2625]124   if (!vc->GetMesh())
125                mViewCellsManager->CreateMesh(vc);
[1990]126
[2625]127        mGvsStats.mViewCellId = vc->GetId();
[1996]128
[2625]129        Debug << "vc: " << vc->GetId() << endl;
[1996]130
131        ++ mProcessedViewCells;
[1982]132   
[2625]133        return vc;
[1982]134}
135
136
[1996]137int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
138                                                                                const Triangle3 &hitTriangle,
139                                                                                const VssRay &oldRay)
[1460]140{
[1932]141        // the predicted hitpoint: we expect to hit the same mesh again
142        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
143
144        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
145        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
146       
[2695]147#if 1
[1932]148        // distance large => this is likely to be a discontinuity
149        if ((predictedLen - len) > mThreshold)
[2695]150#else
151        // q: rather use relative distance?
[1933]152        if ((predictedLen / len) > mThreshold)
153#endif
[1500]154        {
[1933]155                // apply reverse sampling to find the gap
[1500]156                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
[1933]157
[2695]158                // check if reverse sampling was successful
159                if (newRay)
160                {
161                        // set flag for visualization
162                        if (0) newRay->mFlags |= VssRay::ReverseSample;
163               
164                        // check if ray can be processed further
165                        // note: ray deletion handled by ray pool)
166                        HandleRay(newRay);
167
[1996]168                        return 1;
[2695]169                }
[1500]170        }
171
[1996]172        return 0;
[1486]173}
[1473]174
[2053]175
[2705]176int GvsPreprocessor::CountObject(Intersectable *triObj)
[2669]177{
[2705]178        int numObjects = 0;
179
[2687]180        if ((triObj->mCounter != (NOT_ACCOUNTED_OBJECT + 1)) &&
181                (triObj->mCounter != (ACCOUNTED_OBJECT + 1)))
[2669]182        {
183                ++ triObj->mCounter;
[2705]184                ++ numObjects;
[2669]185        }
[2705]186
187        mGenericStats[1] += numObjects;
188
189        return numObjects;
[2669]190}
191
192
193void GvsPreprocessor::UpdateStatsForVisualization(KdIntersectable *kdInt)
194{
195        // count new objects in pvs due to kd node conversion   
196        myobjects.clear();
[2705]197        // also gather duplicates to avoid mailing
198        mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2669]199
[2705]200        int numObj;
201
[2669]202        ObjectContainer::const_iterator oit, oit_end = myobjects.end();
203
204        for (oit = myobjects.begin(); oit != oit_end; ++ oit)
[2705]205                numObj = CountObject(*oit);
206
207        mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt, numObj);
[2669]208}       
209
210
[1999]211bool GvsPreprocessor::HasContribution(VssRay &ray)
[1486]212{
[1999]213        if (!ray.mTerminationObject)
214                return false;
[1933]215
[1999]216        bool result;
217
[1977]218        if (!mPerViewCell)
219        {
[1999]220                // store the rays + the intersected view cells
221                const bool storeViewCells = false; //GVS_DEBUG;
222
223                mViewCellsManager->ComputeSampleContribution(ray,
[1977]224                                                                                                         true,
[1999]225                                                                                                         storeViewCells,
[1990]226                                                                                                         true);
[1999]227
228                result = ray.mPvsContribution > 0;
[1977]229        }
[2625]230        else // original per view cell gvs
[1977]231        {
[1999]232                Intersectable *obj = ray.mTerminationObject;
233
[2692]234                // test if triangle was accounted for yet
[2691]235                result = AddTriangleObject(obj);
236               
237                if (mUseKdPvs && (1 || result))
[1999]238                {
[2669]239                        // exchange the triangle with the node in the pvs for kd pvs
[2691]240                        KdNode *node = mKdTree->GetPvsNode(ray.mTermination);
241
242                        //KdNode *node = mKdTree->GetPvsNodeCheck(ray.mTermination, obj);
[2694]243                        //if (!node) cerr << "e " << obj->GetBox() << " " << ray.mTermination << endl; else
[2691]244                        if (!node->Mailed())
[2694]245                        {//cout<<"o ";
[2691]246                                // add to pvs
247                                node->Mail();
248                                KdIntersectable *kdInt = mKdTree->GetOrCreateKdIntersectable(node);
249                                mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
[1999]250
[2705]251                                if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
[2615]252                        }
[1999]253                }
[1977]254        }
[1932]255
[1999]256        return result;
257}
258
259
260bool GvsPreprocessor::HandleRay(VssRay *vssRay)
261{
262        if (!HasContribution(*vssRay))
[1977]263                return false;
264
[2005]265        if (0 && GVS_DEBUG)
[1990]266                mVssRays.push_back(new VssRay(*vssRay));
267
[1977]268        // add new ray to ray queue
269        mRayQueue.push(vssRay);
270
[1990]271        ++ mGvsStats.mTotalContribution;
[1533]272
[1977]273        return true;
[1460]274}
275
[1500]276
277/** Creates 3 new vertices for triangle vertex with specified index.
[1489]278*/
[1932]279void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
280                                                                                          const Triangle3 &hitTriangle,
281                                                                                          const VssRay &ray,
282                                                                                          const int index) const
[1460]283{
[1486]284        const int indexU = (index + 1) % 3;
285        const int indexL = (index == 0) ? 2 : index - 1;
286
[1524]287        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
[1486]288        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
289        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
[1492]290       
[1533]291        const float len = Magnitude(a);
[1932]292       
[1523]293        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
294        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
[1524]295        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
296                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
[1492]297
[1486]298        // compute the new three hit points
[1500]299        // pi, i + 1:  pi+ e·|pi-xp|·di, j
[1932]300        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
[1500]301        // pi, i - 1:  pi+ e·|pi-xp|·di, j
[1932]302    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
[1500]303        // pi, i:  pi+ e·|pi-xp|·di, j
[1932]304        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
[1489]305       
[1524]306        vertices.push_back(pt2);
307        vertices.push_back(pt3);
[1500]308        vertices.push_back(pt1);
[1489]309}
310
311
[1500]312void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
313                                                                          const Triangle3 &hitTriangle,
[1932]314                                                                          const VssRay &ray) const
[1500]315{
[1932]316        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
317        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
318        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
[1500]319}
[1492]320
[1500]321
[1932]322Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
323                                                                                           const Triangle3 &hitTriangle,
324                                                                                           const VssRay &oldRay) const
[1489]325{
[1932]326        // find the intersection of the plane induced by the
327        // hit triangle with the new ray
[1500]328        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
329
330        const Vector3 hitPt =
331                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
332       
333        return hitPt;
334}
335
336
337static bool EqualVisibility(const VssRay &a, const VssRay &b)
338{
339        return a.mTerminationObject == b.mTerminationObject;
340}
341
342
343int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
344                                                                   const Vector3 &p1,
345                                                                   const Vector3 &p2,
[1932]346                                                                   const VssRay &ray1,
347                                                                   const VssRay &ray2,
[1500]348                                                                   const VssRay &oldRay)
[2048]349{
350        //cout <<"y"<<Magnitude(p1 - p2) << " ";
[1996]351        int castRays = 0;
352
[1990]353        // cast reverse rays if necessary
[1996]354        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
355        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
[1500]356
[2017]357        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
[1500]358        {
[1996]359                return castRays;
[1500]360        }
[1932]361       
[1990]362        // the new subdivision point
363        const Vector3 p = (p1 + p2) * 0.5f;
[2017]364        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
[1990]365        // cast ray into the new point
366        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
[1932]367
[1996]368        VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
369       
370        ++ castRays;
[1580]371
[1996]372        if (!newRay) return castRays;
[1580]373
[2053]374        //newRay->mFlags |= VssRay::BorderSample;
[1990]375
376        // add new ray to queue
377        const bool enqueued = HandleRay(newRay);
378
379        // subdivide further
[1996]380        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
381        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
[1990]382
383        // this ray will not be further processed
[2692]384        // note: ray deletion is handled by ray pool
[1990]385
[1996]386        return castRays;
[1500]387}
388
389
390int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
391{
392        Intersectable *tObj = currentRay.mTerminationObject;
[2597]393        // q matt: can this be possible
394        if (!tObj) return 0;
395
[1486]396        Triangle3 hitTriangle;
[1489]397
398        // other types not implemented yet
399        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2017]400                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[1522]401        else
[2601]402                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
[1489]403
[2601]404        //cout << "type: " << Intersectable::GetTypeName(tObj) << endl;
405
[1500]406        VertexContainer enlargedTriangle;
407       
408        /// create 3 new hit points for each vertex
409        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
410       
411        /// create rays from sample points and handle them
[1492]412        SimpleRayContainer simpleRays;
413        simpleRays.reserve(9);
[1486]414
[1500]415        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
[1486]416
[1500]417        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
418        {
419                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
[1990]420
[1883]421                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
[1990]422                simpleRays.AddRay(sr); 
[1500]423        }
[1522]424
[1566]425        if (0)
426        {
[1932]427                // visualize enlarged triangles
[1566]428                VizStruct dummy;
429                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
430                dummy.originalTriangle = hitTriangle;
431                vizContainer.push_back(dummy);
432        }
433
[1524]434        // cast rays to triangle vertices and determine visibility
[1489]435        VssRayContainer vssRays;
[1533]436
[1932]437        // don't cast double rays as we need only the forward rays
[1996]438        const bool castDoubleRays = !mPerViewCell;
[1990]439        // cannot prune invalid rays because we have to compare adjacent  rays.
[1932]440        const bool pruneInvalidRays = false;
441
[1996]442
443        //////////
444        //-- fill up simple rays with random rays so we can cast 16
445
446        //const int numRandomRays = 0;
447        const int numRandomRays = 16 - (int)simpleRays.size();
448
[2691]449        GenerateRays(numRandomRays, *mDistribution, simpleRays);
[1996]450
[2053]451
[1996]452        /////////////////////
453
[1990]454        // keep origin for per view cell sampling
[1996]455        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
[1932]456
[1996]457        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
[2648]458
459#if 0
[1580]460        // set flags
[2648]461        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
[1996]462        for (rit = vssRays.begin(); rit != rit_end; ++ rit, ++ i)
[2053]463                (*rit)->mFlags |= VssRay::BorderSample;
[2648]464#endif
465
[1999]466        int castRays = (int)simpleRays.size();
467
468        VssRayContainer invalidSamples;
469
[1932]470        // handle rays
[1999]471        EnqueueRays(vssRays, invalidSamples);
472
[1500]473    // recursivly subdivide each edge
[1996]474        for (int i = 0; i < numBorderSamples; ++ i)
[1500]475        {
[1932]476                castRays += SubdivideEdge(hitTriangle,
477                                                                  enlargedTriangle[i],
[1996]478                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
[1932]479                                                                  *vssRays[i],
[1996]480                                                                  *vssRays[(i + 1) % numBorderSamples],
[1932]481                                                                  currentRay);
[1500]482        }
[1999]483       
[1934]484        mGvsStats.mBorderSamples += castRays;
[1932]485
[2048]486       
[1533]487        return castRays;
[1473]488}
489
490
[1996]491bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
492                                                                          const Triangle3 &occluder,
493                                                                          const VssRay &oldRay,
494                                                                          Vector3 &newPoint) const
[1933]495{
496        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
497        //-- with the newly found occluder (xold is the previous ray from
498        //-- which x was generated). On the intersecting line, we select a point
499        //-- pnew which lies just outside of the new triangle so the ray
500        //-- just passes through the gap
501
502        const Plane3 plane(currentRay.GetOrigin(),
503                                           currentRay.GetTermination(),
504                                           oldRay.GetTermination());
505       
506        Vector3 pt1, pt2;
507
508        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
509
510        if (!intersects)
[1996]511        {
[1999]512                //cerr << "big error!! no intersection " << pt1 << " " << pt2 << endl;
[1996]513                return false;
514        }
[1933]515
516        // get the intersection point on the old ray
517        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
518
519        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
520        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
521
[2695]522        // evaluate new hitpoint just outside the triangle
[1933]523        // the point is chosen to be on the side closer to the original ray
524        if (Distance(pt1, pt3) < Distance(pt2, pt3))
[2695]525                newPoint = pt1 + mEps * (pt1 - pt2);
[1933]526        else
[2695]527                newPoint = pt2 + mEps * (pt2 - pt1);
[1933]528
[1934]529        //cout << "passing point: " << newPoint << endl << endl;
[1996]530        return true;
[1500]531}
532
533
534VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
535                                                                                 const Triangle3 &hitTriangle,
536                                                                                 const VssRay &oldRay)
537{
[1933]538        // get triangle occluding the path to the hit mesh
539        Triangle3 occluder;
540        Intersectable *tObj = currentRay.mTerminationObject;
[1934]541
[1933]542        // q: why can this happen?
543        if (!tObj)
544                return NULL;
545
546        // other types not implemented yet
547        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2048]548        {
[2017]549                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[2048]550        }
[1933]551        else
[2048]552        {
553                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
554        }
[1933]555        // get a point which is passing just outside of the occluder
[1996]556    Vector3 newPoint;
557
[2695]558        // q: why is there sometimes no intersecton found?
[1996]559        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
560                return NULL;
561
[1500]562        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
563
[1990]564        Vector3 newDir, newOrigin;
565
[1932]566        //-- Construct the mutated ray with xnew,
567        //-- dir = predicted(x)- pnew as direction vector
[1990]568        newDir = predicted - newPoint;
[1932]569
[1933]570        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
[1500]571        // difficult to say!!
[1935]572        const float offset = 0.5f;
[1990]573        newOrigin = newPoint - newDir * offset;
574       
[2694]575
[1990]576        //////////////
577        //-- for per view cell sampling, we must check for intersection
578        //-- with the current view cell
[1500]579
[1990]580    if (mPerViewCell)
581        {
582                // send ray to view cell
583                static Ray ray;
584                ray.Clear();
585                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
586               
587                //cout << "z";
588                // check if ray intersects view cell
589                if (!mCurrentViewCell->CastRay(ray))
590                        return NULL;
[1981]591
[1990]592                Ray::Intersection &hit = ray.intersections[0];
593       
594                //cout << "q";
595                // the ray starts from the view cell
596                newOrigin = ray.Extrap(hit.mT);
597        }
[1981]598
[2695]599        ++ mGvsStats.mReverseSamples;
600
[1933]601        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
[1571]602
[1933]603        VssRay *reverseRay =
[1996]604                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
[1933]605
606        return reverseRay;
[1473]607}
608
[1489]609
[2691]610int GvsPreprocessor::CastInitialSamples(int numSamples)
[1489]611{       
[1473]612        const long startTime = GetTime();
[1595]613
[1489]614        // generate simple rays
615        SimpleRayContainer simpleRays;
[1990]616       
[2691]617        ViewCellBorderBasedDistribution vcStrat(*this, mCurrentViewCell);
618    GenerateRays(numSamples, *mDistribution, simpleRays);
[1990]619
620        //cout << "sr: " << simpleRays.size() << endl;
[1489]621        // generate vss rays
[1473]622        VssRayContainer samples;
[1990]623       
[1996]624        const bool castDoubleRays = !mPerViewCell;
[1990]625        const bool pruneInvalidRays = true;
626       
[1996]627        CastRays(simpleRays, samples, castDoubleRays, pruneInvalidRays);
628       
[1999]629        VssRayContainer invalidSamples;
630
[1489]631        // add to ray queue
[1999]632        EnqueueRays(samples, invalidSamples);
[1533]633
[2053]634        //CLEAR_CONTAINER(invalidSamples);
[2633]635        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
[1990]636        return (int)simpleRays.size();
[1489]637}
638
639
[1999]640void GvsPreprocessor::EnqueueRays(VssRayContainer &samples, VssRayContainer &invalidSamples)
[1489]641{
[1486]642        // add samples to ray queue
[1473]643        VssRayContainer::const_iterator vit, vit_end = samples.end();
[1576]644        for (vit = samples.begin(); vit != vit_end; ++ vit)
[1473]645        {
[1999]646                VssRay *ray = *vit;
647
[2053]648                HandleRay(ray);
[2633]649                //if (!HandleRay(ray)) invalidSamples.push_back(ray);
[1460]650        }
651}
652
[1473]653
[1990]654int GvsPreprocessor::ProcessQueue()
[1460]655{
[2695]656        ++ mGvsStats.mGvsRuns;
[1545]657
[2687]658        int castSamples = 0;
659
[2048]660        while (!mRayQueue.empty())//&& (mGvsStats.mTotalSamples + castSamples < mTotalSamples) )
[2690]661        {
[1990]662                // handle next ray
663                VssRay *ray = mRayQueue.top();
664                mRayQueue.pop();
[1996]665               
[1990]666                const int newSamples = AdaptiveBorderSampling(*ray);
[1934]667
[1990]668                castSamples += newSamples;
[2687]669                // note: don't have to delete because handled by ray pool
[1473]670        }
671
[2161]672        /*if (mRayCaster->mVssRayPool.mIndex > mSamplesPerPass)
[2048]673        {
674                cout << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
675                Debug << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
[2161]676        }*/
[2048]677
[1533]678        return castSamples;
[1460]679}
680
[1473]681
[1990]682void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
[1460]683{
[1990]684        VssRayContainer vcRays, vcRays2, vcRays3;
[1473]685
[1990]686        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
687
688        // prepare some rays for output
689        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
[1473]690        {
[1990]691                //const float p = RandomValue(0.0f, (float)vssRays.size());
[1545]692
[1990]693                if (1)//(p < raysOut)
694                {
695                        if ((*rit)->mFlags & VssRay::BorderSample)
696                        {
697                                vcRays.push_back(*rit);
698                        }
699                        else if ((*rit)->mFlags & VssRay::ReverseSample)
700                        {
701                                vcRays2.push_back(*rit);
702                        }
703                        else
704                        {
705                                vcRays3.push_back(*rit);
706                        }       
707                }
[1460]708        }
[1990]709
[2005]710        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
711        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
[2003]712        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
[1990]713}
714
715
[1999]716void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
[1990]717{
718    Intersectable::NewMail();
719        Material m;
[1528]720       
[1996]721        char str[64]; sprintf(str, "pass%06d.wrl", mProcessedViewCells);
[1990]722
723        Exporter *exporter = Exporter::GetExporter(str);
724        if (!exporter)
725                return;
726
[1999]727        ObjectContainer::const_iterator oit, oit_end = objects.end();
728
729        for (oit = objects.begin(); oit != oit_end; ++ oit)
730        {
731                Intersectable *intersect = *oit;
732               
733                m = RandomMaterial();
734                exporter->SetForcedMaterial(m);
735                exporter->ExportIntersectable(intersect);
[1990]736        }
737
738        cout << "vssrays: " << (int)mVssRays.size() << endl;
739        ExportVssRays(exporter, mVssRays);
740
[2597]741
[1990]742        /////////////////
743        //-- export view cell geometry
744
[2597]745        //exporter->SetWireframe();
[1990]746
747        m.mDiffuseColor = RgbColor(0, 1, 0);
748        exporter->SetForcedMaterial(m);
749
[1999]750        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
751        exporter->ExportBox(bbox);
[1990]752        //exporter->SetFilled();
753
[2053]754        delete exporter;
[1460]755}
756
757
[1982]758void GvsPreprocessor::VisualizeViewCells()
759{
[1996]760        char str[64]; sprintf(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
[1982]761                       
762        // visualization
763        if (mGvsStats.mPassContribution > 0)
764        {
765                const bool exportRays = true;
766                const bool exportPvs = true;
767
768                mViewCellsManager->ExportSingleViewCells(mObjects,
769                                                                                                 10,
770                                                                                                 false,
771                                                                                                 exportPvs,
772                                                                                                 exportRays,
773                                                                                                 1000,
774                                                                                                 str);
775        }
776
777        // remove pass samples
778        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
779
780        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
781        {
782                (*vit)->DelRayRefs();
783        }
784}
785
786
[2687]787void GvsPreprocessor::CompileViewCellsFromPointList()
[1996]788{
[2687]789        ViewCell::NewMail();
790
[2648]791        // Receive list of view cells from view cells manager
[2598]792        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
[2687]793
794        vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
795
796        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
[2048]797        {
[2687]798                ViewCellPoints *vp = *vit;
[2048]799
[2687]800                if (vp->first) // view cell  specified
[2648]801                {
[2687]802                        ViewCell *viewCell = vp->first;
[2048]803
[2687]804                        if (!viewCell->Mailed())
805                        {
806                                viewCell->Mail();
807                                mViewCells.push_back(viewCell);
808
809                                if (mViewCells.size() >= mMaxViewCells)
810                                        break;
811                        }
[2662]812                }
[2687]813                else // no view cell specified => compute view cells using view point
814                {
815                        SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
816
817                        for (rit = vp->second.begin(); rit != rit_end; ++ rit)
818                        {
819                                SimpleRay ray = *rit;
820
821                                ViewCell *viewCell = mViewCellsManager->GetViewCell(ray.mOrigin);
822
823                                if (viewCell && !viewCell->Mailed())
824                                {
825                                        viewCell->Mail();
826                                        mViewCells.push_back(viewCell);
827
828                                        if (mViewCells.size() >= mMaxViewCells)
829                                                break;
830                                }
831                        }
832                }
[2048]833        }
[2687]834}
835
836
837void GvsPreprocessor::CompileViewCellsList()
838{
839        if (!mViewCellsManager->GetViewCellPointsList()->empty())
840        {
841                cout << "processing view point list" << endl;
842                CompileViewCellsFromPointList();
843        }
[2662]844        else
845        {
[2687]846                ViewCell::NewMail();
847
[2662]848                while ((int)mViewCells.size() < mMaxViewCells)
[1996]849                {
[2662]850                        const int tries = 10000;
851                        int i = 0;
[1996]852
[2662]853                        for (i = 0; i < tries; ++ i)
[1996]854                        {
[2662]855                                const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
856
857                                ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
858
859                                if (!viewCell->Mailed())
860                                {
861                                        viewCell->Mail();
862                                        break;
863                                }
864
865                                mViewCells.push_back(viewCell);
[1999]866                        }
[2597]867
[2662]868                        if (i == tries)
869                        {
870                                cerr << "big error! no view cell found" << endl;
871                                break;
872                        }
[1999]873                }
874        }
[2662]875
876        cout << "\ncomputing list of " << mViewCells.size() << " view cells" << endl;
[1999]877}
[1996]878
[2669]879
[2705]880void GvsPreprocessor::ComputeViewCellGeometryIntersection()
[2687]881{
[2691]882        AxisAlignedBox3 box = mCurrentViewCell->GetBox();
[2687]883
[2691]884        int oldTrianglePvs = (int)mTrianglePvs.size();
885        int newKdObj = 0;
886
[2687]887        // compute pvs kd nodes that intersect view cell
888        ObjectContainer kdobjects;
[2691]889
890        // find intersecting objects not in pvs (i.e., only unmailed)
[2687]891        mKdTree->CollectKdObjects(box, kdobjects);
892
893        ObjectContainer pvsKdObjects;
894
895        ObjectContainer::const_iterator oit, oit_end = kdobjects.end();
896
897        for (oit = kdobjects.begin(); oit != oit_end; ++ oit)
898        {
899        KdIntersectable *kdInt = static_cast<KdIntersectable *>(*oit);
900       
901                myobjects.clear();
[2691]902                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2687]903
904                // account for kd object pvs
905                bool addkdobj = false;
906
907                ObjectContainer::const_iterator oit, oit_end = myobjects.end();
908
909                for (oit = myobjects.begin(); oit != oit_end; ++ oit)
910                {
911                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
[2691]912             
913                        // test if the triangle itself intersects
[2687]914                        if (box.Intersects(triObj->GetItem()))
[2691]915                                addkdobj = AddTriangleObject(triObj);
[2687]916                }
917               
[2691]918                // add node to kd pvs
919                if (1 && addkdobj)
920                {
921                        ++ newKdObj;
922                        mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
923                        //mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
[2705]924                        if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
[2691]925                }
[2687]926        }
927
[2691]928        cout << "added " << (int)mTrianglePvs.size() - oldTrianglePvs << " triangles (" << newKdObj << " objects) by intersection" << endl;
[2687]929}
930
[2691]931
[1990]932void GvsPreprocessor::PerViewCellComputation()
[1982]933{
[2690]934        while (mCurrentViewCell = NextViewCell())
[1999]935        {
[2625]936                // hack: reset counters
937                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
[2615]938
[2625]939                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]940                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[1982]941
[2691]942                mDistribution->SetViewCell(mCurrentViewCell);
[2690]943        ComputeViewCell();
[2625]944        }
945}
[1990]946
[1996]947
[2625]948void GvsPreprocessor::PerViewCellComputation2()
949{
950        while (1)
951        {
952                if (!mRendererWidget)
953                        continue;
[1990]954
[2690]955        mCurrentViewCell = mViewCellsManager->GetViewCell(mRendererWidget->GetViewPoint());
[2601]956
[2625]957                // no valid view cell or view cell already computed
[2690]958                if (!mCurrentViewCell || !mCurrentViewCell->GetPvs().Empty() || !mRendererWidget->mComputeGVS)
[2625]959                        continue;
[2615]960
[2643]961                mRendererWidget->mComputeGVS = false;
[2625]962                // hack: reset counters
963                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
[2615]964
[2625]965                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]966                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2601]967
[2690]968                ComputeViewCell();
[2625]969                ++ mProcessedViewCells;
970        }
971}
[1999]972
[1982]973
[2048]974void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
975{
976        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
977
978        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
979        {
980                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
981        }
982}
983
984
[1990]985void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
986{
987        ObjectPvs newPvs;
988        BvhLeaf::NewMail();
989
990        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
991
992        // output PVS of view cell
993        while (pit.HasMoreEntries())
994        {               
[2117]995                Intersectable *intersect = pit.Next();
[1990]996
997                BvhLeaf *bv = intersect->mBvhLeaf;
998
999                if (!bv || bv->Mailed())
1000                        continue;
1001               
1002                bv->Mail();
1003
1004                //m.mDiffuseColor = RgbColor(1, 0, 0);
1005                newPvs.AddSampleDirty(bv, 1.0f);
[1982]1006        }
[1990]1007
1008        newPvs.SimpleSort();
1009
1010        currentViewCell->SetPvs(newPvs);
[1982]1011}
1012
[1999]1013 
1014void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1015{
[2695]1016        BvhLeaf::NewMail();
1017
[2053]1018        objectPvs.reserve((int)mTrianglePvs.size());
1019
[1999]1020        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1021
1022        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1023        {
1024                Intersectable *intersect = *oit;
1025       
1026                BvhLeaf *bv = intersect->mBvhLeaf;
1027
[2053]1028                // hack: reset counter
[2669]1029                (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2053]1030
[1999]1031                if (!bv || bv->Mailed())
1032                        continue;
[2615]1033
[1999]1034                bv->Mail();
1035                objectPvs.push_back(bv);
1036        }
1037}
1038
1039
[1990]1040void GvsPreprocessor::GlobalComputation()
1041{
1042        int passSamples = 0;
1043        int oldContribution = 0;
1044
1045        while (mGvsStats.mTotalSamples < mTotalSamples)
1046        {
[2048]1047                mRayCaster->InitPass();
[2691]1048
[1990]1049                // Ray queue empty =>
1050                // cast a number of uniform samples to fill ray queue
[2691]1051                int newSamples = CastInitialSamples(mInitialSamples);
[1990]1052
1053                if (!mOnlyRandomSampling)
1054                        newSamples += ProcessQueue();
1055
1056                passSamples += newSamples;
1057                mGvsStats.mTotalSamples += newSamples;
1058
[2048]1059                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
[1990]1060                {
1061                        ++ mPass;
1062
1063                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1064
1065                        ////////
1066                        //-- stats
1067
1068                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1069                        mGvsStats.mPass = mPass;
1070                        mGvsStats.Stop();
1071                        mGvsStats.Print(mGvsStatsStream);
1072
1073                        // reset
1074                        oldContribution = mGvsStats.mTotalContribution;
1075                        mGvsStats.mPassContribution = 0;
1076                        passSamples = 0;
1077
1078                        if (GVS_DEBUG)
1079                                VisualizeViewCells();
1080                }
1081        }
1082}
1083
1084
[1489]1085bool GvsPreprocessor::ComputeVisibility()
[1460]1086{
[1533]1087        cout << "Gvs Preprocessor started\n" << flush;
[1545]1088        const long startTime = GetTime();
[1533]1089
[1990]1090        //Randomize(0);
[1934]1091        mGvsStats.Reset();
1092        mGvsStats.Start();
[1545]1093
[1486]1094        if (!mLoadViewCells)
[1563]1095        {       
1096                /// construct the view cells from the scratch
1097                ConstructViewCells();
[1580]1098                // reset pvs already gathered during view cells construction
1099                mViewCellsManager->ResetPvs();
[1563]1100                cout << "finished view cell construction" << endl;
[1486]1101        }
[1460]1102
[1982]1103        if (mPerViewCell)
[1473]1104        {
[2648]1105#if 1
[2597]1106                // provide list of view cells to compute
[1996]1107                CompileViewCellsList();
[2686]1108
[2597]1109                // start per view cell gvs
[2048]1110                PerViewCellComputation();
[2625]1111#else
1112                PerViewCellComputation2();
1113
1114#endif
[1460]1115        }
[1982]1116        else
1117        {
1118                GlobalComputation();
1119        }
[1460]1120
[2687]1121        cout << "cast " << mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M single rays/s" << endl;
[1545]1122
[1934]1123        if (GVS_DEBUG)
1124        {
1125                Visualize();
1126                CLEAR_CONTAINER(mVssRays);
1127        }
[2048]1128       
1129        // export the preprocessed information to a file
1130        if (0 && mExportVisibility)
1131        {
1132                ExportPreprocessedData(mVisibilityFileName);
1133        }
[2648]1134       
1135        // compute the pixel error of this visibility solution
1136        if (mEvaluatePixelError)
1137        {
1138                ComputeRenderError();
1139        }
[1934]1140
[1473]1141        return true;
[1460]1142}
1143
[1522]1144
[2048]1145void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1146{
[2187]1147        // store triangle directly
[2048]1148        mViewCellsManager->DeterminePvsObjects(rays, true);
1149}
1150
1151
[1522]1152void GvsPreprocessor::Visualize()
1153{
1154        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1155
1156        if (!exporter)
1157                return;
1158       
1159        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
[1999]1160       
[1522]1161        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1162        {
[1524]1163                exporter->SetWireframe();
[1522]1164                exporter->ExportPolygon((*vit).enlargedTriangle);
1165                //Material m;
[1524]1166                exporter->SetFilled();
1167                Polygon3 poly = Polygon3((*vit).originalTriangle);
1168                exporter->ExportPolygon(&poly);
[1522]1169        }
1170
[1933]1171        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
[1999]1172
[1933]1173        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1174        {
1175                Intersectable *obj = (*rit)->mTerminationObject;
1176                exporter->ExportIntersectable(obj);
1177        }
1178
[1990]1179        ExportVssRays(exporter, mVssRays);
1180       
[1522]1181        delete exporter;
[1460]1182}
[1522]1183
[1934]1184
1185void GvsStatistics::Print(ostream &app) const
1186{
[2003]1187        app << "#ViewCells\n" << mViewCells << endl;
[2648]1188        app << "#Id\n" << mViewCellId << endl;
1189        app << "#Time\n" << mTimePerViewCell << endl;;
[2690]1190        app << "#TriPvs\n" << mTrianglePvs << endl;
[2648]1191        app << "#ObjectPvs\n" << mPerViewCellPvs << endl;
[2687]1192        app << "#UpdatedPvs\n" << (int)mPvsCost << endl;
[2003]1193
[2677]1194        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1195        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1196       
[2003]1197        app << "#TotalPvs\n" << mTotalPvs << endl;
[2648]1198        app << "#TotalTime\n" << mTotalTime << endl;
[1934]1199        app << "#TotalSamples\n" << mTotalSamples << endl;
[2677]1200
[2717]1201        app << "#AvgPvs: " << mPvsCost / mViewCells << endl;
[2648]1202        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1203       
[2677]1204        if (0)
1205        {
1206                app << "#ReverseSamples\n" << mReverseSamples << endl;
1207                app << "#BorderSamples\n" << mBorderSamples << endl;
[2648]1208
[2677]1209                app << "#Pass\n" << mPass << endl;
1210                app << "#ScDiff\n" << mPassContribution << endl;
[2695]1211                app << "#GvsRuns\n" << mGvsRuns << endl;       
[2003]1212
[2677]1213                app     << "#SamplesContri\n" << mTotalContribution << endl;
1214        }
[2003]1215
1216        app << endl;
[1883]1217}
[1934]1218
1219
[2690]1220void GvsPreprocessor::ComputeViewCell()
[2625]1221{
[2696]1222        //if (mCurrentViewCell->GetId() != 499) return;
[2695]1223
1224        // clean up
1225        mTrianglePvs.clear();
1226
[2691]1227        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
1228
[2643]1229        KdNode::NewMail();
[2625]1230
[2670]1231        const long startTime = GetTime();
1232
[2625]1233        cout << "\n***********************\n"
[2643]1234                << "computing view cell " << mProcessedViewCells
[2625]1235                << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
[2691]1236        cout << "bb: " << mCurrentViewCell->GetBox() << endl;
[2625]1237
[2690]1238        mGvsStats.mPerViewCellSamples = 0;
1239
[2695]1240        int oldContribution = 0;
[2690]1241        int passSamples = 0;
[2695]1242       
[2691]1243        for (int i = 0; i < 0; ++ i)
1244                mGenericStats[i] = 0;
[2690]1245
1246        while (1)
1247        {
[2691]1248                int oldPvsSize = mCurrentViewCell->GetPvs().GetSize();
[2695]1249               
[2690]1250                mRayCaster->InitPass();
1251
1252                // Ray queue empty =>
1253                // cast a number of uniform samples to fill ray queue
[2691]1254                int newSamples = CastInitialSamples(mInitialSamples);
[2690]1255
1256                if (!mOnlyRandomSampling)
1257                {
1258                        int samplesPerRun = ProcessQueue();
1259                        newSamples += samplesPerRun;
1260                        //if (samplesPerRun > 0) cout << "spr: " << samplesPerRun << " ";
1261                }
1262
1263                passSamples += newSamples;
1264        mGvsStats.mPerViewCellSamples += newSamples;
1265
1266                if (passSamples >= mGvsSamplesPerPass)
1267                {
1268                        if (GVS_DEBUG) VisualizeViewCell(mTrianglePvs);
1269
[2691]1270                        //const bool convertPerPass = true;
[2690]1271                        const bool convertPerPass = false;
1272
1273                        if (convertPerPass)
1274                        {       
1275                                int newObjects = ConvertObjectPvs();
1276
1277                                cout << "added " << newObjects << " triangles to triangle pvs" << endl;
1278                                mGvsStats.mTotalContribution += newObjects;
1279                        }
1280
1281                        ++ mPass;
1282                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1283
1284
1285                        ////////
1286                        //-- stats
1287
1288                        mGvsStats.mPass = mPass;
1289
1290                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
1291                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
1292                        cout << "obj contri=" << mCurrentViewCell->GetPvs().GetSize() - oldPvsSize << " (of " << mMinContribution << ")" << endl;
1293
1294                        // termination criterium
1295                        if (mGvsStats.mPassContribution < mMinContribution)
1296                                break;
1297
[2695]1298                        // reset stats
[2690]1299                        oldContribution = mGvsStats.mTotalContribution;
1300                        mGvsStats.mPassContribution = 0;
1301                        passSamples = 0;
1302                }
1303        }
[2677]1304       
[2691]1305        // at last compute objects that directly intersect view cell
[2705]1306        ComputeViewCellGeometryIntersection();
[2690]1307
1308               
[2677]1309        ////////
1310        //-- stats
[2625]1311
[2690]1312        // timing
1313        mGvsStats.mTimePerViewCell = TimeDiff(startTime, GetTime()) * 1e-3f;
1314
1315        ComputeStats();
1316}
1317
1318
1319void GvsPreprocessor::ComputeStats()
1320{
[2677]1321        // compute pvs size using larger (bvh objects)
1322        // note: for kd pvs we had to do this during gvs computation
1323
[2625]1324        if (!mUseKdPvs)
1325        {
1326                ObjectContainer objectPvs;
1327
1328                // optain object pvs
1329                GetObjectPvs(objectPvs);
1330
1331                // add pvs
1332                ObjectContainer::const_iterator it, it_end = objectPvs.end();
1333
1334                for (it = objectPvs.begin(); it != it_end; ++ it)
1335                {
1336                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1337                }
1338
1339                cout << "triangle pvs of " << (int)mTrianglePvs.size()
1340                        << " was converted to object pvs of " << (int)objectPvs.size() << endl;
1341
1342                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
[2677]1343                mGvsStats.mPvsCost = 0; // todo objectPvs.EvalPvsCost();
[2625]1344        }
[2691]1345        else if (0)
[2625]1346        {
[2691]1347                //KdNode::NewMail();
1348
1349                // compute pvs kd nodes that intersect view cell
1350                ObjectContainer mykdobjects;
1351
1352                // extract kd pvs
1353                ObjectContainer::const_iterator it, it_end = mTrianglePvs.end();
1354
1355                for (it = mTrianglePvs.begin(); it != it_end; ++ it)
1356                {
1357                        Intersectable *obj = *it;
1358                        // find intersecting objects not yet in pvs (i.e., only unmailed)
1359                        mKdTree->CollectKdObjects(obj->GetBox(), mykdobjects);
1360                }
1361
1362                // add pvs
1363                it_end = mykdobjects.end();
1364
1365                for (it = mykdobjects.begin(); it != it_end; ++ it)
1366                {
1367                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1368                }
1369
1370                cout << "added " << (int)mykdobjects.size() << " new objects " << endl;
1371
[2643]1372                mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
[2648]1373                mGvsStats.mPvsCost = mCurrentViewCell->GetPvs().EvalPvsCost();
[2643]1374
[2625]1375        }
1376
[2677]1377        mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
[2625]1378
1379
[2677]1380        ////////////////
1381        // global values
1382
[2690]1383        mGvsStats.mViewCells = mProcessedViewCells;
[2677]1384        mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
1385        mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
1386    mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
[2625]1387        mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
1388
1389        mGvsStats.Stop();
1390        mGvsStats.Print(mGvsStatsStream);
1391
[2677]1392        cout << "id: " << mCurrentViewCell->GetId() << " pvs cost: "
[2690]1393             << mGvsStats.mPvsCost << " pvs tri: " << mTrianglePvs.size() << endl;
1394}
[2677]1395
1396
[2690]1397ObjectContainer triangles;
1398
1399int GvsPreprocessor::ConvertObjectPvs()
1400{
1401        int newObjects = 0;
1402
1403        ObjectPvsIterator pit = mCurrentViewCell->GetPvs().GetIterator();
1404
1405        triangles.clear();
1406
1407        // output PVS of view cell
1408        while (pit.HasMoreEntries())
1409        {               
1410                KdIntersectable *kdInt = static_cast<KdIntersectable *>(pit.Next());
1411
1412                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), triangles);
1413
1414                ObjectContainer::const_iterator oit, oit_end = triangles.end();
1415
1416                for (oit = triangles.begin(); oit != oit_end; ++ oit)
1417                {
1418                        if (AddTriangleObject(*oit))
1419                                ++ newObjects;
1420                }
1421        }
1422
1423        return newObjects;
[1934]1424}
[2625]1425
[2690]1426
1427bool GvsPreprocessor::AddTriangleObject(Intersectable *triObj)
1428{
1429        if ((triObj->mCounter < ACCOUNTED_OBJECT))
1430        {
1431                triObj->mCounter += ACCOUNTED_OBJECT;
1432
1433                mTrianglePvs.push_back(triObj);
[2695]1434                //mDummyBuffer.push_back(mGvsStats.mGvsRuns);
[2691]1435                mGenericStats[0] = (int)mTrianglePvs.size();
[2690]1436                return true;
1437        }
1438
1439        return false;
[2625]1440}
[2690]1441
[2691]1442
1443
[2690]1444}
Note: See TracBrowser for help on using the repository browser.