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

Revision 3020, 49.1 KB checked in by mattausch, 16 years ago (diff)

removed most leaks

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