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

Revision 3020, 49.1 KB checked in by mattausch, 16 years ago (diff)

removed most leaks

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