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

Revision 2887, 42.0 KB checked in by mattausch, 16 years ago (diff)

made changes to view transformation but still not working

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