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

Revision 3203, 52.7 KB checked in by mattausch, 16 years ago (diff)

only adapting filter size left ...

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