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

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