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

Revision 3266, 65.2 KB checked in by mattausch, 15 years ago (diff)
Line 
1// chcdemo.cpp : Defines the entry point for the console application.
2//
3
4
5#include "common.h"
6
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
17#include <math.h>
18#include <time.h>
19#include "glInterface.h"
20
21
22#include "RenderTraverser.h"
23#include "SceneEntity.h"
24#include "Vector3.h"
25#include "Matrix4x4.h"
26#include "ResourceManager.h"
27#include "Bvh.h"
28#include "Camera.h"
29#include "Geometry.h"
30#include "BvhLoader.h"
31#include "FrustumCullingTraverser.h"
32#include "StopAndWaitTraverser.h"
33#include "CHCTraverser.h"
34#include "CHCPlusPlusTraverser.h"
35#include "Visualization.h"
36#include "RenderState.h"
37#include "Timer/PerfTimer.h"
38#include "SceneQuery.h"
39#include "RenderQueue.h"
40#include "Material.h"
41#include "glfont2.h"
42#include "PerformanceGraph.h"
43#include "Environment.h"
44#include "Halton.h"
45#include "Transform3.h"
46#include "SampleGenerator.h"
47#include "FrameBufferObject.h"
48#include "DeferredRenderer.h"
49#include "ShadowMapping.h"
50#include "Light.h"
51#include "SceneEntityConverter.h"
52#include "SkyPreetham.h"
53#include "Texture.h"
54#include "ShaderManager.h"
55#include "MotionPath.h"
56#include "ShaderProgram.h"
57#include "Shape.h"
58#include "WalkThroughRecorder.h"
59#include "StatsWriter.h"
60#include "VisibilitySolutionLoader.h"
61#include "ViewCellsTree.h"
62#include "PvsCollectionRenderer.h"
63#include "ObjExporter.h"
64#include "BvhExporter.h"
65
66
67using namespace std;
68using namespace CHCDemoEngine;
69
70
71/// the environment for the program parameter
72static Environment env;
73
74
75GLuint fontTex;
76/// the fbo used for MRT
77FrameBufferObject *fbo = NULL;
78/// the renderable scene geometry
79SceneEntityContainer sceneEntities;
80/// the dynamic objects in the scene
81SceneEntityContainer dynamicObjects;
82// traverses and renders the hierarchy
83RenderTraverser *traverser = NULL;
84/// the hierarchy
85Bvh *bvh = NULL;
86/// handles scene loading
87ResourceManager *resourceManager = NULL;
88/// handles scene loading
89ShaderManager *shaderManager = NULL;
90/// the scene camera
91PerspectiveCamera *camera = NULL;
92/// the scene camera
93PerspectiveCamera *visCamera = NULL;
94/// the visualization
95Visualization *visualization = NULL;
96/// the current render renderState
97RenderState renderState;
98/// the rendering algorithm
99int renderMode = RenderTraverser::CHCPLUSPLUS;
100/// eye near plane distance
101const float nearDist = 0.2f;
102//const float nearDist = 1.0f;
103/// eye far plane distance
104float farDist = 1e6f;
105/// the field of view
106const float fov = 50.0f;
107
108SceneQuery *sceneQuery = NULL;
109RenderQueue *renderQueue = NULL;
110/// traverses and renders the hierarchy
111RenderTraverser *shadowTraverser = NULL;
112/// the skylight + skydome model
113SkyPreetham *preetham = NULL;
114
115MotionPath *motionPath = NULL;
116/// max depth where candidates for tighter bounds are searched
117int maxDepthForTestingChildren = 3;
118/// use full resolution for ssao or half
119bool ssaoUseFullResolution = false;
120
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;
127/// frame number for replay
128int currentReplayFrame = -1;
129
130string recordedFramesSuffix("frames");
131string statsFilename("stats");
132
133string filename("city");
134string visibilitySolution("");
135
136
137/// the walkThroughRecorder
138WalkThroughRecorder *walkThroughRecorder = NULL;
139WalkThroughPlayer *walkThroughPlayer = NULL;
140StatsWriter *statsWriter = NULL;
141
142bool makeSnapShot = false;
143
144ViewCellsTree *viewCellsTree = NULL;
145ViewCell *viewCell = NULL;
146
147bool useSkylightForIllum = true;
148
149static int globalVisibleId = 0;
150
151
152
153/// the technique used for rendering
154enum RenderTechnique
155{
156        FORWARD,
157        DEFERRED,
158        DEPTH_PASS
159};
160
161
162/// the used render type for this render pass
163enum RenderMethod
164{
165        RENDER_FORWARD,
166        RENDER_DEPTH_PASS,
167        RENDER_DEFERRED,
168        RENDER_DEPTH_PASS_DEFERRED,
169        RENDER_NUM_RENDER_TYPES
170};
171
172/// one of four possible render methods
173int renderMethod = RENDER_FORWARD;
174
175static int winWidth = 1024;
176static int winHeight = 768;
177static float winAspectRatio = 1.0f;
178
179/// these values get scaled with the frame rate
180static float keyForwardMotion = 30.0f;
181static float keyRotation = 1.5f;
182
183/// elapsed time in milliseconds
184double elapsedTime = 1000.0;
185double algTime = 1000.0;
186double accumulatedTime = 1000.0;
187float fps = 1e3f;
188float turbitity = 5.0f;
189
190// ssao parameters
191float ssaoKernelRadius = 1e-8f;
192float ssaoSampleIntensity = 0.2f;
193float ssaoFilterRadius = 12.0f;
194float ssaoTempCohFactor = 255.0;
195bool sortSamples = true;
196
197int shadowSize = 2048;
198
199/// the hud font
200glfont::GLFont myfont;
201
202// rendertexture
203int texWidth = 1024;
204int texHeight = 768;
205
206int renderedObjects = 0;
207int renderedNodes = 0;
208int renderedTriangles = 0;
209
210int issuedQueries = 0;
211int traversedNodes = 0;
212int frustumCulledNodes = 0;
213int queryCulledNodes = 0;
214int stateChanges = 0;
215int numBatches = 0;
216
217// mouse navigation renderState
218int xEyeBegin = 0;
219int yEyeBegin = 0;
220int yMotionBegin = 0;
221int verticalMotionBegin = 0;
222int horizontalMotionBegin = 0;
223
224bool leftKeyPressed = false;
225bool rightKeyPressed = false;
226bool upKeyPressed = false;
227bool downKeyPressed = false;
228bool descendKeyPressed = false;
229bool ascendKeyPressed = false;
230bool leftStrafeKeyPressed = false;
231bool rightStrafeKeyPressed = false;
232
233bool altKeyPressed = false;
234
235bool showHelp = false;
236bool showStatistics = false;
237bool showOptions = true;
238bool showBoundingVolumes = false;
239bool visMode = false;
240
241bool useOptimization = false;
242bool useTightBounds = true;
243bool useRenderQueue = true;
244bool useMultiQueries = true;
245bool flyMode = true;
246
247bool useGlobIllum = false;
248bool useTemporalCoherence = true;
249bool showAlgorithmTime = false;
250
251bool useFullScreen = false;
252bool useLODs = true;
253bool moveLight = false;
254
255bool useAdvancedShading = false;
256bool showShadowMap = false;
257bool renderLightView = false;
258bool useHDR = true;
259bool useAntiAliasing = true;
260bool useLenseFlare = true;
261
262bool usePvs = false;
263
264
265PerfTimer frameTimer, algTimer;
266/// the performance graph window
267PerformanceGraph *perfGraph = NULL;
268
269int sCurrentMrtSet = 0;
270static Matrix4x4 invTrafo = IdentityMatrix();
271float mouseMotion = 0.2f;
272
273float viewCellsScaleFactor = 1.0f;
274
275
276//////////////
277//-- chc++ algorithm parameters
278
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
286
287//////////////
288
289enum {CAMERA_PASS = 0, LIGHT_PASS = 1};
290
291
292//DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_POISSON;
293DeferredRenderer::SAMPLING_METHOD samplingMethod = DeferredRenderer::SAMPLING_QUADRATIC;
294
295ShadowMap *shadowMap = NULL;
296DirectionalLight *light = NULL;
297DeferredRenderer *deferredShader = NULL;
298
299
300SceneEntity *buddha = NULL;
301SceneEntity *skyDome = NULL;
302SceneEntity *sunBox = NULL;
303
304GLuint sunQuery = 0;
305
306
307////////////////////
308//--- function forward declarations
309
310void InitExtensions();
311void InitGLstate();
312
313void DisplayVisualization();
314/// destroys all allocated resources
315void CleanUp();
316void SetupEyeView();
317void SetupLighting();
318void DisplayStats();
319/// draw the help screen
320void DrawHelpMessage();
321/// render the sky dome
322void RenderSky();
323/// render the objects found visible in the depth pass
324void RenderVisibleObjects();
325
326int TestSunVisible();
327
328void Begin2D();
329void End2D();
330/// the main loop
331void MainLoop();
332
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);
338void Mouse(int button, int renderState, int x, int y);
339void LeftMotion(int x, int y);
340void RightMotion(int x, int y);
341void MiddleMotion(int x, int y);
342void KeyHorizontalMotion(float shift);
343void KeyVerticalMotion(float shift);
344/// returns the string representation of a number with the decimal points
345void CalcDecimalPoint(string &str, int d);
346/// Creates the traversal method (vfc, stopandwait, chc, chc++)
347RenderTraverser *CreateTraverser(PerspectiveCamera *cam);
348/// place the viewer on the floor plane
349void PlaceViewer(const Vector3 &oldPos);
350// initialise the frame buffer objects
351void InitFBO();
352/// changes the sunlight direction
353void RightMotionLight(int x, int y);
354/// render the shader map
355void RenderShadowMap(float newfar);
356/// function that touches each material once in order to accelarate render queue
357void PrepareRenderQueue();
358/// loads the specified model
359int LoadModel(const string &model, SceneEntityContainer &entities);
360
361inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
362inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
363
364void CreateAnimation();
365
366SceneQuery *GetOrCreateSceneQuery();
367
368void LoadPvs();
369
370void LoadVisibilitySolution();
371
372void RenderViewCell();
373
374
375// new view projection matrix of the camera
376static Matrix4x4 viewProjMat = IdentityMatrix();
377// the old view projection matrix of the camera
378static Matrix4x4 oldViewProjMat = IdentityMatrix();
379
380
381
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
395int main(int argc, char* argv[])
396{
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
408
409
410        int returnCode = 0;
411
412        Vector3 camPos(.0f, .0f, .0f);
413        Vector3 camDir(.0f, 1.0f, .0f);
414        Vector3 lightDir(-0.8f, 1.0f, -0.7f);
415
416        cout << "=== reading environment file ===" << endl << endl;
417
418        const string envFileName = "default.env";
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);
428                env.GetIntParam(string("winWidth"), winWidth);
429                env.GetIntParam(string("winHeight"), winHeight);
430                env.GetIntParam(string("shadowSize"), shadowSize);
431                env.GetIntParam(string("maxDepthForTestingChildren"), maxDepthForTestingChildren);
432
433                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
434                env.GetFloatParam(string("keyRotation"), keyRotation);
435                env.GetFloatParam(string("mouseMotion"), mouseMotion);
436                env.GetFloatParam(string("tempCohFactor"), ssaoTempCohFactor);
437                env.GetFloatParam(string("turbitity"), turbitity);
438               
439                env.GetVectorParam(string("camPosition"), camPos);
440                env.GetVectorParam(string("camDirection"), camDir);
441                env.GetVectorParam(string("lightDirection"), lightDir);
442
443                env.GetBoolParam(string("useFullScreen"), useFullScreen);
444                env.GetBoolParam(string("useLODs"), useLODs);
445                env.GetBoolParam(string("useHDR"), useHDR);
446                env.GetBoolParam(string("useAA"), useAntiAliasing);
447                env.GetBoolParam(string("useLenseFlare"), useLenseFlare);
448                env.GetBoolParam(string("useAdvancedShading"), useAdvancedShading);
449
450                env.GetIntParam(string("renderMethod"), renderMethod);
451
452                env.GetFloatParam(string("ssaoKernelRadius"), ssaoKernelRadius);
453                env.GetFloatParam(string("ssaoSampleIntensity"), ssaoSampleIntensity);
454                env.GetBoolParam(string("ssaoUseFullResolution"), ssaoUseFullResolution);
455
456                env.GetStringParam(string("recordedFramesSuffix"), recordedFramesSuffix);
457                env.GetStringParam(string("statsFilename"), statsFilename);
458                env.GetStringParam(string("filename"), filename);
459                env.GetStringParam(string("visibilitySolution"), visibilitySolution);
460
461                env.GetBoolParam(string("usePvs"), usePvs);
462                env.GetBoolParam(string("useSkylightForIllum"), useSkylightForIllum);
463                env.GetFloatParam(string("viewCellsScaleFactor"), viewCellsScaleFactor);
464
465                //env.GetStringParam(string("modelPath"), model_path);
466                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
467
468                texWidth = winWidth;
469                texHeight = winHeight;
470
471                cout << "assumed visible frames: " << assumedVisibleFrames << endl;
472                cout << "max batch size: " << maxBatchSize << endl;
473                cout << "triangles per virtual leaf: " << trianglesPerVirtualLeaf << endl;
474
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;
482                cout << "shadow size: " << shadowSize << endl;
483                cout << "render method: " << renderMethod << endl;
484                cout << "use antialiasing: " << useAntiAliasing << endl;
485                cout << "use lense flare: " << useLenseFlare << endl;
486                cout << "use advanced shading: " << useAdvancedShading << endl;
487                cout << "turbitity: " << turbitity << endl;
488                cout << "temporal coherence factor: " << ssaoTempCohFactor << endl;
489                cout << "sample intensity: " << ssaoSampleIntensity << endl;
490                cout << "kernel radius: " << ssaoKernelRadius << endl;
491                cout << "use ssao full resolution: " << ssaoUseFullResolution << endl;
492                cout << "recorded frames suffix: " << recordedFramesSuffix << endl;
493                cout << "stats filename: " << statsFilename << endl;
494                cout << "static scene filename prefix: " << filename << endl;
495                cout << "use PVSs: " << usePvs << endl;
496                cout << "visibility solution: " << visibilitySolution << endl;
497                cout << "view cells scale factor: " << viewCellsScaleFactor << endl;
498                cout << "use skylight for illumination: " << useSkylightForIllum << endl;
499
500                //cout << "model path: " << model_path << endl;
501                cout << "**** end parameters ****" << endl << endl;
502        }
503
504        ///////////////////////////
505
506        camera = new PerspectiveCamera(winWidth / winHeight, fov);
507        camera->SetNear(nearDist);
508        camera->SetFar(1000);
509
510        camera->SetDirection(camDir);
511        camera->SetPosition(camPos);
512
513        visCamera = new PerspectiveCamera(winWidth / winHeight, fov);
514        visCamera->SetNear(0.0f);
515        visCamera->Yaw(.5 * M_PI);
516
517        // create a new light
518        light = new DirectionalLight(lightDir, RgbaColor(1, 1, 1, 1), RgbaColor(1, 1, 1, 1));
519        // the render queue for material sorting
520        renderQueue = new RenderQueue(&renderState);
521
522        glutInitWindowSize(winWidth, winHeight);
523        glutInit(&argc, argv);
524        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
525        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
526        //glutInitDisplayString("samples=2");
527
528        SceneEntity::SetUseLODs(useLODs);
529
530
531        if (!useFullScreen)
532        {
533                glutCreateWindow("FriendlyCulling");
534        }
535        else
536        {
537                glutGameModeString( "1024x768:32@75" );
538                glutEnterGameMode();
539        }
540
541        glutDisplayFunc(MainLoop);
542        glutKeyboardFunc(KeyBoard);
543        glutSpecialFunc(Special);
544        glutReshapeFunc(Reshape);
545        glutMouseFunc(Mouse);
546        glutIdleFunc(MainLoop);
547        glutKeyboardUpFunc(KeyUp);
548        glutSpecialUpFunc(SpecialKeyUp);
549        glutIgnoreKeyRepeat(true);
550
551        // initialise gl graphics
552        InitExtensions();
553        InitGLstate();
554
555        glEnable(GL_MULTISAMPLE_ARB);
556        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
557
558        LeftMotion(0, 0);
559        MiddleMotion(0, 0);
560
561        perfGraph = new PerformanceGraph(1000);
562
563        resourceManager = ResourceManager::GetSingleton();
564        shaderManager = ShaderManager::GetSingleton();
565
566
567        ///////////
568        //-- load the static scene geometry
569
570        LoadModel(filename + ".dem", sceneEntities);
571
572
573        //////////
574        //-- load some dynamic stuff
575
576        //resourceManager->mUseNormalMapping = true;
577        //resourceManager->mUseNormalMapping = false;
578
579        resourceManager->mUseSpecialColors = true;
580
581        //LoadModel("fisch.dem", dynamicObjects);
582
583        //LoadModel("venusm.dem", dynamicObjects);
584        //LoadModel("camel.dem", dynamicObjects);
585        //LoadModel("toyplane2.dem", dynamicObjects);
586        //LoadModel("elephal.dem", dynamicObjects);
587        //LoadModel("sibenik.dem", dynamicObjects);
588
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
606#if 0
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       
611        LoadModel("hbuddha.dem", dynamicObjects);
612
613        buddha = dynamicObjects.back();
614        buddha->GetTransform()->SetMatrix(transl);
615
616        for (int i = 0; i < 10; ++ i)
617        {
618                SceneEntity *ent = new SceneEntity(*buddha);
619                resourceManager->AddSceneEntity(ent);
620
621                Vector3 offs = Vector3::ZERO();
622
623                offs.x = RandomValue(.0f, 50.0f);
624                offs.y = RandomValue(.0f, 50.0f);
625
626                Vector3 newPos = sceneCenter + offs;
627
628                transl = TranslationMatrix(newPos);
629                Transform3 *transform = resourceManager->CreateTransform(transl);
630
631                ent->SetTransform(transform);
632                dynamicObjects.push_back(ent);
633        }
634#endif
635
636       
637        resourceManager->mUseNormalMapping = false;
638        resourceManager->mUseSpecialColors = false;
639
640
641        ///////////
642        //-- load the associated static bvh
643
644        const string bvh_filename = string(model_path + filename + ".bvh");
645
646        BvhFactory bvhFactory;
647        //bvh = bvhFactory.Create(bvh_filename, sceneEntities, dynamicObjects, maxDepthForTestingChildren);
648        bvh = bvhFactory.Create(sceneEntities, dynamicObjects, maxDepthForTestingChildren);
649
650        if (!bvh)
651        {
652                cerr << "loading bvh " << bvh_filename << " failed" << endl;
653                CleanUp();
654                exit(0);
655        }
656
657        /// set the depth of the bvh depending on the triangles per leaf node
658        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
659
660        // set far plane based on scene extent
661        farDist = 10.0f * Magnitude(bvh->GetBox().Diagonal());
662        camera->SetFar(farDist);
663
664
665        //ObjExporter().Export(model_path + "mycity.obj", bvh);
666        //BvhExporter().Export(model_path + "mycity.bvh", bvh);
667
668
669
670        //////////////////
671        //-- setup the skydome model
672
673        LoadModel("sky.dem", sceneEntities);
674        skyDome = sceneEntities.back();
675
676        /// the turbitity of the sky (from clear to hazy, use <3 for clear sky)
677        preetham = new SkyPreetham(turbitity, skyDome);
678
679        CreateAnimation();
680
681
682        //////////////////////////
683        //-- a bounding box representing the sun pos in order to test visibility
684
685        Transform3 *trafo = resourceManager->CreateTransform(IdentityMatrix());
686
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
693
694        //////////////////
695        //-- occlusion query for sun
696
697        // todo: clean up material
698        Material *mat = resourceManager->CreateMaterial();
699
700        mat->GetTechnique(0)->SetDepthWriteEnabled(false);
701        mat->GetTechnique(0)->SetColorWriteEnabled(false);
702
703        sunBox = conv.ConvertBox(sbox, mat, trafo);
704        resourceManager->AddSceneEntity(sunBox);
705
706        /// create single occlusion query that handles sun visibility
707        glGenQueriesARB(1, &sunQuery);
708
709
710        //////////
711        //-- initialize the traversal algorithm
712
713        traverser = CreateTraverser(camera);
714       
715        // the bird-eye visualization
716        visualization = new Visualization(bvh, camera, NULL, &renderState);
717
718        // this function assign the render queue bucket ids of the materials in beforehand
719        // => probably less overhead for new parts of the scene that are not yet assigned
720        PrepareRenderQueue();
721        /// forward rendering is the default
722        renderState.SetRenderTechnique(FORWARD);
723        // frame time is restarted every frame
724        frameTimer.Start();
725
726        //Halton::TestHalton(7, 2);
727        //HaltonSequence::TestHalton(15, 2);
728        //Halton::TestPrime();
729
730        // the rendering loop
731        glutMainLoop();
732       
733        // clean up
734        CleanUp();
735       
736        return 0;
737}
738
739
740void InitFBO()
741{
742        PrintGLerror("fbo start");
743
744        // this fbo basicly stores the scene information we get from standard rendering of a frame
745        // we store diffuse colors, eye space depth and normals
746        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_32);
747
748        // the diffuse color buffer
749        fbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, ColorBufferObject::FILTER_NEAREST);
750        // the normals buffer
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);
753        // a rgb buffer which could hold material properties
754        //fbo->AddColorBuffer(ColorBufferObject::RGB_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST);
755        // buffer holding the difference vector to the old frame
756        fbo->AddColorBuffer(ColorBufferObject::RGB_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR);
757        // another color buffer
758        fbo->AddColorBuffer(ColorBufferObject::RGBA_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_LINEAR, ColorBufferObject::FILTER_NEAREST);
759
760        for (int i = 0; i < 4; ++ i)
761        {
762                FrameBufferObject::InitBuffer(fbo, i);
763        }
764
765        PrintGLerror("init fbo");
766}
767
768
769bool InitFont(void)
770{
771        glEnable(GL_TEXTURE_2D);
772
773        glGenTextures(1, &fontTex);
774        glBindTexture(GL_TEXTURE_2D, fontTex);
775
776        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
777                return false;
778
779        glDisable(GL_TEXTURE_2D);
780       
781        return true;
782}
783
784
785void InitGLstate()
786{
787        glClearColor(0.4f, 0.4f, 0.4f, 1e20f);
788       
789        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
790        glPixelStorei(GL_PACK_ALIGNMENT,1);
791       
792        glDepthFunc(GL_LESS);
793        glEnable(GL_DEPTH_TEST);
794
795        glColor3f(1.0f, 1.0f, 1.0f);
796        glShadeModel(GL_SMOOTH);
797       
798        glMaterialf(GL_FRONT, GL_SHININESS, 64);
799        glEnable(GL_NORMALIZE);
800               
801        glDisable(GL_ALPHA_TEST);
802        glAlphaFunc(GL_GEQUAL, 0.5f);
803
804        glFrontFace(GL_CCW);
805        glCullFace(GL_BACK);
806        glEnable(GL_CULL_FACE);
807
808        glDisable(GL_TEXTURE_2D);
809
810        GLfloat ambientColor[] = {0.2, 0.2, 0.2, 1.0};
811        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
812        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
813
814        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
815        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
816        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
817
818        glDepthFunc(GL_LESS);
819
820        if (!InitFont())
821                cerr << "font creation failed" << endl;
822        else
823                cout << "successfully created font" << endl;
824
825
826        //////////////////////////////
827
828        //GLfloat lmodel_ambient[] = {1.0f, 1.0f, 1.0f, 1.0f};
829        GLfloat lmodel_ambient[] = {0.7f, 0.7f, 0.8f, 1.0f};
830
831        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
832        //glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
833        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
834        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
835}
836
837
838void DrawHelpMessage()
839{
840        const char *message[] =
841        {
842                "Help information",
843                "",
844                "'F1'           - shows/dismisses this message",
845                "'F2'           - shows/hides bird eye view",
846                "'F3'           - shows/hides bounds (boxes or tight bounds)",
847                "'F4',          - shows/hides parameters",
848                "'F5'           - shows/hides statistics",
849                "'F6',          - toggles between fly/walkmode",
850                "'F7',          - cycles throw render modes",
851                "'F8',          - enables/disables ambient occlusion (only deferred)",
852                "'F9',          - shows pure algorithm render time (using glFinish)",
853                "'SPACE'        - cycles through occlusion culling algorithms",
854                "",
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",
860                "",
861                "'-'/'+'        - decreases/increases max batch size",
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",
865                "",
866                "'R'            - use render queue",
867                "'B'            - use tight bounds",
868                "'M'            - use multiqueries",
869                "'O'            - use CHC optimization (geometry queries for leaves)",
870                0,
871        };
872       
873       
874        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
875
876        glRecti(30, 30, winWidth - 30, winHeight - 30);
877
878        glEnd();
879
880        glColor3f(1.0f, 1.0f, 1.0f);
881       
882        glEnable(GL_TEXTURE_2D);
883        myfont.Begin();
884
885        int x = 40, y = 30;
886
887        for(int i = 0; message[i] != 0; ++ i)
888        {
889                if(message[i][0] == '\0')
890                {
891                        y += 15;
892                }
893                else
894                {
895                        myfont.DrawString(message[i], x, winHeight - y);
896                        y += 25;
897                }
898        }
899        glDisable(GL_TEXTURE_2D);
900}
901
902
903RenderTraverser *CreateTraverser(PerspectiveCamera *cam)
904{
905        RenderTraverser *tr;
906       
907        switch (renderMode)
908        {
909        case RenderTraverser::CULL_FRUSTUM:
910                tr = new FrustumCullingTraverser();
911                break;
912        case RenderTraverser::STOP_AND_WAIT:
913                tr = new StopAndWaitTraverser();
914                break;
915        case RenderTraverser::CHC:
916                tr = new CHCTraverser();
917                break;
918        case RenderTraverser::CHCPLUSPLUS:
919                tr = new CHCPlusPlusTraverser();
920                break;
921        case RenderTraverser::CULL_COLLECTOR:
922                tr = new PvsCollectionRenderer();
923                break;
924        default:
925                tr = new FrustumCullingTraverser();
926        }
927
928        tr->SetCamera(cam);
929        tr->SetHierarchy(bvh);
930        tr->SetRenderQueue(renderQueue);
931        tr->SetRenderState(&renderState);
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);
939        tr->SetUseDepthPass((renderMethod == RENDER_DEPTH_PASS) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED));
940        tr->SetRenderQueue(renderQueue);
941        tr->SetShowBounds(showBoundingVolumes);
942
943        bvh->ResetNodeClassifications();
944
945
946        return tr;
947}
948
949/** Setup sunlight
950*/
951void SetupLighting()
952{
953        glEnable(GL_LIGHT0);
954        glDisable(GL_LIGHT1);
955       
956        Vector3 lightDir = -light->GetDirection();
957
958
959        ///////////
960        //-- first light: sunlight
961
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};
965       
966
967        const bool useHDRValues =
968                ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) ||
969                 (renderMethod == RENDER_DEFERRED)) && useHDR;
970
971
972        Vector3 sunAmbient;
973        Vector3 sunDiffuse;
974
975        if (useSkylightForIllum)
976        {
977                preetham->ComputeSunColor(lightDir, sunAmbient, sunDiffuse, !useHDRValues);
978
979                ambient[0] = sunAmbient.x;
980                ambient[1] = sunAmbient.y;
981                ambient[2] = sunAmbient.z;
982
983                diffuse[0] = sunDiffuse.x;
984                diffuse[1] = sunDiffuse.y;
985                diffuse[2] = sunDiffuse.z;
986        }
987        else
988        {
989
990                ambient[0] = .2f;
991                ambient[1] = .2f;
992                ambient[2] = .2f;
993
994                diffuse[0] = 1.0f;
995                diffuse[1] = 1.0f;
996                diffuse[2] = 1.0f;
997        }
998
999        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
1000        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
1001        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
1002
1003        GLfloat position[] = {lightDir.x, lightDir.y, lightDir.z, 0.0f};
1004        glLightfv(GL_LIGHT0, GL_POSITION, position);
1005}
1006
1007
1008void SetupEyeView()
1009{
1010        // store matrix of last frame
1011        oldViewProjMat = viewProjMat;
1012
1013        camera->SetupViewProjection();
1014
1015
1016        /////////////////
1017        //-- compute view projection matrix and store for later use
1018
1019        Matrix4x4 matViewing, matProjection;
1020
1021        camera->GetModelViewMatrix(matViewing);
1022        camera->GetProjectionMatrix(matProjection);
1023
1024        viewProjMat = matViewing * matProjection;
1025}
1026
1027
1028void KeyHorizontalMotion(float shift)
1029{
1030        Vector3 hvec = -camera->GetDirection();
1031        hvec.z = 0;
1032
1033        Vector3 pos = camera->GetPosition();
1034        pos += hvec * shift;
1035       
1036        camera->SetPosition(pos);
1037}
1038
1039
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
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
1068/** Initialize the deferred rendering pass.
1069*/
1070void InitDeferredRendering()
1071{
1072        if (!fbo) InitFBO();
1073        fbo->Bind();
1074
1075        // multisampling does not work with deferred shading
1076        glDisable(GL_MULTISAMPLE_ARB);
1077        renderState.SetRenderTechnique(DEFERRED);
1078
1079
1080        // draw to 3 render targets
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        }
1091
1092        sCurrentMrtSet = 1 - sCurrentMrtSet;
1093}
1094
1095
1096/** the main rendering loop
1097*/
1098void MainLoop()
1099{       
1100        if (buddha)
1101        {
1102                Matrix4x4 oldTrafo = buddha->GetTransform()->GetMatrix();
1103                Vector3 buddhaPos = motionPath->GetCurrentPosition();
1104                Matrix4x4 trafo = TranslationMatrix(buddhaPos);
1105
1106                buddha->GetTransform()->SetMatrix(trafo);
1107
1108#if TODO // drop objects on ground floor
1109                for (int i = 0; i < 10; ++ i)
1110                {
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                        }
1119                }
1120#endif
1121
1122/*
1123                /////////////////////////
1124                //-- update animations
1125
1126                //const float rotAngle = M_PI * 1e-3f;
1127                const float rotAngle = 1.0f * M_PI / 180.0f;
1128
1129                Matrix4x4 rotMatrix = RotationZMatrix(rotAngle);
1130                dynamicObjects[2]->GetTransform()->MultMatrix(rotMatrix);
1131
1132                motionPath->Move(0.01f);
1133                */
1134        }
1135
1136
1137        /////////////
1138
1139        static Vector3 oldPos = camera->GetPosition();
1140        static Vector3 oldDir = camera->GetDirection();
1141
1142        if (leftKeyPressed)
1143                camera->Pitch(KeyRotationAngle());
1144        if (rightKeyPressed)
1145                camera->Pitch(-KeyRotationAngle());
1146        if (upKeyPressed)
1147                KeyHorizontalMotion(-KeyShift());
1148        if (downKeyPressed)
1149                KeyHorizontalMotion(KeyShift());
1150        if (ascendKeyPressed)
1151                KeyVerticalMotion(KeyShift());
1152        if (descendKeyPressed)
1153                KeyVerticalMotion(-KeyShift());
1154        if (leftStrafeKeyPressed)
1155                KeyStrafe(KeyShift());
1156        if (rightStrafeKeyPressed)
1157                KeyStrafe(-KeyShift());
1158
1159
1160        // place view on ground
1161        if (!flyMode) PlaceViewer(oldPos);
1162
1163        if (showAlgorithmTime)
1164        {
1165                glFinish();
1166                algTimer.Start();
1167        }
1168       
1169        // don't allow replay on record
1170        if (replayPath && !recordPath)
1171        {
1172                if (!walkThroughPlayer)
1173                        walkThroughPlayer = new WalkThroughPlayer("frames.log");
1174               
1175                ++ currentReplayFrame;
1176
1177                // reset if end of walkthrough is reached
1178                if (!walkThroughPlayer->ReadNextFrame(camera))
1179                {
1180                        currentReplayFrame = -1;
1181                        replayPath = false;
1182                }
1183        }
1184
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        }
1194       
1195        // bring eye modelview matrix up-to-date
1196        SetupEyeView();
1197       
1198        // set frame related parameters for GPU programs
1199        GPUProgramParameters::InitFrame(camera, light);
1200
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
1213        // hack: store current rendering method and restore later
1214        int oldRenderMethod = renderMethod;
1215        // for rendering the light view, we use forward rendering
1216        if (renderLightView) renderMethod = FORWARD;
1217
1218        /// enable vbo vertex array
1219        glEnableClientState(GL_VERTEX_ARRAY);
1220
1221        if (1 && usePvs)
1222        {
1223                if (!viewCellsTree)     LoadVisibilitySolution();
1224
1225                if (viewCellsTree) LoadPvs();
1226        }
1227
1228        // render with the specified method (forward rendering, forward + depth, deferred)
1229        switch (renderMethod)
1230        {
1231        case RENDER_FORWARD:
1232       
1233                glEnable(GL_MULTISAMPLE_ARB);
1234                renderState.SetRenderTechnique(FORWARD);
1235               
1236                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1237                glEnableClientState(GL_NORMAL_ARRAY);
1238                break;
1239
1240        case RENDER_DEPTH_PASS_DEFERRED:
1241
1242                glDisable(GL_MULTISAMPLE_ARB);
1243                renderState.SetUseAlphaToCoverage(false);
1244                renderState.SetRenderTechnique(DEPTH_PASS);
1245
1246                if (!fbo) InitFBO();
1247                fbo->Bind();
1248                // render to single depth texture
1249                glDrawBuffers(1, mrt);
1250                // clear buffer once
1251                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1252
1253                // the scene is rendered withouth any shading
1254                // (should be handled by render renderState)
1255                glShadeModel(GL_FLAT);
1256                break;
1257
1258        case RENDER_DEPTH_PASS:
1259
1260                glEnable(GL_MULTISAMPLE_ARB);
1261                renderState.SetRenderTechnique(DEPTH_PASS);
1262
1263                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1264
1265                // the scene is rendered withouth any shading
1266                // (should be handled by render renderState)
1267                glShadeModel(GL_FLAT);
1268                break;
1269       
1270        case RENDER_DEFERRED:
1271
1272                if (showShadowMap && !renderLightView)
1273                        RenderShadowMap(camera->GetFar());
1274
1275                //glPushAttrib(GL_VIEWPORT_BIT);
1276                glViewport(0, 0, texWidth, texHeight);
1277
1278                InitDeferredRendering();
1279               
1280                glEnableClientState(GL_NORMAL_ARRAY);
1281                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1282                break;
1283        }
1284
1285        glDepthFunc(GL_LESS);
1286        glDisable(GL_TEXTURE_2D);
1287        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1288               
1289
1290        // set proper lod levels for current frame using current eye point
1291        LODLevel::InitFrame(camera->GetPosition());
1292        // set up sunlight
1293        SetupLighting();
1294
1295
1296        if (renderLightView)
1297        {
1298                // change CHC++ set of renderState variables:
1299                // must be done for each change of camera because otherwise
1300                // the temporal coherency is broken
1301                BvhNode::SetCurrentState(LIGHT_PASS);
1302                shadowMap->RenderShadowView(shadowTraverser, viewProjMat);
1303                BvhNode::SetCurrentState(CAMERA_PASS);
1304        }
1305        else
1306        {
1307                if (traverser->GetType() == RenderTraverser::CULL_COLLECTOR)
1308                        ((PvsCollectionRenderer *)traverser)->SetViewCell(usePvs ? viewCell : NULL);
1309
1310                // actually render the scene geometry using the specified algorithm
1311                traverser->RenderScene();
1312        }
1313
1314
1315        /////////
1316        //-- do the rest of the rendering
1317       
1318        // return from depth pass and render visible objects
1319        if ((renderMethod == RENDER_DEPTH_PASS) ||
1320                (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
1321        {
1322                RenderVisibleObjects();
1323        }
1324
1325        const bool useDeferred =
1326                ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED));
1327
1328        // if no lense flare => just set sun to invisible
1329        const int sunVisiblePixels = useLenseFlare  &&  useDeferred ? TestSunVisible() : 0;
1330
1331       
1332
1333        ///////////////
1334        //-- render sky
1335
1336        // q: should we render sky after deferred shading?
1337        // this would conveniently solves some issues (e.g, skys without shadows)
1338
1339        RenderSky();
1340
1341
1342        //////////////////////////////
1343
1344        if (useDeferred)
1345        {
1346                FrameBufferObject::Release();
1347
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
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
1368                {
1369                        shadingMethod = DeferredRenderer::DEFAULT;
1370                }
1371
1372                static int snapShotIdx = 0;
1373
1374                deferredShader->SetSunVisiblePixels(sunVisiblePixels);
1375                deferredShader->SetShadingMethod(shadingMethod);
1376                deferredShader->SetSamplingMethod(samplingMethod);
1377               
1378                deferredShader->SetUseTemporalCoherence(useTemporalCoherence);
1379                //deferredShader->SetSortSamples(sortSamples);
1380                deferredShader->SetTemporalCoherenceFactorForSsao(ssaoTempCohFactor);
1381                deferredShader->SetUseToneMapping(useHDR);
1382                deferredShader->SetUseAntiAliasing(useAntiAliasing);
1383
1384
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
1392                //if (makeSnapShot) makeSnapShot = false;
1393
1394                ShadowMap *sm = showShadowMap ? shadowMap : NULL;
1395                deferredShader->Render(fbo, light, sm);
1396        }
1397
1398
1399        renderState.SetRenderTechnique(FORWARD);
1400        renderState.Reset();
1401
1402
1403        glDisableClientState(GL_VERTEX_ARRAY);
1404        glDisableClientState(GL_NORMAL_ARRAY);
1405       
1406        renderMethod = oldRenderMethod;
1407
1408
1409        ///////////
1410
1411
1412        if (showAlgorithmTime)
1413        {
1414                glFinish();
1415
1416                algTime = algTimer.Elapsedms();
1417                perfGraph->AddData(algTime);
1418
1419                perfGraph->Draw();
1420        }
1421        else
1422        {
1423                if (visMode) DisplayVisualization();
1424        }
1425
1426        glFlush();
1427
1428        const bool restart = true;
1429        elapsedTime = frameTimer.Elapsedms(restart);
1430
1431        // statistics
1432        DisplayStats();
1433
1434        glutSwapBuffers();
1435
1436        oldPos = camera->GetPosition();
1437        oldDir = camera->GetDirection();
1438}
1439
1440
1441#pragma warning(disable : 4100)
1442void KeyBoard(unsigned char c, int x, int y)
1443{
1444        switch(c)
1445        {
1446        case 27:
1447                // write out current position on exit
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
1451                CleanUp();
1452                exit(0);
1453        case 32: // space
1454                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1455                //renderMode = (renderMode + 1) % 4;
1456
1457                DEL_PTR(traverser);
1458                traverser = CreateTraverser(camera);
1459
1460                if (shadowTraverser)
1461                {
1462                        // shadow traverser has to be recomputed
1463                        DEL_PTR(shadowTraverser);
1464                        shadowTraverser = CreateTraverser(shadowMap->GetShadowCamera());
1465                }
1466
1467                break;
1468        case '+':
1469                if (maxBatchSize < 10)
1470                        maxBatchSize = 10;
1471                else
1472                        maxBatchSize += 10;
1473
1474                traverser->SetMaxBatchSize(maxBatchSize);
1475                break;
1476        case '-':
1477                maxBatchSize -= 10;
1478                if (maxBatchSize < 0) maxBatchSize = 1;
1479                traverser->SetMaxBatchSize(maxBatchSize);               
1480                break;
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':
1493                if (trianglesPerVirtualLeaf >= 100) trianglesPerVirtualLeaf -= 100;
1494                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1495                break;
1496        case '4':
1497                trianglesPerVirtualLeaf += 100;
1498                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1499                break;
1500        case '5':
1501                assumedVisibleFrames -= 1;
1502                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1503                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1504                break;
1505        case '6':
1506                assumedVisibleFrames += 1;
1507                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1508                break;
1509        case '7':
1510                ssaoTempCohFactor *= 1.0f / 1.2f;
1511                cout << "new temporal coherence factor: " << ssaoTempCohFactor << endl;
1512                break;
1513        case '8':
1514                ssaoTempCohFactor *= 1.2f;
1515                cout << "new temporal coherence factor: " << ssaoTempCohFactor << endl;
1516                break;
1517        case '9':
1518                ssaoKernelRadius *= 0.8f;
1519                cout << "new ssao kernel radius: " << ssaoKernelRadius << endl;
1520                if (deferredShader) deferredShader->SetKernelRadius(ssaoKernelRadius);
1521                break;
1522        case '0':
1523                ssaoKernelRadius *= 1.0f / 0.8f;
1524                if (deferredShader) deferredShader->SetKernelRadius(ssaoKernelRadius);
1525                cout << "new ssao kernel radius: " << ssaoKernelRadius << endl;
1526                break;
1527        case 'n':
1528                ssaoSampleIntensity *= 0.9f;
1529                if (deferredShader) deferredShader->SetSampleIntensity(ssaoSampleIntensity);
1530                cout << "new ssao sample intensity: " << ssaoSampleIntensity << endl;
1531                break;
1532        case 'N':
1533                ssaoSampleIntensity *= 1.0f / 0.9f;
1534                if (deferredShader) deferredShader->SetSampleIntensity(ssaoSampleIntensity);
1535                cout << "new ssao sample intensity: " << ssaoSampleIntensity << endl;
1536                break;
1537        case 'o':
1538                ssaoFilterRadius *= 0.9f;
1539                if (deferredShader) deferredShader->SetSsaoFilterRadius(ssaoFilterRadius);
1540                cout << "new ssao filter radius: " << ssaoFilterRadius << endl;
1541                break;
1542        case 'O':
1543                ssaoFilterRadius *= 1.0f / 0.9f;
1544                if (deferredShader) deferredShader->SetSsaoFilterRadius(ssaoFilterRadius);
1545                cout << "new ssao filter radius: " << ssaoFilterRadius << endl;
1546                break;
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;*/
1554        case 'l':
1555        case 'L':
1556                useLODs = !useLODs;
1557                SceneEntity::SetUseLODs(useLODs);
1558                cout << "using LODs: " << useLODs << endl;
1559                break;
1560        case 'P':
1561        case 'p':
1562                samplingMethod = DeferredRenderer::SAMPLING_METHOD((samplingMethod + 1) % 3);
1563                cout << "ssao sampling method: " << samplingMethod << endl;
1564                break;
1565        case 'Y':
1566        case 'y':
1567                showShadowMap = !showShadowMap;
1568                break;
1569        case 'g':
1570        case 'G':
1571                useGlobIllum = !useGlobIllum;
1572                break;
1573        case 't':
1574        case 'T':
1575                useTemporalCoherence = !useTemporalCoherence;
1576                break;
1577        case 'a':
1578        case 'A':
1579                leftKeyPressed = true;
1580                break;
1581        case 'd':
1582        case 'D':
1583                rightKeyPressed = true;
1584                break;
1585        case 'w':
1586        case 'W':
1587                upKeyPressed = true;
1588                break;
1589        case 's':
1590        case 'S':
1591                downKeyPressed = true;
1592                break;
1593        case 'j':
1594        case 'J':
1595                leftStrafeKeyPressed = true;
1596                break;
1597        case 'k':
1598        case 'K':
1599                rightStrafeKeyPressed = true;
1600                break;
1601        case 'r':
1602        case 'R':
1603                useRenderQueue = !useRenderQueue;
1604                traverser->SetUseRenderQueue(useRenderQueue);
1605                break;
1606        case 'b':
1607        case 'B':
1608                useTightBounds = !useTightBounds;
1609                traverser->SetUseTightBounds(useTightBounds);
1610                break;
1611        case 'v':
1612        case 'V':
1613                renderLightView = !renderLightView;
1614                break;
1615        case 'h':
1616        case 'H':
1617                useHDR = !useHDR;
1618                break;
1619        case 'i':
1620        case 'I':
1621                useAntiAliasing = !useAntiAliasing;
1622                break;
1623        case 'c':
1624        case 'C':
1625                useLenseFlare = !useLenseFlare;
1626                break;
1627        case 'u':
1628        case 'U':
1629                // move light source instead of camera tilt
1630                moveLight = !moveLight;
1631                break;
1632        case '#':
1633                // make a snapshot of the current frame
1634                makeSnapShot = true;
1635                break;
1636        case '.':
1637                // enable / disable view cells
1638                usePvs = !usePvs;
1639                if (!usePvs) SceneEntity::SetCurrentVisibleId(-1);
1640                break;
1641        default:
1642                return;
1643        }
1644
1645        glutPostRedisplay();
1646}
1647
1648
1649void SpecialKeyUp(int c, int x, int y)
1650{
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;
1665        case GLUT_ACTIVE_ALT:
1666                altKeyPressed = false;
1667                break;
1668        default:
1669                return;
1670        }
1671}
1672
1673
1674void KeyUp(unsigned char c, int x, int y)
1675{
1676        switch (c)
1677        {
1678
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;
1691        case 'S':
1692        case 's':
1693                downKeyPressed = false;
1694                break;
1695        case '1':
1696                descendKeyPressed = false;
1697                break;
1698        case '2':
1699                ascendKeyPressed = false;
1700                break;
1701        case 'j':
1702        case 'J':
1703                leftStrafeKeyPressed = false;
1704                break;
1705        case 'k':
1706        case 'K':
1707                rightStrafeKeyPressed = false;
1708                break;
1709        default:
1710                return;
1711        }
1712        //glutPostRedisplay();
1713}
1714
1715
1716void Special(int c, int x, int y)
1717{
1718        switch(c)
1719        {
1720        case GLUT_KEY_F1:
1721                showHelp = !showHelp;
1722                break;
1723        case GLUT_KEY_F2:
1724                visMode = !visMode;
1725                break;
1726        case GLUT_KEY_F3:
1727                showBoundingVolumes = !showBoundingVolumes;
1728                traverser->SetShowBounds(showBoundingVolumes);
1729                break;
1730        case GLUT_KEY_F4:
1731                showOptions = !showOptions;
1732                break;
1733        case GLUT_KEY_F5:
1734                showStatistics = !showStatistics;
1735                break;
1736        case GLUT_KEY_F6:
1737                flyMode = !flyMode;
1738                break;
1739        case GLUT_KEY_F7:
1740
1741                renderMethod = (renderMethod + 1) % 4;
1742
1743                traverser->SetUseDepthPass(
1744                        (renderMethod == RENDER_DEPTH_PASS) ||
1745                        (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
1746                        );
1747               
1748                break;
1749        case GLUT_KEY_F8:
1750                useAdvancedShading = !useAdvancedShading;
1751                break;
1752        case GLUT_KEY_F9:
1753                showAlgorithmTime = !showAlgorithmTime;
1754                break;
1755        case GLUT_KEY_F10:
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
1768                break;
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;
1792        case GLUT_KEY_LEFT:
1793                {
1794                        leftKeyPressed = true;
1795                        camera->Pitch(KeyRotationAngle());
1796                }
1797                break;
1798        case GLUT_KEY_RIGHT:
1799                {
1800                        rightKeyPressed = true;
1801                        camera->Pitch(-KeyRotationAngle());
1802                }
1803                break;
1804        case GLUT_KEY_UP:
1805                {
1806                        upKeyPressed = true;
1807                        KeyHorizontalMotion(KeyShift());
1808                }
1809                break;
1810        case GLUT_KEY_DOWN:
1811                {
1812                        downKeyPressed = true;
1813                        KeyHorizontalMotion(-KeyShift());
1814                }
1815                break;
1816        default:
1817                return;
1818
1819        }
1820
1821        glutPostRedisplay();
1822}
1823
1824#pragma warning( default : 4100 )
1825
1826
1827void Reshape(int w, int h)
1828{
1829        winAspectRatio = 1.0f;
1830
1831        glViewport(0, 0, w, h);
1832       
1833        winWidth = w;
1834        winHeight = h;
1835
1836        if (w) winAspectRatio = (float) w / (float) h;
1837
1838        glMatrixMode(GL_PROJECTION);
1839        glLoadIdentity();
1840
1841        gluPerspective(fov, winAspectRatio, nearDist, farDist);
1842
1843        glMatrixMode(GL_MODELVIEW);
1844
1845        glutPostRedisplay();
1846}
1847
1848
1849void Mouse(int button, int renderState, int x, int y)
1850{
1851        if ((button == GLUT_LEFT_BUTTON) && (renderState == GLUT_DOWN))
1852        {
1853                xEyeBegin = x;
1854                yMotionBegin = y;
1855
1856                glutMotionFunc(LeftMotion);
1857        }
1858        else if ((button == GLUT_RIGHT_BUTTON) && (renderState == GLUT_DOWN))
1859        {
1860                xEyeBegin = x;
1861                yEyeBegin = y;
1862                yMotionBegin = y;
1863
1864                if (!moveLight)
1865                        glutMotionFunc(RightMotion);
1866                else
1867                        glutMotionFunc(RightMotionLight);
1868        }
1869        else if ((button == GLUT_MIDDLE_BUTTON) && (renderState == GLUT_DOWN))
1870        {
1871                horizontalMotionBegin = x;
1872                verticalMotionBegin = y;
1873                glutMotionFunc(MiddleMotion);
1874        }
1875
1876        glutPostRedisplay();
1877}
1878
1879
1880/**     rotation for left/right mouse drag
1881        motion for up/down mouse drag
1882*/
1883void LeftMotion(int x, int y)
1884{
1885        Vector3 viewDir = camera->GetDirection();
1886        Vector3 pos = camera->GetPosition();
1887
1888        // don't move in the vertical direction
1889        Vector3 horView(viewDir[0], viewDir[1], 0);
1890       
1891        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1892
1893        camera->Pitch(eyeXAngle);
1894
1895        pos += horView * (yMotionBegin - y) * mouseMotion;
1896       
1897        camera->SetPosition(pos);
1898       
1899        xEyeBegin = x;
1900        yMotionBegin = y;
1901
1902        glutPostRedisplay();
1903}
1904
1905
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
1919        // normalize to avoid accumulating errors
1920        lightDir.Normalize();
1921
1922        light->SetDirection(lightDir);
1923
1924        xEyeBegin = x;
1925        yMotionBegin = y;
1926
1927        glutPostRedisplay();
1928}
1929
1930
1931/**     rotation for left / right mouse drag
1932        motion for up / down mouse drag
1933*/
1934void RightMotion(int x, int y)
1935{
1936        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1937        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1938
1939        camera->Yaw(eyeYAngle);
1940        camera->Pitch(eyeXAngle);
1941
1942        xEyeBegin = x;
1943        yEyeBegin = y;
1944
1945        glutPostRedisplay();
1946}
1947
1948
1949/** strafe
1950*/
1951void MiddleMotion(int x, int y)
1952{
1953        Vector3 viewDir = camera->GetDirection();
1954        Vector3 pos = camera->GetPosition();
1955
1956        // the 90 degree rotated view vector
1957        // y zero so we don't move in the vertical
1958        Vector3 rVec(viewDir[0], viewDir[1], 0);
1959       
1960        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1961        rVec = rot * rVec;
1962       
1963        pos -= rVec * (x - horizontalMotionBegin) * mouseMotion;
1964        pos[2] += (verticalMotionBegin - y) * mouseMotion;
1965
1966        camera->SetPosition(pos);
1967
1968        horizontalMotionBegin = x;
1969        verticalMotionBegin = y;
1970
1971        glutPostRedisplay();
1972}
1973
1974
1975void InitExtensions(void)
1976{
1977        GLenum err = glewInit();
1978
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        }
1985        if  (!GLEW_ARB_occlusion_query)
1986        {
1987                printf("I require the GL_ARB_occlusion_query to work.\n");
1988                exit(1);
1989        }
1990}
1991
1992
1993void Begin2D()
1994{
1995        glDisable(GL_LIGHTING);
1996        glDisable(GL_DEPTH_TEST);
1997
1998        glMatrixMode(GL_PROJECTION);
1999        glPushMatrix();
2000        glLoadIdentity();
2001
2002        gluOrtho2D(0, winWidth, 0, winHeight);
2003
2004        glMatrixMode(GL_MODELVIEW);
2005        glPushMatrix();
2006        glLoadIdentity();
2007}
2008
2009
2010void End2D()
2011{
2012        glMatrixMode(GL_PROJECTION);
2013        glPopMatrix();
2014
2015        glMatrixMode(GL_MODELVIEW);
2016        glPopMatrix();
2017
2018        glEnable(GL_LIGHTING);
2019        glEnable(GL_DEPTH_TEST);
2020}
2021
2022
2023// displays the visualisation of culling algorithm
2024void DisplayVisualization()
2025{
2026        // render current view cell
2027        if (usePvs) RenderViewCell();
2028       
2029        visualization->SetViewCell(usePvs ? viewCell : NULL);
2030        visualization->SetFrameId(traverser->GetCurrentFrameId());
2031       
2032
2033        Begin2D();
2034        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2035        glEnable(GL_BLEND);
2036        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
2037
2038        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
2039        glDisable(GL_BLEND);
2040        End2D();
2041       
2042       
2043        AxisAlignedBox3 box = bvh->GetBox();
2044
2045        const float offs = box.Size().x * 0.3f;
2046       
2047        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
2048       
2049        visCamera->SetPosition(vizpos);
2050        visCamera->ResetPitchAndYaw();
2051       
2052        glPushAttrib(GL_VIEWPORT_BIT);
2053        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
2054
2055        glMatrixMode(GL_PROJECTION);
2056        glPushMatrix();
2057
2058        glLoadIdentity();
2059        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
2060
2061        glMatrixMode(GL_MODELVIEW);
2062        glPushMatrix();
2063
2064        visCamera->SetupCameraView();
2065
2066        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
2067        glMultMatrixf((float *)rotZ.x);
2068
2069        // inverse translation in order to fix current position
2070        Vector3 pos = camera->GetPosition();
2071        glTranslatef(-pos.x, -pos.y, -pos.z);
2072
2073
2074        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
2075        glLightfv(GL_LIGHT0, GL_POSITION, position);
2076
2077        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
2078        glLightfv(GL_LIGHT1, GL_POSITION, position1);
2079
2080        glClear(GL_DEPTH_BUFFER_BIT);
2081
2082
2083        ////////////
2084        //-- visualization of the occlusion culling
2085
2086        visualization->Render(showShadowMap);
2087
2088       
2089        // reset previous settings
2090        glPopAttrib();
2091
2092        glMatrixMode(GL_PROJECTION);
2093        glPopMatrix();
2094        glMatrixMode(GL_MODELVIEW);
2095        glPopMatrix();
2096}
2097
2098
2099// cleanup routine after the main loop
2100void CleanUp()
2101{
2102        DEL_PTR(traverser);
2103        DEL_PTR(sceneQuery);
2104        DEL_PTR(bvh);
2105        DEL_PTR(visualization);
2106        DEL_PTR(camera);
2107        DEL_PTR(renderQueue);
2108        DEL_PTR(perfGraph);
2109        DEL_PTR(fbo);
2110        DEL_PTR(deferredShader);
2111        DEL_PTR(light);
2112        DEL_PTR(visCamera);
2113        DEL_PTR(preetham);
2114        DEL_PTR(shadowMap);
2115        DEL_PTR(shadowTraverser);
2116        DEL_PTR(motionPath);
2117        DEL_PTR(walkThroughRecorder);
2118        DEL_PTR(walkThroughPlayer);
2119        DEL_PTR(statsWriter);
2120        DEL_PTR(viewCellsTree);
2121
2122        ResourceManager::DelSingleton();
2123        ShaderManager::DelSingleton();
2124
2125        resourceManager = NULL;
2126        shaderManager = NULL;
2127}
2128
2129
2130// this function inserts a dezimal point after each 1000
2131void CalcDecimalPoint(string &str, int d, int len)
2132{
2133        static vector<int> numbers;
2134        numbers.clear();
2135
2136        static string shortStr;
2137        shortStr.clear();
2138
2139        static char hstr[100];
2140
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        {
2150                sprintf(hstr, "%d", numbers.back());
2151                shortStr.append(hstr);
2152        }
2153       
2154        for (int i = (int)numbers.size() - 2; i >= 0; i--)
2155        {
2156                sprintf(hstr, ",%03d", numbers[i]);
2157                shortStr.append(hstr);
2158        }
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);
2168}
2169
2170
2171void DisplayStats()
2172{
2173        static char msg[9][300];
2174
2175        static double frameTime = elapsedTime;
2176        static double renderTime = algTime;
2177
2178        const float expFactor = 0.1f;
2179
2180        // if some strange render time spike happened in this frame => don't count
2181        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
2182       
2183        static float rTime = 1000.0f;
2184
2185        // the render time used up purely for the traversal algorithm using glfinish
2186        if (showAlgorithmTime)
2187        {
2188                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
2189        }
2190
2191        accumulatedTime += elapsedTime;
2192
2193        if (accumulatedTime > 500) // update every fraction of a second
2194        {       
2195                accumulatedTime = 0;
2196
2197                if (frameTime) fps = 1e3f / (float)frameTime;
2198
2199                rTime = renderTime;
2200
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
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;
2225                numBatches = traverser->GetStats().mNumBatches;
2226        }
2227
2228
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
2258                averageTime = accTime = .0f;
2259
2260                DEL_PTR(statsWriter);
2261        }
2262
2263
2264        Begin2D();
2265
2266        glEnable(GL_BLEND);
2267        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2268
2269        if (showHelp)
2270        {       
2271                DrawHelpMessage();
2272        }
2273        else
2274        {
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);
2288                myfont.Begin();
2289
2290                if (showOptions)
2291                {
2292                        glColor3f(0.0f, 1.0f, 0.0f);
2293                        int i = 0;
2294
2295                        static char *renderMethodStr[] =
2296                                {"forward", "depth pass + forward", "deferred shading", "depth pass + deferred"};
2297                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
2298                                        useMultiQueries, useTightBounds, useRenderQueue);
2299                        sprintf(msg[i ++], "render technique: %s, use pvss: %d", renderMethodStr[renderMethod], usePvs);
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);
2303
2304                        for (int j = 0; j < 4; ++ j)
2305                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
2306                }
2307
2308                if (showStatistics)
2309                {
2310                        glColor3f(1.0f, 1.0f, 0.0f);
2311
2312                        string objStr, totalObjStr;
2313                        string triStr, totalTriStr;
2314
2315                        int len = 10;
2316                        CalcDecimalPoint(objStr, renderedObjects, len);
2317                        CalcDecimalPoint(totalObjStr, (int)resourceManager->GetNumEntities(), len);
2318
2319                        CalcDecimalPoint(triStr, renderedTriangles, len);
2320                        CalcDecimalPoint(totalTriStr, bvh->GetBvhStats().mTriangles, len);
2321
2322                        int i = 4;
2323
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                        }
2334
2335                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
2336                                traversedNodes, frustumCulledNodes, queryCulledNodes);
2337                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
2338                                issuedQueries, stateChanges, numBatches);
2339
2340                        for (int j = 4; j < 7; ++ j)
2341                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
2342                }
2343
2344                glColor3f(1.0f, 1.0f, 1.0f);
2345                static char *alg_str[] = {
2346                        "Frustum Cull"
2347                        , "Stop and Wait"
2348                        , "CHC"
2349                        , "CHC ++"
2350                        , "Collector"
2351                };
2352               
2353                if (!showAlgorithmTime)
2354                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
2355                else
2356                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
2357               
2358                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
2359               
2360                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
2361                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
2362        }
2363
2364        glDisable(GL_BLEND);
2365        glDisable(GL_TEXTURE_2D);
2366
2367        End2D();
2368}       
2369
2370
2371void RenderSky()
2372{
2373        if ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
2374                renderState.SetRenderTechnique(DEFERRED);
2375
2376        const bool useToneMapping =
2377                ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) ||
2378                 (renderMethod == RENDER_DEFERRED)) && useHDR;
2379       
2380        preetham->RenderSkyDome(-light->GetDirection(), camera, &renderState, !useToneMapping);
2381
2382        /// once again reset the renderState just to make sure
2383        renderState.Reset();
2384}
2385
2386
2387// render visible object from depth pass
2388void RenderVisibleObjects()
2389{
2390        if (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
2391        {
2392                if (showShadowMap && !renderLightView)
2393                {
2394                        // usethe maximal visible distance to focus shadow map
2395                        const float newFar = min(camera->GetFar(), traverser->GetMaxVisibleDistance());
2396                        RenderShadowMap(newFar);
2397                }
2398                // initialize deferred rendering
2399                InitDeferredRendering();
2400        }
2401        else
2402        {
2403                renderState.SetRenderTechnique(FORWARD);
2404        }
2405
2406
2407        /////////////////
2408        //-- reset gl renderState before the final visible objects pass
2409
2410        renderState.Reset();
2411
2412        glEnableClientState(GL_NORMAL_ARRAY);
2413        /// switch back to smooth shading
2414        glShadeModel(GL_SMOOTH);
2415        /// reset alpha to coverage flag
2416        renderState.SetUseAlphaToCoverage(true);
2417        // clear color
2418        glClear(GL_COLOR_BUFFER_BIT);
2419       
2420        // draw only objects having exactly the same depth as the current sample
2421        glDepthFunc(GL_EQUAL);
2422
2423        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2424
2425        SceneEntityContainer::const_iterator sit,
2426                sit_end = traverser->GetVisibleObjects().end();
2427
2428        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
2429        {
2430                renderQueue->Enqueue(*sit);
2431        }
2432
2433        /// now render out everything in one giant pass
2434        renderQueue->Apply();
2435
2436        // switch back to standard depth func
2437        glDepthFunc(GL_LESS);
2438        renderState.Reset();
2439
2440        PrintGLerror("visibleobjects");
2441}
2442
2443
2444SceneQuery *GetOrCreateSceneQuery()
2445{
2446        if (!sceneQuery)
2447        {
2448                sceneQuery = new SceneQuery(bvh->GetBox(), traverser, &renderState);
2449        }
2450
2451        return sceneQuery;
2452}
2453
2454
2455void PlaceViewer(const Vector3 &oldPos)
2456{
2457        Vector3 playerPos = camera->GetPosition();
2458        bool validIntersect = GetOrCreateSceneQuery()->CalcIntersection(playerPos);
2459
2460        if (validIntersect)
2461                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
2462        {
2463                camera->SetPosition(playerPos);
2464        }
2465}
2466
2467
2468void RenderShadowMap(float newfar)
2469{
2470        glDisableClientState(GL_NORMAL_ARRAY);
2471        renderState.SetRenderTechnique(DEPTH_PASS);
2472       
2473        // hack: disable cull face because of alpha textured balconies
2474        glDisable(GL_CULL_FACE);
2475        renderState.LockCullFaceEnabled(true);
2476
2477        /// don't use alpha to coverage for the depth map (problems with fbo rendering)
2478        renderState.SetUseAlphaToCoverage(false);
2479
2480        // change CHC++ set of renderState variables
2481        // this must be done for each change of camera because
2482        // otherwise the temporal coherency is broken
2483        BvhNode::SetCurrentState(LIGHT_PASS);
2484        // hack: temporarily change camera far plane
2485        camera->SetFar(newfar);
2486        // the scene is rendered withouth any shading   
2487        shadowMap->ComputeShadowMap(shadowTraverser, viewProjMat);
2488
2489        camera->SetFar(farDist);
2490
2491        renderState.SetUseAlphaToCoverage(true);
2492        renderState.LockCullFaceEnabled(false);
2493        glEnable(GL_CULL_FACE);
2494
2495        glEnableClientState(GL_NORMAL_ARRAY);
2496        // change back renderState
2497        BvhNode::SetCurrentState(CAMERA_PASS);
2498}
2499
2500
2501/** Touch each material once in order to preload the render queue
2502        bucket id of each material
2503*/
2504void PrepareRenderQueue()
2505{
2506        for (int i = 0; i < 3; ++ i)
2507        {
2508                renderState.SetRenderTechnique(i);
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                {
2515                        static Transform3 dummy(IdentityMatrix());
2516                        renderQueue->Enqueue(*sit, NULL);
2517                }
2518       
2519                // just clear queue again
2520                renderQueue->Clear();
2521        }
2522}
2523
2524
2525int LoadModel(const string &model, SceneEntityContainer &entities)
2526{
2527        const string filename = string(model_path + model);
2528
2529        int numEntities = 0;
2530
2531        cout << "\nloading model " << filename << endl;
2532
2533        if (numEntities = resourceManager->Load(filename, entities))
2534        {
2535                cout << "model " << filename << " successfully loaded" << endl;
2536        }
2537        else
2538        {
2539                cerr << "loading model " << filename << " failed" << endl;
2540
2541                CleanUp();
2542                exit(0);
2543        }
2544
2545        return numEntities;
2546}
2547
2548
2549void CreateAnimation()
2550{
2551        const float radius = 5.0f;
2552        const Vector3 center(480.398f, 268.364f, 181.3);
2553
2554        VertexArray vertices;
2555
2556        /*for (int i = 0; i < 360; ++ i)
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);
2562        }*/
2563
2564        for (int i = 0; i < 5; ++ i)
2565        {
2566                Vector3 offs = Vector3(i, 0, 0);
2567                vertices.push_back(center + offs);
2568        }
2569
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
2577        motionPath = new MotionPath(vertices);
2578}
2579
2580/** This function returns the number of visible pixels of a
2581        bounding box representing the sun.
2582*/
2583int TestSunVisible()
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
2601        return sampleCount;
2602}
2603
2604
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
2618void LoadPvs()
2619{
2620        viewCell = viewCellsTree->GetViewCell(camera->GetPosition());
2621
2622        int numTriangles = 0;
2623
2624        SceneEntity::SetCurrentVisibleId(globalVisibleId);
2625
2626        for (int i = 0; i < viewCell->mPvs.GetSize(); ++ i)
2627        {
2628                SceneEntity *ent = viewCell->mPvs.GetEntry(i);
2629                ent->SetVisibleId(globalVisibleId);
2630                //ent->Render(&renderState);
2631
2632                numTriangles += ent->CountNumTriangles();
2633        }
2634
2635        ++ globalVisibleId;
2636}
2637
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
2649        viewCellsTree = visLoader.Load(vis_filename, bvh, viewCellsScaleFactor);
2650
2651        if (!viewCellsTree)
2652        {
2653                cerr << "loading pvs failed" << endl;
2654                CleanUp();
2655                exit(0);
2656        }
2657}
2658
2659
2660void RenderViewCell()
2661{
2662        // render current view cell
2663        static Technique vcTechnique = GetVizTechnique();
2664
2665        vcTechnique.Render(&renderState);
2666        Visualization::RenderBoxForViz(viewCell->GetBox());
2667}
Note: See TracBrowser for help on using the repository browser.