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

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