source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/DeferredRenderer.cpp @ 3222

Revision 3222, 37.9 KB checked in by mattausch, 16 years ago (diff)

found error that made it slower

Line 
1#include "DeferredRenderer.h"
2#include "FrameBufferObject.h"
3#include "RenderState.h"
4#include "SampleGenerator.h"
5#include "Vector3.h"
6#include "Camera.h"
7#include "shaderenv.h"
8#include "Halton.h"
9#include "ShadowMapping.h"
10#include "Light.h"
11#include "ShaderManager.h"
12#include "Texture.h"
13
14#include <math.h>
15
16#include <IL/il.h>
17#include <assert.h>
18
19
20#ifdef _CRT_SET
21        #define _CRTDBG_MAP_ALLOC
22        #include <stdlib.h>
23        #include <crtdbg.h>
24
25        // redefine new operator
26        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
27        #define new DEBUG_NEW
28#endif
29
30
31using namespace std;
32
33
34static void startil()
35{
36        ilInit();
37        assert(ilGetError() == IL_NO_ERROR);
38}
39
40
41static void stopil()
42{
43        ilShutDown();
44        assert(ilGetError() == IL_NO_ERROR);
45}
46
47
48namespace CHCDemoEngine
49{
50
51static ShaderProgram *sCgSsaoProgram = NULL;
52static ShaderProgram *sCgGiProgram = NULL;
53
54static ShaderProgram *sCgDeferredProgram = NULL;
55static ShaderProgram *sCgAntiAliasingProgram = NULL;
56static ShaderProgram *sCgDeferredShadowProgram = NULL;
57
58static ShaderProgram *sCgCombineSsaoProgram = NULL;
59static ShaderProgram *sCgCombineIllumProgram = NULL;
60static ShaderProgram *sCgLogLumProgram = NULL;
61static ShaderProgram *sCgToneProgram = NULL;
62static ShaderProgram *sCgDownSampleProgram = NULL;
63static ShaderProgram *sCgScaleDepthProgram = NULL;
64static ShaderProgram *sCgPrepareSsaoProgram = NULL;
65static ShaderProgram *sCgLenseFlareProgram = NULL;
66
67
68static GLuint noiseTex2D = 0;
69static GLuint noiseTex1D = 0;
70
71
72// ssao random spherical samples
73static Sample2 samples2[NUM_SAMPLES];
74// number of pcf tabs
75static Sample2 pcfSamples[NUM_PCF_TABS];
76
77
78static float ssaoFilterOffsets[NUM_SSAO_FILTER_SAMPLES * 2];
79static float ssaoFilterWeights[NUM_SSAO_FILTER_SAMPLES];
80
81static Texture *sHaloTex[5];
82
83int DeferredRenderer::colorBufferIdx = 0;
84
85
86
87
88/** Helper method that computes the view vectors in the corners of the current view frustum.
89*/
90static void ComputeViewVectors(PerspectiveCamera *cam, Vector3 &bl, Vector3 &br, Vector3 &tl, Vector3 &tr)
91{
92        Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
93        cam->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
94
95        bl = Normalize(nbl - fbl);
96        br = Normalize(nbr - fbr);
97        tl = Normalize(ntl - ftl);
98        tr = Normalize(ntr - ftr);
99}
100
101
102static float GaussianDistribution(float x, float y, float rho)
103{
104        float g = 1.0f / sqrtf(2.0f * M_PI * rho * rho);
105    g *= expf( -(x * x + y * y) / (2.0f * rho * rho));
106
107    return g;
108}
109
110
111static void PrintGLerror(char *msg)
112{
113        GLenum errCode;
114        const GLubyte *errStr;
115       
116        if ((errCode = glGetError()) != GL_NO_ERROR)
117        {
118                errStr = gluErrorString(errCode);
119                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
120        }
121}
122
123
124static Sample2 UnitTest(float x, float y, int wi, int he)
125{
126        Sample2 s;
127
128        s.x = float(floor(x * (float)wi - 0.5f) + 1.0f) / (float)wi;
129        s.y = float(floor(y * (float)he - 0.5f) + 1.0f) / (float)he;
130
131        return s;
132}
133
134
135static void ComputeSampleOffsets(float *sampleOffsets,
136                                                                 int imageW, int imageH,
137                                                                 float width,
138                                                                 int samples)
139{
140        const float xoffs = width / (float)imageW;
141        const float yoffs = width / (float)imageH;
142       
143        const int numSamples = (int)sqrt((float)samples);
144        const int startSamples = -numSamples / 2;
145        const int endSamples = numSamples + startSamples - 1;
146        //cout << startSamples << " " << endSamples << endl;
147
148        int idx = 0;
149
150        for (int x = startSamples; x <= endSamples; ++ x)
151        {
152                for (int y = startSamples; y <= endSamples; ++ y)
153                {
154                        sampleOffsets[idx + 0] = (float)x * xoffs;
155                        sampleOffsets[idx + 1] = (float)y * yoffs;
156                        idx += 2;
157                }
158        }
159}
160
161
162void DeferredRenderer::FlipFbos(FrameBufferObject *fbo)
163{
164        fbo->Bind();
165        colorBufferIdx = 3 - colorBufferIdx;
166        glDrawBuffers(1, mrt + colorBufferIdx);
167}
168
169
170void DeferredRenderer::DrawQuad(ShaderProgram *p)
171{
172        if (p) p->Bind();
173
174        // interpolate the view vector
175        Vector3 bl = mCornersView[0];
176        Vector3 br = mCornersView[1];
177        Vector3 tl = mCornersView[2];
178        Vector3 tr = mCornersView[3];
179
180        // note: slightly larger texture could hide ambient occlusion error on border but costs resolution
181        glBegin(GL_QUADS);
182
183        glTexCoord2f(0, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, bl.x, bl.y, bl.z); glVertex2f( .0f,  .0f);
184        glTexCoord2f(1, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, br.x, br.y, br.z); glVertex2f(1.0f,  .0f);
185        glTexCoord2f(1, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tr.x, tr.y, tr.z); glVertex2f(1.0f, 1.0f);
186        glTexCoord2f(0, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tl.x, tl.y, tl.z); glVertex2f( .0f, 1.0f);
187
188        glEnd();
189}
190
191
192/** Generate poisson disc distributed sample points on the unit disc
193*/
194static void GenerateSamples(int sampling)
195{
196        switch (sampling)
197        {
198        case DeferredRenderer::SAMPLING_POISSON:
199                {
200                        PoissonDiscSampleGenerator2 poisson(NUM_SAMPLES, 1.0f);
201                        poisson.Generate((float *)samples2);
202                }
203                break;
204        case DeferredRenderer::SAMPLING_QUADRATIC:
205                {
206                        QuadraticDiscSampleGenerator2 g(NUM_SAMPLES, 1.0f);
207                        g.Generate((float *)samples2);
208                }
209                break;
210        default: // SAMPLING_DEFAULT
211                {
212                        RandomSampleGenerator2 g(NUM_SAMPLES, 1.0f);
213                        g.Generate((float *)samples2);
214                }
215        }
216}
217
218
219static void CreateNoiseTex2D(int w, int h)
220{
221        //GLubyte *randomNormals = new GLubyte[mWidth * mHeight * 3];
222        float *randomNormals = new float[w * h * 3];
223
224        static HaltonSequence halton;
225        float r[2];
226
227        for (int i = 0; i < w * h * 3; i += 3)
228        {
229                // create random samples on a circle
230                r[0] = RandomValue(0, 1);
231                //halton.GetNext(1, r);
232
233                const float theta = 2.0f * acos(sqrt(1.0f - r[0]));
234               
235                randomNormals[i + 0] = cos(theta);
236                randomNormals[i + 1] = sin(theta);
237                randomNormals[i + 2] = 0;
238        }
239
240        glEnable(GL_TEXTURE_2D);
241        glGenTextures(1, &noiseTex2D);
242        glBindTexture(GL_TEXTURE_2D, noiseTex2D);
243               
244        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
245        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
246        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
247        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
248
249        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGB, GL_FLOAT, randomNormals);
250
251        glBindTexture(GL_TEXTURE_2D, 0);
252        glDisable(GL_TEXTURE_2D);
253
254        delete [] randomNormals;
255
256        cout << "created noise texture" << endl;
257
258        PrintGLerror("noisetexture");
259}
260
261
262static void CreateNoiseTex1D(int w)
263{
264        float *randomValues = new float[w * 3];
265
266        static HaltonSequence halton;
267       
268        randomValues[0] = randomValues[1] = randomValues[2] = 0;
269
270        for (int i = 3; i < w * 3; i += 3)
271        {
272                // create random samples on a circle
273                randomValues[i + 0] = 20.0f * RandomValue(0, 1) / 512.0f;
274                randomValues[i + 1] = 20.0f * RandomValue(0, 1) / 384.0f;
275                randomValues[i + 2] = 0;
276        }
277
278        glEnable(GL_TEXTURE_2D);
279        glGenTextures(1, &noiseTex1D);
280        glBindTexture(GL_TEXTURE_2D, noiseTex1D);
281               
282        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
283        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
284        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
285        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
286
287        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, 1, 0, GL_RGB, GL_FLOAT, randomValues);
288
289        glBindTexture(GL_TEXTURE_2D, 0);
290        glDisable(GL_TEXTURE_2D);
291
292        delete [] randomValues;
293
294        cout << "created noise texture 1D" << endl;
295
296        PrintGLerror("noisetexture 1D");
297}
298
299
300static void PrepareLenseFlare()
301{
302        string textures[] = {"flare4.tga", "lens2.jpg", "lens3.jpg", "lens4.jpg", "lens1.jpg"};
303
304        for (int i = 0; i < 5; ++ i)
305        {
306                sHaloTex[i] = new Texture(model_path + textures[i]);
307
308                sHaloTex[i]->SetBoundaryModeS(Texture::BORDER);
309                sHaloTex[i]->SetBoundaryModeT(Texture::BORDER);
310
311                sHaloTex[i]->Create();
312        }
313
314        cout << "prepared lense flare textures" << endl;
315
316        PrintGLerror("prepare lense flare");
317}
318
319
320DeferredRenderer::DeferredRenderer(int w, int h,
321                                                                   PerspectiveCamera *cam,
322                                                                   bool ssaoUseFullResolution):
323mWidth(w), mHeight(h),
324mCamera(cam),
325mUseTemporalCoherence(true),
326mRegenerateSamples(true),
327mSamplingMethod(SAMPLING_POISSON),
328mShadingMethod(DEFAULT),
329mIllumFboIndex(0),
330mSortSamples(true),
331mKernelRadius(1e-8f),
332mSsaoFilterRadius(12.0f),
333mSampleIntensity(0.2f),
334mSunVisiblePixels(0),
335mSavedFrameNumber(-1),
336mSavedFrameSuffix("")
337{
338        ///////////
339        //-- the flip-flop fbos
340
341        int downSampledWidth, downSampledHeight;
342
343        if (ssaoUseFullResolution)
344        {
345                downSampledWidth = w; downSampledHeight = h;
346                cout << "using full resolution ssao" << endl;
347        }
348        else
349        {
350                downSampledWidth = w / 2; downSampledHeight = h / 2;
351                cout << "using half resolution ssao" << endl;
352        }
353
354        mIllumFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
355        //mIllumFbo = new FrameBufferObject(w, h, FrameBufferObject::DEPTH_NONE);
356
357        mFBOs.push_back(mIllumFbo);
358
359        for (int i = 0; i < 4; ++ i)
360        {
361                mIllumFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
362                FrameBufferObject::InitBuffer(mIllumFbo, i);
363        }
364
365
366        ///////////////
367        //-- the downsampled ssao + color bleeding textures:
368        //-- as GI is mostly low frequency, we can use lower resolution toimprove performance
369
370        mDownSampleFbo = new FrameBufferObject(downSampledWidth, downSampledHeight, FrameBufferObject::DEPTH_NONE);
371        // the downsampled color + depth buffer
372        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
373        // downsample buffer for the normal texture
374        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
375
376
377        for (int i = 0; i < 2; ++ i)
378        {
379                FrameBufferObject::InitBuffer(mDownSampleFbo, i);
380        }
381
382        mFBOs.push_back(mDownSampleFbo);
383
384        // create noise texture for ssao
385        // for performance reasons we use a smaller texture and repeat it over the screen
386        CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
387       
388        mProjViewMatrix = IdentityMatrix();
389        mOldProjViewMatrix = IdentityMatrix();
390
391        for (int i = 0; i < 4; ++ i)
392        {
393                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
394        }
395
396        mEyePos = mOldEyePos = Vector3::ZERO();
397
398        PrepareLenseFlare();
399
400        InitCg();
401}
402
403
404DeferredRenderer::~DeferredRenderer()
405{
406        CLEAR_CONTAINER(mFBOs);
407
408        glDeleteTextures(1, &noiseTex2D);
409        glDeleteTextures(1, &noiseTex1D);
410}
411
412
413void DeferredRenderer::InitCg()
414{       
415        ShaderManager *sm = ShaderManager::GetSingleton();
416
417        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "DeferredFrag");
418        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "DeferredFragShadow");
419        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "SsaoFrag");
420        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "GiFrag");
421        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "CombineGi");
422        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsao", "CombineSsaoHalfRes", "CombineSsao");
423        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "AntiAliasing");
424        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "ToneMap");
425        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
426        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
427        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "AvgLogLum");
428        sCgPrepareSsaoProgram = sm->CreateFragmentProgram("deferred", "PrepareSsao", "PrepareSsao");
429        sCgLenseFlareProgram = sm->CreateFragmentProgram("lenseFlare", "LenseFlare", "LenseFlare");
430
431
432        ///////////////////
433        //-- initialize program parameters
434
435        string ssaoParams[] =
436                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
437                 "samples", "bl", "br", "tl", "tr",
438                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
439                 "oldtl", "oldtr", "attribsTex", "kernelRadius", "sampleIntensity"};
440        sCgSsaoProgram->AddParameters(ssaoParams, 0, 20);
441       
442        string giParams[] =
443                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
444                 "temporalCoherence", "samples", "bl", "br", "tl",
445                 "tr", "oldModelViewProj", "modelViewProj"};
446        sCgGiProgram->AddParameters(giParams, 0, 13);
447
448        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
449        sCgToneProgram->AddParameters(toneParams, 0, 4);
450
451
452        ////////////////
453
454        string deferredShadowParams[] =
455                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
456                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
457       
458        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
459       
460        ////////////////
461
462        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
463        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
464
465        ////////////////
466
467        string combineSsaoParams[] =
468                {"colorsTex", "normalsTex", "ssaoTex", "filterOffs", "filterWeights",
469                "ssaoFilterRadius", "modelViewProj", "bl", "br", "tl",
470                "tr", "w", "h"};
471        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 13);
472
473        //////////////
474
475        string deferredParams[] = {"colors", "normals", "lightDir"};
476        sCgDeferredProgram->AddParameters(deferredParams, 0, 3);
477
478        ///////////////////
479
480        string aaParams[] = {"colors", "normals", "offsets"};
481        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
482
483        /////////////////////
484
485        string downSampleParams[] = {"colors"};
486        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
487
488        /////////////////////
489
490        string scaleDepthParams[] = {"colors"};
491        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
492
493        ////////////
494
495        sCgLogLumProgram->AddParameter("colors", 0);
496
497        ////////////////
498
499       
500        string prepareSsaoParams[] =
501                {"colorsTex", "normalsTex", "diffVals", "oldTex",
502                 "oldEyePos", "modelViewProj", "oldModelViewProj",
503                 "oldbl", "oldbr", "oldtl", "oldtr"};
504
505        sCgPrepareSsaoProgram->AddParameters(prepareSsaoParams, 0, 11);
506
507
508        ////////////////
509
510       
511        string lenseFlareParams[] =
512                {"colorsTex", "flareTex1", "flareTex2", "flareTex3", "flareTex4",
513                 "flareTex5", "vectorToLight", "distanceToLight", "sunVisiblePixels"};
514
515        sCgLenseFlareProgram->AddParameters(lenseFlareParams, 0, 9);
516
517
518        ////////////////
519        //-- prepare filters for ssao
520
521        PrepareSsaoFilter();
522
523
524        /////////
525        //-- pcf tabs for shadowing
526
527        float filterWeights[NUM_PCF_TABS];
528        PoissonDiscSampleGenerator2 poisson2(NUM_PCF_TABS, 1.0f);
529        poisson2.Generate((float *)pcfSamples);
530
531        for (int i = 0; i < NUM_PCF_TABS; ++ i)
532        {
533                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
534        }
535
536        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
537        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
538
539        PrintGLerror("init");
540}
541
542
543void DeferredRenderer::Render(FrameBufferObject *fbo,
544                                                          float tempCohFactor,
545                                                          DirectionalLight *light,
546                                                          bool useToneMapping,
547                                                          bool useAntiAliasing,
548                                                          ShadowMap *shadowMap
549                                                          )
550{
551        InitFrame();
552
553        if (shadowMap)
554                FirstPassShadow(fbo, light, shadowMap);
555        else
556                FirstPass(fbo, light);
557
558        if (mShadingMethod != 0)
559        {
560                PrepareSsao(fbo); // downsample fbo buffers
561        }
562
563        // q: use antialiasing before or after ssao?
564        //if (useAntiAliasing) AntiAliasing(fbo, light);
565
566        switch (mShadingMethod)
567        {
568        case SSAO:
569                ComputeSsao(fbo, tempCohFactor);
570                CombineSsao(fbo);
571                break;
572        case GI:
573                ComputeGlobIllum(fbo, tempCohFactor);
574                CombineIllum(fbo);
575                break;
576        default:
577                // do nothing: standard deferred shading
578                break;
579        }
580
581        if (useToneMapping)
582        {
583                float imageKey, whiteLum, middleGrey;
584
585                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
586                ToneMap(fbo, imageKey, whiteLum, middleGrey);
587        }
588
589        /// compute lense flare
590        LenseFlare(fbo, light);
591
592        const bool saveFrame = (mSavedFrameNumber != -1);
593        const bool displayAfterAA = !saveFrame;
594
595        // multisampling is difficult / costly with deferred shading
596        // at least do some edge blurring
597        if (useAntiAliasing) AntiAliasing(fbo, light, displayAfterAA);
598       
599        /// store the current frame
600        if (saveFrame) SaveFrame(fbo);
601
602        // if it hasn't been done yet => just output the latest buffer
603        if (!useAntiAliasing || !displayAfterAA)
604                Output(fbo);
605
606        glEnable(GL_LIGHTING);
607        glDisable(GL_TEXTURE_2D);
608
609        glMatrixMode(GL_PROJECTION);
610        glPopMatrix();
611
612        glMatrixMode(GL_MODELVIEW);
613        glPopMatrix();
614
615        // viewport
616        glPopAttrib();
617
618        FrameBufferObject::Release();
619        ShaderManager::GetSingleton()->DisableFragmentProfile();
620}
621
622
623void DeferredRenderer::PrepareSsaoFilter()
624{
625        const float filterWidth = 1.0f;
626
627        PoissonDiscSampleGenerator2 poisson(NUM_SSAO_FILTER_SAMPLES, 1.0f);
628        poisson.Generate((float *)ssaoFilterOffsets);
629
630        const float xoffs = (float)filterWidth / mWidth;
631        const float yoffs = (float)filterWidth / mHeight;
632
633        for (int i = 0; i < NUM_SSAO_FILTER_SAMPLES; ++ i)
634        {
635                float x = ssaoFilterOffsets[2 * i + 0];
636                float y = ssaoFilterOffsets[2 * i + 1];
637
638                ssaoFilterWeights[i] = GaussianDistribution(x, y, 1.0f);
639                //ssaoFilterWeights[i] = 1.0f;
640
641                ssaoFilterOffsets[2 * i + 0] *= xoffs;
642                ssaoFilterOffsets[2 * i + 1] *= yoffs;
643        }
644}
645
646
647static inline float SqrMag(const Sample2 &s)
648{
649        return (s.x * s.x + s.y * s.y);
650}
651
652
653static inline float SqrDist(const Sample2 &a, const Sample2 &b)
654{
655        float x = a.x - b.x;
656        float y = a.y - b.y;
657       
658        return x * x + y * y;
659}
660
661
662static inline bool lt(const Sample2 &a, const Sample2 &b)
663{
664        return SqrMag(a) < SqrMag(b);
665}
666
667
668void DeferredRenderer::SortSamples()
669{
670        static Sample2 tempSamples[NUM_SAMPLES];
671        static bool checked[NUM_SAMPLES];
672
673        for (int i = 0; i < NUM_SAMPLES; ++ i)
674                checked[i] = false;
675
676        Sample2 currentSample;
677        currentSample.x = 0; currentSample.y = 0;
678        int ns = 0; // the next sample index
679
680        for (int i = 0; i < NUM_SAMPLES; ++ i)
681        {
682                float minLen = 1e20f;
683
684                for (int j = 0; j < NUM_SAMPLES; ++ j)
685                {
686                        if (checked[j]) continue;
687
688                        Sample2 s = samples2[j];
689                        const float len = SqrDist(s, currentSample);
690
691                        if (len < minLen)
692                        {
693                                minLen = len;
694                                ns = j;
695                        }
696                }
697
698                tempSamples[i] = samples2[ns];
699                currentSample = samples2[ns];
700                checked[ns] = true;
701        }
702
703        for (int i = 0; i < NUM_SAMPLES; ++ i)
704                samples2[i] = tempSamples[i];
705}
706
707
708void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo, float tempCohFactor)
709{
710        GLuint colorsTex, normalsTex, attribsTex;
711
712        if (0)
713        {
714                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
715                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
716        }
717        else
718        {
719                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
720                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
721        }
722
723        attribsTex = fbo->GetColorBuffer(2)->GetTexture();
724
725        // flip flop between illumination buffers
726        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
727
728        glPushAttrib(GL_VIEWPORT_BIT);
729        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
730
731        // read the second buffer, write to the first buffer
732        mIllumFbo->Bind();
733        glDrawBuffers(1, mrt + mIllumFboIndex);
734
735        int i = 0;
736
737        sCgSsaoProgram->SetTexture(i ++, colorsTex);
738        sCgSsaoProgram->SetTexture(i ++, normalsTex);
739        sCgSsaoProgram->SetTexture(i ++, oldTex);
740        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
741
742        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
743       
744        if (mUseTemporalCoherence || mRegenerateSamples)
745        {
746                mRegenerateSamples = false;
747
748                // q: should we generate new samples or only rotate the old ones?
749                // in the first case, the sample patterns look nicer, but the kernel
750                // needs longer to converge
751                GenerateSamples(mSamplingMethod);
752
753                //if (mSortSamples) { SortSamples(); }
754                sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
755        }
756       
757        ++ i;
758
759        for (int j = 0; j < 4; ++ j, ++ i)
760                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
761
762        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
763        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
764
765        Vector3 de;
766        de.x = mOldEyePos.x - mEyePos.x;
767        de.y = mOldEyePos.y - mEyePos.y;
768        de.z = mOldEyePos.z - mEyePos.z;
769
770        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
771
772        for (int j = 0; j < 4; ++ j, ++ i)
773        {
774                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
775        }
776
777        sCgSsaoProgram->SetTexture(i ++, attribsTex);
778        sCgSsaoProgram->SetValue1f(i ++, mKernelRadius);
779        sCgSsaoProgram->SetValue1f(i ++, mSampleIntensity);
780
781
782        DrawQuad(sCgSsaoProgram);
783
784        glPopAttrib();
785
786        PrintGLerror("ssao first pass");
787}
788
789
790static void SetVertex(float x, float y, float x_offs, float y_offs)
791{
792        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
793        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
794        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
795        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
796        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
797
798        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
799        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
800
801        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
802        glVertex2f(x, y);
803}
804
805
806void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo,
807                                                                        DirectionalLight *light,
808                                                                        bool displayFrame)
809{
810        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
811        GLuint colorsTex = colorBuffer->GetTexture();
812        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
813
814        // read the second buffer, write to the first buffer
815        if (!displayFrame)
816                FlipFbos(fbo);
817        else
818                // end of the pipeline => just draw image to screen
819                FrameBufferObject::Release();
820
821        // the neighbouring texels
822        float xOffs = 1.0f / fbo->GetWidth();
823        float yOffs = 1.0f / fbo->GetHeight();
824
825        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
826        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
827
828        float offsets[16];
829        int i = 0;
830
831        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
832        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
833        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
834        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
835        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
836        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
837        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
838        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
839
840        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
841
842        DrawQuad(sCgAntiAliasingProgram);
843
844        PrintGLerror("antialiasing");
845}
846
847
848void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
849{
850        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
851        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
852
853        FlipFbos(fbo);
854
855        const Vector3 lightDir = -light->GetDirection();
856
857        sCgDeferredProgram->SetTexture(0, colorsTex);
858        sCgDeferredProgram->SetTexture(1, normalsTex);
859        sCgDeferredProgram->SetValue3f(2, lightDir.x, lightDir.y, lightDir.z);
860       
861        DrawQuad(sCgDeferredProgram);
862
863        PrintGLerror("deferred shading");
864}
865
866
867void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
868                                                                                float tempCohFactor)
869{
870#if 0
871        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
872        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
873#else
874        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
875        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
876#endif
877
878        glPushAttrib(GL_VIEWPORT_BIT);
879        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
880
881        // read the second buffer, write to the first buffer
882        mIllumFbo->Bind();
883
884        glDrawBuffers(2, mrt + mIllumFboIndex);
885
886        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
887        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
888
889        int i = 0;
890
891        sCgGiProgram->SetTexture(i ++, colorsTex);
892        sCgGiProgram->SetTexture(i ++, normalsTex);
893        sCgGiProgram->SetTexture(i ++, noiseTex2D);
894        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
895        sCgGiProgram->SetTexture(i ++, oldIllumTex);
896
897        sCgGiProgram->SetValue1f(i ++,
898                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
899
900        if (mUseTemporalCoherence || mRegenerateSamples)
901        {
902                mRegenerateSamples = false;
903
904                // q: should we generate new samples or only rotate the old ones?
905                // in the first case, the sample patterns look nicer, but the kernel
906                // needs longer to converge
907                GenerateSamples(mSamplingMethod);
908
909                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
910        }
911
912        Vector3 bl = mCornersView[0];
913        Vector3 br = mCornersView[1];
914        Vector3 tl = mCornersView[2];
915        Vector3 tr = mCornersView[3];
916
917        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
918        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
919        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
920        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
921
922        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
923        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
924
925
926        DrawQuad(sCgGiProgram);
927
928        glPopAttrib();
929
930        PrintGLerror("globillum first pass");
931}
932
933
934void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
935{
936        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
937
938        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
939        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
940
941        FlipFbos(fbo);
942
943        sCgCombineIllumProgram->SetTexture(0, colorsTex);
944        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
945        sCgCombineIllumProgram->SetTexture(2, illumTex);
946       
947        DrawQuad(sCgCombineIllumProgram);
948
949        PrintGLerror("combine");
950}
951
952
953void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
954{
955        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
956        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
957        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
958       
959        FlipFbos(fbo);
960
961        int i = 0;
962
963        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
964        sCgCombineSsaoProgram->SetTexture(i ++, normalsTex);
965        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
966
967        sCgCombineSsaoProgram->SetArray2f(i ++, (float *)ssaoFilterOffsets, NUM_SSAO_FILTER_SAMPLES);
968        sCgCombineSsaoProgram->SetArray1f(i ++, (float *)ssaoFilterWeights, NUM_SSAO_FILTER_SAMPLES);
969        sCgCombineSsaoProgram->SetValue1f(i ++, mSsaoFilterRadius);
970
971        sCgCombineSsaoProgram->SetMatrix(i++, mProjViewMatrix);
972
973        for (int j = 0; j < 4; ++ j, ++ i)
974                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
975
976        sCgCombineSsaoProgram->SetValue1f(i ++, mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetWidth());
977        sCgCombineSsaoProgram->SetValue1f(i ++, mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetHeight());
978
979        DrawQuad(sCgCombineSsaoProgram);
980       
981        PrintGLerror("combine ssao");
982}
983
984
985void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
986                                                                           DirectionalLight *light,
987                                                                           ShadowMap *shadowMap)
988{
989        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
990        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
991
992        GLuint shadowTex = shadowMap->GetDepthTexture();
993
994        Matrix4x4 shadowMatrix;
995        shadowMap->GetTextureMatrix(shadowMatrix);
996
997
998        FlipFbos(fbo);
999
1000        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
1001        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
1002        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
1003        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
1004        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
1005        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
1006
1007        const Vector3 lightDir = -light->GetDirection();
1008        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
1009        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
1010
1011        DrawQuad(sCgDeferredShadowProgram);
1012
1013        PrintGLerror("deferred shading + shadows");
1014}
1015
1016
1017void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
1018                                                                                         DirectionalLight *light,
1019                                                                                         float &imageKey,
1020                                                                                         float &whiteLum,
1021                                                                                         float &middleGrey)
1022{
1023        // hack: estimate value where sky burns out
1024        whiteLum = log(WHITE_LUMINANCE);
1025       
1026        ////////////////////
1027        //-- linear interpolate brightness key depending on the current sun position
1028
1029        const float minKey = 0.09f;
1030        const float maxKey = 0.36f;
1031
1032        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
1033        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
1034
1035
1036        //////////
1037        //-- compute avg loglum
1038
1039        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1040        GLuint colorsTex = colorBuffer->GetTexture();
1041
1042        FlipFbos(fbo);
1043       
1044        sCgLogLumProgram->SetTexture(0, colorsTex);
1045        DrawQuad(sCgLogLumProgram);
1046       
1047        PrintGLerror("ToneMapParams");
1048
1049
1050        ///////////////////
1051        //-- compute avg loglum in scene using mipmapping
1052
1053        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
1054        glGenerateMipmapEXT(GL_TEXTURE_2D);
1055}
1056
1057
1058static void ExportData(float *data, int w, int h)
1059{
1060        startil();
1061
1062        cout << "w: " << w << " h: " << h << endl;
1063        ILstring filename = ILstring("downsample2.jpg");
1064        ilRegisterType(IL_FLOAT);
1065
1066        const int depth = 1;
1067        const int bpp = 4;
1068
1069        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1070        {
1071                cerr << "IL error " << ilGetError() << endl;
1072                stopil();
1073                return;
1074        }
1075
1076        if (!ilSaveImage(filename))
1077        {
1078                cerr << "TGA write error " << ilGetError() << endl;
1079        }
1080
1081        stopil();
1082}
1083
1084
1085void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1086{
1087        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1088        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1089        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1090        // flip flop between illumination buffers
1091        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1092
1093        int i = 0;
1094
1095        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1096        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1097        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1098        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1099
1100        Vector3 de;
1101        de.x = mOldEyePos.x - mEyePos.x;
1102        de.y = mOldEyePos.y - mEyePos.y;
1103        de.z = mOldEyePos.z - mEyePos.z;
1104
1105        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1106
1107        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1108        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1109
1110        for (int j = 0; j < 4; ++ j, ++ i)
1111                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1112
1113        glPushAttrib(GL_VIEWPORT_BIT);
1114        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1115       
1116        mDownSampleFbo->Bind();
1117
1118        // prepare downsampled depth and normal texture for ssao
1119        glDrawBuffers(2, mrt);
1120
1121        DrawQuad(sCgPrepareSsaoProgram);
1122       
1123        glPopAttrib();
1124        PrintGLerror("prepareSsao");
1125}
1126
1127
1128void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1129                                                                  int bufferIdx,
1130                                                                  FrameBufferObject *downSampleFbo,
1131                                                                  int downSampleBufferIdx,
1132                                                                  ShaderProgram *program)
1133{
1134        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1135        GLuint tex = buffer->GetTexture();
1136
1137        glPushAttrib(GL_VIEWPORT_BIT);
1138        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1139       
1140        downSampleFbo->Bind();
1141
1142        program->SetTexture(0, tex);
1143        glDrawBuffers(1, mrt + downSampleBufferIdx);
1144
1145        DrawQuad(program);
1146       
1147        glPopAttrib();
1148        PrintGLerror("downsample");
1149}
1150
1151
1152void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1153                                                           float imageKey,
1154                                                           float whiteLum,
1155                                                           float middleGrey)
1156{
1157        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1158        GLuint colorsTex = colorBuffer->GetTexture();
1159        //FrameBufferObject::Release();
1160
1161        FlipFbos(fbo);
1162
1163        sCgToneProgram->SetTexture(0, colorsTex);
1164        sCgToneProgram->SetValue1f(1, imageKey);
1165        sCgToneProgram->SetValue1f(2, whiteLum);
1166        sCgToneProgram->SetValue1f(3, middleGrey);
1167
1168        DrawQuad(sCgToneProgram);
1169
1170        PrintGLerror("ToneMap");
1171}
1172
1173
1174void DeferredRenderer::Output(FrameBufferObject *fbo)
1175{
1176        glPushAttrib(GL_VIEWPORT_BIT);
1177        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1178       
1179        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1180        GLuint colorsTex = colorBuffer->GetTexture();
1181
1182        sCgDownSampleProgram->SetTexture(0, colorsTex);
1183
1184        FrameBufferObject::Release();
1185        DrawQuad(sCgDownSampleProgram);
1186
1187        PrintGLerror("output");
1188}
1189
1190
1191void DeferredRenderer::InitFrame()
1192{
1193        for (int i = 0; i < 4; ++ i)
1194                mOldCornersView[i] = mCornersView[i];
1195
1196        mOldProjViewMatrix = mProjViewMatrix;
1197        mOldEyePos = mEyePos;
1198        mEyePos = mCamera->GetPosition();
1199
1200        // hack: temporarily change far to improve precision
1201        const float oldFar = mCamera->GetFar();
1202        const float oldNear = mCamera->GetNear();
1203       
1204
1205        Matrix4x4 matViewing, matProjection;
1206
1207
1208        ///////////////////
1209
1210        // use view orientation as we assume that the eye point is always in the center
1211        // of our coordinate system, this way we have the highest precision near the eye point
1212        mCamera->GetViewOrientationMatrix(matViewing);
1213        mCamera->GetProjectionMatrix(matProjection);
1214
1215        mProjViewMatrix = matViewing * matProjection;
1216        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1217       
1218
1219        // switch roles of old and new fbo
1220        // the algorihm uses two input fbos, where the one
1221        // contais the color buffer from the last frame,
1222        // the other one will be written
1223
1224        mIllumFboIndex = 2 - mIllumFboIndex;
1225       
1226        // enable fragment shading
1227        ShaderManager::GetSingleton()->EnableFragmentProfile();
1228
1229        glDisable(GL_ALPHA_TEST);
1230        glDisable(GL_TEXTURE_2D);
1231        glDisable(GL_LIGHTING);
1232        glDisable(GL_BLEND);
1233        glDisable(GL_DEPTH_TEST);
1234
1235        glPolygonMode(GL_FRONT, GL_FILL);
1236
1237        glMatrixMode(GL_PROJECTION);
1238        glPushMatrix();
1239        glLoadIdentity();
1240
1241        gluOrtho2D(0, 1, 0, 1);
1242
1243
1244        glMatrixMode(GL_MODELVIEW);
1245        glPushMatrix();
1246        glLoadIdentity();
1247
1248       
1249        glPushAttrib(GL_VIEWPORT_BIT);
1250        glViewport(0, 0, mWidth, mHeight);
1251
1252        // revert to old far and near plane
1253        mCamera->SetFar(oldFar);
1254        mCamera->SetNear(oldNear);
1255}
1256
1257
1258void DeferredRenderer::LenseFlare(FrameBufferObject *fbo,
1259                                                                  DirectionalLight *light                                                       
1260                                                                  )
1261{
1262        // light source not visible
1263        if (!mSunVisiblePixels) return;
1264
1265        // the sun is a large distance in the reverse light direction
1266        // => extrapolate light pos
1267        const Vector3 lightPos = light->GetDirection() * -1e3f;
1268
1269        float w;
1270        Vector3 projLightPos = mProjViewMatrix.Transform(w, lightPos, 1.0f);
1271        projLightPos /= w;
1272        projLightPos = projLightPos * 0.5f + Vector3(0.5f);
1273
1274        // vector to light from screen center in texture space
1275        Vector3 vectorToLight = projLightPos - Vector3(0.5f);
1276        vectorToLight.z = .0f;
1277
1278        const float distanceToLight = Magnitude(vectorToLight);
1279        vectorToLight /= distanceToLight;
1280
1281        //cout << "dist " << distanceToLight << " v " << vectorToLight << endl;
1282
1283
1284        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1285        GLuint colorsTex = colorBuffer->GetTexture();
1286       
1287        FlipFbos(fbo);
1288
1289        int i = 0;
1290
1291        sCgLenseFlareProgram->SetTexture(i ++, colorsTex);
1292        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[0]->GetId());
1293        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[1]->GetId());
1294        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[2]->GetId());
1295        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[3]->GetId());
1296        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[4]->GetId());
1297        sCgLenseFlareProgram->SetValue2f(i ++, vectorToLight.x, vectorToLight.y);
1298        sCgLenseFlareProgram->SetValue1f(i ++, distanceToLight);
1299        sCgLenseFlareProgram->SetValue1f(i ++, (float)mSunVisiblePixels);
1300
1301        DrawQuad(sCgLenseFlareProgram);
1302
1303        PrintGLerror("LenseFlare");
1304}
1305
1306
1307void DeferredRenderer::SaveFrame(FrameBufferObject *fbo)
1308{
1309        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1310        GLuint colorsTex = colorBuffer->GetTexture();
1311
1312        GLubyte *data = new GLubyte[mWidth * mHeight * 4];
1313
1314        // grab texture data
1315        glEnable(GL_TEXTURE_2D);
1316        glBindTexture(GL_TEXTURE_2D, colorsTex);
1317        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
1318
1319        glBindTexture(GL_TEXTURE_2D, 0);
1320        glDisable(GL_TEXTURE_2D);
1321
1322        /////////////////
1323
1324        startil();
1325
1326        static char imageName[200];
1327        sprintf(imageName, "%s_%05d.bmp", mSavedFrameSuffix.c_str(), mSavedFrameNumber);
1328
1329        ILstring fileName = ILstring(imageName);
1330        ilRegisterType(IL_FLOAT);
1331
1332        const int depth = 1;
1333        const int bpp = 4;
1334
1335        if (!ilTexImage(mWidth, mHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data))
1336        {
1337                cerr << "IL error " << ilGetError() << endl;
1338                stopil();
1339                return;
1340        }
1341
1342        ilEnable(IL_FILE_OVERWRITE);
1343
1344        if (!ilSaveImage(fileName))
1345        {
1346                cerr << "TGA write error " << ilGetError() << endl;
1347        }
1348
1349        delete [] data;
1350
1351        stopil();
1352
1353        PrintGLerror("Store frame");
1354}
1355
1356
1357void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
1358{
1359        mUseTemporalCoherence = temporal;
1360}
1361
1362
1363void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
1364{
1365        if (s != mSamplingMethod)
1366        {
1367                mSamplingMethod = s;
1368                mRegenerateSamples = true;
1369        }
1370}
1371
1372
1373void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
1374{
1375        if (s != mShadingMethod)
1376        {
1377                mShadingMethod = s;
1378                mRegenerateSamples = true;
1379        }
1380}
1381
1382
1383#if TODO
1384
1385void DeferredRenderer::SetNumSamples(int numSamples)
1386{
1387        mNumSamples = numSamples;
1388}
1389
1390#endif
1391
1392
1393void DeferredRenderer::SetSampleIntensity(float sampleIntensity)
1394{
1395        mSampleIntensity = sampleIntensity;
1396}
1397
1398
1399void DeferredRenderer::SetKernelRadius(float kernelRadius)
1400{
1401        mKernelRadius = kernelRadius;
1402}
1403
1404
1405void DeferredRenderer::SetSsaoFilterRadius(float ssaoFilterRadius)
1406{
1407        mSsaoFilterRadius = ssaoFilterRadius;
1408}
1409
1410
1411void DeferredRenderer::SetSortSamples(bool sortSamples)
1412{
1413        mSortSamples = sortSamples;
1414}
1415
1416
1417void DeferredRenderer::SetSunVisiblePixels(int pixels)
1418{
1419        mSunVisiblePixels = pixels;
1420}
1421
1422
1423void DeferredRenderer::SetSaveFrame(const string &suffix, int frameNumber)
1424{
1425        mSavedFrameSuffix = suffix;
1426        mSavedFrameNumber = frameNumber;
1427}
1428
1429
1430} // namespace
Note: See TracBrowser for help on using the repository browser.