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

Revision 3305, 69.8 KB checked in by mattausch, 15 years ago (diff)

removed filter radius

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