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

Revision 2686, 33.4 KB checked in by mattausch, 16 years ago (diff)

fixed several problems

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