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

Revision 2861, 39.5 KB checked in by mattausch, 16 years ago (diff)

cleaned up code

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