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

Revision 2667, 33.3 KB checked in by bittner, 16 years ago (diff)

merge on nemo

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