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

Revision 2868, 40.3 KB checked in by mattausch, 16 years ago (diff)

changed ssao to multipass algorithm

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#include "SsaoShader.h"
36#include "DeferredShader.h"
37
38
39using namespace std;
40using namespace CHCDemoEngine;
41
42
43static Environment env;
44
45
46/////////////
47//-- fbos
48
49FrameBufferObject *fbo;
50
51bool isFirstTexture = true;
52
53GLuint fontTex;
54
55/// the renderable scene geometry
56SceneEntityContainer sceneEntities;
57// traverses and renders the hierarchy
58RenderTraverser *traverser = NULL;
59/// the hierarchy
60Bvh *bvh = NULL;
61/// handles scene loading
62ResourceManager *loader = NULL;
63/// the scene camera
64Camera *camera = NULL;
65/// the scene camera
66Camera *visCamera = NULL;
67/// the visualization
68Visualization *visualization = NULL;
69/// the current render state
70RenderState state;
71/// the rendering algorithm
72int renderMode = RenderTraverser::CHCPLUSPLUS;
73// eye near plane distance
74float nearDist = 0.2f;
75/// the field of view
76float fov = 50.0f;
77/// the pixel threshold where a node is still considered invisible
78int threshold;
79
80int assumedVisibleFrames = 10;
81int maxBatchSize = 50;
82
83int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
84
85SceneQuery *sceneQuery = NULL;
86RenderQueue *renderQueue = NULL;
87
88/// these values get scaled with the frame rate
89static float keyForwardMotion = 30.0f;
90static float keyRotation = 1.5f;
91
92/// elapsed time in milliseconds
93double elapsedTime = 1000.0f;
94double algTime = 1000.0f;
95
96static int winWidth = 1024;
97static int winHeight = 768;
98static float winAspectRatio = 1.0f;
99
100double accumulatedTime = 1000;
101float fps = 1e3f;
102
103float myfar = 0;
104
105glfont::GLFont myfont;
106
107// rendertexture
108static int texWidth = 1024;
109static int texHeight = 768;
110
111//static int texWidth = 512;
112//static int texHeight = 384;
113
114//static int texWidth = 2048;
115//static int texHeight = 2048;
116
117int renderedObjects = 0;
118int renderedNodes = 0;
119int renderedTriangles = 0;
120
121int issuedQueries = 0;
122int traversedNodes = 0;
123int frustumCulledNodes = 0;
124int queryCulledNodes = 0;
125int stateChanges = 0;
126int numBatches = 0;
127
128bool showHelp = false;
129bool showStatistics = false;
130bool showOptions = true;
131bool showBoundingVolumes = false;
132bool visMode = false;
133
134// mouse navigation state
135int xEyeBegin = 0;
136int yEyeBegin = 0;
137int yMotionBegin = 0;
138int verticalMotionBegin = 0;
139int horizontalMotionBegin = 0;
140
141bool useOptimization = false;
142bool useTightBounds = true;
143bool useRenderQueue = true;
144bool useMultiQueries = true;
145bool flyMode = true;
146
147SceneEntityContainer skyGeometry;
148
149bool leftKeyPressed = false;
150bool rightKeyPressed = false;
151bool upKeyPressed = false;
152bool downKeyPressed = false;
153bool descendKeyPressed = false;
154bool ascendKeyPressed = false;
155
156bool useSsao = false;
157static float ssaoExpFactor = 0.1f;
158
159bool showAlgorithmTime = false;
160
161GLubyte *randomNormals = NULL;
162
163PerfTimer frameTimer, algTimer;
164
165int renderType = RenderState::FIXED;
166
167PerformanceGraph *perfGraph = NULL;
168
169bool useFullScreen = false;
170
171bool useLODs = true;
172
173
174static Matrix4x4 matProjectionView = IdentityMatrix();
175
176
177
178// function forward declarations
179void InitExtensions();
180void DisplayVisualization();
181void InitGLstate();
182void InitRenderTexture();
183void InitCg();
184void CleanUp();
185void SetupEyeView();
186void UpdateEyeMtx();
187void SetupLighting();
188void DisplayStats();
189void Output(int x, int y, const char *string);
190void DrawHelpMessage();
191void RenderSky();
192void RenderVisibleObjects();
193
194void Begin2D();
195void End2D();
196void KeyBoard(unsigned char c, int x, int y);
197void DrawStatistics();
198void Display();
199void Special(int c, int x, int y);
200void KeyUp(unsigned char c, int x, int y);
201void SpecialKeyUp(int c, int x, int y);
202void Reshape(int w, int h);
203void Mouse(int button, int state, int x, int y);
204void LeftMotion(int x, int y);
205void RightMotion(int x, int y);
206void MiddleMotion(int x, int y);
207void CalcDecimalPoint(string &str, int d);
208void ResetTraverser();
209
210void KeyHorizontalMotion(float shift);
211void KeyVerticalMotion(float shift);
212
213void PlaceViewer(const Vector3 &oldPos);
214
215
216inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
217inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
218
219void InitFBO();
220
221SsaoShader *ssaoShader = NULL;
222DeferredShader *deferredShader = NULL;
223
224GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
225
226
227/////////
228//-- cg stuff
229
230static CGcontext sCgContext = NULL;
231static CGprogram sCgMrtVertexProgram = NULL;
232
233static CGparameter sModelViewProjMatrixParam;
234static CGparameter sMaxDepthParam;
235static CGparameter sMaxDepthParamTex;
236
237static Matrix4x4 oldViewProjMatrix;
238
239
240static void cgErrorCallback()
241{
242        CGerror lastError = cgGetError();
243
244        if(lastError)
245        {
246                printf("%s\n\n", cgGetErrorString(lastError));
247                printf("%s\n", cgGetLastListing(sCgContext));
248               
249                printf("Cg error, exiting...\n");
250
251                exit(0);
252        }
253}
254
255
256static void PrintGLerror(char *msg)
257{
258        GLenum errCode;
259        const GLubyte *errStr;
260       
261        if ((errCode = glGetError()) != GL_NO_ERROR)
262        {
263                errStr = gluErrorString(errCode);
264                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
265        }
266}
267
268
269int main(int argc, char* argv[])
270{
271        int returnCode = 0;
272
273        Vector3 camPos(.0f, .0f, .0f);
274        Vector3 camDir(.0f, 1.0f, .0f);
275
276        cout << "=== reading environment file === " << endl;
277
278        string envFileName = "default.env";
279        if (!env.Read(envFileName))
280        {
281                cerr << "loading environment " << envFileName << " failed!" << endl;
282        }
283        else
284        {
285                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
286                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
287                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
288
289                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
290                env.GetFloatParam(string("keyRotation"), keyRotation);
291
292                env.GetIntParam(string("winWidth"), winWidth);
293                env.GetIntParam(string("winHeight"), winHeight);
294
295                env.GetBoolParam(string("useFullScreen"), useFullScreen);
296                env.GetFloatParam(string("expFactor"), ssaoExpFactor);
297                env.GetVectorParam(string("camPosition"), camPos);
298                env.GetVectorParam(string("camDirection"), camDir);
299
300                env.GetBoolParam(string("useLODs"), useLODs);
301
302                //env.GetStringParam(string("modelPath"), model_path);
303                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
304
305
306                cout << "*********** parameters ***************" << endl;
307
308                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
309                cout << "maxBatchSize: " << maxBatchSize << endl;
310                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
311
312                cout << "keyForwardMotion: " << keyForwardMotion << endl;
313                cout << "keyRotation: " << keyRotation << endl;
314                cout << "winWidth: " << winWidth << endl;
315                cout << "winHeight: " << winHeight << endl;
316                cout << "useFullScreen: " << useFullScreen << endl;
317                cout << "useLODs: " << useLODs << endl;
318                cout << "camPosition: " << camPos << endl;
319                cout << "expFactor: " << ssaoExpFactor << endl;
320                //cout << "model path: " << model_path << endl;
321        }
322
323        ///////////////////////////
324
325        camera = new Camera(winWidth, winHeight, fov);
326        camera->SetNear(nearDist);
327       
328        camera->SetDirection(camDir);
329        camera->SetPosition(camPos);
330
331        visCamera = new Camera(winWidth, winHeight, fov);
332
333        visCamera->SetNear(0.0f);
334        visCamera->Yaw(.5 * M_PI);
335
336        renderQueue = new RenderQueue(&state, camera);
337
338        glutInitWindowSize(winWidth, winHeight);
339        glutInit(&argc, argv);
340        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
341        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
342        //glutInitDisplayString("samples=2");
343
344        SceneEntity::SetUseLODs(useLODs);
345
346
347        if (!useFullScreen)
348        {
349                glutCreateWindow("FriendlyCulling");
350        }
351        else
352        {
353                glutGameModeString( "1024x768:32@75" );
354                glutEnterGameMode();
355        }
356
357        glutDisplayFunc(Display);
358        glutKeyboardFunc(KeyBoard);
359        glutSpecialFunc(Special);
360        glutReshapeFunc(Reshape);
361        glutMouseFunc(Mouse);
362        glutIdleFunc(Display);
363        glutKeyboardUpFunc(KeyUp);
364        glutSpecialUpFunc(SpecialKeyUp);
365        glutIgnoreKeyRepeat(true);
366
367        // initialise gl graphics
368        InitExtensions();
369        InitGLstate();
370
371        glEnable(GL_MULTISAMPLE_ARB);
372        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
373
374        InitFBO();
375       
376        LeftMotion(0, 0);
377        MiddleMotion(0, 0);
378
379        perfGraph = new PerformanceGraph(1000);
380
381        loader = new ResourceManager();
382
383        //const string filename("data/city/model/city.dem");
384        const string filename = string(model_path + "city.dem");
385
386        if (loader->Load(filename, sceneEntities))
387                cout << "scene " << filename << " loaded" << endl;
388        else
389        {
390                cerr << "loading scene " << filename << " failed" << endl;
391                CleanUp();
392                exit(0);
393        }
394
395        SceneEntityContainer dummy;
396
397        const string envname = string(model_path + "env.dem");
398
399        if (loader->Load(envname, skyGeometry))
400                cout << "sky box " << filename << " loaded" << endl;
401        else
402        {
403                cerr << "loading sky box " << filename << " failed" << endl;
404                CleanUp();
405                exit(0);
406        }
407
408        const string bvh_filename = string(model_path + "city.bvh");
409        BvhLoader bvhLoader;
410        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
411
412        if (!bvh)
413        {
414                cerr << "loading bvh " << bvh_filename << " failed" << endl;
415                CleanUp();
416                exit(0);
417        }
418
419        // set far plane based on scene extent
420        myfar = 10.0f * Magnitude(bvh->GetBox().Diagonal());
421        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
422
423        bvh->SetCamera(camera);
424       
425        InitCg();
426
427        DeferredShader::Init(sCgContext);
428        SsaoShader::Init(sCgContext);
429
430        deferredShader = new DeferredShader(texWidth, texHeight);
431        ssaoShader = new SsaoShader(texWidth, texHeight, camera, myfar / 10.0f);
432
433        // initialize the render traverser
434        ResetTraverser();
435
436        visualization = new Visualization(bvh, camera, NULL, &state);
437
438        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
439
440        // frame time is restarted every frame
441        frameTimer.Start();
442
443        // the rendering loop
444        glutMainLoop();
445
446        // clean up
447        CleanUp();
448
449        return 0;
450}
451
452
453void InitCg(void)
454{
455        // Setup Cg
456        cgSetErrorCallback(cgErrorCallback);
457
458        // Create cgContext.
459        sCgContext = cgCreateContext();
460
461        // get the best profile for this hardware
462        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
463        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
464
465        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
466        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
467
468        sCgMrtVertexProgram =
469                cgCreateProgramFromFile(sCgContext,
470                                                                CG_SOURCE,
471                                                                "src/shaders/mrt.cg",
472                                                                RenderState::sCgVertexProfile,
473                                                                "vtx",
474                                                                NULL);
475
476        if (sCgMrtVertexProgram != NULL)
477        {
478                cgGLLoadProgram(sCgMrtVertexProgram);
479
480                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
481                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
482        }
483
484        RenderState::sCgMrtFragmentTexProgram =
485                cgCreateProgramFromFile(sCgContext,
486                                                                CG_SOURCE,
487                                                                "src/shaders/mrt.cg",
488                                                                RenderState::sCgFragmentProfile,
489                                                                "fragtex",
490                                                                NULL);
491
492        if (RenderState::sCgMrtFragmentTexProgram != NULL)
493        {
494                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
495
496                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
497                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
498                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
499
500                cgGLSetParameter1f(sMaxDepthParamTex, 10.0f / myfar);
501                Debug << "maxdepth: " << 10.0f / myfar << endl;
502        }
503        else
504                cerr << "fragment tex program failed to load" << endl;
505
506        RenderState::sCgMrtFragmentProgram =
507                cgCreateProgramFromFile(sCgContext,
508                                                                CG_SOURCE,
509                                                                "src/shaders/mrt.cg",
510                                                                RenderState::sCgFragmentProfile,
511                                                                "frag",
512                                                                NULL);
513
514        if (RenderState::sCgMrtFragmentProgram != NULL)
515        {
516                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
517
518                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
519                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
520                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
521
522                cgGLSetParameter1f(sMaxDepthParam, 10.0f / myfar);
523        }
524        else
525                cerr << "fragment program failed to load" << endl;
526
527        PrintGLerror("init");
528
529        cout << "cg initialization successful" << endl;
530}
531
532
533void InitFBO()
534{
535        // this fbo basicly stores the scene information we get from standard rendering of a frame
536        // we store colors, normals, positions (for the ssao)
537        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_32);
538
539        // the diffuse color buffer
540        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
541
542        // the positions buffer
543        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
544        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, true);
545       
546        // the normals buffer
547        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
548        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
549
550        PrintGLerror("fbo");
551}
552
553
554bool InitFont(void)
555{
556        glEnable(GL_TEXTURE_2D);
557
558        glGenTextures(1, &fontTex);
559        glBindTexture(GL_TEXTURE_2D, fontTex);
560        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
561                return false;
562
563        glDisable(GL_TEXTURE_2D);
564       
565        return true;
566}
567
568
569void InitGLstate()
570{
571        glClearColor(0.5f, 0.5f, 0.8f, 0.0f);
572       
573        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
574        glPixelStorei(GL_PACK_ALIGNMENT,1);
575       
576        glDepthFunc(GL_LESS);
577        glEnable(GL_DEPTH_TEST);
578
579        SetupLighting();
580
581        glColor3f(1.0f, 1.0f, 1.0f);
582        glShadeModel(GL_SMOOTH);
583       
584        glMaterialf(GL_FRONT, GL_SHININESS, 64);
585        glEnable(GL_NORMALIZE);
586               
587        //glEnable(GL_ALPHA_TEST);
588        glDisable(GL_ALPHA_TEST);
589        glAlphaFunc(GL_GEQUAL, 0.8f);
590
591        glFrontFace(GL_CCW);
592        glCullFace(GL_BACK);
593        glEnable(GL_CULL_FACE);
594
595        //glDisable(GL_CULL_FACE);
596        glDisable(GL_TEXTURE_2D);
597
598        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
599        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
600        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
601
602        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
603        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
604        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
605
606        glDepthFunc(GL_LESS);
607
608        if (!InitFont())
609                cerr << "font creation failed" << endl;
610        else
611                cout << "successfully created font" << endl;
612}
613
614
615void DrawHelpMessage()
616{
617        const char *message[] =
618        {
619                "Help information",
620                "",
621                "'F1'           - shows/dismisses this message",
622                "'F2'           - shows/hides bird eye view",
623                "'F3'           - shows/hides bounds (boxes or tight bounds)",
624                "'F4',          - shows/hides parameters",
625                "'F5'           - shows/hides statistics",
626                "'F6',          - toggles between fly/walkmode",
627                "'F7',          - cycles throw render modes",
628                "'F8',          - enables/disables ambient occlusion (only deferred)",
629                "'F9',          - shows pure algorithm render time (using glFinish)",
630                "'SPACE'        - cycles through occlusion culling algorithms",
631                "",
632                "'MOUSE LEFT'        - turn left/right, move forward/backward",
633                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
634                "'MOUSE MIDDLE'      - move up/down, left/right",
635                "'CURSOR UP/DOWN'    - move forward/backward",
636                "'CURSOR LEFT/RIGHT' - turn left/right",
637                "",
638                "'-'/'+'        - decreases/increases max batch size",
639                "'1'/'2'        - downward/upward motion",
640                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
641                "'5'/'6'        - decreases/increases assumed visible frames",
642                "",
643                "'R'            - use render queue",
644                "'B'            - use tight bounds",
645                "'M'            - use multiqueries",
646                "'O'            - use CHC optimization (geometry queries for leaves)",
647                0,
648        };
649       
650       
651        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
652
653        glRecti(30, 30, winWidth - 30, winHeight - 30);
654
655        glEnd();
656
657        glColor3f(1.0f, 1.0f, 1.0f);
658       
659        glEnable(GL_TEXTURE_2D);
660        myfont.Begin();
661
662        int x = 40, y = 30;
663
664        for(int i = 0; message[i] != 0; ++ i)
665        {
666                if(message[i][0] == '\0')
667                {
668                        y += 15;
669                }
670                else
671                {
672                        myfont.DrawString(message[i], x, winHeight - y);
673                        y += 25;
674                }
675        }
676        glDisable(GL_TEXTURE_2D);
677}
678
679
680void ResetTraverser()
681{
682        DEL_PTR(traverser);
683
684        bvh->ResetNodeClassifications();
685
686        switch (renderMode)
687        {
688        case RenderTraverser::CULL_FRUSTUM:
689                traverser = new FrustumCullingTraverser();
690                break;
691        case RenderTraverser::STOP_AND_WAIT:
692                traverser = new StopAndWaitTraverser();
693                break;
694        case RenderTraverser::CHC:
695                traverser = new CHCTraverser();
696                break;
697        case RenderTraverser::CHCPLUSPLUS:
698                traverser = new CHCPlusPlusTraverser();
699                break;
700       
701        default:
702                traverser = new FrustumCullingTraverser();
703        }
704
705        traverser->SetCamera(camera);
706        traverser->SetHierarchy(bvh);
707        traverser->SetRenderQueue(renderQueue);
708        traverser->SetRenderState(&state);
709        traverser->SetUseOptimization(useOptimization);
710        traverser->SetUseRenderQueue(useRenderQueue);
711        traverser->SetVisibilityThreshold(threshold);
712        traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
713        traverser->SetMaxBatchSize(maxBatchSize);
714        traverser->SetUseMultiQueries(useMultiQueries);
715        traverser->SetUseTightBounds(useTightBounds);
716        traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
717        traverser->SetRenderQueue(renderQueue);
718}
719
720
721void SetupLighting()
722{
723        glEnable(GL_LIGHTING);
724        glEnable(GL_LIGHT0);
725        glEnable(GL_LIGHT1);
726       
727        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
728        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
729        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
730           
731        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
732
733        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
734        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
735        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
736
737
738        ////////////
739        //-- second light
740
741        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
742        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
743        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
744        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
745
746        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
747        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
748        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
749
750       
751        //////////////////////////////
752
753        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
754        glLightfv(GL_LIGHT0, GL_POSITION, position);
755
756        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
757        glLightfv(GL_LIGHT1, GL_POSITION, position1);
758
759        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
760        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
761        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
762}
763
764
765void SetupEyeView()
766{
767        // store matrix of last frame
768        oldViewProjMatrix = matProjectionView;
769
770        glMatrixMode(GL_PROJECTION);
771        glLoadIdentity();
772
773        gluPerspective(fov, winAspectRatio, nearDist, myfar);
774
775        glMatrixMode(GL_MODELVIEW);
776        glLoadIdentity();
777
778        // set up the camera view
779        camera->SetupCameraView();
780
781        // set lights
782        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
783        glLightfv(GL_LIGHT0, GL_POSITION, position);
784
785        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
786        glLightfv(GL_LIGHT1, GL_POSITION, position1);
787
788       
789        /////////////////
790
791        Matrix4x4 matViewing, matProjection;
792
793        camera->GetModelViewMatrix(matViewing);
794        camera->GetProjectionMatrix(matProjection);
795
796        // store matrix for later use
797        matProjectionView = matViewing * matProjection;
798       
799        if (renderType == RenderState::DEFERRED)
800        {
801                // set modelview matrix for shaders
802                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
803                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
804                                                                        CG_GL_MATRIX_IDENTITY);
805
806                static Matrix4x4 identity = IdentityMatrix();
807                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
808        }               
809}
810
811
812void KeyHorizontalMotion(float shift)
813{
814        Vector3 hvec = camera->GetDirection();
815        hvec.z = 0;
816
817        Vector3 pos = camera->GetPosition();
818        pos += hvec * shift;
819       
820        camera->SetPosition(pos);
821}
822
823
824void KeyVerticalMotion(float shift)
825{
826        Vector3 uvec = Vector3(0, 0, shift);
827
828        Vector3 pos = camera->GetPosition();
829        pos += uvec;
830       
831        camera->SetPosition(pos);
832}
833
834
835// the main rendering loop
836void Display()
837{       
838        Vector3 oldPos = camera->GetPosition();
839
840        if (leftKeyPressed)
841                camera->Pitch(KeyRotationAngle());
842        if (rightKeyPressed)
843                camera->Pitch(-KeyRotationAngle());
844        if (upKeyPressed)
845                KeyHorizontalMotion(KeyShift());
846        if (downKeyPressed)
847                KeyHorizontalMotion(-KeyShift());
848        if (ascendKeyPressed)
849                KeyVerticalMotion(KeyShift());
850        if (descendKeyPressed)
851                KeyVerticalMotion(-KeyShift());
852
853        // place view on ground
854        if (!flyMode) PlaceViewer(oldPos);
855
856        if (showAlgorithmTime)
857        {
858                glFinish();
859                algTimer.Start();
860        }
861       
862        // render without shading
863        switch (renderType)
864        {
865        case RenderState::FIXED:
866       
867                glEnable(GL_MULTISAMPLE_ARB);
868                //glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
869
870                fbo->Release();
871
872                state.SetRenderType(RenderState::FIXED);
873                glEnable(GL_LIGHTING);
874
875                cgGLDisableProfile(RenderState::sCgFragmentProfile);
876                cgGLDisableProfile(RenderState::sCgVertexProfile);
877
878                glDrawBuffers(1, mrt);
879
880                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
881
882                break;
883
884        case RenderState::DEPTH_PASS:
885
886                glEnable(GL_MULTISAMPLE_ARB);
887                //glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
888
889                fbo->Release();
890
891                cgGLDisableProfile(RenderState::sCgFragmentProfile);
892                cgGLDisableProfile(RenderState::sCgVertexProfile);
893
894                state.SetRenderType(RenderState::DEPTH_PASS);
895
896                // the scene is rendered withouth any shading   
897                glDisable(GL_LIGHTING);
898       
899                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
900
901                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
902
903                glDrawBuffers(1, mrt);
904
905                break;
906       
907        case RenderState::DEFERRED:
908
909                // multisampling not working with deferred shading
910                //glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
911                glDisable(GL_MULTISAMPLE_ARB);
912
913                state.SetRenderType(RenderState::DEFERRED);
914
915                fbo->Bind();
916       
917                glPushAttrib(GL_VIEWPORT_BIT);
918                glViewport(0, 0, texWidth, texHeight);
919
920                cgGLEnableProfile(RenderState::sCgFragmentProfile);
921                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
922
923                cgGLEnableProfile(RenderState::sCgVertexProfile);
924                cgGLBindProgram(sCgMrtVertexProgram);
925
926                /// draw to 3 color buffers
927                glDrawBuffers(3, mrt);
928
929                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
930
931                break;
932        }
933
934
935        glDepthFunc(GL_LESS);
936
937        glDisable(GL_TEXTURE_2D);
938        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
939               
940
941        // reset lod levels for current frame
942        LODLevel::InitFrame(camera->GetPosition());
943
944
945        // bring eye modelview matrix up-to-date
946        SetupEyeView();
947
948        // actually render the scene geometry using one of the specified algorithms
949        traverser->RenderScene();
950
951
952
953        /////////
954        //-- do the rest of the rendering
955
956        glEnableClientState(GL_VERTEX_ARRAY);
957        glEnableClientState(GL_NORMAL_ARRAY);
958
959
960        // reset depth pass and render visible objects
961        if (renderType == RenderState::DEPTH_PASS)
962        {
963                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
964                RenderVisibleObjects();
965        }
966       
967
968        ///////////////
969        //-- render sky
970
971        RenderSky();
972
973        state.Reset();
974
975        glDisableClientState(GL_VERTEX_ARRAY);
976        glDisableClientState(GL_NORMAL_ARRAY);
977
978
979        if (renderType == RenderState::DEFERRED)
980        {
981                fbo->Release();
982
983                cgGLDisableProfile(RenderState::sCgVertexProfile);
984                cgGLDisableProfile(RenderState::sCgFragmentProfile);
985
986                glDrawBuffers(1, mrt);
987
988                if (useSsao)
989                        ssaoShader->Render(fbo, oldViewProjMatrix, ssaoExpFactor);
990                else
991                        deferredShader->Render(fbo);
992        }
993       
994        ///////////
995
996        state.SetRenderType(RenderState::FIXED);
997
998        if (showAlgorithmTime)
999        {
1000                glFinish();
1001
1002                algTime = algTimer.Elapsedms();
1003                perfGraph->AddData(algTime);
1004
1005                perfGraph->Draw();
1006        }
1007        else
1008        {
1009                if (visMode) DisplayVisualization();
1010        }
1011
1012        //glFlush();
1013
1014        const bool restart = true;
1015        elapsedTime = frameTimer.Elapsedms(restart);
1016
1017        DisplayStats();
1018
1019        // flip textures for temporal smoothing
1020        isFirstTexture = !isFirstTexture;
1021
1022        glutSwapBuffers();
1023}
1024
1025
1026#pragma warning( disable : 4100 )
1027void KeyBoard(unsigned char c, int x, int y)
1028{
1029        switch(c)
1030        {
1031        case 27:
1032                CleanUp();
1033                exit(0);
1034                break;
1035        case 32: //space
1036                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1037                ResetTraverser();
1038                break;
1039        case 'h':
1040        case 'H':
1041                showHelp = !showHelp;
1042                break;
1043        case '+':
1044                if (maxBatchSize < 10)
1045                        maxBatchSize = 10;
1046                else
1047                        maxBatchSize += 10;
1048
1049                traverser->SetMaxBatchSize(maxBatchSize);
1050                break;
1051        case '-':
1052                maxBatchSize -= 10;
1053                if (maxBatchSize < 0) maxBatchSize = 1;
1054                traverser->SetMaxBatchSize(maxBatchSize);               
1055                break;
1056        case 'M':
1057        case 'm':
1058                useMultiQueries = !useMultiQueries;
1059                traverser->SetUseMultiQueries(useMultiQueries);
1060                break;
1061        case '1':
1062                descendKeyPressed = true;
1063                break;
1064        case '2':
1065                ascendKeyPressed = true;
1066                break;
1067        case '3':
1068                if (trianglesPerVirtualLeaf >= 100)
1069                        trianglesPerVirtualLeaf -= 100;
1070                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1071                break;
1072        case '4':
1073                trianglesPerVirtualLeaf += 100;
1074                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1075                break;
1076        case '5':
1077                assumedVisibleFrames -= 1;
1078                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1079                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1080                break;
1081        case '6':
1082                assumedVisibleFrames += 1;
1083                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1084                break;
1085        case '7':
1086                ssaoExpFactor *= 0.5f;
1087                break;
1088        case '8':
1089                ssaoExpFactor *= 2.0f;
1090                if (ssaoExpFactor > 1.0f) ssaoExpFactor = 1.0f;
1091                break;
1092        case '9':
1093                useLODs = !useLODs;
1094                SceneEntity::SetUseLODs(useLODs);
1095                break;
1096        case 'o':
1097        case 'O':
1098                useOptimization = !useOptimization;
1099                traverser->SetUseOptimization(useOptimization);
1100                break;
1101        case 'a':
1102        case 'A':
1103                        leftKeyPressed = true;
1104                break;
1105        case 'd':
1106        case 'D':
1107                        rightKeyPressed = true;
1108                break;
1109        case 'w':
1110        case 'W':
1111                        upKeyPressed = true;
1112                break;
1113        case 's':
1114        case 'S':
1115                        downKeyPressed = true;
1116                break;
1117        case 'r':
1118        case 'R':
1119                {
1120                        useRenderQueue = !useRenderQueue;
1121                        traverser->SetUseRenderQueue(useRenderQueue);
1122                }
1123                break;
1124        case 'b':
1125        case 'B':
1126                {
1127                        useTightBounds = !useTightBounds;
1128                        traverser->SetUseTightBounds(useTightBounds);
1129                }
1130                break;
1131        default:
1132                return;
1133        }
1134
1135        glutPostRedisplay();
1136}
1137
1138
1139void SpecialKeyUp(int c, int x, int y)
1140{
1141        switch (c)
1142        {
1143        case GLUT_KEY_LEFT:
1144                leftKeyPressed = false;
1145                break;
1146        case GLUT_KEY_RIGHT:
1147                rightKeyPressed = false;
1148                break;
1149        case GLUT_KEY_UP:
1150                upKeyPressed = false;
1151                break;
1152        case GLUT_KEY_DOWN:
1153                downKeyPressed = false;
1154                break;
1155        default:
1156                return;
1157        }
1158        //glutPostRedisplay();
1159}
1160
1161
1162void KeyUp(unsigned char c, int x, int y)
1163{
1164        switch (c)
1165        {
1166        case 'A':
1167        case 'a':
1168                leftKeyPressed = false;
1169                break;
1170        case 'D':
1171        case 'd':
1172                rightKeyPressed = false;
1173                break;
1174        case 'W':
1175        case 'w':
1176                upKeyPressed = false;
1177                break;
1178        case 'S':
1179        case 's':
1180                downKeyPressed = false;
1181                break;
1182        case '1':
1183                descendKeyPressed = false;
1184                break;
1185        case '2':
1186                ascendKeyPressed = false;
1187                break;
1188       
1189        default:
1190                return;
1191        }
1192        //glutPostRedisplay();
1193}
1194
1195
1196void Special(int c, int x, int y)
1197{
1198        switch(c)
1199        {
1200        case GLUT_KEY_F1:
1201                showHelp = !showHelp;
1202                break;
1203        case GLUT_KEY_F2:
1204                visMode = !visMode;
1205                break;
1206        case GLUT_KEY_F3:
1207                showBoundingVolumes = !showBoundingVolumes;
1208                traverser->SetShowBounds(showBoundingVolumes);
1209                break;
1210        case GLUT_KEY_F4:
1211                showOptions = !showOptions;
1212                break;
1213        case GLUT_KEY_F5:
1214                showStatistics = !showStatistics;
1215                break;
1216        case GLUT_KEY_F6:
1217                flyMode = !flyMode;
1218                break;
1219        case GLUT_KEY_F7:
1220
1221                renderType = (renderType + 1) % 3;
1222                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1223               
1224                break;
1225        case GLUT_KEY_F8:
1226                useSsao = !useSsao;
1227                break;
1228        case GLUT_KEY_F9:
1229                showAlgorithmTime = !showAlgorithmTime;
1230                break;
1231
1232        case GLUT_KEY_LEFT:
1233                {
1234                        leftKeyPressed = true;
1235                        camera->Pitch(KeyRotationAngle());
1236                }
1237                break;
1238        case GLUT_KEY_RIGHT:
1239                {
1240                        rightKeyPressed = true;
1241                        camera->Pitch(-KeyRotationAngle());
1242                }
1243                break;
1244        case GLUT_KEY_UP:
1245                {
1246                        upKeyPressed = true;
1247                        KeyHorizontalMotion(KeyShift());
1248                }
1249                break;
1250        case GLUT_KEY_DOWN:
1251                {
1252                        downKeyPressed = true;
1253                        KeyHorizontalMotion(-KeyShift());
1254                }
1255                break;
1256        default:
1257                return;
1258
1259        }
1260
1261        glutPostRedisplay();
1262}
1263
1264#pragma warning( default : 4100 )
1265
1266
1267void Reshape(int w, int h)
1268{
1269        winAspectRatio = 1.0f;
1270
1271        glViewport(0, 0, w, h);
1272       
1273        winWidth = w;
1274        winHeight = h;
1275
1276        if (w) winAspectRatio = (float) w / (float) h;
1277
1278        glMatrixMode(GL_PROJECTION);
1279        glLoadIdentity();
1280
1281        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1282
1283        glMatrixMode(GL_MODELVIEW);
1284
1285        glutPostRedisplay();
1286}
1287
1288
1289void Mouse(int button, int state, int x, int y)
1290{
1291        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
1292        {
1293                xEyeBegin = x;
1294                yMotionBegin = y;
1295
1296                glutMotionFunc(LeftMotion);
1297        }
1298        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
1299        {
1300                xEyeBegin = x;
1301                yEyeBegin = y;
1302                yMotionBegin = y;
1303
1304                glutMotionFunc(RightMotion);
1305        }
1306        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1307        {
1308                horizontalMotionBegin = x;
1309                verticalMotionBegin = y;
1310                glutMotionFunc(MiddleMotion);
1311        }
1312
1313        glutPostRedisplay();
1314}
1315
1316
1317/**     rotation for left/right mouse drag
1318        motion for up/down mouse drag
1319*/
1320void LeftMotion(int x, int y)
1321{
1322        Vector3 viewDir = camera->GetDirection();
1323        Vector3 pos = camera->GetPosition();
1324
1325        // don't move in the vertical direction
1326        Vector3 horView(viewDir[0], viewDir[1], 0);
1327       
1328        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1329
1330        camera->Pitch(eyeXAngle);
1331
1332        pos += horView * (yMotionBegin - y) * 0.2f;
1333       
1334        camera->SetPosition(pos);
1335       
1336        xEyeBegin = x;
1337        yMotionBegin = y;
1338
1339        glutPostRedisplay();
1340}
1341
1342
1343/**     rotation for left / right mouse drag
1344        motion for up / down mouse drag
1345*/
1346void RightMotion(int x, int y)
1347{
1348        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1349        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1350
1351        camera->Yaw(eyeYAngle);
1352        camera->Pitch(eyeXAngle);
1353
1354        xEyeBegin = x;
1355        yEyeBegin = y;
1356
1357        glutPostRedisplay();
1358}
1359
1360
1361// strafe
1362void MiddleMotion(int x, int y)
1363{
1364        Vector3 viewDir = camera->GetDirection();
1365        Vector3 pos = camera->GetPosition();
1366
1367        // the 90 degree rotated view vector
1368        // y zero so we don't move in the vertical
1369        Vector3 rVec(viewDir[0], viewDir[1], 0);
1370       
1371        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1372        rVec = rot * rVec;
1373       
1374        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
1375        pos[2] += (verticalMotionBegin - y) * 0.1f;
1376
1377        camera->SetPosition(pos);
1378
1379        horizontalMotionBegin = x;
1380        verticalMotionBegin = y;
1381
1382        glutPostRedisplay();
1383}
1384
1385
1386void InitExtensions(void)
1387{
1388        GLenum err = glewInit();
1389
1390        if (GLEW_OK != err)
1391        {
1392                // problem: glewInit failed, something is seriously wrong
1393                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1394                exit(1);
1395        }
1396        if  (!GLEW_ARB_occlusion_query)
1397        {
1398                printf("I require the GL_ARB_occlusion_query to work.\n");
1399                exit(1);
1400        }
1401}
1402
1403
1404void Begin2D()
1405{
1406        glDisable(GL_LIGHTING);
1407        glDisable(GL_DEPTH_TEST);
1408
1409        glMatrixMode(GL_PROJECTION);
1410        glPushMatrix();
1411        glLoadIdentity();
1412
1413        gluOrtho2D(0, winWidth, 0, winHeight);
1414
1415        glMatrixMode(GL_MODELVIEW);
1416        glPushMatrix();
1417        glLoadIdentity();
1418}
1419
1420
1421void End2D()
1422{
1423        glMatrixMode(GL_PROJECTION);
1424        glPopMatrix();
1425
1426        glMatrixMode(GL_MODELVIEW);
1427        glPopMatrix();
1428
1429        glEnable(GL_LIGHTING);
1430        glEnable(GL_DEPTH_TEST);
1431}
1432
1433
1434// displays the visualisation of culling algorithm
1435void DisplayVisualization()
1436{
1437        visualization->SetFrameId(traverser->GetCurrentFrameId());
1438       
1439        Begin2D();
1440        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1441        glEnable(GL_BLEND);
1442        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
1443
1444        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
1445        glDisable(GL_BLEND);
1446        End2D();
1447       
1448       
1449        AxisAlignedBox3 box = bvh->GetBox();
1450
1451        // hack: set far plane for viz
1452        camera->SetFar(0.35f * Magnitude(box.Diagonal()));
1453
1454        const float offs = box.Size().x * 0.3f;
1455       
1456        //Vector3 vizpos = Vector3(box.Min().x, box.Min().y + box.Size().y * 0.5f, box.Min().z + box.Size().z * 50);
1457        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
1458       
1459        visCamera->SetPosition(vizpos);
1460        visCamera->ResetPitchAndYaw();
1461        //visCamera->Pitch(M_PI);
1462
1463        glPushAttrib(GL_VIEWPORT_BIT);
1464        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
1465
1466        glMatrixMode(GL_PROJECTION);
1467        glPushMatrix();
1468
1469        glLoadIdentity();
1470       
1471        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
1472
1473        glMatrixMode(GL_MODELVIEW);
1474        glPushMatrix();
1475
1476        visCamera->SetupCameraView();
1477
1478        //Matrix4x4 rotX = RotationXMatrix(camera->GetYaw());
1479        //glMultMatrixf((float *)rotX.x);
1480        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1481        glMultMatrixf((float *)rotZ.x);
1482
1483        Vector3 pos = camera->GetPosition();
1484        glTranslatef(-pos.x, -pos.y, -pos.z);
1485
1486
1487        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1488        glLightfv(GL_LIGHT0, GL_POSITION, position);
1489
1490        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1491        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1492
1493        glClear(GL_DEPTH_BUFFER_BIT);
1494
1495
1496        ////////////
1497        //-- visualization of the occlusion culling
1498
1499        visualization->Render();
1500       
1501       
1502        // reset previous settings
1503        glPopAttrib();
1504
1505        glMatrixMode(GL_PROJECTION);
1506        glPopMatrix();
1507        glMatrixMode(GL_MODELVIEW);
1508        glPopMatrix();
1509}
1510
1511
1512// cleanup routine after the main loop
1513void CleanUp()
1514{
1515        DEL_PTR(traverser);
1516        DEL_PTR(sceneQuery);
1517        DEL_PTR(bvh);
1518        DEL_PTR(visualization);
1519        DEL_PTR(camera);
1520        DEL_PTR(loader);
1521        DEL_PTR(renderQueue);
1522        DEL_PTR(perfGraph);
1523
1524        if (sCgMrtVertexProgram)
1525                cgDestroyProgram(sCgMrtVertexProgram);
1526        if (RenderState::sCgMrtFragmentProgram)
1527                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1528        if (RenderState::sCgMrtFragmentTexProgram)
1529                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
1530       
1531        if (sCgContext)
1532                cgDestroyContext(sCgContext);
1533}
1534
1535
1536// this function inserts a dezimal point after each 1000
1537void CalcDecimalPoint(string &str, int d, int len)
1538{
1539        static vector<int> numbers;
1540        numbers.clear();
1541
1542        static string shortStr;
1543        shortStr.clear();
1544
1545        static char hstr[100];
1546
1547        while (d != 0)
1548        {
1549                numbers.push_back(d % 1000);
1550                d /= 1000;
1551        }
1552
1553        // first element without leading zeros
1554        if (numbers.size() > 0)
1555        {
1556                sprintf(hstr, "%d", numbers.back());
1557                shortStr.append(hstr);
1558        }
1559       
1560        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1561        {
1562                sprintf(hstr, ",%03d", numbers[i]);
1563                shortStr.append(hstr);
1564        }
1565
1566        int dif = len - (int)shortStr.size();
1567
1568        for (int i = 0; i < dif; ++ i)
1569        {
1570                str += " ";
1571        }
1572
1573        str.append(shortStr);
1574}
1575
1576
1577void DisplayStats()
1578{
1579        static char msg[9][300];
1580
1581        static double frameTime = elapsedTime;
1582        static double renderTime = algTime;
1583
1584        const float expFactor = 0.1f;
1585
1586        // if some strange render time spike happened in this frame => don't count
1587        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1588       
1589        static float rTime = 1000.0f;
1590
1591        if (showAlgorithmTime)
1592        {
1593                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1594        }
1595
1596        accumulatedTime += elapsedTime;
1597
1598        if (accumulatedTime > 500) // update every fraction of a second
1599        {       
1600                accumulatedTime = 0;
1601
1602                if (frameTime) fps = 1e3f / (float)frameTime;
1603
1604                rTime = renderTime;
1605                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1606                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1607                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1608
1609                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1610                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1611                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1612                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1613                stateChanges = traverser->GetStats().mNumStateChanges;
1614                numBatches = traverser->GetStats().mNumBatches;
1615        }
1616
1617
1618        Begin2D();
1619
1620        glEnable(GL_BLEND);
1621        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1622
1623        if (showHelp)
1624        {       
1625                DrawHelpMessage();
1626        }
1627        else
1628        {
1629                if (showOptions)
1630                {
1631                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1632                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1633                }
1634
1635                if (showStatistics)
1636                {
1637                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1638                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1639                }
1640
1641                glEnable(GL_TEXTURE_2D);
1642
1643                myfont.Begin();
1644
1645                if (showOptions)
1646                {
1647                        glColor3f(0.0f, 1.0f, 0.0f);
1648
1649                        int i = 0;
1650
1651                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
1652       
1653                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1654                                                        useMultiQueries, useTightBounds, useRenderQueue);
1655
1656                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useSsao);
1657
1658                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1659
1660                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1661                                assumedVisibleFrames, maxBatchSize);
1662
1663                        for (int j = 0; j < 4; ++ j)
1664                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1665                }
1666
1667                if (showStatistics)
1668                {
1669                        glColor3f(1.0f, 1.0f, 0.0f);
1670
1671                        string str;
1672                        string str2;
1673
1674                        int len = 10;
1675                        CalcDecimalPoint(str, renderedTriangles, len);
1676                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
1677
1678                        int i = 4;
1679
1680                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1681                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1682
1683                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1684                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1685
1686                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1687                                issuedQueries, stateChanges, numBatches);
1688
1689                        for (int j = 4; j < 7; ++ j)
1690                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1691                }
1692
1693                glColor3f(1.0f, 1.0f, 1.0f);
1694                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1695               
1696                if (!showAlgorithmTime)
1697                {
1698                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1699                }
1700                else
1701                {
1702                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1703                }
1704
1705                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1706               
1707                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1708                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1709        }
1710
1711        glDisable(GL_BLEND);
1712        glDisable(GL_TEXTURE_2D);
1713
1714        End2D();
1715}       
1716
1717
1718void RenderSky()
1719{
1720        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
1721
1722        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
1723                (*sit)->Render(&state);
1724}
1725
1726
1727void RenderVisibleObjects()
1728{
1729        state.SetRenderType(RenderState::FIXED);
1730        state.Reset();
1731
1732        glEnable(GL_LIGHTING);
1733        glDepthFunc(GL_LEQUAL);
1734
1735        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
1736
1737        SceneEntityContainer::const_iterator sit,
1738                sit_end = traverser->GetVisibleObjects().end();
1739
1740        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
1741                renderQueue->Enqueue(*sit);
1742               
1743        renderQueue->Apply();
1744
1745        glDepthFunc(GL_LESS);
1746}
1747
1748
1749void PlaceViewer(const Vector3 &oldPos)
1750{
1751        Vector3 playerPos = camera->GetPosition();
1752
1753        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
1754
1755        if (validIntersect)
1756                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
1757        {
1758                camera->SetPosition(playerPos);
1759        }
1760}
Note: See TracBrowser for help on using the repository browser.