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

Revision 3367, 43.1 KB checked in by mattausch, 15 years ago (diff)

working nicely but still artifacts where high convergence regions come on low convergence ones

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#if 1
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        mTempFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
450        FrameBufferObject::InitBuffer(mTempFbo, 0);
451        FrameBufferObject::InitBuffer(mTempFbo, 1);
452       
453
454        // create noise texture for ssao
455        // for performance reasons we use a smaller texture and repeat it over the screen
456        CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
457               
458        mProjViewMatrix = IdentityMatrix();
459        mOldProjViewMatrix = IdentityMatrix();
460
461        for (int i = 0; i < 4; ++ i)
462        {
463                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
464        }
465
466        mEyePos = mOldEyePos = Vector3::ZERO();
467
468        PrepareLenseFlare();
469#endif
470        InitCg();
471}
472
473
474DeferredRenderer::~DeferredRenderer()
475{
476        CLEAR_CONTAINER(mFBOs);
477
478        glDeleteTextures(1, &noiseTex2D);
479        glDeleteTextures(1, &noiseTex1D);
480}
481
482
483void DeferredRenderer::InitCg()
484{       
485        ShaderManager *sm = ShaderManager::GetSingleton();
486
487        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "DeferredFrag");
488        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "DeferredFragShadow");
489        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "SsaoFrag");
490        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "GiFrag");
491        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "CombineGi");
492
493        if (mSsaoUseFullResolution)
494        {
495                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoFullRes", "FilterSsao");
496        }
497        else
498        {
499                sCgFilterSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "FilterSsaoHalfRes", "FilterSsao");
500        }
501       
502        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsaoSep", "CombineSsao", "CombineSsao");
503        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "AntiAliasing");
504        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "ToneMap");
505        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
506        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
507        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "AvgLogLum");
508        sCgPrepareSsaoProgram = sm->CreateFragmentProgram("deferred", "PrepareSsao", "PrepareSsao");
509        sCgLenseFlareProgram = sm->CreateFragmentProgram("lenseFlare", "LenseFlare", "LenseFlare");
510        sCgDOFProgram = sm->CreateFragmentProgram("depthOfField", "DepthOfField", "DepthOfField");
511
512
513        ///////////////////
514        //-- initialize program parameters
515
516        string ssaoParams[] =
517                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
518                 "samples", "bl", "br", "tl", "tr",
519                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
520                 "oldtl", "oldtr", "attribsTex", "kernelRadius", "sampleIntensity",
521             "dummyIdx"};
522       
523        sCgSsaoProgram->AddParameters(ssaoParams, 0, 21);
524       
525        string giParams[] =
526                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
527                 "temporalCoherence", "samples", "bl", "br", "tl",
528                 "tr", "oldModelViewProj", "modelViewProj"};
529
530        sCgGiProgram->AddParameters(giParams, 0, 13);
531
532        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
533        sCgToneProgram->AddParameters(toneParams, 0, 4);
534
535
536        ////////////////
537
538        string deferredShadowParams[] =
539                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
540                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
541       
542        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
543       
544        ////////////////
545
546        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
547        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
548
549        ////////////////
550
551        string combineSsaoParams[] =
552                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
553
554        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 9);
555
556       
557        ////////////////
558
559        string filterSsaoParams[] =
560                {"colorsTex", "ssaoTex", "bl", "br", "tl", "tr", "res", "maxConvergence", "spatialWeight"};
561        sCgFilterSsaoProgram->AddParameters(filterSsaoParams, 0, 9);
562
563
564        //////////////
565
566        string deferredParams[] = {"colors", "normals", "lightDir", "aoTex", "useAO"};
567        sCgDeferredProgram->AddParameters(deferredParams, 0, 5);
568
569        ///////////////////
570
571        string aaParams[] = {"colors", "normals", "offsets"};
572        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
573
574        /////////////////////
575
576        string downSampleParams[] = {"colors"};
577        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
578
579        /////////////////////
580
581        string scaleDepthParams[] = {"colors"};
582        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
583
584        ////////////
585
586        sCgLogLumProgram->AddParameter("colors", 0);
587
588        ////////////////
589
590       
591        string prepareSsaoParams[] =
592                {"colorsTex", "normalsTex", "diffVals", "oldTex",
593                 "oldEyePos", "modelViewProj", "oldModelViewProj",
594                 "oldbl", "oldbr", "oldtl", "oldtr", "myTex"};
595        sCgPrepareSsaoProgram->AddParameters(prepareSsaoParams, 0, 12);
596
597
598        ////////////////
599       
600        string lenseFlareParams[] =
601                {"colorsTex", "flareTex1", "flareTex2", "flareTex3", "flareTex4",
602                 "flareTex5", "vectorToLight", "distanceToLight", "sunVisiblePixels"};
603
604        sCgLenseFlareProgram->AddParameters(lenseFlareParams, 0, 9);
605
606       
607        ////////////////
608       
609        string dofParams[] = {"colorsTex", "filterOffs", "sceneRange", "zFocus"};
610
611        sCgDOFProgram->AddParameters(dofParams, 0, 4);
612
613
614        /////////
615        //-- pcf tabs for shadowing
616
617        float filterWeights[NUM_PCF_TABS];
618        PoissonDiscSampleGenerator2D poisson2(NUM_PCF_TABS, 1.0f);
619        poisson2.Generate((float *)pcfSamples);
620
621        for (int i = 0; i < NUM_PCF_TABS; ++ i)
622        {
623                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
624        }
625
626        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
627        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
628
629
630        /////////
631        //-- pcf tabs for depth of field
632
633        // todo matt: it is stupid to put num samples and width of kernel into constructor => change this!!!
634        PoissonDiscSampleGenerator2D poisson3(NUM_DOF_TABS, 1.0f);
635        poisson3.Generate((float *)dofSamples);
636
637        for (int i = 0; i < NUM_DOF_TABS; ++ i)
638        {
639                dofSamples[i].x *= 1.0f / mWidth;
640                dofSamples[i].y *= 1.0f / mHeight;
641        }
642
643        //float dofWeights[NUM_PCF_TABS];
644        //sCgDOFProgram->SetArray1f(2, (float *)dofWeights, NUM_DOF_TABS);
645
646        PrintGLerror("init");
647}
648
649
650void DeferredRenderer::Render(FrameBufferObject *fbo,
651                                                          DirectionalLight *light,
652                                                          ShadowMap *shadowMap
653                                                          )
654{
655        InitFrame();
656
657        /*if (shadowMap)
658                FirstPassShadow(fbo, light, shadowMap);
659        else
660                FirstPass(fbo, light);
661        */
662
663        if (mShadingMethod != DEFAULT)
664        {
665                PrepareSsao(fbo); // downsample fbo buffers
666        }
667
668        // q: use antialiasing before or after ssao?
669        //if (useAntiAliasing) AntiAliasing(fbo, light);
670
671        switch (mShadingMethod)
672        {
673        case SSAO:
674                ComputeSsao(fbo, mTempCohFactor);
675                FilterSsao(fbo);
676                CombineSsao(fbo);
677
678                break;
679        case GI:
680                ComputeGlobIllum(fbo, mTempCohFactor);
681                CombineIllum(fbo);
682                break;
683        default:
684                // do nothing: standard deferred shading
685                break;
686        }
687
688        if (shadowMap)
689                FirstPassShadow(fbo, light, shadowMap);
690        else
691                FirstPass(fbo, light);
692
693        /// depth of field
694        if (mUseDepthOfField)
695        {
696                DepthOfField(fbo);
697        }
698
699        if (mUseToneMapping)
700        {
701                float imageKey, whiteLum, middleGrey;
702
703                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
704                ToneMap(fbo, imageKey, whiteLum, middleGrey);
705        }
706
707        /// compute lense flare
708        LenseFlare(fbo, light);
709
710        const bool saveFrame = (mSavedFrameNumber != -1);
711        const bool displayAfterAA = !saveFrame;
712
713        // multisampling is difficult / costly with deferred shading
714        // at least do some edge blurring
715        if (mUseAntiAliasing) AntiAliasing(fbo, light, displayAfterAA);
716       
717        /// store the current frame
718        if (saveFrame) SaveFrame(fbo);
719
720        // if it hasn't been done yet => just output the latest buffer
721        if (!mUseAntiAliasing || !displayAfterAA)
722        {
723                Output(fbo);
724        }
725
726        glEnable(GL_LIGHTING);
727        glDisable(GL_TEXTURE_2D);
728
729        glMatrixMode(GL_PROJECTION);
730        glPopMatrix();
731
732        glMatrixMode(GL_MODELVIEW);
733        glPopMatrix();
734
735        // viewport
736        glPopAttrib();
737
738        FrameBufferObject::Release();
739        ShaderManager::GetSingleton()->DisableFragmentProfile();
740}
741
742
743static inline float SqrMag(const Sample2 &s)
744{
745        return (s.x * s.x + s.y * s.y);
746}
747
748
749static inline float SqrDist(const Sample2 &a, const Sample2 &b)
750{
751        float x = a.x - b.x;
752        float y = a.y - b.y;
753       
754        return x * x + y * y;
755}
756
757
758static inline bool lt(const Sample2 &a, const Sample2 &b)
759{
760        return SqrMag(a) < SqrMag(b);
761}
762
763
764void DeferredRenderer::SortSamples()
765{
766        static Sample2 tempSamples[NUM_SAMPLES];
767        static bool checked[NUM_SAMPLES];
768
769        for (int i = 0; i < NUM_SAMPLES; ++ i)
770                checked[i] = false;
771
772        Sample2 currentSample;
773        currentSample.x = 0; currentSample.y = 0;
774        int ns = 0; // the next sample index
775
776        for (int i = 0; i < NUM_SAMPLES; ++ i)
777        {
778                float minLen = 1e20f;
779
780                for (int j = 0; j < NUM_SAMPLES; ++ j)
781                {
782                        if (checked[j]) continue;
783
784                        Sample2 s = samples2[j];
785                        const float len = SqrDist(s, currentSample);
786
787                        if (len < minLen)
788                        {
789                                minLen = len;
790                                ns = j;
791                        }
792                }
793
794                tempSamples[i] = samples2[ns];
795                currentSample = samples2[ns];
796
797                checked[ns] = true;
798        }
799
800        for (int i = 0; i < NUM_SAMPLES; ++ i)
801                samples2[i] = tempSamples[i];
802}
803
804
805void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo, float tempCohFactor)
806{
807        GLuint colorsTex, normalsTex, attribsTex;
808
809        if (0)
810        {
811                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
812                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
813        }
814        else
815        {
816                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
817                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
818        }
819
820        attribsTex = fbo->GetColorBuffer(2)->GetTexture();
821
822
823        /////////
824        //-- flip flop between illumination buffers
825
826        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
827
828        glPushAttrib(GL_VIEWPORT_BIT);
829        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
830
831        // read the second buffer, write to the first buffer
832        mIllumFbo->Bind();
833        glDrawBuffers(1, mrt + mIllumFboIndex);
834
835        int i = 0;
836
837        sCgSsaoProgram->SetTexture(i ++, colorsTex);
838        sCgSsaoProgram->SetTexture(i ++, normalsTex);
839        sCgSsaoProgram->SetTexture(i ++, oldSsaoTex);
840        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
841
842        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
843       
844
845        if (/*mUseTemporalCoherence || */mRegenerateSamples)
846        {
847                mRegenerateSamples = false;
848
849                // q: should we generate new samples or only rotate the old ones?
850                // in the first case, the sample patterns look nicer, but the kernel
851                // needs longer to converge
852                GenerateSamples(mSamplingMethod);
853
854                if (!sampleTex2D)
855                {
856                        CreateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
857                }
858                else
859                {
860                        UpdateSampleTex(samples2, NUM_PRECOMPUTED_SAMPLES);
861                }
862
863                //if (mSortSamples) { SortSamples(); }
864                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
865                //sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_PRECOMPUTED_SAMPLES);
866        }
867
868        sCgSsaoProgram->SetTexture(i, sampleTex2D);
869
870        ++ i;
871
872        for (int j = 0; j < 4; ++ j, ++ i)
873        {
874                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
875        }
876
877        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
878        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
879
880        Vector3 de;
881        de.x = mOldEyePos.x - mEyePos.x;
882        de.y = mOldEyePos.y - mEyePos.y;
883        de.z = mOldEyePos.z - mEyePos.z;
884
885        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
886
887        for (int j = 0; j < 4; ++ j, ++ i)
888        {
889                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
890        }
891
892        sCgSsaoProgram->SetTexture(i ++, attribsTex);
893        sCgSsaoProgram->SetValue1f(i ++, mKernelRadius);
894        sCgSsaoProgram->SetValue1f(i ++, mSampleIntensity * mKernelRadius);
895
896        static int dummyIdx = 0;
897        sCgSsaoProgram->SetValue1f(i ++, dummyIdx);
898        dummyIdx += NUM_SAMPLES;
899
900        DrawQuad(sCgSsaoProgram);
901        glPopAttrib();
902
903        PrintGLerror("ssao first pass");
904}
905
906
907static void SetVertex(float x, float y, float x_offs, float y_offs)
908{
909        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
910        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
911        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
912        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
913        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
914
915        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
916        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
917
918        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
919        glVertex2f(x, y);
920}
921
922
923void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo,
924                                                                        DirectionalLight *light,
925                                                                        bool displayFrame)
926{
927        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
928        GLuint colorsTex = colorBuffer->GetTexture();
929        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
930
931        // read the second buffer, write to the first buffer
932        if (!displayFrame)
933        {
934                FlipFbos(fbo);
935        }
936        else
937        {
938                // end of the pipeline => just draw image to screen
939                FrameBufferObject::Release();
940        }
941
942        // the neighbouring texels
943        float xOffs = 1.0f / fbo->GetWidth();
944        float yOffs = 1.0f / fbo->GetHeight();
945
946        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
947        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
948
949        float offsets[16];
950        int i = 0;
951
952        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
953        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
954        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
955        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
956        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
957        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
958        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
959        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
960
961        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
962
963        DrawQuad(sCgAntiAliasingProgram);
964
965        PrintGLerror("antialiasing");
966}
967
968
969void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
970{
971        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
972        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
973        //GLuint aoTex = fbo->GetColorBuffer(1)->GetTexture();
974        GLuint aoTex = mTempFbo->GetColorBuffer(1)->GetTexture();
975
976        FlipFbos(fbo);
977
978        const Vector3 lightDir = -light->GetDirection();
979
980        int i = 0;
981        sCgDeferredProgram->SetTexture(i ++, colorsTex);
982        sCgDeferredProgram->SetTexture(i ++, normalsTex);
983        sCgDeferredProgram->SetValue3f(i ++, lightDir.x, lightDir.y, lightDir.z);
984        sCgDeferredProgram->SetTexture(i ++, aoTex);
985        sCgDeferredProgram->SetValue1f(i ++, float(mShadingMethod == SSAO));
986
987        DrawQuad(sCgDeferredProgram);
988
989        PrintGLerror("deferred shading");
990}
991
992
993void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
994                                                                                float tempCohFactor)
995{
996#if 0
997        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
998        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
999#else
1000        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
1001        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
1002#endif
1003
1004        glPushAttrib(GL_VIEWPORT_BIT);
1005        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
1006
1007        // read the second buffer, write to the first buffer
1008        mIllumFbo->Bind();
1009        glDrawBuffers(2, mrt + mIllumFboIndex);
1010
1011        // bind the old buffers for temporal coherence
1012        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1013        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1014
1015        int i = 0;
1016
1017        sCgGiProgram->SetTexture(i ++, colorsTex);
1018        sCgGiProgram->SetTexture(i ++, normalsTex);
1019        sCgGiProgram->SetTexture(i ++, noiseTex2D);
1020        sCgGiProgram->SetTexture(i ++, oldSsaoTex);
1021        sCgGiProgram->SetTexture(i ++, oldIllumTex);
1022
1023        sCgGiProgram->SetValue1f(i ++,
1024                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
1025
1026        if (mUseTemporalCoherence || mRegenerateSamples)
1027        {
1028                mRegenerateSamples = false;
1029
1030                // q: should we generate new samples or only rotate the old ones?
1031                // in the first case, the sample patterns look nicer, but the kernel
1032                // needs longer to converge
1033                GenerateSamples(mSamplingMethod);
1034
1035                sCgGiProgram->SetArray2f(i ++, (float *)samples2, NUM_SAMPLES);
1036        }
1037
1038        Vector3 bl = mCornersView[0];
1039        Vector3 br = mCornersView[1];
1040        Vector3 tl = mCornersView[2];
1041        Vector3 tr = mCornersView[3];
1042
1043        sCgGiProgram->SetValue3f(i ++, bl.x, bl.y, bl.z);
1044        sCgGiProgram->SetValue3f(i ++, br.x, br.y, br.z);
1045        sCgGiProgram->SetValue3f(i ++, tl.x, tl.y, tl.z);
1046        sCgGiProgram->SetValue3f(i ++, tr.x, tr.y, tr.z);
1047
1048        sCgGiProgram->SetMatrix(i ++, mOldProjViewMatrix);
1049        sCgGiProgram->SetMatrix(i ++, mProjViewMatrix);
1050
1051
1052        DrawQuad(sCgGiProgram);
1053
1054        glPopAttrib();
1055
1056        PrintGLerror("globillum first pass");
1057}
1058
1059
1060void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
1061{
1062        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1063
1064        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1065        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
1066
1067        FlipFbos(fbo);
1068
1069        sCgCombineIllumProgram->SetTexture(0, colorsTex);
1070        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
1071        sCgCombineIllumProgram->SetTexture(2, illumTex);
1072       
1073        DrawQuad(sCgCombineIllumProgram);
1074
1075        PrintGLerror("combine");
1076}
1077
1078
1079void DeferredRenderer::FilterSsao(FrameBufferObject *fbo)
1080{
1081        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1082        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1083        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1084       
1085        mTempFbo->Bind();
1086        glDrawBuffers(1, mrt);
1087       
1088        int i = 0;
1089
1090        sCgFilterSsaoProgram->SetTexture(i ++, colorsTex);
1091        sCgFilterSsaoProgram->SetTexture(i ++, ssaoTex);
1092
1093        for (int j = 0; j < 4; ++ j, ++ i)
1094        {
1095                sCgFilterSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1096        }
1097
1098        sCgFilterSsaoProgram->SetValue2f(i ++, (float)mWidth, (float)mHeight);
1099        sCgFilterSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1100        sCgFilterSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1101
1102        DrawQuad(sCgFilterSsaoProgram);
1103        PrintGLerror("filter ssao");
1104}
1105
1106
1107void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
1108{
1109        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1110        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1111        //GLuint ssaoTex = fbo->GetColorBuffer(1)->GetTexture();
1112        GLuint ssaoTex = mTempFbo->GetColorBuffer(0)->GetTexture();
1113       
1114        mTempFbo->Bind();
1115        glDrawBuffers(1, mrt + 1);
1116        //FlipFbos(fbo);
1117
1118        int i = 0;
1119
1120        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
1121        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
1122
1123        for (int j = 0; j < 4; ++ j, ++ i)
1124        {
1125                sCgCombineSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
1126        }
1127
1128        sCgCombineSsaoProgram->SetValue2f(i ++, mWidth, mHeight);
1129        sCgCombineSsaoProgram->SetValue1f(i ++, mMaxConvergence);
1130        sCgCombineSsaoProgram->SetValue1f(i ++, mSpatialWeight);
1131
1132        DrawQuad(sCgCombineSsaoProgram);
1133       
1134        PrintGLerror("combine ssao");
1135}
1136
1137
1138void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
1139                                                                           DirectionalLight *light,
1140                                                                           ShadowMap *shadowMap)
1141{
1142        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1143        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1144
1145        GLuint shadowTex = shadowMap->GetDepthTexture();
1146
1147        Matrix4x4 shadowMatrix;
1148        shadowMap->GetTextureMatrix(shadowMatrix);
1149
1150
1151        FlipFbos(fbo);
1152
1153        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
1154        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
1155        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
1156        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
1157        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
1158        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
1159
1160        const Vector3 lightDir = -light->GetDirection();
1161        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
1162        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
1163
1164        DrawQuad(sCgDeferredShadowProgram);
1165
1166        PrintGLerror("deferred shading + shadows");
1167}
1168
1169
1170void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
1171                                                                                         DirectionalLight *light,
1172                                                                                         float &imageKey,
1173                                                                                         float &whiteLum,
1174                                                                                         float &middleGrey)
1175{
1176        // hack: estimate value where sky burns out
1177        whiteLum = log(WHITE_LUMINANCE);
1178       
1179        ////////////////////
1180        //-- linear interpolate brightness key depending on the current sun position
1181
1182        const float minKey = 0.09f;
1183        const float maxKey = 0.36f;
1184
1185        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
1186        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
1187
1188
1189        //////////
1190        //-- compute avg loglum
1191
1192        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1193        GLuint colorsTex = colorBuffer->GetTexture();
1194
1195        FlipFbos(fbo);
1196       
1197        sCgLogLumProgram->SetTexture(0, colorsTex);
1198        DrawQuad(sCgLogLumProgram);
1199       
1200        PrintGLerror("ToneMapParams");
1201
1202
1203        ///////////////////
1204        //-- compute avg loglum in scene using mipmapping
1205
1206        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
1207        glGenerateMipmapEXT(GL_TEXTURE_2D);
1208}
1209
1210
1211static void ExportData(float *data, int w, int h)
1212{
1213        startil();
1214
1215        cout << "w: " << w << " h: " << h << endl;
1216        ILstring filename = ILstring("downsample2.jpg");
1217        ilRegisterType(IL_FLOAT);
1218
1219        const int depth = 1;
1220        const int bpp = 4;
1221
1222        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
1223        {
1224                cerr << "IL error " << ilGetError() << endl;
1225                stopil();
1226                return;
1227        }
1228
1229        if (!ilSaveImage(filename))
1230        {
1231                cerr << "TGA write error " << ilGetError() << endl;
1232        }
1233
1234        stopil();
1235}
1236
1237
1238void DeferredRenderer::PrepareSsao(FrameBufferObject *fbo)
1239{
1240        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1241        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
1242        GLuint diffVals = fbo->GetColorBuffer(2)->GetTexture();
1243
1244        // flip flop between illumination buffers
1245        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
1246        GLuint myTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
1247
1248        int i = 0;
1249
1250        sCgPrepareSsaoProgram->SetTexture(i ++, colorsTex);
1251        sCgPrepareSsaoProgram->SetTexture(i ++, normalsTex);
1252        sCgPrepareSsaoProgram->SetTexture(i ++, diffVals);
1253        sCgPrepareSsaoProgram->SetTexture(i ++, oldTex);
1254
1255        Vector3 de;
1256        de.x = mOldEyePos.x - mEyePos.x;
1257        de.y = mOldEyePos.y - mEyePos.y;
1258        de.z = mOldEyePos.z - mEyePos.z;
1259
1260        sCgPrepareSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
1261
1262        sCgPrepareSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
1263        sCgPrepareSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
1264
1265
1266        for (int j = 0; j < 4; ++ j, ++ i)
1267        {
1268                sCgPrepareSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
1269        }
1270
1271        sCgPrepareSsaoProgram->SetTexture(i ++, myTex);
1272
1273        glPushAttrib(GL_VIEWPORT_BIT);
1274        glViewport(0, 0, mDownSampleFbo->GetWidth(), mDownSampleFbo->GetHeight());
1275       
1276        mDownSampleFbo->Bind();
1277
1278        // prepare downsampled depth and normal texture for ssao
1279        glDrawBuffers(2, mrt);
1280
1281        DrawQuad(sCgPrepareSsaoProgram);
1282       
1283        glPopAttrib();
1284        PrintGLerror("prepareSsao");
1285}
1286
1287
1288void DeferredRenderer::DownSample(FrameBufferObject *fbo,
1289                                                                  int bufferIdx,
1290                                                                  FrameBufferObject *downSampleFbo,
1291                                                                  int downSampleBufferIdx,
1292                                                                  ShaderProgram *program)
1293{
1294        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
1295        GLuint tex = buffer->GetTexture();
1296
1297        glPushAttrib(GL_VIEWPORT_BIT);
1298        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
1299       
1300        downSampleFbo->Bind();
1301
1302        program->SetTexture(0, tex);
1303        glDrawBuffers(1, mrt + downSampleBufferIdx);
1304
1305        DrawQuad(program);
1306       
1307        glPopAttrib();
1308        PrintGLerror("downsample");
1309}
1310
1311
1312void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
1313                                                           float imageKey,
1314                                                           float whiteLum,
1315                                                           float middleGrey)
1316{
1317        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1318        GLuint colorsTex = colorBuffer->GetTexture();
1319       
1320
1321        FlipFbos(fbo);
1322
1323        sCgToneProgram->SetTexture(0, colorsTex);
1324        sCgToneProgram->SetValue1f(1, imageKey);
1325        sCgToneProgram->SetValue1f(2, whiteLum);
1326        sCgToneProgram->SetValue1f(3, middleGrey);
1327
1328        DrawQuad(sCgToneProgram);
1329
1330        PrintGLerror("ToneMap");
1331}
1332
1333
1334void DeferredRenderer::Output(FrameBufferObject *fbo)
1335{
1336        glPushAttrib(GL_VIEWPORT_BIT);
1337        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
1338       
1339        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1340        GLuint colorsTex = colorBuffer->GetTexture();
1341
1342        sCgDownSampleProgram->SetTexture(0, colorsTex);
1343
1344        FrameBufferObject::Release();
1345        DrawQuad(sCgDownSampleProgram);
1346
1347        PrintGLerror("Output");
1348}
1349
1350
1351void DeferredRenderer::InitFrame()
1352{
1353        for (int i = 0; i < 4; ++ i)
1354        {
1355                mOldCornersView[i] = mCornersView[i];
1356        }
1357
1358        mOldProjViewMatrix = mProjViewMatrix;
1359        mOldEyePos = mEyePos;
1360        mEyePos = mCamera->GetPosition();
1361
1362        // hack: temporarily change far to improve precision
1363        const float oldFar = mCamera->GetFar();
1364        const float oldNear = mCamera->GetNear();
1365       
1366
1367        Matrix4x4 matViewing, matProjection;
1368
1369
1370        ///////////////////
1371
1372        // use view orientation as we assume that the eye point is always in the center
1373        // of our coordinate system, this way we have the highest precision near the eye point
1374        mCamera->GetViewOrientationMatrix(matViewing);
1375        mCamera->GetProjectionMatrix(matProjection);
1376
1377        mProjViewMatrix = matViewing * matProjection;
1378        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1379       
1380
1381        // switch roles of old and new fbo
1382        // the algorihm uses two input fbos, where the one
1383        // contais the color buffer from the last frame,
1384        // the other one will be written
1385
1386        mIllumFboIndex = 2 - mIllumFboIndex;
1387       
1388        // enable fragment shading
1389        ShaderManager::GetSingleton()->EnableFragmentProfile();
1390
1391        glDisable(GL_ALPHA_TEST);
1392        glDisable(GL_TEXTURE_2D);
1393        glDisable(GL_LIGHTING);
1394        glDisable(GL_BLEND);
1395        glDisable(GL_DEPTH_TEST);
1396
1397        glPolygonMode(GL_FRONT, GL_FILL);
1398
1399        glMatrixMode(GL_PROJECTION);
1400        glPushMatrix();
1401        glLoadIdentity();
1402
1403        gluOrtho2D(0, 1, 0, 1);
1404
1405
1406        glMatrixMode(GL_MODELVIEW);
1407        glPushMatrix();
1408        glLoadIdentity();
1409
1410       
1411        glPushAttrib(GL_VIEWPORT_BIT);
1412        glViewport(0, 0, mWidth, mHeight);
1413
1414        // revert to old far and near plane
1415        mCamera->SetFar(oldFar);
1416        mCamera->SetNear(oldNear);
1417}
1418
1419
1420void DeferredRenderer::LenseFlare(FrameBufferObject *fbo,
1421                                                                  DirectionalLight *light                                                       
1422                                                                  )
1423{
1424        // light source visible?
1425        if (!mSunVisiblePixels) return;
1426
1427        // the sun is a large distance in the reverse light direction
1428        // => extrapolate light pos
1429        const Vector3 lightPos = light->GetDirection() * -1e3f;
1430
1431        float w;
1432        Vector3 projLightPos = mProjViewMatrix.Transform(w, lightPos, 1.0f);
1433        projLightPos /= w;
1434        projLightPos = projLightPos * 0.5f + Vector3(0.5f);
1435
1436        // vector to light from screen center in texture space
1437        Vector3 vectorToLight = projLightPos - Vector3(0.5f);
1438        vectorToLight.z = .0f;
1439
1440        const float distanceToLight = Magnitude(vectorToLight);
1441        vectorToLight /= distanceToLight;
1442        //cout << "dist " << distanceToLight << " v " << vectorToLight << endl;
1443
1444
1445        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1446        GLuint colorsTex = colorBuffer->GetTexture();
1447       
1448        FlipFbos(fbo);
1449
1450        int i = 0;
1451
1452        sCgLenseFlareProgram->SetTexture(i ++, colorsTex);
1453        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[0]->GetId());
1454        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[1]->GetId());
1455        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[2]->GetId());
1456        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[3]->GetId());
1457        sCgLenseFlareProgram->SetTexture(i ++, sHaloTex[4]->GetId());
1458        sCgLenseFlareProgram->SetValue2f(i ++, vectorToLight.x, vectorToLight.y);
1459        sCgLenseFlareProgram->SetValue1f(i ++, distanceToLight);
1460        sCgLenseFlareProgram->SetValue1f(i ++, (float)mSunVisiblePixels);
1461
1462        DrawQuad(sCgLenseFlareProgram);
1463
1464        PrintGLerror("LenseFlare");
1465}
1466
1467
1468void DeferredRenderer::DepthOfField(FrameBufferObject *fbo)
1469{
1470        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1471        GLuint colorsTex = colorBuffer->GetTexture();
1472       
1473        FlipFbos(fbo);
1474
1475        int i = 0;
1476
1477        const float zFocus = 7.0f;
1478
1479        sCgDOFProgram->SetTexture(i ++, colorsTex);
1480        sCgDOFProgram->SetArray2f(i ++, (float *)dofSamples, NUM_DOF_TABS);
1481        sCgDOFProgram->SetValue1f(i ++, min(mCamera->GetFar(), mMaxDistance) - mCamera->GetNear());
1482        sCgDOFProgram->SetValue1f(i ++, zFocus);
1483
1484        DrawQuad(sCgDOFProgram);
1485
1486        PrintGLerror("LenseFlare");
1487}
1488
1489
1490void DeferredRenderer::SaveFrame(FrameBufferObject *fbo)
1491{
1492        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1493        GLuint colorsTex = colorBuffer->GetTexture();
1494
1495        GLubyte *data = new GLubyte[mWidth * mHeight * 4];
1496
1497        // grab texture data
1498        glEnable(GL_TEXTURE_2D);
1499        glBindTexture(GL_TEXTURE_2D, colorsTex);
1500        glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
1501
1502        glBindTexture(GL_TEXTURE_2D, 0);
1503        glDisable(GL_TEXTURE_2D);
1504
1505        /////////////////
1506
1507        startil();
1508
1509        static char imageName[200];
1510        sprintf(imageName, "%s_%05d.tga", mSavedFrameSuffix.c_str(), mSavedFrameNumber);
1511
1512        //cout << "writing " << imageName << endl;
1513
1514        ILstring fileName = ILstring(imageName);
1515        ilRegisterType(IL_FLOAT);
1516
1517        const int depth = 1;
1518        const int bpp = 4;
1519
1520        if (!ilTexImage(mWidth, mHeight, depth, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data))
1521        {
1522                cerr << "IL error " << ilGetError() << endl;
1523                stopil();
1524                return;
1525        }
1526
1527        ilEnable(IL_FILE_OVERWRITE);
1528
1529        if (!ilSaveImage(fileName))
1530        {
1531                cerr << "TGA write error " << ilGetError() << endl;
1532        }
1533
1534        //cout << "wrote " << fileName << endl;
1535
1536        delete [] data;
1537        stopil();
1538
1539        PrintGLerror("Store frame");
1540}
1541
1542
1543void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
1544{
1545        mUseTemporalCoherence = temporal;
1546}
1547
1548
1549void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
1550{
1551        if (s != mSamplingMethod)
1552        {
1553                mSamplingMethod = s;
1554                mRegenerateSamples = true;
1555        }
1556}
1557
1558
1559void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
1560{
1561        if (s != mShadingMethod)
1562        {
1563                mShadingMethod = s;
1564                mRegenerateSamples = true;
1565        }
1566}
1567
1568
1569#if TODO
1570
1571void DeferredRenderer::SetNumSamples(int numSamples)
1572{
1573        mNumSamples = numSamples;
1574}
1575
1576#endif
1577
1578
1579void DeferredRenderer::SetSampleIntensity(float sampleIntensity)
1580{
1581        mSampleIntensity = sampleIntensity;
1582        mRegenerateSamples = true;
1583}
1584
1585
1586void DeferredRenderer::SetKernelRadius(float kernelRadius)
1587{
1588        mKernelRadius = kernelRadius;
1589        mRegenerateSamples = true;
1590}
1591
1592
1593/*void DeferredRenderer::SetSortSamples(bool sortSamples)
1594{
1595        mSortSamples = sortSamples;
1596}*/
1597
1598
1599void DeferredRenderer::SetSunVisiblePixels(int pixels)
1600{
1601        mSunVisiblePixels = pixels;
1602}
1603
1604
1605void DeferredRenderer::SetMaxDistance(float maxDist)
1606{
1607        mMaxDistance = maxDist;
1608}
1609
1610
1611void DeferredRenderer::SetUseToneMapping(bool toneMapping)
1612{
1613        mUseToneMapping = toneMapping;
1614}
1615       
1616
1617void DeferredRenderer::SetUseAntiAliasing(bool antiAliasing)
1618{
1619        mUseAntiAliasing = antiAliasing;
1620}
1621
1622
1623void DeferredRenderer::SetUseDepthOfField(bool dof)
1624{
1625        mUseDepthOfField = dof;
1626}
1627
1628
1629void DeferredRenderer::SetTemporalCoherenceFactorForSsao(float factor)
1630{
1631        mTempCohFactor = factor;
1632}
1633
1634
1635void DeferredRenderer::SetSaveFrame(const string &suffix, int frameNumber)
1636{
1637        mSavedFrameSuffix = suffix;
1638        mSavedFrameNumber = frameNumber;
1639}
1640
1641
1642void DeferredRenderer::SetMaxConvergence(float c)
1643{
1644        mMaxConvergence = c;
1645}
1646
1647
1648void DeferredRenderer::SetSpatialWeight(float w)
1649{
1650        mSpatialWeight = w;
1651}
1652
1653
1654} // namespace
Note: See TracBrowser for help on using the repository browser.