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

Revision 3123, 51.4 KB checked in by mattausch, 16 years ago (diff)

working on ssao for dynamic objects, found error with tight bounds

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