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

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