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

Revision 3313, 69.4 KB checked in by mattausch, 15 years ago (diff)

reverted back to before poisson sampling scheme

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 0
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        case 'O':
1577                useOptimization = !useOptimization;
1578                // chc optimization of using the objects instead of
1579                // the bounding boxes for querying previously visible nodes
1580                traverser->SetUseOptimization(useOptimization);
1581                break;*/
1582        case 'l':
1583        case 'L':
1584                useLODs = !useLODs;
1585                SceneEntity::SetUseLODs(useLODs);
1586                cout << "using LODs: " << useLODs << endl;
1587                break;
1588        case 'P':
1589        case 'p':
1590                samplingMethod = DeferredRenderer::SAMPLING_METHOD((samplingMethod + 1) % 3);
1591                cout << "ssao sampling method: " << samplingMethod << endl;
1592                break;
1593        case 'Y':
1594        case 'y':
1595                showShadowMap = !showShadowMap;
1596                break;
1597        case 'g':
1598        case 'G':
1599                useGlobIllum = !useGlobIllum;
1600                break;
1601        case 't':
1602        case 'T':
1603                useTemporalCoherence = !useTemporalCoherence;
1604                break;
1605        case 'a':
1606        case 'A':
1607                leftKeyPressed = true;
1608                break;
1609        case 'd':
1610        case 'D':
1611                rightKeyPressed = true;
1612                break;
1613        case 'w':
1614        case 'W':
1615                upKeyPressed = true;
1616                break;
1617        case 's':
1618        case 'S':
1619                downKeyPressed = true;
1620                break;
1621        case 'j':
1622        case 'J':
1623                leftStrafeKeyPressed = true;
1624                break;
1625        case 'k':
1626        case 'K':
1627                rightStrafeKeyPressed = true;
1628                break;
1629        case 'r':
1630        case 'R':
1631                useRenderQueue = !useRenderQueue;
1632                traverser->SetUseRenderQueue(useRenderQueue);
1633                break;
1634        case 'b':
1635        case 'B':
1636                useTightBounds = !useTightBounds;
1637                traverser->SetUseTightBounds((renderMode == RenderTraverser::CHCPLUSPLUS) && useTightBounds);
1638                break;
1639        case 'v':
1640        case 'V':
1641                renderLightView = !renderLightView;
1642                break;
1643        case 'h':
1644        case 'H':
1645                useHDR = !useHDR;
1646                break;
1647        case 'i':
1648        case 'I':
1649                useAntiAliasing = !useAntiAliasing;
1650                break;
1651        case 'c':
1652        case 'C':
1653                useLenseFlare = !useLenseFlare;
1654                break;
1655        case 'u':
1656        case 'U':
1657                // move light source instead of camera tilt
1658                moveLight = !moveLight;
1659                break;
1660        case '#':
1661                // make a snapshot of the current frame
1662                makeSnapShot = true;
1663                break;
1664        case '.':
1665                // enable / disable view cells
1666                usePvs = !usePvs;
1667                if (!usePvs) SceneEntity::SetCurrentVisibleId(-1);
1668                break;
1669        case ',':
1670                // show / hide FPS
1671                showFPS = !showFPS;
1672                break;
1673       
1674        default:
1675                return;
1676        }
1677
1678        glutPostRedisplay();
1679}
1680
1681
1682void SpecialKeyUp(int c, int x, int y)
1683{
1684        switch (c)
1685        {
1686        case GLUT_KEY_LEFT:
1687                leftKeyPressed = false;
1688                break;
1689        case GLUT_KEY_RIGHT:
1690                rightKeyPressed = false;
1691                break;
1692        case GLUT_KEY_UP:
1693                upKeyPressed = false;
1694                break;
1695        case GLUT_KEY_DOWN:
1696                downKeyPressed = false;
1697                break;
1698        case GLUT_ACTIVE_ALT:
1699                altKeyPressed = false;
1700                break;
1701        default:
1702                return;
1703        }
1704}
1705
1706
1707void KeyUp(unsigned char c, int x, int y)
1708{
1709        switch (c)
1710        {
1711
1712        case 'A':
1713        case 'a':
1714                leftKeyPressed = false;
1715                break;
1716        case 'D':
1717        case 'd':
1718                rightKeyPressed = false;
1719                break;
1720        case 'W':
1721        case 'w':
1722                upKeyPressed = false;
1723                break;
1724        case 'S':
1725        case 's':
1726                downKeyPressed = false;
1727                break;
1728        case '1':
1729                descendKeyPressed = false;
1730                break;
1731        case '2':
1732                ascendKeyPressed = false;
1733                break;
1734        case 'j':
1735        case 'J':
1736                leftStrafeKeyPressed = false;
1737                break;
1738        case 'k':
1739        case 'K':
1740                rightStrafeKeyPressed = false;
1741                break;
1742        default:
1743                return;
1744        }
1745        //glutPostRedisplay();
1746}
1747
1748
1749void Special(int c, int x, int y)
1750{
1751        switch(c)
1752        {
1753        case GLUT_KEY_F1:
1754                showHelp = !showHelp;
1755                break;
1756        case GLUT_KEY_F2:
1757                visMode = !visMode;
1758                break;
1759        case GLUT_KEY_F3:
1760                showBoundingVolumes = !showBoundingVolumes;
1761                traverser->SetShowBounds(showBoundingVolumes);
1762                break;
1763        case GLUT_KEY_F4:
1764                showOptions = !showOptions;
1765                break;
1766        case GLUT_KEY_F5:
1767                showStatistics = !showStatistics;
1768                break;
1769        case GLUT_KEY_F6:
1770                flyMode = !flyMode;
1771                break;
1772        case GLUT_KEY_F7:
1773
1774                renderMethod = (renderMethod + 1) % 4;
1775
1776                traverser->SetUseDepthPass(
1777                        (renderMethod == RENDER_DEPTH_PASS) ||
1778                        (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
1779                        );
1780                break;
1781        case GLUT_KEY_F8:
1782                useAdvancedShading = !useAdvancedShading;
1783                break;
1784        case GLUT_KEY_F9:
1785                showAlgorithmTime = !showAlgorithmTime;
1786                break;
1787        case GLUT_KEY_F10:
1788                replayPath = !replayPath;
1789
1790                if (replayPath)
1791                {
1792                        cout << "replaying path" << endl;
1793                        currentReplayFrame = -1;
1794
1795                        // hack: load pvs on replay (remove later!)
1796                        //usePvs = true;
1797                }
1798                else
1799                {
1800                        cout << "finished replaying path" << endl;
1801                }
1802                break;
1803        case GLUT_KEY_F11:
1804                recordPath = !recordPath;
1805               
1806                if (recordPath)
1807                {
1808                        cout << "recording path" << endl;
1809                }
1810                else
1811                {
1812                        cout << "finished recording path" << endl;
1813                        // start over with new frame recording next time
1814                        DEL_PTR(walkThroughRecorder);
1815                }
1816                break;
1817        case GLUT_KEY_F12:
1818                recordFrames = !recordFrames;
1819
1820                if (recordFrames)
1821                        cout << "recording frames on replaying" << endl;
1822                else
1823                        cout << "not recording frames on replaying" << endl;
1824                break;
1825        case GLUT_KEY_LEFT:
1826                {
1827                        leftKeyPressed = true;
1828                        camera->Pitch(KeyRotationAngle());
1829                }
1830                break;
1831        case GLUT_KEY_RIGHT:
1832                {
1833                        rightKeyPressed = true;
1834                        camera->Pitch(-KeyRotationAngle());
1835                }
1836                break;
1837        case GLUT_KEY_UP:
1838                {
1839                        upKeyPressed = true;
1840                        KeyHorizontalMotion(KeyShift());
1841                }
1842                break;
1843        case GLUT_KEY_DOWN:
1844                {
1845                        downKeyPressed = true;
1846                        KeyHorizontalMotion(-KeyShift());
1847                }
1848                break;
1849        default:
1850                return;
1851
1852        }
1853
1854        glutPostRedisplay();
1855}
1856
1857#pragma warning( default : 4100 )
1858
1859
1860void Reshape(int w, int h)
1861{
1862        winAspectRatio = 1.0f;
1863
1864        glViewport(0, 0, w, h);
1865       
1866        winWidth = w;
1867        winHeight = h;
1868
1869        if (w) winAspectRatio = (float) w / (float) h;
1870
1871        glMatrixMode(GL_PROJECTION);
1872        glLoadIdentity();
1873
1874        gluPerspective(fov, winAspectRatio, nearDist, farDist);
1875
1876        glMatrixMode(GL_MODELVIEW);
1877
1878        glutPostRedisplay();
1879}
1880
1881
1882void Mouse(int button, int renderState, int x, int y)
1883{
1884        if ((button == GLUT_LEFT_BUTTON) && (renderState == GLUT_DOWN))
1885        {
1886                xEyeBegin = x;
1887                yMotionBegin = y;
1888
1889                glutMotionFunc(LeftMotion);
1890        }
1891        else if ((button == GLUT_RIGHT_BUTTON) && (renderState == GLUT_DOWN))
1892        {
1893                xEyeBegin = x;
1894                yEyeBegin = y;
1895                yMotionBegin = y;
1896
1897                if (!moveLight)
1898                        glutMotionFunc(RightMotion);
1899                else
1900                        glutMotionFunc(RightMotionLight);
1901        }
1902        else if ((button == GLUT_MIDDLE_BUTTON) && (renderState == GLUT_DOWN))
1903        {
1904                horizontalMotionBegin = x;
1905                verticalMotionBegin = y;
1906                glutMotionFunc(MiddleMotion);
1907        }
1908
1909        glutPostRedisplay();
1910}
1911
1912
1913/**     rotation for left/right mouse drag
1914        motion for up/down mouse drag
1915*/
1916void LeftMotion(int x, int y)
1917{
1918        Vector3 viewDir = camera->GetDirection();
1919        Vector3 pos = camera->GetPosition();
1920
1921        // don't move in the vertical direction
1922        Vector3 horView(viewDir[0], viewDir[1], 0);
1923       
1924        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1925
1926        camera->Pitch(eyeXAngle);
1927
1928        pos += horView * (yMotionBegin - y) * mouseMotion;
1929       
1930        camera->SetPosition(pos);
1931       
1932        xEyeBegin = x;
1933        yMotionBegin = y;
1934
1935        glutPostRedisplay();
1936}
1937
1938
1939void RightMotionLight(int x, int y)
1940{
1941        float theta = 0.2f * M_PI * (xEyeBegin - x) / 180.0f;
1942        float phi = 0.2f * M_PI * (yMotionBegin - y) / 180.0f;
1943       
1944        Vector3 lightDir = light->GetDirection();
1945
1946        Matrix4x4 roty = RotationYMatrix(theta);
1947        Matrix4x4 rotx = RotationXMatrix(phi);
1948
1949        lightDir = roty * lightDir;
1950        lightDir = rotx * lightDir;
1951
1952        // normalize to avoid accumulating errors
1953        lightDir.Normalize();
1954
1955        light->SetDirection(lightDir);
1956
1957        xEyeBegin = x;
1958        yMotionBegin = y;
1959
1960        glutPostRedisplay();
1961}
1962
1963
1964/**     rotation for left / right mouse drag
1965        motion for up / down mouse drag
1966*/
1967void RightMotion(int x, int y)
1968{
1969        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1970        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1971
1972        camera->Yaw(eyeYAngle);
1973        camera->Pitch(eyeXAngle);
1974
1975        xEyeBegin = x;
1976        yEyeBegin = y;
1977
1978        glutPostRedisplay();
1979}
1980
1981
1982/** strafe
1983*/
1984void MiddleMotion(int x, int y)
1985{
1986        Vector3 viewDir = camera->GetDirection();
1987        Vector3 pos = camera->GetPosition();
1988
1989        // the 90 degree rotated view vector
1990        // y zero so we don't move in the vertical
1991        Vector3 rVec(viewDir[0], viewDir[1], 0);
1992       
1993        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1994        rVec = rot * rVec;
1995       
1996        pos -= rVec * (x - horizontalMotionBegin) * mouseMotion;
1997        pos[2] += (verticalMotionBegin - y) * mouseMotion;
1998
1999        camera->SetPosition(pos);
2000
2001        horizontalMotionBegin = x;
2002        verticalMotionBegin = y;
2003
2004        glutPostRedisplay();
2005}
2006
2007
2008void InitExtensions(void)
2009{
2010        GLenum err = glewInit();
2011
2012        if (GLEW_OK != err)
2013        {
2014                // problem: glewInit failed, something is seriously wrong
2015                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
2016                exit(1);
2017        }
2018        if  (!GLEW_ARB_occlusion_query)
2019        {
2020                printf("I require the GL_ARB_occlusion_query to work.\n");
2021                exit(1);
2022        }
2023}
2024
2025
2026void Begin2D()
2027{
2028        glDisable(GL_LIGHTING);
2029        glDisable(GL_DEPTH_TEST);
2030
2031        glMatrixMode(GL_PROJECTION);
2032        glPushMatrix();
2033        glLoadIdentity();
2034
2035        gluOrtho2D(0, winWidth, 0, winHeight);
2036
2037        glMatrixMode(GL_MODELVIEW);
2038        glPushMatrix();
2039        glLoadIdentity();
2040}
2041
2042
2043void End2D()
2044{
2045        glMatrixMode(GL_PROJECTION);
2046        glPopMatrix();
2047
2048        glMatrixMode(GL_MODELVIEW);
2049        glPopMatrix();
2050
2051        glEnable(GL_LIGHTING);
2052        glEnable(GL_DEPTH_TEST);
2053}
2054
2055
2056// displays the visualisation of culling algorithm
2057void DisplayVisualization()
2058{
2059        // render current view cell
2060        if (usePvs) RenderViewCell();
2061       
2062        visualization->SetViewCell(usePvs ? viewCell : NULL);
2063        visualization->SetFrameId(traverser->GetCurrentFrameId());
2064       
2065
2066        Begin2D();
2067        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2068        glEnable(GL_BLEND);
2069        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
2070
2071        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
2072        glDisable(GL_BLEND);
2073        End2D();
2074       
2075       
2076        AxisAlignedBox3 box = bvh->GetBox();
2077
2078        const float offs = box.Size().x * 0.3f;
2079       
2080        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
2081       
2082        visCamera->SetPosition(vizpos);
2083        visCamera->ResetPitchAndYaw();
2084       
2085        glPushAttrib(GL_VIEWPORT_BIT);
2086        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
2087
2088        glMatrixMode(GL_PROJECTION);
2089        glPushMatrix();
2090
2091        glLoadIdentity();
2092        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
2093
2094        glMatrixMode(GL_MODELVIEW);
2095        glPushMatrix();
2096
2097        visCamera->SetupCameraView();
2098
2099        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
2100        glMultMatrixf((float *)rotZ.x);
2101
2102        // inverse translation in order to fix current position
2103        Vector3 pos = camera->GetPosition();
2104        glTranslatef(-pos.x, -pos.y, -pos.z);
2105
2106
2107        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
2108        glLightfv(GL_LIGHT0, GL_POSITION, position);
2109
2110        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
2111        glLightfv(GL_LIGHT1, GL_POSITION, position1);
2112
2113        glClear(GL_DEPTH_BUFFER_BIT);
2114
2115
2116        ////////////
2117        //-- visualization of the occlusion culling
2118
2119        visualization->Render(showShadowMap);
2120
2121       
2122        // reset previous settings
2123        glPopAttrib();
2124
2125        glMatrixMode(GL_PROJECTION);
2126        glPopMatrix();
2127        glMatrixMode(GL_MODELVIEW);
2128        glPopMatrix();
2129}
2130
2131
2132// cleanup routine after the main loop
2133void CleanUp()
2134{
2135        DEL_PTR(traverser);
2136        DEL_PTR(sceneQuery);
2137        DEL_PTR(bvh);
2138        DEL_PTR(visualization);
2139        DEL_PTR(camera);
2140        DEL_PTR(renderQueue);
2141        DEL_PTR(perfGraph);
2142        DEL_PTR(fbo);
2143        DEL_PTR(deferredShader);
2144        DEL_PTR(light);
2145        DEL_PTR(visCamera);
2146        DEL_PTR(preetham);
2147        DEL_PTR(shadowMap);
2148        DEL_PTR(shadowTraverser);
2149        DEL_PTR(motionPath);
2150        DEL_PTR(walkThroughRecorder);
2151        DEL_PTR(walkThroughPlayer);
2152        DEL_PTR(statsWriter);
2153        DEL_PTR(viewCellsTree);
2154
2155        ResourceManager::DelSingleton();
2156        ShaderManager::DelSingleton();
2157
2158        resourceManager = NULL;
2159        shaderManager = NULL;
2160}
2161
2162
2163// this function inserts a dezimal point after each 1000
2164void CalcDecimalPoint(string &str, int d, int len)
2165{
2166        static vector<int> numbers;
2167        numbers.clear();
2168
2169        static string shortStr;
2170        shortStr.clear();
2171
2172        static char hstr[100];
2173
2174        while (d != 0)
2175        {
2176                numbers.push_back(d % 1000);
2177                d /= 1000;
2178        }
2179
2180        // first element without leading zeros
2181        if (numbers.size() > 0)
2182        {
2183                sprintf(hstr, "%d", numbers.back());
2184                shortStr.append(hstr);
2185        }
2186       
2187        for (int i = (int)numbers.size() - 2; i >= 0; i--)
2188        {
2189                sprintf(hstr, ",%03d", numbers[i]);
2190                shortStr.append(hstr);
2191        }
2192
2193        int dif = len - (int)shortStr.size();
2194
2195        for (int i = 0; i < dif; ++ i)
2196        {
2197                str += " ";
2198        }
2199
2200        str.append(shortStr);
2201}
2202
2203
2204void DisplayStats()
2205{
2206        static char msg[9][300];
2207
2208        static double frameTime = elapsedTime;
2209        static double renderTime = algTime;
2210
2211        const float expFactor = 0.1f;
2212
2213        // if some strange render time spike happened in this frame => don't count
2214        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
2215       
2216        static float rTime = 1000.0f;
2217
2218        // the render time is used only for the traversal algorithm using glfinish
2219        if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
2220       
2221
2222        accumulatedTime += elapsedTime;
2223
2224        if (accumulatedTime > 500) // update every fraction of a second
2225        {       
2226                accumulatedTime = 0;
2227
2228                if (frameTime) fps = 1e3f / (float)frameTime;
2229                rTime = renderTime;
2230
2231                if (renderLightView && shadowTraverser)
2232                {
2233                        renderedTriangles = shadowTraverser->GetStats().mNumRenderedTriangles;
2234                        renderedObjects = shadowTraverser->GetStats().mNumRenderedGeometry;
2235                        renderedNodes = shadowTraverser->GetStats().mNumRenderedNodes;
2236                }
2237                else if (showShadowMap && shadowTraverser)
2238                {
2239                        renderedNodes = traverser->GetStats().mNumRenderedNodes + shadowTraverser->GetStats().mNumRenderedNodes;
2240                        renderedObjects = traverser->GetStats().mNumRenderedGeometry + shadowTraverser->GetStats().mNumRenderedGeometry;
2241                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles + shadowTraverser->GetStats().mNumRenderedTriangles;
2242                }
2243                else
2244                {
2245                        renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
2246                        renderedObjects = traverser->GetStats().mNumRenderedGeometry;
2247                        renderedNodes = traverser->GetStats().mNumRenderedNodes;
2248                }
2249
2250                traversedNodes = traverser->GetStats().mNumTraversedNodes;
2251                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
2252                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
2253                issuedQueries = traverser->GetStats().mNumIssuedQueries;
2254                stateChanges = traverser->GetStats().mNumStateChanges;
2255                numBatches = traverser->GetStats().mNumBatches;
2256        }
2257
2258
2259        ////////////////
2260        //-- record stats on walkthrough
2261
2262        static float accTime = .0f;
2263        static float averageTime = .0f;
2264
2265        if (currentReplayFrame > -1)
2266        {
2267                accTime += frameTime;
2268                averageTime = accTime / (currentReplayFrame + 1);
2269
2270                if (!statsWriter)
2271                        statsWriter = new StatsWriter(statsFilename + ".log");
2272                       
2273                FrameStats frameStats;
2274                frameStats.mFrame = currentReplayFrame;
2275                frameStats.mFPS = 1e3f / (float)frameTime;
2276                frameStats.mTime = frameTime;
2277                frameStats.mNodes = renderedNodes;
2278                frameStats.mObjects = renderedObjects;
2279                frameStats.mTriangles = renderedTriangles;
2280
2281                statsWriter->WriteFrameStats(frameStats);
2282        }
2283        else if (statsWriter)
2284        {
2285                Debug << "average frame time " << averageTime << " for traversal algorithm " << renderMode << endl;
2286
2287                // reset average frame time
2288                averageTime = accTime = .0f;
2289
2290                DEL_PTR(statsWriter);
2291        }
2292
2293
2294        Begin2D();
2295
2296        glEnable(GL_BLEND);
2297        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2298
2299        if (showHelp)
2300        {       
2301                DrawHelpMessage();
2302        }
2303        else
2304        {
2305                if (showOptions)
2306                {
2307                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
2308                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
2309                }
2310
2311                if (showStatistics)
2312                {
2313                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
2314                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
2315                }
2316
2317                glEnable(GL_TEXTURE_2D);
2318                myfont.Begin();
2319
2320                if (showOptions)
2321                {
2322                        glColor3f(0.0f, 1.0f, 0.0f);
2323                        int i = 0;
2324
2325                        static char *renderMethodStr[] =
2326                                {"forward", "depth pass + forward", "deferred shading", "depth pass + deferred"};
2327                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
2328                                        useMultiQueries, (renderMode == RenderTraverser::CHCPLUSPLUS) && useTightBounds, useRenderQueue);
2329                        sprintf(msg[i ++], "render technique: %s, use pvss: %d", renderMethodStr[renderMethod], usePvs);
2330                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
2331                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
2332                                assumedVisibleFrames, maxBatchSize);
2333
2334                        for (int j = 0; j < 4; ++ j)
2335                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
2336                }
2337
2338                if (showStatistics)
2339                {
2340                        glColor3f(1.0f, 1.0f, 0.0f);
2341
2342                        string objStr, totalObjStr;
2343                        string triStr, totalTriStr;
2344
2345                        int len = 10;
2346                        CalcDecimalPoint(objStr, renderedObjects, len);
2347                        CalcDecimalPoint(totalObjStr, (int)resourceManager->GetNumEntities(), len);
2348
2349                        CalcDecimalPoint(triStr, renderedTriangles, len);
2350                        CalcDecimalPoint(totalTriStr, bvh->GetBvhStats().mTriangles, len);
2351
2352                        int i = 4;
2353
2354                        if (0) // q: show rendered objects or nodes (no space for both)
2355                        {
2356                                sprintf(msg[i ++], "rendered: %s of %s objects, %s of %s triangles",
2357                                        objStr.c_str(), totalObjStr.c_str(), triStr.c_str(), totalTriStr.c_str());
2358                        }
2359                        else
2360                        {
2361                                sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
2362                                        renderedNodes, bvh->GetNumVirtualNodes(), triStr.c_str(), totalTriStr.c_str());
2363                        }
2364
2365                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d nodes",
2366                                traversedNodes, frustumCulledNodes, queryCulledNodes);
2367                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
2368                                issuedQueries, stateChanges, numBatches);
2369
2370                        for (int j = 4; j < 7; ++ j)
2371                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
2372                }
2373
2374                glColor3f(0.0f, 1.0f, 0.0f);
2375
2376                static char *alg_str[] = {
2377                        "Frustum Cull"
2378                        , "Stop and Wait"
2379                        , "CHC"
2380                        , "CHC ++"
2381            //, "Collector"
2382                };
2383       
2384                if (!showAlgorithmTime)
2385                {
2386                        if (showFPS)
2387                        {                       
2388                                sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);           
2389                                myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 10.0f);
2390
2391                                //int mrays = (int)shotRays / 1000000;
2392                                //sprintf(msg[7], "%s:  %04d M rays", alg_str[renderMode], mrays);     
2393                                //myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 60.0f);           
2394                        }
2395                }
2396                else
2397                {
2398                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
2399                        myfont.DrawString(msg[7], 1.3f, winWidth - 330, winHeight - 10.0f);
2400                }
2401
2402                glColor3f(1.0f, 1.0f, 1.0f);
2403        }
2404
2405        glColor3f(1, 1, 1);
2406        glDisable(GL_BLEND);
2407        glDisable(GL_TEXTURE_2D);
2408
2409        End2D();
2410}       
2411
2412
2413void RenderSky()
2414{
2415        if ((renderMethod == RENDER_DEFERRED) || (renderMethod == RENDER_DEPTH_PASS_DEFERRED))
2416                renderState.SetRenderTechnique(DEFERRED);
2417
2418        const bool useToneMapping =
2419                ((renderMethod == RENDER_DEPTH_PASS_DEFERRED) ||
2420                 (renderMethod == RENDER_DEFERRED)) && useHDR;
2421       
2422        preetham->RenderSkyDome(-light->GetDirection(), camera, &renderState, !useToneMapping, skyDomeScaleFactor);
2423
2424        /// once again reset the renderState just to make sure
2425        renderState.Reset();
2426}
2427
2428
2429// render visible object from depth pass
2430void RenderVisibleObjects()
2431{
2432        if (renderMethod == RENDER_DEPTH_PASS_DEFERRED)
2433        {
2434                if (showShadowMap && !renderLightView)
2435                {
2436                        // usethe maximal visible distance to focus shadow map
2437                        const float newFar = min(camera->GetFar(), traverser->GetMaxVisibleDistance());
2438                        RenderShadowMap(newFar);
2439                }
2440
2441                // initialize deferred rendering
2442                InitDeferredRendering();
2443        }
2444        else
2445        {
2446                renderState.SetRenderTechnique(FORWARD);
2447        }
2448
2449
2450        /////////////////
2451        //-- reset gl renderState before the final visible objects pass
2452
2453        renderState.Reset();
2454
2455        glEnableClientState(GL_NORMAL_ARRAY);
2456        /// switch back to smooth shading
2457        glShadeModel(GL_SMOOTH);
2458        /// reset alpha to coverage flag
2459        renderState.SetUseAlphaToCoverage(true);
2460        // clear color
2461        glClear(GL_COLOR_BUFFER_BIT);
2462       
2463        // draw only objects having exactly the same depth as the current sample
2464        glDepthFunc(GL_EQUAL);
2465
2466        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
2467
2468        SceneEntityContainer::const_iterator sit,
2469                sit_end = traverser->GetVisibleObjects().end();
2470
2471        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
2472        {
2473                renderQueue->Enqueue(*sit);
2474        }
2475
2476        /// now render out everything in one giant pass
2477        renderQueue->Apply();
2478
2479        // switch back to standard depth func
2480        glDepthFunc(GL_LESS);
2481        renderState.Reset();
2482
2483        PrintGLerror("visible objects");
2484}
2485
2486
2487SceneQuery *GetOrCreateSceneQuery()
2488{
2489        if (!sceneQuery)
2490        {
2491                sceneQuery = new SceneQuery(bvh->GetBox(), traverser, &renderState);
2492        }
2493
2494        return sceneQuery;
2495}
2496
2497
2498void PlaceViewer(const Vector3 &oldPos)
2499{
2500        Vector3 playerPos = camera->GetPosition();
2501        bool validIntersect = GetOrCreateSceneQuery()->CalcIntersection(playerPos);
2502
2503        if (validIntersect)
2504                //&& ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
2505        {
2506                camera->SetPosition(playerPos);
2507        }
2508}
2509
2510
2511void RenderShadowMap(float newfar)
2512{
2513        glDisableClientState(GL_NORMAL_ARRAY);
2514        renderState.SetRenderTechnique(DEPTH_PASS);
2515       
2516        // hack: disable cull face because of alpha textured balconies
2517        glDisable(GL_CULL_FACE);
2518        renderState.LockCullFaceEnabled(true);
2519
2520        /// don't use alpha to coverage for the depth map (problems with fbo rendering)
2521        renderState.SetUseAlphaToCoverage(false);
2522
2523        const Vector3 lightPos = light->GetDirection() * -1e3f;
2524        if (usePvs) LoadOrUpdatePVSs(lightPos);
2525
2526
2527        // change CHC++ set of renderState variables
2528        // this must be done for each change of camera because
2529        // otherwise the temporal coherency is broken
2530        BvhNode::SetCurrentState(LIGHT_PASS);
2531        // hack: temporarily change camera far plane
2532        camera->SetFar(newfar);
2533        // the scene is rendered withouth any shading   
2534        shadowMap->ComputeShadowMap(shadowTraverser, viewProjMat);
2535
2536        camera->SetFar(farDist);
2537
2538        renderState.SetUseAlphaToCoverage(true);
2539        renderState.LockCullFaceEnabled(false);
2540        glEnable(GL_CULL_FACE);
2541
2542        glEnableClientState(GL_NORMAL_ARRAY);
2543        // change back renderState
2544        BvhNode::SetCurrentState(CAMERA_PASS);
2545}
2546
2547
2548/** Touch each material once in order to preload the render queue
2549        bucket id of each material
2550*/
2551void PrepareRenderQueue()
2552{
2553        for (int i = 0; i < 3; ++ i)
2554        {
2555                renderState.SetRenderTechnique(i);
2556
2557                // fill all shapes into the render queue        once so we can establish the buckets
2558                ShapeContainer::const_iterator sit, sit_end = (*resourceManager->GetShapes()).end();
2559
2560                for (sit = (*resourceManager->GetShapes()).begin(); sit != sit_end; ++ sit)
2561                {
2562                        static Transform3 dummy(IdentityMatrix());
2563                        renderQueue->Enqueue(*sit, NULL);
2564                }
2565       
2566                // just clear queue again
2567                renderQueue->Clear();
2568        }
2569}
2570
2571
2572int LoadModel(const string &model, SceneEntityContainer &entities)
2573{
2574        const string filename = string(model_path + model);
2575        int numEntities = 0;
2576
2577        cout << "\nloading model " << filename << endl;
2578
2579        if (numEntities = resourceManager->Load(filename, entities))
2580        {
2581                cout << "model " << filename << " successfully loaded" << endl;
2582        }
2583        else
2584        {
2585                cerr << "loading model " << filename << " failed" << endl;
2586
2587                CleanUp();
2588                exit(0);
2589        }
2590
2591        return numEntities;
2592}
2593
2594
2595void CreateAnimation()
2596{
2597        const float radius = 5.0f;
2598        const Vector3 center(480.398f, 268.364f, 181.3);
2599
2600        VertexArray vertices;
2601
2602        /*for (int i = 0; i < 360; ++ i)
2603        {
2604                float angle = (float)i * M_PI / 180.0f;
2605
2606                Vector3 offs = Vector3(cos(angle) * radius, sin(angle) * radius, 0);
2607                vertices.push_back(center + offs);
2608        }*/
2609
2610        for (int i = 0; i < 5; ++ i)
2611        {
2612                Vector3 offs = Vector3(i, 0, 0);
2613                vertices.push_back(center + offs);
2614        }
2615
2616       
2617        for (int i = 0; i < 5; ++ i)
2618        {
2619                Vector3 offs = Vector3(4 -i, 0, 0);
2620                vertices.push_back(center + offs);
2621        }
2622
2623        motionPath = new MotionPath(vertices);
2624}
2625
2626/** This function returns the number of visible pixels of a
2627        bounding box representing the sun.
2628*/
2629int TestSunVisible()
2630{
2631        // assume sun is at a far away point along the light vector
2632        Vector3 sunPos = light->GetDirection() * -1e3f;
2633        sunPos += camera->GetPosition();
2634
2635        sunBox->GetTransform()->SetMatrix(TranslationMatrix(sunPos));
2636
2637        glBeginQueryARB(GL_SAMPLES_PASSED_ARB, sunQuery);
2638
2639        sunBox->Render(&renderState);
2640
2641        glEndQueryARB(GL_SAMPLES_PASSED_ARB);
2642
2643        GLuint sampleCount;
2644
2645        glGetQueryObjectuivARB(sunQuery, GL_QUERY_RESULT_ARB, &sampleCount);
2646
2647        return sampleCount;
2648}
2649
2650
2651static Technique GetVizTechnique()
2652{
2653        Technique tech;
2654        tech.Init();
2655
2656        tech.SetEmmisive(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2657        tech.SetDiffuse(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2658        tech.SetAmbient(RgbaColor(1.0f, 1.0f, 1.0f, 1.0f));
2659
2660        return tech;
2661}
2662
2663
2664void UpdatePvs(const Vector3 &pos)
2665{
2666        viewCell = viewCellsTree->GetViewCell(camera->GetPosition());
2667
2668        const float elapsedAlgorithmTime = applicationTimer.Elapsedms(false);
2669
2670        // assume 60 FPS, total time is in secs
2671        const float raysPerMs = 2.0f * pvsTotalSamples / (pvsTotalTime * 1000.0f);
2672        //shotRays = visibilitySolutionInitialState + elapsedAlgorithmTime * raysPerMs;
2673        //shotRays += 1000 * raysPerMs / 60.0f;
2674
2675        //cout << "totalt: " << pvsTotalTime << endl;
2676        //cout << "rays per ms: " << raysPerMs << endl;
2677
2678        SceneEntity::SetCurrentVisibleId(globalVisibleId);
2679
2680        for (int i = 0; i < viewCell->mPvs.GetSize(); ++ i)
2681        {
2682                PvsEntry entry = viewCell->mPvs.GetEntry(i);
2683#ifdef USE_TIMESTAMPS
2684                if (!((entry.mTimeStamp < 0.0f) || (entry.mTimeStamp <= shotRays)))
2685                        continue;
2686#endif
2687                entry.mEntity->SetVisibleId(globalVisibleId);
2688                //numTriangles += entry.mEntity->CountNumTriangles();
2689        }
2690
2691        ++ globalVisibleId;
2692}
2693
2694
2695void LoadVisibilitySolution()
2696{
2697        ///////////
2698        //-- load the visibility solution
2699
2700        const string vis_filename =
2701                string(model_path + visibilitySolution + ".vis");
2702
2703        VisibilitySolutionLoader visLoader;
2704
2705        viewCellsTree = visLoader.Load(vis_filename,
2706                                           bvh,
2707                                                                   pvsTotalSamples,
2708                                                                   pvsTotalTime,
2709                                                                   viewCellsScaleFactor);
2710
2711        if (!viewCellsTree)
2712        {
2713                cerr << "loading pvs failed" << endl;
2714                CleanUp();
2715                exit(0);
2716        }
2717}
2718
2719
2720void RenderViewCell()
2721{
2722        // render current view cell
2723        static Technique vcTechnique = GetVizTechnique();
2724
2725        vcTechnique.Render(&renderState);
2726        Visualization::RenderBoxForViz(viewCell->GetBox());
2727}
2728
2729
2730void LoadPompeiiFloor()
2731{
2732        AxisAlignedBox3 pompeiiBox =
2733                SceneEntity::ComputeBoundingBox(staticObjects);
2734
2735        // todo: dispose texture
2736        Texture *floorTex = new Texture(model_path + "stairs.c.01.tif");
2737
2738        floorTex->SetBoundaryModeS(Texture::REPEAT);
2739        floorTex->SetBoundaryModeT(Texture::REPEAT);
2740
2741        floorTex->Create();
2742        Material *mymat = resourceManager->CreateMaterial();
2743
2744        Technique *tech = mymat->GetDefaultTechnique();
2745        tech->SetDiffuse(RgbaColor(1, 1, 1, 1));
2746        tech->SetTexture(floorTex);
2747
2748        Technique *depthPass = new Technique(*tech);
2749        Technique *deferred = new Technique(*tech);
2750
2751        depthPass->SetColorWriteEnabled(false);
2752        depthPass->SetLightingEnabled(false);
2753
2754        ShaderProgram *defaultFragmentTexProgramMrt =
2755                ShaderManager::GetSingleton()->GetShaderProgram("defaultFragmentTexMrt");
2756        ShaderProgram *defaultVertexProgramMrt =
2757                ShaderManager::GetSingleton()->GetShaderProgram("defaultVertexMrt");
2758
2759        deferred->SetFragmentProgram(defaultFragmentTexProgramMrt);
2760        deferred->SetVertexProgram(defaultVertexProgramMrt);
2761
2762        deferred->GetFragmentProgramParameters()->SetViewMatrixParam(0);
2763        deferred->GetVertexProgramParameters()->SetModelMatrixParam(1);
2764        deferred->GetVertexProgramParameters()->SetOldModelMatrixParam(2);
2765
2766        deferred->SetTexture(floorTex);
2767       
2768        mymat->AddTechnique(deferred);
2769        mymat->AddTechnique(depthPass);
2770
2771
2772        //const Vector3 offs(1300.0f, -2500.0f, .0f);
2773        const Vector3 offs(pompeiiBox.Center(0), pompeiiBox.Center(1), 0);
2774        Matrix4x4 moffs = TranslationMatrix(offs);
2775
2776        Plane3 plane;
2777        Transform3 *mytrafo = resourceManager->CreateTransform(moffs);
2778
2779        SceneEntity *myplane =
2780                SceneEntityConverter().ConvertPlane(plane,
2781                                                    pompeiiBox.Size(0),
2782                                                                                        pompeiiBox.Size(1),
2783                                                                                        5,
2784                                                                                        5,
2785                                                                                        mymat,
2786                                                                                        mytrafo);
2787
2788        resourceManager->AddSceneEntity(myplane);
2789        staticObjects.push_back(myplane);
2790}
2791
2792
2793void LoadOrUpdatePVSs(const Vector3 &pos)
2794{
2795        if (!viewCellsTree)     
2796        {
2797                LoadVisibilitySolution();
2798                applicationTimer.Start();
2799                shotRays = visibilitySolutionInitialState;
2800        }
2801
2802        if (viewCellsTree) UpdatePvs(pos);
2803}
Note: See TracBrowser for help on using the repository browser.