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

Revision 2965, 48.9 KB checked in by mattausch, 16 years ago (diff)

removed dirttexture stuff. started tonemapping stuff

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