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

Revision 2615, 32.1 KB checked in by mattausch, 16 years ago (diff)

did some stuff for the visualization

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