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

Revision 2888, 42.2 KB checked in by mattausch, 16 years ago (diff)

corrected views

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