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

Revision 3148, 30.5 KB checked in by mattausch, 16 years ago (diff)

done a little cleanup

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
13#include <IL/il.h>
14#include <assert.h>
15
16
17#ifdef _CRT_SET
18        #define _CRTDBG_MAP_ALLOC
19        #include <stdlib.h>
20        #include <crtdbg.h>
21
22        // redefine new operator
23        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
24        #define new DEBUG_NEW
25#endif
26
27
28using namespace std;
29
30
31static void startil()
32{
33        ilInit();
34        assert(ilGetError() == IL_NO_ERROR);
35}
36
37
38static void stopil()
39{
40        ilShutDown();
41        assert(ilGetError() == IL_NO_ERROR);
42}
43
44namespace CHCDemoEngine
45{
46
47static ShaderProgram *sCgSsaoProgram = NULL;
48static ShaderProgram *sCgGiProgram = NULL;
49
50static ShaderProgram *sCgDeferredProgram = NULL;
51static ShaderProgram *sCgAntiAliasingProgram = NULL;
52static ShaderProgram *sCgDeferredShadowProgram = NULL;
53
54static ShaderProgram *sCgCombineSsaoProgram = NULL;
55static ShaderProgram *sCgCombineIllumProgram = NULL;
56static ShaderProgram *sCgLogLumProgram = NULL;
57static ShaderProgram *sCgToneProgram = NULL;
58static ShaderProgram *sCgDownSampleProgram = NULL;
59static ShaderProgram *sCgScaleDepthProgram = NULL;
60
61
62static GLuint noiseTex2D = 0;
63static GLuint noiseTex1D = 0;
64
65
66// ssao random spherical samples
67static Sample2 samples2[NUM_SAMPLES];
68// number of pcf tabs
69static Sample2 pcfSamples[NUM_PCF_TABS];
70
71
72static float ssaoFilterOffsets[NUM_SSAO_FILTERSAMPLES * 2];
73static float ssaoFilterWeights[NUM_SSAO_FILTERSAMPLES];
74
75
76int DeferredRenderer::colorBufferIdx = 0;
77
78
79/** Helper method that computes the view vectors in the corners of the current view frustum.
80*/
81static void ComputeViewVectors(PerspectiveCamera *cam, Vector3 &bl, Vector3 &br, Vector3 &tl, Vector3 &tr)
82{
83        Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
84        cam->ComputePoints(ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr);
85
86        bl = Normalize(nbl - fbl);
87        br = Normalize(nbr - fbr);
88        tl = Normalize(ntl - ftl);
89        tr = Normalize(ntr - ftr);
90}
91
92
93static float GaussianDistribution(float x, float y, float rho)
94{
95        float g = 1.0f / sqrtf(2.0f * M_PI * rho * rho);
96    g *= expf( -(x * x + y * y) / (2.0f * rho * rho));
97
98    return g;
99}
100
101
102static void PrintGLerror(char *msg)
103{
104        GLenum errCode;
105        const GLubyte *errStr;
106       
107        if ((errCode = glGetError()) != GL_NO_ERROR)
108        {
109                errStr = gluErrorString(errCode);
110                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
111        }
112}
113
114
115static void ComputeSampleOffsets(float *sampleOffsets,
116                                                                 int imageW, int imageH,
117                                                                 float width,
118                                                                 int samples)
119{
120        const float xoffs = width / (float)imageW;
121        const float yoffs = width / (float)imageH;
122       
123        const int numSamples = (int)sqrt((float)samples);
124        const int startSamples = -numSamples / 2;
125        const int endSamples = numSamples + startSamples - 1;
126        //cout << startSamples << " " << endSamples << endl;
127
128        int idx = 0;
129
130        for (int x = startSamples; x <= endSamples; ++ x)
131        {
132                for (int y = startSamples; y <= endSamples; ++ y)
133                {
134                        sampleOffsets[idx + 0] = (float)x * xoffs;
135                        sampleOffsets[idx + 1] = (float)y * yoffs;
136                        idx += 2;
137                }
138        }
139}
140
141
142void DeferredRenderer::FlipFbos(FrameBufferObject *fbo)
143{
144        fbo->Bind();
145        colorBufferIdx = 3 - colorBufferIdx;
146        glDrawBuffers(1, mrt + colorBufferIdx);
147}
148
149
150void DeferredRenderer::DrawQuad(ShaderProgram *p)
151{
152        if (p) p->Bind();
153
154        // interpolate the view vector
155        Vector3 bl = mCornersView[0];
156        Vector3 br = mCornersView[1];
157        Vector3 tl = mCornersView[2];
158        Vector3 tr = mCornersView[3];
159
160        // note: slightly larger texture could hide ambient occlusion error on border but costs resolution
161        glBegin(GL_QUADS);
162
163        glTexCoord2f(0, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, bl.x, bl.y, bl.z); glVertex2f( .0f,  .0f);
164        glTexCoord2f(1, 0); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, br.x, br.y, br.z); glVertex2f(1.0f,  .0f);
165        glTexCoord2f(1, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tr.x, tr.y, tr.z); glVertex2f(1.0f, 1.0f);
166        glTexCoord2f(0, 1); glMultiTexCoord3fARB(GL_TEXTURE1_ARB, tl.x, tl.y, tl.z); glVertex2f( .0f, 1.0f);
167
168        glEnd();
169}
170
171
172/** Generate poisson disc distributed sample points on the unit disc
173*/
174static void GenerateSamples(int sampling)
175{
176        switch (sampling)
177        {
178        case DeferredRenderer::SAMPLING_POISSON:
179                {
180                        PoissonDiscSampleGenerator2 poisson(NUM_SAMPLES, 1.0f);
181                        poisson.Generate((float *)samples2);
182                }
183                break;
184        case DeferredRenderer::SAMPLING_QUADRATIC:
185                {
186                        QuadraticDiscSampleGenerator2 g(NUM_SAMPLES, 1.0f);
187                        g.Generate((float *)samples2);
188                }
189                break;
190        default: // SAMPLING_DEFAULT
191                {
192                        RandomSampleGenerator2 g(NUM_SAMPLES, 1.0f);
193                        g.Generate((float *)samples2);
194                }
195        }
196}
197
198
199static void CreateNoiseTex2D(int w, int h)
200{
201        //GLubyte *randomNormals = new GLubyte[mWidth * mHeight * 3];
202        float *randomNormals = new float[w * h * 3];
203
204        static HaltonSequence halton;
205        float r[2];
206
207        for (int i = 0; i < w * h * 3; i += 3)
208        {
209                // create random samples on a circle
210                r[0] = RandomValue(0, 1);
211                //halton.GetNext(1, r);
212
213                const float theta = 2.0f * acos(sqrt(1.0f - r[0]));
214               
215                randomNormals[i + 0] = cos(theta);
216                randomNormals[i + 1] = sin(theta);
217                randomNormals[i + 2] = 0;
218        }
219
220        glEnable(GL_TEXTURE_2D);
221        glGenTextures(1, &noiseTex2D);
222        glBindTexture(GL_TEXTURE_2D, noiseTex2D);
223               
224        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
225        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
226        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
227        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
228
229        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGB, GL_FLOAT, randomNormals);
230
231        glBindTexture(GL_TEXTURE_2D, 0);
232        glDisable(GL_TEXTURE_2D);
233
234        delete [] randomNormals;
235
236        cout << "created noise texture" << endl;
237
238        PrintGLerror("noisetexture");
239}
240
241
242static void CreateNoiseTex1D(int w)
243{
244        float *randomValues = new float[w * 3];
245
246        static HaltonSequence halton;
247       
248        randomValues[0] = randomValues[1] = randomValues[2] = 0;
249
250        for (int i = 3; i < w * 3; i += 3)
251        {
252                // create random samples on a circle
253                randomValues[i + 0] = 20.0f * RandomValue(0, 1) / 512.0f;
254                randomValues[i + 1] = 20.0f * RandomValue(0, 1) / 384.0f;
255                randomValues[i + 2] = 0;
256        }
257
258        glEnable(GL_TEXTURE_2D);
259        glGenTextures(1, &noiseTex1D);
260        glBindTexture(GL_TEXTURE_2D, noiseTex1D);
261               
262        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
263        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
264        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
265        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
266
267        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, 1, 0, GL_RGB, GL_FLOAT, randomValues);
268
269        glBindTexture(GL_TEXTURE_2D, 0);
270        glDisable(GL_TEXTURE_2D);
271
272        delete [] randomValues;
273
274        cout << "created noise texture 1D" << endl;
275
276        PrintGLerror("noisetexture 1D");
277}
278
279
280
281DeferredRenderer::DeferredRenderer(int w, int h, PerspectiveCamera *cam):
282mWidth(w), mHeight(h),
283mCamera(cam),
284mUseTemporalCoherence(true),
285mRegenerateSamples(true),
286mSamplingMethod(SAMPLING_POISSON),
287mShadingMethod(DEFAULT),
288mIllumFboIndex(0)
289{
290        ///////////
291        //-- the flip-flop fbos
292
293        const int dsw = w / 2; const int dsh = h / 2;
294        //const int dsw = w; const int dsh = h;
295
296        mIllumFbo = new FrameBufferObject(dsw, dsh, FrameBufferObject::DEPTH_NONE);
297        //mIllumFbo = new FrameBufferObject(w, h, FrameBufferObject::DEPTH_NONE);
298
299        mFBOs.push_back(mIllumFbo);
300
301        for (int i = 0; i < 4; ++ i)
302        {
303                mIllumFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
304                FrameBufferObject::InitBuffer(mIllumFbo, i);
305        }
306
307
308        ///////////////
309        //-- the downsampled ssao + color bleeding textures: as gi is inherently low frequency, we can use these to improve performance
310
311        mDownSampleFbo = new FrameBufferObject(dsw, dsh, FrameBufferObject::DEPTH_NONE);
312        //mDownSampleFbo = new FrameBufferObject(w, h, FrameBufferObject::DEPTH_NONE);
313        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
314        // downsample buffer for the normal texture
315        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
316        // downsample buffer for the offset texture
317        mDownSampleFbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
318
319        for (int i = 0; i < 3; ++ i)
320        {
321                FrameBufferObject::InitBuffer(mDownSampleFbo, i);
322        }
323
324        mFBOs.push_back(mDownSampleFbo);
325
326        // create noise texture for ssao
327        CreateNoiseTex2D(mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
328        //CreateNoiseTex2D(mIllumFbo->GetWidth() / 4, mIllumFbo->GetWidth() / 4);
329        CreateNoiseTex1D(mWidth / 8);
330
331        mProjViewMatrix = IdentityMatrix();
332        mOldProjViewMatrix = IdentityMatrix();
333
334        for (int i = 0; i < 4; ++ i)
335        {
336                mCornersView[i] = mOldCornersView[i] = Vector3::UNIT_X();
337        }
338
339        mEyePos = mOldEyePos = Vector3::ZERO();
340
341        InitCg();
342}
343
344
345DeferredRenderer::~DeferredRenderer()
346{
347        CLEAR_CONTAINER(mFBOs);
348        glDeleteTextures(1, &noiseTex2D);
349        glDeleteTextures(1, &noiseTex1D);
350}
351
352
353void DeferredRenderer::SetUseTemporalCoherence(bool temporal)
354{
355        mUseTemporalCoherence = temporal;
356}
357
358
359
360void DeferredRenderer::InitCg()
361{       
362        ShaderManager *sm = ShaderManager::GetSingleton();
363
364        sCgDeferredProgram = sm->CreateFragmentProgram("deferred", "main", "deferredFrag");
365        sCgDeferredShadowProgram = sm->CreateFragmentProgram("deferred", "main_shadow", "deferredFragShader");
366        sCgSsaoProgram = sm->CreateFragmentProgram("ssao", "main", "ssaoFrag");
367        sCgGiProgram = sm->CreateFragmentProgram("globillum", "main", "giFrag");
368        sCgCombineIllumProgram = sm->CreateFragmentProgram("globillum", "combine", "combineGi");
369        sCgCombineSsaoProgram = sm->CreateFragmentProgram("combineSsao", "combine", "combineSsao");
370        sCgAntiAliasingProgram = sm->CreateFragmentProgram("antialiasing", "main", "antiAliasing");
371        sCgToneProgram = sm->CreateFragmentProgram("tonemap", "ToneMap", "toneMap");
372        sCgDownSampleProgram = sm->CreateFragmentProgram("deferred", "Output", "Output");
373        sCgScaleDepthProgram = sm->CreateFragmentProgram("deferred", "ScaleDepth", "ScaleDepth");
374        sCgLogLumProgram = sm->CreateFragmentProgram("tonemap", "CalcAvgLogLum", "avgLogLum");
375
376
377        ///////////////////
378        //-- initialize program parameters
379
380        string ssaoParams[] =
381                {"colors", "normals", "oldTex", "noiseTex", "temporalCoherence",
382                 "samples", "bl", "br", "tl", "tr",
383                 "modelViewProj", "oldModelViewProj", "oldEyePos", "oldbl", "oldbr",
384                 "oldtl", "oldtr", "attribsTex", "noiseTex1D"};
385        sCgSsaoProgram->AddParameters(ssaoParams, 0, 19);
386       
387        string giParams[] =
388                {"colors", "normals", "noiseTex", "oldSsaoTex", "oldIllumTex",
389                 "temporalCoherence", "samples", "bl", "br", "tl",
390                 "tr", "oldModelViewProj", "modelViewProj"};
391        sCgGiProgram->AddParameters(giParams, 0, 13);
392
393        string toneParams[] = {"colors", "imageKey", "whiteLum", "middleGrey"};
394        sCgToneProgram->AddParameters(toneParams, 0, 4);
395
396
397        ////////////////
398
399        string deferredShadowParams[] =
400                {"colors", "normals", "shadowMap", "noiseTex", "shadowMatrix",
401                 "sampleWidth", "lightDir", "eyePos", "samples", "weights"};
402       
403        sCgDeferredShadowProgram->AddParameters(deferredShadowParams, 0, 10);
404       
405        ////////////////
406
407        string combineIllumParams[] = {"colorsTex", "ssaoTex", "illumTex"};
408        sCgCombineIllumProgram->AddParameters(combineIllumParams, 0, 3);
409
410        ////////////////
411
412        string combineSsaoParams[] = {"colorsTex", "normalsTex", "ssaoTex", "filterOffs", "filterWeights", "bl", "br", "tl", "tr"};
413        sCgCombineSsaoProgram->AddParameters(combineSsaoParams, 0, 9);
414
415        //////////////
416
417        string deferredParams[] = {"colors", "normals", "lightDir"};
418        sCgDeferredProgram->AddParameters(deferredParams, 0, 3);
419
420        ///////////////////
421
422        string aaParams[] = {"colors", "normals", "offsets"};
423        sCgAntiAliasingProgram->AddParameters(aaParams, 0, 3);
424
425        /////////////////////
426
427        string downSampleParams[] = {"colors"};
428        sCgDownSampleProgram->AddParameters(downSampleParams, 0, 1);
429
430        /////////////////////
431
432        string scaleDepthParams[] = {"colors"};
433        sCgScaleDepthProgram->AddParameters(scaleDepthParams, 0, 1);
434
435        ////////////
436
437        sCgLogLumProgram->AddParameter("colors", 0);
438
439        ////////////////
440
441
442        const float filterWidth = 100.0f;
443        //const float filterWidth = 1000.0f;
444
445#if 1
446        PoissonDiscSampleGenerator2 poisson(NUM_SSAO_FILTERSAMPLES, 1.0f);
447        poisson.Generate((float *)ssaoFilterOffsets);
448
449        const float xoffs = (float)filterWidth / mWidth;
450        const float yoffs = (float)filterWidth / mHeight;
451
452        for (int i = 0; i < NUM_SSAO_FILTERSAMPLES; ++ i)
453        {
454                float x = ssaoFilterOffsets[2 * i + 0];
455                float y = ssaoFilterOffsets[2 * i + 1];
456
457                ssaoFilterWeights[i] = GaussianDistribution(x, y, 1.0f);
458                //ssaoFilterWeights[i] = 1.0f;
459
460                ssaoFilterOffsets[2 * i + 0] *= xoffs;
461                ssaoFilterOffsets[2 * i + 1] *= yoffs;
462        }
463#else
464        //ComputeSampleOffsets(ssaoFilterOffsets, mWidth, mHeight, sqrt(NUM_SSAO_FILTERSAMPLES), NUM_SSAO_FILTERSAMPLES);
465        ComputeSampleOffsets(ssaoFilterOffsets, mWidth, mHeight, filterWidth, NUM_SSAO_FILTERSAMPLES);
466        //cout<<"ssao filter size: " << NUM_SSAO_FILTERSAMPLES << endl;
467        for (int i = 0; i < NUM_SSAO_FILTERSAMPLES; ++ i)
468                ssaoFilterWeights[i] = 1.0f;
469
470#endif
471
472        /////////
473        //-- pcf tabs for shadowing
474
475        float filterWeights[NUM_PCF_TABS];
476        PoissonDiscSampleGenerator2 poisson2(NUM_PCF_TABS, 1.0f);
477        poisson2.Generate((float *)pcfSamples);
478
479        for (int i = 0; i < NUM_PCF_TABS; ++ i)
480        {
481                filterWeights[i] = GaussianDistribution(pcfSamples[i].x, pcfSamples[i].y, 1.0f);
482        }
483
484        sCgDeferredShadowProgram->SetArray2f(8, (float *)pcfSamples, NUM_PCF_TABS);
485        sCgDeferredShadowProgram->SetArray1f(9, (float *)filterWeights, NUM_PCF_TABS);
486
487        PrintGLerror("init");
488}
489
490
491void DeferredRenderer::Render(FrameBufferObject *fbo,
492                                                          float tempCohFactor,
493                                                          DirectionalLight *light,
494                                                          bool useToneMapping,
495                                                          ShadowMap *shadowMap
496                                                          )
497{
498        InitFrame();
499
500        if (shadowMap)
501                FirstPassShadow(fbo, light, shadowMap);
502        else
503                FirstPass(fbo, light);
504
505        if (mShadingMethod != 0)
506        {
507                // downsample fbo buffers
508                // colors
509                DownSample(fbo, colorBufferIdx, mDownSampleFbo, 0, sCgScaleDepthProgram);
510                DownSample(fbo, 1, mDownSampleFbo, 1, sCgDownSampleProgram); // normals
511                DownSample(fbo, 2, mDownSampleFbo, 2, sCgDownSampleProgram); // offsets
512        }
513
514        // antialiasing of the color buffer
515        //AntiAliasing(fbo, light);
516
517        switch (mShadingMethod)
518        {
519        case SSAO:
520                ComputeSsao(fbo, tempCohFactor);
521                CombineSsao(fbo);
522                break;
523        case GI:
524                ComputeGlobIllum(fbo, tempCohFactor);
525                CombineIllum(fbo);
526                break;
527        default: // DEFAULT
528                // do nothing: standard deferred shading
529                break;
530        }
531
532        if (useToneMapping)
533        {
534                float imageKey, whiteLum, middleGrey;
535
536                ComputeToneParameters(fbo, light, imageKey, whiteLum, middleGrey);
537                ToneMap(fbo, imageKey, whiteLum, middleGrey);
538        }
539
540        // as multisampling is difficult / costly with deferred shading,
541        // at least do some antialiasing
542        AntiAliasing(fbo, light);
543
544        // just output the latest buffer
545        //Output(fbo);
546
547        glEnable(GL_LIGHTING);
548        glDisable(GL_TEXTURE_2D);
549
550        glMatrixMode(GL_PROJECTION);
551        glPopMatrix();
552
553        glMatrixMode(GL_MODELVIEW);
554        glPopMatrix();
555
556        // viewport
557        glPopAttrib();
558
559        FrameBufferObject::Release();
560        ShaderManager::GetSingleton()->DisableFragmentProfile();
561}
562
563
564void DeferredRenderer::ComputeSsao(FrameBufferObject *fbo,
565                                                                   float tempCohFactor)
566{
567        GLuint colorsTex, normalsTex, attribsTex;
568
569        if (0)
570        {
571                colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
572                normalsTex = fbo->GetColorBuffer(1)->GetTexture();
573                attribsTex = fbo->GetColorBuffer(2)->GetTexture();
574        }
575        else
576        {
577                colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
578                normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
579                attribsTex = mDownSampleFbo->GetColorBuffer(2)->GetTexture();
580                //attribsTex = fbo->GetColorBuffer(2)->GetTexture();
581        }
582
583        // flip flop between illumination buffers
584        GLuint oldTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
585
586        glPushAttrib(GL_VIEWPORT_BIT);
587        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
588
589        // read the second buffer, write to the first buffer
590        mIllumFbo->Bind();
591        glDrawBuffers(1, mrt + mIllumFboIndex);
592
593        int i = 0;
594
595        sCgSsaoProgram->SetTexture(i ++, colorsTex);
596        sCgSsaoProgram->SetTexture(i ++, normalsTex);
597        sCgSsaoProgram->SetTexture(i ++, oldTex);
598        sCgSsaoProgram->SetTexture(i ++, noiseTex2D);
599
600        sCgSsaoProgram->SetValue1f(i ++, (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
601       
602        if (mUseTemporalCoherence || mRegenerateSamples)
603        //if (mRegenerateSamples)
604        {
605                mRegenerateSamples = false;
606
607                // q: should we generate new samples or only rotate the old ones?
608                // in the first case, the sample patterns look nicer, but the kernel
609                // needs longer to converge
610                GenerateSamples(mSamplingMethod);
611                sCgSsaoProgram->SetArray2f(i, (float *)samples2, NUM_SAMPLES);
612        }
613       
614        ++ i;
615
616        for (int j = 0; j < 4; ++ j, ++ i)
617                sCgSsaoProgram->SetValue3f(i, mCornersView[j].x, mCornersView[j].y, mCornersView[j].z);
618
619        sCgSsaoProgram->SetMatrix(i ++, mProjViewMatrix);
620        sCgSsaoProgram->SetMatrix(i ++, mOldProjViewMatrix);
621
622        Vector3 de;
623        de.x = mOldEyePos.x - mEyePos.x;
624        de.y = mOldEyePos.y - mEyePos.y;
625        de.z = mOldEyePos.z - mEyePos.z;
626
627        sCgSsaoProgram->SetValue3f(i ++, de.x, de.y, de.z);
628
629        for (int j = 0; j < 4; ++ j, ++ i)
630                sCgSsaoProgram->SetValue3f(i, mOldCornersView[j].x, mOldCornersView[j].y, mOldCornersView[j].z);
631
632        sCgSsaoProgram->SetTexture(i ++, attribsTex);
633
634        sCgSsaoProgram->SetTexture(i ++, noiseTex1D);
635
636        DrawQuad(sCgSsaoProgram);
637
638        glPopAttrib();
639
640        PrintGLerror("ssao first pass");
641}
642
643
644static void SetVertex(float x, float y, float x_offs, float y_offs)
645{
646        glMultiTexCoord2fARB(GL_TEXTURE0_ARB, x, y); // center
647        glMultiTexCoord2fARB(GL_TEXTURE1_ARB, x - x_offs, y + y_offs); // left top
648        glMultiTexCoord2fARB(GL_TEXTURE2_ARB, x + x_offs, y - y_offs); // right bottom
649        glMultiTexCoord2fARB(GL_TEXTURE3_ARB, x + x_offs, y + y_offs); // right top
650        glMultiTexCoord2fARB(GL_TEXTURE4_ARB, x - x_offs, y - y_offs); // left bottom
651
652        glMultiTexCoord4fARB(GL_TEXTURE5_ARB, x - x_offs, y, x + x_offs, y); // left right
653        glMultiTexCoord4fARB(GL_TEXTURE6_ARB, x, y + y_offs, x, y - y_offs); // top bottom
654
655        //glVertex3f(x - 0.5f, y - 0.5f, -0.5f);
656        glVertex2f(x, y);
657}
658
659
660void DeferredRenderer::AntiAliasing(FrameBufferObject *fbo, DirectionalLight *light)
661{
662        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
663        GLuint colorsTex = colorBuffer->GetTexture();
664        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
665
666        FrameBufferObject::Release();
667        // read the second buffer, write to the first buffer
668        //FlipFbos(fbo);
669
670        // the neighbouring texels
671        float xOffs = 1.0f / fbo->GetWidth();
672        float yOffs = 1.0f / fbo->GetHeight();
673
674        sCgAntiAliasingProgram->SetTexture(0, colorsTex);
675        sCgAntiAliasingProgram->SetTexture(1, normalsTex);
676
677        float offsets[16];
678        int i = 0;
679
680        offsets[i] = -xOffs; offsets[i + 1] =  yOffs; i += 2; // left top
681        offsets[i] =  xOffs; offsets[i + 1] = -yOffs; i += 2; // right bottom
682        offsets[i] =  xOffs; offsets[i + 1] =  yOffs; i += 2; // right top
683        offsets[i] = -xOffs; offsets[i + 1] = -yOffs; i += 2; // left bottom
684        offsets[i] = -xOffs; offsets[i + 1] =    .0f; i += 2; // left
685        offsets[i] =  xOffs; offsets[i + 1] =    .0f; i += 2; // right
686        offsets[i] =    .0f; offsets[i + 1] =  yOffs; i += 2; // top
687        offsets[i] =    .0f; offsets[i + 1] = -yOffs; i += 2; // bottom
688
689        sCgAntiAliasingProgram->SetArray2f(2, offsets, 8);
690
691        DrawQuad(sCgAntiAliasingProgram);
692
693        PrintGLerror("antialiasing");
694}
695
696
697void DeferredRenderer::FirstPass(FrameBufferObject *fbo, DirectionalLight *light)
698{
699        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
700        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
701
702        FlipFbos(fbo);
703
704        const Vector3 lightDir = -light->GetDirection();
705
706        sCgDeferredProgram->SetTexture(0, colorsTex);
707        sCgDeferredProgram->SetTexture(1, normalsTex);
708        sCgDeferredProgram->SetValue3f(2, lightDir.x, lightDir.y, lightDir.z);
709       
710        DrawQuad(sCgDeferredProgram);
711
712        PrintGLerror("deferred shading");
713}
714
715
716void DeferredRenderer::ComputeGlobIllum(FrameBufferObject *fbo,
717                                                                                float tempCohFactor)
718{
719#if 0
720        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
721        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
722#else
723        GLuint colorsTex = mDownSampleFbo->GetColorBuffer(0)->GetTexture();
724        GLuint normalsTex = mDownSampleFbo->GetColorBuffer(1)->GetTexture();
725#endif
726
727        glPushAttrib(GL_VIEWPORT_BIT);
728        glViewport(0, 0, mIllumFbo->GetWidth(), mIllumFbo->GetHeight());
729
730        // read the second buffer, write to the first buffer
731        mIllumFbo->Bind();
732
733        glDrawBuffers(2, mrt + mIllumFboIndex);
734
735        GLuint oldSsaoTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex)->GetTexture();
736        GLuint oldIllumTex = mIllumFbo->GetColorBuffer(2 - mIllumFboIndex + 1)->GetTexture();
737
738        sCgGiProgram->SetTexture(0, colorsTex);
739        sCgGiProgram->SetTexture(1, normalsTex);
740        sCgGiProgram->SetTexture(2, noiseTex2D);
741        sCgGiProgram->SetTexture(3, oldSsaoTex);
742        sCgGiProgram->SetTexture(4, oldIllumTex);
743
744        sCgGiProgram->SetValue1f(5,
745                (mUseTemporalCoherence && !mRegenerateSamples) ? tempCohFactor : 0);
746
747        if (mUseTemporalCoherence || mRegenerateSamples)
748        {
749                mRegenerateSamples = false;
750
751                // q: should we generate new samples or only rotate the old ones?
752                // in the first case, the sample patterns look nicer, but the kernel
753                // needs longer to converge
754                GenerateSamples(mSamplingMethod);
755
756                sCgGiProgram->SetArray2f(6, (float *)samples2, NUM_SAMPLES);
757        }
758
759        Vector3 bl = mCornersView[0];
760        Vector3 br = mCornersView[1];
761        Vector3 tl = mCornersView[2];
762        Vector3 tr = mCornersView[3];
763
764        sCgGiProgram->SetValue3f(7, bl.x, bl.y, bl.z);
765        sCgGiProgram->SetValue3f(8, br.x, br.y, br.z);
766        sCgGiProgram->SetValue3f(9, tl.x, tl.y, tl.z);
767        sCgGiProgram->SetValue3f(10, tr.x, tr.y, tr.z);
768
769        sCgGiProgram->SetMatrix(11, mOldProjViewMatrix);
770        sCgGiProgram->SetMatrix(12, mProjViewMatrix);
771
772
773        DrawQuad(sCgGiProgram);
774
775        glPopAttrib();
776
777        PrintGLerror("globillum first pass");
778}
779
780
781void DeferredRenderer::CombineIllum(FrameBufferObject *fbo)
782{
783        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
784
785        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
786        GLuint illumTex = mIllumFbo->GetColorBuffer(mIllumFboIndex + 1)->GetTexture();
787
788        FlipFbos(fbo);
789
790        sCgCombineIllumProgram->SetTexture(0, colorsTex);
791        sCgCombineIllumProgram->SetTexture(1, ssaoTex);
792        sCgCombineIllumProgram->SetTexture(2, illumTex);
793       
794        DrawQuad(sCgCombineIllumProgram);
795
796        PrintGLerror("combine");
797}
798
799
800void DeferredRenderer::CombineSsao(FrameBufferObject *fbo)
801{
802        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
803        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
804        GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
805       
806        FlipFbos(fbo);
807
808        int i = 0;
809
810        sCgCombineSsaoProgram->SetTexture(i ++, colorsTex);
811        sCgCombineSsaoProgram->SetTexture(i ++, normalsTex);
812        sCgCombineSsaoProgram->SetTexture(i ++, ssaoTex);
813
814        sCgCombineSsaoProgram->SetArray2f(i ++, (float *)ssaoFilterOffsets, NUM_SSAO_FILTERSAMPLES);
815        sCgCombineSsaoProgram->SetArray1f(i ++, (float *)ssaoFilterWeights, NUM_SSAO_FILTERSAMPLES);
816       
817        Vector3 bl = mCornersView[0];
818        Vector3 br = mCornersView[1];
819        Vector3 tl = mCornersView[2];
820        Vector3 tr = mCornersView[3];
821
822
823        DrawQuad(sCgCombineSsaoProgram);
824       
825        PrintGLerror("combine ssao");
826}
827
828
829void DeferredRenderer::FirstPassShadow(FrameBufferObject *fbo,
830                                                                           DirectionalLight *light,
831                                                                           ShadowMap *shadowMap)
832{
833        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
834        GLuint normalsTex = fbo->GetColorBuffer(1)->GetTexture();
835
836        GLuint shadowTex = shadowMap->GetDepthTexture();
837
838        Matrix4x4 shadowMatrix;
839        shadowMap->GetTextureMatrix(shadowMatrix);
840
841
842        FlipFbos(fbo);
843
844        sCgDeferredShadowProgram->SetTexture(0, colorsTex);
845        sCgDeferredShadowProgram->SetTexture(1, normalsTex);
846        sCgDeferredShadowProgram->SetTexture(2, shadowTex);
847        sCgDeferredShadowProgram->SetTexture(3, noiseTex2D);
848        sCgDeferredShadowProgram->SetMatrix(4, shadowMatrix);
849        sCgDeferredShadowProgram->SetValue1f(5, 2.0f / shadowMap->GetSize());
850
851        const Vector3 lightDir = -light->GetDirection();
852        sCgDeferredShadowProgram->SetValue3f(6, lightDir.x, lightDir.y, lightDir.z);
853        sCgDeferredShadowProgram->SetValue3f(7, mEyePos.x, mEyePos.y, mEyePos.z);
854
855        DrawQuad(sCgDeferredShadowProgram);
856
857        PrintGLerror("deferred shading + shadows");
858}
859
860
861void DeferredRenderer::SetSamplingMethod(SAMPLING_METHOD s)
862{
863        if (s != mSamplingMethod)
864        {
865                mSamplingMethod = s;
866                mRegenerateSamples = true;
867        }
868}
869
870
871void DeferredRenderer::SetShadingMethod(SHADING_METHOD s)
872{
873        if (s != mShadingMethod)
874        {
875                mShadingMethod = s;
876                mRegenerateSamples = true;
877        }
878}
879
880
881void DeferredRenderer::ComputeToneParameters(FrameBufferObject *fbo,
882                                                                                         DirectionalLight *light,
883                                                                                         float &imageKey,
884                                                                                         float &whiteLum,
885                                                                                         float &middleGrey)
886{
887        // hack: estimate value where sky burns out
888        whiteLum = log(WHITE_LUMINANCE);
889       
890        ////////////////////
891        //-- linear interpolate brightness key depending on the current sun position
892
893        const float minKey = 0.09f;
894        const float maxKey = 0.36f;
895
896        const float lightIntensity = DotProd(-light->GetDirection(), Vector3::UNIT_Z());
897        middleGrey = lightIntensity * maxKey + (1.0f - lightIntensity) * minKey;
898
899
900        //////////
901        //-- compute avg loglum
902
903        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
904        GLuint colorsTex = colorBuffer->GetTexture();
905
906        FlipFbos(fbo);
907       
908        sCgLogLumProgram->SetTexture(0, colorsTex);
909        DrawQuad(sCgLogLumProgram);
910       
911        PrintGLerror("ToneMapParams");
912
913
914        ///////////////////
915        //-- compute avg loglum in scene using mipmapping
916
917        glBindTexture(GL_TEXTURE_2D, fbo->GetColorBuffer(colorBufferIdx)->GetTexture());
918        glGenerateMipmapEXT(GL_TEXTURE_2D);
919}
920
921
922static void ExportData(float *data, int w, int h)
923{
924        startil();
925
926        cout << "w: " << w << " h: " << h << endl;
927        ILstring filename = ILstring("downsample2.jpg");
928        ilRegisterType(IL_FLOAT);
929
930        const int depth = 1;
931        const int bpp = 4;
932
933        if (!ilTexImage(w, h, depth, bpp, IL_RGBA, IL_FLOAT, data))
934        {
935                cerr << "IL error " << ilGetError() << endl;
936                stopil();
937                return;
938        }
939
940        if (!ilSaveImage(filename))
941        {
942                cerr << "TGA write error " << ilGetError() << endl;
943        }
944
945        stopil();
946}
947
948
949void DeferredRenderer::DownSample(FrameBufferObject *fbo,
950                                                                  int bufferIdx,
951                                                                  FrameBufferObject *downSampleFbo,
952                                                                  int downSampleBufferIdx,
953                                                                  ShaderProgram *program)
954{
955        ColorBufferObject *buffer = fbo->GetColorBuffer(bufferIdx);
956        GLuint tex = buffer->GetTexture();
957
958        glPushAttrib(GL_VIEWPORT_BIT);
959        glViewport(0, 0, downSampleFbo->GetWidth(), downSampleFbo->GetHeight());
960       
961        downSampleFbo->Bind();
962
963        program->SetTexture(0, tex);
964        glDrawBuffers(1, mrt + downSampleBufferIdx);
965
966        DrawQuad(program);
967       
968        glPopAttrib();
969        PrintGLerror("downsample");
970}
971
972
973void DeferredRenderer::ToneMap(FrameBufferObject *fbo,
974                                                           float imageKey,
975                                                           float whiteLum,
976                                                           float middleGrey)
977{
978        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
979        GLuint colorsTex = colorBuffer->GetTexture();
980        //FrameBufferObject::Release();
981
982        FlipFbos(fbo);
983
984        sCgToneProgram->SetTexture(0, colorsTex);
985        sCgToneProgram->SetValue1f(1, imageKey);
986        sCgToneProgram->SetValue1f(2, whiteLum);
987        sCgToneProgram->SetValue1f(3, middleGrey);
988
989        DrawQuad(sCgToneProgram);
990
991        PrintGLerror("ToneMap");
992}
993
994
995void DeferredRenderer::Output(FrameBufferObject *fbo)
996{
997        glPushAttrib(GL_VIEWPORT_BIT);
998        glViewport(0, 0, fbo->GetWidth(), fbo->GetHeight());
999       
1000        ColorBufferObject *colorBuffer = fbo->GetColorBuffer(colorBufferIdx);
1001        GLuint colorsTex = colorBuffer->GetTexture();
1002
1003        sCgDownSampleProgram->SetTexture(0, colorsTex);
1004
1005        FrameBufferObject::Release();
1006        DrawQuad(sCgDownSampleProgram);
1007
1008        PrintGLerror("output");
1009}
1010
1011
1012/*
1013void DeferredRenderer::BackProject(FrameBufferObject *fbo)
1014{
1015        // back project new frame into old one and check
1016        // if pixel still valid. store this property with ssao texture or even
1017        // betteer with color / depth texture. This way
1018        // we can sample this property together with the color / depth
1019        // values and we do not require additional texture lookups
1020        fbo->Bind();
1021
1022        GLuint colorsTex = fbo->GetColorBuffer(colorBufferIdx)->GetTexture();
1023        //GLuint ssaoTex = mIllumFbo->GetColorBuffer(mIllumFboIndex)->GetTexture();
1024
1025        // overwrite old color texture
1026        //colorBufferIdx = 3 - colorBufferIdx;
1027        //glDrawBuffers(1, mrt + colorBufferIdx);
1028        //glDrawBuffers(1, mrt + colorBufferIdx);
1029
1030        sCgCombineSsaoProgram->SetTexture(0, colorsTex);
1031        //sCgCombineSsaoProgram->SetTexture(1, ssaoTex);
1032
1033        DrawQuad(sCgBackProjectProgram);
1034       
1035        PrintGLerror("combine ssao");
1036}
1037*/
1038
1039
1040void DeferredRenderer::InitFrame()
1041{
1042        for (int i = 0; i < 4; ++ i)
1043                mOldCornersView[i] = mCornersView[i];
1044
1045        mOldProjViewMatrix = mProjViewMatrix;
1046        mOldEyePos = mEyePos;
1047        mEyePos = mCamera->GetPosition();
1048
1049        // hack: temporarily change far to improve precision
1050        const float oldFar = mCamera->GetFar();
1051        const float oldNear = mCamera->GetNear();
1052       
1053
1054        Matrix4x4 matViewing, matProjection;
1055
1056
1057        ///////////////////
1058
1059
1060        mCamera->GetViewOrientationMatrix(matViewing);
1061        mCamera->GetProjectionMatrix(matProjection);
1062
1063        mProjViewMatrix = matViewing * matProjection;
1064        ComputeViewVectors(mCamera, mCornersView[0], mCornersView[1], mCornersView[2], mCornersView[3]);
1065       
1066
1067        // switch roles of old and new fbo
1068        // the algorihm uses two input fbos, where the one
1069        // contais the color buffer from the last frame,
1070        // the other one will be written
1071
1072        mIllumFboIndex = 2 - mIllumFboIndex;
1073       
1074        // enable fragment shading
1075        ShaderManager::GetSingleton()->EnableFragmentProfile();
1076
1077        glDisable(GL_ALPHA_TEST);
1078        glDisable(GL_TEXTURE_2D);
1079        glDisable(GL_LIGHTING);
1080        glDisable(GL_BLEND);
1081        glDisable(GL_DEPTH_TEST);
1082
1083        glPolygonMode(GL_FRONT, GL_FILL);
1084
1085        glMatrixMode(GL_PROJECTION);
1086        glPushMatrix();
1087        glLoadIdentity();
1088
1089        gluOrtho2D(0, 1, 0, 1);
1090
1091
1092        glMatrixMode(GL_MODELVIEW);
1093        glPushMatrix();
1094        glLoadIdentity();
1095
1096       
1097        glPushAttrib(GL_VIEWPORT_BIT);
1098        glViewport(0, 0, mWidth, mHeight);
1099
1100        // revert to old far and near plane
1101        mCamera->SetFar(oldFar);
1102        mCamera->SetNear(oldNear);
1103}
1104
1105
1106} // namespace
Note: See TracBrowser for help on using the repository browser.