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

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