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

Revision 2942, 43.4 KB checked in by mattausch, 16 years ago (diff)

lispsm finally working!!

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