source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/chcdemo.cpp @ 2853

Revision 2853, 58.1 KB checked in by mattausch, 16 years ago (diff)
Line 
1// occquery.cpp : Defines the entry point for the console application.
2//
3#include "glInterface.h"
4#include <math.h>
5#include <time.h>
6#include "common.h"
7#include "RenderTraverser.h"
8#include "SceneEntity.h"
9#include "Vector3.h"
10#include "Matrix4x4.h"
11#include "ResourceManager.h"
12#include "Bvh.h"
13#include "Camera.h"
14#include "Geometry.h"
15#include "BvhLoader.h"
16#include "FrustumCullingTraverser.h"
17#include "StopAndWaitTraverser.h"
18#include "CHCTraverser.h"
19#include "CHCPlusPlusTraverser.h"
20#include "Visualization.h"
21#include "RenderState.h"
22#include "Timer/PerfTimer.h"
23#include "SceneQuery.h"
24#include "RenderQueue.h"
25#include "Material.h"
26#include <Cg/cg.h>
27#include <Cg/cgGL.h>
28#include "glfont2.h"
29#include "PerformanceGraph.h"
30#include "Environment.h"
31#include "Halton.h"
32#include "Transform3.h"
33#include "SampleGenerator.h"
34
35
36using namespace std;
37using namespace CHCDemoEngine;
38
39
40static Environment env;
41
42
43/////////////
44//-- fbos
45
46GLuint fbo;
47GLuint fbo1;
48GLuint fbo2;
49
50bool isFirstTexture = true;
51
52/////////////
53//-- renderbuffers
54
55
56GLuint depthBuffer;
57
58GLuint positionsBuffer;
59GLuint colorsBuffer;
60GLuint colorsBuffer1;
61GLuint colorsBuffer2;
62GLuint normalsBuffer;
63
64
65/////////////
66//-- textures
67
68
69GLuint positionsTex;
70GLuint colorsTex;
71GLuint colorsTex1;
72GLuint colorsTex2;
73
74GLuint normalsTex;
75
76GLuint noiseTex;
77
78GLuint fontTex;
79
80/// the renderable scene geometry
81SceneEntityContainer sceneEntities;
82// traverses and renders the hierarchy
83RenderTraverser *traverser = NULL;
84/// the hierarchy
85Bvh *bvh = NULL;
86/// handles scene loading
87ResourceManager *loader = NULL;
88/// the scene camera
89Camera *camera = NULL;
90/// the scene camera
91Camera *visCamera = NULL;
92/// the visualization
93Visualization *visualization = NULL;
94/// the current render state
95RenderState state;
96/// the rendering algorithm
97int renderMode = RenderTraverser::CHCPLUSPLUS;
98// eye near plane distance
99float nearDist = 0.2f;
100/// the pixel threshold where a node is still considered invisible
101int threshold;
102
103float fov = 50.0f;
104
105int assumedVisibleFrames = 10;
106int maxBatchSize = 50;
107
108int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
109
110SceneQuery *sceneQuery = NULL;
111RenderQueue *renderQueue = NULL;
112
113/// these values get scaled with the frame rate
114static float keyForwardMotion = 30.0f;
115static float keyRotation = 1.5f;
116
117/// elapsed time in milliseconds
118double elapsedTime = 1000.0f;
119double algTime = 1000.0f;
120
121static int winWidth = 1024;
122static int winHeight = 768;
123static float winAspectRatio = 1.0f;
124
125double accumulatedTime = 1000;
126float fps = 1e3f;
127
128float myfar = 0;
129
130glfont::GLFont myfont;
131
132// rendertexture
133static int texWidth = 1024;
134static int texHeight = 768;
135//static int texWidth = 2048;
136//static int texHeight = 2048;
137
138int renderedObjects = 0;
139int renderedNodes = 0;
140int renderedTriangles = 0;
141
142int issuedQueries = 0;
143int traversedNodes = 0;
144int frustumCulledNodes = 0;
145int queryCulledNodes = 0;
146int stateChanges = 0;
147int numBatches = 0;
148
149bool showHelp = false;
150bool showStatistics = false;
151bool showOptions = false;
152bool showBoundingVolumes = false;
153bool visMode = false;
154
155// mouse navigation state
156int xEyeBegin = 0;
157int yEyeBegin = 0;
158int yMotionBegin = 0;
159int verticalMotionBegin = 0;
160int horizontalMotionBegin = 0;
161
162bool useOptimization = false;
163bool useTightBounds = true;
164bool useRenderQueue = true;
165bool useMultiQueries = true;
166bool flyMode = true;
167
168SceneEntityContainer skyGeometry;
169
170bool leftKeyPressed = false;
171bool rightKeyPressed = false;
172bool upKeyPressed = false;
173bool downKeyPressed = false;
174bool descendKeyPressed = false;
175bool ascendKeyPressed = false;
176
177bool useSsao = false;
178
179bool showAlgorithmTime = false;
180
181GLubyte *randomNormals = NULL;
182
183PerfTimer frameTimer, algTimer;
184
185int renderType = RenderState::FIXED;
186
187PerformanceGraph *perfGraph = NULL;
188
189bool useFullScreen = false;
190
191// exp factor for ssao
192float expFactor = 0.05f;
193
194// ssao number of samples
195//#define NUM_SAMPLES 8
196#define NUM_SAMPLES 16
197
198// ssao random spherical samples
199static float samples[NUM_SAMPLES * 2];
200
201static Matrix4x4 matProjectionView = IdentityMatrix();
202
203
204// function forward declarations
205void InitExtensions();
206void DisplayVisualization();
207void InitGLstate();
208void InitRenderTexture();
209void InitCg();
210void CleanUp();
211void SetupEyeView();
212void UpdateEyeMtx();
213void SetupLighting();
214void DisplayStats();
215void Output(int x, int y, const char *string);
216void DrawHelpMessage();
217void RenderSky();
218void RenderVisibleObjects();
219
220void Begin2D();
221void End2D();
222void KeyBoard(unsigned char c, int x, int y);
223void DrawStatistics();
224void Display();
225void Special(int c, int x, int y);
226void KeyUp(unsigned char c, int x, int y);
227void SpecialKeyUp(int c, int x, int y);
228void Reshape(int w, int h);
229void Mouse(int button, int state, int x, int y);
230void LeftMotion(int x, int y);
231void RightMotion(int x, int y);
232void MiddleMotion(int x, int y);
233void CalcDecimalPoint(string &str, int d);
234void ResetTraverser();
235
236void KeyHorizontalMotion(float shift);
237void KeyVerticalMotion(float shift);
238
239void PlaceViewer(const Vector3 &oldPos);
240void DisplayRenderTexture();
241
242
243inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
244inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
245
246void InitFBO();
247
248void CreateNoiseTex2D();
249
250void ComputeViewVectors(Vector3 &tl, Vector3 &tr, Vector3 &bl, Vector3 &br);
251
252void GenerateSamples();
253
254
255GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
256
257
258/////////
259//-- cg stuff
260
261static CGcontext sCgContext = NULL;
262static CGprogram sCgMrtVertexProgram = NULL;
263static CGprogram sCgSsaoProgram = NULL;
264static CGprogram sCgDeferredProgram = NULL;
265
266static CGparameter sColorsTexParam;
267static CGparameter sPositionsTexParam;
268static CGparameter sNormalsTexParam;
269
270static CGparameter sColorsTexParamSsao;
271static CGparameter sPositionsTexParamSsao;
272static CGparameter sNormalsTexParamSsao;
273static CGparameter sNoiseTexParamSsao;
274
275static CGparameter sModelViewProjMatrixParam;
276static CGparameter sOldModelViewProjMatrixParam;
277static CGparameter sMaxDepthParam;
278static CGparameter sMaxDepthParamSsao;
279static CGparameter sMaxDepthParamTex;
280
281static CGparameter sSamplesParamSsao;
282static CGparameter sOldTexParamSsao;
283static CGparameter sNoiseMultiplierParam;
284static CGparameter sExpFactorParamSsao;
285
286
287static void cgErrorCallback()
288{
289        CGerror lastError = cgGetError();
290
291        if(lastError)
292        {
293                printf("%s\n\n", cgGetErrorString(lastError));
294                printf("%s\n", cgGetLastListing(sCgContext));
295                printf("Cg error, exiting...\n");
296
297                exit(0);
298        }
299}
300
301
302static void PrintGLerror(char *msg)
303{
304        GLenum errCode;
305        const GLubyte *errStr;
306       
307        if ((errCode = glGetError()) != GL_NO_ERROR)
308        {
309                errStr = gluErrorString(errCode);
310                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
311        }
312}
313
314
315int main(int argc, char* argv[])
316{
317        int returnCode = 0;
318
319        Vector3 camPos(.0f, .0f, .0f);
320        Vector3 camDir(.0f, 1.0f, .0f);
321
322        cout << "=== reading environment file === " << endl;
323
324        string envFileName = "default.env";
325        if (!env.Read(envFileName))
326        {
327                cerr << "loading environment " << envFileName << " failed!" << endl;
328        }
329        else
330        {
331                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
332                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
333                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
334
335                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
336                env.GetFloatParam(string("keyRotation"), keyRotation);
337
338                env.GetIntParam(string("winWidth"), winWidth);
339                env.GetIntParam(string("winHeight"), winHeight);
340
341                env.GetBoolParam(string("useFullScreen"), useFullScreen);
342                env.GetFloatParam(string("expFactor"), expFactor);
343                env.GetVectorParam(string("camPosition"), camPos);
344                env.GetVectorParam(string("camDirection"), camDir);
345
346                //env.GetStringParam(string("modelPath"), model_path);
347                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
348
349                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
350                cout << "maxBatchSize: " << maxBatchSize << endl;
351                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
352
353                cout << "keyForwardMotion: " << keyForwardMotion << endl;
354                cout << "keyRotation: " << keyRotation << endl;
355                cout << "winWidth: " << winWidth << endl;
356                cout << "winHeight: " << winHeight << endl;
357                cout << "useFullScreen: " << useFullScreen << endl;
358                cout << "camPosition: " << camPos << endl;
359                cout << "expFactor: " << expFactor << endl;
360                //cout << "model path: " << model_path << endl;
361        }
362
363        ///////////////////////////
364
365        camera = new Camera(winWidth, winHeight, fov);
366        camera->SetNear(nearDist);
367       
368        camera->SetDirection(camDir);
369        camera->SetPosition(camPos);
370
371        visCamera = new Camera(winWidth, winHeight, fov);
372
373        visCamera->SetNear(0.0f);
374        visCamera->Yaw(.5 * M_PI);
375
376        renderQueue = new RenderQueue(&state, camera);
377
378        glutInitWindowSize(winWidth, winHeight);
379        glutInit(&argc, argv);
380        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
381        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
382
383        //glutInitDisplayString("samples=2");
384
385        if (!useFullScreen)
386                glutCreateWindow("FriendlyCulling");
387        else
388        {
389                glutGameModeString( "1024x768:32@75" );
390                glutEnterGameMode();
391        }
392
393        glutDisplayFunc(Display);
394        glutKeyboardFunc(KeyBoard);
395        glutSpecialFunc(Special);
396        glutReshapeFunc(Reshape);
397        glutMouseFunc(Mouse);
398        glutIdleFunc(Display);
399        glutKeyboardUpFunc(KeyUp);
400        glutSpecialUpFunc(SpecialKeyUp);
401        glutIgnoreKeyRepeat(true);
402
403        // initialise gl graphics
404        InitExtensions();
405        InitGLstate();
406
407        //glEnable(GL_MULTISAMPLE_ARB);
408        //glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
409
410        InitFBO();
411       
412        LeftMotion(0, 0);
413        MiddleMotion(0, 0);
414
415        perfGraph = new PerformanceGraph(1000);
416
417        loader = new ResourceManager();
418
419        //const string filename("data/city/model/city.dem");
420        const string filename = string(model_path + "city.dem");
421
422        if (loader->Load(filename, sceneEntities))
423                cout << "scene " << filename << " loaded" << endl;
424        else
425        {
426                cerr << "loading scene " << filename << " failed" << endl;
427                CleanUp();
428                exit(0);
429        }
430
431        SceneEntityContainer dummy;
432
433        const string envname = string(model_path + "env.dem");
434
435        if (loader->Load(envname, skyGeometry))
436                cout << "sky box " << filename << " loaded" << endl;
437        else
438        {
439                cerr << "loading sky box " << filename << " failed" << endl;
440                CleanUp();
441                exit(0);
442        }
443
444        const string bvh_filename = string(model_path + "city.bvh");
445        BvhLoader bvhLoader;
446        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
447
448        if (!bvh)
449        {
450                cerr << "loading bvh " << bvh_filename << " failed" << endl;
451                CleanUp();
452                exit(0);
453        }
454
455        // set far plane based on scene extent
456        myfar = 10.0f * Magnitude(bvh->GetBox().Diagonal());
457        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
458
459        bvh->SetCamera(camera);
460       
461        InitCg();
462
463        // create noise texture for ssao
464        CreateNoiseTex2D();
465
466        // init render traverser
467        ResetTraverser();
468
469        visualization = new Visualization(bvh, camera, NULL, &state);
470
471        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
472
473        // frame time is restarted every frame
474        frameTimer.Start();
475
476
477        glutMainLoop();
478
479        // clean up
480        CleanUp();
481
482        return 0;
483}
484
485
486void InitCg(void)
487{
488        // Setup Cg
489        cgSetErrorCallback(cgErrorCallback);
490
491        // Create cgContext.
492        sCgContext = cgCreateContext();
493
494        // get the best profile for this hardware
495        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
496        //assert(sCgFragmentProfile != CG_PROFILE_UNKNOWN);
497        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
498
499        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
500        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
501
502        sCgMrtVertexProgram =
503                cgCreateProgramFromFile(sCgContext,
504                                                                CG_SOURCE,
505                                                                "src/shaders/mrt.cg",
506                                                                RenderState::sCgVertexProfile,
507                                                                "vtx",
508                                                                NULL);
509
510        if (sCgMrtVertexProgram != NULL)
511        {
512                cgGLLoadProgram(sCgMrtVertexProgram);
513
514                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
515                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
516        }
517
518        RenderState::sCgMrtFragmentTexProgram =
519                cgCreateProgramFromFile(sCgContext,
520                                                                CG_SOURCE,
521                                                                "src/shaders/mrt.cg",
522                                                                RenderState::sCgFragmentProfile,
523                                                                "fragtex",
524                                                                NULL);
525
526        if (RenderState::sCgMrtFragmentTexProgram != NULL)
527        {
528                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
529
530                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
531                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
532                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
533
534                cgGLSetParameter1f(sMaxDepthParamTex, 10.0f / myfar);
535                Debug << "maxdepth: " << 10.0f / myfar << endl;
536        }
537        else
538                cerr << "fragment tex program failed to load" << endl;
539
540        RenderState::sCgMrtFragmentProgram =
541                cgCreateProgramFromFile(sCgContext,
542                                                                CG_SOURCE,
543                                                                "src/shaders/mrt.cg",
544                                                                RenderState::sCgFragmentProfile,
545                                                                "frag",
546                                                                NULL);
547
548        if (RenderState::sCgMrtFragmentProgram != NULL)
549        {
550                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
551
552                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
553                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
554                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
555
556                cgGLSetParameter1f(sMaxDepthParam, 10.0f / myfar);
557        }
558        else
559                cerr << "fragment program failed to load" << endl;
560
561        PrintGLerror("test");
562
563
564        ///////////////
565
566        sCgSsaoProgram =
567                cgCreateProgramFromFile(sCgContext,
568                                                                CG_SOURCE,
569                                                                "src/shaders/deferred.cg",
570                                                                RenderState::sCgFragmentProfile,
571                                                                "main_ssao",
572                                                                NULL);
573
574        if (sCgSsaoProgram != NULL)
575        {
576                cgGLLoadProgram(sCgSsaoProgram);
577
578                // we need size of texture for scaling
579                sPositionsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "positions"); 
580                sColorsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "colors"); 
581                sNormalsTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "normals"); 
582                sNoiseTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "noiseTexture");
583                sNoiseMultiplierParam = cgGetNamedParameter(sCgSsaoProgram, "noiseMultiplier");
584                sOldModelViewProjMatrixParam = cgGetNamedParameter(sCgSsaoProgram, "oldModelViewProj");
585                sMaxDepthParamSsao = cgGetNamedParameter(sCgSsaoProgram, "maxDepth");
586                sExpFactorParamSsao = cgGetNamedParameter(sCgSsaoProgram, "expFactor");
587
588                cgGLSetParameter1f(sMaxDepthParamSsao, myfar / 10.0f);
589                cgGLSetParameter1f(sExpFactorParamSsao, expFactor);
590
591                sSamplesParamSsao = cgGetNamedParameter(sCgSsaoProgram, "samples");
592                sOldTexParamSsao = cgGetNamedParameter(sCgSsaoProgram, "oldTex"); 
593
594                GenerateSamples(); cgGLSetParameterArray2f(sSamplesParamSsao, 0, NUM_SAMPLES, (const float *)samples);
595        }
596        else
597                cerr << "ssao program failed to load" << endl;
598
599       
600        sCgDeferredProgram =
601                cgCreateProgramFromFile(sCgContext,
602                                                                CG_SOURCE,
603                                                                "src/shaders/deferred.cg",
604                                                                RenderState::sCgFragmentProfile,
605                                                                "main",
606                                                                NULL);
607
608        if (sCgDeferredProgram != NULL)
609        {
610                cgGLLoadProgram(sCgDeferredProgram);
611
612                // we need size of texture for scaling
613                sPositionsTexParam = cgGetNamedParameter(sCgDeferredProgram, "positions"); 
614                sColorsTexParam = cgGetNamedParameter(sCgDeferredProgram, "colors"); 
615                sNormalsTexParam = cgGetNamedParameter(sCgDeferredProgram, "normals");
616        }
617        else
618                cerr << "deferred program failed to load" << endl;
619
620
621        PrintGLerror("init");
622
623        cout << "cg initialization successful" << endl;
624}
625
626
627void PrintFBOStatus(GLenum status)
628{
629        switch(status)
630        {
631        case GL_FRAMEBUFFER_COMPLETE_EXT:
632                cout << "frame buffer object created successfully" << endl;
633                break;
634        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
635                cerr << "incomplete attachment" << endl;
636                break;
637        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
638                cerr << "missing attachment" << endl;
639                break;
640        case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
641                cerr << "incomplete dimensions" << endl;
642                break;
643        case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
644                cerr << "incomplete formats" << endl;
645                break;
646        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
647                cerr << "incomplete draw buffer" << endl;
648                break;
649        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
650                cerr << "incomplete read buffer" << endl;
651                break;
652        case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
653                cerr << "framebuffer unsupported" << endl;
654                break;
655        default:
656                cerr << "unknown status code " << status << endl;
657        }
658}
659
660
661void InitFBO()
662{
663        glGenFramebuffersEXT(1, &fbo);
664        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
665
666       
667        ////////////
668        //-- colors buffer
669
670        glGenRenderbuffersEXT(1, &colorsBuffer);
671        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer);
672       
673        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
674
675        int samples = 8;
676        //glEnable(GL_MULTISAMPLE_ARB);
677        //glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_RGBA8, texWidth, texHeight);
678        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer);
679       
680        glGenTextures(1, &colorsTex);
681        glBindTexture(GL_TEXTURE_2D, colorsTex);
682
683        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
684        //glGenerateMipmapEXT(GL_TEXTURE_2D);
685        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex, 0);
686
687        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
688        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
689
690        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
691        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
692
693
694        //////////
695        //-- positions buffer
696
697        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
698        glGenRenderbuffersEXT(1, &positionsBuffer);
699        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, positionsBuffer);
700        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
701
702        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_RENDERBUFFER_EXT, positionsBuffer);
703
704        glGenTextures(1, &positionsTex);
705        glBindTexture(GL_TEXTURE_2D, positionsTex);
706        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
707        //glGenerateMipmapEXT(GL_TEXTURE_2D);
708        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, positionsTex, 0);
709
710        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
711        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
712
713        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
714        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
715
716        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
717       
718       
719        ////////
720        //-- normals buffer
721
722        glGenRenderbuffersEXT(1, &normalsBuffer);
723        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, normalsBuffer);
724        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, texWidth, texHeight);
725       
726        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_RENDERBUFFER_EXT, normalsBuffer);
727
728        glGenTextures(1, &normalsTex);
729        glBindTexture(GL_TEXTURE_2D, normalsTex);
730        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
731        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_TEXTURE_2D, normalsTex, 0);
732
733        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
734        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
735
736        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
737        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
738
739        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
740
741
742        ///////////
743        //-- create depth buffer
744
745        glGenRenderbuffersEXT(1, &depthBuffer);
746        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer);
747        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, texWidth, texHeight);
748        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer);
749
750       
751        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
752       
753       
754
755        //////////////////////////////////
756
757
758
759        glGenFramebuffersEXT(1, &fbo1);
760        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo1);
761
762       
763        ////////////
764        //-- colors buffer
765
766        glGenRenderbuffersEXT(1, &colorsBuffer1);
767        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer1);
768       
769        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
770        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer1);
771       
772        glGenTextures(1, &colorsTex1);
773        glBindTexture(GL_TEXTURE_2D, colorsTex1);
774
775        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
776        //glGenerateMipmapEXT(GL_TEXTURE_2D);
777        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex1, 0);
778
779        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
780        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
781
782        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
783        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
784
785        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
786        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
787
788        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
789
790
791
792        /////////////////////////
793
794        glGenFramebuffersEXT(1, &fbo2);
795        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo2);
796
797       
798        ////////////
799        //-- colors buffer
800
801        glGenRenderbuffersEXT(1, &colorsBuffer2);
802        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorsBuffer2);
803       
804        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA32F_ARB, texWidth, texHeight);
805        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorsBuffer2);
806       
807        glGenTextures(1, &colorsTex2);
808        glBindTexture(GL_TEXTURE_2D, colorsTex2);
809
810        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, NULL);
811        //glGenerateMipmapEXT(GL_TEXTURE_2D);
812        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorsTex2, 0);
813
814        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
815        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
816
817        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
818        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
819
820        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
821        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
822
823        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
824        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
825
826        PrintFBOStatus(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
827
828        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
829
830        PrintGLerror("fbo");
831}
832
833
834bool InitFont(void)
835{
836        glEnable(GL_TEXTURE_2D);
837
838        glGenTextures(1, &fontTex);
839        glBindTexture(GL_TEXTURE_2D, fontTex);
840        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
841                return false;
842
843        glDisable(GL_TEXTURE_2D);
844       
845        return true;
846}
847
848
849void InitGLstate()
850{
851        glClearColor(0.5f, 0.5f, 0.8f, 0.0f);
852       
853        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
854        glPixelStorei(GL_PACK_ALIGNMENT,1);
855       
856        glDepthFunc(GL_LESS);
857        glEnable(GL_DEPTH_TEST);
858
859        SetupLighting();
860
861        glColor3f(1.0f, 1.0f, 1.0f);
862        glShadeModel(GL_SMOOTH);
863       
864        glMaterialf(GL_FRONT, GL_SHININESS, 64);
865        glEnable(GL_NORMALIZE);
866               
867        //glEnable(GL_ALPHA_TEST);
868        glDisable(GL_ALPHA_TEST);
869        glAlphaFunc(GL_GEQUAL, 0.8f);
870
871        glFrontFace(GL_CCW);
872        glCullFace(GL_BACK);
873        glEnable(GL_CULL_FACE);
874
875        //glDisable(GL_CULL_FACE);
876        glDisable(GL_TEXTURE_2D);
877
878        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
879        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
880        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
881
882        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
883        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
884        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
885
886        glDepthFunc(GL_LESS);
887
888        if (!InitFont())
889                cerr << "font creation failed" << endl;
890        else
891                cout << "successfully created font" << endl;
892}
893
894
895void DrawHelpMessage()
896{
897        const char *message[] =
898        {
899                "Help information",
900                "",
901                "'F1'           - shows/dismisses this message",
902                "'F2'           - shows/hides bird eye view",
903                "'F3'           - shows/hides bounds (boxes or tight bounds)",
904                "'F4',          - shows/hides parameters",
905                "'F5'           - shows/hides statistics",
906                "'F6',          - toggles between fly/walkmode",
907                "'F7',          - cycles throw render modes",
908                "'F8',          - enables/disables ambient occlusion (only deferred)",
909                "'F9',          - shows pure algorithm render time (using glFinish)",
910                "'SPACE'        - cycles through occlusion culling algorithms",
911                "",
912                "'MOUSE LEFT'        - turn left/right, move forward/backward",
913                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
914                "'MOUSE MIDDLE'      - move up/down, left/right",
915                "'CURSOR UP/DOWN'    - move forward/backward",
916                "'CURSOR LEFT/RIGHT' - turn left/right",
917                "",
918                "'-'/'+'        - decreases/increases max batch size",
919                "'1'/'2'        - downward/upward motion",
920                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
921                "'5'/'6'        - decreases/increases assumed visible frames",
922                "",
923                "'R'            - use render queue",
924                "'B'            - use tight bounds",
925                "'M'            - use multiqueries",
926                "'O'            - use CHC optimization (geometry queries for leaves)",
927                0,
928        };
929       
930       
931        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
932
933        glRecti(30, 30, winWidth - 30, winHeight - 30);
934
935        glEnd();
936
937        glColor3f(1.0f, 1.0f, 1.0f);
938       
939        glEnable(GL_TEXTURE_2D);
940        myfont.Begin();
941
942        int x = 40, y = 30;
943
944        for(int i = 0; message[i] != 0; ++ i)
945        {
946                if(message[i][0] == '\0')
947                {
948                        y += 15;
949                }
950                else
951                {
952                        myfont.DrawString(message[i], x, winHeight - y);
953                        y += 25;
954                }
955        }
956        glDisable(GL_TEXTURE_2D);
957}
958
959
960void ResetTraverser()
961{
962        DEL_PTR(traverser);
963
964        bvh->ResetNodeClassifications();
965
966        switch (renderMode)
967        {
968        case RenderTraverser::CULL_FRUSTUM:
969                traverser = new FrustumCullingTraverser();
970                break;
971        case RenderTraverser::STOP_AND_WAIT:
972                traverser = new StopAndWaitTraverser();
973                break;
974        case RenderTraverser::CHC:
975                traverser = new CHCTraverser();
976                break;
977        case RenderTraverser::CHCPLUSPLUS:
978                traverser = new CHCPlusPlusTraverser();
979                break;
980       
981        default:
982                traverser = new FrustumCullingTraverser();
983        }
984
985        traverser->SetCamera(camera);
986        traverser->SetHierarchy(bvh);
987        traverser->SetRenderQueue(renderQueue);
988        traverser->SetRenderState(&state);
989        traverser->SetUseOptimization(useOptimization);
990        traverser->SetUseRenderQueue(useRenderQueue);
991        traverser->SetVisibilityThreshold(threshold);
992        traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
993        traverser->SetMaxBatchSize(maxBatchSize);
994        traverser->SetUseMultiQueries(useMultiQueries);
995        traverser->SetUseTightBounds(useTightBounds);
996        traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
997        traverser->SetRenderQueue(renderQueue);
998}
999
1000
1001void SetupLighting()
1002{
1003        glEnable(GL_LIGHTING);
1004        glEnable(GL_LIGHT0);
1005        glEnable(GL_LIGHT1);
1006       
1007        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
1008        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
1009        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
1010           
1011        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
1012
1013        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
1014        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
1015        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
1016
1017
1018        ////////////
1019        //-- second light
1020
1021        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
1022        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
1023        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
1024        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
1025
1026        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
1027        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
1028        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
1029
1030       
1031        //////////////////////////////
1032
1033        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
1034        glLightfv(GL_LIGHT0, GL_POSITION, position);
1035
1036        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
1037        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1038
1039        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
1040        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1041        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
1042}
1043
1044
1045void SetupEyeView()
1046{
1047        Matrix4x4 matViewing, matProjection;
1048
1049        if (renderType == RenderState::DEFERRED)
1050        {
1051                cgGLSetMatrixParameterfc(sOldModelViewProjMatrixParam, (const float *)matProjectionView.x);
1052        }
1053
1054        glMatrixMode(GL_PROJECTION);
1055        glLoadIdentity();
1056
1057        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1058
1059        glMatrixMode(GL_MODELVIEW);
1060        glLoadIdentity();
1061        camera->SetupCameraView();
1062
1063        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
1064        glLightfv(GL_LIGHT0, GL_POSITION, position);
1065
1066        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
1067        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1068
1069       
1070        camera->GetModelViewMatrix(matViewing);
1071        camera->GetProjectionMatrix(matProjection);
1072
1073        matProjectionView = matViewing * matProjection;
1074       
1075        if (renderType == RenderState::DEFERRED)
1076        {
1077                // set modelview matrix for shaders
1078                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
1079                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
1080                                                                        CG_GL_MATRIX_IDENTITY);
1081
1082                static Matrix4x4 identity = IdentityMatrix();
1083                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
1084        }               
1085}
1086
1087
1088void KeyHorizontalMotion(float shift)
1089{
1090        Vector3 hvec = camera->GetDirection();
1091        hvec.z = 0;
1092
1093        Vector3 pos = camera->GetPosition();
1094        pos += hvec * shift;
1095       
1096        camera->SetPosition(pos);
1097}
1098
1099
1100void KeyVerticalMotion(float shift)
1101{
1102        Vector3 uvec = Vector3(0, 0, shift);
1103
1104        Vector3 pos = camera->GetPosition();
1105        pos += uvec;
1106       
1107        camera->SetPosition(pos);
1108}
1109
1110
1111void Display()
1112{       
1113        Vector3 oldPos = camera->GetPosition();
1114
1115        if (leftKeyPressed)
1116                camera->Pitch(KeyRotationAngle());
1117        if (rightKeyPressed)
1118                camera->Pitch(-KeyRotationAngle());
1119        if (upKeyPressed)
1120                KeyHorizontalMotion(KeyShift());
1121        if (downKeyPressed)
1122                KeyHorizontalMotion(-KeyShift());
1123        if (ascendKeyPressed)
1124                KeyVerticalMotion(KeyShift());
1125        if (descendKeyPressed)
1126                KeyVerticalMotion(-KeyShift());
1127
1128        // place view on ground
1129        if (!flyMode) PlaceViewer(oldPos);
1130
1131        if (showAlgorithmTime)
1132        {
1133                glFinish();
1134                algTimer.Start();
1135        }
1136       
1137        // render without shading
1138        switch (renderType)
1139        {
1140        case RenderState::FIXED:
1141       
1142                glEnable(GL_MULTISAMPLE_ARB);
1143                //glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
1144
1145                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1146
1147                state.SetRenderType(RenderState::FIXED);
1148                glEnable(GL_LIGHTING);
1149
1150                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1151                cgGLDisableProfile(RenderState::sCgVertexProfile);
1152
1153                glDrawBuffers(1, mrt);
1154
1155                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1156
1157                break;
1158
1159        case RenderState::DEPTH_PASS:
1160
1161                glEnable(GL_MULTISAMPLE_ARB);
1162                //glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
1163
1164                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1165
1166                state.SetRenderType(RenderState::DEPTH_PASS);
1167                glDisable(GL_LIGHTING);
1168
1169                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1170                cgGLDisableProfile(RenderState::sCgVertexProfile);
1171       
1172                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1173
1174                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1175
1176                glDrawBuffers(1, mrt);
1177
1178                break;
1179       
1180        case RenderState::DEFERRED:
1181
1182                // multisampling not working with deferred shading
1183                //glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
1184                glDisable(GL_MULTISAMPLE_ARB);
1185
1186                state.SetRenderType(RenderState::DEFERRED);
1187
1188                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
1189       
1190                glPushAttrib(GL_VIEWPORT_BIT);
1191                glViewport(0, 0, texWidth, texHeight);
1192
1193                cgGLEnableProfile(RenderState::sCgFragmentProfile);
1194                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
1195
1196                cgGLEnableProfile(RenderState::sCgVertexProfile);
1197                cgGLBindProgram(sCgMrtVertexProgram);
1198
1199                glDrawBuffers(3, mrt);
1200
1201                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1202
1203                break;
1204        }
1205
1206
1207        glDepthFunc(GL_LESS);
1208
1209        glDisable(GL_TEXTURE_2D);
1210        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1211               
1212
1213        LODLevel::InitFrame(camera->GetPosition());
1214
1215
1216        // bring eye modelview matrix up-to-date
1217        SetupEyeView();
1218
1219
1220        /*state.Reset();
1221        state.SetState(RenderState::RENDER);
1222       
1223        glEnableClientState(GL_VERTEX_ARRAY);
1224        glEnableClientState(GL_NORMAL_ARRAY);
1225
1226        for (int i = 0; i < loader->mSceneEntities.size(); ++ i)
1227        {
1228                SceneEntity *ent = loader->mSceneEntities[i];
1229
1230                ent->UpdateLODs(camera);
1231                ent->Render(&state);
1232        }*/
1233
1234        // actually render the scene geometry using one of the specified algorithms
1235        traverser->RenderScene();
1236
1237
1238
1239        /////////
1240        //-- do the rest of the rendering
1241
1242        glEnableClientState(GL_VERTEX_ARRAY);
1243        glEnableClientState(GL_NORMAL_ARRAY);
1244
1245
1246        // reset depth pass and render visible objects
1247        if (renderType == RenderState::DEPTH_PASS)
1248        {
1249                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1250                RenderVisibleObjects();
1251        }
1252       
1253
1254        ///////////////
1255        //-- render sky
1256
1257        RenderSky();
1258
1259        state.Reset();
1260
1261        glDisableClientState(GL_VERTEX_ARRAY);
1262        glDisableClientState(GL_NORMAL_ARRAY);
1263
1264        if (renderType == RenderState::DEFERRED)
1265        {
1266                glPopAttrib();
1267                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1268
1269                cgGLDisableProfile(RenderState::sCgVertexProfile);
1270                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1271
1272                glDrawBuffers(1, mrt);
1273
1274                DisplayRenderTexture();
1275        }
1276
1277       
1278        ///////////
1279
1280        state.SetRenderType(RenderState::FIXED);
1281
1282        if (showAlgorithmTime)
1283        {
1284                glFinish();
1285
1286                algTime = algTimer.Elapsedms();
1287                perfGraph->AddData(algTime);
1288
1289                perfGraph->Draw();
1290        }
1291        else
1292        {
1293                if (visMode) DisplayVisualization();
1294        }
1295
1296        glFlush();
1297
1298        const bool restart = true;
1299        elapsedTime = frameTimer.Elapsedms(restart);
1300
1301        DisplayStats();
1302
1303        isFirstTexture = !isFirstTexture;
1304
1305        glutSwapBuffers();
1306}
1307
1308
1309#pragma warning( disable : 4100 )
1310void KeyBoard(unsigned char c, int x, int y)
1311{
1312        switch(c)
1313        {
1314        case 27:
1315                CleanUp();
1316                exit(0);
1317                break;
1318        case 32: //space
1319                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1320                ResetTraverser();
1321                break;
1322        case 'h':
1323        case 'H':
1324                showHelp = !showHelp;
1325                break;
1326        case '+':
1327                maxBatchSize += 10;
1328                traverser->SetMaxBatchSize(maxBatchSize);
1329                break;
1330        case '-':
1331                maxBatchSize -= 10;
1332                if (maxBatchSize < 0) maxBatchSize = 1;
1333                traverser->SetMaxBatchSize(maxBatchSize);               
1334                break;
1335        case 'M':
1336        case 'm':
1337                useMultiQueries = !useMultiQueries;
1338                traverser->SetUseMultiQueries(useMultiQueries);
1339                break;
1340        case '1':
1341                descendKeyPressed = true;
1342                break;
1343        case '2':
1344                ascendKeyPressed = true;
1345                break;
1346        case '3':
1347                if (trianglesPerVirtualLeaf >= 100)
1348                        trianglesPerVirtualLeaf -= 100;
1349                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1350                break;
1351        case '4':
1352                trianglesPerVirtualLeaf += 100;
1353                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1354                break;
1355        case '5':
1356                assumedVisibleFrames -= 1;
1357                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1358                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1359                break;
1360        case '6':
1361                assumedVisibleFrames += 1;
1362                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1363                break;
1364        case '7':
1365                expFactor *= 0.5f;
1366                break;
1367        case '8':
1368                expFactor *= 2.0f;
1369                if (expFactor > 1.0f) expFactor = 1.0f;
1370                break;
1371        case 'o':
1372        case 'O':
1373                useOptimization = !useOptimization;
1374                traverser->SetUseOptimization(useOptimization);
1375                break;
1376        case 'a':
1377        case 'A':
1378                        leftKeyPressed = true;
1379                break;
1380        case 'd':
1381        case 'D':
1382                        rightKeyPressed = true;
1383                break;
1384        case 'w':
1385        case 'W':
1386                        upKeyPressed = true;
1387                break;
1388        case 's':
1389        case 'S':
1390                        downKeyPressed = true;
1391                break;
1392        case 'r':
1393        case 'R':
1394                {
1395                        useRenderQueue = !useRenderQueue;
1396                        traverser->SetUseRenderQueue(useRenderQueue);
1397                }
1398                break;
1399        case 'b':
1400        case 'B':
1401                {
1402                        useTightBounds = !useTightBounds;
1403                        traverser->SetUseTightBounds(useTightBounds);
1404                }
1405                break;
1406        default:
1407                return;
1408        }
1409
1410        glutPostRedisplay();
1411}
1412
1413
1414void SpecialKeyUp(int c, int x, int y)
1415{
1416        switch (c)
1417        {
1418        case GLUT_KEY_LEFT:
1419                leftKeyPressed = false;
1420                break;
1421        case GLUT_KEY_RIGHT:
1422                rightKeyPressed = false;
1423                break;
1424        case GLUT_KEY_UP:
1425                upKeyPressed = false;
1426                break;
1427        case GLUT_KEY_DOWN:
1428                downKeyPressed = false;
1429                break;
1430        default:
1431                return;
1432        }
1433        //glutPostRedisplay();
1434}
1435
1436
1437void KeyUp(unsigned char c, int x, int y)
1438{
1439        switch (c)
1440        {
1441        case 'A':
1442        case 'a':
1443                leftKeyPressed = false;
1444                break;
1445        case 'D':
1446        case 'd':
1447                rightKeyPressed = false;
1448                break;
1449        case 'W':
1450        case 'w':
1451                upKeyPressed = false;
1452                break;
1453        case 'S':
1454        case 's':
1455                downKeyPressed = false;
1456                break;
1457        case '1':
1458                descendKeyPressed = false;
1459                break;
1460        case '2':
1461                ascendKeyPressed = false;
1462                break;
1463       
1464        default:
1465                return;
1466        }
1467        //glutPostRedisplay();
1468}
1469
1470
1471void Special(int c, int x, int y)
1472{
1473        switch(c)
1474        {
1475        case GLUT_KEY_F1:
1476                showHelp = !showHelp;
1477                break;
1478        case GLUT_KEY_F2:
1479                visMode = !visMode;
1480                break;
1481        case GLUT_KEY_F3:
1482                showBoundingVolumes = !showBoundingVolumes;
1483                traverser->SetShowBounds(showBoundingVolumes);
1484                break;
1485        case GLUT_KEY_F4:
1486                showOptions = !showOptions;
1487                break;
1488        case GLUT_KEY_F5:
1489                showStatistics = !showStatistics;
1490                break;
1491        case GLUT_KEY_F6:
1492                flyMode = !flyMode;
1493                break;
1494        case GLUT_KEY_F7:
1495
1496                renderType = (renderType + 1) % 3;
1497                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1498               
1499                break;
1500        case GLUT_KEY_F8:
1501                useSsao = !useSsao;
1502                break;
1503        case GLUT_KEY_F9:
1504                showAlgorithmTime = !showAlgorithmTime;
1505                break;
1506
1507        case GLUT_KEY_LEFT:
1508                {
1509                        leftKeyPressed = true;
1510                        camera->Pitch(KeyRotationAngle());
1511                }
1512                break;
1513        case GLUT_KEY_RIGHT:
1514                {
1515                        rightKeyPressed = true;
1516                        camera->Pitch(-KeyRotationAngle());
1517                }
1518                break;
1519        case GLUT_KEY_UP:
1520                {
1521                        upKeyPressed = true;
1522                        KeyHorizontalMotion(KeyShift());
1523                }
1524                break;
1525        case GLUT_KEY_DOWN:
1526                {
1527                        downKeyPressed = true;
1528                        KeyHorizontalMotion(-KeyShift());
1529                }
1530                break;
1531        default:
1532                return;
1533
1534        }
1535
1536        glutPostRedisplay();
1537}
1538
1539#pragma warning( default : 4100 )
1540
1541
1542void Reshape(int w, int h)
1543{
1544        winAspectRatio = 1.0f;
1545
1546        glViewport(0, 0, w, h);
1547       
1548        winWidth = w;
1549        winHeight = h;
1550
1551        if (w) winAspectRatio = (float) w / (float) h;
1552
1553        glMatrixMode(GL_PROJECTION);
1554        glLoadIdentity();
1555
1556        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1557
1558        glMatrixMode(GL_MODELVIEW);
1559
1560        glutPostRedisplay();
1561}
1562
1563
1564void Mouse(int button, int state, int x, int y)
1565{
1566        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
1567        {
1568                xEyeBegin = x;
1569                yMotionBegin = y;
1570
1571                glutMotionFunc(LeftMotion);
1572        }
1573        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
1574        {
1575                xEyeBegin = x;
1576                yEyeBegin = y;
1577                yMotionBegin = y;
1578
1579                glutMotionFunc(RightMotion);
1580        }
1581        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1582        {
1583                horizontalMotionBegin = x;
1584                verticalMotionBegin = y;
1585                glutMotionFunc(MiddleMotion);
1586        }
1587
1588        glutPostRedisplay();
1589}
1590
1591
1592/**     rotation for left/right mouse drag
1593        motion for up/down mouse drag
1594*/
1595void LeftMotion(int x, int y)
1596{
1597        Vector3 viewDir = camera->GetDirection();
1598        Vector3 pos = camera->GetPosition();
1599
1600        // don't move in the vertical direction
1601        Vector3 horView(viewDir[0], viewDir[1], 0);
1602       
1603        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1604
1605        camera->Pitch(eyeXAngle);
1606
1607        pos += horView * (yMotionBegin - y) * 0.2f;
1608       
1609        camera->SetPosition(pos);
1610       
1611        xEyeBegin = x;
1612        yMotionBegin = y;
1613
1614        glutPostRedisplay();
1615}
1616
1617
1618/**     rotation for left / right mouse drag
1619        motion for up / down mouse drag
1620*/
1621void RightMotion(int x, int y)
1622{
1623        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1624        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1625
1626        camera->Yaw(eyeYAngle);
1627        camera->Pitch(eyeXAngle);
1628
1629        xEyeBegin = x;
1630        yEyeBegin = y;
1631
1632        glutPostRedisplay();
1633}
1634
1635
1636// strafe
1637void MiddleMotion(int x, int y)
1638{
1639        Vector3 viewDir = camera->GetDirection();
1640        Vector3 pos = camera->GetPosition();
1641
1642        // the 90 degree rotated view vector
1643        // y zero so we don't move in the vertical
1644        Vector3 rVec(viewDir[0], viewDir[1], 0);
1645       
1646        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1647        rVec = rot * rVec;
1648       
1649        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
1650        pos[2] += (verticalMotionBegin - y) * 0.1f;
1651
1652        camera->SetPosition(pos);
1653
1654        horizontalMotionBegin = x;
1655        verticalMotionBegin = y;
1656
1657        glutPostRedisplay();
1658}
1659
1660
1661void InitExtensions(void)
1662{
1663        GLenum err = glewInit();
1664
1665        if (GLEW_OK != err)
1666        {
1667                // problem: glewInit failed, something is seriously wrong
1668                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1669                exit(1);
1670        }
1671        if  (!GLEW_ARB_occlusion_query)
1672        {
1673                printf("I require the GL_ARB_occlusion_query to work.\n");
1674                exit(1);
1675        }
1676}
1677
1678
1679void Begin2D()
1680{
1681        glDisable(GL_LIGHTING);
1682        glDisable(GL_DEPTH_TEST);
1683
1684        glMatrixMode(GL_PROJECTION);
1685        glPushMatrix();
1686        glLoadIdentity();
1687
1688        gluOrtho2D(0, winWidth, 0, winHeight);
1689
1690        glMatrixMode(GL_MODELVIEW);
1691        glPushMatrix();
1692        glLoadIdentity();
1693}
1694
1695
1696void End2D()
1697{
1698        glMatrixMode(GL_PROJECTION);
1699        glPopMatrix();
1700
1701        glMatrixMode(GL_MODELVIEW);
1702        glPopMatrix();
1703
1704        glEnable(GL_LIGHTING);
1705        glEnable(GL_DEPTH_TEST);
1706}
1707
1708
1709// displays the visualisation of culling algorithm
1710void DisplayVisualization()
1711{
1712        visualization->SetFrameId(traverser->GetCurrentFrameId());
1713       
1714        Begin2D();
1715        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1716        glEnable(GL_BLEND);
1717        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
1718
1719        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
1720        glDisable(GL_BLEND);
1721        End2D();
1722       
1723       
1724        AxisAlignedBox3 box = bvh->GetBox();
1725
1726        // hack: set far plane for viz
1727        camera->SetFar(0.35f * Magnitude(box.Diagonal()));
1728
1729        const float offs = box.Size().x * 0.3f;
1730       
1731        //Vector3 vizpos = Vector3(box.Min().x, box.Min().y + box.Size().y * 0.5f, box.Min().z + box.Size().z * 50);
1732        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
1733       
1734        visCamera->SetPosition(vizpos);
1735        visCamera->ResetPitchAndYaw();
1736        //visCamera->Pitch(M_PI);
1737
1738        glPushAttrib(GL_VIEWPORT_BIT);
1739        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
1740
1741        glMatrixMode(GL_PROJECTION);
1742        glPushMatrix();
1743
1744        glLoadIdentity();
1745       
1746        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
1747
1748        glMatrixMode(GL_MODELVIEW);
1749        glPushMatrix();
1750
1751        visCamera->SetupCameraView();
1752
1753        //Matrix4x4 rotX = RotationXMatrix(camera->GetYaw());
1754        //glMultMatrixf((float *)rotX.x);
1755        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1756        glMultMatrixf((float *)rotZ.x);
1757
1758        Vector3 pos = camera->GetPosition();
1759        glTranslatef(-pos.x, -pos.y, -pos.z);
1760
1761
1762        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1763        glLightfv(GL_LIGHT0, GL_POSITION, position);
1764
1765        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1766        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1767
1768        glClear(GL_DEPTH_BUFFER_BIT);
1769
1770
1771        ////////////
1772        //-- visualization of the occlusion culling
1773
1774        visualization->Render();
1775       
1776       
1777        // reset previous settings
1778        glPopAttrib();
1779
1780        glMatrixMode(GL_PROJECTION);
1781        glPopMatrix();
1782        glMatrixMode(GL_MODELVIEW);
1783        glPopMatrix();
1784}
1785
1786
1787// cleanup routine after the main loop
1788void CleanUp()
1789{
1790        DEL_PTR(traverser);
1791        DEL_PTR(sceneQuery);
1792        DEL_PTR(bvh);
1793        DEL_PTR(visualization);
1794        DEL_PTR(camera);
1795        DEL_PTR(loader);
1796        DEL_PTR(renderQueue);
1797        DEL_PTR(perfGraph);
1798
1799        if (sCgMrtVertexProgram)
1800                cgDestroyProgram(sCgMrtVertexProgram);
1801        if (RenderState::sCgMrtFragmentProgram)
1802                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1803        if (RenderState::sCgMrtFragmentTexProgram)
1804                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
1805        if (sCgSsaoProgram)
1806                cgDestroyProgram(sCgSsaoProgram);
1807        if (sCgDeferredProgram)
1808                cgDestroyProgram(sCgDeferredProgram);
1809        if (sCgContext)
1810                cgDestroyContext(sCgContext);
1811
1812        glDeleteFramebuffersEXT(1, &fbo);
1813        glDeleteRenderbuffersEXT(1, &depthBuffer);
1814        glDeleteRenderbuffersEXT(1, &colorsBuffer);
1815        glDeleteRenderbuffersEXT(1, &normalsBuffer);
1816        glDeleteRenderbuffersEXT(1, &positionsBuffer);
1817
1818        glDeleteTextures(1, &colorsTex);
1819        glDeleteTextures(1, &normalsTex);
1820        glDeleteTextures(1, &positionsTex);
1821        glDeleteTextures(1, &noiseTex);
1822        glDeleteTextures(1, &fontTex);
1823}
1824
1825
1826// this function inserts a dezimal point after each 1000
1827void CalcDecimalPoint(string &str, int d, int len)
1828{
1829        static vector<int> numbers;
1830        numbers.clear();
1831
1832        static string shortStr;
1833        shortStr.clear();
1834
1835        static char hstr[100];
1836
1837        while (d != 0)
1838        {
1839                numbers.push_back(d % 1000);
1840                d /= 1000;
1841        }
1842
1843        // first element without leading zeros
1844        if (numbers.size() > 0)
1845        {
1846                sprintf(hstr, "%d", numbers.back());
1847                shortStr.append(hstr);
1848        }
1849       
1850        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1851        {
1852                sprintf(hstr, ",%03d", numbers[i]);
1853                shortStr.append(hstr);
1854        }
1855
1856        int dif = len - (int)shortStr.size();
1857
1858        for (int i = 0; i < dif; ++ i)
1859        {
1860                str += " ";
1861        }
1862
1863        str.append(shortStr);
1864}
1865
1866
1867void DisplayStats()
1868{
1869        static char msg[9][300];
1870
1871        static double frameTime = elapsedTime;
1872        static double renderTime = algTime;
1873
1874        const float expFactor = 0.1f;
1875
1876        // if some strange render time spike happened in this frame => don't count
1877        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1878       
1879        static float rTime = 1000.0f;
1880
1881        if (showAlgorithmTime)
1882        {
1883                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1884        }
1885
1886        accumulatedTime += elapsedTime;
1887
1888        if (accumulatedTime > 500) // update every fraction of a second
1889        {       
1890                accumulatedTime = 0;
1891
1892                if (frameTime) fps = 1e3f / (float)frameTime;
1893
1894                rTime = renderTime;
1895                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1896                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1897                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1898
1899                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1900                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1901                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1902                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1903                stateChanges = traverser->GetStats().mNumStateChanges;
1904                numBatches = traverser->GetStats().mNumBatches;
1905        }
1906
1907
1908        Begin2D();
1909
1910        glEnable(GL_BLEND);
1911        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1912
1913        if (showHelp)
1914        {       
1915                DrawHelpMessage();
1916        }
1917        else
1918        {
1919                if (showOptions)
1920                {
1921                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1922                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1923                }
1924
1925                if (showStatistics)
1926                {
1927                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1928                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1929                }
1930
1931                glEnable(GL_TEXTURE_2D);
1932
1933                myfont.Begin();
1934
1935                if (showOptions)
1936                {
1937                        glColor3f(0.0f, 1.0f, 0.0f);
1938
1939                        int i = 0;
1940
1941                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
1942       
1943                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1944                                                        useMultiQueries, useTightBounds, useRenderQueue);
1945
1946                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useSsao);
1947
1948                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1949
1950                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1951                                assumedVisibleFrames, maxBatchSize);
1952
1953                        for (int j = 0; j < 4; ++ j)
1954                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1955                }
1956
1957                if (showStatistics)
1958                {
1959                        glColor3f(1.0f, 1.0f, 0.0f);
1960
1961                        string str;
1962                        string str2;
1963
1964                        int len = 10;
1965                        CalcDecimalPoint(str, renderedTriangles, len);
1966                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
1967
1968                        int i = 4;
1969
1970                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1971                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1972
1973                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1974                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1975
1976                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1977                                issuedQueries, stateChanges, numBatches);
1978
1979                        for (int j = 4; j < 7; ++ j)
1980                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1981                }
1982
1983                glColor3f(1.0f, 1.0f, 1.0f);
1984                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1985               
1986                if (!showAlgorithmTime)
1987                {
1988                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1989                }
1990                else
1991                {
1992                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1993                }
1994
1995                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1996               
1997                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1998                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1999        }
2000
2001        glDisable(GL_BLEND);
2002        glDisable(GL_TEXTURE_2D);
2003
2004        End2D();
2005}       
2006
2007
2008void RenderSky()
2009{
2010        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
2011
2012        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
2013                (*sit)->Render(&state);
2014}
2015
2016
2017void RenderVisibleObjects()
2018{
2019        state.SetRenderType(RenderState::FIXED);
2020        state.Reset();
2021
2022        glEnable(GL_LIGHTING);
2023        glDepthFunc(GL_LEQUAL);
2024
2025        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2026
2027        SceneEntityContainer::const_iterator sit,
2028                sit_end = traverser->GetVisibleObjects().end();
2029
2030        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
2031                renderQueue->Enqueue(*sit);
2032               
2033        renderQueue->Apply();
2034
2035        glDepthFunc(GL_LESS);
2036}
2037
2038
2039void PlaceViewer(const Vector3 &oldPos)
2040{
2041        Vector3 playerPos = camera->GetPosition();
2042
2043        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
2044
2045        if (validIntersect)
2046                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
2047        {
2048                camera->SetPosition(playerPos);
2049        }
2050}
2051
2052
2053void DisplayRenderTexture3()
2054{
2055        glEnable(GL_TEXTURE_2D);
2056
2057        if (isFirstTexture)
2058                glBindTexture(GL_TEXTURE_2D, colorsTex1);
2059        else
2060                glBindTexture(GL_TEXTURE_2D, colorsTex2);
2061
2062        glDisable(GL_LIGHTING);
2063       
2064        glMatrixMode(GL_PROJECTION);
2065        glPushMatrix();
2066        glLoadIdentity();
2067
2068        glMatrixMode(GL_MODELVIEW);
2069        glPushMatrix();
2070        glLoadIdentity();
2071
2072        const float offs = 0.5f;
2073        glOrtho(-offs, offs, -offs, offs, 0, 1);
2074       
2075        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2076
2077        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
2078        glBegin(GL_QUADS);
2079
2080        glTexCoord2f(0, 0); glVertex3f(-offs, -offs, -0.5f);
2081        glTexCoord2f(1, 0); glVertex3f( offs, -offs, -0.5f);
2082        glTexCoord2f(1, 1); glVertex3f( offs,  offs, -0.5f);
2083        glTexCoord2f(0, 1); glVertex3f(-offs,  offs, -0.5f);
2084
2085        glEnd();
2086
2087        glEnable(GL_LIGHTING);
2088        glDisable(GL_TEXTURE_2D);
2089       
2090        glMatrixMode(GL_PROJECTION);
2091        glPopMatrix();
2092
2093        glMatrixMode(GL_MODELVIEW);
2094        glPopMatrix();
2095
2096        PrintGLerror("displaytexture3");
2097}
2098
2099
2100void DisplayRenderTexture()
2101{
2102        GLuint oldTex;
2103
2104        if (isFirstTexture)
2105        {
2106                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo1);
2107                oldTex = colorsTex2;
2108        }
2109        else
2110        {
2111                glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo2);
2112                oldTex = colorsTex1;
2113        }
2114
2115        glPushAttrib(GL_VIEWPORT_BIT);
2116        glViewport(0, 0, texWidth, texHeight);
2117
2118        glDrawBuffers(1, mrt);
2119
2120        glDisable(GL_ALPHA_TEST);
2121        glDisable(GL_TEXTURE_2D);
2122        glDisable(GL_LIGHTING);
2123       
2124        glMatrixMode(GL_PROJECTION);
2125        glPushMatrix();
2126        glLoadIdentity();
2127
2128        glMatrixMode(GL_MODELVIEW);
2129        glPushMatrix();
2130        glLoadIdentity();
2131
2132        const float offs = 0.5f;
2133       
2134        glOrtho(-offs, offs, -offs, offs, 0, 1);
2135       
2136        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2137
2138        cgGLEnableProfile(RenderState::sCgFragmentProfile);
2139
2140        if (useSsao)
2141        {
2142                cgGLBindProgram(sCgSsaoProgram);
2143               
2144                cgGLSetTextureParameter(sPositionsTexParamSsao, positionsTex);
2145                cgGLEnableTextureParameter(sPositionsTexParamSsao);
2146
2147                cgGLSetTextureParameter(sColorsTexParamSsao, colorsTex);
2148                cgGLEnableTextureParameter(sColorsTexParamSsao);
2149
2150                cgGLSetTextureParameter(sNormalsTexParamSsao, normalsTex);
2151                cgGLEnableTextureParameter(sNormalsTexParamSsao);
2152
2153                cgGLSetTextureParameter(sNoiseTexParamSsao, noiseTex);
2154                cgGLEnableTextureParameter(sNoiseTexParamSsao);
2155
2156                cgGLSetTextureParameter(sOldTexParamSsao, oldTex);
2157                cgGLEnableTextureParameter(sOldTexParamSsao);
2158
2159                cgGLSetParameter1f(sNoiseMultiplierParam, RandomValue(3.0f, 17.0f));
2160                cgGLSetParameter1f(sExpFactorParamSsao, expFactor);
2161
2162                GenerateSamples(); cgGLSetParameterArray2f(sSamplesParamSsao, 0, NUM_SAMPLES, (const float *)samples);
2163        }
2164        else
2165        {
2166                cgGLBindProgram(sCgDeferredProgram);
2167
2168                cgGLSetTextureParameter(sPositionsTexParam, positionsTex);
2169                cgGLEnableTextureParameter(sPositionsTexParam);
2170
2171                cgGLSetTextureParameter(sColorsTexParam, colorsTex);
2172                cgGLEnableTextureParameter(sColorsTexParam);
2173
2174                cgGLSetTextureParameter(sNormalsTexParam, normalsTex);
2175                cgGLEnableTextureParameter(sNormalsTexParam);
2176        }
2177
2178        Vector3 tl, tr, bl, br;
2179        ComputeViewVectors(tl, tr, bl, br);
2180
2181        glColor3f(1.0f, 1.0f, 1.0f);
2182
2183        glBegin(GL_QUADS);
2184
2185        // note: slightly larger texture hides ambient occlusion error on border but costs resolution
2186        //float offs2 = 0.55f;
2187        float offs2 = 0.5f;
2188
2189        glColor3f(bl.x, bl.y, bl.z); glTexCoord2f(0, 0); glVertex3f(-offs2, -offs2, -0.5f);
2190        glColor3f(br.x, br.y, br.z); glTexCoord2f(1, 0); glVertex3f( offs2, -offs2, -0.5f);
2191        glColor3f(tr.x, tr.y, tr.z); glTexCoord2f(1, 1); glVertex3f( offs2,  offs2, -0.5f);
2192        glColor3f(tl.x, tl.y, tl.z); glTexCoord2f(0, 1); glVertex3f(-offs2,  offs2, -0.5f);
2193
2194        glEnd();
2195
2196       
2197        if (useSsao)
2198        {
2199                cgGLDisableTextureParameter(sColorsTexParamSsao);
2200                cgGLDisableTextureParameter(sPositionsTexParamSsao);
2201                cgGLDisableTextureParameter(sNormalsTexParamSsao);
2202                cgGLDisableTextureParameter(sNoiseTexParamSsao);
2203                cgGLDisableTextureParameter(sOldTexParamSsao);
2204        }
2205        else
2206        {
2207                cgGLDisableTextureParameter(sColorsTexParam);
2208                cgGLDisableTextureParameter(sPositionsTexParam);
2209                cgGLDisableTextureParameter(sNormalsTexParam);
2210        }
2211
2212        cgGLDisableProfile(RenderState::sCgFragmentProfile);
2213       
2214        glEnable(GL_LIGHTING);
2215        glDisable(GL_TEXTURE_2D);
2216       
2217        glMatrixMode(GL_PROJECTION);
2218        glPopMatrix();
2219
2220        glMatrixMode(GL_MODELVIEW);
2221        glPopMatrix();
2222
2223        glPopAttrib();
2224
2225        PrintGLerror("displaytexture");
2226
2227        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
2228
2229        DisplayRenderTexture3();
2230}
2231
2232#if 0
2233// kustls magic sample positions
2234void GenerateSamples()
2235{
2236        static const float mysamples[] =
2237        {
2238                -0.326212f, -0.405805f,
2239                -0.840144f, -0.07358f,
2240                -0.695914f, 0.457137f,
2241                -0.203345f, 0.620716,
2242                0.96234f, -0.194983f,
2243                0.473434f, -0.480026f,
2244                0.519456, 0.767022f,
2245                0.185461f, -0.893124f,
2246                0.507431f, 0.064425f,
2247                0.89642f, 0.412458f,
2248                -0.32194f, -0.932615f,
2249                -0.791559f, -0.597705f,
2250                0.326212f, 0.405805f,
2251                0.840144f, 0.07358f,
2252                0.695914f, -0.457137f,
2253                0.203345f, -0.620716,
2254                -0.96234f, 0.194983f,
2255                -0.473434f, 0.480026f,
2256                -0.519456, -0.767022f,
2257                -0.185461f, 0.893124f,
2258                -0.507431f, -0.064425f,
2259                -0.89642f, -0.412458f,
2260                0.32194f, 0.932615f,
2261                0.791559f, 0.597705f
2262        };
2263
2264        for (int i = 0; i < NUM_SAMPLES; ++ i)
2265        {
2266                samples[i] = mysamples[i];
2267        }
2268}
2269
2270#else
2271
2272
2273void GenerateSamples()
2274{
2275        /*static HaltonSequence halton;
2276
2277        float r[2];
2278
2279        // generates poisson distribution on disc
2280        float minDist = 2.0f / sqrt((float)NUM_SAMPLES);
2281
2282        //cout << "minDist before= " << minDist << endl;
2283
2284        for (int i = 0; i < NUM_SAMPLES * 2; i += 2)
2285        {
2286                int tries = 0, totalTries = 0;
2287
2288                // repeat until valid sample was found
2289                while (1)
2290                {
2291                        ++ tries;
2292                        ++ totalTries;
2293
2294                        halton.GetNext(2, r);
2295
2296                        //const float rx = RandomValue(-1, 1);
2297                        //const float ry = RandomValue(-1, 1);
2298
2299                        const float rx = r[0] * 2.0f - 1.0f;
2300                        const float ry = r[1] * 2.0f - 1.0f;
2301
2302                        // check if in disk, else exit early
2303                        if (rx * rx + ry * ry > 1)
2304                                continue;
2305
2306                        bool sampleValid = true;
2307
2308                        // check poisson property
2309                        for (int j = 0; ((j < i) && sampleValid); j += 2)
2310                        {
2311                                const float dist =
2312                                        sqrt((samples[j] - rx) * (samples[j] - rx) +
2313                                             (samples[j + 1] - ry) * (samples[j + 1] - ry));
2314                       
2315                                if (dist < minDist)
2316                                        sampleValid = false;
2317                        }
2318
2319                        if (sampleValid)
2320                        {
2321                                samples[i] = rx;
2322                                samples[i + 1]= ry;
2323                                break;
2324                        }
2325
2326                        if (tries > 2000)
2327                        {
2328                                minDist *= 0.9f;
2329                                tries = 0;
2330                        }
2331                }
2332        }
2333*/
2334
2335        static PoissonDiscSampleGenerator poisson(NUM_SAMPLES, 1.0f);
2336        poisson.Generate((Sample2 *)samples);
2337}
2338
2339
2340#endif
2341
2342
2343void ComputeViewVectors(Vector3 &tl, Vector3 &tr, Vector3 &bl, Vector3 &br)
2344{
2345        float myfov = fov * M_PI / 180.0f;
2346
2347        const float w_far = 2.0f * tan(myfov / 2.0f);
2348        const float aspect = texWidth / texHeight;
2349
2350        const float h_far = w_far / aspect;
2351
2352        float t1 = h_far * 0.5f;
2353        float t2 = w_far * 0.5f;
2354
2355#if 0
2356        bl = Normalize(-Vector3(-t1, -t2, 1.0f));
2357        br = Normalize(-Vector3( t1, -t2, 1.0f));
2358        tl = Normalize(-Vector3(-t1,  t2, 1.0f));
2359        tr = Normalize(-Vector3( t1,  t2, 1.0f));
2360#else
2361        bl = -Normalize(camera->GetDirection());
2362        br = -Normalize(camera->GetDirection());
2363        tl = -Normalize(camera->GetDirection());
2364        tr = -Normalize(camera->GetDirection());
2365#endif
2366        // normalize to 0 .. 1
2367        bl = bl * 0.5f + 0.5f;
2368        br = br * 0.5f + 0.5f;
2369        tl = tl * 0.5f + 0.5f;
2370        tr = tr * 0.5f + 0.5f;
2371}
2372
2373
2374void CreateNoiseTex2D()
2375{
2376        randomNormals = new GLubyte[texWidth * texHeight * 3];
2377
2378        for (int i = 0; i < texWidth * texHeight * 3; i += 3)
2379        {
2380                // create random samples over sphere
2381                const float rx = RandomValue(0, 1);
2382                const float theta = 2.0f * acos(sqrt(1.0f - rx));
2383
2384                randomNormals[i + 0] = (GLubyte)((cos(theta) * 0.5f + 0.5f) * 255.0f);
2385                randomNormals[i + 1] = (GLubyte)((sin(theta) * 0.5f + 0.5f) * 255.0f);
2386                randomNormals[i + 2] = 0;
2387        }
2388
2389        glEnable(GL_TEXTURE_2D);
2390        glGenTextures(1, &noiseTex);
2391        glBindTexture(GL_TEXTURE_2D, noiseTex);
2392               
2393        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2394        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2395        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
2396        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
2397
2398        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, randomNormals);
2399        //gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texWidth, texHeight, GL_RGB, GL_UNSIGNED_BYTE, randomNormals);
2400
2401        glBindTexture(GL_TEXTURE_2D, 0);
2402        glDisable(GL_TEXTURE_2D);
2403
2404        cout << "created noise texture" << endl;
2405        PrintGLerror("noisetexture");
2406}
Note: See TracBrowser for help on using the repository browser.