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

Revision 2866, 40.1 KB checked in by mattausch, 16 years ago (diff)

bug: downsampling of positions does not work

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