source: GTP/trunk/Lib/Vis/Preprocessing/src/GlobalLinesRenderer.cpp @ 1990

Revision 1990, 26.4 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include "glInterface.h"
2#include "GlobalLinesRenderer.h"
3#include "common.h"
4#include "RenderTexture.h"
5#include "Preprocessor.h"
6#include "GlRenderer.h"
7#include "Exporter.h"
8#include "ViewCellsManager.h"
9#include "SamplingStrategy.h"
10
11// the devil library
12#include <IL/il.h>
13#include <IL/ilu.h>
14#include <IL/ilut.h>
15
16#ifdef USE_CG
17
18#include <Cg/cg.h>
19#include <Cg/cgGL.h>
20
21
22namespace GtpVisibilityPreprocessor {
23
24
25static CGcontext sCgContext = NULL;
26static CGprogram sCgDepthPeelingProgram = NULL;
27static CGprogram sCgPassThroughProgram = NULL;
28
29static CGprofile sCgFragmentProfile;
30static CGparameter sTextureParam;
31static CGparameter sTexWidthParam;
32static CGparameter sStepSizeParam;
33
34GlobalLinesRenderer *globalLinesRenderer = NULL;
35
36static bool isDepth = true;
37
38static void InitDevIl()
39{
40        ilInit();
41        ILuint ImageName;
42        ilGenImages(1, &ImageName);
43        ilBindImage(ImageName);
44        ilEnable(IL_FILE_OVERWRITE);
45
46        //  ilRegisterFormat(IL_RGBA);
47        //  ilRegisterType(IL_FLOAT);
48
49        //  ilEnable(IL_ORIGIN_SET);
50        //  ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
51}
52
53
54static void cgErrorCallback()
55{
56        CGerror lastError = cgGetError();
57
58        if(lastError)
59        {
60                printf("%s\n\n", cgGetErrorString(lastError));
61                printf("%s\n", cgGetLastListing(sCgContext));
62                printf("Cg error, exiting...\n");
63
64                exit(0);
65        }
66}
67
68static void PrintGLerror(char *msg)
69{
70        GLenum errCode;
71        const GLubyte *errStr;
72       
73        if ((errCode = glGetError()) != GL_NO_ERROR)
74        {
75                errStr = gluErrorString(errCode);
76                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
77        }
78}
79
80
81void Reshape(int w, int h)
82{
83        if (h == 0) h = 1;
84
85        glViewport(0, 0, w, h);
86
87        glMatrixMode(GL_PROJECTION);
88        glLoadIdentity();
89
90        //gluPerspective(60.0, (GLfloat)w/(GLfloat)h, 3, 5000.0);
91        //gluPerspective(60.0, (GLfloat)w/(GLfloat)h, 0.5, 10.0);
92        glOrtho(-1, 1, -1, 1, 0.5, 15);
93}
94
95
96void SetFrustum(const int sizeX, const int sizeY,
97                                const float nearPlane, const float farPlane)
98{
99        glMatrixMode(GL_PROJECTION);
100        glLoadIdentity();
101
102        glOrtho(-sizeX * 0.5, sizeX * 0.5,
103                        -sizeY * 0.5, sizeY * 0.5,
104                        nearPlane, farPlane);
105
106        /*glOrtho(0, sizeX,
107                    0, sizeY ,
108                        nearPlane, farPlane);*/
109}
110
111void Display()
112{
113        //globalLinesRenderer->DrawGeometry();
114        //globalLinesRenderer->CastGlobalLines(Beam(), 0);
115        globalLinesRenderer->DisplayBuffer(isDepth);
116        PrintGLerror("display");
117
118        glutSwapBuffers();
119}
120
121
122void Idle()
123{
124        glutPostRedisplay();
125}
126
127
128void Keyboard(unsigned char key, int x, int y)
129{
130        switch(key)
131        {
132        case '2':
133                {
134                        VssRayContainer rays;
135
136                        ++ globalLinesRenderer->mMaxDepth;
137                        globalLinesRenderer->ApplyDepthPeeling(rays);
138
139                        cout << "max depth: " << globalLinesRenderer->mMaxDepth << endl;
140                        CLEAR_CONTAINER(rays);
141                        return;
142                }
143        case '1':
144                {
145                        VssRayContainer rays;
146
147                        -- globalLinesRenderer->mMaxDepth;
148                        cout << "max depth: " << globalLinesRenderer->mMaxDepth << endl;
149                       
150                        globalLinesRenderer->ApplyDepthPeeling(rays);
151                        CLEAR_CONTAINER(rays);
152                        return;
153                }
154        case '3':
155                {
156                        globalLinesRenderer->ExportDepthBuffer();
157                        return;
158                }
159        case '4':
160                {
161                        globalLinesRenderer->ExportItemBuffer();
162                        return;
163                }
164        case '5':
165                {
166                        VssRayContainer rays;
167
168                        HwGlobalLinesDistribution glStrategy(*globalLinesRenderer->mPreprocessor);
169
170                        SimpleRayContainer simpleRays;
171                        glStrategy.GenerateSamples(5, simpleRays);
172
173                        //cout << "simple ray: " << simpleRays[4] << endl;
174                        globalLinesRenderer->CastGlobalLines(simpleRays[1], rays);
175
176                        // visualize
177                        VssRayContainer outRays;
178                        VssRayContainer::const_iterator vit, vit_end = rays.end();
179
180                        const float p = 8.0f / (float)rays.size();
181
182                        for (vit = rays.begin(); vit != vit_end; ++ vit)
183                        {
184                                if (Random(1.0f) < p)
185                                {
186                                        outRays.push_back(*vit);
187                                }
188                        }
189
190                        globalLinesRenderer->Visualize(rays);
191
192                        CLEAR_CONTAINER(rays);
193                        return;
194                }
195        case '8':
196                {
197                        isDepth = !isDepth;
198                        return;
199                }
200        case '9':
201                {
202                        VssRayContainer rays;
203                        globalLinesRenderer->ApplyDepthPeeling(rays);
204
205                        // visualize
206                        VssRayContainer outRays;
207                        VssRayContainer::const_iterator vit, vit_end = rays.end();
208
209                        const float p = 8.0f / (float)rays.size();
210
211                        for (vit = rays.begin(); vit != vit_end; ++ vit)
212                        {
213                                if (Random(1.0f) < p)
214                                {
215                                        outRays.push_back(*vit);
216                                }
217                        }
218
219                        globalLinesRenderer->Visualize(rays);
220                        CLEAR_CONTAINER(rays);
221                        return;
222                }
223        case '0':
224                {
225                        VssRayContainer rays;
226                        globalLinesRenderer->ApplyDepthPeeling(rays);
227                        CLEAR_CONTAINER(rays);
228                        return;
229                }
230        default:
231                return;
232        }
233}
234
235
236GlobalLinesRenderer::GlobalLinesRenderer(Preprocessor *preprocessor,
237                                                                                 const int texHeight,
238                                                                                 const int texWidth,
239                                                                                 const float eps,
240                                                                                 const int maxDepth,
241                                                                                 const bool sampleReverse):
242mNewTexture(NULL),
243mOldTexture(NULL),
244mPreprocessor(preprocessor),
245mTexHeight(texHeight),
246mTexWidth(texWidth),
247mEpsilon(eps),
248mMaxDepth(maxDepth),
249mSampleReverse(sampleReverse)
250{
251        mRenderer = new GlRenderer(mPreprocessor->mSceneGraph,
252                                                           mPreprocessor->mViewCellsManager,
253                                                           mPreprocessor->mKdTree);
254
255}
256
257
258GlobalLinesRenderer::GlobalLinesRenderer(Preprocessor *preprocessor):
259mNewTexture(NULL),
260mOldTexture(NULL),
261mMaxDepth(40),
262mPreprocessor(preprocessor),
263mTexHeight(128),
264mTexWidth(128),
265mEpsilon(0.0001),
266mSampleReverse(true)
267{
268        mRenderer = new GlRenderer(mPreprocessor->mSceneGraph,
269                                                           mPreprocessor->mViewCellsManager,
270                                                           mPreprocessor->mKdTree);
271}
272
273
274void GlobalLinesRenderer::DisplayBuffer(const bool isDepth)
275{
276        if (!isDepth)
277                mNewTexture->Bind();
278        else
279                mNewTexture->BindDepth();
280
281        mNewTexture->EnableTextureTarget();
282       
283        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
284       
285        if (mNewTexture->IsRectangleTexture())
286        {
287                glBegin(GL_QUADS);
288                glTexCoord2f(0, 0); glVertex3f(-1, -1, -0.5f);
289                glTexCoord2f(mNewTexture->GetWidth(), 0); glVertex3f( 1, -1, -0.5f);
290                glTexCoord2f(mNewTexture->GetWidth(), mNewTexture->GetHeight()); glVertex3f( 1,  1, -0.5f);
291                glTexCoord2f(0, mNewTexture->GetHeight()); glVertex3f(-1, 1, -0.5f);
292                glEnd();
293        }
294        else
295        {
296                glBegin(GL_QUADS);
297                glTexCoord2f(0, 0); glVertex3f(-1, -1, -0.5f);
298                glTexCoord2f(1, 0); glVertex3f( 1, -1, -0.5f);
299                glTexCoord2f(1, 1); glVertex3f( 1,  1, -0.5f);
300                glTexCoord2f(0, 1); glVertex3f(-1,  1, -0.5f);
301                glEnd();
302        } 
303
304        mNewTexture->DisableTextureTarget();
305        PrintGLerror("displaytexture");
306}
307
308
309GlobalLinesRenderer::~GlobalLinesRenderer()
310{
311        if (sCgDepthPeelingProgram)
312                cgDestroyProgram(sCgDepthPeelingProgram);
313        if (sCgContext)
314                cgDestroyContext(sCgContext);
315
316        // init the receiving buffers
317        delete mNewDepthBuffer;
318        delete mOldDepthBuffer;
319       
320        delete mNewItemBuffer;
321        delete mOldItemBuffer;
322
323        DEL_PTR(mRenderer);
324}
325
326 
327void GlobalLinesRenderer::InitRenderTexture(RenderTexture *rt)
328{
329         // setup the rendering context for the RenderTexture
330        rt->BeginCapture();
331        {
332                //Reshape(mTexWidth, mTexHeight);
333                glViewport(0, 0, mTexWidth, mTexHeight);
334                SetFrustum(mWidth, mWidth, mNear, mFar);
335
336                // for item buffer: white means no color
337                glClearColor(1, 1, 1, 1);
338                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
339
340                glFrontFace(GL_CCW);
341                glCullFace(GL_BACK);
342
343                glDisable(GL_CULL_FACE);
344                //glEnable(GL_CULL_FACE);
345
346                glShadeModel(GL_FLAT);
347                glEnable(GL_DEPTH_TEST);
348               
349                glMatrixMode(GL_MODELVIEW);
350                glLoadIdentity();
351                gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
352                                  mTermination.x, mTermination.y, mTermination.z,
353                                  mUpVec.x, mUpVec.y, mUpVec.z);
354
355        }
356        rt->EndCapture();
357}
358
359
360void GlobalLinesRenderer::InitScene(const float alpha, const float beta)
361{
362        AxisAlignedBox3 bbox =
363                globalLinesRenderer->mPreprocessor->mKdTree->GetBox();
364
365        const float sceneSize = Magnitude(bbox.Diagonal());
366
367        // compute the center of the scene
368        mTermination = bbox.Center();
369       
370        // add a small offset to provide some randomness in the sampling
371        if (0)
372        {
373                Vector3 offset(
374                        Random(sceneSize * 1e-3f),
375                        Random(sceneSize * 1e-3f),
376                        Random(sceneSize * 1e-3f));
377
378                mTermination += offset;
379        }
380               
381        mNear = 1;
382        mFar = sceneSize * 2;
383        mWidth = sceneSize;
384
385        ComputeLookAt(alpha,
386                                  beta,
387                                  mEyeVec,
388                                  mUpVec,
389                                  mLeftVec);
390       
391        mViewPoint = mTermination - 0.5f * sceneSize * mEyeVec;
392
393        //cout << "termination point: " << mTermination << endl;
394        //cout << "view point: " << mViewPoint << endl;
395        //cout << "scene: " << bbox << endl;
396
397        InitRenderTexture(mNewTexture);
398        InitRenderTexture(mOldTexture);
399       
400        //cout << "eye: " << mEyeVec << " left: " << mLeftVec << " up: " << mUpVec << endl;
401}
402
403
404void GlobalLinesRenderer::InitScene(const SimpleRay &ray)
405{
406        AxisAlignedBox3 bbox =
407                globalLinesRenderer->mPreprocessor->mKdTree->GetBox();
408       
409        const float sceneSize = Magnitude(bbox.Diagonal());
410
411        // compute the center of the scene
412        mViewPoint = ray.mOrigin;
413        mTermination = ray.mOrigin + ray.mDirection;
414
415        mEyeVec = Normalize(ray.mDirection);
416
417        mNear = 1;
418        mFar = sceneSize * 2;
419        mWidth = sceneSize;
420
421        mEyeVec.RightHandedBase(mUpVec, mLeftVec);
422
423        //cout << "termination point: " << mTermination << endl;
424        //cout << "view point: " << mViewPoint << endl;
425        //cout << "scene: " << bbox << endl;
426
427        InitRenderTexture(mNewTexture);
428        InitRenderTexture(mOldTexture);
429       
430        //cout << "eye: " << mEyeVec << " left: " << mLeftVec << " up: " << mUpVec << endl;
431}
432
433
434int GlobalLinesRenderer::CastGlobalLines(const float alpha,
435                                                                                  const float beta,
436                                                                                  VssRayContainer &rays)
437{
438        InitScene(alpha, beta);
439
440        // bind pixel shader implementing the front depth buffer functionality
441        const int layers = ApplyDepthPeeling(rays);
442
443        return layers;
444}
445
446
447int GlobalLinesRenderer::CastGlobalLines(const SimpleRay &ray,
448                                                                                  VssRayContainer &rays)
449{
450        const long startTime = GetTime();
451        cout << "casting global lines ... " << endl;
452
453        InitScene(ray);
454
455        // bind pixel shader implementing the front depth buffer functionality
456        const int layers = ApplyDepthPeeling(rays);
457
458        const float rays_per_sec = (float)rays.size() / (TimeDiff(startTime, GetTime()) * 1e-3f);
459        cout << "cast " << rays.size() << " samples in " << layers << " layers in "
460                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs (" << rays_per_sec << " rays/sec)" << endl;
461
462        return layers;
463}
464
465
466void GlobalLinesRenderer::DrawGeometry()
467{
468        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
469        glMatrixMode(GL_MODELVIEW);
470
471        glPushMatrix();
472        {
473                //glLoadIdentity();
474                ObjectContainer::const_iterator oit, oit_end = mPreprocessor->mObjects.end();
475
476                Intersectable::NewMail();
477       
478                mRenderer->RenderScene();
479        }
480        glPopMatrix();
481}
482
483
484void GlobalLinesRenderer::SwitchRenderTextures()
485{
486        RenderTexture *buffer = mOldTexture;
487        mOldTexture = mNewTexture;
488        mNewTexture = buffer;
489}
490
491
492void GlobalLinesRenderer::ComputeLookAt(const float alpha,
493                                                                                const float beta,
494                                                                                Vector3 &eye,
495                                                                                Vector3 &up,
496                                                                                Vector3 &left)
497{
498        eye.x = sin(alpha) * cos(beta);
499        eye.y = sin(alpha) * sin(beta);
500        eye.z = cos(alpha);
501
502        eye.RightHandedBase(up, left);
503}
504
505
506void GlobalLinesRenderer::InitGl()
507{
508        InitDevIl();
509        cout << "texwidth: " << mTexWidth << " texheight: " << mTexHeight << endl;
510    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
511        glutInitWindowPosition(50, 50);
512        glutInitWindowSize(512, 512);
513        glutCreateWindow("TestRenderDepthTexture"); 
514
515        int err = glewInit();
516        if (GLEW_OK != err)
517        {
518                // problem: glewInit failed, something is seriously wrong
519                fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
520                exit(-1);
521        } 
522       
523        glutKeyboardFunc(Keyboard);
524        glutDisplayFunc(Display);
525        glutIdleFunc(Idle);
526        glutReshapeFunc(Reshape);
527
528        Reshape(512, 512);
529        glMatrixMode(GL_MODELVIEW);
530        glLoadIdentity();
531
532        // initialise the receiving buffers
533        mNewDepthBuffer = new float[mTexWidth * mTexHeight];
534        mNewItemBuffer = new unsigned char[mTexWidth * mTexHeight * 4];
535
536        mOldDepthBuffer = new float[mTexWidth * mTexHeight];
537    mOldItemBuffer = new unsigned char[mTexWidth * mTexHeight * 4];
538
539        for (int i = 0; i < mTexWidth * mTexHeight; ++ i)
540        {
541                mNewDepthBuffer[i] = 1;
542                mOldDepthBuffer[i] = 1;
543
544                mNewItemBuffer[i * 4]     = 255;
545                mNewItemBuffer[i * 4 + 1] = 255;
546                mNewItemBuffer[i * 4 + 2] = 255;
547                mNewItemBuffer[i * 4 + 3] = 255;
548
549                mOldItemBuffer[i * 4]     = 255;
550                mOldItemBuffer[i * 4 + 1] = 255;
551                mOldItemBuffer[i * 4 + 2] = 255;
552                mOldItemBuffer[i * 4 + 3] = 255;
553        }
554
555        /*gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
556                          midPoint.x, midPoint.y, midPoint.z,
557                          0, 1, 0);
558*/
559        gluLookAt(0, 0, 3, 0, 0, 0, 0, 1, 0);
560
561        //glDisable(GL_CULL_FACE);
562        glEnable(GL_CULL_FACE);
563        glDisable(GL_LIGHTING);
564        glDisable(GL_COLOR_MATERIAL);
565        glEnable(GL_DEPTH_TEST);
566        glClearColor(0.1, 0.2, 0.3, 1);
567       
568        // A square, mipmapped, anisotropically filtered 8-bit RGBA texture with
569        // depth and stencil.
570        // Note that RT_COPY_TO_TEXTURE is required for depth textures on ATI hardware
571
572        mNewTexture = new RenderTexture(mTexWidth, mTexHeight, true, true);
573#ifdef ATI
574        mNewTexture->Initialize(true, true, false, false, false, 8, 8, 8, 8, RenderTexture::RT_COPY_TO_TEXTURE);
575#else
576        mNewTexture->Initialize(true, true, false, false, false, 8, 8, 8, 8);//, RenderTexture::RT_COPY_TO_TEXTURE);
577#endif
578
579        mOldTexture = new RenderTexture(mTexWidth, mTexHeight, true, true);
580
581#ifdef ATI
582        mOldTexture ->Initialize(true, true, false, false, false, 8, 8, 8, 8, RenderTexture::RT_COPY_TO_TEXTURE);
583#else
584        mOldTexture ->Initialize(true, true, false, false, false, 8, 8, 8, 8);//, RenderTexture::RT_COPY_TO_TEXTURE);
585#endif
586
587        // Setup Cg
588        cgSetErrorCallback(cgErrorCallback);
589
590        // Create cgContext.
591        sCgContext = cgCreateContext();
592
593        // get the best profile for this hardware
594        sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
595       
596        //assert(sCgFragmentProfile != CG_PROFILE_UNKNOWN);
597        cgGLSetOptimalOptions(sCgFragmentProfile);
598
599        sCgDepthPeelingProgram =
600                cgCreateProgramFromFile(sCgContext,
601                                                                CG_SOURCE,
602                                                                mNewTexture->IsRectangleTexture() ?
603                                                                "../src/depth_peelingRect.cg" : "../src/depth_peeling2d.cg",
604                                                                GLEW_ARB_fragment_program ? CG_PROFILE_ARBFP1 : CG_PROFILE_FP30,
605                                                                NULL,
606                                                                NULL);
607
608        if(sCgDepthPeelingProgram != NULL)
609        {
610                cgGLLoadProgram(sCgDepthPeelingProgram);
611                sTextureParam = cgGetNamedParameter(sCgDepthPeelingProgram, "depthTex"); 
612               
613                // we need size of texture for scaling
614                if (!mNewTexture->IsRectangleTexture())
615                {
616                        sTexWidthParam = cgGetNamedParameter(sCgDepthPeelingProgram, "invTexWidth");
617                }
618
619                sStepSizeParam = cgGetNamedParameter(sCgDepthPeelingProgram, "stepSize");
620
621                cgGLSetParameter1f(sTexWidthParam, 1.0f / (float)mTexWidth);
622                cgGLSetParameter1f(sStepSizeParam, mEpsilon);
623        }
624
625        sCgPassThroughProgram =
626                cgCreateProgramFromFile(sCgContext,
627                                                                CG_SOURCE,
628                                                                "../src/passthrough.cg",
629                                                                GLEW_ARB_fragment_program ? CG_PROFILE_ARBFP1 : CG_PROFILE_FP30,
630                                                                NULL,
631                                                                NULL);
632
633        if(sCgPassThroughProgram != NULL)
634        {
635                cgGLLoadProgram(sCgPassThroughProgram);
636        }
637
638        const float alpha = 1.1;
639        const float beta = 0.9;
640
641        InitScene(alpha, beta);
642
643        PrintGLerror("init");
644}
645
646
647Intersectable *GlobalLinesRenderer::ExtractSamplePoint(float *depthBuffer,
648                                                                                                           unsigned char *itemBuffer,
649                                                                                                           const int x,
650                                                                                                           const int y,
651                                                                                                           Vector3 &hitPoint,
652                                                                                                           const bool isFrontBuffer) const
653{
654        const int depthIndex = x + mTexWidth * y;
655        const int itemIndex = 4 * depthIndex;
656
657        const float depth = depthBuffer[depthIndex];
658        const float eyeDist = mNear + (mFar - mNear) * depth;
659       
660        const float leftDist = -0.5f * mWidth + mWidth * ((float)x + 0.5f) / mTexWidth;
661        const float upDist   = -0.5f * mWidth + mWidth * ((float)y + 0.5f) / mTexHeight;
662
663        hitPoint = mViewPoint +
664                       eyeDist * mEyeVec +
665                           upDist * mUpVec +
666                           leftDist * mLeftVec;
667                               
668        unsigned char r = itemBuffer[itemIndex];
669        unsigned char g = itemBuffer[itemIndex + 1];
670        unsigned char b = itemBuffer[itemIndex + 2];
671                       
672        // 3 times 255 means no valid object
673        if ((r == 255) && (g == 255) && (b == 255))
674                return NULL;
675
676        const int id = mRenderer->GetId(r, g, b);
677        //cout << "r: " << (int)r << "g: " << (int)g << " b: " << (int)b << " id: " << id << "|";
678        Intersectable *intersect = mPreprocessor->GetObjectById(id);
679
680        const Vector3 dir = isFrontBuffer ? mEyeVec : -mEyeVec;
681        // HACK: assume triangle intersectable
682        const Vector3 norm = intersect->GetNormal(0);
683
684        // test for invalid view space
685        if (DotProd(dir, norm) >= -Limits::Small)
686                return NULL;
687
688        return intersect;
689}
690
691
692void GlobalLinesRenderer::ComputeBoundingQuad(int &xMin,
693                                                                                          int &yMin,
694                                                                                          int &xMax,
695                                                                                          int &yMax)
696{
697        const AxisAlignedBox3 bbox = mPreprocessor->mKdTree->GetBox();
698
699        Matrix4x4 m(mEyeVec, mUpVec, mLeftVec);
700
701        m.Invert();
702
703        Vector3 eye(m.x[0][0], m.x[1][0], m.x[2][0]);
704        Vector3 up(m.x[0][0], m.x[1][1], m.x[2][1]);
705        Vector3 left(m.x[0][2], m.x[1][2], m.x[2][2]);
706
707        Vector3 boxMin(1e20f);
708        Vector3 boxMax(-1e20f);
709       
710        for (int i = 0; i < 8; ++ i)
711        {
712        Vector3 vtx;
713
714                bbox.GetVertex(i, vtx);
715
716                Vector3 pt = vtx.x * eye + vtx.y * up + vtx.z * left;
717
718                // TODO
719                if (boxMin.x > pt.x)
720                        boxMin.x = pt.x;
721               
722                if (boxMin.y > pt.y)
723                        boxMin.y = pt.y;
724
725                if (boxMin.z > pt.z)
726                        boxMin.z = pt.z;
727
728                if (boxMax.x < pt.x)
729                        boxMax.x = pt.x;
730               
731                if (boxMax.y < pt.y)
732                        boxMax.y = pt.y;
733
734                if (boxMax.z < pt.z)
735                        boxMax.z = pt.z;
736        }
737
738        cout << "xmin: " << boxMin.x << " ymin " << boxMin.y << " xmax: " << boxMax.x << " ymax: " << boxMax.y << endl;
739
740        xMin = (int)(-0.5f * mWidth + mWidth * (boxMin.x + 0.5f) / mTexWidth);
741        yMin = (int)(-0.5f * mWidth + mWidth * (boxMin.y + 0.5f) / mTexHeight);
742        xMax = (int)(-0.5f * mWidth + mWidth * (boxMax.x + 0.5f) / mTexWidth);
743        yMax = (int)(-0.5f * mWidth + mWidth * (boxMax.y + 0.5f) / mTexHeight);
744}
745
746
747bool GlobalLinesRenderer::ProcessDepthBuffer(VssRayContainer &vssRays,
748                                                                                         const bool oldBufferInitialised,
749                                                                                         const int pass)
750{
751        GrabDepthBuffer(mNewDepthBuffer, mNewTexture);
752        GrabItemBuffer(mNewItemBuffer, mNewTexture);
753
754        if (oldBufferInitialised)
755        {
756                GrabDepthBuffer(mOldDepthBuffer, mOldTexture);
757                GrabItemBuffer(mOldItemBuffer, mOldTexture);
758        }
759        else
760        {
761                for (int i = 0; i < mTexWidth * mTexHeight; ++ i)
762                {
763                        mOldDepthBuffer[i] = 0;
764
765                        mOldItemBuffer[i * 4]     = 255;
766                        mOldItemBuffer[i * 4 + 1] = 255;
767                        mOldItemBuffer[i * 4 + 2] = 255;
768                        mOldItemBuffer[i * 4 + 3] = 255;
769                }
770        }
771
772        int xMin, yMin, xMax, yMax;
773        ComputeBoundingQuad(xMin, yMin, xMax, yMax);
774       
775        cout << "xmin2: " << xMin << " ymin " << yMin << " xmax: " << xMax << " ymax: " << yMax << endl;
776
777        /////////////////
778        // test for validity
779
780        bool buffersEqual = true;
781        bool bufferEmpty = true;
782
783        for (int y = 0; y < mTexHeight; ++ y)
784        {
785                for (int x = 0; x < mTexWidth; ++ x)
786                {
787                        const int depthIndex = x + mTexWidth * y;   
788                        const int itemIndex = 4 * depthIndex;
789               
790                        if (mOldItemBuffer[itemIndex] != mNewItemBuffer[itemIndex])
791                        {
792                                buffersEqual = false;
793                        }
794
795                        unsigned char r = mNewItemBuffer[itemIndex];
796                        unsigned char g = mNewItemBuffer[itemIndex + 1];
797                        unsigned char b = mNewItemBuffer[itemIndex + 2];
798
799                        // 3 times 255 means no valid object
800                        if (!((r == 255) && (g == 255) && (b == 255)))
801                        {
802                                bufferEmpty = false;
803                        }
804                }
805               
806                // early exit
807                if (!buffersEqual && !bufferEmpty)
808                        break;
809        }
810
811        // depth buffer not valid
812        if (buffersEqual || bufferEmpty)
813        {
814                cout << "stopped at layer " << pass << endl;
815                return false;
816        }
817
818        for (int y = 0; y < mTexHeight; ++ y)
819        {
820                for (int x = 0; x < mTexWidth; ++ x)
821                {
822                        Vector3 newPt, oldPt;
823
824                        Intersectable *termObj1 = ExtractSamplePoint(mNewDepthBuffer,
825                                                                                                                 mNewItemBuffer,
826                                                                                                                 x,
827                                                                                                                 y,
828                                                                                                                 newPt,
829                                                                                                                 true);
830
831                        Intersectable *termObj2 = ExtractSamplePoint(mOldDepthBuffer,
832                                                                                                                 mOldItemBuffer,
833                                                                                                                 x,
834                                                                                                                 y,
835                                                                                                                 oldPt,
836                                                                                                                 false);
837
838                        if (!termObj1 && !termObj2) // we do not create a ray
839                                continue;
840
841                        Vector3 clippedOldPt, clippedNewPt;
842
843                        if (ClipToViewSpaceBox(oldPt, newPt, clippedOldPt, clippedNewPt))//;if(1)
844                        {
845                                //clippedOldPt = oldPt;
846                                //clippedNewPt = newPt;
847
848                                // create rays in both directions
849                                if (termObj1)
850                                {
851                                        vssRays.push_back(new VssRay(clippedOldPt, clippedNewPt, NULL, termObj1, pass));
852                                        //cout << "new pt: " << newPt << endl;
853                                }
854
855                                if (mSampleReverse && termObj2)
856                                {
857                                        vssRays.push_back(new VssRay(clippedNewPt, clippedOldPt, NULL, termObj2, pass));
858                                        //cout << "old pt: " << oldPt << endl;
859                                }
860                        }
861                }
862        }
863
864        return true;
865}
866
867
868bool GlobalLinesRenderer::ClipToViewSpaceBox(const Vector3 &origin,
869                                                                                         const Vector3 &termination,
870                                                                                         Vector3 &clippedOrigin,
871                                                                                         Vector3 &clippedTermination)
872{
873        Ray ray(origin, termination - origin, Ray::LINE_SEGMENT);       
874        ray.Precompute();
875       
876        float tmin, tmax;
877       
878        //const AxisAlignedBox3 bbox = mPreprocessor->mViewCellsManager->GetViewSpaceBox();
879        // hack
880        AxisAlignedBox3 bbox = mPreprocessor->mKdTree->GetBox();
881
882        //bbox.Enlarge(1);
883        if (!bbox.ComputeMinMaxT(ray, &tmin, &tmax) || (tmin >= tmax))
884        {
885                return false;
886        }
887       
888        if (tmin >= 1.0f || tmax <= 0.0f)
889                return false;
890
891        if (tmin > 0.0f)
892                clippedOrigin = ray.Extrap(tmin);
893        else
894                clippedOrigin = origin;
895
896        if (tmax < 1.0f)
897                clippedTermination = ray.Extrap(tmax);
898        else
899                clippedTermination = termination;
900
901        return true;
902}
903
904
905void GlobalLinesRenderer::Run()
906{
907        glutMainLoop();
908}
909
910
911void GlobalLinesRenderer::Visualize(const VssRayContainer &vssRays)
912{
913        cout << "exporting visualization ... ";
914        Exporter *exporter = Exporter::GetExporter("globalLines.wrl");
915       
916        if (!exporter)
917                return;
918
919        exporter->SetWireframe();
920        //exporter->ExportGeometry(preprocessor->mObjects);
921        exporter->SetFilled();
922
923        VssRayContainer::const_iterator vit, vit_end = vssRays.end();
924        VssRayContainer outRays;
925
926        Intersectable::NewMail();
927
928        for (vit = vssRays.begin(); vit != vit_end; ++ vit)
929        {
930                VssRay *ray = *vit;
931                Intersectable *obj = (*vit)->mTerminationObject;
932
933                if (!obj->Mailed())
934                {
935                        obj->Mail();
936                        exporter->ExportIntersectable(obj);
937                }
938
939                //if (ray->mPass == 4)
940                        outRays.push_back(ray);
941        }       
942
943        //exporter->ExportRays(outRays);
944        cout << "finished" << endl;
945        delete exporter;
946}
947
948
949void GlobalLinesRenderer::GrabDepthBuffer(float *data, RenderTexture *rt)
950{
951        rt->BindDepth();
952        rt->EnableTextureTarget();
953
954        const int texFormat = GL_DEPTH_COMPONENT;
955        glGetTexImage(mNewTexture->GetTextureTarget(), 0, texFormat, GL_FLOAT, data);
956
957        mNewTexture->DisableTextureTarget();
958}
959
960
961void GlobalLinesRenderer::GrabItemBuffer(unsigned char *data, RenderTexture *rt)
962{
963        rt->Bind();
964        rt->EnableTextureTarget();
965
966        const int texFormat = GL_RGBA;
967        glGetTexImage(mNewTexture->GetTextureTarget(), 0, texFormat, GL_UNSIGNED_BYTE, data);
968
969        mNewTexture->DisableTextureTarget();
970}
971
972
973void GlobalLinesRenderer::ExportDepthBuffer()
974{
975        mNewTexture->BindDepth();
976        mNewTexture->EnableTextureTarget();
977        cout << "depth: " << mNewTexture->GetDepthBits() << endl;
978
979        const int components = 1;//mNewTexture->GetDepthBits() / 8;
980
981        float *data = new float[mTexWidth * mTexHeight * components];
982        //const int texFormat = WGL_TEXTURE_DEPTH_COMPONENT_NV;
983        const int texFormat = GL_DEPTH_COMPONENT;
984        //const int texFormat = GL_RGBA;
985        glGetTexImage(mNewTexture->GetTextureTarget(), 0, texFormat, GL_FLOAT, data);
986
987        string filename("depth.tga");
988        ilRegisterType(IL_FLOAT);
989
990        const int depth = 1;
991        const int bpp = components;
992
993        ilTexImage(mTexWidth, mTexHeight, depth, bpp, IL_LUMINANCE, IL_FLOAT, data);
994        ilSaveImage((char *const)filename.c_str());
995
996        cout << "finished" << endl;
997        delete data;
998        cout << "data deleted" << endl;
999        mNewTexture->DisableTextureTarget();
1000        PrintGLerror("grab texture");
1001}
1002
1003
1004void GlobalLinesRenderer::ExportItemBuffer()
1005{
1006        mNewTexture->Bind();
1007        mNewTexture->EnableTextureTarget();
1008        cout << "depth: " << mNewTexture->GetDepthBits() << endl;
1009
1010        const int components = 4;//mNewTexture->GetDepthBits() / 8;
1011
1012        unsigned char *data = new unsigned char [mTexWidth * mTexHeight * components];
1013        //const int texFormat = WGL_TEXTURE_DEPTH_COMPONENT_NV;
1014        const int texFormat = GL_RGBA;
1015        glGetTexImage(mNewTexture->GetTextureTarget(), 0, texFormat, GL_UNSIGNED_BYTE, data);
1016
1017        string filename("items.jpg");
1018        ilRegisterType(IL_UNSIGNED_BYTE);
1019
1020        const int depth = 1;
1021        const int bpp = components;
1022
1023        ilTexImage(mTexWidth, mTexHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data);
1024        ilSaveImage((char *const)filename.c_str());
1025
1026        cout << "finished" << endl;
1027        delete data;
1028        cout << "data deleted" << endl;
1029        mNewTexture->DisableTextureTarget();
1030        PrintGLerror("grab texture");
1031}
1032
1033
1034int GlobalLinesRenderer::ApplyDepthPeeling(VssRayContainer &rays)
1035{
1036        int layers = 1;
1037
1038        mNewTexture->BeginCapture();
1039        {
1040                //cgGLBindProgram(sCgPassThroughProgram);
1041                //cgGLEnableProfile(sCgFragmentProfile);
1042                DrawGeometry();
1043        }
1044        mNewTexture->EndCapture();
1045       
1046        PrintGLerror("firstpass");
1047        if (mNewTexture->IsRectangleTexture()) cout << "rect" << endl;
1048
1049        // process the buffers for the first layer
1050        ProcessDepthBuffer(rays, false, 0);
1051
1052        long renderTime = 0;
1053        long bufferTime = 0;
1054
1055        for(; layers < mMaxDepth; ++ layers)
1056        {
1057                cout << ".";
1058                const long startRenderTime = GetTime();
1059
1060                // Peel another layer
1061                // switch pointer between rendertextures
1062                SwitchRenderTextures();
1063
1064                mNewTexture->BeginCapture();
1065                {
1066                        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);         
1067
1068                        cgGLBindProgram(sCgDepthPeelingProgram);
1069                        cgGLEnableProfile(sCgFragmentProfile);
1070                        cgGLSetTextureParameter(sTextureParam, mOldTexture->GetDepthTextureID());
1071                        cgGLEnableTextureParameter(sTextureParam);
1072
1073                        DrawGeometry();
1074                       
1075                        cgGLDisableTextureParameter(sTextureParam);
1076                        cgGLDisableProfile(sCgFragmentProfile);
1077                }
1078                mNewTexture->EndCapture();
1079
1080                renderTime += TimeDiff(startRenderTime, GetTime());
1081
1082                const long startBufferTime = GetTime();
1083
1084                // process the buffers for following layer
1085                // jump out of loop for the first invalid buffer
1086                if (!ProcessDepthBuffer(rays, true, layers))
1087                        break;
1088
1089                bufferTime += TimeDiff(startBufferTime, GetTime());
1090        }
1091
1092        Debug << "time spent in rendering: " << renderTime * 1e-3f << endl;
1093        Debug << "time spent in buffer: " << bufferTime * 1e-3f << endl;
1094       
1095        PrintGLerror("endpeeling");
1096
1097        return layers;
1098}
1099
1100}
1101
1102#endif
Note: See TracBrowser for help on using the repository browser.