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

Revision 2884, 41.0 KB checked in by mattausch, 16 years ago (diff)

found bug with lod levels
made env file for shaders

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