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

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