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

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