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

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