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

Revision 3345, 42.3 KB checked in by mattausch, 15 years ago (diff)

trying to reduce render targets but something srange

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