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

Revision 2879, 41.2 KB checked in by mattausch, 16 years ago (diff)

improved performance

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