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

Revision 3168, 32.9 KB checked in by mattausch, 16 years ago (diff)

removed bug (second aa output), normsl normalization now during mrt output

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