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

Revision 2888, 42.2 KB checked in by mattausch, 16 years ago (diff)

corrected views

Line 
1// occquery.cpp : Defines the entry point for the console application.
2//
3#include "glInterface.h"
4#include <math.h>
5#include <time.h>
6#include "common.h"
7#include "RenderTraverser.h"
8#include "SceneEntity.h"
9#include "Vector3.h"
10#include "Matrix4x4.h"
11#include "ResourceManager.h"
12#include "Bvh.h"
13#include "Camera.h"
14#include "Geometry.h"
15#include "BvhLoader.h"
16#include "FrustumCullingTraverser.h"
17#include "StopAndWaitTraverser.h"
18#include "CHCTraverser.h"
19#include "CHCPlusPlusTraverser.h"
20#include "Visualization.h"
21#include "RenderState.h"
22#include "Timer/PerfTimer.h"
23#include "SceneQuery.h"
24#include "RenderQueue.h"
25#include "Material.h"
26#include <Cg/cg.h>
27#include <Cg/cgGL.h>
28#include "glfont2.h"
29#include "PerformanceGraph.h"
30#include "Environment.h"
31#include "Halton.h"
32#include "Transform3.h"
33#include "SampleGenerator.h"
34#include "FrameBufferObject.h"
35#include "SsaoShader.h"
36#include "DeferredShader.h"
37#include "ShadowMapping.h"
38#include "Light.h"
39
40
41using namespace std;
42using namespace CHCDemoEngine;
43
44
45static Environment env;
46
47
48// fbo
49FrameBufferObject *fbo = NULL;
50
51GLuint fontTex;
52
53/// the renderable scene geometry
54SceneEntityContainer sceneEntities;
55// traverses and renders the hierarchy
56RenderTraverser *traverser = NULL;
57/// the hierarchy
58Bvh *bvh = NULL;
59/// handles scene loading
60ResourceManager *loader = NULL;
61/// the scene camera
62Camera *camera = NULL;
63/// the scene camera
64Camera *visCamera = NULL;
65/// the visualization
66Visualization *visualization = NULL;
67/// the current render state
68RenderState state;
69/// the rendering algorithm
70int renderMode = RenderTraverser::CHCPLUSPLUS;
71// eye near plane distance
72float nearDist = 0.2f;
73/// the field of view
74float fov = 50.0f;
75/// the pixel threshold where a node is still considered invisible
76int threshold;
77
78int assumedVisibleFrames = 10;
79int maxBatchSize = 50;
80
81int trianglesPerVirtualLeaf = INITIAL_TRIANGLES_PER_VIRTUAL_LEAVES;
82
83SceneQuery *sceneQuery = NULL;
84RenderQueue *renderQueue = NULL;
85
86/// these values get scaled with the frame rate
87static float keyForwardMotion = 30.0f;
88static float keyRotation = 1.5f;
89
90/// elapsed time in milliseconds
91double elapsedTime = 1000.0f;
92double algTime = 1000.0f;
93
94static int winWidth = 1024;
95static int winHeight = 768;
96static float winAspectRatio = 1.0f;
97
98double accumulatedTime = 1000;
99float fps = 1e3f;
100
101float myfar = 0;
102
103glfont::GLFont myfont;
104
105// rendertexture
106static int texWidth = 1024;
107static int texHeight = 768;
108
109//static int texWidth = 512;
110//static int texHeight = 384;
111
112//static int texWidth = 2048;
113//static int texHeight = 2048;
114
115int renderedObjects = 0;
116int renderedNodes = 0;
117int renderedTriangles = 0;
118
119int issuedQueries = 0;
120int traversedNodes = 0;
121int frustumCulledNodes = 0;
122int queryCulledNodes = 0;
123int stateChanges = 0;
124int numBatches = 0;
125
126bool showHelp = false;
127bool showStatistics = false;
128bool showOptions = true;
129bool showBoundingVolumes = false;
130bool visMode = false;
131
132// mouse navigation state
133int xEyeBegin = 0;
134int yEyeBegin = 0;
135int yMotionBegin = 0;
136int verticalMotionBegin = 0;
137int horizontalMotionBegin = 0;
138
139bool useOptimization = false;
140bool useTightBounds = true;
141bool useRenderQueue = true;
142bool useMultiQueries = true;
143bool flyMode = true;
144
145SceneEntityContainer skyGeometry;
146
147bool leftKeyPressed = false;
148bool rightKeyPressed = false;
149bool upKeyPressed = false;
150bool downKeyPressed = false;
151bool descendKeyPressed = false;
152bool ascendKeyPressed = false;
153
154bool useGlobIllum = false;
155bool useSsao = false;
156bool useTemporalCoherence = true;
157
158static float ssaoExpFactor = 0.1f;
159
160bool showAlgorithmTime = false;
161
162GLubyte *randomNormals = NULL;
163
164PerfTimer frameTimer, algTimer;
165
166int renderType = RenderState::FIXED;
167
168PerformanceGraph *perfGraph = NULL;
169
170bool useFullScreen = false;
171
172bool useLODs = true;
173
174int samplingMethod = SsaoShader::POISSON;
175
176static Matrix4x4 matProjectionView = IdentityMatrix();
177
178ShadowMapping *shadowMapping = NULL;
179Light *light = NULL;
180
181// function forward declarations
182void InitExtensions();
183void DisplayVisualization();
184void InitGLstate();
185void InitRenderTexture();
186void InitCg();
187void CleanUp();
188void SetupEyeView();
189void UpdateEyeMtx();
190void SetupLighting();
191void DisplayStats();
192void Output(int x, int y, const char *string);
193void DrawHelpMessage();
194void RenderSky();
195void RenderVisibleObjects();
196
197void Begin2D();
198void End2D();
199void KeyBoard(unsigned char c, int x, int y);
200void DrawStatistics();
201void Display();
202void Special(int c, int x, int y);
203void KeyUp(unsigned char c, int x, int y);
204void SpecialKeyUp(int c, int x, int y);
205void Reshape(int w, int h);
206void Mouse(int button, int state, int x, int y);
207void LeftMotion(int x, int y);
208void RightMotion(int x, int y);
209void MiddleMotion(int x, int y);
210void CalcDecimalPoint(string &str, int d);
211void ResetTraverser();
212
213void KeyHorizontalMotion(float shift);
214void KeyVerticalMotion(float shift);
215
216void PlaceViewer(const Vector3 &oldPos);
217
218
219
220inline float KeyRotationAngle() { return keyRotation * elapsedTime * 1e-3f; }
221inline float KeyShift() { return keyForwardMotion * elapsedTime * 1e-3f; }
222
223void InitFBO();
224
225SsaoShader *ssaoShader = NULL;
226DeferredShader *deferredShader = NULL;
227
228static GLenum mrt[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT};
229
230
231/////////
232//-- cg stuff
233
234static CGcontext sCgContext = NULL;
235static CGprogram sCgMrtVertexProgram = NULL;
236
237static CGparameter sModelViewProjMatrixParam;
238static CGparameter sMaxDepthParam;
239static CGparameter sMaxDepthParamTex;
240
241static Matrix4x4 oldViewProjMatrix;
242
243
244static void cgErrorCallback()
245{
246        CGerror lastError = cgGetError();
247
248        if(lastError)
249        {
250                printf("%s\n\n", cgGetErrorString(lastError));
251                printf("%s\n", cgGetLastListing(sCgContext));
252               
253                printf("Cg error, exiting...\n");
254
255                exit(0);
256        }
257}
258
259
260static void PrintGLerror(char *msg)
261{
262        GLenum errCode;
263        const GLubyte *errStr;
264       
265        if ((errCode = glGetError()) != GL_NO_ERROR)
266        {
267                errStr = gluErrorString(errCode);
268                fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg);
269        }
270}
271
272
273int main(int argc, char* argv[])
274{
275        int returnCode = 0;
276
277        Vector3 camPos(.0f, .0f, .0f);
278        Vector3 camDir(.0f, 1.0f, .0f);
279
280        cout << "=== reading environment file ===" << endl << endl;
281
282        string envFileName = "default.env";
283        if (!env.Read(envFileName))
284        {
285                cerr << "loading environment " << envFileName << " failed!" << endl;
286        }
287        else
288        {
289                env.GetIntParam(string("assumedVisibleFrames"), assumedVisibleFrames);
290                env.GetIntParam(string("maxBatchSize"), maxBatchSize);
291                env.GetIntParam(string("trianglesPerVirtualLeaf"), trianglesPerVirtualLeaf);
292
293                env.GetFloatParam(string("keyForwardMotion"), keyForwardMotion);
294                env.GetFloatParam(string("keyRotation"), keyRotation);
295
296                env.GetIntParam(string("winWidth"), winWidth);
297                env.GetIntParam(string("winHeight"), winHeight);
298
299                env.GetBoolParam(string("useFullScreen"), useFullScreen);
300                env.GetFloatParam(string("expFactor"), ssaoExpFactor);
301                env.GetVectorParam(string("camPosition"), camPos);
302                env.GetVectorParam(string("camDirection"), camDir);
303
304                env.GetBoolParam(string("useLODs"), useLODs);
305
306                //env.GetStringParam(string("modelPath"), model_path);
307                //env.GetIntParam(string("numSssaoSamples"), numSsaoSamples);
308
309
310                cout << "assumedVisibleFrames: " << assumedVisibleFrames << endl;
311                cout << "maxBatchSize: " << maxBatchSize << endl;
312                cout << "trianglesPerVirtualLeaf: " << trianglesPerVirtualLeaf << endl;
313
314                cout << "keyForwardMotion: " << keyForwardMotion << endl;
315                cout << "keyRotation: " << keyRotation << endl;
316                cout << "winWidth: " << winWidth << endl;
317                cout << "winHeight: " << winHeight << endl;
318                cout << "useFullScreen: " << useFullScreen << endl;
319                cout << "useLODs: " << useLODs << endl;
320                cout << "camPosition: " << camPos << endl;
321                cout << "expFactor: " << ssaoExpFactor << endl;
322
323                //cout << "model path: " << model_path << endl;
324
325                cout << "**** end parameters ****" << endl << endl;
326        }
327
328        ///////////////////////////
329
330        camera = new Camera(winWidth, winHeight, fov);
331        camera->SetNear(nearDist);
332        camera->SetFar(1000);
333
334        cout << "here2 " << Normalize(camDir) << endl;
335
336        camera->SetDirection(camDir);
337
338        cout << "here3 " << camera->GetDirection() << endl;
339        cout << "here3 " << camera->GetRightVector() << endl;
340        cout << "here3 " << camera->GetUpVector() << endl;
341
342        camera->SetPosition(camPos);
343
344        visCamera = new Camera(winWidth, winHeight, fov);
345
346        visCamera->SetNear(0.0f);
347        visCamera->Yaw(.5 * M_PI);
348
349        renderQueue = new RenderQueue(&state, camera);
350
351        glutInitWindowSize(winWidth, winHeight);
352        glutInit(&argc, argv);
353        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
354        //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
355        //glutInitDisplayString("samples=2");
356
357        SceneEntity::SetUseLODs(useLODs);
358
359
360        if (!useFullScreen)
361        {
362                glutCreateWindow("FriendlyCulling");
363        }
364        else
365        {
366                glutGameModeString( "1024x768:32@75" );
367                glutEnterGameMode();
368        }
369
370        glutDisplayFunc(Display);
371        glutKeyboardFunc(KeyBoard);
372        glutSpecialFunc(Special);
373        glutReshapeFunc(Reshape);
374        glutMouseFunc(Mouse);
375        glutIdleFunc(Display);
376        glutKeyboardUpFunc(KeyUp);
377        glutSpecialUpFunc(SpecialKeyUp);
378        glutIgnoreKeyRepeat(true);
379
380        // initialise gl graphics
381        InitExtensions();
382        InitGLstate();
383
384        glEnable(GL_MULTISAMPLE_ARB);
385        glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
386
387        LeftMotion(0, 0);
388        MiddleMotion(0, 0);
389
390        perfGraph = new PerformanceGraph(1000);
391
392        loader = new ResourceManager();
393
394        //const string filename("data/city/model/city.dem");
395        const string filename = string(model_path + "city.dem");
396
397        if (loader->Load(filename, sceneEntities))
398                cout << "scene " << filename << " loaded" << endl;
399        else
400        {
401                cerr << "loading scene " << filename << " failed" << endl;
402                CleanUp();
403                exit(0);
404        }
405
406        SceneEntityContainer dummy;
407
408        const string envname = string(model_path + "env.dem");
409
410        if (loader->Load(envname, skyGeometry))
411                cout << "sky box " << filename << " loaded" << endl;
412        else
413        {
414                cerr << "loading sky box " << filename << " failed" << endl;
415                CleanUp();
416                exit(0);
417        }
418
419        const string bvh_filename = string(model_path + "city.bvh");
420        BvhLoader bvhLoader;
421        bvh = bvhLoader.Load(bvh_filename, sceneEntities);
422
423        if (!bvh)
424        {
425                cerr << "loading bvh " << bvh_filename << " failed" << endl;
426                CleanUp();
427                exit(0);
428        }
429
430        // set far plane based on scene extent
431        myfar = 10.0f * Magnitude(bvh->GetBox().Diagonal());
432        bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
433
434        bvh->SetCamera(camera);
435       
436        InitCg();
437
438        DeferredShader::Init(sCgContext);
439        SsaoShader::Init(sCgContext);
440        ShadowMapping::Init(sCgContext);
441
442        //deferredShader = new DeferredShader(texWidth, texHeight);
443        //ssaoShader = new SsaoShader(texWidth, texHeight, camera, myfar / 10.0f);
444
445
446        // initialize the render traverser
447        ResetTraverser();
448
449        visualization = new Visualization(bvh, camera, NULL, &state);
450
451        sceneQuery = new SceneQuery(bvh->GetBox(), traverser);
452
453        light = new Light(Vector3(0, 0, -1), RgbaColor(1, 1, 1, 1));
454
455        shadowMapping = new ShadowMapping(bvh->GetBox(), 512);
456        shadowMapping->ComputeShadowMap(light, traverser);
457
458        // frame time is restarted every frame
459        frameTimer.Start();
460
461        // the rendering loop
462        glutMainLoop();
463
464        // clean up
465        CleanUp();
466
467        return 0;
468}
469
470
471void InitCg(void)
472{
473        // Setup Cg
474        cgSetErrorCallback(cgErrorCallback);
475
476        // Create cgContext.
477        sCgContext = cgCreateContext();
478
479        // get the best profile for this hardware
480        RenderState::sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
481        cgGLSetOptimalOptions(RenderState::sCgFragmentProfile);
482
483        RenderState::sCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
484        cgGLSetOptimalOptions(RenderState::sCgVertexProfile);
485
486        sCgMrtVertexProgram =
487                cgCreateProgramFromFile(sCgContext,
488                                                                CG_SOURCE,
489                                                                "src/shaders/mrt.cg",
490                                                                RenderState::sCgVertexProfile,
491                                                                "vtx",
492                                                                NULL);
493
494        if (sCgMrtVertexProgram != NULL)
495        {
496                cgGLLoadProgram(sCgMrtVertexProgram);
497
498                Transform3::sModelMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelMatrix");
499                sModelViewProjMatrixParam = cgGetNamedParameter(sCgMrtVertexProgram, "ModelViewProj");
500        }
501
502        RenderState::sCgMrtFragmentTexProgram =
503                cgCreateProgramFromFile(sCgContext,
504                                                                CG_SOURCE,
505                                                                "src/shaders/mrt.cg",
506                                                                RenderState::sCgFragmentProfile,
507                                                                "fragtex",
508                                                                NULL);
509
510        if (RenderState::sCgMrtFragmentTexProgram != NULL)
511        {
512                cgGLLoadProgram(RenderState::sCgMrtFragmentTexProgram);
513
514                sMaxDepthParamTex = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "maxDepth");
515                Material::sDiffuseTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "diffuse");
516                Material::sAmbientTexParam = cgGetNamedParameter(RenderState::sCgMrtFragmentTexProgram, "ambient");
517
518                cgGLSetParameter1f(sMaxDepthParamTex, 10.0f / myfar);
519                Debug << "maxdepth: " << 10.0f / myfar << endl;
520        }
521        else
522                cerr << "fragment tex program failed to load" << endl;
523
524        RenderState::sCgMrtFragmentProgram =
525                cgCreateProgramFromFile(sCgContext,
526                                                                CG_SOURCE,
527                                                                "src/shaders/mrt.cg",
528                                                                RenderState::sCgFragmentProfile,
529                                                                "frag",
530                                                                NULL);
531
532        if (RenderState::sCgMrtFragmentProgram != NULL)
533        {
534                cgGLLoadProgram(RenderState::sCgMrtFragmentProgram);
535
536                sMaxDepthParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "maxDepth");
537                Material::sDiffuseParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "diffuse");
538                Material::sAmbientParam = cgGetNamedParameter(RenderState::sCgMrtFragmentProgram, "ambient");
539
540                cgGLSetParameter1f(sMaxDepthParam, 10.0f / myfar);
541        }
542        else
543                cerr << "fragment program failed to load" << endl;
544
545        PrintGLerror("init");
546
547        cout << "cg initialization successful" << endl;
548}
549
550
551void InitFBO()
552{
553        // this fbo basicly stores the scene information we get from standard rendering of a frame
554        // we store colors, normals, positions (for the ssao)
555        fbo = new FrameBufferObject(texWidth, texHeight, FrameBufferObject::DEPTH_32);
556
557        // the diffuse color buffer
558        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
559        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
560
561        // the positions buffer
562        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_MIPMAP_LINEAR, true);
563        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
564       
565        // the normals buffer
566        //fbo->AddColorBuffer(ColorBufferObject::BUFFER_UBYTE, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
567        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_16, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
568
569        // another color buffer
570        fbo->AddColorBuffer(ColorBufferObject::BUFFER_FLOAT_32, ColorBufferObject::WRAP_CLAMP_TO_EDGE, ColorBufferObject::FILTER_NEAREST, false);
571
572        PrintGLerror("fbo");
573}
574
575
576bool InitFont(void)
577{
578        glEnable(GL_TEXTURE_2D);
579
580        glGenTextures(1, &fontTex);
581        glBindTexture(GL_TEXTURE_2D, fontTex);
582        if (!myfont.Create("data/fonts/verdana.glf", fontTex))
583                return false;
584
585        glDisable(GL_TEXTURE_2D);
586       
587        return true;
588}
589
590
591void InitGLstate()
592{
593        glClearColor(0.0f, 0.0, 0.2f, 0.0f);
594       
595        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
596        glPixelStorei(GL_PACK_ALIGNMENT,1);
597       
598        glDepthFunc(GL_LESS);
599        glEnable(GL_DEPTH_TEST);
600
601        SetupLighting();
602
603        glColor3f(1.0f, 1.0f, 1.0f);
604        glShadeModel(GL_SMOOTH);
605       
606        glMaterialf(GL_FRONT, GL_SHININESS, 64);
607        glEnable(GL_NORMALIZE);
608               
609        //glEnable(GL_ALPHA_TEST);
610        glDisable(GL_ALPHA_TEST);
611        glAlphaFunc(GL_GEQUAL, 0.8f);
612
613        glFrontFace(GL_CCW);
614        glCullFace(GL_BACK);
615        glEnable(GL_CULL_FACE);
616
617        //glDisable(GL_CULL_FACE);
618        glDisable(GL_TEXTURE_2D);
619
620        GLfloat ambientColor[] = {0.5, 0.5, 0.5, 1.0};
621        GLfloat diffuseColor[] = {1.0, 0.0, 0.0, 1.0};
622        GLfloat specularColor[] = {0.0, 0.0, 0.0, 1.0};
623
624        glMaterialfv(GL_FRONT, GL_AMBIENT, ambientColor);
625        glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseColor);
626        glMaterialfv(GL_FRONT, GL_SPECULAR, specularColor);
627
628        glDepthFunc(GL_LESS);
629
630        if (!InitFont())
631                cerr << "font creation failed" << endl;
632        else
633                cout << "successfully created font" << endl;
634}
635
636
637void DrawHelpMessage()
638{
639        const char *message[] =
640        {
641                "Help information",
642                "",
643                "'F1'           - shows/dismisses this message",
644                "'F2'           - shows/hides bird eye view",
645                "'F3'           - shows/hides bounds (boxes or tight bounds)",
646                "'F4',          - shows/hides parameters",
647                "'F5'           - shows/hides statistics",
648                "'F6',          - toggles between fly/walkmode",
649                "'F7',          - cycles throw render modes",
650                "'F8',          - enables/disables ambient occlusion (only deferred)",
651                "'F9',          - shows pure algorithm render time (using glFinish)",
652                "'SPACE'        - cycles through occlusion culling algorithms",
653                "",
654                "'MOUSE LEFT'        - turn left/right, move forward/backward",
655                "'MOUSE RIGHT'       - turn left/right, move forward/backward",
656                "'MOUSE MIDDLE'      - move up/down, left/right",
657                "'CURSOR UP/DOWN'    - move forward/backward",
658                "'CURSOR LEFT/RIGHT' - turn left/right",
659                "",
660                "'-'/'+'        - decreases/increases max batch size",
661                "'1'/'2'        - downward/upward motion",
662                "'3'/'4'        - decreases/increases triangles per virtual bvh leaf (sets bvh depth)",
663                "'5'/'6'        - decreases/increases assumed visible frames",
664                "",
665                "'R'            - use render queue",
666                "'B'            - use tight bounds",
667                "'M'            - use multiqueries",
668                "'O'            - use CHC optimization (geometry queries for leaves)",
669                0,
670        };
671       
672       
673        glColor4f(0.0f, 1.0f , 0.0f, 0.2f); // 20% green.
674
675        glRecti(30, 30, winWidth - 30, winHeight - 30);
676
677        glEnd();
678
679        glColor3f(1.0f, 1.0f, 1.0f);
680       
681        glEnable(GL_TEXTURE_2D);
682        myfont.Begin();
683
684        int x = 40, y = 30;
685
686        for(int i = 0; message[i] != 0; ++ i)
687        {
688                if(message[i][0] == '\0')
689                {
690                        y += 15;
691                }
692                else
693                {
694                        myfont.DrawString(message[i], x, winHeight - y);
695                        y += 25;
696                }
697        }
698        glDisable(GL_TEXTURE_2D);
699}
700
701
702void ResetTraverser()
703{
704        DEL_PTR(traverser);
705
706        bvh->ResetNodeClassifications();
707
708        switch (renderMode)
709        {
710        case RenderTraverser::CULL_FRUSTUM:
711                traverser = new FrustumCullingTraverser();
712                break;
713        case RenderTraverser::STOP_AND_WAIT:
714                traverser = new StopAndWaitTraverser();
715                break;
716        case RenderTraverser::CHC:
717                traverser = new CHCTraverser();
718                break;
719        case RenderTraverser::CHCPLUSPLUS:
720                traverser = new CHCPlusPlusTraverser();
721                break;
722       
723        default:
724                traverser = new FrustumCullingTraverser();
725        }
726
727        traverser->SetCamera(camera);
728        traverser->SetHierarchy(bvh);
729        traverser->SetRenderQueue(renderQueue);
730        traverser->SetRenderState(&state);
731        traverser->SetUseOptimization(useOptimization);
732        traverser->SetUseRenderQueue(useRenderQueue);
733        traverser->SetVisibilityThreshold(threshold);
734        traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
735        traverser->SetMaxBatchSize(maxBatchSize);
736        traverser->SetUseMultiQueries(useMultiQueries);
737        traverser->SetUseTightBounds(useTightBounds);
738        traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
739        traverser->SetRenderQueue(renderQueue);
740}
741
742
743void SetupLighting()
744{
745        glEnable(GL_LIGHTING);
746        glEnable(GL_LIGHT0);
747        glEnable(GL_LIGHT1);
748       
749        GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0};
750        GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
751        GLfloat specular[] = {1.0, 1.0, 1.0, 1.0};
752           
753        GLfloat lmodel_ambient[] = {0.3f, 0.3f, 0.3f, 1.0f};
754
755        glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
756        glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
757        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
758
759
760        ////////////
761        //-- second light
762
763        GLfloat ambient1[] = {0.2, 0.2, 0.2, 1.0};
764        GLfloat diffuse1[] = {1.0, 1.0, 1.0, 1.0};
765        //GLfloat diffuse1[] = {0.5, 0.5, 0.5, 1.0};
766        GLfloat specular1[] = {0.0, 0.0, 0.0, 1.0};
767
768        glLightfv(GL_LIGHT1, GL_AMBIENT, ambient1);
769        glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse1);
770        glLightfv(GL_LIGHT1, GL_SPECULAR, specular1);
771
772       
773        //////////////////////////////
774
775        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
776        glLightfv(GL_LIGHT0, GL_POSITION, position);
777
778        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
779        glLightfv(GL_LIGHT1, GL_POSITION, position1);
780
781        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
782        glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
783        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SINGLE_COLOR_EXT);
784}
785
786
787void SetupEyeView()
788{
789        // store matrix of last frame
790        oldViewProjMatrix = matProjectionView;
791
792        glMatrixMode(GL_PROJECTION);
793        glLoadIdentity();
794
795        gluPerspective(fov, winAspectRatio, nearDist, myfar);
796
797        glMatrixMode(GL_MODELVIEW);
798        glLoadIdentity();
799
800        // set up the camera view
801        camera->SetupCameraView();
802
803        // set lights
804        GLfloat position[] = {0.8f, -1.0f, 0.7f, 0.0f};
805        glLightfv(GL_LIGHT0, GL_POSITION, position);
806
807        GLfloat position1[] = {-0.5f, 0.5f, 0.4f, 0.0f};
808        glLightfv(GL_LIGHT1, GL_POSITION, position1);
809
810       
811        /////////////////
812
813        Matrix4x4 matViewing, matProjection;
814
815        camera->GetModelViewMatrix(matViewing);
816        camera->GetProjectionMatrix(matProjection);
817
818        // store matrix for later use
819        matProjectionView = matViewing * matProjection;
820       
821        if (renderType == RenderState::DEFERRED)
822        {
823                // set modelview matrix for shaders
824                cgGLSetStateMatrixParameter(sModelViewProjMatrixParam,
825                                                                        CG_GL_MODELVIEW_PROJECTION_MATRIX,
826                                                                        CG_GL_MATRIX_IDENTITY);
827
828                static Matrix4x4 identity = IdentityMatrix();
829                cgGLSetMatrixParameterfc(Transform3::sModelMatrixParam, (const float *)identity.x);
830        }               
831}
832
833
834void KeyHorizontalMotion(float shift)
835{
836        Vector3 hvec = -camera->GetDirection();
837        hvec.z = 0;
838
839        Vector3 pos = camera->GetPosition();
840        pos += hvec * shift;
841       
842        camera->SetPosition(pos);
843}
844
845
846void KeyVerticalMotion(float shift)
847{
848        Vector3 uvec = Vector3(0, 0, shift);
849
850        Vector3 pos = camera->GetPosition();
851        pos += uvec;
852       
853        camera->SetPosition(pos);
854}
855
856
857// the main rendering loop
858void Display()
859{       
860        Vector3 oldPos = camera->GetPosition();
861
862        if (leftKeyPressed)
863                camera->Pitch(KeyRotationAngle());
864        if (rightKeyPressed)
865                camera->Pitch(-KeyRotationAngle());
866        if (upKeyPressed)
867                KeyHorizontalMotion(-KeyShift());
868        if (downKeyPressed)
869                KeyHorizontalMotion(KeyShift());
870        if (ascendKeyPressed)
871                KeyVerticalMotion(KeyShift());
872        if (descendKeyPressed)
873                KeyVerticalMotion(-KeyShift());
874
875        // place view on ground
876        if (!flyMode) PlaceViewer(oldPos);
877
878        if (showAlgorithmTime)
879        {
880                glFinish();
881                algTimer.Start();
882        }
883       
884       
885        //shadowMapping->ComputeShadowMap(light, traverser);
886
887
888
889        // render without shading
890        switch (renderType)
891        {
892        case RenderState::FIXED:
893       
894                glEnable(GL_MULTISAMPLE_ARB);
895               
896                state.SetRenderType(RenderState::FIXED);
897                glEnable(GL_LIGHTING);
898
899                cgGLDisableProfile(RenderState::sCgFragmentProfile);
900                cgGLDisableProfile(RenderState::sCgVertexProfile);
901
902                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
903
904                break;
905
906        case RenderState::DEPTH_PASS:
907
908                glEnable(GL_MULTISAMPLE_ARB);
909               
910                cgGLDisableProfile(RenderState::sCgFragmentProfile);
911                cgGLDisableProfile(RenderState::sCgVertexProfile);
912
913                state.SetRenderType(RenderState::DEPTH_PASS);
914
915                // the scene is rendered withouth any shading   
916                glDisable(GL_LIGHTING);
917       
918                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
919
920                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
921
922                break;
923       
924        case RenderState::DEFERRED:
925
926                if (!fbo) InitFBO();
927
928                // multisampling does not work with deferred shading
929                glDisable(GL_MULTISAMPLE_ARB);
930
931                state.SetRenderType(RenderState::DEFERRED);
932
933                fbo->Bind();
934       
935                glPushAttrib(GL_VIEWPORT_BIT);
936                glViewport(0, 0, texWidth, texHeight);
937
938                cgGLEnableProfile(RenderState::sCgFragmentProfile);
939                cgGLBindProgram(RenderState::sCgMrtFragmentProgram);
940
941                cgGLEnableProfile(RenderState::sCgVertexProfile);
942                cgGLBindProgram(sCgMrtVertexProgram);
943
944                /// draw to 3 color buffers
945                glDrawBuffers(3, mrt);
946
947                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
948
949                break;
950        }
951
952
953        glDepthFunc(GL_LESS);
954
955        glDisable(GL_TEXTURE_2D);
956        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
957               
958
959        // reset lod levels for current frame
960        LODLevel::InitFrame(camera->GetPosition());
961
962
963        // bring eye modelview matrix up-to-date
964        SetupEyeView();
965
966        // actually render the scene geometry using one of the specified algorithms
967        traverser->RenderScene();
968
969
970
971        /////////
972        //-- do the rest of the rendering
973
974        glEnableClientState(GL_VERTEX_ARRAY);
975        glEnableClientState(GL_NORMAL_ARRAY);
976
977
978        // reset depth pass and render visible objects
979        if (renderType == RenderState::DEPTH_PASS)
980        {
981                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
982                RenderVisibleObjects();
983        }
984       
985
986        ///////////////
987        //-- render sky
988
989        RenderSky();
990
991        state.Reset();
992
993        glDisableClientState(GL_VERTEX_ARRAY);
994        glDisableClientState(GL_NORMAL_ARRAY);
995
996
997        if (renderType == RenderState::DEFERRED)
998        {
999                FrameBufferObject::Release();
1000
1001                cgGLDisableProfile(RenderState::sCgVertexProfile);
1002                cgGLDisableProfile(RenderState::sCgFragmentProfile);
1003
1004                if (useSsao)
1005                {
1006                        if (!ssaoShader) ssaoShader = new SsaoShader(texWidth, texHeight, camera, myfar / 10.0f);
1007                        //DEL_PTR(deferredShader);
1008                        ssaoShader->Render(fbo, oldViewProjMatrix, ssaoExpFactor);
1009
1010                }
1011                else
1012                {
1013                        if (!deferredShader) deferredShader = new DeferredShader(texWidth, texHeight);
1014                        //DEL_PTR(ssaoShader);
1015                        deferredShader->Render(fbo);
1016                }
1017        }
1018        else
1019        {
1020                /*DEL_PTR(fbo);
1021                DEL_PTR(ssaoShader);
1022                DEL_PTR(deferredShader);
1023                */
1024        }
1025       
1026        ///////////
1027
1028        state.SetRenderType(RenderState::FIXED);
1029
1030        if (showAlgorithmTime)
1031        {
1032                glFinish();
1033
1034                algTime = algTimer.Elapsedms();
1035                perfGraph->AddData(algTime);
1036
1037                perfGraph->Draw();
1038        }
1039        else
1040        {
1041                if (visMode) DisplayVisualization();
1042        }
1043
1044        glFlush();
1045
1046        const bool restart = true;
1047        elapsedTime = frameTimer.Elapsedms(restart);
1048
1049        DisplayStats();
1050
1051        glutSwapBuffers();
1052}
1053
1054
1055#pragma warning( disable : 4100 )
1056void KeyBoard(unsigned char c, int x, int y)
1057{
1058        switch(c)
1059        {
1060        case 27:
1061                CleanUp();
1062                exit(0);
1063                break;
1064        case 32: //space
1065                renderMode = (renderMode + 1) % RenderTraverser::NUM_TRAVERSAL_TYPES;
1066                ResetTraverser();
1067                break;
1068        case 'h':
1069        case 'H':
1070                showHelp = !showHelp;
1071                break;
1072        case '+':
1073                if (maxBatchSize < 10)
1074                        maxBatchSize = 10;
1075                else
1076                        maxBatchSize += 10;
1077
1078                traverser->SetMaxBatchSize(maxBatchSize);
1079                break;
1080        case '-':
1081                maxBatchSize -= 10;
1082                if (maxBatchSize < 0) maxBatchSize = 1;
1083                traverser->SetMaxBatchSize(maxBatchSize);               
1084                break;
1085        case 'M':
1086        case 'm':
1087                useMultiQueries = !useMultiQueries;
1088                traverser->SetUseMultiQueries(useMultiQueries);
1089                break;
1090        case '1':
1091                descendKeyPressed = true;
1092                break;
1093        case '2':
1094                ascendKeyPressed = true;
1095                break;
1096        case '3':
1097                if (trianglesPerVirtualLeaf >= 100)
1098                        trianglesPerVirtualLeaf -= 100;
1099                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1100                break;
1101        case '4':
1102                trianglesPerVirtualLeaf += 100;
1103                bvh->SetVirtualLeaves(trianglesPerVirtualLeaf);
1104                break;
1105        case '5':
1106                assumedVisibleFrames -= 1;
1107                if (assumedVisibleFrames < 1) assumedVisibleFrames = 1;
1108                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);
1109                break;
1110        case '6':
1111                assumedVisibleFrames += 1;
1112                traverser->SetAssumedVisibleFrames(assumedVisibleFrames);               
1113                break;
1114        case '7':
1115                ssaoExpFactor *= 0.5f;
1116                break;
1117        case '8':
1118                ssaoExpFactor *= 2.0f;
1119                if (ssaoExpFactor > 1.0f) ssaoExpFactor = 1.0f;
1120                break;
1121        case '9':
1122                useLODs = !useLODs;
1123                SceneEntity::SetUseLODs(useLODs);
1124                break;
1125        case 'P':
1126        case 'p':
1127                if (samplingMethod == SsaoShader::GAUSS)
1128                        samplingMethod = SsaoShader::POISSON;
1129                else
1130                        samplingMethod = SsaoShader::GAUSS;
1131
1132                ssaoShader->SetSamplingMethod(samplingMethod);
1133
1134                break;
1135        case 'g':
1136        case 'G':
1137                useGlobIllum = !useGlobIllum;
1138                ssaoShader->SetUseGlobIllum(useGlobIllum);
1139                break;
1140        case 't':
1141        case 'T':
1142                useTemporalCoherence = !useTemporalCoherence;
1143                ssaoShader->SetUseTemporalCoherence(useTemporalCoherence);
1144                break;
1145        case 'o':
1146        case 'O':
1147                useOptimization = !useOptimization;
1148                traverser->SetUseOptimization(useOptimization);
1149                break;
1150        case 'a':
1151        case 'A':
1152                        leftKeyPressed = true;
1153                break;
1154        case 'd':
1155        case 'D':
1156                        rightKeyPressed = true;
1157                break;
1158        case 'w':
1159        case 'W':
1160                        upKeyPressed = true;
1161                break;
1162        case 's':
1163        case 'S':
1164                        downKeyPressed = true;
1165                break;
1166        case 'r':
1167        case 'R':
1168                {
1169                        useRenderQueue = !useRenderQueue;
1170                        traverser->SetUseRenderQueue(useRenderQueue);
1171                }
1172                break;
1173        case 'b':
1174        case 'B':
1175                {
1176                        useTightBounds = !useTightBounds;
1177                        traverser->SetUseTightBounds(useTightBounds);
1178                }
1179                break;
1180        default:
1181                return;
1182        }
1183
1184        glutPostRedisplay();
1185}
1186
1187
1188void SpecialKeyUp(int c, int x, int y)
1189{
1190        switch (c)
1191        {
1192        case GLUT_KEY_LEFT:
1193                leftKeyPressed = false;
1194                break;
1195        case GLUT_KEY_RIGHT:
1196                rightKeyPressed = false;
1197                break;
1198        case GLUT_KEY_UP:
1199                upKeyPressed = false;
1200                break;
1201        case GLUT_KEY_DOWN:
1202                downKeyPressed = false;
1203                break;
1204        default:
1205                return;
1206        }
1207        //glutPostRedisplay();
1208}
1209
1210
1211void KeyUp(unsigned char c, int x, int y)
1212{
1213        switch (c)
1214        {
1215
1216        case 'A':
1217        case 'a':
1218                leftKeyPressed = false;
1219                break;
1220        case 'D':
1221        case 'd':
1222                rightKeyPressed = false;
1223                break;
1224        case 'W':
1225        case 'w':
1226                upKeyPressed = false;
1227                break;
1228        case 'S':
1229        case 's':
1230                downKeyPressed = false;
1231                break;
1232        case '1':
1233                descendKeyPressed = false;
1234                break;
1235        case '2':
1236                ascendKeyPressed = false;
1237                break;
1238       
1239        default:
1240                return;
1241        }
1242        //glutPostRedisplay();
1243}
1244
1245
1246void Special(int c, int x, int y)
1247{
1248        switch(c)
1249        {
1250        case GLUT_KEY_F1:
1251                showHelp = !showHelp;
1252                break;
1253        case GLUT_KEY_F2:
1254                visMode = !visMode;
1255                break;
1256        case GLUT_KEY_F3:
1257                showBoundingVolumes = !showBoundingVolumes;
1258                traverser->SetShowBounds(showBoundingVolumes);
1259                break;
1260        case GLUT_KEY_F4:
1261                showOptions = !showOptions;
1262                break;
1263        case GLUT_KEY_F5:
1264                showStatistics = !showStatistics;
1265                break;
1266        case GLUT_KEY_F6:
1267                flyMode = !flyMode;
1268                break;
1269        case GLUT_KEY_F7:
1270
1271                renderType = (renderType + 1) % 3;
1272                traverser->SetUseDepthPass(renderType == RenderState::DEPTH_PASS);
1273               
1274                break;
1275        case GLUT_KEY_F8:
1276                useSsao = !useSsao;
1277                break;
1278        case GLUT_KEY_F9:
1279                showAlgorithmTime = !showAlgorithmTime;
1280                break;
1281
1282        case GLUT_KEY_LEFT:
1283                {
1284                        leftKeyPressed = true;
1285                        camera->Pitch(KeyRotationAngle());
1286                }
1287                break;
1288        case GLUT_KEY_RIGHT:
1289                {
1290                        rightKeyPressed = true;
1291                        camera->Pitch(-KeyRotationAngle());
1292                }
1293                break;
1294        case GLUT_KEY_UP:
1295                {
1296                        upKeyPressed = true;
1297                        KeyHorizontalMotion(KeyShift());
1298                }
1299                break;
1300        case GLUT_KEY_DOWN:
1301                {
1302                        downKeyPressed = true;
1303                        KeyHorizontalMotion(-KeyShift());
1304                }
1305                break;
1306        default:
1307                return;
1308
1309        }
1310
1311        glutPostRedisplay();
1312}
1313
1314#pragma warning( default : 4100 )
1315
1316
1317void Reshape(int w, int h)
1318{
1319        winAspectRatio = 1.0f;
1320
1321        glViewport(0, 0, w, h);
1322       
1323        winWidth = w;
1324        winHeight = h;
1325
1326        if (w) winAspectRatio = (float) w / (float) h;
1327
1328        glMatrixMode(GL_PROJECTION);
1329        glLoadIdentity();
1330
1331        gluPerspective(fov, winAspectRatio, nearDist, myfar);
1332
1333        glMatrixMode(GL_MODELVIEW);
1334
1335        glutPostRedisplay();
1336}
1337
1338
1339void Mouse(int button, int state, int x, int y)
1340{
1341        if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
1342        {
1343                xEyeBegin = x;
1344                yMotionBegin = y;
1345
1346                glutMotionFunc(LeftMotion);
1347        }
1348        else if ((button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN))
1349        {
1350                xEyeBegin = x;
1351                yEyeBegin = y;
1352                yMotionBegin = y;
1353
1354                glutMotionFunc(RightMotion);
1355        }
1356        else if ((button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN))
1357        {
1358                horizontalMotionBegin = x;
1359                verticalMotionBegin = y;
1360                glutMotionFunc(MiddleMotion);
1361        }
1362
1363        glutPostRedisplay();
1364}
1365
1366
1367/**     rotation for left/right mouse drag
1368        motion for up/down mouse drag
1369*/
1370void LeftMotion(int x, int y)
1371{
1372        Vector3 viewDir = camera->GetDirection();
1373        Vector3 pos = camera->GetPosition();
1374
1375        // don't move in the vertical direction
1376        Vector3 horView(viewDir[0], viewDir[1], 0);
1377       
1378        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1379
1380        camera->Pitch(eyeXAngle);
1381
1382        pos += horView * (yMotionBegin - y) * 0.2f;
1383       
1384        camera->SetPosition(pos);
1385       
1386        xEyeBegin = x;
1387        yMotionBegin = y;
1388
1389        glutPostRedisplay();
1390}
1391
1392
1393/**     rotation for left / right mouse drag
1394        motion for up / down mouse drag
1395*/
1396void RightMotion(int x, int y)
1397{
1398        float eyeXAngle = 0.2f *  M_PI * (xEyeBegin - x) / 180.0;
1399        float eyeYAngle = -0.2f *  M_PI * (yEyeBegin - y) / 180.0;
1400
1401        camera->Yaw(eyeYAngle);
1402        camera->Pitch(eyeXAngle);
1403
1404        xEyeBegin = x;
1405        yEyeBegin = y;
1406
1407        glutPostRedisplay();
1408}
1409
1410
1411// strafe
1412void MiddleMotion(int x, int y)
1413{
1414        Vector3 viewDir = camera->GetDirection();
1415        Vector3 pos = camera->GetPosition();
1416
1417        // the 90 degree rotated view vector
1418        // y zero so we don't move in the vertical
1419        Vector3 rVec(viewDir[0], viewDir[1], 0);
1420       
1421        Matrix4x4 rot = RotationZMatrix(M_PI * 0.5f);
1422        rVec = rot * rVec;
1423       
1424        pos -= rVec * (x - horizontalMotionBegin) * 0.1f;
1425        pos[2] += (verticalMotionBegin - y) * 0.1f;
1426
1427        camera->SetPosition(pos);
1428
1429        horizontalMotionBegin = x;
1430        verticalMotionBegin = y;
1431
1432        glutPostRedisplay();
1433}
1434
1435
1436void InitExtensions(void)
1437{
1438        GLenum err = glewInit();
1439
1440        if (GLEW_OK != err)
1441        {
1442                // problem: glewInit failed, something is seriously wrong
1443                fprintf(stderr,"Error: %s\n", glewGetErrorString(err));
1444                exit(1);
1445        }
1446        if  (!GLEW_ARB_occlusion_query)
1447        {
1448                printf("I require the GL_ARB_occlusion_query to work.\n");
1449                exit(1);
1450        }
1451}
1452
1453
1454void Begin2D()
1455{
1456        glDisable(GL_LIGHTING);
1457        glDisable(GL_DEPTH_TEST);
1458
1459        glMatrixMode(GL_PROJECTION);
1460        glPushMatrix();
1461        glLoadIdentity();
1462
1463        gluOrtho2D(0, winWidth, 0, winHeight);
1464
1465        glMatrixMode(GL_MODELVIEW);
1466        glPushMatrix();
1467        glLoadIdentity();
1468}
1469
1470
1471void End2D()
1472{
1473        glMatrixMode(GL_PROJECTION);
1474        glPopMatrix();
1475
1476        glMatrixMode(GL_MODELVIEW);
1477        glPopMatrix();
1478
1479        glEnable(GL_LIGHTING);
1480        glEnable(GL_DEPTH_TEST);
1481}
1482
1483
1484// displays the visualisation of culling algorithm
1485void DisplayVisualization()
1486{
1487        visualization->SetFrameId(traverser->GetCurrentFrameId());
1488       
1489        Begin2D();
1490        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1491        glEnable(GL_BLEND);
1492        glColor4f(0.0f ,0.0f, 0.0f, 0.5f);
1493
1494        glRecti(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth, winHeight);
1495        glDisable(GL_BLEND);
1496        End2D();
1497       
1498       
1499        AxisAlignedBox3 box = bvh->GetBox();
1500
1501        // hack: set far plane for viz
1502        camera->SetFar(0.35f * Magnitude(box.Diagonal()));
1503
1504        const float offs = box.Size().x * 0.3f;
1505       
1506        //Vector3 vizpos = Vector3(box.Min().x, box.Min().y + box.Size().y * 0.5f, box.Min().z + box.Size().z * 50);
1507        Vector3 vizpos = Vector3(box.Min().x, box.Min().y  - box.Size().y * 0.35f, box.Min().z + box.Size().z * 50);
1508       
1509        visCamera->SetPosition(vizpos);
1510        visCamera->ResetPitchAndYaw();
1511        //visCamera->Pitch(M_PI);
1512
1513        glPushAttrib(GL_VIEWPORT_BIT);
1514        glViewport(winWidth - winWidth / 3, winHeight - winHeight / 3, winWidth / 3, winHeight / 3);
1515
1516        glMatrixMode(GL_PROJECTION);
1517        glPushMatrix();
1518
1519        glLoadIdentity();
1520       
1521        glOrtho(-offs, offs, -offs, offs, 0.0f, box.Size().z * 100.0f);
1522
1523        glMatrixMode(GL_MODELVIEW);
1524        glPushMatrix();
1525
1526        visCamera->SetupCameraView();
1527
1528        //Matrix4x4 rotX = RotationXMatrix(camera->GetYaw());
1529        //glMultMatrixf((float *)rotX.x);
1530        Matrix4x4 rotZ = RotationZMatrix(-camera->GetPitch());
1531        glMultMatrixf((float *)rotZ.x);
1532
1533        // inverse translation in order to fix current position
1534        Vector3 pos = camera->GetPosition();
1535        glTranslatef(-pos.x, -pos.y, -pos.z);
1536
1537
1538        GLfloat position[] = {0.8f, 1.0f, 1.5f, 0.0f};
1539        glLightfv(GL_LIGHT0, GL_POSITION, position);
1540
1541        GLfloat position1[] = {bvh->GetBox().Center().x, bvh->GetBox().Max().y, bvh->GetBox().Center().z, 1.0f};
1542        glLightfv(GL_LIGHT1, GL_POSITION, position1);
1543
1544        glClear(GL_DEPTH_BUFFER_BIT);
1545
1546
1547        ////////////
1548        //-- visualization of the occlusion culling
1549
1550        visualization->Render();
1551
1552        // coordinates
1553        glColor3f(0.0f, 1.0f, 0.0f);
1554        glBegin(GL_LINES);
1555        glVertex3d(pos.x, pos.y, pos.z);
1556        glVertex3d(pos.x + 100, pos.y, pos.z);
1557        glEnd();
1558
1559        glColor3f(0.0f, 0.0f, 1.0f);
1560        glBegin(GL_LINES);
1561        glVertex3d(pos.x, pos.y, pos.z);
1562        glVertex3d(pos.x, pos.y + 100, pos.z);
1563        glEnd();
1564       
1565        // reset previous settings
1566        glPopAttrib();
1567
1568        glMatrixMode(GL_PROJECTION);
1569        glPopMatrix();
1570        glMatrixMode(GL_MODELVIEW);
1571        glPopMatrix();
1572}
1573
1574
1575// cleanup routine after the main loop
1576void CleanUp()
1577{
1578        DEL_PTR(traverser);
1579        DEL_PTR(sceneQuery);
1580        DEL_PTR(bvh);
1581        DEL_PTR(visualization);
1582        DEL_PTR(camera);
1583        DEL_PTR(loader);
1584        DEL_PTR(renderQueue);
1585        DEL_PTR(perfGraph);
1586
1587        DEL_PTR(fbo);
1588        DEL_PTR(ssaoShader);
1589        DEL_PTR(deferredShader);
1590
1591        if (sCgMrtVertexProgram)
1592                cgDestroyProgram(sCgMrtVertexProgram);
1593        if (RenderState::sCgMrtFragmentProgram)
1594                cgDestroyProgram(RenderState::sCgMrtFragmentProgram);
1595        if (RenderState::sCgMrtFragmentTexProgram)
1596                cgDestroyProgram(RenderState::sCgMrtFragmentTexProgram);
1597       
1598        if (sCgContext)
1599                cgDestroyContext(sCgContext);
1600}
1601
1602
1603// this function inserts a dezimal point after each 1000
1604void CalcDecimalPoint(string &str, int d, int len)
1605{
1606        static vector<int> numbers;
1607        numbers.clear();
1608
1609        static string shortStr;
1610        shortStr.clear();
1611
1612        static char hstr[100];
1613
1614        while (d != 0)
1615        {
1616                numbers.push_back(d % 1000);
1617                d /= 1000;
1618        }
1619
1620        // first element without leading zeros
1621        if (numbers.size() > 0)
1622        {
1623                sprintf(hstr, "%d", numbers.back());
1624                shortStr.append(hstr);
1625        }
1626       
1627        for (int i = (int)numbers.size() - 2; i >= 0; i--)
1628        {
1629                sprintf(hstr, ",%03d", numbers[i]);
1630                shortStr.append(hstr);
1631        }
1632
1633        int dif = len - (int)shortStr.size();
1634
1635        for (int i = 0; i < dif; ++ i)
1636        {
1637                str += " ";
1638        }
1639
1640        str.append(shortStr);
1641}
1642
1643
1644void DisplayStats()
1645{
1646        static char msg[9][300];
1647
1648        static double frameTime = elapsedTime;
1649        static double renderTime = algTime;
1650
1651        const float expFactor = 0.1f;
1652
1653        // if some strange render time spike happened in this frame => don't count
1654        if (elapsedTime < 500) frameTime = elapsedTime * expFactor + (1.0f - expFactor) * elapsedTime;
1655       
1656        static float rTime = 1000.0f;
1657
1658        if (showAlgorithmTime)
1659        {
1660                if (algTime < 500) renderTime = algTime * expFactor + (1.0f - expFactor) * renderTime;
1661        }
1662
1663        accumulatedTime += elapsedTime;
1664
1665        if (accumulatedTime > 500) // update every fraction of a second
1666        {       
1667                accumulatedTime = 0;
1668
1669                if (frameTime) fps = 1e3f / (float)frameTime;
1670
1671                rTime = renderTime;
1672                renderedObjects = traverser->GetStats().mNumRenderedGeometry;
1673                renderedNodes = traverser->GetStats().mNumRenderedNodes;
1674                renderedTriangles = traverser->GetStats().mNumRenderedTriangles;
1675
1676                traversedNodes = traverser->GetStats().mNumTraversedNodes;
1677                frustumCulledNodes = traverser->GetStats().mNumFrustumCulledNodes;
1678                queryCulledNodes = traverser->GetStats().mNumQueryCulledNodes;
1679                issuedQueries = traverser->GetStats().mNumIssuedQueries;
1680                stateChanges = traverser->GetStats().mNumStateChanges;
1681                numBatches = traverser->GetStats().mNumBatches;
1682        }
1683
1684
1685        Begin2D();
1686
1687        glEnable(GL_BLEND);
1688        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1689
1690        if (showHelp)
1691        {       
1692                DrawHelpMessage();
1693        }
1694        else
1695        {
1696                if (showOptions)
1697                {
1698                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1699                        glRecti(5, winHeight - 95, winWidth * 2 / 3 - 5, winHeight - 5);
1700                }
1701
1702                if (showStatistics)
1703                {
1704                        glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
1705                        glRecti(5, winHeight - 165, winWidth * 2 / 3 - 5, winHeight - 100);
1706                }
1707
1708                glEnable(GL_TEXTURE_2D);
1709
1710                myfont.Begin();
1711
1712                if (showOptions)
1713                {
1714                        glColor3f(0.0f, 1.0f, 0.0f);
1715
1716                        int i = 0;
1717
1718                        static char *renderTypeStr[] = {"fixed function", "fixed function + depth pass", "deferred shading"};
1719       
1720                        sprintf(msg[i ++], "multiqueries: %d, tight bounds: %d, render queue: %d",
1721                                                        useMultiQueries, useTightBounds, useRenderQueue);
1722
1723                        sprintf(msg[i ++], "render technique: %s, SSAO: %d", renderTypeStr[renderType], useSsao);
1724
1725                        sprintf(msg[i ++], "triangles per virtual leaf: %5d", trianglesPerVirtualLeaf);
1726
1727                        sprintf(msg[i ++], "assumed visible frames: %4d, max batch size: %4d",
1728                                assumedVisibleFrames, maxBatchSize);
1729
1730                        for (int j = 0; j < 4; ++ j)
1731                                myfont.DrawString(msg[j], 10.0f, winHeight - 5 - j * 20);
1732                }
1733
1734                if (showStatistics)
1735                {
1736                        glColor3f(1.0f, 1.0f, 0.0f);
1737
1738                        string str;
1739                        string str2;
1740
1741                        int len = 10;
1742                        CalcDecimalPoint(str, renderedTriangles, len);
1743                        CalcDecimalPoint(str2, bvh->GetBvhStats().mTriangles, len);
1744
1745                        int i = 4;
1746
1747                        sprintf(msg[i ++], "rendered: %6d of %6d nodes, %s of %s triangles",
1748                                renderedNodes, bvh->GetNumVirtualNodes(), str.c_str(), str2.c_str());
1749
1750                        sprintf(msg[i ++], "traversed: %5d, frustum culled: %5d, query culled: %5d",
1751                                traversedNodes, frustumCulledNodes, queryCulledNodes);
1752
1753                        sprintf(msg[i ++], "issued queries: %5d, state changes: %5d, render batches: %5d",
1754                                issuedQueries, stateChanges, numBatches);
1755
1756                        for (int j = 4; j < 7; ++ j)
1757                                myfont.DrawString(msg[j], 10.0f, winHeight - (j + 1) * 20);
1758                }
1759
1760                glColor3f(1.0f, 1.0f, 1.0f);
1761                static char *alg_str[] = {"Frustum Cull", "Stop and Wait", "CHC", "CHC ++"};
1762               
1763                if (!showAlgorithmTime)
1764                {
1765                        sprintf(msg[7], "%s:  %6.1f fps", alg_str[renderMode], fps);
1766                }
1767                else
1768                {
1769                        sprintf(msg[7], "%s:  %6.1f ms", alg_str[renderMode], rTime);
1770                }
1771
1772                myfont.DrawString(msg[7], 1.3f, 690.0f, 760.0f);//, top_color, bottom_color);
1773               
1774                //sprintf(msg[8], "algorithm time: %6.1f ms", rTime);
1775                //myfont.DrawString(msg[8], 720.0f, 730.0f);           
1776        }
1777
1778        glDisable(GL_BLEND);
1779        glDisable(GL_TEXTURE_2D);
1780
1781        End2D();
1782}       
1783
1784
1785void RenderSky()
1786{
1787        SceneEntityContainer::const_iterator sit, sit_end = skyGeometry.end();
1788
1789        for (sit = skyGeometry.begin(); sit != sit_end; ++ sit)
1790                (*sit)->Render(&state);
1791}
1792
1793
1794void RenderVisibleObjects()
1795{
1796        state.SetRenderType(RenderState::FIXED);
1797        state.Reset();
1798
1799        glEnable(GL_LIGHTING);
1800        glDepthFunc(GL_LEQUAL);
1801
1802        //cout << "visible: " << (int)traverser->GetVisibleObjects().size() << endl;
1803
1804        SceneEntityContainer::const_iterator sit,
1805                sit_end = traverser->GetVisibleObjects().end();
1806
1807        for (sit = traverser->GetVisibleObjects().begin(); sit != sit_end; ++ sit)
1808                renderQueue->Enqueue(*sit);
1809               
1810        renderQueue->Apply();
1811
1812        glDepthFunc(GL_LESS);
1813}
1814
1815
1816void PlaceViewer(const Vector3 &oldPos)
1817{
1818        Vector3 playerPos = camera->GetPosition();
1819
1820        bool validIntersect = sceneQuery->CalcIntersection(playerPos);
1821
1822        if (validIntersect)
1823                // && ((playerPos.z - oldPos.z) < bvh->GetBox().Size(2) * 1e-1f))
1824        {
1825                camera->SetPosition(playerPos);
1826        }
1827}
Note: See TracBrowser for help on using the repository browser.