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

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