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

Revision 3316, 70.5 KB checked in by mattausch, 15 years ago (diff)

surpressed blur, worked on object placing in sibenik (why performance worse than vienna??)

RevLine 
[2961]1// chcdemo.cpp : Defines the entry point for the console application.
[2642]2//
[3019]3
[3021]4
5#include "common.h"
6
[3019]7#ifdef _CRT_SET
8        #define _CRTDBG_MAP_ALLOC
9        #include <stdlib.h>
10        #include <crtdbg.h>
11
12        // redefine new operator
13        #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
14        #define new DEBUG_NEW
15#endif
16
[2746]17#include <math.h>
18#include <time.h>
[3019]19#include "glInterface.h"
20
21
[2642]22#include "RenderTraverser.h"
[2756]23#include "SceneEntity.h"
24#include "Vector3.h"
25#include "Matrix4x4.h"
[2795]26#include "ResourceManager.h"
[2756]27#include "Bvh.h"
28#include "Camera.h"
29#include "Geometry.h"
[2760]30#include "BvhLoader.h"
31#include "FrustumCullingTraverser.h"
[2763]32#include "StopAndWaitTraverser.h"
[2764]33#include "CHCTraverser.h"
[2767]34#include "CHCPlusPlusTraverser.h"
35#include "Visualization.h"
[2769]36#include "RenderState.h"
[2795]37#include "Timer/PerfTimer.h"
[2796]38#include "SceneQuery.h"
[2801]39#include "RenderQueue.h"
[2819]40#include "Material.h"
[2826]41#include "glfont2.h"
[2827]42#include "PerformanceGraph.h"
[2828]43#include "Environment.h"
[2837]44#include "Halton.h"
[2840]45#include "Transform3.h"
[2853]46#include "SampleGenerator.h"
[2857]47#include "FrameBufferObject.h"
[2896]48#include "DeferredRenderer.h"
[2887]49#include "ShadowMapping.h"
50#include "Light.h"
[2953]51#include "SceneEntityConverter.h"
[2957]52#include "SkyPreetham.h"
[2964]53#include "Texture.h"
[3057]54#include "ShaderManager.h"
[3078]55#include "MotionPath.h"
[3113]56#include "ShaderProgram.h"
57#include "Shape.h"
[3219]58#include "WalkThroughRecorder.h"
[3223]59#include "StatsWriter.h"
[3243]60#include "VisibilitySolutionLoader.h"
61#include "ViewCellsTree.h"
[3258]62#include "PvsCollectionRenderer.h"
[3260]63#include "ObjExporter.h"
64#include "BvhExporter.h"
[2642]65
[3066]66
[2756]67using namespace std;
[2776]68using namespace CHCDemoEngine;
[2642]69
70
[3068]71/// the environment for the program parameter
[2828]72static Environment env;
73
74
[2826]75GLuint fontTex;
[3068]76/// the fbo used for MRT
[3038]77FrameBufferObject *fbo = NULL;
[2756]78/// the renderable scene geometry
[3267]79SceneEntityContainer staticObjects;
[3214]80/// the dynamic objects in the scene
[3070]81SceneEntityContainer dynamicObjects;
[2756]82// traverses and renders the hierarchy
[2767]83RenderTraverser *traverser = NULL;
[2756]84/// the hierarchy
[2767]85Bvh *bvh = NULL;
[2793]86/// handles scene loading
[3059]87ResourceManager *resourceManager = NULL;
[3057]88/// handles scene loading
89ShaderManager *shaderManager = NULL;
[2756]90/// the scene camera
[3062]91PerspectiveCamera *camera = NULL;
[2795]92/// the scene camera
[3062]93PerspectiveCamera *visCamera = NULL;
[2767]94/// the visualization
95Visualization *visualization = NULL;
[3101]96/// the current render renderState
97RenderState renderState;
[2764]98/// the rendering algorithm
[2795]99int renderMode = RenderTraverser::CHCPLUSPLUS;
[3038]100/// eye near plane distance
[3068]101const float nearDist = 0.2f;
[3106]102//const float nearDist = 1.0f;
[3038]103/// eye far plane distance
[2927]104float farDist = 1e6f;
[2856]105/// the field of view
[3068]106const float fov = 50.0f;
[2764]107
[3279]108float skyDomeScaleFactor = 80.0f;
109
[2796]110SceneQuery *sceneQuery = NULL;
[2801]111RenderQueue *renderQueue = NULL;
[3068]112/// traverses and renders the hierarchy
[2897]113RenderTraverser *shadowTraverser = NULL;
[3068]114/// the skylight + skydome model
[2957]115SkyPreetham *preetham = NULL;
[2897]116
[3078]117MotionPath *motionPath = NULL;
[3189]118/// max depth where candidates for tighter bounds are searched
[3123]119int maxDepthForTestingChildren = 3;
[3246]120/// use full resolution for ssao or half
[3216]121bool ssaoUseFullResolution = false;
[3123]122
[3219]123/// store the frames as tga
124bool recordFrames = false;
125/// record the taken path
126bool recordPath = false;
127/// replays the recorded path
128bool replayPath = false;
[3223]129/// frame number for replay
[3219]130int currentReplayFrame = -1;
131
[3220]132string recordedFramesSuffix("frames");
[3223]133string statsFilename("stats");
[3220]134
[3238]135string filename("city");
[3271]136string bvhname("");
[3243]137string visibilitySolution("");
[3238]138
139
[3219]140/// the walkThroughRecorder
141WalkThroughRecorder *walkThroughRecorder = NULL;
142WalkThroughPlayer *walkThroughPlayer = NULL;
[3223]143StatsWriter *statsWriter = NULL;
[3219]144
[3225]145bool makeSnapShot = false;
[3219]146
[3244]147ViewCellsTree *viewCellsTree = NULL;
[3246]148ViewCell *viewCell = NULL;
[3225]149
[3247]150bool useSkylightForIllum = true;
151
[3273]152bool showFPS = true;
153
[3245]154static int globalVisibleId = 0;
[3244]155
[3284]156PerfTimer applicationTimer;
[3245]157
[3284]158float shotRays = .0f;
[3286]159/// the visibility solution is initialized at this number of rays shot that
160int visibilitySolutionInitialState = 0;
[3245]161
[3295]162Vector3 defaultAmbient(0.2f);
163Vector3 defaultDiffuse(1.0f);
[3284]164
[3295]165
[3068]166/// the technique used for rendering
167enum RenderTechnique
168{
169        FORWARD,
170        DEFERRED,
171        DEPTH_PASS
172};
173
174
[2994]175/// the used render type for this render pass
176enum RenderMethod
177{
[3043]178        RENDER_FORWARD,
[2994]179        RENDER_DEPTH_PASS,
180        RENDER_DEFERRED,
181        RENDER_DEPTH_PASS_DEFERRED,
182        RENDER_NUM_RENDER_TYPES
183};
[2957]184
[2994]185/// one of four possible render methods
[3043]186int renderMethod = RENDER_FORWARD;
[2994]187
[3059]188static int winWidth = 1024;
189static int winHeight = 768;
190static float winAspectRatio = 1.0f;
[2994]191
[2809]192/// these values get scaled with the frame rate
[2828]193static float keyForwardMotion = 30.0f;
194static float keyRotation = 1.5f;
[2801]195
[2826]196/// elapsed time in milliseconds
[3059]197double elapsedTime = 1000.0;
198double algTime = 1000.0;
199double accumulatedTime = 1000.0;
200float fps = 1e3f;
[3193]201float turbitity = 5.0f;
[2795]202
[3212]203// ssao parameters
204float ssaoKernelRadius = 1e-8f;
205float ssaoSampleIntensity = 0.2f;
[3305]206float ssaoFilterRadius = 3.0f;
[3212]207float ssaoTempCohFactor = 255.0;
208bool sortSamples = true;
209
[2945]210int shadowSize = 2048;
[3212]211
[3059]212/// the hud font
[2826]213glfont::GLFont myfont;
214
[2809]215// rendertexture
[3212]216int texWidth = 1024;
217int texHeight = 768;
[2866]218
[2770]219int renderedObjects = 0;
[2773]220int renderedNodes = 0;
221int renderedTriangles = 0;
222
[2770]223int issuedQueries = 0;
224int traversedNodes = 0;
225int frustumCulledNodes = 0;
226int queryCulledNodes = 0;
227int stateChanges = 0;
[2800]228int numBatches = 0;
[2770]229
[3101]230// mouse navigation renderState
[2809]231int xEyeBegin = 0;
232int yEyeBegin = 0;
233int yMotionBegin = 0;
234int verticalMotionBegin = 0;
235int horizontalMotionBegin = 0;
[2642]236
[2792]237bool leftKeyPressed = false;
238bool rightKeyPressed = false;
239bool upKeyPressed = false;
240bool downKeyPressed = false;
[2837]241bool descendKeyPressed = false;
242bool ascendKeyPressed = false;
[3105]243bool leftStrafeKeyPressed = false;
244bool rightStrafeKeyPressed = false;
245
[3054]246bool altKeyPressed = false;
247
[2994]248bool showHelp = false;
249bool showStatistics = false;
250bool showOptions = true;
251bool showBoundingVolumes = false;
252bool visMode = false;
253
254bool useOptimization = false;
[3074]255bool useTightBounds = true;
[2994]256bool useRenderQueue = true;
257bool useMultiQueries = true;
258bool flyMode = true;
259
[2875]260bool useGlobIllum = false;
261bool useTemporalCoherence = true;
[2994]262bool showAlgorithmTime = false;
[2875]263
[2994]264bool useFullScreen = false;
265bool useLODs = true;
266bool moveLight = false;
267
268bool useAdvancedShading = false;
269bool showShadowMap = false;
270bool renderLightView = false;
[3054]271bool useHDR = true;
[3175]272bool useAntiAliasing = true;
[3215]273bool useLenseFlare = true;
[2994]274
[3246]275bool usePvs = false;
276
277
[3054]278PerfTimer frameTimer, algTimer;
[3212]279/// the performance graph window
[3054]280PerformanceGraph *perfGraph = NULL;
[2994]281
[3189]282int sCurrentMrtSet = 0;
[3111]283static Matrix4x4 invTrafo = IdentityMatrix();
[3246]284float mouseMotion = 0.2f;
[3111]285
[3256]286float viewCellsScaleFactor = 1.0f;
[3246]287
[3316]288float maxConvergence = 2000.0f;
[3256]289
[3316]290
291
[3068]292//////////////
[3246]293//-- chc++ algorithm parameters
[2827]294
[3068]295/// the pixel threshold where a node is still considered invisible
296/// (should be zero for conservative visibility)
297int threshold;
298int assumedVisibleFrames = 10;
299int maxBatchSize = 50;
300int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
301
[3244]302
[3068]303//////////////
304
305enum {CAMERA_PASS = 0, LIGHT_PASS = 1};
306
307
[2948]308//DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_POISSON;
309DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_QUADRATIC;
[2865]310
[2894]311ShadowMap *shadowMap = NULL;
[2952]312DirectionalLight *light = NULL;
[3111]313DeferredRenderer *deferredShader = NULL;
[2834]314
[3175]315
[3059]316SceneEntity *buddha = NULL;
[2957]317SceneEntity *skyDome = NULL;
[3214]318SceneEntity *sunBox = NULL;
[2895]319
[3214]320GLuint sunQuery = 0;
[2952]321
[3271]322string walkThroughSuffix("frames");
[3214]323
[3271]324
[3059]325////////////////////
326//--- function forward declarations
[2991]327
[2759]328void InitExtensions();
[3059]329void InitGLstate();
330
[2756]331void DisplayVisualization();
[3059]332/// destroys all allocated resources
[2759]333void CleanUp();
334void SetupEyeView();
335void SetupLighting();
[2764]336void DisplayStats();
[3059]337/// draw the help screen
[2786]338void DrawHelpMessage();
[3059]339/// render the sky dome
[2796]340void RenderSky();
[3059]341/// render the objects found visible in the depth pass
[2801]342void RenderVisibleObjects();
[2756]343
[3215]344int TestSunVisible();
[3214]345
[2792]346void Begin2D();
347void End2D();
[3059]348/// the main loop
349void MainLoop();
350
[2792]351void KeyBoard(unsigned char c, int x, int y);
352void Special(int c, int x, int y);
353void KeyUp(unsigned char c, int x, int y);
354void SpecialKeyUp(int c, int x, int y);
355void Reshape(int w, int h);
[3101]356void Mouse(int button, int renderState, int x, int y);
[2792]357void LeftMotion(int x, int y);
358void RightMotion(int x, int y);
359void MiddleMotion(int x, int y);
[3059]360void KeyHorizontalMotion(float shift);
361void KeyVerticalMotion(float shift);
362/// returns the string representation of a number with the decimal points
[2792]363void CalcDecimalPoint(string &str, int d);
[3059]364/// Creates the traversal method (vfc, stopandwait, chc, chc++)
[3062]365RenderTraverser *CreateTraverser(PerspectiveCamera *cam);
[3059]366/// place the viewer on the floor plane
[2801]367void PlaceViewer(const Vector3 &oldPos);
[3019]368// initialise the frame buffer objects
[2809]369void InitFBO();
[3059]370/// changes the sunlight direction
[2954]371void RightMotionLight(int x, int y);
[3059]372/// render the shader map
[2951]373void RenderShadowMap(float newfar);
[3059]374/// function that touches each material once in order to accelarate render queue
375void PrepareRenderQueue();
376/// loads the specified model
[3237]377int LoadModel(const string &model, SceneEntityContainer &entities);
[2810]378
[3059]379inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
380inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
[3054]381
[3316]382void CreateAnimation(const Vector3 &pos);
[3078]383
[3120]384SceneQuery *GetOrCreateSceneQuery();
[3078]385
[3246]386void LoadPvs();
[3120]387
[3246]388void LoadVisibilitySolution();
[3244]389
[3246]390void RenderViewCell();
391
[3279]392void LoadPompeiiFloor();
[3246]393
[3287]394void LoadOrUpdatePVSs(const Vector3 &pos);
395
[3316]396void CreateNewInstance(SceneEntity *parent, const Vector3 &pos);
397
398
399/////////////
400
[3292]401string envFileName = "default.env";
[3287]402
[3285]403float pvsTotalSamples = .0f;
404float pvsTotalTime = .0f;
[3276]405
[3285]406
[3120]407// new view projection matrix of the camera
[3005]408static Matrix4x4 viewProjMat = IdentityMatrix();
[3120]409// the old view projection matrix of the camera
[3005]410static Matrix4x4 oldViewProjMat = IdentityMatrix();
[2820]411
[2837]412
[2995]413
[2809]414static void PrintGLerror(char *msg)
415{
416        GLenum errCode;
417        const GLubyte *errStr;
418       
419        if ((errCode = glGetError()) != GL_NO_ERROR)
420        {
421                errStr = gluErrorString(errCode);
422                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
423        }
424}
425
426
[2642]427int main(int argc, char* argv[])
428{
[3019]429#ifdef _CRT_SET
430        //Now just call this function at the start of your program and if you're
431        //compiling in debug mode (F5), any leaks will be displayed in the Output
432        //window when the program shuts down. If you're not in debug mode this will
433        //be ignored. Use it as you will!
434        //note: from GDNet Direct [3.8.04 - 3.14.04] void detectMemoryLeaks() {
435
436        _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF);
437        _CrtSetReportMode(_CRT_ASSERT,_CRTDBG_MODE_FILE);
438        _CrtSetReportFile(_CRT_ASSERT,_CRTDBG_FILE_STDERR);
439#endif
[3052]440
[3019]441
[2781]442        int returnCode = 0;
443
[2837]444        Vector3 camPos(.0f, .0f, .0f);
[2838]445        Vector3 camDir(.0f, 1.0f, .0f);
[2952]446        Vector3 lightDir(-0.8f, 1.0f, -0.7f);
[2837]447
[3292]448        if (argc > 1) envFileName = argv[1];
[2830]449
[3292]450        cout << "=== reading environment file " << envFileName << " ===" << endl << endl;
451
[2837]452        if (!env.Read(envFileName))
453        {
454                cerr << "loading environment " << envFileName << " failed!" << endl;
455        }
456        else
457        {
458                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
459                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
460                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
[3123]461                env.GetIntParam(string("winWidth"), winWidth);
462                env.GetIntParam(string("winHeight"), winHeight);
463                env.GetIntParam(string("shadowSize"), shadowSize);
464                env.GetIntParam(string("maxDepthForTestingChildren"), maxDepthForTestingChildren);
[2828]465
[2837]466                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
467                env.GetFloatParam(string("keyRotation"), keyRotation);
[3246]468                env.GetFloatParam(string("mouseMotion"), mouseMotion);
[3123]469                env.GetFloatParam(string("tempCohFactor"), ssaoTempCohFactor);
[3193]470                env.GetFloatParam(string("turbitity"), turbitity);
[3123]471               
[2837]472                env.GetVectorParam(string("camPosition"), camPos);
[2838]473                env.GetVectorParam(string("camDirection"), camDir);
[2952]474                env.GetVectorParam(string("lightDirection"), lightDir);
[3295]475                env.GetVectorParam(string("defaultAmbient"), defaultAmbient);
476                env.GetVectorParam(string("defaultDiffuse"), defaultDiffuse);
[2865]477
[3117]478                env.GetBoolParam(string("useFullScreen"), useFullScreen);
479                env.GetBoolParam(string("useLODs"), useLODs);
[2994]480                env.GetBoolParam(string("useHDR"), useHDR);
[3175]481                env.GetBoolParam(string("useAA"), useAntiAliasing);
[3215]482                env.GetBoolParam(string("useLenseFlare"), useLenseFlare);
[3175]483                env.GetBoolParam(string("useAdvancedShading"), useAdvancedShading);
[2994]484
[3175]485                env.GetIntParam(string("renderMethod"), renderMethod);
[3117]486
[3212]487                env.GetFloatParam(string("ssaoKernelRadius"), ssaoKernelRadius);
488                env.GetFloatParam(string("ssaoSampleIntensity"), ssaoSampleIntensity);
[3216]489                env.GetBoolParam(string("ssaoUseFullResolution"), ssaoUseFullResolution);
490
[3220]491                env.GetStringParam(string("recordedFramesSuffix"), recordedFramesSuffix);
[3271]492                env.GetStringParam(string("walkThroughSuffix"), walkThroughSuffix);
[3223]493                env.GetStringParam(string("statsFilename"), statsFilename);
[3238]494                env.GetStringParam(string("filename"), filename);
[3271]495                env.GetStringParam(string("bvhname"), bvhname);
[3243]496                env.GetStringParam(string("visibilitySolution"), visibilitySolution);
[3220]497
[3246]498                env.GetBoolParam(string("usePvs"), usePvs);
[3247]499                env.GetBoolParam(string("useSkylightForIllum"), useSkylightForIllum);
[3256]500                env.GetFloatParam(string("viewCellsScaleFactor"), viewCellsScaleFactor);
[3279]501                env.GetFloatParam(string("skyDomeScaleFactor"), skyDomeScaleFactor);
[3286]502                env.GetIntParam(string("visibilitySolutionInitialState"), visibilitySolutionInitialState);
[3294]503                env.GetIntParam(string("renderMode"), renderMode);
[3279]504               
[2846]505                //env.GetStringParam(string("modelPath"), model_path);
[2838]506                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
507
[3212]508                texWidth = winWidth;
509                texHeight = winHeight;
510
[3251]511                cout << "assumed visible frames: " << assumedVisibleFrames << endl;
512                cout << "max batch size: " << maxBatchSize << endl;
513                cout << "triangles per virtual leaf: " << trianglesPerVirtualLeaf << endl;
[2828]514
[3271]515                cout << "static scene filename prefix: " << filename << endl;
516                cout << "bvh filename prefix: " << bvhname << endl;
517
[3251]518                cout << "key forward motion: " << keyForwardMotion << endl;
519                cout << "key rotation: " << keyRotation << endl;
520                cout << "win width: " << winWidth << endl;
521                cout << "win height: " << winHeight << endl;
522                cout << "use full screen: " << useFullScreen << endl;
523                cout << "use LODs: " << useLODs << endl;
524                cout << "camera position: " << camPos << endl;
[2945]525                cout << "shadow size: " << shadowSize << endl;
[3175]526                cout << "render method: " << renderMethod << endl;
527                cout << "use antialiasing: " << useAntiAliasing << endl;
[3215]528                cout << "use lense flare: " << useLenseFlare << endl;
[3175]529                cout << "use advanced shading: " << useAdvancedShading << endl;
[3193]530                cout << "turbitity: " << turbitity << endl;
[3251]531                cout << "temporal coherence factor: " << ssaoTempCohFactor << endl;
[3212]532                cout << "sample intensity: " << ssaoSampleIntensity << endl;
533                cout << "kernel radius: " << ssaoKernelRadius << endl;
[3251]534                cout << "use ssao full resolution: " << ssaoUseFullResolution << endl;
[3220]535                cout << "recorded frames suffix: " << recordedFramesSuffix << endl;
[3271]536                cout << "walkthrough suffix: " << walkThroughSuffix << endl;
[3223]537                cout << "stats filename: " << statsFilename << endl;
[3251]538                cout << "use PVSs: " << usePvs << endl;
539                cout << "visibility solution: " << visibilitySolution << endl;
[3256]540                cout << "view cells scale factor: " << viewCellsScaleFactor << endl;
[3251]541                cout << "use skylight for illumination: " << useSkylightForIllum << endl;
[3279]542                cout << "sky dome scale factor: " << skyDomeScaleFactor << endl;
[3294]543                cout << "rendermode: " << renderMode << endl;
[2873]544
[2846]545                //cout << "model path: " << model_path << endl;
[3294]546                cout << "==== end parameters ====" << endl << endl;
[2837]547        }
[2829]548
[2828]549        ///////////////////////////
550
[3062]551        camera = new PerspectiveCamera(winWidth / winHeight, fov);
[2795]552        camera->SetNear(nearDist);
[2913]553        camera->SetFar(1000);
[2888]554
[2838]555        camera->SetDirection(camDir);
[2829]556        camera->SetPosition(camPos);
557
[3062]558        visCamera = new PerspectiveCamera(winWidth / winHeight, fov);
[2796]559        visCamera->SetNear(0.0f);
560        visCamera->Yaw(.5 * M_PI);
[2781]561
[2952]562        // create a new light
[2968]563        light = new DirectionalLight(lightDir, RgbaColor(1, 1, 1, 1), RgbaColor(1, 1, 1, 1));
[3061]564        // the render queue for material sorting
[3101]565        renderQueue = new RenderQueue(&renderState);
[2952]566
[2760]567        glutInitWindowSize(winWidth, winHeight);
[2756]568        glutInit(&argc, argv);
[2853]569        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
570        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
[2850]571        //glutInitDisplayString("samples=2");
572
[2867]573        SceneEntity::SetUseLODs(useLODs);
574
[3256]575
[2828]576        if (!useFullScreen)
[2856]577        {
[2828]578                glutCreateWindow("FriendlyCulling");
[2856]579        }
[2828]580        else
581        {
582                glutGameModeString( "1024x768:32@75" );
583                glutEnterGameMode();
584        }
585
[3059]586        glutDisplayFunc(MainLoop);
[2792]587        glutKeyboardFunc(KeyBoard);
588        glutSpecialFunc(Special);
589        glutReshapeFunc(Reshape);
590        glutMouseFunc(Mouse);
[3059]591        glutIdleFunc(MainLoop);
[2792]592        glutKeyboardUpFunc(KeyUp);
593        glutSpecialUpFunc(SpecialKeyUp);
594        glutIgnoreKeyRepeat(true);
595
[2829]596        // initialise gl graphics
[2756]597        InitExtensions();
598        InitGLstate();
[2850]599
[2854]600        glEnable(GL_MULTISAMPLE_ARB);
601        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
[2850]602
[2792]603        LeftMotion(0, 0);
604        MiddleMotion(0, 0);
[2756]605
[2829]606        perfGraph = new PerformanceGraph(1000);
[2756]607
[3059]608        resourceManager = ResourceManager::GetSingleton();
[3057]609        shaderManager = ShaderManager::GetSingleton();
[2793]610
[3220]611
[3059]612        ///////////
613        //-- load the static scene geometry
[2756]614
[3267]615        LoadModel(filename + ".dem", staticObjects);
[3059]616
[3074]617
[3072]618        //////////
619        //-- load some dynamic stuff
[3059]620
[3203]621        //resourceManager->mUseNormalMapping = true;
[3193]622        //resourceManager->mUseNormalMapping = false;
[3127]623
[3226]624        resourceManager->mUseSpecialColors = true;
625
[3203]626        //LoadModel("fisch.dem", dynamicObjects);
[3235]627
[3146]628        //LoadModel("venusm.dem", dynamicObjects);
[3153]629        //LoadModel("camel.dem", dynamicObjects);
[3146]630        //LoadModel("toyplane2.dem", dynamicObjects);
[3151]631        //LoadModel("elephal.dem", dynamicObjects);
[3128]632
[3294]633        if (0) LoadPompeiiFloor();
[3271]634
[3314]635#if 1
[3316]636
637#if 0
638        VertexArray positions;
639        positions.push_back(Vector3(478.398f, 268.0f, 181.3));
640        positions.push_back(Vector3(470.461, 268.543, 181.7));
641        positions.push_back(Vector3(499.648, 264.358, 181.7));
642        positions.push_back(Vector3(487.913, 285.162, 181.7));
643
644#else
645
646        VertexArray positions;
647        //positions.push_back(Vector3(6.07307, 8.20723, 6.7));
648        positions.push_back(Vector3(6.07307, 8.20723, 6.62));
649        positions.push_back(Vector3(-17.1935, 11.1687, 8.8781));
650        //positions.push_back(Vector3(499.648, 264.358, 181.7));
651        //positions.push_back(Vector3(487.913, 285.162, 181.7));
652
653#endif
654
[3261]655        //const Vector3 sceneCenter(470.398f, 240.364f, 180.3);
[3316]656        Matrix4x4 transl = TranslationMatrix(positions[0]);
[3261]657       
[3247]658        LoadModel("hbuddha.dem", dynamicObjects);
[3128]659
[3072]660        buddha = dynamicObjects.back();
661        buddha->GetTransform()->SetMatrix(transl);
662
[3316]663       
664        for (size_t i = 1; i < positions.size(); ++ i)
[3072]665        {
[3316]666                CreateNewInstance(buddha, positions[i]);
667        }
[3072]668
[3247]669#endif
[3072]670
[3247]671       
672        resourceManager->mUseNormalMapping = false;
673        resourceManager->mUseSpecialColors = false;
674
675
[3059]676        ///////////
677        //-- load the associated static bvh
678
[3266]679        BvhFactory bvhFactory;
[2795]680
[3271]681        if (bvhname != "")
[2795]682        {
[3271]683                cout << "loading bvh from disc" << endl;
684                const string bvh_fullpath = string(model_path + bvhname + ".bvh");
685                bvh = bvhFactory.Create(bvh_fullpath, staticObjects, dynamicObjects, maxDepthForTestingChildren);
686
687                if (!bvh)
688                {
689                        cerr << "loading bvh " << bvh_fullpath << " failed" << endl;
690                        CleanUp();
691                        exit(0);
692                }
[2795]693        }
[3271]694        else
695        {
696                cout << "creating new bvh" << endl;
697                bvh = bvhFactory.Create(staticObjects, dynamicObjects, maxDepthForTestingChildren);
698        }
[2795]699
[3059]700        /// set the depth of the bvh depending on the triangles per leaf node
701        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
702
[2963]703        // set far plane based on scene extent
704        farDist = 10.0f * Magnitude(bvh->GetBox().Diagonal());
[3059]705        camera->SetFar(farDist);
[2963]706
[2961]707
[3282]708        //ObjExporter().Export(model_path + "mytest.obj", bvh);
709        //BvhExporter().Export(model_path + "mytest.bv", bvh);
[3260]710
711
712
[3059]713        //////////////////
714        //-- setup the skydome model
[2964]715
[3267]716        LoadModel("sky.dem", staticObjects);
717        skyDome = staticObjects.back();
[2861]718
[3059]719        /// the turbitity of the sky (from clear to hazy, use <3 for clear sky)
[3193]720        preetham = new SkyPreetham(turbitity, skyDome);
[2961]721
[3316]722        CreateAnimation(positions[0]);
[3059]723
[3219]724
[3214]725        //////////////////////////
[3219]726        //-- a bounding box representing the sun pos in order to test visibility
727
[3214]728        Transform3 *trafo = resourceManager->CreateTransform(IdentityMatrix());
[3078]729
[3214]730        // make it slightly bigger to simulate sun diameter
731        const float size = 25.0f;
732        AxisAlignedBox3 sbox(Vector3(-size), Vector3(size));
733
734        SceneEntityConverter conv;
735
[3245]736
737        //////////////////
738        //-- occlusion query for sun
739
[3215]740        Material *mat = resourceManager->CreateMaterial();
[3214]741
742        mat->GetTechnique(0)->SetDepthWriteEnabled(false);
743        mat->GetTechnique(0)->SetColorWriteEnabled(false);
744
745        sunBox = conv.ConvertBox(sbox, mat, trafo);
[3215]746        resourceManager->AddSceneEntity(sunBox);
747
748        /// create single occlusion query that handles sun visibility
[3214]749        glGenQueriesARB(1, &sunQuery);
750
751
[3059]752        //////////
753        //-- initialize the traversal algorithm
754
[2897]755        traverser = CreateTraverser(camera);
[3059]756       
757        // the bird-eye visualization
[3101]758        visualization = new Visualization(bvh, camera, NULL, &renderState);
[3054]759
[3059]760        // this function assign the render queue bucket ids of the materials in beforehand
[3227]761        // => probably less overhead for new parts of the scene that are not yet assigned
[3059]762        PrepareRenderQueue();
763        /// forward rendering is the default
[3101]764        renderState.SetRenderTechnique(FORWARD);
[2847]765        // frame time is restarted every frame
766        frameTimer.Start();
[3059]767
[3238]768        //Halton::TestHalton(7, 2);
769        //HaltonSequence::TestHalton(15, 2);
770        //Halton::TestPrime();
[3227]771
[2857]772        // the rendering loop
[2642]773        glutMainLoop();
[3059]774       
[2642]775        // clean up
[2756]776        CleanUp();
[3019]777       
[2642]778        return 0;
779}
780
[2756]781
[2809]782void InitFBO()
[2810]783{
[2949]784        PrintGLerror("fbo start");
[2980]785
[2857]786        // this fbo basicly stores the scene information we get from standard rendering of a frame
[3066]787        // we store diffuse colors, eye space depth and normals
[2884]788        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_32);
[2857]789
[2859]790        // the diffuse color buffer
[3015]791        fbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, ColorBufferObject::FILTER_NEAREST);
[3009]792        // the normals buffer
[3197]793        //fbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST);
794        fbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
[3066]795        // a rgb buffer which could hold material properties
[3113]796        //fbo->AddColorBuffer(ColorBufferObject::RGB_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST);
[3117]797        // buffer holding the difference vector to the old frame
[3167]798        fbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
[2879]799        // another color buffer
[3015]800        fbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, ColorBufferObject::FILTER_NEAREST);
[2879]801
[3117]802        for (int i = 0; i < 4; ++ i)
[3219]803        {
[3117]804                FrameBufferObject::InitBuffer(fbo, i);
[3219]805        }
806
[3117]807        PrintGLerror("init fbo");
[2809]808}
809
810
[2827]811bool InitFont(void)
[2642]812{
[2826]813        glEnable(GL_TEXTURE_2D);
814
815        glGenTextures(1, &fontTex);
816        glBindTexture(GL_TEXTURE_2D, fontTex);
[3019]817
[2829]818        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
[2826]819                return false;
820
821        glDisable(GL_TEXTURE_2D);
[2827]822       
[2826]823        return true;
824}
825
826
827void InitGLstate()
828{
[3246]829        glClearColor(0.4f, 0.4f, 0.4f, 1e20f);
[2642]830       
831        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
832        glPixelStorei(GL_PACK_ALIGNMENT,1);
833       
834        glDepthFunc(GL_LESS);
[2762]835        glEnable(GL_DEPTH_TEST);
[2642]836
[2760]837        glColor3f(1.0f, 1.0f, 1.0f);
[2642]838        glShadeModel(GL_SMOOTH);
839       
840        glMaterialf(GL_FRONT, GL_SHININESS, 64);
841        glEnable(GL_NORMALIZE);
[2767]842               
843        glDisable(GL_ALPHA_TEST);
[2951]844        glAlphaFunc(GL_GEQUAL, 0.5f);
[2767]845
[2642]846        glFrontFace(GL_CCW);
847        glCullFace(GL_BACK);
[2851]848        glEnable(GL_CULL_FACE);
849
[2800]850        glDisable(GL_TEXTURE_2D);
[2762]851
[2959]852        GLfloat ambientColor[] = {0.2, 0.2, 0.2, 1.0};
[2756]853        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
[2759]854        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
[2642]855
[2756]856        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
857        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
858        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
[2801]859
860        glDepthFunc(GL_LESS);
[2826]861
[2827]862        if (!InitFont())
[2826]863                cerr << "font creation failed" << endl;
864        else
865                cout << "successfully created font" << endl;
[2953]866
867
[2954]868        //////////////////////////////
869
[2959]870        //GLfloat lmodel_ambient[] = {1.0f, 1.0f, 1.0f, 1.0f};
871        GLfloat lmodel_ambient[] = {0.7f, 0.7f, 0.8f, 1.0f};
[2954]872
873        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
[2959]874        //glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
875        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
[2954]876        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
[2642]877}
878
879
[2827]880void DrawHelpMessage()
[2826]881{
[2642]882        const char *message[] =
883        {
884                "Help information",
885                "",
886                "'F1'           - shows/dismisses this message",
[2795]887                "'F2'           - shows/hides bird eye view",
[2790]888                "'F3'           - shows/hides bounds (boxes or tight bounds)",
[2827]889                "'F4',          - shows/hides parameters",
890                "'F5'           - shows/hides statistics",
891                "'F6',          - toggles between fly/walkmode",
[2826]892                "'F7',          - cycles throw render modes",
893                "'F8',          - enables/disables ambient occlusion (only deferred)",
894                "'F9',          - shows pure algorithm render time (using glFinish)",
[2790]895                "'SPACE'        - cycles through occlusion culling algorithms",
[2642]896                "",
[2827]897                "'MOUSE LEFT'        - turn left/right, move forward/backward",
898                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
899                "'MOUSE MIDDLE'      - move up/down, left/right",
900                "'CURSOR UP/DOWN'    - move forward/backward",
901                "'CURSOR LEFT/RIGHT' - turn left/right",
[2642]902                "",
[2827]903                "'-'/'+'        - decreases/increases max batch size",
[2837]904                "'1'/'2'        - downward/upward motion",
905                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
906                "'5'/'6'        - decreases/increases assumed visible frames",
[2776]907                "",
[2786]908                "'R'            - use render queue",
[2790]909                "'B'            - use tight bounds",
910                "'M'            - use multiqueries",
[2792]911                "'O'            - use CHC optimization (geometry queries for leaves)",
[2642]912                0,
913        };
914       
[2756]915       
[2827]916        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
[2756]917
[2827]918        glRecti(30, 30, winWidth - 30, winHeight - 30);
[2642]919
[2827]920        glEnd();
921
[2756]922        glColor3f(1.0f, 1.0f, 1.0f);
923       
[2829]924        glEnable(GL_TEXTURE_2D);
[2827]925        myfont.Begin();
926
927        int x = 40, y = 30;
928
929        for(int i = 0; message[i] != 0; ++ i)
[2756]930        {
931                if(message[i][0] == '\0')
932                {
[2786]933                        y += 15;
[2756]934                }
935                else
936                {
[2827]937                        myfont.DrawString(message[i], x, winHeight - y);
938                        y += 25;
[2642]939                }
940        }
[2829]941        glDisable(GL_TEXTURE_2D);
[2642]942}
943
944
[3062]945RenderTraverser *CreateTraverser(PerspectiveCamera *cam)
[2764]946{
[2897]947        RenderTraverser *tr;
948       
[2764]949        switch (renderMode)
950        {
951        case RenderTraverser::CULL_FRUSTUM:
[2897]952                tr = new FrustumCullingTraverser();
[2764]953                break;
954        case RenderTraverser::STOP_AND_WAIT:
[2897]955                tr = new StopAndWaitTraverser();
[2764]956                break;
957        case RenderTraverser::CHC:
[2897]958                tr = new CHCTraverser();
[2764]959                break;
[2767]960        case RenderTraverser::CHCPLUSPLUS:
[2897]961                tr = new CHCPlusPlusTraverser();
[2767]962                break;
[3284]963        //case RenderTraverser::CULL_COLLECTOR:
964        //      tr = new PvsCollectionRenderer();
965        //      break;
[2764]966        default:
[2897]967                tr = new FrustumCullingTraverser();
[2764]968        }
969
[2897]970        tr->SetCamera(cam);
971        tr->SetHierarchy(bvh);
972        tr->SetRenderQueue(renderQueue);
[3101]973        tr->SetRenderState(&renderState);
[2897]974        tr->SetUseOptimization(useOptimization);
975        tr->SetUseRenderQueue(useRenderQueue);
976        tr->SetVisibilityThreshold(threshold);
977        tr->SetAssumedVisibleFrames(assumedVisibleFrames);
978        tr->SetMaxBatchSize(maxBatchSize);
979        tr->SetUseMultiQueries(useMultiQueries);
[3294]980        tr->SetUseTightBounds((renderMode == RenderTraverser::CHCPLUSPLUS) && useTightBounds);
[2955]981        tr->SetUseDepthPass((renderMethod == RENDER_DEPTH_PASS) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED));
[2897]982        tr->SetRenderQueue(renderQueue);
[3066]983        tr->SetShowBounds(showBoundingVolumes);
[2897]984
[3066]985        bvh->ResetNodeClassifications();
986
987
[2897]988        return tr;
[2764]989}
990
[3295]991/** Setup lighting conditions
[3059]992*/
[2759]993void SetupLighting()
[2642]994{
[2759]995        glEnable(GL_LIGHT0);
[2959]996        glDisable(GL_LIGHT1);
[2825]997       
[2954]998        Vector3 lightDir = -light->GetDirection();
999
1000
[2945]1001        ///////////
1002        //-- first light: sunlight
1003
[2954]1004        GLfloat ambient[] = {0.25f, 0.25f, 0.3f, 1.0f};
1005        GLfloat diffuse[] = {1.0f, 0.95f, 0.85f, 1.0f};
1006        GLfloat specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
[2982]1007       
[2759]1008
[3175]1009        const bool useHDRValues =
[3046]1010                ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) ||
1011                 (renderMethod == RENDER_DEFERRED)) && useHDR;
[2982]1012
[3046]1013
[2954]1014        Vector3 sunAmbient;
1015        Vector3 sunDiffuse;
[2759]1016
[3247]1017        if (useSkylightForIllum)
1018        {
1019                preetham->ComputeSunColor(lightDir, sunAmbient, sunDiffuse, !useHDRValues);
[2945]1020
[3247]1021                ambient[0] = sunAmbient.x;
1022                ambient[1] = sunAmbient.y;
1023                ambient[2] = sunAmbient.z;
[2825]1024
[3247]1025                diffuse[0] = sunDiffuse.x;
1026                diffuse[1] = sunDiffuse.y;
1027                diffuse[2] = sunDiffuse.z;
1028        }
1029        else
1030        {
[3295]1031                ambient[0] = defaultAmbient.x;
1032                ambient[1] = defaultAmbient.y;
1033                ambient[2] = defaultAmbient.z;
[2945]1034
[3295]1035                diffuse[0] = defaultDiffuse.x;
1036                diffuse[1] = defaultDiffuse.y;
1037                diffuse[2] = defaultDiffuse.z;
[3247]1038        }
[3193]1039
[2954]1040        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
1041        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
1042        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
[2825]1043
[2954]1044        GLfloat position[] = {lightDir.x, lightDir.y, lightDir.z, 0.0f};
1045        glLightfv(GL_LIGHT0, GL_POSITION, position);
[2642]1046}
1047
[2800]1048
[2795]1049void SetupEyeView()
[2642]1050{
[2861]1051        // store matrix of last frame
[3005]1052        oldViewProjMat = viewProjMat;
[2834]1053
[3061]1054        camera->SetupViewProjection();
[2759]1055
[3061]1056
[2864]1057        /////////////////
[3059]1058        //-- compute view projection matrix and store for later use
[2864]1059
[2894]1060        Matrix4x4 matViewing, matProjection;
[2864]1061
[2834]1062        camera->GetModelViewMatrix(matViewing);
1063        camera->GetProjectionMatrix(matProjection);
1064
[3005]1065        viewProjMat = matViewing * matProjection;
[2642]1066}
1067
1068
[2792]1069void KeyHorizontalMotion(float shift)
1070{
[2888]1071        Vector3 hvec = -camera->GetDirection();
[2792]1072        hvec.z = 0;
1073
1074        Vector3 pos = camera->GetPosition();
1075        pos += hvec * shift;
1076       
1077        camera->SetPosition(pos);
1078}
1079
1080
[2794]1081void KeyVerticalMotion(float shift)
1082{
1083        Vector3 uvec = Vector3(0, 0, shift);
1084
1085        Vector3 pos = camera->GetPosition();
1086        pos += uvec;
1087       
1088        camera->SetPosition(pos);
1089}
1090
1091
[3105]1092void KeyStrafe(float shift)
1093{
1094        Vector3 viewDir = camera->GetDirection();
1095        Vector3 pos = camera->GetPosition();
1096
1097        // the 90 degree rotated view vector
1098        // z zero so we don't move in the vertical
1099        Vector3 rVec(viewDir[0], viewDir[1], 0);
1100
1101        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1102        rVec = rot * rVec;
1103        pos += rVec * shift;
1104
1105        camera->SetPosition(pos);
1106}
1107
1108
[3059]1109/** Initialize the deferred rendering pass.
1110*/
[2948]1111void InitDeferredRendering()
1112{
1113        if (!fbo) InitFBO();
1114        fbo->Bind();
1115
1116        // multisampling does not work with deferred shading
1117        glDisable(GL_MULTISAMPLE_ARB);
[3101]1118        renderState.SetRenderTechnique(DEFERRED);
[2948]1119
1120
[3175]1121        // draw to 3 render targets
[3118]1122        if (sCurrentMrtSet == 0)
1123        {
1124                DeferredRenderer::colorBufferIdx = 0;
1125                glDrawBuffers(3, mrt);
1126        }
1127        else
1128        {
1129                DeferredRenderer::colorBufferIdx = 3;
1130                glDrawBuffers(3, mrt2);
1131        }
[2985]1132
[2978]1133        sCurrentMrtSet = 1 - sCurrentMrtSet;
[2948]1134}
1135
1136
[3059]1137/** the main rendering loop
1138*/
1139void MainLoop()
[2801]1140{       
[3291]1141        if (buddha)
[3120]1142        {
[3246]1143                Matrix4x4 oldTrafo = buddha->GetTransform()->GetMatrix();
1144                Vector3 buddhaPos = motionPath->GetCurrentPosition();
1145                Matrix4x4 trafo = TranslationMatrix(buddhaPos);
[3120]1146
[3246]1147                buddha->GetTransform()->SetMatrix(trafo);
1148
1149#if TODO // drop objects on ground floor
1150                for (int i = 0; i < 10; ++ i)
[3120]1151                {
[3246]1152                        SceneEntity *ent = dynamicObjects[i];
1153                        Vector3 newPos = ent->GetWorldCenter();
1154
1155                        if (GetOrCreateSceneQuery()->CalcIntersection(newPos))
1156                        {
1157                                Matrix4x4 mat = TranslationMatrix(newPos - ent->GetCenter());
1158                                ent->GetTransform()->SetMatrix(mat);
1159                        }
[3120]1160                }
[3221]1161#endif
[3120]1162
[3246]1163                /////////////////////////
1164                //-- update animations
[3221]1165
[3246]1166                //const float rotAngle = M_PI * 1e-3f;
[3316]1167                //const float rotAngle = 0.3f * M_PI / 180.0f;
1168                const float rotAngle = 0.6f * M_PI / 180.0f;
[3225]1169
[3246]1170                Matrix4x4 rotMatrix = RotationZMatrix(rotAngle);
[3316]1171                // hack: second buddha
[3291]1172                dynamicObjects[1]->GetTransform()->MultMatrix(rotMatrix);
[3125]1173
[3316]1174                //const float moveSpeed = 5e-3f;
1175                const float moveSpeed = 1e-1f;
[3314]1176                motionPath->Move(moveSpeed);
[3246]1177        }
[3125]1178
[3113]1179
[3111]1180        /////////////
[3078]1181
[3219]1182        static Vector3 oldPos = camera->GetPosition();
1183        static Vector3 oldDir = camera->GetDirection();
[2800]1184
[2792]1185        if (leftKeyPressed)
[2795]1186                camera->Pitch(KeyRotationAngle());
[2792]1187        if (rightKeyPressed)
[2795]1188                camera->Pitch(-KeyRotationAngle());
[2792]1189        if (upKeyPressed)
[2887]1190                KeyHorizontalMotion(-KeyShift());
1191        if (downKeyPressed)
[2795]1192                KeyHorizontalMotion(KeyShift());
[2837]1193        if (ascendKeyPressed)
1194                KeyVerticalMotion(KeyShift());
1195        if (descendKeyPressed)
[2795]1196                KeyVerticalMotion(-KeyShift());
[3105]1197        if (leftStrafeKeyPressed)
1198                KeyStrafe(KeyShift());
1199        if (rightStrafeKeyPressed)
1200                KeyStrafe(-KeyShift());
[2792]1201
[3105]1202
[2801]1203        // place view on ground
1204        if (!flyMode) PlaceViewer(oldPos);
[2800]1205
[2826]1206        if (showAlgorithmTime)
1207        {
1208                glFinish();
1209                algTimer.Start();
1210        }
[2809]1211       
[3219]1212        // don't allow replay on record
1213        if (replayPath && !recordPath)
1214        {
1215                if (!walkThroughPlayer)
[3271]1216                        walkThroughPlayer = new WalkThroughPlayer(walkThroughSuffix + ".log");
[3219]1217               
1218                ++ currentReplayFrame;
[2895]1219
[3223]1220                // reset if end of walkthrough is reached
[3219]1221                if (!walkThroughPlayer->ReadNextFrame(camera))
1222                {
[3286]1223                        cout << "reached end of walkthrough" << endl;
[3219]1224                        currentReplayFrame = -1;
1225                        replayPath = false;
1226                }
1227        }
1228
[2931]1229        if ((!shadowMap || !shadowTraverser) && (showShadowMap || renderLightView))
1230        {
[3313]1231                if (!shadowMap)
1232                        shadowMap = new ShadowMap(light, shadowSize, bvh->GetBox(), camera);
1233
1234                if (!shadowTraverser)
1235                        shadowTraverser = CreateTraverser(shadowMap->GetShadowCamera());
1236
[2931]1237        }
[2951]1238       
1239        // bring eye modelview matrix up-to-date
1240        SetupEyeView();
[3219]1241       
[3287]1242
[3059]1243        // set frame related parameters for GPU programs
[3046]1244        GPUProgramParameters::InitFrame(camera, light);
[3045]1245
[3219]1246        if (recordPath)
1247        {
1248                if (!walkThroughRecorder)
[3286]1249                {
[3271]1250                        walkThroughRecorder = new WalkThroughRecorder(walkThroughSuffix + ".log");
[3286]1251                }
1252
1253                // question: check if player has moved more than a minimum distance?
1254
1255                if (0 ||
1256                        (Distance(oldPos, camera->GetPosition()) > 1e-6f) ||
[3219]1257                        (DotProd(oldDir, camera->GetDirection()) < 1.0f - 1e-6f))
1258                {
1259                        walkThroughRecorder->WriteFrame(camera);
1260                }
1261        }
1262
[3059]1263        // hack: store current rendering method and restore later
[2955]1264        int oldRenderMethod = renderMethod;
[3044]1265        // for rendering the light view, we use forward rendering
[3068]1266        if (renderLightView) renderMethod = FORWARD;
[2931]1267
[3059]1268        /// enable vbo vertex array
[2953]1269        glEnableClientState(GL_VERTEX_ARRAY);
[2931]1270
[3287]1271        if (usePvs) LoadOrUpdatePVSs(camera->GetPosition());
[3256]1272
[3246]1273
[2931]1274        // render with the specified method (forward rendering, forward + depth, deferred)
[2955]1275        switch (renderMethod)
[2825]1276        {
[3043]1277        case RENDER_FORWARD:
[2825]1278       
[2851]1279                glEnable(GL_MULTISAMPLE_ARB);
[3101]1280                renderState.SetRenderTechnique(FORWARD);
[3223]1281               
[2829]1282                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[2953]1283                glEnableClientState(GL_NORMAL_ARRAY);
[2825]1284                break;
1285
[2955]1286        case RENDER_DEPTH_PASS_DEFERRED:
[2948]1287
[2950]1288                glDisable(GL_MULTISAMPLE_ARB);
[3101]1289                renderState.SetUseAlphaToCoverage(false);
1290                renderState.SetRenderTechnique(DEPTH_PASS);
[2949]1291
[3175]1292                if (!fbo) InitFBO();
1293                fbo->Bind();
[3223]1294                // render to single depth texture
[2948]1295                glDrawBuffers(1, mrt);
[3223]1296                // clear buffer once
[2951]1297                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[2948]1298
[3068]1299                // the scene is rendered withouth any shading
[3101]1300                // (should be handled by render renderState)
[2948]1301                glShadeModel(GL_FLAT);
1302                break;
1303
[2955]1304        case RENDER_DEPTH_PASS:
[2851]1305
1306                glEnable(GL_MULTISAMPLE_ARB);
[3101]1307                renderState.SetRenderTechnique(DEPTH_PASS);
[2857]1308
[3067]1309                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1310
[3068]1311                // the scene is rendered withouth any shading
[3101]1312                // (should be handled by render renderState)
[2943]1313                glShadeModel(GL_FLAT);
[2825]1314                break;
1315       
[3048]1316        case RENDER_DEFERRED:
[2851]1317
[2948]1318                if (showShadowMap && !renderLightView)
[3295]1319                {
[2951]1320                        RenderShadowMap(camera->GetFar());
[3295]1321                }
[2951]1322
[2948]1323                //glPushAttrib(GL_VIEWPORT_BIT);
[2825]1324                glViewport(0, 0, texWidth, texHeight);
1325
[2948]1326                InitDeferredRendering();
[2951]1327               
[2953]1328                glEnableClientState(GL_NORMAL_ARRAY);
[2954]1329                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
[2825]1330                break;
1331        }
1332
[2801]1333        glDepthFunc(GL_LESS);
1334        glDisable(GL_TEXTURE_2D);
1335        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
[2825]1336               
[2801]1337
[3059]1338        // set proper lod levels for current frame using current eye point
[2847]1339        LODLevel::InitFrame(camera->GetPosition());
[3059]1340        // set up sunlight
[2954]1341        SetupLighting();
[2795]1342
[2801]1343
[2931]1344        if (renderLightView)
1345        {
[3101]1346                // change CHC++ set of renderState variables:
[3059]1347                // must be done for each change of camera because otherwise
1348                // the temporal coherency is broken
[3054]1349                BvhNode::SetCurrentState(LIGHT_PASS);
[3005]1350                shadowMap->RenderShadowView(shadowTraverser, viewProjMat);
[3054]1351                BvhNode::SetCurrentState(CAMERA_PASS);
[2931]1352        }
1353        else
[3079]1354        {
[3284]1355                //if (traverser->GetType() == RenderTraverser::CULL_COLLECTOR)
1356                //      ((PvsCollectionRenderer *)traverser)->SetViewCell(usePvs ? viewCell : NULL);
[3258]1357
[2931]1358                // actually render the scene geometry using the specified algorithm
[3245]1359                traverser->RenderScene();
[2948]1360        }
[2892]1361
[2931]1362
[2825]1363        /////////
[2809]1364        //-- do the rest of the rendering
[2893]1365       
[3244]1366        // return from depth pass and render visible objects
[2955]1367        if ((renderMethod == RENDER_DEPTH_PASS) ||
1368                (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
[2801]1369        {
1370                RenderVisibleObjects();
1371        }
1372
[3215]1373        const bool useDeferred =
1374                ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED));
[3214]1375
[3215]1376        // if no lense flare => just set sun to invisible
[3221]1377        const int sunVisiblePixels = useLenseFlare  &&  useDeferred ? TestSunVisible() : 0;
[3214]1378
[3246]1379       
[3215]1380
[2796]1381        ///////////////
1382        //-- render sky
[2795]1383
[2894]1384        // q: should we render sky after deferred shading?
1385        // this would conveniently solves some issues (e.g, skys without shadows)
[2893]1386
[3051]1387        RenderSky();
[2801]1388
[2961]1389
[3221]1390        //////////////////////////////
1391
[3215]1392        if (useDeferred)
[2825]1393        {
[2881]1394                FrameBufferObject::Release();
[2810]1395
[3247]1396                if (!deferredShader)
1397                {
1398                        deferredShader =
1399                                new DeferredRenderer(texWidth, texHeight, camera, ssaoUseFullResolution);
1400
1401                        deferredShader->SetKernelRadius(ssaoKernelRadius);
1402                        deferredShader->SetSampleIntensity(ssaoSampleIntensity);
1403                }
1404
[2903]1405                DeferredRenderer::SHADING_METHOD shadingMethod;
1406
1407                if (useAdvancedShading)
1408                {
1409                        if (useGlobIllum)
1410                                shadingMethod = DeferredRenderer::GI;
1411                        else
1412                                shadingMethod = DeferredRenderer::SSAO;
1413                }
1414                else
[3216]1415                {
[2903]1416                        shadingMethod = DeferredRenderer::DEFAULT;
[3216]1417                }
[2903]1418
[3225]1419                static int snapShotIdx = 0;
1420
[3215]1421                deferredShader->SetSunVisiblePixels(sunVisiblePixels);
[3111]1422                deferredShader->SetShadingMethod(shadingMethod);
1423                deferredShader->SetSamplingMethod(samplingMethod);
[3247]1424               
[3111]1425                deferredShader->SetUseTemporalCoherence(useTemporalCoherence);
[3242]1426                //deferredShader->SetSortSamples(sortSamples);
1427                deferredShader->SetTemporalCoherenceFactorForSsao(ssaoTempCohFactor);
1428                deferredShader->SetUseToneMapping(useHDR);
1429                deferredShader->SetUseAntiAliasing(useAntiAliasing);
[3316]1430                deferredShader->SetMaxConvergence(maxConvergence);
[2903]1431
[3242]1432
[3225]1433                if (recordFrames && replayPath)
[3269]1434                {
1435                        // record all frames of the walkthrough
[3225]1436                        deferredShader->SetSaveFrame(recordedFramesSuffix, currentReplayFrame);
[3269]1437                }
[3225]1438                else if (makeSnapShot)
[3269]1439                {
1440                        // make snap shot
1441                        deferredShader->SetSaveFrame("snap", snapShotIdx ++);
1442                }
[3225]1443                else
[3269]1444                {
1445                        // do nothing
[3225]1446                        deferredShader->SetSaveFrame("", -1);           
[3269]1447                }
[3276]1448               
1449                if (makeSnapShot) makeSnapShot = false;
[3225]1450
[2895]1451                ShadowMap *sm = showShadowMap ? shadowMap : NULL;
[3242]1452                deferredShader->Render(fbo, light, sm);
[2825]1453        }
[2827]1454
[2893]1455
[3101]1456        renderState.SetRenderTechnique(FORWARD);
1457        renderState.Reset();
[2827]1458
[2893]1459        glDisableClientState(GL_VERTEX_ARRAY);
1460        glDisableClientState(GL_NORMAL_ARRAY);
[2931]1461       
[2955]1462        renderMethod = oldRenderMethod;
[2893]1463
1464
1465        ///////////
1466
1467
[2826]1468        if (showAlgorithmTime)
1469        {
1470                glFinish();
[2827]1471
[2826]1472                algTime = algTimer.Elapsedms();
[2827]1473                perfGraph->AddData(algTime);
[2828]1474
[2827]1475                perfGraph->Draw();
[2826]1476        }
[2827]1477        else
1478        {
1479                if (visMode) DisplayVisualization();
1480        }
[2825]1481
[2884]1482        glFlush();
[2847]1483
1484        const bool restart = true;
1485        elapsedTime = frameTimer.Elapsedms(restart);
1486
[3223]1487        // statistics
[2764]1488        DisplayStats();
[2767]1489
[2642]1490        glutSwapBuffers();
[3219]1491
1492        oldPos = camera->GetPosition();
1493        oldDir = camera->GetDirection();
[2642]1494}
1495
1496
[3219]1497#pragma warning(disable : 4100)
[2792]1498void KeyBoard(unsigned char c, int x, int y)
[2642]1499{
1500        switch(c)
1501        {
1502        case 27:
[3212]1503                // write out current position on exit
[3134]1504                Debug << "camPosition=" << camera->GetPosition().x << " " << camera->GetPosition().y << " " << camera->GetPosition().z << endl;
1505                Debug << "camDirection=" << camera->GetDirection().x << " " << camera->GetDirection().y << " " << camera->GetDirection().z << endl;
[3285]1506                Debug << "lightDirection=" << light->GetDirection().x << " " << light->GetDirection().y << " " << light->GetDirection().z << endl;
[3134]1507
[2792]1508                CleanUp();
[2642]1509                exit(0);
[2948]1510        case 32: // space
[2800]1511                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
[3258]1512                //renderMode = (renderMode + 1) % 4;
[2897]1513
1514                DEL_PTR(traverser);
1515                traverser = CreateTraverser(camera);
1516
[2931]1517                if (shadowTraverser)
[2897]1518                {
[2948]1519                        // shadow traverser has to be recomputed
[2897]1520                        DEL_PTR(shadowTraverser);
[2948]1521                        shadowTraverser = CreateTraverser(shadowMap->GetShadowCamera());
[2897]1522                }
1523
[2642]1524                break;
1525        case '+':
[2867]1526                if (maxBatchSize < 10)
1527                        maxBatchSize = 10;
1528                else
1529                        maxBatchSize += 10;
1530
[2776]1531                traverser->SetMaxBatchSize(maxBatchSize);
[2642]1532                break;
1533        case '-':
[2776]1534                maxBatchSize -= 10;
1535                if (maxBatchSize < 0) maxBatchSize = 1;
1536                traverser->SetMaxBatchSize(maxBatchSize);               
[2642]1537                break;
[2837]1538        case 'M':
1539        case 'm':
1540                useMultiQueries = !useMultiQueries;
1541                traverser->SetUseMultiQueries(useMultiQueries);
1542                break;
1543        case '1':
1544                descendKeyPressed = true;
1545                break;
1546        case '2':
1547                ascendKeyPressed = true;
1548                break;
1549        case '3':
[3212]1550                if (trianglesPerVirtualLeaf >= 100) trianglesPerVirtualLeaf -= 100;
[2837]1551                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1552                break;
1553        case '4':
1554                trianglesPerVirtualLeaf += 100;
1555                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1556                break;
1557        case '5':
[2776]1558                assumedVisibleFrames -= 1;
1559                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1560                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1561                break;
[2837]1562        case '6':
[2776]1563                assumedVisibleFrames += 1;
1564                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1565                break;
[2837]1566        case '7':
[3227]1567                ssaoTempCohFactor *= 1.0f / 1.2f;
[3216]1568                cout << "new temporal coherence factor: " << ssaoTempCohFactor << endl;
[2776]1569                break;
[2767]1570        case '8':
[3227]1571                ssaoTempCohFactor *= 1.2f;
[3216]1572                cout << "new temporal coherence factor: " << ssaoTempCohFactor << endl;
[2837]1573                break;
[3212]1574        case '9':
1575                ssaoKernelRadius *= 0.8f;
[3216]1576                cout << "new ssao kernel radius: " << ssaoKernelRadius << endl;
[3247]1577                if (deferredShader) deferredShader->SetKernelRadius(ssaoKernelRadius);
[3212]1578                break;
1579        case '0':
[3227]1580                ssaoKernelRadius *= 1.0f / 0.8f;
[3247]1581                if (deferredShader) deferredShader->SetKernelRadius(ssaoKernelRadius);
[3216]1582                cout << "new ssao kernel radius: " << ssaoKernelRadius << endl;
[3212]1583                break;
1584        case 'n':
1585                ssaoSampleIntensity *= 0.9f;
[3247]1586                if (deferredShader) deferredShader->SetSampleIntensity(ssaoSampleIntensity);
[3216]1587                cout << "new ssao sample intensity: " << ssaoSampleIntensity << endl;
[3212]1588                break;
1589        case 'N':
[3227]1590                ssaoSampleIntensity *= 1.0f / 0.9f;
[3247]1591                if (deferredShader) deferredShader->SetSampleIntensity(ssaoSampleIntensity);
[3216]1592                cout << "new ssao sample intensity: " << ssaoSampleIntensity << endl;
[3212]1593                break;
[3219]1594        /*      case 'o':
1595        case 'O':
1596                useOptimization = !useOptimization;
1597                // chc optimization of using the objects instead of
1598                // the bounding boxes for querying previously visible nodes
1599                traverser->SetUseOptimization(useOptimization);
1600                break;*/
[3316]1601        case 'o':
1602        case 'O':
1603                if (maxConvergence > 100.0f)
1604                        maxConvergence = 1.0f;
1605                else
1606                        maxConvergence = 5000.0f;
1607
1608                cout << "max convergence: " << maxConvergence << endl;
1609
1610                break;
[3175]1611        case 'l':
1612        case 'L':
[2865]1613                useLODs = !useLODs;
1614                SceneEntity::SetUseLODs(useLODs);
[3216]1615                cout << "using LODs: " << useLODs << endl;
[2865]1616                break;
[2887]1617        case 'P':
1618        case 'p':
[2930]1619                samplingMethod = DeferredRenderer::SAMPLING_METHOD((samplingMethod + 1) % 3);
1620                cout << "ssao sampling method: " << samplingMethod << endl;
[2887]1621                break;
[2895]1622        case 'Y':
1623        case 'y':
1624                showShadowMap = !showShadowMap;
1625                break;
[2875]1626        case 'g':
[2903]1627        case 'G':
1628                useGlobIllum = !useGlobIllum;
1629                break;
[2875]1630        case 't':
1631        case 'T':
1632                useTemporalCoherence = !useTemporalCoherence;
1633                break;
[2767]1634        case 'a':
1635        case 'A':
[2931]1636                leftKeyPressed = true;
[2767]1637                break;
1638        case 'd':
1639        case 'D':
[2931]1640                rightKeyPressed = true;
[2767]1641                break;
1642        case 'w':
1643        case 'W':
[2931]1644                upKeyPressed = true;
[2767]1645                break;
[2829]1646        case 's':
1647        case 'S':
[2931]1648                downKeyPressed = true;
[2767]1649                break;
[3105]1650        case 'j':
1651        case 'J':
1652                leftStrafeKeyPressed = true;
1653                break;
1654        case 'k':
1655        case 'K':
1656                rightStrafeKeyPressed = true;
1657                break;
[2767]1658        case 'r':
1659        case 'R':
[2931]1660                useRenderQueue = !useRenderQueue;
1661                traverser->SetUseRenderQueue(useRenderQueue);
[2790]1662                break;
[2786]1663        case 'b':
1664        case 'B':
[2931]1665                useTightBounds = !useTightBounds;
[3294]1666                traverser->SetUseTightBounds((renderMode == RenderTraverser::CHCPLUSPLUS) && useTightBounds);
[2790]1667                break;
[3175]1668        case 'v':
1669        case 'V':
[2931]1670                renderLightView = !renderLightView;
1671                break;
[2994]1672        case 'h':
1673        case 'H':
1674                useHDR = !useHDR;
1675                break;
[3175]1676        case 'i':
1677        case 'I':
1678                useAntiAliasing = !useAntiAliasing;
1679                break;
[3215]1680        case 'c':
1681        case 'C':
1682                useLenseFlare = !useLenseFlare;
[3189]1683                break;
[3219]1684        case 'u':
1685        case 'U':
[3220]1686                // move light source instead of camera tilt
[3219]1687                moveLight = !moveLight;
1688                break;
[3225]1689        case '#':
1690                // make a snapshot of the current frame
1691                makeSnapShot = true;
1692                break;
[3246]1693        case '.':
1694                // enable / disable view cells
1695                usePvs = !usePvs;
[3259]1696                if (!usePvs) SceneEntity::SetCurrentVisibleId(-1);
[3246]1697                break;
[3273]1698        case ',':
1699                // show / hide FPS
1700                showFPS = !showFPS;
1701                break;
1702       
[2642]1703        default:
1704                return;
1705        }
1706
1707        glutPostRedisplay();
1708}
1709
1710
[2792]1711void SpecialKeyUp(int c, int x, int y)
[2642]1712{
[2792]1713        switch (c)
1714        {
1715        case GLUT_KEY_LEFT:
1716                leftKeyPressed = false;
1717                break;
1718        case GLUT_KEY_RIGHT:
1719                rightKeyPressed = false;
1720                break;
1721        case GLUT_KEY_UP:
1722                upKeyPressed = false;
1723                break;
1724        case GLUT_KEY_DOWN:
1725                downKeyPressed = false;
1726                break;
[2953]1727        case GLUT_ACTIVE_ALT:
1728                altKeyPressed = false;
1729                break;
[2792]1730        default:
1731                return;
1732        }
1733}
1734
1735
1736void KeyUp(unsigned char c, int x, int y)
1737{
1738        switch (c)
1739        {
[2879]1740
[2792]1741        case 'A':
1742        case 'a':
1743                leftKeyPressed = false;
1744                break;
1745        case 'D':
1746        case 'd':
1747                rightKeyPressed = false;
1748                break;
1749        case 'W':
1750        case 'w':
1751                upKeyPressed = false;
1752                break;
[2829]1753        case 'S':
1754        case 's':
[2792]1755                downKeyPressed = false;
1756                break;
[2837]1757        case '1':
1758                descendKeyPressed = false;
[2794]1759                break;
[2837]1760        case '2':
1761                ascendKeyPressed = false;
[2794]1762                break;
[3105]1763        case 'j':
1764        case 'J':
1765                leftStrafeKeyPressed = false;
1766                break;
1767        case 'k':
1768        case 'K':
1769                rightStrafeKeyPressed = false;
1770                break;
[2792]1771        default:
1772                return;
1773        }
1774        //glutPostRedisplay();
1775}
1776
1777
1778void Special(int c, int x, int y)
1779{
[2642]1780        switch(c)
1781        {
1782        case GLUT_KEY_F1:
1783                showHelp = !showHelp;
1784                break;
[2790]1785        case GLUT_KEY_F2:
[2795]1786                visMode = !visMode;
[2790]1787                break;
1788        case GLUT_KEY_F3:
1789                showBoundingVolumes = !showBoundingVolumes;
1790                traverser->SetShowBounds(showBoundingVolumes);
1791                break;
1792        case GLUT_KEY_F4:
[2827]1793                showOptions = !showOptions;
[2790]1794                break;
1795        case GLUT_KEY_F5:
[2827]1796                showStatistics = !showStatistics;
[2790]1797                break;
[2800]1798        case GLUT_KEY_F6:
1799                flyMode = !flyMode;
1800                break;
[2801]1801        case GLUT_KEY_F7:
[2825]1802
[2955]1803                renderMethod = (renderMethod + 1) % 4;
1804
1805                traverser->SetUseDepthPass(
1806                        (renderMethod == RENDER_DEPTH_PASS) ||
1807                        (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
1808                        );
[2801]1809                break;
[2803]1810        case GLUT_KEY_F8:
[2903]1811                useAdvancedShading = !useAdvancedShading;
[2821]1812                break;
[2826]1813        case GLUT_KEY_F9:
1814                showAlgorithmTime = !showAlgorithmTime;
1815                break;
[2954]1816        case GLUT_KEY_F10:
[3219]1817                replayPath = !replayPath;
1818
1819                if (replayPath)
1820                {
1821                        cout << "replaying path" << endl;
1822                        currentReplayFrame = -1;
[3285]1823
1824                        // hack: load pvs on replay (remove later!)
[3287]1825                        //usePvs = true;
[3219]1826                }
1827                else
1828                {
1829                        cout << "finished replaying path" << endl;
1830                }
[2954]1831                break;
[3219]1832        case GLUT_KEY_F11:
1833                recordPath = !recordPath;
1834               
1835                if (recordPath)
1836                {
1837                        cout << "recording path" << endl;
1838                }
1839                else
1840                {
1841                        cout << "finished recording path" << endl;
1842                        // start over with new frame recording next time
1843                        DEL_PTR(walkThroughRecorder);
1844                }
1845                break;
1846        case GLUT_KEY_F12:
1847                recordFrames = !recordFrames;
1848
1849                if (recordFrames)
1850                        cout << "recording frames on replaying" << endl;
1851                else
[3286]1852                        cout << "not recording frames on replaying" << endl;
[3219]1853                break;
[2642]1854        case GLUT_KEY_LEFT:
[2767]1855                {
[2792]1856                        leftKeyPressed = true;
[2795]1857                        camera->Pitch(KeyRotationAngle());
[2767]1858                }
[2642]1859                break;
1860        case GLUT_KEY_RIGHT:
[2767]1861                {
[2792]1862                        rightKeyPressed = true;
[2795]1863                        camera->Pitch(-KeyRotationAngle());
[2767]1864                }
[2642]1865                break;
1866        case GLUT_KEY_UP:
[2767]1867                {
[2792]1868                        upKeyPressed = true;
[2795]1869                        KeyHorizontalMotion(KeyShift());
[2767]1870                }
[2642]1871                break;
1872        case GLUT_KEY_DOWN:
[2767]1873                {
[2792]1874                        downKeyPressed = true;
[2795]1875                        KeyHorizontalMotion(-KeyShift());
[2767]1876                }
[2642]1877                break;
1878        default:
1879                return;
1880
1881        }
1882
1883        glutPostRedisplay();
1884}
[2767]1885
[2642]1886#pragma warning( default : 4100 )
1887
1888
[2792]1889void Reshape(int w, int h)
[2642]1890{
[2759]1891        winAspectRatio = 1.0f;
[2642]1892
1893        glViewport(0, 0, w, h);
1894       
1895        winWidth = w;
1896        winHeight = h;
1897
[2833]1898        if (w) winAspectRatio = (float) w / (float) h;
[2642]1899
[2758]1900        glMatrixMode(GL_PROJECTION);
1901        glLoadIdentity();
[2642]1902
[2927]1903        gluPerspective(fov, winAspectRatio, nearDist, farDist);
[2788]1904
[2758]1905        glMatrixMode(GL_MODELVIEW);
1906
[2642]1907        glutPostRedisplay();
1908}
1909
1910
[3101]1911void Mouse(int button, int renderState, int x, int y)
[2642]1912{
[3101]1913        if ((button == GLUT_LEFT_BUTTON) && (renderState == GLUT_DOWN))
[2642]1914        {
1915                xEyeBegin = x;
1916                yMotionBegin = y;
1917
[2792]1918                glutMotionFunc(LeftMotion);
[2642]1919        }
[3101]1920        else if ((button == GLUT_RIGHT_BUTTON) && (renderState == GLUT_DOWN))
[2642]1921        {
[2829]1922                xEyeBegin = x;
[2758]1923                yEyeBegin = y;
1924                yMotionBegin = y;
1925
[2954]1926                if (!moveLight)
1927                        glutMotionFunc(RightMotion);
1928                else
1929                        glutMotionFunc(RightMotionLight);
[2758]1930        }
[3101]1931        else if ((button == GLUT_MIDDLE_BUTTON) && (renderState == GLUT_DOWN))
[2758]1932        {
[2642]1933                horizontalMotionBegin = x;
1934                verticalMotionBegin = y;
[2792]1935                glutMotionFunc(MiddleMotion);
[2642]1936        }
1937
1938        glutPostRedisplay();
1939}
1940
[2758]1941
1942/**     rotation for left/right mouse drag
[2642]1943        motion for up/down mouse drag
1944*/
[2792]1945void LeftMotion(int x, int y)
[2642]1946{
[2758]1947        Vector3 viewDir = camera->GetDirection();
1948        Vector3 pos = camera->GetPosition();
1949
1950        // don't move in the vertical direction
[2764]1951        Vector3 horView(viewDir[0], viewDir[1], 0);
[2642]1952       
[2795]1953        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
[2756]1954
[2795]1955        camera->Pitch(eyeXAngle);
[2787]1956
[3246]1957        pos += horView * (yMotionBegin - y) * mouseMotion;
[2795]1958       
[2758]1959        camera->SetPosition(pos);
[2642]1960       
1961        xEyeBegin = x;
1962        yMotionBegin = y;
[2758]1963
[2642]1964        glutPostRedisplay();
1965}
1966
[2758]1967
[2954]1968void RightMotionLight(int x, int y)
1969{
1970        float theta = 0.2f * M_PI * (xEyeBegin - x) / 180.0f;
1971        float phi = 0.2f * M_PI * (yMotionBegin - y) / 180.0f;
1972       
1973        Vector3 lightDir = light->GetDirection();
1974
1975        Matrix4x4 roty = RotationYMatrix(theta);
1976        Matrix4x4 rotx = RotationXMatrix(phi);
1977
1978        lightDir = roty * lightDir;
1979        lightDir = rotx * lightDir;
1980
[2967]1981        // normalize to avoid accumulating errors
1982        lightDir.Normalize();
1983
[2954]1984        light->SetDirection(lightDir);
1985
1986        xEyeBegin = x;
1987        yMotionBegin = y;
1988
1989        glutPostRedisplay();
1990}
1991
1992
[2767]1993/**     rotation for left / right mouse drag
1994        motion for up / down mouse drag
[2758]1995*/
[2792]1996void RightMotion(int x, int y)
[2758]1997{
[2829]1998        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
[2795]1999        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
[2758]2000
[2795]2001        camera->Yaw(eyeYAngle);
[2829]2002        camera->Pitch(eyeXAngle);
[2780]2003
[2829]2004        xEyeBegin = x;
[2758]2005        yEyeBegin = y;
[2829]2006
[2758]2007        glutPostRedisplay();
2008}
2009
2010
[3105]2011/** strafe
2012*/
[2792]2013void MiddleMotion(int x, int y)
[2642]2014{
[2758]2015        Vector3 viewDir = camera->GetDirection();
2016        Vector3 pos = camera->GetPosition();
2017
[2642]2018        // the 90 degree rotated view vector
2019        // y zero so we don't move in the vertical
[2764]2020        Vector3 rVec(viewDir[0], viewDir[1], 0);
[2642]2021       
[2764]2022        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
[2758]2023        rVec = rot * rVec;
[2642]2024       
[3246]2025        pos -= rVec * (x - horizontalMotionBegin) * mouseMotion;
2026        pos[2] += (verticalMotionBegin - y) * mouseMotion;
[2642]2027
[2758]2028        camera->SetPosition(pos);
2029
[2642]2030        horizontalMotionBegin = x;
2031        verticalMotionBegin = y;
[2758]2032
[2642]2033        glutPostRedisplay();
2034}
2035
2036
[2756]2037void InitExtensions(void)
[2642]2038{
2039        GLenum err = glewInit();
[2756]2040
[2642]2041        if (GLEW_OK != err)
2042        {
2043                // problem: glewInit failed, something is seriously wrong
2044                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
2045                exit(1);
2046        }
[2756]2047        if  (!GLEW_ARB_occlusion_query)
[2642]2048        {
[2756]2049                printf("I require the GL_ARB_occlusion_query to work.\n");
[2642]2050                exit(1);
2051        }
2052}
2053
2054
[2826]2055void Begin2D()
[2642]2056{
2057        glDisable(GL_LIGHTING);
2058        glDisable(GL_DEPTH_TEST);
2059
[2826]2060        glMatrixMode(GL_PROJECTION);
[2642]2061        glPushMatrix();
2062        glLoadIdentity();
[2834]2063
[2826]2064        gluOrtho2D(0, winWidth, 0, winHeight);
[2642]2065
[2826]2066        glMatrixMode(GL_MODELVIEW);
[2642]2067        glPushMatrix();
2068        glLoadIdentity();
2069}
2070
2071
[2826]2072void End2D()
[2642]2073{
[2834]2074        glMatrixMode(GL_PROJECTION);
[2642]2075        glPopMatrix();
[2834]2076
[2642]2077        glMatrixMode(GL_MODELVIEW);
2078        glPopMatrix();
2079
2080        glEnable(GL_LIGHTING);
2081        glEnable(GL_DEPTH_TEST);
2082}
2083
2084
[2787]2085// displays the visualisation of culling algorithm
2086void DisplayVisualization()
[2796]2087{
[3246]2088        // render current view cell
2089        if (usePvs) RenderViewCell();
2090       
2091        visualization->SetViewCell(usePvs ? viewCell : NULL);
[2787]2092        visualization->SetFrameId(traverser->GetCurrentFrameId());
[3246]2093       
[3245]2094
[2792]2095        Begin2D();
[2642]2096        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2097        glEnable(GL_BLEND);
[2827]2098        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
[2642]2099
[2827]2100        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
[2642]2101        glDisable(GL_BLEND);
[2792]2102        End2D();
[2788]2103       
2104       
2105        AxisAlignedBox3 box = bvh->GetBox();
2106
[2948]2107        const float offs = box.Size().x * 0.3f;
[2834]2108       
[2838]2109        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
[2806]2110       
[2795]2111        visCamera->SetPosition(vizpos);
[2838]2112        visCamera->ResetPitchAndYaw();
[2892]2113       
[2834]2114        glPushAttrib(GL_VIEWPORT_BIT);
[2806]2115        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
[2796]2116
2117        glMatrixMode(GL_PROJECTION);
[2834]2118        glPushMatrix();
2119
[2787]2120        glLoadIdentity();
[2807]2121        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
[2787]2122
[2796]2123        glMatrixMode(GL_MODELVIEW);
[2834]2124        glPushMatrix();
[2787]2125
[2796]2126        visCamera->SetupCameraView();
[2806]2127
2128        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
2129        glMultMatrixf((float *)rotZ.x);
2130
[2887]2131        // inverse translation in order to fix current position
[2838]2132        Vector3 pos = camera->GetPosition();
[2806]2133        glTranslatef(-pos.x, -pos.y, -pos.z);
2134
2135
[2788]2136        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
2137        glLightfv(GL_LIGHT0, GL_POSITION, position);
[2787]2138
[2788]2139        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
2140        glLightfv(GL_LIGHT1, GL_POSITION, position1);
[2787]2141
[2642]2142        glClear(GL_DEPTH_BUFFER_BIT);
2143
[2888]2144
[2767]2145        ////////////
[2787]2146        //-- visualization of the occlusion culling
2147
[3063]2148        visualization->Render(showShadowMap);
[2887]2149
[2767]2150       
[2834]2151        // reset previous settings
2152        glPopAttrib();
2153
2154        glMatrixMode(GL_PROJECTION);
2155        glPopMatrix();
2156        glMatrixMode(GL_MODELVIEW);
2157        glPopMatrix();
[2642]2158}
2159
[2767]2160
[2642]2161// cleanup routine after the main loop
[2756]2162void CleanUp()
[2642]2163{
[2756]2164        DEL_PTR(traverser);
[2796]2165        DEL_PTR(sceneQuery);
[2756]2166        DEL_PTR(bvh);
[2767]2167        DEL_PTR(visualization);
[2787]2168        DEL_PTR(camera);
[2801]2169        DEL_PTR(renderQueue);
[2827]2170        DEL_PTR(perfGraph);
[2879]2171        DEL_PTR(fbo);
[3111]2172        DEL_PTR(deferredShader);
[3019]2173        DEL_PTR(light);
2174        DEL_PTR(visCamera);
2175        DEL_PTR(preetham);
[3020]2176        DEL_PTR(shadowMap);
2177        DEL_PTR(shadowTraverser);
[3078]2178        DEL_PTR(motionPath);
[3219]2179        DEL_PTR(walkThroughRecorder);
2180        DEL_PTR(walkThroughPlayer);
[3223]2181        DEL_PTR(statsWriter);
[3244]2182        DEL_PTR(viewCellsTree);
[3052]2183
[3037]2184        ResourceManager::DelSingleton();
[3057]2185        ShaderManager::DelSingleton();
2186
[3059]2187        resourceManager = NULL;
[3057]2188        shaderManager = NULL;
[2642]2189}
2190
2191
2192// this function inserts a dezimal point after each 1000
[2829]2193void CalcDecimalPoint(string &str, int d, int len)
[2642]2194{
[2827]2195        static vector<int> numbers;
2196        numbers.clear();
2197
[2829]2198        static string shortStr;
2199        shortStr.clear();
[2642]2200
[2829]2201        static char hstr[100];
2202
[2642]2203        while (d != 0)
2204        {
2205                numbers.push_back(d % 1000);
2206                d /= 1000;
2207        }
2208
2209        // first element without leading zeros
2210        if (numbers.size() > 0)
2211        {
[2800]2212                sprintf(hstr, "%d", numbers.back());
[2829]2213                shortStr.append(hstr);
[2642]2214        }
2215       
[2764]2216        for (int i = (int)numbers.size() - 2; i >= 0; i--)
[2642]2217        {
[2800]2218                sprintf(hstr, ",%03d", numbers[i]);
[2829]2219                shortStr.append(hstr);
[2642]2220        }
[2829]2221
2222        int dif = len - (int)shortStr.size();
2223
2224        for (int i = 0; i < dif; ++ i)
2225        {
2226                str += " ";
2227        }
2228
2229        str.append(shortStr);
[2764]2230}
2231
2232
2233void DisplayStats()
2234{
[2826]2235        static char msg[9][300];
[2764]2236
[2826]2237        static double frameTime = elapsedTime;
2238        static double renderTime = algTime;
2239
[2818]2240        const float expFactor = 0.1f;
[2767]2241
[2802]2242        // if some strange render time spike happened in this frame => don't count
[2826]2243        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
2244       
2245        static float rTime = 1000.0f;
[2764]2246
[3285]2247        // the render time is used only for the traversal algorithm using glfinish
2248        if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
2249       
[2802]2250
[2826]2251        accumulatedTime += elapsedTime;
2252
[2776]2253        if (accumulatedTime > 500) // update every fraction of a second
[2770]2254        {       
2255                accumulatedTime = 0;
2256
[2826]2257                if (frameTime) fps = 1e3f / (float)frameTime;
2258                rTime = renderTime;
[2773]2259
[2948]2260                if (renderLightView && shadowTraverser)
2261                {
2262                        renderedTriangles = shadowTraverser->GetStats().mNumRenderedTriangles;
2263                        renderedObjects = shadowTraverser->GetStats().mNumRenderedGeometry;
2264                        renderedNodes = shadowTraverser->GetStats().mNumRenderedNodes;
2265                }
2266                else if (showShadowMap && shadowTraverser)
2267                {
2268                        renderedNodes = traverser->GetStats().mNumRenderedNodes + shadowTraverser->GetStats().mNumRenderedNodes;
2269                        renderedObjects = traverser->GetStats().mNumRenderedGeometry + shadowTraverser->GetStats().mNumRenderedGeometry;
2270                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles + shadowTraverser->GetStats().mNumRenderedTriangles;
2271                }
2272                else
2273                {
2274                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
2275                        renderedObjects = traverser->GetStats().mNumRenderedGeometry;
2276                        renderedNodes = traverser->GetStats().mNumRenderedNodes;
2277                }
2278
[2770]2279                traversedNodes = traverser->GetStats().mNumTraversedNodes;
2280                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
2281                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
2282                issuedQueries = traverser->GetStats().mNumIssuedQueries;
2283                stateChanges = traverser->GetStats().mNumStateChanges;
[2800]2284                numBatches = traverser->GetStats().mNumBatches;
[2770]2285        }
2286
[2764]2287
[3223]2288        ////////////////
2289        //-- record stats on walkthrough
2290
2291        static float accTime = .0f;
2292        static float averageTime = .0f;
2293
2294        if (currentReplayFrame > -1)
2295        {
2296                accTime += frameTime;
2297                averageTime = accTime / (currentReplayFrame + 1);
2298
2299                if (!statsWriter)
[3279]2300                        statsWriter = new StatsWriter(statsFilename + ".log");
[3223]2301                       
2302                FrameStats frameStats;
2303                frameStats.mFrame = currentReplayFrame;
2304                frameStats.mFPS = 1e3f / (float)frameTime;
2305                frameStats.mTime = frameTime;
2306                frameStats.mNodes = renderedNodes;
2307                frameStats.mObjects = renderedObjects;
2308                frameStats.mTriangles = renderedTriangles;
2309
2310                statsWriter->WriteFrameStats(frameStats);
2311        }
2312        else if (statsWriter)
2313        {
2314                Debug << "average frame time " << averageTime << " for traversal algorithm " << renderMode << endl;
2315
2316                // reset average frame time
[3224]2317                averageTime = accTime = .0f;
[3223]2318
2319                DEL_PTR(statsWriter);
2320        }
2321
2322
[2826]2323        Begin2D();
[2808]2324
[2826]2325        glEnable(GL_BLEND);
2326        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
[2764]2327
[2826]2328        if (showHelp)
2329        {       
2330                DrawHelpMessage();
2331        }
2332        else
2333        {
[2829]2334                if (showOptions)
2335                {
2336                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
2337                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
2338                }
2339
2340                if (showStatistics)
2341                {
2342                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
2343                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
2344                }
2345
2346                glEnable(GL_TEXTURE_2D);
[2827]2347                myfont.Begin();
[2769]2348
[2826]2349                if (showOptions)
2350                {
[2829]2351                        glColor3f(0.0f, 1.0f, 0.0f);
[2826]2352                        int i = 0;
2353
[3065]2354                        static char *renderMethodStr[] =
2355                                {"forward", "depth pass + forward", "deferred shading", "depth pass + deferred"};
[2826]2356                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
[3294]2357                                        useMultiQueries, (renderMode == RenderTraverser::CHCPLUSPLUS) && useTightBounds, useRenderQueue);
[3246]2358                        sprintf(msg[i ++], "render technique: %s, use pvss: %d", renderMethodStr[renderMethod], usePvs);
[2826]2359                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
2360                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
2361                                assumedVisibleFrames, maxBatchSize);
[2808]2362
[2826]2363                        for (int j = 0; j < 4; ++ j)
[2829]2364                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
[2826]2365                }
[2808]2366
[2786]2367                if (showStatistics)
[2764]2368                {
[2829]2369                        glColor3f(1.0f, 1.0f, 0.0f);
2370
[2948]2371                        string objStr, totalObjStr;
2372                        string triStr, totalTriStr;
[2826]2373
[2829]2374                        int len = 10;
[2948]2375                        CalcDecimalPoint(objStr, renderedObjects, len);
[3059]2376                        CalcDecimalPoint(totalObjStr, (int)resourceManager->GetNumEntities(), len);
[2826]2377
[2948]2378                        CalcDecimalPoint(triStr, renderedTriangles, len);
2379                        CalcDecimalPoint(totalTriStr, bvh->GetBvhStats().mTriangles, len);
2380
[2826]2381                        int i = 4;
2382
[3276]2383                        if (0) // q: show rendered objects or nodes (no space for both)
[2953]2384                        {
2385                                sprintf(msg[i ++], "rendered: %s of %s objects, %s of %s triangles",
2386                                        objStr.c_str(), totalObjStr.c_str(), triStr.c_str(), totalTriStr.c_str());
2387                        }
2388                        else
2389                        {
2390                                sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
2391                                        renderedNodes, bvh->GetNumVirtualNodes(), triStr.c_str(), totalTriStr.c_str());
2392                        }
[2826]2393
[3276]2394                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d nodes",
[2826]2395                                traversedNodes, frustumCulledNodes, queryCulledNodes);
[3251]2396                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
[2826]2397                                issuedQueries, stateChanges, numBatches);
2398
2399                        for (int j = 4; j < 7; ++ j)
[2829]2400                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
[2764]2401                }
[2790]2402
[3286]2403                glColor3f(0.0f, 1.0f, 0.0f);
2404
[3258]2405                static char *alg_str[] = {
2406                        "Frustum Cull"
2407                        , "Stop and Wait"
2408                        , "CHC"
2409                        , "CHC ++"
[3285]2410            //, "Collector"
[3258]2411                };
[3284]2412       
[2827]2413                if (!showAlgorithmTime)
[3273]2414                {
2415                        if (showFPS)
[3276]2416                        {                       
2417                                sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);           
[3292]2418                                myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 10.0f);
[3288]2419
2420                                //int mrays = (int)shotRays / 1000000;
2421                                //sprintf(msg[7], "%s:  %04d M rays", alg_str[renderMode], mrays);     
[3292]2422                                //myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 60.0f);           
[3276]2423                        }
[3273]2424                }
[2827]2425                else
[3276]2426                {
[2827]2427                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
[3292]2428                        myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 10.0f);
[3276]2429                }
[3286]2430
2431                glColor3f(1.0f, 1.0f, 1.0f);
[2764]2432        }
2433
[3286]2434        glColor3f(1, 1, 1);
[2826]2435        glDisable(GL_BLEND);
2436        glDisable(GL_TEXTURE_2D);
2437
[2792]2438        End2D();
[2764]2439}       
[2796]2440
2441
2442void RenderSky()
2443{
[2959]2444        if ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
[3101]2445                renderState.SetRenderTechnique(DEFERRED);
[2958]2446
[3036]2447        const bool useToneMapping =
2448                ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) ||
2449                 (renderMethod == RENDER_DEFERRED)) && useHDR;
[3059]2450       
[3279]2451        preetham->RenderSkyDome(-light->GetDirection(), camera, &renderState, !useToneMapping, skyDomeScaleFactor);
[3212]2452
2453        /// once again reset the renderState just to make sure
[3101]2454        renderState.Reset();
[2801]2455}
[2796]2456
[2948]2457
[2895]2458// render visible object from depth pass
[2801]2459void RenderVisibleObjects()
2460{
[2955]2461        if (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
[2948]2462        {
[2950]2463                if (showShadowMap && !renderLightView)
[2951]2464                {
[3068]2465                        // usethe maximal visible distance to focus shadow map
[3235]2466                        const float newFar = min(camera->GetFar(), traverser->GetMaxVisibleDistance());
2467                        RenderShadowMap(newFar);
[2951]2468                }
[3284]2469
[3068]2470                // initialize deferred rendering
[2948]2471                InitDeferredRendering();
2472        }
[2949]2473        else
[2950]2474        {
[3101]2475                renderState.SetRenderTechnique(FORWARD);
[2950]2476        }
[2948]2477
[3127]2478
[3068]2479        /////////////////
[3101]2480        //-- reset gl renderState before the final visible objects pass
[3068]2481
[3101]2482        renderState.Reset();
[3068]2483
[2953]2484        glEnableClientState(GL_NORMAL_ARRAY);
[3068]2485        /// switch back to smooth shading
[3067]2486        glShadeModel(GL_SMOOTH);
[3068]2487        /// reset alpha to coverage flag
[3101]2488        renderState.SetUseAlphaToCoverage(true);
[3067]2489        // clear color
2490        glClear(GL_COLOR_BUFFER_BIT);
[3039]2491       
[3068]2492        // draw only objects having exactly the same depth as the current sample
2493        glDepthFunc(GL_EQUAL);
[2951]2494
[2949]2495        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2496
[3068]2497        SceneEntityContainer::const_iterator sit,
[2801]2498                sit_end = traverser->GetVisibleObjects().end();
2499
2500        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
[2948]2501        {
[2801]2502                renderQueue->Enqueue(*sit);
[2948]2503        }
[3258]2504
[3068]2505        /// now render out everything in one giant pass
[2801]2506        renderQueue->Apply();
2507
[3068]2508        // switch back to standard depth func
[2801]2509        glDepthFunc(GL_LESS);
[3101]2510        renderState.Reset();
[2949]2511
[3276]2512        PrintGLerror("visible objects");
[2801]2513}
2514
2515
[3120]2516SceneQuery *GetOrCreateSceneQuery()
[2801]2517{
[3037]2518        if (!sceneQuery)
[3258]2519        {
[3101]2520                sceneQuery = new SceneQuery(bvh->GetBox(), traverser, &renderState);
[3258]2521        }
[3037]2522
[3120]2523        return sceneQuery;
2524}
2525
2526
2527void PlaceViewer(const Vector3 &oldPos)
2528{
[2801]2529        Vector3 playerPos = camera->GetPosition();
[3120]2530        bool validIntersect = GetOrCreateSceneQuery()->CalcIntersection(playerPos);
[2801]2531
[2853]2532        if (validIntersect)
[3276]2533                //&& ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
[2801]2534        {
2535                camera->SetPosition(playerPos);
2536        }
[2809]2537}
[2948]2538
2539
[2951]2540void RenderShadowMap(float newfar)
[2948]2541{
[2953]2542        glDisableClientState(GL_NORMAL_ARRAY);
[3101]2543        renderState.SetRenderTechnique(DEPTH_PASS);
[3038]2544       
2545        // hack: disable cull face because of alpha textured balconies
2546        glDisable(GL_CULL_FACE);
[3101]2547        renderState.LockCullFaceEnabled(true);
[3068]2548
2549        /// don't use alpha to coverage for the depth map (problems with fbo rendering)
[3101]2550        renderState.SetUseAlphaToCoverage(false);
[2948]2551
[3287]2552        const Vector3 lightPos = light->GetDirection() * -1e3f;
2553        if (usePvs) LoadOrUpdatePVSs(lightPos);
2554
2555
[3101]2556        // change CHC++ set of renderState variables
[2980]2557        // this must be done for each change of camera because
[2948]2558        // otherwise the temporal coherency is broken
[3054]2559        BvhNode::SetCurrentState(LIGHT_PASS);
[2948]2560        // hack: temporarily change camera far plane
[2951]2561        camera->SetFar(newfar);
[2948]2562        // the scene is rendered withouth any shading   
[3005]2563        shadowMap->ComputeShadowMap(shadowTraverser, viewProjMat);
[2948]2564
2565        camera->SetFar(farDist);
2566
[3101]2567        renderState.SetUseAlphaToCoverage(true);
2568        renderState.LockCullFaceEnabled(false);
[3102]2569        glEnable(GL_CULL_FACE);
[2948]2570
[2953]2571        glEnableClientState(GL_NORMAL_ARRAY);
[3101]2572        // change back renderState
[3054]2573        BvhNode::SetCurrentState(CAMERA_PASS);
[2952]2574}
[3059]2575
[3068]2576
[3110]2577/** Touch each material once in order to preload the render queue
[3059]2578        bucket id of each material
2579*/
2580void PrepareRenderQueue()
2581{
2582        for (int i = 0; i < 3; ++ i)
2583        {
[3101]2584                renderState.SetRenderTechnique(i);
[3059]2585
2586                // fill all shapes into the render queue        once so we can establish the buckets
2587                ShapeContainer::const_iterator sit, sit_end = (*resourceManager->GetShapes()).end();
2588
2589                for (sit = (*resourceManager->GetShapes()).begin(); sit != sit_end; ++ sit)
2590                {
[3071]2591                        static Transform3 dummy(IdentityMatrix());
[3110]2592                        renderQueue->Enqueue(*sit, NULL);
[3059]2593                }
2594       
2595                // just clear queue again
2596                renderQueue->Clear();
2597        }
2598}
2599
2600
[3237]2601int LoadModel(const string &model, SceneEntityContainer &entities)
[3059]2602{
2603        const string filename = string(model_path + model);
[3237]2604        int numEntities = 0;
2605
[3127]2606        cout << "\nloading model " << filename << endl;
[3237]2607
2608        if (numEntities = resourceManager->Load(filename, entities))
[3225]2609        {
[3127]2610                cout << "model " << filename << " successfully loaded" << endl;
[3225]2611        }
[3059]2612        else
2613        {
2614                cerr << "loading model " << filename << " failed" << endl;
[3225]2615
[3059]2616                CleanUp();
2617                exit(0);
2618        }
[3237]2619
2620        return numEntities;
[3078]2621}
2622
2623
[3316]2624void CreateAnimation(const Vector3 &pos)
[3078]2625{
[3316]2626        //const float b = 5.0f; const float a = 1.5f;
2627        const float a = 5.0f; const float b = 1.5f;
[3078]2628
2629        VertexArray vertices;
2630
[3316]2631        for (int i = 0; i < 360; ++ i)
[3078]2632        {
[3316]2633                const float angle = (float)i * M_PI / 180.0f;
[3078]2634
[3316]2635                Vector3 offs = Vector3(cos(angle) * a, sin(angle) * b, 0);
2636                vertices.push_back(pos + offs);
2637        }
[3080]2638
[3316]2639        /*for (int i = 0; i < 5; ++ i)
[3080]2640        {
2641                Vector3 offs = Vector3(i, 0, 0);
2642                vertices.push_back(center + offs);
[3078]2643        }
[3080]2644       
2645        for (int i = 0; i < 5; ++ i)
2646        {
[3316]2647                Vector3 offs = Vector3(4 - i, 0, 0);
[3080]2648                vertices.push_back(center + offs);
[3316]2649        }*/
[3080]2650
[3078]2651        motionPath = new MotionPath(vertices);
[3214]2652}
2653
[3316]2654
[3215]2655/** This function returns the number of visible pixels of a
2656        bounding box representing the sun.
2657*/
2658int TestSunVisible()
[3214]2659{
2660        // assume sun is at a far away point along the light vector
2661        Vector3 sunPos = light->GetDirection() * -1e3f;
2662        sunPos += camera->GetPosition();
2663
2664        sunBox->GetTransform()->SetMatrix(TranslationMatrix(sunPos));
2665
2666        glBeginQueryARB(GL_SAMPLES_PASSED_ARB, sunQuery);
2667
2668        sunBox->Render(&renderState);
2669
2670        glEndQueryARB(GL_SAMPLES_PASSED_ARB);
2671
2672        GLuint sampleCount;
2673
2674        glGetQueryObjectuivARB(sunQuery, GL_QUERY_RESULT_ARB, &sampleCount);
2675
[3215]2676        return sampleCount;
[3214]2677}
[3244]2678
2679
[3245]2680static Technique GetVizTechnique()
2681{
2682        Technique tech;
2683        tech.Init();
2684
2685        tech.SetEmmisive(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2686        tech.SetDiffuse(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2687        tech.SetAmbient(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2688
2689        return tech;
2690}
2691
2692
[3287]2693void UpdatePvs(const Vector3 &pos)
[3244]2694{
[3245]2695        viewCell = viewCellsTree->GetViewCell(camera->GetPosition());
[3244]2696
[3286]2697        const float elapsedAlgorithmTime = applicationTimer.Elapsedms(false);
[3245]2698
[3286]2699        // assume 60 FPS, total time is in secs
2700        const float raysPerMs = 2.0f * pvsTotalSamples / (pvsTotalTime * 1000.0f);
2701        //shotRays = visibilitySolutionInitialState + elapsedAlgorithmTime * raysPerMs;
2702        //shotRays += 1000 * raysPerMs / 60.0f;
[3285]2703
[3286]2704        //cout << "totalt: " << pvsTotalTime << endl;
2705        //cout << "rays per ms: " << raysPerMs << endl;
[3284]2706
[3259]2707        SceneEntity::SetCurrentVisibleId(globalVisibleId);
[3251]2708
[3259]2709        for (int i = 0; i < viewCell->mPvs.GetSize(); ++ i)
[3244]2710        {
[3284]2711                PvsEntry entry = viewCell->mPvs.GetEntry(i);
[3285]2712#ifdef USE_TIMESTAMPS
[3286]2713                if (!((entry.mTimeStamp < 0.0f) || (entry.mTimeStamp <= shotRays)))
2714                        continue;
[3285]2715#endif
[3286]2716                entry.mEntity->SetVisibleId(globalVisibleId);
2717                //numTriangles += entry.mEntity->CountNumTriangles();
[3244]2718        }
[3245]2719
[3251]2720        ++ globalVisibleId;
[3246]2721}
[3245]2722
[3246]2723
2724void LoadVisibilitySolution()
2725{
2726        ///////////
2727        //-- load the visibility solution
2728
2729        const string vis_filename =
2730                string(model_path + visibilitySolution + ".vis");
2731
2732        VisibilitySolutionLoader visLoader;
2733
[3285]2734        viewCellsTree = visLoader.Load(vis_filename,
2735                                           bvh,
2736                                                                   pvsTotalSamples,
2737                                                                   pvsTotalTime,
2738                                                                   viewCellsScaleFactor);
[3247]2739
2740        if (!viewCellsTree)
2741        {
2742                cerr << "loading pvs failed" << endl;
2743                CleanUp();
2744                exit(0);
2745        }
[3246]2746}
2747
2748
2749void RenderViewCell()
2750{
[3245]2751        // render current view cell
2752        static Technique vcTechnique = GetVizTechnique();
2753
2754        vcTechnique.Render(&renderState);
2755        Visualization::RenderBoxForViz(viewCell->GetBox());
[3276]2756}
2757
2758
[3279]2759void LoadPompeiiFloor()
[3276]2760{
[3284]2761        AxisAlignedBox3 pompeiiBox =
2762                SceneEntity::ComputeBoundingBox(staticObjects);
[3276]2763
2764        // todo: dispose texture
2765        Texture *floorTex = new Texture(model_path + "stairs.c.01.tif");
2766
2767        floorTex->SetBoundaryModeS(Texture::REPEAT);
2768        floorTex->SetBoundaryModeT(Texture::REPEAT);
2769
2770        floorTex->Create();
2771        Material *mymat = resourceManager->CreateMaterial();
2772
2773        Technique *tech = mymat->GetDefaultTechnique();
2774        tech->SetDiffuse(RgbaColor(1, 1, 1, 1));
2775        tech->SetTexture(floorTex);
2776
2777        Technique *depthPass = new Technique(*tech);
2778        Technique *deferred = new Technique(*tech);
2779
2780        depthPass->SetColorWriteEnabled(false);
2781        depthPass->SetLightingEnabled(false);
2782
[3284]2783        ShaderProgram *defaultFragmentTexProgramMrt =
2784                ShaderManager::GetSingleton()->GetShaderProgram("defaultFragmentTexMrt");
2785        ShaderProgram *defaultVertexProgramMrt =
2786                ShaderManager::GetSingleton()->GetShaderProgram("defaultVertexMrt");
[3276]2787
2788        deferred->SetFragmentProgram(defaultFragmentTexProgramMrt);
2789        deferred->SetVertexProgram(defaultVertexProgramMrt);
2790
2791        deferred->GetFragmentProgramParameters()->SetViewMatrixParam(0);
2792        deferred->GetVertexProgramParameters()->SetModelMatrixParam(1);
2793        deferred->GetVertexProgramParameters()->SetOldModelMatrixParam(2);
2794
2795        deferred->SetTexture(floorTex);
2796       
2797        mymat->AddTechnique(deferred);
2798        mymat->AddTechnique(depthPass);
2799
2800
2801        //const Vector3 offs(1300.0f, -2500.0f, .0f);
2802        const Vector3 offs(pompeiiBox.Center(0), pompeiiBox.Center(1), 0);
2803        Matrix4x4 moffs = TranslationMatrix(offs);
2804
2805        Plane3 plane;
2806        Transform3 *mytrafo = resourceManager->CreateTransform(moffs);
2807
2808        SceneEntity *myplane =
2809                SceneEntityConverter().ConvertPlane(plane,
2810                                                    pompeiiBox.Size(0),
2811                                                                                        pompeiiBox.Size(1),
2812                                                                                        5,
2813                                                                                        5,
2814                                                                                        mymat,
2815                                                                                        mytrafo);
2816
2817        resourceManager->AddSceneEntity(myplane);
2818        staticObjects.push_back(myplane);
[3287]2819}
2820
2821
2822void LoadOrUpdatePVSs(const Vector3 &pos)
2823{
2824        if (!viewCellsTree)     
2825        {
2826                LoadVisibilitySolution();
2827                applicationTimer.Start();
2828                shotRays = visibilitySolutionInitialState;
2829        }
2830
2831        if (viewCellsTree) UpdatePvs(pos);
[3316]2832}
2833
2834
2835void CreateNewInstance(SceneEntity *parent, const Vector3 &pos)
2836{
2837        SceneEntity *ent = new SceneEntity(*parent);
2838        resourceManager->AddSceneEntity(ent);
2839
2840        Matrix4x4 transl = TranslationMatrix(pos);
2841        Transform3 *transform = resourceManager->CreateTransform(transl);
2842
2843        ent->SetTransform(transform);
2844        dynamicObjects.push_back(ent);
2845        //Debug << "positions: " << newPos << endl;
[3246]2846}
Note: See TracBrowser for help on using the repository browser.