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

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