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

Revision 3023, 49.2 KB checked in by mattausch, 16 years ago (diff)
Line 
1// chcdemo.cpp : Defines the entry point for the console application.
2//
3
4
5#include "common.h"
6
7#ifdef _CRT_SET
8        #define _CRTDBG_MAP_ALLOC
9        #include <stdlib.h>
10        #include <crtdbg.h>
11
12        // redefine new operator
13        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
14        #define new DEBUG_NEW
15#endif
16
17#include <math.h>
18#include <time.h>
19#include "glInterface.h"
20
21#include <Cg/cg.h>
22#include <Cg/cgGL.h>
23
24
25#include "RenderTraverser.h"
26#include "SceneEntity.h"
27#include "Vector3.h"
28#include "Matrix4x4.h"
29#include "ResourceManager.h"
30#include "Bvh.h"
31#include "Camera.h"
32#include "Geometry.h"
33#include "BvhLoader.h"
34#include "FrustumCullingTraverser.h"
35#include "StopAndWaitTraverser.h"
36#include "CHCTraverser.h"
37#include "CHCPlusPlusTraverser.h"
38#include "Visualization.h"
39#include "RenderState.h"
40#include "Timer/PerfTimer.h"
41#include "SceneQuery.h"
42#include "RenderQueue.h"
43#include "Material.h"
44#include "glfont2.h"
45#include "PerformanceGraph.h"
46#include "Environment.h"
47#include "Halton.h"
48#include "Transform3.h"
49#include "SampleGenerator.h"
50#include "FrameBufferObject.h"
51#include "DeferredRenderer.h"
52#include "ShadowMapping.h"
53#include "Light.h"
54#include "SceneEntityConverter.h"
55#include "ObjConverter.h"
56#include "SkyPreetham.h"
57#include "Texture.h"
58#include "EntityMerger.h"
59
60using namespace std;
61using namespace CHCDemoEngine;
62
63
64static Environment env;
65
66#define MAX_DEPTH_CONST 10.0f
67
68// fbo
69FrameBufferObject *fbo = NULL;
70
71GLuint fontTex;
72
73/// the renderable scene geometry
74SceneEntityContainer sceneEntities;
75
76// traverses and renders the hierarchy
77RenderTraverser *traverser = NULL;
78/// the hierarchy
79Bvh *bvh = NULL;
80/// handles scene loading
81ResourceManager *loader = NULL;
82/// the scene camera
83Camera *camera = NULL;
84/// the scene camera
85Camera *visCamera = NULL;
86/// the visualization
87Visualization *visualization = NULL;
88/// the current render state
89RenderState state;
90/// the rendering algorithm
91int renderMode = RenderTraverser::CHCPLUSPLUS;
92// eye near plane distance
93float nearDist = 0.2f;
94float farDist = 1e6f;
95/// the field of view
96float fov = 50.0f;
97/// the pixel threshold where a node is still considered invisible
98int threshold;
99
100int assumedVisibleFrames = 10;
101int maxBatchSize = 50;
102
103int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
104
105SceneQuery *sceneQuery = NULL;
106RenderQueue *renderQueue = NULL;
107
108// traverses and renders the hierarchy
109RenderTraverser *shadowTraverser = NULL;
110
111SkyPreetham *preetham = NULL;
112
113
114/// the used render type for this render pass
115enum RenderMethod
116{
117        RENDER_FIXED,
118        RENDER_DEPTH_PASS,
119        RENDER_DEFERRED,
120        RENDER_DEPTH_PASS_DEFERRED,
121        RENDER_NUM_RENDER_TYPES
122};
123
124/// one of four possible render methods
125int renderMethod = RENDER_FIXED;
126
127
128/// these values get scaled with the frame rate
129static float keyForwardMotion = 30.0f;
130static float keyRotation = 1.5f;
131
132/// elapsed time in milliseconds
133double elapsedTime = 1000.0f;
134double algTime = 1000.0f;
135
136static int winWidth = 1024;
137static int winHeight = 768;
138
139int shadowSize = 2048;
140
141static float winAspectRatio = 1.0f;
142
143double accumulatedTime = 1000;
144float fps = 1e3f;
145
146glfont::GLFont myfont;
147
148// rendertexture
149static int texWidth = 1024;
150static int texHeight = 768;
151
152int renderedObjects = 0;
153int renderedNodes = 0;
154int renderedTriangles = 0;
155
156int issuedQueries = 0;
157int traversedNodes = 0;
158int frustumCulledNodes = 0;
159int queryCulledNodes = 0;
160int stateChanges = 0;
161int numBatches = 0;
162
163
164// mouse navigation state
165int xEyeBegin = 0;
166int yEyeBegin = 0;
167int yMotionBegin = 0;
168int verticalMotionBegin = 0;
169int horizontalMotionBegin = 0;
170
171
172bool leftKeyPressed = false;
173bool rightKeyPressed = false;
174bool upKeyPressed = false;
175bool downKeyPressed = false;
176bool descendKeyPressed = false;
177bool ascendKeyPressed = false;
178
179bool showHelp = false;
180bool showStatistics = false;
181bool showOptions = true;
182bool showBoundingVolumes = false;
183bool visMode = false;
184
185bool useOptimization = false;
186bool useTightBounds = true;
187bool useRenderQueue = true;
188bool useMultiQueries = true;
189bool flyMode = true;
190
191bool useGlobIllum = false;
192bool useTemporalCoherence = true;
193bool showAlgorithmTime = false;
194
195bool useFullScreen = false;
196bool useLODs = true;
197bool moveLight = false;
198
199bool useAdvancedShading = false;
200bool showShadowMap = false;
201bool renderLightView = false;
202
203bool altKeyPressed = false;
204
205bool useHDR = true;
206
207static float ssaoTempCohFactor = 255.0;
208
209
210PerfTimer frameTimer, algTimer;
211
212static int sCurrentMrtSet = 0;
213
214PerformanceGraph *perfGraph = NULL;
215
216
217//DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_POISSON;
218DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_QUADRATIC;
219
220ShadowMap *shadowMap = NULL;
221DirectionalLight *light = NULL;
222DeferredRenderer *ssaoShader = NULL;
223
224SceneEntity *cube = NULL;
225SceneEntity *aeroplane = NULL;
226SceneEntity *skyDome = NULL;
227
228
229
230// function forward declarations
231void InitExtensions();
232void DisplayVisualization();
233void InitGLstate();
234void InitRenderTexture();
235void InitCg();
236void CleanUp();
237void SetupEyeView();
238void UpdateEyeMtx();
239void SetupLighting();
240void DisplayStats();
241void Output(int x, int y, const char *string);
242void DrawHelpMessage();
243void RenderSky();
244void RenderVisibleObjects();
245
246void Begin2D();
247void End2D();
248void KeyBoard(unsigned char c, int x, int y);
249void DrawStatistics();
250void Display();
251void Special(int c, int x, int y);
252void KeyUp(unsigned char c, int x, int y);
253void SpecialKeyUp(int c, int x, int y);
254void Reshape(int w, int h);
255void Mouse(int button, int state, int x, int y);
256void LeftMotion(int x, int y);
257void RightMotion(int x, int y);
258void MiddleMotion(int x, int y);
259void CalcDecimalPoint(string &str, int d);
260
261RenderTraverser *CreateTraverser(Camera *cam);
262
263void KeyHorizontalMotion(float shift);
264void KeyVerticalMotion(float shift);
265
266void PlaceViewer(const Vector3 &oldPos);
267
268inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
269inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
270// initialise the frame buffer objects
271void InitFBO();
272
273void RightMotionLight(int x, int y);
274
275void RenderShadowMap(float newfar);
276
277
278
279/////////
280//-- cg stuff
281
282static CGcontext sCgContext = NULL;
283static CGprogram sCgMrtVertexProgram = NULL;
284
285static CGparameter sEyePosParamTex;
286static CGparameter sEyePosParam;
287
288static Matrix4x4 viewProjMat = IdentityMatrix();
289static Matrix4x4 oldViewProjMat = IdentityMatrix();
290
291
292
293static void cgErrorCallback()
294{
295        CGerror lastError = cgGetError();
296
297        if(lastError)
298        {
299                printf("%s\n\n", cgGetErrorString(lastError));
300                printf("%s\n", cgGetLastListing(sCgContext));
301               
302                printf("Cg error, exiting...\n");
303
304                exit(0);
305        }
306}
307
308
309static void PrintGLerror(char *msg)
310{
311        GLenum errCode;
312        const GLubyte *errStr;
313       
314        if ((errCode = glGetError()) != GL_NO_ERROR)
315        {
316                errStr = gluErrorString(errCode);
317                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
318        }
319}
320
321
322int main(int argc, char* argv[])
323{
324#ifdef _CRT_SET
325
326        //Now just call this function at the start of your program and if you're
327        //compiling in debug mode (F5), any leaks will be displayed in the Output
328        //window when the program shuts down. If you're not in debug mode this will
329        //be ignored. Use it as you will!
330        //note: from GDNet Direct [3.8.04 - 3.14.04] void detectMemoryLeaks() {
331
332        _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF);
333        _CrtSetReportMode(_CRT_ASSERT,_CRTDBG_MODE_FILE);
334        _CrtSetReportFile(_CRT_ASSERT,_CRTDBG_FILE_STDERR);
335#endif
336
337        cout << "=== reading environment file ===" << endl << endl;
338
339        int returnCode = 0;
340
341        Vector3 camPos(.0f, .0f, .0f);
342        Vector3 camDir(.0f, 1.0f, .0f);
343        Vector3 lightDir(-0.8f, 1.0f, -0.7f);
344
345        cout << "=== reading environment file ===" << endl << endl;
346
347        const string envFileName = "default.env";
348        if (!env.Read(envFileName))
349        {
350                cerr << "loading environment " << envFileName << " failed!" << endl;
351        }
352        else
353        {
354                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
355                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
356                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
357
358                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
359                env.GetFloatParam(string("keyRotation"), keyRotation);
360
361                env.GetIntParam(string("winWidth"), winWidth);
362                env.GetIntParam(string("winHeight"), winHeight);
363
364                env.GetBoolParam(string("useFullScreen"), useFullScreen);
365                env.GetFloatParam(string("tempCohFactor"), ssaoTempCohFactor);
366                env.GetVectorParam(string("camPosition"), camPos);
367                env.GetVectorParam(string("camDirection"), camDir);
368                env.GetVectorParam(string("lightDirection"), lightDir);
369
370                env.GetBoolParam(string("useLODs"), useLODs);
371                env.GetIntParam(string("shadowSize"), shadowSize);
372
373                env.GetBoolParam(string("useHDR"), useHDR);
374
375                //env.GetStringParam(string("modelPath"), model_path);
376                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
377
378                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
379                cout << "maxBatchSize: " << maxBatchSize << endl;
380                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
381
382                cout << "keyForwardMotion: " << keyForwardMotion << endl;
383                cout << "keyRotation: " << keyRotation << endl;
384                cout << "winWidth: " << winWidth << endl;
385                cout << "winHeight: " << winHeight << endl;
386                cout << "useFullScreen: " << useFullScreen << endl;
387                cout << "useLODs: " << useLODs << endl;
388                cout << "camPosition: " << camPos << endl;
389                cout << "temporal coherence: " << ssaoTempCohFactor << endl;
390                cout << "shadow size: " << shadowSize << endl;
391
392                //cout << "model path: " << model_path << endl;
393
394                cout << "**** end parameters ****" << endl << endl;
395        }
396
397        ///////////////////////////
398
399        camera = new Camera(winWidth, winHeight, fov);
400        camera->SetNear(nearDist);
401        camera->SetFar(1000);
402
403        camera->SetDirection(camDir);
404        camera->SetPosition(camPos);
405
406        visCamera = new Camera(winWidth, winHeight, fov);
407        visCamera->SetNear(0.0f);
408        visCamera->Yaw(.5 * M_PI);
409
410        // create a new light
411        light = new DirectionalLight(lightDir, RgbaColor(1, 1, 1, 1), RgbaColor(1, 1, 1, 1));
412
413
414        renderQueue = new RenderQueue(&state, camera);
415
416        glutInitWindowSize(winWidth, winHeight);
417        glutInit(&argc, argv);
418        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
419        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
420        //glutInitDisplayString("samples=2");
421
422        SceneEntity::SetUseLODs(useLODs);
423
424        if (!useFullScreen)
425        {
426                glutCreateWindow("FriendlyCulling");
427        }
428        else
429        {
430                glutGameModeString( "1024x768:32@75" );
431                glutEnterGameMode();
432        }
433
434        glutDisplayFunc(Display);
435        glutKeyboardFunc(KeyBoard);
436        glutSpecialFunc(Special);
437        glutReshapeFunc(Reshape);
438        glutMouseFunc(Mouse);
439        glutIdleFunc(Display);
440        glutKeyboardUpFunc(KeyUp);
441        glutSpecialUpFunc(SpecialKeyUp);
442        glutIgnoreKeyRepeat(true);
443
444        // initialise gl graphics
445        InitExtensions();
446        InitGLstate();
447
448        glEnable(GL_MULTISAMPLE_ARB);
449        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
450
451        LeftMotion(0, 0);
452        MiddleMotion(0, 0);
453
454        perfGraph = new PerformanceGraph(1000);
455
456        loader = new ResourceManager();
457
458        const string filename = string(model_path + "city.dem");
459       
460
461        if (loader->Load(filename, sceneEntities))
462                cout << "model " << filename << " loaded" << endl;
463        else
464        {
465                cerr << "loading model " << filename << " failed" << endl;
466                CleanUp();
467                exit(0);
468        }
469       
470
471        const string bvh_filename = string(model_path + "city.bvh");
472        BvhLoader bvhLoader;
473        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
474
475        if (!bvh)
476        {
477                cerr << "loading bvh " << bvh_filename << " failed" << endl;
478                CleanUp();
479                exit(0);
480        }
481
482        // set far plane based on scene extent
483        farDist = 10.0f * Magnitude(bvh->GetBox().Diagonal());
484        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
485
486        camera->SetFar(Magnitude(bvh->GetBox().Diagonal()));
487       
488        InitCg();
489
490        DeferredRenderer::InitCG(sCgContext);
491        SkyPreetham::InitCG(sCgContext);
492
493        Vector3 cubeCenter(470.398f, 240.364f, 182.5f);
494       
495        Matrix4x4 transl = TranslationMatrix(cubeCenter);
496
497        SceneEntityContainer dummy;
498       
499        string skyDomeStr(model_path + "sky.dem");
500
501        if (loader->Load(skyDomeStr, sceneEntities))
502        {
503                cout << "successfully loaded " << sceneEntities.size() << " scene entities" << endl;
504        }
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        DeferredRenderer::ReleaseCG();
1791        SkyPreetham::ReleaseCG();
1792
1793        if (sCgContext)
1794                cgDestroyContext(sCgContext);
1795}
1796
1797
1798// this function inserts a dezimal point after each 1000
1799void CalcDecimalPoint(string &str, int d, int len)
1800{
1801        static vector<int> numbers;
1802        numbers.clear();
1803
1804        static string shortStr;
1805        shortStr.clear();
1806
1807        static char hstr[100];
1808
1809        while (d != 0)
1810        {
1811                numbers.push_back(d % 1000);
1812                d /= 1000;
1813        }
1814
1815        // first element without leading zeros
1816        if (numbers.size() > 0)
1817        {
1818                sprintf(hstr, "%d", numbers.back());
1819                shortStr.append(hstr);
1820        }
1821       
1822        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1823        {
1824                sprintf(hstr, ",%03d", numbers[i]);
1825                shortStr.append(hstr);
1826        }
1827
1828        int dif = len - (int)shortStr.size();
1829
1830        for (int i = 0; i < dif; ++ i)
1831        {
1832                str += " ";
1833        }
1834
1835        str.append(shortStr);
1836}
1837
1838
1839void DisplayStats()
1840{
1841        static char msg[9][300];
1842
1843        static double frameTime = elapsedTime;
1844        static double renderTime = algTime;
1845
1846        const float expFactor = 0.1f;
1847
1848        // if some strange render time spike happened in this frame => don't count
1849        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1850       
1851        static float rTime = 1000.0f;
1852
1853        if (showAlgorithmTime)
1854        {
1855                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1856        }
1857
1858        accumulatedTime += elapsedTime;
1859
1860        if (accumulatedTime > 500) // update every fraction of a second
1861        {       
1862                accumulatedTime = 0;
1863
1864                if (frameTime) fps = 1e3f / (float)frameTime;
1865
1866                rTime = renderTime;
1867
1868                if (renderLightView && shadowTraverser)
1869                {
1870                        renderedTriangles = shadowTraverser->GetStats().mNumRenderedTriangles;
1871                        renderedObjects = shadowTraverser->GetStats().mNumRenderedGeometry;
1872                        renderedNodes = shadowTraverser->GetStats().mNumRenderedNodes;
1873                }
1874                else if (showShadowMap && shadowTraverser)
1875                {
1876                        renderedNodes = traverser->GetStats().mNumRenderedNodes + shadowTraverser->GetStats().mNumRenderedNodes;
1877                        renderedObjects = traverser->GetStats().mNumRenderedGeometry + shadowTraverser->GetStats().mNumRenderedGeometry;
1878                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles + shadowTraverser->GetStats().mNumRenderedTriangles;
1879                }
1880                else
1881                {
1882                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1883                        renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1884                        renderedNodes = traverser->GetStats().mNumRenderedNodes;
1885                }
1886
1887                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1888                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1889                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1890                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1891                stateChanges = traverser->GetStats().mNumStateChanges;
1892                numBatches = traverser->GetStats().mNumBatches;
1893        }
1894
1895
1896        Begin2D();
1897
1898        glEnable(GL_BLEND);
1899        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1900
1901        if (showHelp)
1902        {       
1903                DrawHelpMessage();
1904        }
1905        else
1906        {
1907                if (showOptions)
1908                {
1909                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1910                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1911                }
1912
1913                if (showStatistics)
1914                {
1915                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1916                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1917                }
1918
1919                glEnable(GL_TEXTURE_2D);
1920
1921                myfont.Begin();
1922
1923                if (showOptions)
1924                {
1925                        glColor3f(0.0f, 1.0f, 0.0f);
1926
1927                        int i = 0;
1928
1929                        static char *renderMethodStr[] = {"forward", "depth pass + forward", "deferred shading", "depth pass + deferred"};
1930       
1931                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1932                                                        useMultiQueries, useTightBounds, useRenderQueue);
1933
1934                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderMethodStr[renderMethod], useAdvancedShading);
1935
1936                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1937
1938                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1939                                assumedVisibleFrames, maxBatchSize);
1940
1941                        for (int j = 0; j < 4; ++ j)
1942                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1943                }
1944
1945                if (showStatistics)
1946                {
1947                        glColor3f(1.0f, 1.0f, 0.0f);
1948
1949                        string objStr, totalObjStr;
1950                        string triStr, totalTriStr;
1951
1952                        int len = 10;
1953                        CalcDecimalPoint(objStr, renderedObjects, len);
1954                        CalcDecimalPoint(totalObjStr, (int)loader->GetNumEntities(), len);
1955
1956                        CalcDecimalPoint(triStr, renderedTriangles, len);
1957                        CalcDecimalPoint(totalTriStr, bvh->GetBvhStats().mTriangles, len);
1958
1959                        int i = 4;
1960
1961                        if (0)
1962                        {
1963                                sprintf(msg[i ++], "rendered: %s of %s objects, %s of %s triangles",
1964                                        objStr.c_str(), totalObjStr.c_str(), triStr.c_str(), totalTriStr.c_str());
1965                        }
1966                        else
1967                        {
1968                                sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1969                                        renderedNodes, bvh->GetNumVirtualNodes(), triStr.c_str(), totalTriStr.c_str());
1970                        }
1971
1972                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1973                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1974
1975                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1976                                issuedQueries, stateChanges, numBatches);
1977
1978                        for (int j = 4; j < 7; ++ j)
1979                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1980                }
1981
1982                glColor3f(1.0f, 1.0f, 1.0f);
1983                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1984               
1985                if (!showAlgorithmTime)
1986                                sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1987                else
1988                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1989               
1990                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1991               
1992                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1993                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1994        }
1995
1996        glDisable(GL_BLEND);
1997        glDisable(GL_TEXTURE_2D);
1998
1999        End2D();
2000}       
2001
2002
2003void RenderSky()
2004{
2005        cgGLEnableProfile(RenderState::sCgVertexProfile);
2006
2007        if ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
2008                state.SetRenderPassType(RenderState::DEFERRED);
2009
2010        const bool useToneMapping = ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) || (renderMethod == RENDER_DEFERRED)) && useHDR;
2011
2012        preetham->RenderSkyDome(-light->GetDirection(), camera, &state, !useToneMapping);
2013
2014        cgGLDisableProfile(RenderState::sCgVertexProfile);
2015        cgGLDisableProfile(RenderState::sCgFragmentProfile);
2016}
2017
2018
2019// render visible object from depth pass
2020void RenderVisibleObjects()
2021{
2022        if (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
2023        {
2024                if (showShadowMap && !renderLightView)
2025                {
2026                        float minVisibleDist = min(camera->GetFar(), traverser->GetMaxVisibleDistance());
2027                        RenderShadowMap(minVisibleDist);
2028                }
2029
2030                glDisable(GL_LIGHTING);
2031                glViewport(0, 0, texWidth, texHeight);
2032
2033                InitDeferredRendering();
2034        }
2035        else
2036        {
2037                glEnable(GL_LIGHTING);
2038                state.SetRenderPassType(RenderState::FIXED);
2039        }
2040
2041        glShadeModel(GL_SMOOTH);
2042        glEnableClientState(GL_NORMAL_ARRAY);
2043
2044        // draw all objects that have exactly the same depth as the current sample
2045        glDepthFunc(GL_LEQUAL);
2046        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2047
2048        glClear(GL_COLOR_BUFFER_BIT);
2049
2050        state.SetUseAlphaToCoverage(true);
2051        state.Reset();
2052
2053        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2054
2055        SceneEntityContainer::const_iterator sit,
2056                sit_end = traverser->GetVisibleObjects().end();
2057
2058        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
2059        {
2060                renderQueue->Enqueue(*sit);
2061        }
2062
2063        renderQueue->Apply();
2064
2065        glDepthFunc(GL_LESS);
2066        state.Reset();
2067
2068        PrintGLerror("visibleobjects");
2069}
2070
2071
2072void PlaceViewer(const Vector3 &oldPos)
2073{
2074        Vector3 playerPos = camera->GetPosition();
2075        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
2076
2077        if (validIntersect)
2078                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
2079        {
2080                camera->SetPosition(playerPos);
2081        }
2082}
2083
2084
2085void RenderShadowMap(float newfar)
2086{
2087        cgGLDisableProfile(RenderState::sCgFragmentProfile);
2088        cgGLDisableProfile(RenderState::sCgVertexProfile);
2089
2090        glDisableClientState(GL_NORMAL_ARRAY);
2091
2092        state.SetRenderPassType(RenderState::DEPTH_PASS);
2093        state.LockCullFaceEnabled(true);
2094        state.SetUseAlphaToCoverage(false);
2095
2096        // change CHC++ set of state variables
2097        // this must be done for each change of camera because
2098        // otherwise the temporal coherency is broken
2099        BvhNode::SetCurrentState(1);
2100
2101        // hack: temporarily change camera far plane
2102        camera->SetFar(newfar);
2103        glDisable(GL_CULL_FACE);
2104       
2105        // the scene is rendered withouth any shading   
2106        shadowMap->ComputeShadowMap(shadowTraverser, viewProjMat);
2107
2108        glEnable(GL_CULL_FACE);
2109        camera->SetFar(farDist);
2110
2111        state.SetUseAlphaToCoverage(true);
2112        state.LockCullFaceEnabled(false);
2113
2114        glEnableClientState(GL_NORMAL_ARRAY);
2115
2116        // change back state
2117        BvhNode::SetCurrentState(0);
2118}
Note: See TracBrowser for help on using the repository browser.