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

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