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

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