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

Revision 2861, 39.5 KB checked in by mattausch, 16 years ago (diff)

cleaned up code

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