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

Revision 1928, 14.2 KB checked in by mattausch, 18 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
4#include "VssRay.h"
5#include "ViewCellsManager.h"
6#include "Triangle3.h"
7#include "IntersectableWrapper.h"
8#include "Plane3.h"
9#include "RayCaster.h"
10#include "Exporter.h"
11#include "SamplingStrategy.h"
12
13
14namespace GtpVisibilityPreprocessor
15{
16 
17struct VizStruct
18{
19        Polygon3 *enlargedTriangle;
20        Triangle3 originalTriangle;
21        VssRay *ray;
22};
23
24static vector<VizStruct> vizContainer;
25
26GvsPreprocessor::GvsPreprocessor():
27Preprocessor(),
28//mSamplingType(SamplingStrategy::DIRECTION_BASED_DISTRIBUTION),
29mSamplingType(SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION),
30mSampleContriPerPass(0),
31mTotalSampleContri(0),
32mReverseSamples(0),
33mBorderSamples(0)
34{
35        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
36        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
37        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
38        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
39        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
40
41        Debug << "Gvs preprocessor options" << endl;
42        Debug << "number of total samples: " << mTotalSamples << endl;
43        Debug << "number of initial samples: " << mInitialSamples << endl;
44        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
45        Debug << "threshold: " << mThreshold << endl;
46        Debug << "eps: " << mEps << endl;
47
48        mStats.open("gvspreprocessor.log");
49}
50
51
52bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
53                                                                                 const Triangle3 &hitTriangle,
54                                                                                 const VssRay &oldRay)
55{
56        const float dist = Magnitude(oldRay.GetDir());
57        const float newDist = Magnitude(currentRay.GetDir());
58 
59#if 0
60        if ((dist - newDist) > mThresHold)
61#else
62        // rather take relative distance
63        if ((dist / newDist) > mThreshold)
64#endif
65        {
66                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
67                // set flag for visualization
68                newRay->mFlags |= VssRay::ReverseSample;
69               
70                // ray is not pushed into the queue => can delete ray
71                if (!HandleRay(newRay))
72                        delete newRay;
73               
74                return true;
75        }
76
77        return false;
78}
79
80
81bool GvsPreprocessor::HandleRay(VssRay *vssRay)
82{
83        const bool storeRaysForViz = true;
84        mViewCellsManager->ComputeSampleContribution(*vssRay, true, storeRaysForViz);
85               
86        // some pvs contribution for this ray?
87        if (vssRay->mPvsContribution > 0)
88        {
89                // add new ray to ray queue
90                mRayQueue.push(vssRay);
91
92                if (storeRaysForViz)
93                {
94                        ViewCellContainer::const_iterator vit, vit_end = vssRay->mViewCells.end();
95                        for (vit = vssRay->mViewCells.begin(); vit != vit_end; ++ vit)
96                        {
97                                VssRay *nray = new VssRay(*vssRay);
98                                (*vit)->GetOrCreateRays()->push_back(nray);                             
99                        }
100                }
101                //mVssRays.push_back(new VssRay(*vssRay));
102        ++ mSampleContriPerPass;
103
104                return true;
105        }
106
107        return false;
108}
109
110
111/** Creates 3 new vertices for triangle vertex with specified index.
112*/
113static void CreateNewVertices(VertexContainer &vertices,
114                                                          const Triangle3 &hitTriangle,
115                                                          const VssRay &ray,
116                                                          const int index,
117                                                          const float eps)
118{
119        const int indexU = (index + 1) % 3;
120        const int indexL = (index == 0) ? 2 : index - 1;
121
122        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
123        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
124        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
125       
126        const float len = Magnitude(a);
127
128        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
129        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
130        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
131                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
132
133        // compute the new three hit points
134        // pi, i + 1:  pi+ e·|pi-xp|·di, j
135        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
136        // pi, i - 1:  pi+ e·|pi-xp|·di, j
137    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
138        // pi, i:  pi+ e·|pi-xp|·di, j
139        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
140       
141        vertices.push_back(pt2);
142        vertices.push_back(pt3);
143        vertices.push_back(pt1);
144}
145
146
147void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
148                                                                          const Triangle3 &hitTriangle,
149                                                                          const VssRay &ray)
150{
151        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
152        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
153        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
154}
155
156
157static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
158                                                                         const Triangle3 &hitTriangle,
159                                                                         const VssRay &oldRay)
160{
161        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
162
163        const Vector3 hitPt =
164                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
165       
166        return hitPt;
167}
168
169
170static bool EqualVisibility(const VssRay &a, const VssRay &b)
171{
172        return a.mTerminationObject == b.mTerminationObject;
173}
174
175
176int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
177                                                                   const Vector3 &p1,
178                                                                   const Vector3 &p2,
179                                                                   const VssRay &x,
180                                                                   const VssRay &y,
181                                                                   const VssRay &oldRay)
182{
183        // the predicted hitpoint expects to hit the same mesh again
184        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
185        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
186
187        CheckDiscontinuity(x, hitTriangle, oldRay);
188        CheckDiscontinuity(y, hitTriangle, oldRay);
189
190        if (EqualVisibility(x, y))
191        {
192                return 0;
193        }
194        else
195        {
196                cout << "s";
197                const Vector3 p = (p1 + p2) * 0.5f;
198                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
199       
200                // cast ray into the new subdivision point
201                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
202               
203                if (!newRay) return 0;
204
205                newRay->mFlags |= VssRay::BorderSample;
206
207                // add new ray to queue
208                const bool enqueued = HandleRay(newRay);
209               
210                // subdivide further
211                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
212                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
213                               
214                if (!enqueued)
215                        delete newRay;
216               
217                return s1 + s2 + 1;
218        }
219}
220
221
222int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
223{
224        cout << "a";
225        Intersectable *tObj = currentRay.mTerminationObject;
226        Triangle3 hitTriangle;
227
228        // other types not implemented yet
229        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
230        {
231                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
232        }
233        else
234        {
235                cout << "not yet implemented" << endl;
236        }
237
238        VertexContainer enlargedTriangle;
239       
240        /// create 3 new hit points for each vertex
241        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
242       
243        /// create rays from sample points and handle them
244        SimpleRayContainer simpleRays;
245        simpleRays.reserve(9);
246
247        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
248
249        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
250        {
251                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
252                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
253                simpleRays.AddRay(sr);
254        }
255
256        // visualize enlarged triangles
257        if (0)
258        {
259                VizStruct dummy;
260                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
261                dummy.originalTriangle = hitTriangle;
262                //dummy.ray = new VssRay(currentRay);
263                vizContainer.push_back(dummy);
264        }
265
266        // cast rays to triangle vertices and determine visibility
267        VssRayContainer vssRays;
268        CastRays(simpleRays, vssRays, false, false);
269
270        // set flags
271        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
272        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
273        {
274                (*rit)->mFlags |= VssRay::BorderSample;
275        }
276
277        // add to ray queue
278        EnqueueRays(vssRays);
279       
280        const int n = (int)enlargedTriangle.size();
281        int castRays = (int)vssRays.size();
282
283    // recursivly subdivide each edge
284        for (int i = 0; 1 && (i < n); ++ i)
285        {
286                castRays += SubdivideEdge(
287                        hitTriangle,
288                        enlargedTriangle[i],
289                        enlargedTriangle[(i + 1) % n],
290                        *vssRays[i],
291                        *vssRays[(i + 1) % n],
292                        currentRay);
293        }
294
295        mBorderSamples += castRays;
296        return castRays;
297}
298
299
300static Vector3 GetPassingPoint(const VssRay &currentRay,
301                                                           const Triangle3 &hitTriangle,
302                                                           const VssRay &oldRay)
303{
304        // intersect triangle plane with plane spanned by current samples
305        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
306        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
307
308        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
309
310        // Evaluate new hitpoint just outside the triangle
311        const float factor = 0.95f;
312        float t = triPlane.FindT(intersectLine);
313        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
314
315        return newPoint;
316}
317
318
319VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
320                                                                                 const Triangle3 &hitTriangle,
321                                                                                 const VssRay &oldRay)
322{
323        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
324        //-- with the newly found triangle (xold is the previous ray from
325        //-- which x was generated). On the intersecting line, we select a point
326        //-- pnew which lies just outside of the new triangle so the ray
327        //-- just passes by inside the gap
328    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
329        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
330
331        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
332        //-- as direction vector
333        const Vector3 newDir = predicted - newPoint ;
334        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
335        // difficult to say!!
336        const Vector3 newOrigin = newDir * -5000.0f;
337
338        ++ mReverseSamples;
339
340        return new VssRay(currentRay);
341}
342
343
344int GvsPreprocessor::CastInitialSamples(const int numSamples,
345                                                                                const int sampleType)
346{       
347        const long startTime = GetTime();
348
349        // generate simple rays
350        SimpleRayContainer simpleRays;
351        GenerateRays(numSamples, sampleType, simpleRays);
352
353        // generate vss rays
354        VssRayContainer samples;
355        CastRays(simpleRays, samples, true);
356        // add to ray queue
357        EnqueueRays(samples);
358
359        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
360        return (int)samples.size();
361}
362
363
364void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
365{
366        // add samples to ray queue
367        VssRayContainer::const_iterator vit, vit_end = samples.end();
368        for (vit = samples.begin(); vit != vit_end; ++ vit)
369        {
370                HandleRay(*vit);
371        }
372}
373
374
375int GvsPreprocessor::Pass()
376{
377        // reset samples
378        int castSamples = 0;
379        mSampleContriPerPass = 0;
380
381        while (castSamples < mSamplesPerPass)
382        {       
383                // Ray queue empty =>
384                // cast a number of uniform samples to fill ray queue
385                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
386                castSamples += ProcessQueue();
387                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
388        }
389
390        mTotalSampleContri += mSampleContriPerPass;
391        return castSamples;
392}
393
394
395int GvsPreprocessor::ProcessQueue()
396{
397        int castSamples = 0;
398        ++ mGvsPass;
399
400        while (!mRayQueue.empty())
401        {
402                // handle next ray
403                VssRay *ray = mRayQueue.top();
404                mRayQueue.pop();
405
406                castSamples += AdaptiveBorderSampling(*ray);
407                delete ray;
408        }
409       
410        return castSamples;
411}
412
413
414bool GvsPreprocessor::ComputeVisibility()
415{
416        cout << "Gvs Preprocessor started\n" << flush;
417        const long startTime = GetTime();
418
419        Randomize(0);
420       
421        mPass = 0;
422        mGvsPass = 0;
423        mSampleContriPerPass = 0;
424        mTotalSampleContri = 0;
425        mReverseSamples = 0;
426        mBorderSamples = 0;
427
428        int castSamples = 0;
429
430        if (!mLoadViewCells)
431        {       
432                /// construct the view cells from the scratch
433                ConstructViewCells();
434                // reset pvs already gathered during view cells construction
435                mViewCellsManager->ResetPvs();
436                cout << "finished view cell construction" << endl;
437        }
438        else if (0)
439        {       
440                //-- load view cells from file
441                //-- test successful view cells loading by exporting them again
442                VssRayContainer dummies;
443                mViewCellsManager->Visualize(mObjects, dummies);
444                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
445        }
446
447        while (castSamples < mTotalSamples)
448        {
449                castSamples += Pass();
450                               
451                ////////
452                //-- stats
453                cout << "\nPass " << mPass << " #samples: " << castSamples << " of " << mTotalSamples << endl;
454
455                //mVssRays.PrintStatistics(mStats);
456                mStats
457                        << "#Pass\n" << mPass << endl
458                        << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
459                        << "#TotalSamples\n" << castSamples << endl
460                        << "#ScDiff\n" << mSampleContriPerPass << endl
461                        << "#SamplesContri\n" << mTotalSampleContri << endl
462                        << "#ReverseSamples\n" << mReverseSamples << endl
463                        << "#BorderSamples\n" << mBorderSamples << endl                 
464                        << "#GvsRuns\n" << mGvsPass << endl;
465
466                mViewCellsManager->PrintPvsStatistics(mStats);
467
468                char str[64]; sprintf(str, "tmp/pass%04d-", mPass);
469               
470        // visualization
471                if (mSampleContriPerPass > 0)
472                {
473                        const bool exportRays = true;
474                        const bool exportPvs = true;
475
476                        mViewCellsManager->ExportSingleViewCells(mObjects, 10, false, exportPvs, exportRays, 1000, str);
477                }
478
479                // remove pass samples
480                ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
481                for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
482                {
483                        (*vit)->DelRayRefs();
484                }
485
486                //CLEAR_CONTAINER(mVssRays);
487                // ComputeRenderError();
488                ++ mPass;
489        }
490
491        cout << 2 * castSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
492        Visualize();
493
494        return true;
495}
496
497
498void GvsPreprocessor::Visualize()
499{
500        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
501
502        if (!exporter)
503                return;
504       
505        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
506        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
507        {
508                exporter->SetWireframe();
509                exporter->ExportPolygon((*vit).enlargedTriangle);
510                //Material m;
511                exporter->SetFilled();
512                Polygon3 poly = Polygon3((*vit).originalTriangle);
513                exporter->ExportPolygon(&poly);
514        }
515
516        exporter->ExportRays(mVssRays);
517        delete exporter;
518}
519
520}
Note: See TracBrowser for help on using the repository browser.