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

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