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

Revision 1563, 12.9 KB checked in by mattausch, 18 years ago (diff)

fixed bug with view space box

  • 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                if (!HandleRay(newRay))
68                {
69                        delete newRay;
70                }
71                return true;
72        }
73
74        return false;
75}
76
77
78bool GvsPreprocessor::HandleRay(VssRay *vssRay)
79{
80        mViewCellsManager->ComputeSampleContribution(*vssRay, true, false);
81               
82        // some pvs contribution for this ray?
83        if (vssRay->mPvsContribution > 0)
84        {
85                //cout << " h " << mSampleContriPerPass << " " << mSamplesPerPass << " " << mTotalSamples << endl;
86                mRayQueue.push(vssRay);
87                //mVssRays.push_back(new VssRay(*vssRay));
88        ++ mSampleContriPerPass;
89
90                return true;
91        }
92
93        return false;
94}
95
96
97/** Creates 3 new vertices for triangle vertex with specified index.
98*/
99static void CreateNewVertices(VertexContainer &vertices,
100                                                          const Triangle3 &hitTriangle,
101                                                          const VssRay &ray,
102                                                          const int index,
103                                                          const float eps)
104{
105        const int indexU = (index + 1) % 3;
106        const int indexL = (index == 0) ? 2 : index - 1;
107
108        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
109        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
110        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
111       
112        const float len = Magnitude(a);
113
114        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
115        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
116        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
117                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
118
119        // compute the new three hit points
120        // pi, i + 1:  pi+ e·|pi-xp|·di, j
121        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
122        // pi, i - 1:  pi+ e·|pi-xp|·di, j
123    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
124        // pi, i:  pi+ e·|pi-xp|·di, j
125        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
126       
127        vertices.push_back(pt2);
128        vertices.push_back(pt3);
129        vertices.push_back(pt1);
130}
131
132
133void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
134                                                                          const Triangle3 &hitTriangle,
135                                                                          const VssRay &ray)
136{
137        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
138        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
139        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
140}
141
142
143static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
144                                                                         const Triangle3 &hitTriangle,
145                                                                         const VssRay &oldRay)
146{
147        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
148
149        const Vector3 hitPt =
150                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
151       
152        return hitPt;
153}
154
155
156static bool EqualVisibility(const VssRay &a, const VssRay &b)
157{
158        return a.mTerminationObject == b.mTerminationObject;
159}
160
161
162int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
163                                                                   const Vector3 &p1,
164                                                                   const Vector3 &p2,
165                                                                   const VssRay &x,
166                                                                   const VssRay &y,
167                                                                   const VssRay &oldRay)
168{
169        // the predicted hitpoint expects to hit the same mesh again
170        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
171        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
172
173        CheckDiscontinuity(x, hitTriangle, oldRay);
174        CheckDiscontinuity(y, hitTriangle, oldRay);
175
176        if (EqualVisibility(x, y))
177        {
178                return 0;
179        }
180        else
181        {
182                cout << "s";
183                const Vector3 p = (p1 + p2) * 0.5f;
184                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
185       
186                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
187                //cout << "\np1: " << p1 << "\np : " <<  p << "\np2: " << p2 << endl;
188                if (!newRay) return 0;
189
190                const bool enqueued = HandleRay(newRay);
191               
192                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
193                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
194                               
195                if (!enqueued)
196                        delete newRay;
197               
198                return s1 + s2 + 1;
199        }
200}
201
202
203int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
204{
205        cout << "a";
206        Intersectable *tObj = currentRay.mTerminationObject;
207        Triangle3 hitTriangle;
208
209        // other types not implemented yet
210        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
211        {
212                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
213        }
214        else
215        {
216                cout << "not yet implemented" << endl;
217        }
218
219        VertexContainer enlargedTriangle;
220       
221        /// create 3 new hit points for each vertex
222        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
223       
224        /// create rays from sample points and handle them
225        SimpleRayContainer simpleRays;
226        simpleRays.reserve(9);
227
228        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
229
230        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
231        {
232                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
233                SimpleRay sr(currentRay.GetOrigin(), rayDir);
234                simpleRays.AddRay(sr);
235        }
236#if 0
237        VizStruct dummy;
238        dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
239        dummy.originalTriangle = hitTriangle;
240        //dummy.ray = new VssRay(currentRay);
241        vizContainer.push_back(dummy);
242#endif
243
244        // cast rays to triangle vertices and determine visibility
245        VssRayContainer vssRays;
246        CastRays(simpleRays, vssRays, false, false);
247
248        // add to ray queue
249        EnqueueRays(vssRays);
250       
251        const int n = (int)enlargedTriangle.size();
252        int castRays = (int)vssRays.size();
253#if 1
254    // recursivly subdivide each edge
255        for (int i = 0; i < n; ++ i)
256        {
257                castRays += SubdivideEdge(
258                        hitTriangle,
259                        enlargedTriangle[i],
260                        enlargedTriangle[(i + 1) % n],
261                        *vssRays[i],
262                        *vssRays[(i + 1) % n],
263                        currentRay);
264        }
265#endif
266
267        mBorderSamples += castRays;
268        return castRays;
269}
270
271
272static Vector3 GetPassingPoint(const VssRay &currentRay,
273                                                           const Triangle3 &hitTriangle,
274                                                           const VssRay &oldRay)
275{
276        // intersect triangle plane with plane spanned by current samples
277        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
278        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
279
280        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
281
282        // Evaluate new hitpoint just outside the triangle
283        const float factor = 0.95f;
284        float t = triPlane.FindT(intersectLine);
285        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
286
287        return newPoint;
288}
289
290
291VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
292                                                                                 const Triangle3 &hitTriangle,
293                                                                                 const VssRay &oldRay)
294{
295        ++ mReverseSamples;
296
297        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
298        //-- with the newly found triangle (xold is the previous ray from
299        //-- which x was generated). On the intersecting line, we select a point
300        //-- pnew which lies just outside of the new triangle so the ray
301        //-- just passes by inside the gap
302    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
303        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
304
305        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
306        //-- as direction vector
307        const Vector3 newDir = predicted - newPoint ;
308        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
309        // difficult to say!!
310        const Vector3 newOrigin = newDir * -5000.0f;
311
312        return new VssRay(currentRay);
313}
314
315
316int GvsPreprocessor::CastInitialSamples(const int numSamples,
317                                                                                const int sampleType)
318{       
319        const long startTime = GetTime();
320
321        // generate simple rays
322        SimpleRayContainer simpleRays;
323        GenerateRays(numSamples, sampleType, simpleRays);
324
325        // generate vss rays
326        VssRayContainer samples;
327        CastRays(simpleRays, samples, true);
328        // add to ray queue
329        EnqueueRays(samples);
330
331        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
332
333        return (int)samples.size();
334}
335
336
337void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
338{
339        // add samples to ray queue
340        VssRayContainer::const_iterator vit, vit_end = samples.end();
341       
342        for (vit = samples.begin(); vit != vit_end; ++ vit)
343        {
344                HandleRay(*vit);
345        }
346}
347
348
349int GvsPreprocessor::Pass()
350{
351        // reset samples
352        int castSamples = 0;
353        mSampleContriPerPass = 0;
354
355        while (castSamples < mSamplesPerPass)
356        {       
357                // Ray queue empty =>
358                // cast a number of uniform samples to fill ray queue
359                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
360                castSamples += ProcessQueue();
361                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
362        }
363
364        mTotalSampleContri += mSampleContriPerPass;
365
366        return castSamples;
367}
368
369
370int GvsPreprocessor::ProcessQueue()
371{
372        int castSamples = 0;
373        ++ mGvsPass;
374
375        while (!mRayQueue.empty())
376        {
377                // handle next ray
378                VssRay *ray = mRayQueue.top();
379                mRayQueue.pop();
380
381                castSamples += AdaptiveBorderSampling(*ray);
382                delete ray;
383        }
384       
385        return castSamples;
386}
387
388
389bool GvsPreprocessor::ComputeVisibility()
390{
391        cout << "Gvs Preprocessor started\n" << flush;
392        const long startTime = GetTime();
393
394        Randomize(0);
395       
396        mPass = 0;
397        mGvsPass = 0;
398        mSampleContriPerPass = 0;
399        mTotalSampleContri = 0;
400        mReverseSamples = 0;
401        mBorderSamples = 0;
402
403        int castSamples = 0;
404
405        if (!mLoadViewCells)
406        {       
407                /// construct the view cells from the scratch
408                ConstructViewCells();
409                cout << "finished view cell construction" << endl;
410        }
411        else if (1)
412        {       
413                //-- load view cells from file
414                //-- test successful view cells loading by exporting them again
415                VssRayContainer dummies;
416                mViewCellsManager->Visualize(mObjects, dummies);
417                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
418        }
419
420        while (castSamples < mTotalSamples)
421        {
422                castSamples += Pass();
423                               
424                ////////
425                //-- stats
426                cout << "\nPass " << mPass << " #samples: " << castSamples << " of " << mTotalSamples << endl;
427
428                //mVssRays.PrintStatistics(mStats);
429                mStats
430                        << "#Pass\n" << mPass << endl
431                        << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
432                        << "#TotalSamples\n" << castSamples << endl
433                        << "#ScDiff\n" << mSampleContriPerPass << endl
434                        << "#SamplesContri\n" << mTotalSampleContri << endl
435                        << "#ReverseSamples\n" << mReverseSamples << endl
436                        << "#BorderSamples\n" << mBorderSamples << endl                 
437                        << "#GvsRuns\n" << mGvsPass << endl;
438
439
440                mViewCellsManager->PrintPvsStatistics(mStats);
441                // ComputeRenderError();
442                ++ mPass;
443        }
444
445        cout << 2 * castSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
446        Visualize();
447
448        return true;
449}
450
451
452void GvsPreprocessor::Visualize()
453{
454        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
455
456        if (!exporter)
457                return;
458       
459        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
460        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
461        {
462                exporter->SetWireframe();
463                exporter->ExportPolygon((*vit).enlargedTriangle);
464                //Material m;
465                exporter->SetFilled();
466                Polygon3 poly = Polygon3((*vit).originalTriangle);
467                exporter->ExportPolygon(&poly);
468        }
469
470        exporter->ExportRays(mVssRays);
471        delete exporter;
472}
473
474}
Note: See TracBrowser for help on using the repository browser.