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

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