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

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