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

Revision 2884, 41.0 KB checked in by mattausch, 16 years ago (diff)

found bug with lod levels
made env file for shaders

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