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

Revision 3028, 48.3 KB checked in by mattausch, 16 years ago (diff)

debug version: what to do with shader programs??

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