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

Revision 3105, 50.0 KB checked in by mattausch, 16 years ago (diff)

now strafing up not working anymore!!!!

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