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

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