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

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