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

Revision 3214, 54.7 KB checked in by mattausch, 16 years ago (diff)

worked on lense flare

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