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

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