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

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