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

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