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

Revision 3309, 39.5 KB checked in by mattausch, 15 years ago (diff)

working on changed sampling scheme for temporal coherence

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