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

Revision 3261, 65.1 KB checked in by mattausch, 15 years ago (diff)

worked on powerplant loading

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