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

Revision 2900, 42.4 KB checked in by mattausch, 16 years ago (diff)

changed to real 3d samples which are then projected to texture space

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