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

Revision 3374, 72.8 KB checked in by mattausch, 15 years ago (diff)

testing city

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