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

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